mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-30 04:28:44 +00:00
Compare commits
62
Commits
dev/tutorial
...
v5.5.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b6cf4c12b | ||
|
|
2329a5c7b4 | ||
|
|
8f50d70703 | ||
|
|
d2d515658e | ||
|
|
72123494ca | ||
|
|
7b81fd1bff | ||
|
|
5ea7296e7a | ||
|
|
279b00f890 | ||
|
|
01d71d6f35 | ||
|
|
96df69b3fb | ||
|
|
b17fce357d | ||
|
|
37dfd95ae1 | ||
|
|
b834b9876d | ||
|
|
7f48e66fdc | ||
|
|
b7c57dc7f2 | ||
|
|
cb2405a8b9 | ||
|
|
4398777f07 | ||
|
|
6e8285e4ec | ||
|
|
aceaaf24d2 | ||
|
|
64bb63e304 | ||
|
|
a681ccf2b9 | ||
|
|
8c8a25a73b | ||
|
|
d419d23368 | ||
|
|
081500b5ce | ||
|
|
7dd36ecc0f | ||
|
|
10a16ac6f0 | ||
|
|
d7f61fa0f5 | ||
|
|
3665a533cf | ||
|
|
c9332a8c9e | ||
|
|
e40534942c | ||
|
|
de52856cf3 | ||
|
|
0dd345eb91 | ||
|
|
c4620aa587 | ||
|
|
bda63c70bf | ||
|
|
3407715599 | ||
|
|
7eaf579c18 | ||
|
|
488849535e | ||
|
|
15b892af6e | ||
|
|
cceb24a1e5 | ||
|
|
bea454a0b9 | ||
|
|
276fb2d698 | ||
|
|
8e3046b00f | ||
|
|
8a5790ed8b | ||
|
|
fd6f5ec525 | ||
|
|
987d549ff0 | ||
|
|
f57e724ef6 | ||
|
|
920417beb3 | ||
|
|
2a016ac4f5 | ||
|
|
ba3a3f7c38 | ||
|
|
ae6f5dd0f5 | ||
|
|
7914805524 | ||
|
|
5c2f113631 | ||
|
|
d3df3ed5ec | ||
|
|
40389ee102 | ||
|
|
edc8c2aeea | ||
|
|
f9ad87e54f | ||
|
|
a6a10270a0 | ||
|
|
9a1ff5e9a0 | ||
|
|
7151648279 | ||
|
|
921c629a5e | ||
|
|
25b2a0392d | ||
|
|
cb7aa3c14f |
No files matched your search
@@ -4,6 +4,12 @@ Here is a list of people who were happy to meet GRDB :-)
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/swiftkarim/status/1354753451377483781
|
||||
|
||||
> I cannot recommend GRDB enough. It works well with Swift and eliminates whole classes of potential programming errors that can be made with Core Data. Also being able to use raw SQL queries if needed can be extremely useful!
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/peres/status/1352219836508729346
|
||||
|
||||
> Just the occasional reminder that GRDB and its documentation is the gold standard. That's it.
|
||||
|
||||
@@ -7,6 +7,8 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 5.x Releases
|
||||
|
||||
- `5.5.x` Releases - [5.5.0](#550)
|
||||
- `5.4.x` Releases - [5.4.0](#540)
|
||||
- `5.3.x` Releases - [5.3.0](#530)
|
||||
- `5.2.x` Releases - [5.2.0](#520)
|
||||
- `5.1.x` Releases - [5.1.0](#510)
|
||||
@@ -69,6 +71,57 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
- [0.110.0](#01100), ...
|
||||
|
||||
|
||||
## 5.5.0
|
||||
|
||||
Released March 3, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.4.0...v5.5.0)
|
||||
|
||||
- **New**: You can now define common table expressions without any generic qualifier (which defaults to `Row`):
|
||||
|
||||
```swift
|
||||
let cte = CommonTableExpression(...)
|
||||
```
|
||||
|
||||
The [Common Table Expressions Guide](Documentation/CommonTableExpressions.md) was updated accordingly.
|
||||
|
||||
- **New**: `DatabaseQueue` reading methods are now wrapped in a deferred transaction. This guarantees snapshot isolation in case of concurrent writes performed by external connections, and makes `DatabaseQueue` a type suitable for shared databases.
|
||||
|
||||
- **Fixed**: `DatabaseQueue.read` is now declared `throws` instead of `rethrows`.
|
||||
|
||||
- **Fixed**: [#930](https://github.com/groue/GRDB.swift/pull/930): Fix SQL generation for `COLLATE`, `IN`, `NOT IN`
|
||||
|
||||
## 5.4.0
|
||||
|
||||
Released February 15, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.3.0...v5.4.0)
|
||||
|
||||
- **Breaking Change**: The query interface was refactored and some types such as `SQLExpression` are no longer a protocol.
|
||||
|
||||
This may break some applications that rely on Swift type inference, such as in the following example:
|
||||
|
||||
```swift
|
||||
// No longer compiles
|
||||
let values = [Column("score"), Column("score") + Column("bonus")]
|
||||
```
|
||||
|
||||
The fix is to add an explicit declaration of the desired type:
|
||||
|
||||
```swift
|
||||
// A possible fix
|
||||
let values: [SQLExpressible] = [Column("score"), Column("score") + Column("bonus")]
|
||||
```
|
||||
|
||||
Occurrences of such code breakage should be very rare.
|
||||
|
||||
- **New**: [SQL Interpolation](Documentation/SQLInterpolation.md) supports embedding collations into SQL literals:
|
||||
|
||||
```swift
|
||||
let request: SQLRequest<Player> = "SELECT * FROM player ORDER BY email COLLATION \(.nocase)"
|
||||
let request: SQLRequest<Player> = "SELECT * FROM player ORDER BY name COLLATION \(.localizedCompare)"
|
||||
```
|
||||
|
||||
- **Documentation update**: [Adding support for missing SQL functions or operators](README.md#adding-support-for-missing-sql-functions-or-operators) explains how to extend the query interface when needed.
|
||||
|
||||
- **Documentation update**: The [Demo Applications](Documentation/DemoApps/) now provide tests for the database access layer.
|
||||
|
||||
## 5.3.0
|
||||
|
||||
Released January 9, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.2.0...v5.3.0)
|
||||
|
||||
@@ -941,7 +941,21 @@ The pattern is always the same: you start from a base request, that you extend w
|
||||
|
||||
Another way to describe the difference is that `required` filters the fetched results in order to discard missing associated records, when `optional` does not filter anything, and lets missing values pass through.
|
||||
|
||||
Finally, readers who speak SQL may compare `optional` with left joins, and `required` with inner joins.
|
||||
Finally, readers who speak SQL may compare `optional` with left joins, and `required` with inner joins:
|
||||
|
||||
```swift
|
||||
// SELECT book.* FROM book LEFT JOIN author ON author.id = book.authorID
|
||||
Book.joining(optional: Book.author)
|
||||
|
||||
// SELECT book.* FROM book JOIN author ON author.id = book.authorID
|
||||
Book.joining(required: Book.author)
|
||||
|
||||
// SELECT book.*, author.* FROM book LEFT JOIN author ON author.id = book.authorID
|
||||
Book.including(optional: Book.author)
|
||||
|
||||
// SELECT book.*, author.* FROM book JOIN author ON author.id = book.authorID
|
||||
Book.including(required: Book.author)
|
||||
```
|
||||
|
||||
|
||||
## Combining Associations
|
||||
|
||||
@@ -29,7 +29,7 @@ The CTE request can be provided as a [query interface request]:
|
||||
|
||||
```swift
|
||||
// WITH playerName AS (SELECT name FROM player) ...
|
||||
let playerNameCTE = CommonTableExpression<Void>(
|
||||
let playerNameCTE = CommonTableExpression(
|
||||
named: "playerName",
|
||||
request: Player.select(Column("name")))
|
||||
```
|
||||
@@ -40,18 +40,18 @@ You can feed a CTE with raw SQL as well (second and third examples use [SQL Inte
|
||||
let name = "O'Brien"
|
||||
|
||||
// WITH playerName AS (SELECT 'O''Brien') ...
|
||||
let playerNameCTE = CommonTableExpression<Void>(
|
||||
let playerNameCTE = CommonTableExpression(
|
||||
named: "playerName",
|
||||
sql: "SELECT ?", arguments: [name])
|
||||
|
||||
// WITH playerName AS (SELECT 'O''Brien') ...
|
||||
let playerNameCTE = CommonTableExpression<Void>(
|
||||
let playerNameCTE = CommonTableExpression(
|
||||
named: "playerName",
|
||||
literal: "SELECT \(name)")
|
||||
|
||||
// WITH playerName AS (SELECT 'O''Brien') ...
|
||||
let request: SQLRequest<String> = "SELECT \(name)"
|
||||
let playerNameCTE = CommonTableExpression<Void>(
|
||||
let playerNameCTE = CommonTableExpression(
|
||||
named: "playerName",
|
||||
request: requests)
|
||||
```
|
||||
@@ -60,7 +60,7 @@ All CTEs can be provided with explicit column names:
|
||||
|
||||
```swift
|
||||
// WITH pair(a, b) AS (SELECT 1, 2) ...
|
||||
let pairCTE = CommonTableExpression<Void>(
|
||||
let pairCTE = CommonTableExpression(
|
||||
named: "pair",
|
||||
columns: ["a", "b"],
|
||||
sql: "SELECT 1, 2")
|
||||
@@ -71,7 +71,7 @@ Recursive CTEs need the `recursive` flag. The example below selects all integers
|
||||
```swift
|
||||
// WITH RECURSIVE counter(x) AS
|
||||
// (VALUES(1) UNION ALL SELECT x+1 FROM counter WHERE x<1000)
|
||||
let counterCTE = CommonTableExpression<Int>(
|
||||
let counterCTE = CommonTableExpression(
|
||||
recursive: true,
|
||||
named: "counter",
|
||||
columns: ["x"],
|
||||
@@ -84,8 +84,6 @@ let counterCTE = CommonTableExpression<Int>(
|
||||
|
||||
> :point_up: **Note**: many recursive CTEs use the `UNION ALL` SQL operator. The query interface does not provide any Swift support for it, so you'll generally have to write SQL in your definitions of recursive CTEs.
|
||||
|
||||
As you can see in all above examples, `CommonTableExpression` is a generic type: `CommonTableExpression<Void>`, `CommonTableExpression<Int>`. The generic argument (`Void`, `Int`) turns useful when you [join common table expressions](#associations-to-common-table-expressions), or when you [fetch values directly from a common table expression](#fetch-values-from-common-table-expressions). Otherwise, you can just use `Void`.
|
||||
|
||||
|
||||
## Embed Common Table Expressions in Requests
|
||||
|
||||
@@ -103,7 +101,7 @@ We first build a `CommonTableExpression`:
|
||||
|
||||
```swift
|
||||
let name = "O'Brien"
|
||||
let playerNameCTE = CommonTableExpression<Void>(
|
||||
let playerNameCTE = CommonTableExpression(
|
||||
named: "playerName",
|
||||
literal: "SELECT \(name)")
|
||||
```
|
||||
@@ -184,48 +182,37 @@ try Player
|
||||
|
||||
In the previous chapter, a common table expression was embedded as a subquery, with the `CommonTableExpression.all()` method.
|
||||
|
||||
`all()` builds a regular [query interface request] that you can filter, sort, etc, like all query interface requests. You can also fetch from it, but only as long as it is provided with the definition of the CTE.
|
||||
`cte.all()` builds a regular [query interface request] that you can filter, sort, etc, like all query interface requests.
|
||||
|
||||
This will generally give requests of the form `cte.all().with(cte)`. In SQL, this would give: `WITH cte AS (...) SELECT * FROM cte`.
|
||||
You can also fetch from `cte.all()`, as long as the request is given the definition of the CTE: `cte.all().with(cte)`. In SQL, this would give: `WITH cte AS (...) SELECT * FROM cte`:
|
||||
|
||||
The generic type of `CommonTableExpression<...>` now turns out useful, so that you can fetch the desired outcome (database [rows](../README.md#row-queries), simple [values](../README.md#value-queries), or custom [records](../README.md#records)).
|
||||
|
||||
For example, let's fetch a range of integer:
|
||||
This request, of type `QueryInterfaceRequest<Row>`, can fetch raw database [rows](../README.md#row-queries):
|
||||
|
||||
```swift
|
||||
func counterRequest(range: ClosedRange<Int>) -> QueryInterfaceRequest<Int> {
|
||||
// WITH RECURSIVE counter(x) AS
|
||||
// (VALUES(...) UNION ALL SELECT x+1 FROM counter WHERE x<...)
|
||||
// SELECT * FROM counter
|
||||
let counter = CommonTableExpression<Int>(
|
||||
recursive: true,
|
||||
named: "counter",
|
||||
columns: ["x"],
|
||||
literal: """
|
||||
VALUES(\(range.lowerBound)) \
|
||||
UNION ALL \
|
||||
SELECT x+1 FROM counter WHERE x < \(range.upperBound)
|
||||
""")
|
||||
return counter.all().with(counter)
|
||||
}
|
||||
|
||||
let values = try dbQueue.read { db in
|
||||
try counterRequest(range: 3...7).fetchAll(db)
|
||||
}
|
||||
print(values) // prints "[3, 4, 5, 6, 7]"
|
||||
let cte = CommonTableExpression(...)
|
||||
let request = cte.all().with(cte)
|
||||
let rows = try request.fetchAll(db) // [Row]
|
||||
```
|
||||
|
||||
When you have to fetch from a `CommonTableExpression` which does not have the desired generic type, you can still use the `asRequest(of:)` method:
|
||||
In order to fetch something else, such as simple [values](../README.md#value-queries), or custom [records](../README.md#records), you have two possible options:
|
||||
|
||||
```swift
|
||||
let cte: CommonTableExpression<Void> = ...
|
||||
let rows: [Row] = try dbQueue.read { db in
|
||||
try cte.all().with(cte)
|
||||
.asRequest(of: Row.self)
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
1. Use the `asRequest(of:)` method:
|
||||
|
||||
```swift
|
||||
let cte = CommonTableExpression(...)
|
||||
let request = cte.all().with(cte).asRequest(of: Player.self)
|
||||
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
let players = try request.fetchAll(db) // [Player]
|
||||
```
|
||||
|
||||
2. Provide the fetched type to the cte itself:
|
||||
|
||||
```swift
|
||||
let cte = CommonTableExpression<Player>(...)
|
||||
// ~~~~~~~~
|
||||
let request = cte.all().with(cte)
|
||||
let players = try request.fetchAll(db) // [Player]
|
||||
```
|
||||
|
||||
## Associations to Common Table Expressions
|
||||
|
||||
@@ -337,7 +324,7 @@ We can now define the CTE for the latest messages:
|
||||
```swift
|
||||
// WITH latestMessage AS
|
||||
// (SELECT *, MAX(date) FROM message GROUP BY chatID)
|
||||
let latestMessageCTE = CommonTableExpression<Void>(
|
||||
let latestMessageCTE = CommonTableExpression(
|
||||
named: "latestMessage",
|
||||
request: latestMessageRequest)
|
||||
```
|
||||
@@ -378,9 +365,9 @@ And we can fetch the data that feeds our application screen:
|
||||
let chatInfos: [ChatInfos] = try dbQueue.read(request.fetchAll)
|
||||
```
|
||||
|
||||
> :bulb: **Tip**: the joining methods are generally type-safe: they won't allow you to join apples to oranges. This works when associations have a *precise* type. In this context, our go-to `CommonTableExpression<Void>` CTEs can work against type safety. So when you want to define associations between several CTEs, and make sure the compiler will notice wrong uses of those associations, tag your `CommonTableExpression` with a type instead of `Void`.
|
||||
> :bulb: **Tip**: the joining methods are generally type-safe: they won't allow you to join apples to oranges. This works when associations have a *precise* type. In this context, anonymous `CommonTableExpression` CTEs can work against type safety. When you want to define associations between several CTEs, and make sure the compiler will notice wrong uses of those associations, tag your common table expressions with an explicit type: `CommonTableExpression<SomeType>`.
|
||||
>
|
||||
> You can use an existing record type, or an ad-hoc enum. For example:
|
||||
> To do so, you can use an existing record type, or an ad-hoc enum. For example:
|
||||
>
|
||||
> ```swift
|
||||
> enum CTE1 { }
|
||||
@@ -389,9 +376,9 @@ let chatInfos: [ChatInfos] = try dbQueue.read(request.fetchAll)
|
||||
> enum CTE2 { }
|
||||
> let cte2 = CommonTableExpression<CTE2>(...)
|
||||
>
|
||||
> let assoc1 = BaseRecord.association(to: cte1, on: ...)
|
||||
> let assoc2 = cte1.association(to: cte2, on: ...)
|
||||
> let assoc3 = cte2.association(to: FarRecord.self, on: ...)
|
||||
> let assoc1 = BaseRecord.association(to: cte1, on: ...) // from BaseRecord to CTE1
|
||||
> let assoc2 = cte1.association(to: cte2, on: ...) // from CTE1 to CTE2
|
||||
> let assoc3 = cte2.association(to: FarRecord.self, on: ...) // from CTE2 to FarRecord
|
||||
>
|
||||
> // WITH ...
|
||||
> // SELECT base.* FROM base
|
||||
@@ -400,12 +387,14 @@ let chatInfos: [ChatInfos] = try dbQueue.read(request.fetchAll)
|
||||
> // JOIN far ON ...
|
||||
> let request = BaseRecord
|
||||
> .with(cte1).with(cte2)
|
||||
> .joining(required: assoc1
|
||||
> .joining(required: assoc2
|
||||
> .joining(required: assoc3)))
|
||||
> .joining(required: assoc1. // OK
|
||||
> .joining(required: assoc2. // OK
|
||||
> .joining(required: assoc3))) // OK
|
||||
>
|
||||
> // Compiler error
|
||||
> let request = BaseRecord.joining(required: assoc2)
|
||||
> let request = BaseRecord
|
||||
> .joining(required: assoc2) // Not OK
|
||||
> .joining(required: assoc3) // Not OK
|
||||
> ```
|
||||
|
||||
[query interface request]: ../README.md#requests
|
||||
|
||||
@@ -38,9 +38,6 @@ struct AppDatabase {
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
// Sort player names in a localized case insensitive fashion by default
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#unicode
|
||||
.collate(.localizedCaseInsensitiveCompare)
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
}
|
||||
@@ -58,7 +55,7 @@ struct AppDatabase {
|
||||
|
||||
extension AppDatabase {
|
||||
/// Saves (inserts or updates) a player. When the method returns, the
|
||||
/// player id is not nil.
|
||||
/// player is present in the database, and its id is not nil.
|
||||
func savePlayer(_ player: inout Player) throws {
|
||||
try dbWriter.write { db in
|
||||
try player.save(db)
|
||||
@@ -83,7 +80,7 @@ extension AppDatabase {
|
||||
func refreshPlayers() throws {
|
||||
try dbWriter.write { db in
|
||||
if try Player.fetchCount(db) == 0 {
|
||||
// Insert new random players
|
||||
// When database is empty, insert new random players
|
||||
try createRandomPlayers(db)
|
||||
} else {
|
||||
// Insert a player
|
||||
|
||||
@@ -6,12 +6,21 @@ extension AppDatabase {
|
||||
|
||||
private static func makeShared() -> AppDatabase {
|
||||
do {
|
||||
// Create a folder for storing the SQLite database, as well as
|
||||
// the various temporary files created during normal database
|
||||
// operations (https://sqlite.org/tempfiles.html).
|
||||
let fileManager = FileManager()
|
||||
let folderURL = try fileManager
|
||||
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
.appendingPathComponent("database", isDirectory: true)
|
||||
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
|
||||
|
||||
// Connect to a database on disk
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
let url: URL = try FileManager.default
|
||||
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
.appendingPathComponent("db.sqlite")
|
||||
let dbPool = try DatabasePool(path: url.path)
|
||||
let dbURL = folderURL.appendingPathComponent("db.sqlite")
|
||||
let dbPool = try DatabasePool(path: dbURL.path)
|
||||
|
||||
// Create the AppDatabase
|
||||
let appDatabase = try AppDatabase(dbPool)
|
||||
|
||||
// Populate the database if it is empty, for better demo purpose.
|
||||
|
||||
@@ -71,25 +71,35 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
|
||||
extension DerivableRequest where RowDecoder == Player {
|
||||
/// A request of players ordered by name
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let players = try dbQueue.read { db in
|
||||
/// let players: [Player] = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByName().fetchAll(db)
|
||||
/// }
|
||||
func orderedByName() -> Self {
|
||||
order(Player.Columns.name)
|
||||
// Sort by name in a localized case insensitive fashion
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
|
||||
order(Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
|
||||
/// A request of players ordered by score
|
||||
/// A request of players ordered by score.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let players = try dbQueue.read { db in
|
||||
/// let players: [Player] = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByScore().fetchAll(db)
|
||||
/// }
|
||||
/// let bestPlayer: Player? = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByScore().fetchOne(db)
|
||||
/// }
|
||||
func orderedByScore() -> Self {
|
||||
order(Player.Columns.score.desc, Player.Columns.name)
|
||||
// Sort by descending score, and then by name, in a
|
||||
// localized case insensitive fashion
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
|
||||
order(
|
||||
Player.Columns.score.desc,
|
||||
Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
}
|
||||
+19
-6
@@ -78,8 +78,10 @@
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<RemoteRunnable
|
||||
runnableDebuggingMode = "2"
|
||||
BundleIdentifier = "com.apple.Carousel"
|
||||
RemotePath = "/GRDBDemoiOS">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
@@ -87,7 +89,7 @@
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</RemoteRunnable>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
@@ -95,8 +97,10 @@
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<RemoteRunnable
|
||||
runnableDebuggingMode = "2"
|
||||
BundleIdentifier = "com.apple.Carousel"
|
||||
RemotePath = "/GRDBDemoiOS">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
@@ -104,7 +108,16 @@
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</RemoteRunnable>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
BuildableName = "GRDBDemoWatchOS.app"
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
|
||||
@@ -37,9 +37,6 @@ final class AppDatabase {
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
// Sort player names in a localized case insensitive fashion by default
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#unicode
|
||||
.collate(.localizedCaseInsensitiveCompare)
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
}
|
||||
@@ -57,7 +54,7 @@ final class AppDatabase {
|
||||
|
||||
extension AppDatabase {
|
||||
/// Saves (inserts or updates) a player. When the method returns, the
|
||||
/// player id is not nil.
|
||||
/// player is present in the database, and its id is not nil.
|
||||
func savePlayer(_ player: inout Player) throws {
|
||||
try dbWriter.write { db in
|
||||
try player.save(db)
|
||||
@@ -82,7 +79,7 @@ extension AppDatabase {
|
||||
func refreshPlayers() throws {
|
||||
try dbWriter.write { db in
|
||||
if try Player.fetchCount(db) == 0 {
|
||||
// Insert new random players
|
||||
// When database is empty, insert new random players
|
||||
try createRandomPlayers(db)
|
||||
} else {
|
||||
// Insert a player
|
||||
@@ -127,20 +124,6 @@ extension AppDatabase {
|
||||
// MARK: - Database Access: Reads
|
||||
|
||||
extension AppDatabase {
|
||||
/// Tracks changes in the number of players
|
||||
func observePlayerCount(
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Int) -> Void)
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
ValueObservation
|
||||
.tracking(Player.fetchCount)
|
||||
.start(
|
||||
in: dbWriter,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
}
|
||||
|
||||
/// Tracks changes in players ordered by name
|
||||
func observePlayersOrderedByName(
|
||||
onError: @escaping (Error) -> Void,
|
||||
|
||||
@@ -1,17 +1,26 @@
|
||||
import GRDB
|
||||
|
||||
extension AppDatabase {
|
||||
/// The shared `PlayerDatabase`
|
||||
/// The database for the application
|
||||
static let shared = makeShared()
|
||||
|
||||
private static func makeShared() -> AppDatabase {
|
||||
do {
|
||||
// Create a folder for storing the SQLite database, as well as
|
||||
// the various temporary files created during normal database
|
||||
// operations (https://sqlite.org/tempfiles.html).
|
||||
let fileManager = FileManager()
|
||||
let folderURL = try fileManager
|
||||
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
.appendingPathComponent("database", isDirectory: true)
|
||||
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
|
||||
|
||||
// Connect to a database on disk
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
let url: URL = try FileManager.default
|
||||
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
.appendingPathComponent("db.sqlite")
|
||||
let dbPool = try DatabasePool(path: url.path)
|
||||
let dbURL = folderURL.appendingPathComponent("db.sqlite")
|
||||
let dbPool = try DatabasePool(path: dbURL.path)
|
||||
|
||||
// Create the AppDatabase
|
||||
let appDatabase = try AppDatabase(dbPool)
|
||||
|
||||
// Populate the database if it is empty, for better demo purpose.
|
||||
|
||||
@@ -70,25 +70,35 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
|
||||
extension DerivableRequest where RowDecoder == Player {
|
||||
/// A request of players ordered by name
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let players = try dbQueue.read { db in
|
||||
/// let players: [Player] = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByName().fetchAll(db)
|
||||
/// }
|
||||
func orderedByName() -> Self {
|
||||
order(Player.Columns.name)
|
||||
// Sort by name in a localized case insensitive fashion
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
|
||||
order(Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
|
||||
/// A request of players ordered by score
|
||||
/// A request of players ordered by score.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let players = try dbQueue.read { db in
|
||||
/// let players: [Player] = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByScore().fetchAll(db)
|
||||
/// }
|
||||
/// let bestPlayer: Player? = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByScore().fetchOne(db)
|
||||
/// }
|
||||
func orderedByScore() -> Self {
|
||||
order(Player.Columns.score.desc, Player.Columns.name)
|
||||
// Sort by descending score, and then by name, in a
|
||||
// localized case insensitive fashion
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
|
||||
order(
|
||||
Player.Columns.score.desc,
|
||||
Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
}
|
||||
+32
-34
@@ -12,11 +12,10 @@ class PlayerListViewController: UITableViewController {
|
||||
private var dataSource: PlayerDataSource!
|
||||
private var animatesPlayersChange = false // Don't animate first update
|
||||
private var playersCancellable: DatabaseCancellable?
|
||||
private var playerCountCancellable: DatabaseCancellable?
|
||||
private var playerOrdering: PlayerOrdering = .byScore {
|
||||
didSet {
|
||||
configureOrderingBarButtonItem()
|
||||
configureDataSourceContent()
|
||||
observePlayers()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +24,7 @@ class PlayerListViewController: UITableViewController {
|
||||
configureToolbar()
|
||||
configureNavigationItem()
|
||||
configureDataSource()
|
||||
configureDataSourceContent()
|
||||
observePlayers()
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
@@ -49,7 +48,6 @@ class PlayerListViewController: UITableViewController {
|
||||
target: nil, action: nil)
|
||||
navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem]
|
||||
configureOrderingBarButtonItem()
|
||||
configureTitle()
|
||||
}
|
||||
|
||||
private func configureOrderingBarButtonItem() {
|
||||
@@ -67,19 +65,6 @@ class PlayerListViewController: UITableViewController {
|
||||
}
|
||||
}
|
||||
|
||||
private func configureTitle() {
|
||||
playerCountCancellable = AppDatabase.shared.observePlayerCount(
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] count in
|
||||
guard let self = self else { return }
|
||||
switch count {
|
||||
case 0: self.navigationItem.title = "No Player"
|
||||
case 1: self.navigationItem.title = "1 Player"
|
||||
default: self.navigationItem.title = "\(count) Players"
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private func configureDataSource() {
|
||||
dataSource = PlayerDataSource(tableView: tableView) { (tableView, indexPath, player) in
|
||||
let cell = tableView.dequeueReusableCell(withIdentifier: "Player", for: indexPath)
|
||||
@@ -95,26 +80,18 @@ class PlayerListViewController: UITableViewController {
|
||||
tableView.dataSource = dataSource
|
||||
}
|
||||
|
||||
private func configureDataSourceContent() {
|
||||
switch playerOrdering {
|
||||
case .byName:
|
||||
playersCancellable = AppDatabase.shared.observePlayersOrderedByName(
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
self.updateDataSourceContent(with: players)
|
||||
})
|
||||
case .byScore:
|
||||
playersCancellable = AppDatabase.shared.observePlayersOrderedByScore(
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
self.updateDataSourceContent(with: players)
|
||||
})
|
||||
private func configureTitle(from players: [Player]) {
|
||||
switch players.count {
|
||||
case 0:
|
||||
navigationItem.title = "No Player"
|
||||
case 1:
|
||||
navigationItem.title = "1 Player"
|
||||
case let count:
|
||||
navigationItem.title = "\(count) Players"
|
||||
}
|
||||
}
|
||||
|
||||
private func updateDataSourceContent(with players: [Player]) {
|
||||
private func configureDataSource(from players: [Player]) {
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Int, Player>()
|
||||
snapshot.appendSections([0])
|
||||
snapshot.appendItems(players, toSection: 0)
|
||||
@@ -127,6 +104,27 @@ class PlayerListViewController: UITableViewController {
|
||||
dataSource.apply(snapshot, animatingDifferences: false, completion: nil)
|
||||
}
|
||||
}
|
||||
|
||||
private func observePlayers() {
|
||||
switch playerOrdering {
|
||||
case .byName:
|
||||
playersCancellable = AppDatabase.shared.observePlayersOrderedByName(
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
self.configureTitle(from: players)
|
||||
self.configureDataSource(from: players)
|
||||
})
|
||||
case .byScore:
|
||||
playersCancellable = AppDatabase.shared.observePlayersOrderedByScore(
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
self.configureTitle(from: players)
|
||||
self.configureDataSource(from: players)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -144,34 +144,6 @@ class AppDatabaseTests: XCTestCase {
|
||||
XCTAssertEqual(players, [player])
|
||||
}
|
||||
|
||||
func test_observePlayerCount() throws {
|
||||
// Given a players database that contains one player
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try dbQueue.write { db in
|
||||
try player.insert(db)
|
||||
}
|
||||
|
||||
// When we observe the player count and wait for the first value
|
||||
let exp = expectation(description: "Player count")
|
||||
var count: Int?
|
||||
let cancellable = appDatabase.observePlayerCount(
|
||||
onError: { error in
|
||||
XCTFail("Unexpected error \(error)")
|
||||
},
|
||||
onChange: {
|
||||
count = $0
|
||||
exp.fulfill()
|
||||
})
|
||||
withExtendedLifetime(cancellable) {
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
}
|
||||
|
||||
// Then that first value is one
|
||||
XCTAssertEqual(count, 1)
|
||||
}
|
||||
|
||||
func test_observePlayersOrderedByName() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = DatabaseQueue()
|
||||
|
||||
@@ -280,7 +280,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.3/Structs/StatementArguments.html):
|
||||
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -529,7 +529,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.3/Structs/StatementArguments.html):
|
||||
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
|
||||
@@ -68,7 +68,7 @@ try dbQueue.read { db in
|
||||
}
|
||||
```
|
||||
|
||||
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.3/Structs/DatabaseMigrator.html) for more migrator methods.
|
||||
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.5/Structs/DatabaseMigrator.html) for more migrator methods.
|
||||
|
||||
|
||||
## The `eraseDatabaseOnSchemaChange` Option
|
||||
|
||||
@@ -417,9 +417,16 @@ This chapter lists all kinds of supported interpolations.
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player ORDER BY name DESC
|
||||
"SELECT * FROM player WHERE id IN \(Column("name").desc)"
|
||||
"SELECT * FROM player ORDER BY \(Column("name").desc)"
|
||||
```
|
||||
|
||||
- Database Collations:
|
||||
|
||||
```swift
|
||||
"SELECT * FROM player ORDER BY email COLLATING \(.nocase)"
|
||||
"SELECT * FROM player ORDER BY email COLLATING \(.localizedCompare)"
|
||||
```
|
||||
|
||||
- Subqueries:
|
||||
|
||||
```swift
|
||||
|
||||
@@ -66,7 +66,7 @@ Since several processes may open the database at the same time, protect the crea
|
||||
}
|
||||
}
|
||||
}
|
||||
let dbPool = try DatabasePool(path: databaseURL.path)
|
||||
let dbPool = try DatabasePool(path: databaseURL.path, configuration: configuration)
|
||||
|
||||
// Perform here other database setups, such as defining
|
||||
// the database schema with a DatabaseMigrator, and
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '5.3.0'
|
||||
s.version = '5.5.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -18,6 +18,9 @@
|
||||
560432A1228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */; };
|
||||
560432A3228F1668009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */; };
|
||||
560432A4228F1668009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */; };
|
||||
5604484925DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */; };
|
||||
5604484A25DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */; };
|
||||
5604484B25DEEEF8002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */; };
|
||||
56057C552291B16A00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56057C4E2291B16900A7CB10 /* AssociationHasManyRowScopeTests.swift */; };
|
||||
56057C562291B16A00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56057C4E2291B16900A7CB10 /* AssociationHasManyRowScopeTests.swift */; };
|
||||
56057C622291C7C600A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56057C612291C7C600A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */; };
|
||||
@@ -128,6 +131,10 @@
|
||||
5623936D1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */; };
|
||||
562393721DEE104400A6B01F /* MapCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393711DEE104400A6B01F /* MapCursorTests.swift */; };
|
||||
562393761DEE104400A6B01F /* MapCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393711DEE104400A6B01F /* MapCursorTests.swift */; };
|
||||
56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; };
|
||||
56256EDA25D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; };
|
||||
56256EDB25D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; };
|
||||
56256EDC25D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; };
|
||||
562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
|
||||
562756471E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
|
||||
562EA8261F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
|
||||
@@ -260,9 +267,6 @@
|
||||
564390D52414FC2C00BA61E6 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AAA4DCFE230F1E0600C74B15 /* GRDB.framework */; };
|
||||
564448831EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
|
||||
564448871EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
|
||||
5644DE6D20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; };
|
||||
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 */; };
|
||||
564CE43121AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
|
||||
564CE43221AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
|
||||
@@ -329,9 +333,6 @@
|
||||
5653EB2120944C7C00F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */; };
|
||||
5653EB2220944C7C00F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */; };
|
||||
5653EB2320944C7C00F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */; };
|
||||
5653EB252094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */; };
|
||||
5653EB262094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */; };
|
||||
5653EB272094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */; };
|
||||
5653EC122098738B00F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */; };
|
||||
5653EC132098738B00F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */; };
|
||||
5653EC142098738B00F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */; };
|
||||
@@ -414,12 +415,6 @@
|
||||
5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475991D97D8A000FF74B8 /* SQLCollection.swift */; };
|
||||
5664759D1D97D8A000FF74B8 /* SQLCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475991D97D8A000FF74B8 /* SQLCollection.swift */; };
|
||||
566475A01D97D8A000FF74B8 /* SQLCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475991D97D8A000FF74B8 /* SQLCollection.swift */; };
|
||||
566475A21D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */; };
|
||||
566475A51D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */; };
|
||||
566475A81D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */; };
|
||||
566475BA1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */; };
|
||||
566475BD1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */; };
|
||||
566475C01D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */; };
|
||||
566475CC1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */; };
|
||||
566475CF1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */; };
|
||||
566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */; };
|
||||
@@ -466,6 +461,10 @@
|
||||
566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
|
||||
566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
|
||||
566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
|
||||
566B9C2025C6CC24004542CF /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */; };
|
||||
566B9C2125C6CC24004542CF /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */; };
|
||||
566B9C2225C6CC24004542CF /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */; };
|
||||
566B9C2325C6CC24004542CF /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */; };
|
||||
566BE71E2342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; };
|
||||
566BE71F2342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; };
|
||||
566BE7202342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; };
|
||||
@@ -532,6 +531,18 @@
|
||||
568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLQueryGenerator.swift */; };
|
||||
568D13202207213E00674B58 /* SQLQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLQueryGenerator.swift */; };
|
||||
568D13212207213F00674B58 /* SQLQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLQueryGenerator.swift */; };
|
||||
568ECA8A25D7013000B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA8925D7013000B71526 /* SQLSelection.swift */; };
|
||||
568ECA8B25D7013000B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA8925D7013000B71526 /* SQLSelection.swift */; };
|
||||
568ECA8C25D7013000B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA8925D7013000B71526 /* SQLSelection.swift */; };
|
||||
568ECA8D25D7013000B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA8925D7013000B71526 /* SQLSelection.swift */; };
|
||||
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */; };
|
||||
568ECAA025D7E53E00B71526 /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */; };
|
||||
568ECAA125D7E53E00B71526 /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */; };
|
||||
568ECAA225D7E53E00B71526 /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */; };
|
||||
568ECB1825D9161600B71526 /* SQLSubquery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB1725D9161500B71526 /* SQLSubquery.swift */; };
|
||||
568ECB1925D9161600B71526 /* SQLSubquery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB1725D9161500B71526 /* SQLSubquery.swift */; };
|
||||
568ECB1A25D9161600B71526 /* SQLSubquery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB1725D9161500B71526 /* SQLSubquery.swift */; };
|
||||
568ECB1B25D9161600B71526 /* SQLSubquery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB1725D9161500B71526 /* SQLSubquery.swift */; };
|
||||
5690C32A1D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; };
|
||||
5690C33B1D23E7D200E59934 /* FoundationDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3361D23E7D200E59934 /* FoundationDateTests.swift */; };
|
||||
5690C3401D23E82A00E59934 /* Data.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C33F1D23E82A00E59934 /* Data.swift */; };
|
||||
@@ -726,18 +737,9 @@
|
||||
56CEB5451EAA359A00BFAF62 /* Column.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5401EAA359A00BFAF62 /* Column.swift */; };
|
||||
56CEB5481EAA359A00BFAF62 /* Column.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5401EAA359A00BFAF62 /* Column.swift */; };
|
||||
56CEB54B1EAA359A00BFAF62 /* Column.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5401EAA359A00BFAF62 /* Column.swift */; };
|
||||
56CEB54C1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */; };
|
||||
56CEB54F1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */; };
|
||||
56CEB5521EAA359A00BFAF62 /* SQLExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */; };
|
||||
56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */; };
|
||||
56CEB5561EAA359A00BFAF62 /* SQLExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */; };
|
||||
56CEB5591EAA359A00BFAF62 /* SQLExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */; };
|
||||
56CEB55A1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */; };
|
||||
56CEB55D1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */; };
|
||||
56CEB5601EAA359A00BFAF62 /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */; };
|
||||
56CEB5611EAA359A00BFAF62 /* SQLSelectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */; };
|
||||
56CEB5641EAA359A00BFAF62 /* SQLSelectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */; };
|
||||
56CEB5671EAA359A00BFAF62 /* SQLSelectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */; };
|
||||
56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */; };
|
||||
56D496551D812F83008276D7 /* FoundationDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */; };
|
||||
56D496571D81303E008276D7 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; };
|
||||
@@ -821,10 +823,6 @@
|
||||
56D51D001EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; };
|
||||
56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; };
|
||||
56D51D061EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; };
|
||||
56D8B3FF257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */; };
|
||||
56D8B400257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */; };
|
||||
56D8B401257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */; };
|
||||
56D8B402257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */; };
|
||||
56D91AA22205E03700770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA12205E03700770D8D /* SQLRelation.swift */; };
|
||||
56D91AA32205E03700770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA12205E03700770D8D /* SQLRelation.swift */; };
|
||||
56D91AA42205E03700770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA12205E03700770D8D /* SQLRelation.swift */; };
|
||||
@@ -886,9 +884,6 @@
|
||||
56FBFED92210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
|
||||
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
|
||||
56FBFEDB2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
|
||||
56FC98781D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; };
|
||||
56FC987B1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; };
|
||||
56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; };
|
||||
56FDECE31BB32DFD009AD709 /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; };
|
||||
56FEB8F8248403000081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */; };
|
||||
56FEB8F9248403010081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */; };
|
||||
@@ -914,7 +909,6 @@
|
||||
AAA4DC83230F1E0600C74B15 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; };
|
||||
AAA4DC84230F1E0600C74B15 /* CGFloat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1491C672E4000235C62 /* CGFloat.swift */; };
|
||||
AAA4DC85230F1E0600C74B15 /* Column.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5401EAA359A00BFAF62 /* Column.swift */; };
|
||||
AAA4DC86230F1E0600C74B15 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */; };
|
||||
AAA4DC87230F1E0600C74B15 /* Date.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F14F1C672E4000235C62 /* Date.swift */; };
|
||||
AAA4DC89230F1E0600C74B15 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
|
||||
AAA4DC8A230F1E0600C74B15 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
|
||||
@@ -936,13 +930,11 @@
|
||||
AAA4DC9A230F1E0600C74B15 /* FTS5TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */; };
|
||||
AAA4DC9B230F1E0600C74B15 /* SerializedDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */; };
|
||||
AAA4DC9C230F1E0600C74B15 /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; };
|
||||
AAA4DC9D230F1E0600C74B15 /* SQLExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */; };
|
||||
AAA4DC9E230F1E0600C74B15 /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; };
|
||||
AAA4DC9F230F1E0600C74B15 /* NSString.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1521C672E4000235C62 /* NSString.swift */; };
|
||||
AAA4DCA0230F1E0600C74B15 /* Database+Statements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91081FA4C3960012D5B0 /* Database+Statements.swift */; };
|
||||
AAA4DCA1230F1E0600C74B15 /* UUID.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C22F1D1914540096E9D4 /* UUID.swift */; };
|
||||
AAA4DCA2230F1E0600C74B15 /* DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */; };
|
||||
AAA4DCA3230F1E0600C74B15 /* SQLSpecificExpressible+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */; };
|
||||
AAA4DCA4230F1E0600C74B15 /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; };
|
||||
AAA4DCA5230F1E0600C74B15 /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; };
|
||||
AAA4DCA6230F1E0600C74B15 /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; };
|
||||
@@ -967,7 +959,6 @@
|
||||
AAA4DCBA230F1E0600C74B15 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; };
|
||||
AAA4DCBB230F1E0600C74B15 /* DatabaseValueConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */; };
|
||||
AAA4DCBC230F1E0600C74B15 /* DatabaseCollation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91121FA4C3F50012D5B0 /* DatabaseCollation.swift */; };
|
||||
AAA4DCBD230F1E0600C74B15 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; };
|
||||
AAA4DCBE230F1E0600C74B15 /* Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238761B9C75030082EB20 /* Row.swift */; };
|
||||
AAA4DCC1230F1E0600C74B15 /* Inflections.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF4492161F179007DAACD /* Inflections.swift */; };
|
||||
AAA4DCC2230F1E0600C74B15 /* FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */; };
|
||||
@@ -990,7 +981,6 @@
|
||||
AAA4DCD4230F1E0600C74B15 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; };
|
||||
AAA4DCD5230F1E0600C74B15 /* FTS5WrapperTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */; };
|
||||
AAA4DCD6230F1E0600C74B15 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
|
||||
AAA4DCD7230F1E0600C74B15 /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; };
|
||||
AAA4DCD8230F1E0600C74B15 /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = C96C0F242084A442006B2981 /* SQLiteDateParser.swift */; };
|
||||
AAA4DCD9230F1E0600C74B15 /* NSNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1511C672E4000235C62 /* NSNumber.swift */; };
|
||||
AAA4DCDB230F1E0600C74B15 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */; };
|
||||
@@ -1001,15 +991,12 @@
|
||||
AAA4DCE0230F1E0600C74B15 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; };
|
||||
AAA4DCE2230F1E0600C74B15 /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; };
|
||||
AAA4DCE3230F1E0600C74B15 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3421A95A5C00DC7A68 /* Map.swift */; };
|
||||
AAA4DCE4230F1E0600C74B15 /* SQLSelectable+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */; };
|
||||
AAA4DCE5230F1E0600C74B15 /* SQLLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAD7221053DC00C703A8 /* SQLLiteral.swift */; };
|
||||
AAA4DCE6230F1E0600C74B15 /* SQLForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAF920944C7B00F46237 /* SQLForeignKeyRequest.swift */; };
|
||||
AAA4DCE7230F1E0600C74B15 /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; };
|
||||
AAA4DCEA230F1E0600C74B15 /* DatabaseValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238751B9C75030082EB20 /* DatabaseValue.swift */; };
|
||||
AAA4DCEB230F1E0600C74B15 /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */; };
|
||||
AAA4DCEC230F1E0600C74B15 /* Database+Schema.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91221FA4CF810012D5B0 /* Database+Schema.swift */; };
|
||||
AAA4DCED230F1E0600C74B15 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; };
|
||||
AAA4DCEE230F1E0600C74B15 /* SQLSelectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */; };
|
||||
AAA4DCEF230F1E0600C74B15 /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA12205E03700770D8D /* SQLRelation.swift */; };
|
||||
AAA4DCF0230F1E0600C74B15 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; };
|
||||
AAA4DCF1230F1E0600C74B15 /* RemoveDuplicates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* RemoveDuplicates.swift */; };
|
||||
@@ -1250,6 +1237,7 @@
|
||||
56012B742574048B00B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = "<group>"; };
|
||||
56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = "<group>"; };
|
||||
560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = "<group>"; };
|
||||
5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = "<group>"; };
|
||||
56057C4E2291B16900A7CB10 /* AssociationHasManyRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyRowScopeTests.swift; sourceTree = "<group>"; };
|
||||
56057C612291C7C600A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughRowScopeTests.swift; sourceTree = "<group>"; };
|
||||
5605F1491C672E4000235C62 /* CGFloat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloat.swift; sourceTree = "<group>"; };
|
||||
@@ -1294,6 +1282,7 @@
|
||||
562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FlattenCursorTests.swift; sourceTree = "<group>"; };
|
||||
562393711DEE104400A6B01F /* MapCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MapCursorTests.swift; sourceTree = "<group>"; };
|
||||
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = "<group>"; };
|
||||
56256ED825D1B316008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = "<group>"; };
|
||||
562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = "<group>"; };
|
||||
562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = "<group>"; };
|
||||
562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1349,7 +1338,6 @@
|
||||
56419A6D24A51601004967E1 /* DatabaseRegionObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationPublisherTests.swift; sourceTree = "<group>"; };
|
||||
56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationPublisherTests.swift; sourceTree = "<group>"; };
|
||||
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>"; };
|
||||
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>"; };
|
||||
@@ -1379,7 +1367,6 @@
|
||||
5653EAFA20944C7B00F46237 /* Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Association.swift; sourceTree = "<group>"; };
|
||||
5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasManyAssociation.swift; sourceTree = "<group>"; };
|
||||
5653EB0220944C7C00F46237 /* HasOneAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasOneAssociation.swift; sourceTree = "<group>"; };
|
||||
5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "QueryInterfaceRequest+Association.swift"; sourceTree = "<group>"; };
|
||||
5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLGenerationContext.swift; sourceTree = "<group>"; };
|
||||
565490A01D5A4798005622CB /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
56553C181C3E906C00522B5C /* GRDBOSXCrashTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXCrashTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
@@ -1405,8 +1392,6 @@
|
||||
565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NumericOverflowTests.swift; sourceTree = "<group>"; };
|
||||
565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowAdapterTests.swift; sourceTree = "<group>"; };
|
||||
566475991D97D8A000FF74B8 /* SQLCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollection.swift; sourceTree = "<group>"; };
|
||||
566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLSelectable+QueryInterface.swift"; sourceTree = "<group>"; };
|
||||
566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLSpecificExpressible+QueryInterface.swift"; sourceTree = "<group>"; };
|
||||
566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunctions.swift; sourceTree = "<group>"; };
|
||||
566475CB1D981D5E00FF74B8 /* SQLOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperators.swift; sourceTree = "<group>"; };
|
||||
5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1425,6 +1410,7 @@
|
||||
566B91221FA4CF810012D5B0 /* Database+Schema.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Schema.swift"; sourceTree = "<group>"; };
|
||||
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = "<group>"; };
|
||||
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = "<group>"; };
|
||||
566B9C1F25C6CC24004542CF /* RowDecodingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowDecodingError.swift; sourceTree = "<group>"; };
|
||||
566BE7172342542F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.swift; sourceTree = "<group>"; };
|
||||
56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1455,6 +1441,9 @@
|
||||
56848972242DE36F002F9702 /* ValueObservationScheduler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationScheduler.swift; sourceTree = "<group>"; };
|
||||
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
|
||||
568D13182207213E00674B58 /* SQLQueryGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQueryGenerator.swift; sourceTree = "<group>"; };
|
||||
568ECA8925D7013000B71526 /* SQLSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelection.swift; sourceTree = "<group>"; };
|
||||
568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOrdering.swift; sourceTree = "<group>"; };
|
||||
568ECB1725D9161500B71526 /* SQLSubquery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSubquery.swift; sourceTree = "<group>"; };
|
||||
5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = "<group>"; };
|
||||
5690C3361D23E7D200E59934 /* FoundationDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateTests.swift; sourceTree = "<group>"; };
|
||||
5690C33F1D23E82A00E59934 /* Data.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Data.swift; sourceTree = "<group>"; };
|
||||
@@ -1571,13 +1560,9 @@
|
||||
56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FTS3+QueryInterface.swift"; sourceTree = "<group>"; };
|
||||
56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FTS5+QueryInterface.swift"; sourceTree = "<group>"; };
|
||||
56CEB5401EAA359A00BFAF62 /* Column.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Column.swift; sourceTree = "<group>"; };
|
||||
56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpressible.swift; sourceTree = "<group>"; };
|
||||
56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpression.swift; sourceTree = "<group>"; };
|
||||
56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOrdering.swift; sourceTree = "<group>"; };
|
||||
56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectable.swift; sourceTree = "<group>"; };
|
||||
56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = "<group>"; };
|
||||
56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = "<group>"; };
|
||||
56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRowValue.swift; sourceTree = "<group>"; };
|
||||
56D91AA12205E03700770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = "<group>"; };
|
||||
56D91AA82205F2F000770D8D /* DatabasePromise.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePromise.swift; sourceTree = "<group>"; };
|
||||
56D91AAF2205F8AC00770D8D /* SQLQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQuery.swift; sourceTree = "<group>"; };
|
||||
@@ -1604,7 +1589,6 @@
|
||||
56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLIdentifyingColumnsTests.swift; sourceTree = "<group>"; };
|
||||
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = "<group>"; };
|
||||
56FBFED82210731A00945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = "<group>"; };
|
||||
56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = "<group>"; };
|
||||
56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = "<group>"; };
|
||||
56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseTraceTests.swift; sourceTree = "<group>"; };
|
||||
56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1882,6 +1866,7 @@
|
||||
56300B6D1C53F592005A543B /* QueryInterface */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56256ED825D1B316008C2BDD /* ForeignKey.swift */,
|
||||
56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterface.swift */,
|
||||
56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */,
|
||||
5656A8182295B044001FF3FF /* Request */,
|
||||
@@ -2002,6 +1987,7 @@
|
||||
56DF001A228DDBA300D611F3 /* AssociationPrefetchingCodableRecordTests.swift */,
|
||||
569BBA20228DE51800478429 /* AssociationPrefetchingFetchableRecordTests.swift */,
|
||||
560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */,
|
||||
5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */,
|
||||
56DF0019228DDBA200D611F3 /* AssociationPrefetchingRowTests.swift */,
|
||||
560714E2227DD0810091BB10 /* AssociationPrefetchingSQLTests.swift */,
|
||||
5653EAC820944B4D00F46237 /* AssociationRowScopeSearchTests.swift */,
|
||||
@@ -2051,19 +2037,15 @@
|
||||
5656A81D2295B12F001FF3FF /* SQLAssociation.swift */,
|
||||
5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */,
|
||||
566475991D97D8A000FF74B8 /* SQLCollection.swift */,
|
||||
56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */,
|
||||
56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */,
|
||||
56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */,
|
||||
5653EAF920944C7B00F46237 /* SQLForeignKeyRequest.swift */,
|
||||
566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */,
|
||||
566475CB1D981D5E00FF74B8 /* SQLOperators.swift */,
|
||||
56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */,
|
||||
568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */,
|
||||
56D91AAF2205F8AC00770D8D /* SQLQuery.swift */,
|
||||
56D91AA12205E03700770D8D /* SQLRelation.swift */,
|
||||
56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */,
|
||||
56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */,
|
||||
566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */,
|
||||
566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */,
|
||||
568ECA8925D7013000B71526 /* SQLSelection.swift */,
|
||||
568ECB1725D9161500B71526 /* SQLSubquery.swift */,
|
||||
);
|
||||
path = SQL;
|
||||
sourceTree = "<group>";
|
||||
@@ -2074,7 +2056,6 @@
|
||||
5653EAF720944BC900F46237 /* Association */,
|
||||
56012B742574048B00B4925B /* CommonTableExpression.swift */,
|
||||
56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */,
|
||||
5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */,
|
||||
5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */,
|
||||
);
|
||||
path = Request;
|
||||
@@ -2300,12 +2281,12 @@
|
||||
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
|
||||
566A84192041146100E50BFD /* DatabaseSnapshot.swift */,
|
||||
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
|
||||
5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */,
|
||||
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
|
||||
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
|
||||
5636E9BB1D22574100B9B05F /* FetchRequest.swift */,
|
||||
56A238761B9C75030082EB20 /* Row.swift */,
|
||||
567404871CEF84C8003ED5CC /* RowAdapter.swift */,
|
||||
566B9C1F25C6CC24004542CF /* RowDecodingError.swift */,
|
||||
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
|
||||
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
|
||||
569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */,
|
||||
@@ -2876,11 +2857,11 @@
|
||||
565490E41D5AE252005622CB /* TableRecord.swift in Sources */,
|
||||
564CE5AE21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
|
||||
565490CF1D5AE252005622CB /* NSNumber.swift in Sources */,
|
||||
566475C01D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */,
|
||||
56CEB51F1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */,
|
||||
56D91AA42205E03700770D8D /* SQLRelation.swift in Sources */,
|
||||
565490E21D5AE252005622CB /* Record.swift in Sources */,
|
||||
565490C11D5AE236005622CB /* FetchRequest.swift in Sources */,
|
||||
568ECB1A25D9161600B71526 /* SQLSubquery.swift in Sources */,
|
||||
5613ED4621A95B2C00DC7A68 /* ValueReducer.swift in Sources */,
|
||||
5698AD1C1DAAD17F0056AF8C /* FTS5Tokenizer.swift in Sources */,
|
||||
56CEB5171EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */,
|
||||
@@ -2891,22 +2872,19 @@
|
||||
564CE59F21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */,
|
||||
56F5ABDA1D814330001F60CB /* NSData.swift in Sources */,
|
||||
564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */,
|
||||
566475A81D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */,
|
||||
5659F4961EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
|
||||
56172950223533F40006E219 /* EncodableRecord.swift in Sources */,
|
||||
56AE64142229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */,
|
||||
5613ED3721A95A5C00DC7A68 /* Map.swift in Sources */,
|
||||
5659F48E1EA8D94E004A4992 /* Utils.swift in Sources */,
|
||||
564CE43321AA901800652B19 /* ValueObserver.swift in Sources */,
|
||||
56CEB5671EAA359A00BFAF62 /* SQLSelectable.swift in Sources */,
|
||||
563B8FC724A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
5653EB272094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */,
|
||||
566B9C2225C6CC24004542CF /* RowDecodingError.swift in Sources */,
|
||||
565490B91D5AE236005622CB /* DatabasePool.swift in Sources */,
|
||||
563B06AD217EF0CC00B38F35 /* ValueObservation.swift in Sources */,
|
||||
5674A6EF1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */,
|
||||
565490D81D5AE252005622CB /* DatabaseMigrator.swift in Sources */,
|
||||
5656A8AF2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */,
|
||||
56CEB5601EAA359A00BFAF62 /* SQLOrdering.swift in Sources */,
|
||||
565490C21D5AE236005622CB /* Row.swift in Sources */,
|
||||
565490C71D5AE236005622CB /* StatementColumnConvertible.swift in Sources */,
|
||||
565490D91D5AE252005622CB /* Migration.swift in Sources */,
|
||||
@@ -2926,6 +2904,7 @@
|
||||
565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */,
|
||||
566B91191FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
|
||||
56CEB5591EAA359A00BFAF62 /* SQLExpression.swift in Sources */,
|
||||
568ECA8C25D7013000B71526 /* SQLSelection.swift in Sources */,
|
||||
5674A6FF1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
|
||||
56E9FAD9221053DD00C703A8 /* SQLLiteral.swift in Sources */,
|
||||
563082E62430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */,
|
||||
@@ -2954,9 +2933,9 @@
|
||||
56CEB54B1EAA359A00BFAF62 /* Column.swift in Sources */,
|
||||
565490CC1D5AE252005622CB /* (null) in Sources */,
|
||||
566B91291FA4CF810012D5B0 /* Database+Schema.swift in Sources */,
|
||||
568ECAA125D7E53E00B71526 /* SQLOrdering.swift in Sources */,
|
||||
5671FC261DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
|
||||
5653EC142098738B00F46237 /* SQLGenerationContext.swift in Sources */,
|
||||
56CEB5521EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
|
||||
563B8F94249E6171007A48C9 /* Trace.swift in Sources */,
|
||||
568D13212207213F00674B58 /* SQLQueryGenerator.swift in Sources */,
|
||||
565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */,
|
||||
@@ -2970,7 +2949,6 @@
|
||||
566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
|
||||
565490B61D5AE236005622CB /* Configuration.swift in Sources */,
|
||||
565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */,
|
||||
56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */,
|
||||
569BBA50229170FA00478429 /* Inflections+English.swift in Sources */,
|
||||
563B8FB724A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
|
||||
566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
@@ -2989,14 +2967,13 @@
|
||||
565490D61D5AE252005622CB /* StandardLibrary.swift in Sources */,
|
||||
565490B81D5AE236005622CB /* DatabaseError.swift in Sources */,
|
||||
56DAA2E11DE9C827006E10C8 /* Cursor.swift in Sources */,
|
||||
56D8B401257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */,
|
||||
5653EB0520944C7C00F46237 /* BelongsToAssociation.swift in Sources */,
|
||||
5644DE6F20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */,
|
||||
56A2FA3C24424F4800E97D23 /* Export.swift in Sources */,
|
||||
565490BC1D5AE236005622CB /* DatabaseSchemaCache.swift in Sources */,
|
||||
563EF42F2161180D007DAACD /* AssociationAggregate.swift in Sources */,
|
||||
565490BA1D5AE236005622CB /* DatabaseQueue.swift in Sources */,
|
||||
56781B0D243F86E600650A83 /* Refinable.swift in Sources */,
|
||||
56256EDB25D1B316008C2BDD /* ForeignKey.swift in Sources */,
|
||||
565490CD1D5AE252005622CB /* Date.swift in Sources */,
|
||||
5653EB0820944C7C00F46237 /* SQLForeignKeyRequest.swift in Sources */,
|
||||
565490BE1D5AE236005622CB /* DatabaseValue.swift in Sources */,
|
||||
@@ -3024,6 +3001,7 @@
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
568ECAA025D7E53E00B71526 /* SQLOrdering.swift in Sources */,
|
||||
5636E9BF1D22574100B9B05F /* FetchRequest.swift in Sources */,
|
||||
563EF42E2161180D007DAACD /* AssociationAggregate.swift in Sources */,
|
||||
56BB6EAC1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
|
||||
@@ -3041,10 +3019,10 @@
|
||||
56CEB4FD1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
|
||||
5605F15A1C672E4000235C62 /* CGFloat.swift in Sources */,
|
||||
56CEB5481EAA359A00BFAF62 /* Column.swift in Sources */,
|
||||
5653EB262094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */,
|
||||
5605F1641C672E4000235C62 /* Date.swift in Sources */,
|
||||
566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
564CE43221AA901800652B19 /* ValueObserver.swift in Sources */,
|
||||
568ECA8B25D7013000B71526 /* SQLSelection.swift in Sources */,
|
||||
56AACAA922ACED7100A40F2A /* Fetch.swift in Sources */,
|
||||
5605F1721C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
|
||||
56CEB5141EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */,
|
||||
@@ -3065,13 +3043,11 @@
|
||||
563B8FB624A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
|
||||
560A37A81C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
|
||||
566A841B2041146100E50BFD /* DatabaseSnapshot.swift in Sources */,
|
||||
56CEB54F1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
|
||||
56A238941B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
|
||||
5605F16A1C672E4000235C62 /* NSString.swift in Sources */,
|
||||
566B910C1FA4C3970012D5B0 /* Database+Statements.swift in Sources */,
|
||||
56A8C2331D1914540096E9D4 /* UUID.swift in Sources */,
|
||||
560D92411C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */,
|
||||
566475BD1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */,
|
||||
56A238A51B9C753B0082EB20 /* Record.swift in Sources */,
|
||||
5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
|
||||
56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
|
||||
@@ -3089,6 +3065,7 @@
|
||||
56A2387C1B9C75030082EB20 /* Configuration.swift in Sources */,
|
||||
56DAA2DE1DE9C827006E10C8 /* Cursor.swift in Sources */,
|
||||
560A37A51C8F625000949E71 /* DatabasePool.swift in Sources */,
|
||||
56256EDA25D1B316008C2BDD /* ForeignKey.swift in Sources */,
|
||||
5674A7081F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
|
||||
56AE64132229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */,
|
||||
56A2388C1B9C75030082EB20 /* Statement.swift in Sources */,
|
||||
@@ -3099,7 +3076,6 @@
|
||||
5674A7001F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
|
||||
5674A6E91F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
|
||||
566B91161FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
|
||||
56FC987B1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */,
|
||||
56A238881B9C75030082EB20 /* Row.swift in Sources */,
|
||||
563EF44B2161F179007DAACD /* Inflections.swift in Sources */,
|
||||
56CEB4F41EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */,
|
||||
@@ -3122,10 +3098,9 @@
|
||||
5653EB0D20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
|
||||
567ECE502222E431009245CA /* GRDB-5.0.swift in Sources */,
|
||||
566AD8B51D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
|
||||
56D8B400257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */,
|
||||
5698AD241DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
|
||||
568ECB1925D9161600B71526 /* SQLSubquery.swift in Sources */,
|
||||
56FBFED92210731A00945324 /* SQLRequest.swift in Sources */,
|
||||
5644DE6E20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */,
|
||||
C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */,
|
||||
5605F1681C672E4000235C62 /* NSNumber.swift in Sources */,
|
||||
564CE5AD21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
|
||||
@@ -3133,20 +3108,18 @@
|
||||
563B8F93249E6171007A48C9 /* Trace.swift in Sources */,
|
||||
5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */,
|
||||
56E9FACC221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */,
|
||||
566B9C2125C6CC24004542CF /* RowDecodingError.swift in Sources */,
|
||||
560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */,
|
||||
5613ED4521A95B2C00DC7A68 /* ValueReducer.swift in Sources */,
|
||||
560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */,
|
||||
5613ED3621A95A5C00DC7A68 /* Map.swift in Sources */,
|
||||
566475A51D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */,
|
||||
56E9FAD8221053DD00C703A8 /* SQLLiteral.swift in Sources */,
|
||||
56781B0C243F86E600650A83 /* Refinable.swift in Sources */,
|
||||
5653EB0720944C7C00F46237 /* SQLForeignKeyRequest.swift in Sources */,
|
||||
5657AABC1D107001006283EF /* NSData.swift in Sources */,
|
||||
56A238861B9C75030082EB20 /* DatabaseValue.swift in Sources */,
|
||||
56CEB55D1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */,
|
||||
566B91261FA4CF810012D5B0 /* Database+Schema.swift in Sources */,
|
||||
566B912E1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */,
|
||||
56CEB5641EAA359A00BFAF62 /* SQLSelectable.swift in Sources */,
|
||||
56D91AA32205E03700770D8D /* SQLRelation.swift in Sources */,
|
||||
564F9C311F07611600877A00 /* DatabaseFunction.swift in Sources */,
|
||||
564CE59E21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */,
|
||||
@@ -3312,6 +3285,7 @@
|
||||
561CFA7923735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */,
|
||||
56A238621B9C74A90082EB20 /* RecordEditedTests.swift in Sources */,
|
||||
5653EAE120944B4F00F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */,
|
||||
5604484A25DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */,
|
||||
5653EAE720944B4F00F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */,
|
||||
56419C6F24A519A3004967E1 /* DatabaseReaderReadPublisherTests.swift in Sources */,
|
||||
563EF440216131D1007DAACD /* AssociationAggregateTests.swift in Sources */,
|
||||
@@ -3538,6 +3512,7 @@
|
||||
5653EAE820944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */,
|
||||
561CFA7823735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */,
|
||||
56A5EF0F1EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */,
|
||||
5604484925DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */,
|
||||
56D496B61D813434008276D7 /* DatabaseRegionTests.swift in Sources */,
|
||||
5653EAE020944B4F00F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */,
|
||||
56419C6A24A519A2004967E1 /* DatabaseReaderReadPublisherTests.swift in Sources */,
|
||||
@@ -3611,6 +3586,7 @@
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
568ECAA225D7E53E00B71526 /* SQLOrdering.swift in Sources */,
|
||||
AAA4DC77230F1E0600C74B15 /* FetchRequest.swift in Sources */,
|
||||
AAA4DC78230F1E0600C74B15 /* AssociationAggregate.swift in Sources */,
|
||||
AAA4DC79230F1E0600C74B15 /* SchedulingWatchdog.swift in Sources */,
|
||||
@@ -3628,10 +3604,10 @@
|
||||
AAA4DC83230F1E0600C74B15 /* FTS3.swift in Sources */,
|
||||
AAA4DC84230F1E0600C74B15 /* CGFloat.swift in Sources */,
|
||||
AAA4DC85230F1E0600C74B15 /* Column.swift in Sources */,
|
||||
AAA4DC86230F1E0600C74B15 /* QueryInterfaceRequest+Association.swift in Sources */,
|
||||
AAA4DC87230F1E0600C74B15 /* Date.swift in Sources */,
|
||||
AAA4DC89230F1E0600C74B15 /* TransactionObserver.swift in Sources */,
|
||||
AAA4DC8A230F1E0600C74B15 /* ValueObserver.swift in Sources */,
|
||||
568ECA8D25D7013000B71526 /* SQLSelection.swift in Sources */,
|
||||
AAA4DC8B230F1E0600C74B15 /* Fetch.swift in Sources */,
|
||||
AAA4DC8C230F1E0600C74B15 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
|
||||
AAA4DC8D230F1E0600C74B15 /* FTS3+QueryInterface.swift in Sources */,
|
||||
@@ -3652,13 +3628,11 @@
|
||||
563B8FB824A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
|
||||
AAA4DC9B230F1E0600C74B15 /* SerializedDatabase.swift in Sources */,
|
||||
AAA4DC9C230F1E0600C74B15 /* DatabaseSnapshot.swift in Sources */,
|
||||
AAA4DC9D230F1E0600C74B15 /* SQLExpressible.swift in Sources */,
|
||||
AAA4DC9E230F1E0600C74B15 /* DatabaseMigrator.swift in Sources */,
|
||||
AAA4DC9F230F1E0600C74B15 /* NSString.swift in Sources */,
|
||||
AAA4DCA0230F1E0600C74B15 /* Database+Statements.swift in Sources */,
|
||||
AAA4DCA1230F1E0600C74B15 /* UUID.swift in Sources */,
|
||||
AAA4DCA2230F1E0600C74B15 /* DatabaseValueConvertible.swift in Sources */,
|
||||
AAA4DCA3230F1E0600C74B15 /* SQLSpecificExpressible+QueryInterface.swift in Sources */,
|
||||
AAA4DCA4230F1E0600C74B15 /* Record.swift in Sources */,
|
||||
AAA4DCA5230F1E0600C74B15 /* FTS3TokenizerDescriptor.swift in Sources */,
|
||||
AAA4DCA6230F1E0600C74B15 /* FetchableRecord+TableRecord.swift in Sources */,
|
||||
@@ -3676,6 +3650,7 @@
|
||||
AAA4DCB0230F1E0600C74B15 /* Configuration.swift in Sources */,
|
||||
AAA4DCB1230F1E0600C74B15 /* Cursor.swift in Sources */,
|
||||
AAA4DCB2230F1E0600C74B15 /* DatabasePool.swift in Sources */,
|
||||
56256EDC25D1B316008C2BDD /* ForeignKey.swift in Sources */,
|
||||
AAA4DCB3230F1E0600C74B15 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
|
||||
AAA4DCB4230F1E0600C74B15 /* HasOneThroughAssociation.swift in Sources */,
|
||||
AAA4DCB5230F1E0600C74B15 /* Statement.swift in Sources */,
|
||||
@@ -3686,7 +3661,6 @@
|
||||
AAA4DCBA230F1E0600C74B15 /* FetchableRecord+Decodable.swift in Sources */,
|
||||
AAA4DCBB230F1E0600C74B15 /* DatabaseValueConvertible+Decodable.swift in Sources */,
|
||||
AAA4DCBC230F1E0600C74B15 /* DatabaseCollation.swift in Sources */,
|
||||
AAA4DCBD230F1E0600C74B15 /* SQLExpression+QueryInterface.swift in Sources */,
|
||||
AAA4DCBE230F1E0600C74B15 /* Row.swift in Sources */,
|
||||
AAA4DCC1230F1E0600C74B15 /* Inflections.swift in Sources */,
|
||||
AAA4DCC2230F1E0600C74B15 /* FetchableRecord.swift in Sources */,
|
||||
@@ -3709,10 +3683,9 @@
|
||||
AAA4DCD2230F1E0600C74B15 /* HasManyAssociation.swift in Sources */,
|
||||
AAA4DCD3230F1E0600C74B15 /* GRDB-5.0.swift in Sources */,
|
||||
AAA4DCD4230F1E0600C74B15 /* TableDefinition.swift in Sources */,
|
||||
56D8B402257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */,
|
||||
AAA4DCD5230F1E0600C74B15 /* FTS5WrapperTokenizer.swift in Sources */,
|
||||
568ECB1B25D9161600B71526 /* SQLSubquery.swift in Sources */,
|
||||
AAA4DCD6230F1E0600C74B15 /* SQLRequest.swift in Sources */,
|
||||
AAA4DCD7230F1E0600C74B15 /* DatabaseValueConversion.swift in Sources */,
|
||||
AAA4DCD8230F1E0600C74B15 /* SQLiteDateParser.swift in Sources */,
|
||||
AAA4DCD9230F1E0600C74B15 /* NSNumber.swift in Sources */,
|
||||
AAA4DCDB230F1E0600C74B15 /* DatabaseRegionObservation.swift in Sources */,
|
||||
@@ -3720,20 +3693,18 @@
|
||||
563B8F95249E6171007A48C9 /* Trace.swift in Sources */,
|
||||
AAA4DCDD230F1E0600C74B15 /* StandardLibrary.swift in Sources */,
|
||||
AAA4DCDE230F1E0600C74B15 /* SQLInterpolation+QueryInterface.swift in Sources */,
|
||||
566B9C2325C6CC24004542CF /* RowDecodingError.swift in Sources */,
|
||||
AAA4DCDF230F1E0600C74B15 /* PersistableRecord.swift in Sources */,
|
||||
AAA4DCE0230F1E0600C74B15 /* ValueReducer.swift in Sources */,
|
||||
AAA4DCE2230F1E0600C74B15 /* StatementColumnConvertible.swift in Sources */,
|
||||
AAA4DCE3230F1E0600C74B15 /* Map.swift in Sources */,
|
||||
AAA4DCE4230F1E0600C74B15 /* SQLSelectable+QueryInterface.swift in Sources */,
|
||||
AAA4DCE5230F1E0600C74B15 /* SQLLiteral.swift in Sources */,
|
||||
56781B0E243F86E600650A83 /* Refinable.swift in Sources */,
|
||||
AAA4DCE6230F1E0600C74B15 /* SQLForeignKeyRequest.swift in Sources */,
|
||||
AAA4DCE7230F1E0600C74B15 /* NSData.swift in Sources */,
|
||||
AAA4DCEA230F1E0600C74B15 /* DatabaseValue.swift in Sources */,
|
||||
AAA4DCEB230F1E0600C74B15 /* SQLOrdering.swift in Sources */,
|
||||
AAA4DCEC230F1E0600C74B15 /* Database+Schema.swift in Sources */,
|
||||
AAA4DCED230F1E0600C74B15 /* StatementAuthorizer.swift in Sources */,
|
||||
AAA4DCEE230F1E0600C74B15 /* SQLSelectable.swift in Sources */,
|
||||
AAA4DCEF230F1E0600C74B15 /* SQLRelation.swift in Sources */,
|
||||
AAA4DCF0230F1E0600C74B15 /* DatabaseFunction.swift in Sources */,
|
||||
AAA4DCF1230F1E0600C74B15 /* RemoveDuplicates.swift in Sources */,
|
||||
@@ -3899,6 +3870,7 @@
|
||||
561CFA7A23735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */,
|
||||
AAA4DD8E230F262000C74B15 /* RecordEditedTests.swift in Sources */,
|
||||
AAA4DD8F230F262000C74B15 /* AssociationTableAliasTestsSQLTests.swift in Sources */,
|
||||
5604484B25DEEEF8002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */,
|
||||
AAA4DD90230F262000C74B15 /* AssociationBelongsToFetchableRecordTests.swift in Sources */,
|
||||
56419C7424A519A4004967E1 /* DatabaseReaderReadPublisherTests.swift in Sources */,
|
||||
AAA4DD91230F262000C74B15 /* AssociationAggregateTests.swift in Sources */,
|
||||
@@ -3972,6 +3944,7 @@
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */,
|
||||
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */,
|
||||
56D91AB02205F8AC00770D8D /* SQLQuery.swift in Sources */,
|
||||
5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
|
||||
@@ -3992,11 +3965,11 @@
|
||||
56CEB4F11EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */,
|
||||
56D91AA22205E03700770D8D /* SQLRelation.swift in Sources */,
|
||||
56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */,
|
||||
568ECA8A25D7013000B71526 /* SQLSelection.swift in Sources */,
|
||||
56AACAA822ACED7100A40F2A /* Fetch.swift in Sources */,
|
||||
5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */,
|
||||
566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
566475D31D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
|
||||
56CEB5611EAA359A00BFAF62 /* SQLSelectable.swift in Sources */,
|
||||
56CEB4FA1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
|
||||
563082E42430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */,
|
||||
564CE59D21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */,
|
||||
@@ -4016,7 +3989,6 @@
|
||||
5659F4981EA8D989004A4992 /* Pool.swift in Sources */,
|
||||
56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */,
|
||||
5674A6F41F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */,
|
||||
56CEB54C1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
|
||||
5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */,
|
||||
567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */,
|
||||
5653EB0320944C7C00F46237 /* BelongsToAssociation.swift in Sources */,
|
||||
@@ -4028,17 +4000,15 @@
|
||||
56A2FA3624424D2A00E97D23 /* Export.swift in Sources */,
|
||||
56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
|
||||
560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
|
||||
5653EB252094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */,
|
||||
563B8FAC24A1CE43007A48C9 /* DatabasePublishers.swift in Sources */,
|
||||
5605F1691C672E4000235C62 /* NSString.swift in Sources */,
|
||||
560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */,
|
||||
56A8C2301D1914540096E9D4 /* UUID.swift in Sources */,
|
||||
56CEB5011EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
|
||||
56AE64122229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */,
|
||||
56CEB55A1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */,
|
||||
56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */,
|
||||
56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */,
|
||||
56D51D001EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
|
||||
566475BA1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */,
|
||||
5653EB0920944C7C00F46237 /* Association.swift in Sources */,
|
||||
56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */,
|
||||
5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
|
||||
@@ -4058,7 +4028,6 @@
|
||||
5656A8AD2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */,
|
||||
5690C3401D23E82A00E59934 /* Data.swift in Sources */,
|
||||
5659F4881EA8D94E004A4992 /* Utils.swift in Sources */,
|
||||
56FC98781D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */,
|
||||
566BE71E2342542F00A8254B /* LockedBox.swift in Sources */,
|
||||
56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
|
||||
5611620825757583007AAF99 /* JoinAssociation.swift in Sources */,
|
||||
@@ -4070,10 +4039,10 @@
|
||||
56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
|
||||
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */,
|
||||
563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */,
|
||||
56D8B3FF257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */,
|
||||
564CE43121AA901800652B19 /* ValueObserver.swift in Sources */,
|
||||
5605F1651C672E4000235C62 /* NSNull.swift in Sources */,
|
||||
56CEB5191EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */,
|
||||
568ECB1825D9161600B71526 /* SQLSubquery.swift in Sources */,
|
||||
5674A6FB1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
|
||||
5653EB0620944C7C00F46237 /* SQLForeignKeyRequest.swift in Sources */,
|
||||
56E9FACB221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */,
|
||||
@@ -4081,6 +4050,7 @@
|
||||
5698AC781DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */,
|
||||
56A2387D1B9C75030082EB20 /* Database.swift in Sources */,
|
||||
566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
|
||||
566B9C2025C6CC24004542CF /* RowDecodingError.swift in Sources */,
|
||||
5698AD211DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
|
||||
56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */,
|
||||
5605F1671C672E4000235C62 /* NSNumber.swift in Sources */,
|
||||
@@ -4092,10 +4062,8 @@
|
||||
5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */,
|
||||
5653EC122098738B00F46237 /* SQLGenerationContext.swift in Sources */,
|
||||
560D92471C672C4B00F4F92B /* PersistableRecord.swift in Sources */,
|
||||
566475A21D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */,
|
||||
5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
|
||||
5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
|
||||
5644DE6D20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */,
|
||||
5657AAB91D107001006283EF /* NSData.swift in Sources */,
|
||||
560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */,
|
||||
56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */,
|
||||
|
||||
@@ -669,6 +669,24 @@ public struct PrimaryKeyInfo {
|
||||
return tableHasRowID
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of the fastest primary key column
|
||||
///
|
||||
/// Returns nil for WITHOUT ROWID tables with a multi-columns primary key
|
||||
var fastPrimaryKeyColumn: String? {
|
||||
if let rowIDColumn = rowIDColumn {
|
||||
// Prefer the user-provided name of the rowid
|
||||
return rowIDColumn
|
||||
} else if tableHasRowID {
|
||||
// Prefer the rowid
|
||||
return Column.rowID.name
|
||||
} else if columns.count == 1 {
|
||||
// WITHOUT ROWID table: use primary key column
|
||||
return columns[0]
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// You get foreign keys from table names, with the
|
||||
|
||||
@@ -449,7 +449,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError(DatabaseError(resultCode: code, message: lastErrorMessage).description)
|
||||
fatalError(DatabaseError(resultCode: code, message: lastErrorMessage))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -130,7 +130,7 @@ public final class DatabaseFunction: Hashable {
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage).description)
|
||||
fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,7 +146,7 @@ public final class DatabaseFunction: Hashable {
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage).description)
|
||||
fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -190,9 +190,16 @@ extension DatabaseQueue {
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
public func read<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
try writer.sync { db in
|
||||
try db.readOnly { try block(db) }
|
||||
// The transaction guarantees snapshot isolation against eventual
|
||||
// external connection.
|
||||
var result: T?
|
||||
try db.inTransaction(.deferred) {
|
||||
result = try db.readOnly { try block(db) }
|
||||
return .commit
|
||||
}
|
||||
return result!
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,6 +221,9 @@ extension DatabaseQueue {
|
||||
public func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void) {
|
||||
writer.async { db in
|
||||
do {
|
||||
// The transaction guarantees snapshot isolation against eventual
|
||||
// external connection.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.beginReadOnly()
|
||||
} catch {
|
||||
block(.failure(error))
|
||||
@@ -224,6 +234,7 @@ extension DatabaseQueue {
|
||||
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.endReadOnly()
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -236,6 +247,9 @@ extension DatabaseQueue {
|
||||
}
|
||||
|
||||
do {
|
||||
// The transaction guarantees snapshot isolation against eventual
|
||||
// external connection.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.beginReadOnly()
|
||||
} catch {
|
||||
block(.failure(error))
|
||||
@@ -246,6 +260,7 @@ extension DatabaseQueue {
|
||||
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.endReadOnly()
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -289,9 +304,14 @@ extension DatabaseQueue {
|
||||
try writer.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
|
||||
return try db.readOnly {
|
||||
try block(db)
|
||||
// The transaction guarantees snapshot isolation against eventual
|
||||
// external connection.
|
||||
var result: T?
|
||||
try db.inTransaction(.deferred) {
|
||||
result = try db.readOnly { try block(db) }
|
||||
return .commit
|
||||
}
|
||||
return result!
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -306,6 +326,7 @@ extension DatabaseQueue {
|
||||
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
|
||||
|
||||
do {
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.beginReadOnly()
|
||||
} catch {
|
||||
block(.failure(error))
|
||||
@@ -316,6 +337,7 @@ extension DatabaseQueue {
|
||||
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.endReadOnly()
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import Foundation
|
||||
/// DatabaseValue is the intermediate type between SQLite and your values.
|
||||
///
|
||||
/// See https://www.sqlite.org/datatype3.html
|
||||
public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLExpression {
|
||||
public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLSpecificExpressible {
|
||||
/// The SQLite storage
|
||||
public let storage: Storage
|
||||
|
||||
@@ -115,6 +115,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
|
||||
}
|
||||
|
||||
/// Returns a DatabaseValue initialized from a raw SQLite statement pointer.
|
||||
@usableFromInline
|
||||
init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_NULL:
|
||||
@@ -137,69 +138,6 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
|
||||
fatalError("Unexpected SQLite column type: \(type)")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: SQLExpression
|
||||
|
||||
/// :nodoc:
|
||||
public func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
if isNull {
|
||||
// fast path for NULL
|
||||
return "NULL"
|
||||
} else if context.append(arguments: [self]) {
|
||||
// Use statement arguments
|
||||
return "?"
|
||||
} else {
|
||||
// Quoting needed: just use SQLite, which knows better.
|
||||
return try String.fetchOne(context.db, sql: "SELECT QUOTE(?)", arguments: [self])!
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set<Int64>? {
|
||||
if isNull || self == false.databaseValue {
|
||||
// Those requests select no row:
|
||||
// - WHERE NULL
|
||||
// - WHERE 0
|
||||
return []
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Specific boolean checks for null, true, and false
|
||||
/// :nodoc:
|
||||
public func _is(_ test: _SQLBooleanTest) -> SQLExpression {
|
||||
switch storage {
|
||||
case .null:
|
||||
return DatabaseValue.null
|
||||
|
||||
case .int64(let int64) where int64 == 0 || int64 == 1:
|
||||
switch test {
|
||||
case .true:
|
||||
return (int64 == 1).sqlExpression
|
||||
case .false, .falsey:
|
||||
return (int64 == 0).sqlExpression
|
||||
}
|
||||
|
||||
default:
|
||||
switch test {
|
||||
case .true:
|
||||
return SQLExpressionEqual(.equal, self, true.sqlExpression)
|
||||
case .false:
|
||||
return SQLExpressionEqual(.equal, self, false.sqlExpression)
|
||||
case .falsey:
|
||||
return SQLExpressionNot(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public var _isConstantInRequest: Bool { true }
|
||||
|
||||
/// :nodoc:
|
||||
public var _isTrue: Bool { self == true.databaseValue }
|
||||
|
||||
/// :nodoc:
|
||||
public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { self }
|
||||
}
|
||||
|
||||
// MARK: - Hashable & Equatable
|
||||
@@ -276,9 +214,8 @@ extension DatabaseValue {
|
||||
|
||||
// SQLExpressible
|
||||
extension DatabaseValue {
|
||||
/// :nodoc:
|
||||
public var sqlExpression: SQLExpression {
|
||||
self
|
||||
.databaseValue(self)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,315 +0,0 @@
|
||||
// MARK: - Conversion Context and Errors
|
||||
|
||||
/// A type that helps the user understanding value conversion errors
|
||||
struct ValueConversionContext: Refinable {
|
||||
private enum Column {
|
||||
case columnIndex(Int)
|
||||
case columnName(String)
|
||||
}
|
||||
|
||||
var row: Row?
|
||||
var sql: String?
|
||||
var arguments: StatementArguments?
|
||||
private var column: Column?
|
||||
|
||||
func atColumn(_ columnIndex: Int) -> Self {
|
||||
with(\.column, .columnIndex(columnIndex))
|
||||
}
|
||||
|
||||
func atColumn(_ columnName: String) -> Self {
|
||||
with(\.column, .columnName(columnName))
|
||||
}
|
||||
|
||||
var columnIndex: Int? {
|
||||
guard let column = column else { return nil }
|
||||
switch column {
|
||||
case .columnIndex(let index):
|
||||
return index
|
||||
case .columnName(let name):
|
||||
return row?.index(forColumn: name)
|
||||
}
|
||||
}
|
||||
|
||||
var columnName: String? {
|
||||
guard let column = column else { return nil }
|
||||
switch column {
|
||||
case .columnIndex(let index):
|
||||
guard let row = row else { return nil }
|
||||
return Array(row.columnNames)[index]
|
||||
case .columnName(let name):
|
||||
return name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension ValueConversionContext {
|
||||
init(_ statement: SelectStatement) {
|
||||
self.init(
|
||||
row: Row(statement: statement).copy(),
|
||||
sql: statement.sql,
|
||||
arguments: statement.arguments,
|
||||
column: nil)
|
||||
}
|
||||
|
||||
init(_ row: Row) {
|
||||
if let statement = row.statement {
|
||||
self.init(
|
||||
row: row.copy(),
|
||||
sql: statement.sql,
|
||||
arguments: statement.arguments,
|
||||
column: nil)
|
||||
} else if let sqliteStatement = row.sqliteStatement {
|
||||
let sql = String(cString: sqlite3_sql(sqliteStatement)).trimmingCharacters(in: .sqlStatementSeparators)
|
||||
self.init(
|
||||
row: row.copy(),
|
||||
sql: sql,
|
||||
arguments: nil,
|
||||
column: nil)
|
||||
} else {
|
||||
self.init(
|
||||
row: row.copy(),
|
||||
sql: nil,
|
||||
arguments: nil,
|
||||
column: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The canonical conversion error message
|
||||
///
|
||||
/// - parameter dbValue: nil means "missing column"
|
||||
func conversionErrorMessage<T>(
|
||||
to: T.Type,
|
||||
from dbValue: DatabaseValue?,
|
||||
conversionContext: ValueConversionContext?)
|
||||
-> String
|
||||
{
|
||||
var message: String
|
||||
var extras: [String] = []
|
||||
|
||||
if let dbValue = dbValue {
|
||||
message = "could not convert database value \(dbValue) to \(T.self)"
|
||||
if let columnName = conversionContext?.columnName {
|
||||
extras.append("column: `\(columnName)`")
|
||||
}
|
||||
if let columnIndex = conversionContext?.columnIndex {
|
||||
extras.append("column index: \(columnIndex)")
|
||||
}
|
||||
} else {
|
||||
message = "could not read \(T.self) from missing column"
|
||||
if let columnName = conversionContext?.columnName {
|
||||
message += " `\(columnName)`"
|
||||
}
|
||||
}
|
||||
|
||||
if let row = conversionContext?.row {
|
||||
extras.append("row: \(row)")
|
||||
}
|
||||
|
||||
if let sql = conversionContext?.sql {
|
||||
extras.append("sql: `\(sql)`")
|
||||
if let arguments = conversionContext?.arguments, arguments.isEmpty == false {
|
||||
extras.append("arguments: \(arguments)")
|
||||
}
|
||||
}
|
||||
|
||||
if extras.isEmpty == false {
|
||||
message += " (" + extras.joined(separator: ", ") + ")"
|
||||
}
|
||||
return message
|
||||
}
|
||||
|
||||
/// The canonical conversion fatal error
|
||||
///
|
||||
/// - parameter dbValue: nil means "missing column", for consistency with (row["missing"] as DatabaseValue? == nil)
|
||||
func fatalConversionError<T>(
|
||||
to: T.Type,
|
||||
from dbValue: DatabaseValue?,
|
||||
conversionContext: ValueConversionContext?,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
-> Never
|
||||
{
|
||||
fatalError(
|
||||
conversionErrorMessage(
|
||||
to: T.self,
|
||||
from: dbValue,
|
||||
conversionContext: conversionContext),
|
||||
file: file,
|
||||
line: line)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func fatalConversionError<T>(
|
||||
to: T.Type,
|
||||
from dbValue: DatabaseValue?,
|
||||
in row: Row,
|
||||
atColumn columnName: String,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
-> Never
|
||||
{
|
||||
fatalConversionError(
|
||||
to: T.self,
|
||||
from: dbValue,
|
||||
conversionContext: ValueConversionContext(row).atColumn(columnName))
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func fatalConversionError<T>(
|
||||
to: T.Type,
|
||||
sqliteStatement: SQLiteStatement,
|
||||
index: Int32,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
-> Never
|
||||
{
|
||||
let row = Row(sqliteStatement: sqliteStatement)
|
||||
fatalConversionError(
|
||||
to: T.self,
|
||||
from: DatabaseValue(sqliteStatement: sqliteStatement, index: index),
|
||||
conversionContext: ValueConversionContext(row).atColumn(Int(index)))
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func fatalConversionError<T>(
|
||||
to: T.Type,
|
||||
from dbValue: DatabaseValue?,
|
||||
sqliteStatement: SQLiteStatement,
|
||||
index: Int32,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
-> Never
|
||||
{
|
||||
let row = Row(sqliteStatement: sqliteStatement)
|
||||
fatalConversionError(
|
||||
to: T.self,
|
||||
from: dbValue,
|
||||
conversionContext: ValueConversionContext(row).atColumn(Int(index)))
|
||||
}
|
||||
|
||||
// MARK: - DatabaseValueConvertible
|
||||
|
||||
/// Lossless conversions from database values and rows
|
||||
extension DatabaseValueConvertible {
|
||||
@usableFromInline
|
||||
static func decode(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self {
|
||||
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
|
||||
if let value = fromDatabaseValue(dbValue) {
|
||||
return value
|
||||
} else {
|
||||
fatalConversionError(to: Self.self, from: dbValue, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
}
|
||||
|
||||
static func decode(
|
||||
from dbValue: DatabaseValue,
|
||||
conversionContext: @autoclosure () -> ValueConversionContext?)
|
||||
-> Self
|
||||
{
|
||||
if let value = fromDatabaseValue(dbValue) {
|
||||
return value
|
||||
} else {
|
||||
fatalConversionError(to: Self.self, from: dbValue, conversionContext: conversionContext())
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
static func decode(from row: Row, atUncheckedIndex index: Int) -> Self {
|
||||
decode(
|
||||
from: row.impl.databaseValue(atUncheckedIndex: index),
|
||||
conversionContext: ValueConversionContext(row).atColumn(index))
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
static func decodeIfPresent(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self? {
|
||||
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
|
||||
if let value = fromDatabaseValue(dbValue) {
|
||||
return value
|
||||
} else if dbValue.isNull {
|
||||
return nil
|
||||
} else {
|
||||
fatalConversionError(to: Self.self, from: dbValue, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
}
|
||||
|
||||
static func decodeIfPresent(
|
||||
from dbValue: DatabaseValue,
|
||||
conversionContext: @autoclosure () -> ValueConversionContext?)
|
||||
-> Self?
|
||||
{
|
||||
// Use fromDatabaseValue before checking for null: this allows DatabaseValue to convert NULL to .null.
|
||||
if let value = fromDatabaseValue(dbValue) {
|
||||
return value
|
||||
} else if dbValue.isNull {
|
||||
return nil
|
||||
} else {
|
||||
fatalConversionError(to: Self.self, from: dbValue, conversionContext: conversionContext())
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
static func decodeIfPresent(from row: Row, atUncheckedIndex index: Int) -> Self? {
|
||||
decodeIfPresent(
|
||||
from: row.impl.databaseValue(atUncheckedIndex: index),
|
||||
conversionContext: ValueConversionContext(row).atColumn(index))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - DatabaseValueConvertible & StatementColumnConvertible
|
||||
|
||||
/// Lossless conversions from database values and rows
|
||||
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
@inlinable
|
||||
static func fastDecode(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self {
|
||||
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
|
||||
fatalConversionError(to: Self.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
return self.init(sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func fastDecode(from row: Row, atUncheckedIndex index: Int) -> Self {
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return fastDecode(from: sqliteStatement, atUncheckedIndex: Int32(index))
|
||||
}
|
||||
return row.fastDecode(Self.self, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func fastDecodeIfPresent(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self? {
|
||||
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
|
||||
return nil
|
||||
}
|
||||
return self.init(sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func fastDecodeIfPresent(from row: Row, atUncheckedIndex index: Int) -> Self? {
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return fastDecodeIfPresent(from: sqliteStatement, atUncheckedIndex: Int32(index))
|
||||
}
|
||||
return row.fastDecodeIfPresent(Self.self, atUncheckedIndex: index)
|
||||
}
|
||||
}
|
||||
|
||||
// Support for @inlinable decoding
|
||||
extension Row {
|
||||
@usableFromInline
|
||||
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int)
|
||||
-> Value
|
||||
{
|
||||
impl.fastDecode(type, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int)
|
||||
-> Value?
|
||||
{
|
||||
impl.fastDecodeIfPresent(type, atUncheckedIndex: index)
|
||||
}
|
||||
}
|
||||
@@ -23,12 +23,98 @@ public protocol DatabaseValueConvertible: SQLExpressible {
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible {
|
||||
/// :nodoc:
|
||||
public var sqlExpression: SQLExpression {
|
||||
databaseValue
|
||||
.databaseValue(databaseValue)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Conversions
|
||||
|
||||
extension DatabaseValueConvertible {
|
||||
static func decode(
|
||||
fromDatabaseValue dbValue: DatabaseValue,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Self
|
||||
{
|
||||
if let value = fromDatabaseValue(dbValue) {
|
||||
return value
|
||||
} else {
|
||||
throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue)
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
static func decode(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: Int32,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Self
|
||||
{
|
||||
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
|
||||
return try decode(fromDatabaseValue: dbValue, context: context())
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
static func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Self {
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return try decode(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
return try decode(
|
||||
fromDatabaseValue: row.impl.databaseValue(atUncheckedIndex: index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
|
||||
static func decodeIfPresent(
|
||||
fromDatabaseValue dbValue: DatabaseValue,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Self?
|
||||
{
|
||||
// Use fromDatabaseValue before checking for null: this allows DatabaseValue to convert NULL to .null.
|
||||
if let value = fromDatabaseValue(dbValue) {
|
||||
return value
|
||||
} else if dbValue.isNull {
|
||||
return nil
|
||||
} else {
|
||||
throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue)
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
static func decodeIfPresent(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: Int32,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Self?
|
||||
{
|
||||
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
|
||||
if let value = fromDatabaseValue(dbValue) {
|
||||
return value
|
||||
} else if dbValue.isNull {
|
||||
return nil
|
||||
} else {
|
||||
throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue)
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
static func decodeIfPresent(fromRow row: Row, atUncheckedIndex index: Int) throws -> Self? {
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return try decodeIfPresent(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
return try decodeIfPresent(
|
||||
fromDatabaseValue: row.impl.databaseValue(atUncheckedIndex: index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Cursors
|
||||
|
||||
/// A cursor of database values extracted from a single column.
|
||||
/// For example:
|
||||
///
|
||||
@@ -77,7 +163,11 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor
|
||||
_done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return Value.decode(from: _sqliteStatement, atUncheckedIndex: _columnIndex)
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
return try! Value.decode(
|
||||
fromStatement: _sqliteStatement,
|
||||
atUncheckedIndex: _columnIndex,
|
||||
context: RowDecodingContext(statement: _statement, index: Int(_columnIndex)))
|
||||
case let code:
|
||||
try _statement.didFail(withResultCode: code)
|
||||
}
|
||||
@@ -132,7 +222,11 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>:
|
||||
_done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return Value.decodeIfPresent(from: _sqliteStatement, atUncheckedIndex: _columnIndex)
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
return try! Value.decodeIfPresent(
|
||||
fromStatement: _sqliteStatement,
|
||||
atUncheckedIndex: _columnIndex,
|
||||
context: RowDecodingContext(statement: _statement, index: Int(_columnIndex)))
|
||||
case let code:
|
||||
try _statement.didFail(withResultCode: code)
|
||||
}
|
||||
|
||||
+10
-111
@@ -1,53 +1,5 @@
|
||||
// MARK: - FetchRequest
|
||||
|
||||
/// Implementation details of `FetchRequest`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol _FetchRequest {
|
||||
/// The number of columns selected by the request.
|
||||
///
|
||||
/// This method makes it possible to find the columns of a CTE in a request
|
||||
/// that includes a CTE association:
|
||||
///
|
||||
/// // WITH cte AS (SELECT 1 AS a, 2 AS b)
|
||||
/// // SELECT player.*, cte.*
|
||||
/// // FROM player
|
||||
/// // JOIN cte
|
||||
/// let cte = CommonTableExpression<Void>(named: "cte", sql: "SELECT 1 AS a, 2 AS b")
|
||||
/// let request = Player
|
||||
/// .with(cte)
|
||||
/// .including(required: Player.association(to: cte))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// // We know that "SELECT 1 AS a, 2 AS b" selects two columns,
|
||||
/// // so we can find cte columns in the row:
|
||||
/// row.scopes["cte"] // [a:1, b:2]
|
||||
///
|
||||
/// :nodoc:
|
||||
func _selectedColumnCount(_ db: Database) throws -> Int
|
||||
|
||||
/// Returns the request SQL.
|
||||
///
|
||||
/// This method makes it possible to embed a request as a subquery:
|
||||
///
|
||||
/// // SELECT *
|
||||
/// // FROM "player"
|
||||
/// // WHERE "score" = (SELECT MAX("score") FROM "player")
|
||||
/// let maxScore = Player.select(max(Column("score")))
|
||||
/// let players = try Player
|
||||
/// .filter(Column("score") == maxScore)
|
||||
/// .fetchAll(db)
|
||||
///
|
||||
/// - parameter context: An SQL generation context.
|
||||
/// - parameter singleResult: A hint that a single result row will be
|
||||
/// consumed. Implementations can optionally use it to optimize the
|
||||
/// generated SQL, for example by adding a `LIMIT 1` SQL clause.
|
||||
/// - returns: An SQL string.
|
||||
///
|
||||
/// :nodoc:
|
||||
func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String
|
||||
}
|
||||
|
||||
/// The protocol for all requests that fetch database rows, and tell how those
|
||||
/// rows should be interpreted.
|
||||
///
|
||||
@@ -58,7 +10,7 @@ public protocol _FetchRequest {
|
||||
/// try request.fetchSet(db) // Set<Player>
|
||||
/// try request.fetchOne(db) // Player?
|
||||
/// try request.fetchCount(db) // Int
|
||||
public protocol FetchRequest: _FetchRequest, DatabaseRegionConvertible, SQLExpression, SQLCollection {
|
||||
public protocol FetchRequest: SQLSubqueryable, DatabaseRegionConvertible {
|
||||
/// The type that tells how fetched database rows should be interpreted.
|
||||
associatedtype RowDecoder
|
||||
|
||||
@@ -84,45 +36,12 @@ public protocol FetchRequest: _FetchRequest, DatabaseRegionConvertible, SQLExpre
|
||||
}
|
||||
|
||||
extension FetchRequest {
|
||||
// MARK: DatabaseRegionConvertible
|
||||
|
||||
/// Returns the database region that the request feeds from.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
try makePreparedRequest(db, forSingleResult: false).statement.databaseRegion
|
||||
}
|
||||
|
||||
// MARK: SQLCollection
|
||||
|
||||
/// :nodoc:
|
||||
public var _collectionExpressions: [SQLExpression]? { nil }
|
||||
|
||||
/// :nodoc:
|
||||
public func _collectionSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
try "("
|
||||
+ _requestSQL(context, forSingleResult: false)
|
||||
+ ")"
|
||||
}
|
||||
|
||||
public func contains(_ value: SQLExpressible) -> SQLExpression {
|
||||
SQLExpressionContains(value, self)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _qualifiedCollection(with alias: TableAlias) -> SQLCollection { self }
|
||||
|
||||
// MARK: SQLExpression
|
||||
|
||||
/// :nodoc:
|
||||
public func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
try "("
|
||||
+ _requestSQL(context, forSingleResult: false)
|
||||
+ ")"
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { self }
|
||||
}
|
||||
|
||||
// MARK: - PreparedRequest
|
||||
@@ -174,6 +93,10 @@ public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
|
||||
self.adapter = adapter
|
||||
}
|
||||
|
||||
public var sqlSubquery: SQLSubquery {
|
||||
base.sqlSubquery
|
||||
}
|
||||
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
try base.fetchCount(db)
|
||||
}
|
||||
@@ -193,16 +116,6 @@ public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
|
||||
|
||||
return preparedRequest
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _selectedColumnCount(_ db: Database) throws -> Int {
|
||||
try base._selectedColumnCount(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
|
||||
try base._requestSQL(context, forSingleResult: singleResult)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - AnyFetchRequest
|
||||
@@ -222,9 +135,8 @@ public struct AnyFetchRequest<RowDecoder>: FetchRequest {
|
||||
AnyFetchRequest<RowDecoder>(request: request)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _selectedColumnCount(_ db: Database) throws -> Int {
|
||||
try request._selectedColumnCount(db)
|
||||
public var sqlSubquery: SQLSubquery {
|
||||
request.sqlSubquery
|
||||
}
|
||||
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
@@ -238,11 +150,6 @@ public struct AnyFetchRequest<RowDecoder>: FetchRequest {
|
||||
{
|
||||
try request.makePreparedRequest(db, forSingleResult: singleResult)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
|
||||
try request._requestSQL(context, forSingleResult: singleResult)
|
||||
}
|
||||
}
|
||||
|
||||
extension AnyFetchRequest {
|
||||
@@ -258,7 +165,7 @@ extension AnyFetchRequest {
|
||||
private class FetchRequestEraser: FetchRequest {
|
||||
typealias RowDecoder = Void
|
||||
|
||||
func _selectedColumnCount(_ db: Database) throws -> Int {
|
||||
var sqlSubquery: SQLSubquery {
|
||||
fatalError("subclass must override")
|
||||
}
|
||||
|
||||
@@ -269,10 +176,6 @@ private class FetchRequestEraser: FetchRequest {
|
||||
func fetchCount(_ db: Database) throws -> Int {
|
||||
fatalError("subclass must override")
|
||||
}
|
||||
|
||||
func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
|
||||
fatalError("subclass must override")
|
||||
}
|
||||
}
|
||||
|
||||
private final class ConcreteFetchRequestEraser<Request: FetchRequest>: FetchRequestEraser {
|
||||
@@ -282,8 +185,8 @@ private final class ConcreteFetchRequestEraser<Request: FetchRequest>: FetchRequ
|
||||
self.request = request
|
||||
}
|
||||
|
||||
override func _selectedColumnCount(_ db: Database) throws -> Int {
|
||||
try request._selectedColumnCount(db)
|
||||
override var sqlSubquery: SQLSubquery {
|
||||
request.sqlSubquery
|
||||
}
|
||||
|
||||
override func fetchCount(_ db: Database) throws -> Int {
|
||||
@@ -293,8 +196,4 @@ private final class ConcreteFetchRequestEraser<Request: FetchRequest>: FetchRequ
|
||||
override func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
|
||||
try request.makePreparedRequest(db, forSingleResult: singleResult)
|
||||
}
|
||||
|
||||
override func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
|
||||
try request._requestSQL(context, forSingleResult: singleResult)
|
||||
}
|
||||
}
|
||||
+576
-135
@@ -166,8 +166,9 @@ extension Row {
|
||||
|
||||
/// Fatal errors if index is out of bounds
|
||||
@inlinable
|
||||
func _checkIndex(_ index: Int, file: StaticString = #file, line: UInt = #line) {
|
||||
func checkedIndex(_ index: Int, file: StaticString = #file, line: UInt = #line) -> Int {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range", file: file, line: line)
|
||||
return index
|
||||
}
|
||||
|
||||
/// Returns true if and only if one column contains a non-null value, or if
|
||||
@@ -202,8 +203,7 @@ extension Row {
|
||||
/// in performance-critical code because it can avoid decoding database
|
||||
/// values.
|
||||
public func hasNull(atIndex index: Int) -> Bool {
|
||||
_checkIndex(index)
|
||||
return impl.hasNull(atUncheckedIndex: index)
|
||||
impl.hasNull(atUncheckedIndex: checkedIndex(index))
|
||||
}
|
||||
|
||||
/// Returns Int64, Double, String, Data or nil, depending on the value
|
||||
@@ -212,8 +212,7 @@ extension Row {
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
/// righmost column.
|
||||
public subscript(_ index: Int) -> DatabaseValueConvertible? {
|
||||
_checkIndex(index)
|
||||
return impl.databaseValue(atUncheckedIndex: index).storage.value
|
||||
impl.databaseValue(atUncheckedIndex: checkedIndex(index)).storage.value
|
||||
}
|
||||
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
@@ -226,8 +225,7 @@ extension Row {
|
||||
/// fail, a fatal error is raised.
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value? {
|
||||
_checkIndex(index)
|
||||
return Value.decodeIfPresent(from: self, atUncheckedIndex: index)
|
||||
try! decodeIfPresent(Value.self, atIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
@@ -244,8 +242,7 @@ extension Row {
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value? {
|
||||
_checkIndex(index)
|
||||
return Value.fastDecodeIfPresent(from: self, atUncheckedIndex: index)
|
||||
try! decodeIfPresent(Value.self, atIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
@@ -257,8 +254,7 @@ extension Row {
|
||||
/// SQLite value can not be converted to `Value`.
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value {
|
||||
_checkIndex(index)
|
||||
return Value.decode(from: self, atUncheckedIndex: index)
|
||||
try! decode(Value.self, atIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
@@ -274,8 +270,7 @@ extension Row {
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value {
|
||||
_checkIndex(index)
|
||||
return Value.fastDecode(from: self, atUncheckedIndex: index)
|
||||
try! decode(Value.self, atIndex: index)
|
||||
}
|
||||
|
||||
/// Returns Int64, Double, String, Data or nil, depending on the value
|
||||
@@ -309,10 +304,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 {
|
||||
return nil
|
||||
}
|
||||
return Value.decodeIfPresent(from: self, atUncheckedIndex: index)
|
||||
try! decodeIfPresent(Value.self, forKey: columnName)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -329,10 +321,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 {
|
||||
return nil
|
||||
}
|
||||
return Value.fastDecodeIfPresent(from: self, atUncheckedIndex: index)
|
||||
try! decodeIfPresent(Value.self, forKey: columnName)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -346,11 +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 {
|
||||
// No such column
|
||||
fatalConversionError(to: Value.self, from: nil, in: self, atColumn: columnName)
|
||||
}
|
||||
return Value.decode(from: self, atUncheckedIndex: index)
|
||||
try! decode(Value.self, forKey: columnName)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -368,11 +353,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 {
|
||||
// No such column
|
||||
fatalConversionError(to: Value.self, from: nil, in: self, atColumn: columnName)
|
||||
}
|
||||
return Value.fastDecode(from: self, atUncheckedIndex: index)
|
||||
try! decode(Value.self, forKey: columnName)
|
||||
}
|
||||
|
||||
/// Returns Int64, Double, String, NSData or nil, depending on the value
|
||||
@@ -397,7 +378,7 @@ extension Row {
|
||||
/// `Value`. Should this conversion fail, a fatal error is raised.
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible, Column: ColumnExpression>(_ column: Column) -> Value? {
|
||||
self[column.name]
|
||||
try! decodeIfPresent(Value.self, forKey: column.name)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -419,7 +400,7 @@ extension Row {
|
||||
Value: DatabaseValueConvertible & StatementColumnConvertible,
|
||||
Column: ColumnExpression
|
||||
{
|
||||
self[column.name]
|
||||
try! decodeIfPresent(Value.self, forKey: column.name)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -433,7 +414,7 @@ extension Row {
|
||||
/// SQLite value can not be converted to `Value`.
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible, Column: ColumnExpression>(_ column: Column) -> Value {
|
||||
self[column.name]
|
||||
try! decode(Value.self, forKey: column.name)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -456,7 +437,7 @@ extension Row {
|
||||
Value: DatabaseValueConvertible & StatementColumnConvertible,
|
||||
Column: ColumnExpression
|
||||
{
|
||||
self[column.name]
|
||||
try! decode(Value.self, forKey: column.name)
|
||||
}
|
||||
|
||||
/// Returns the optional Data at given index.
|
||||
@@ -470,8 +451,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(atIndex index: Int) -> Data? {
|
||||
_checkIndex(index)
|
||||
return impl.dataNoCopy(atUncheckedIndex: index)
|
||||
try! decodeDataNoCopyIfPresent(atIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the optional Data at given column.
|
||||
@@ -486,10 +466,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 {
|
||||
return nil
|
||||
}
|
||||
return impl.dataNoCopy(atUncheckedIndex: index)
|
||||
try! decodeDataNoCopyIfPresent(forKey: columnName)
|
||||
}
|
||||
|
||||
/// Returns the optional `NSData` at given column.
|
||||
@@ -504,7 +481,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<Column: ColumnExpression>(_ column: Column) -> Data? {
|
||||
dataNoCopy(named: column.name)
|
||||
try! decodeDataNoCopyIfPresent(forKey: column.name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -557,20 +534,7 @@ extension Row {
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support
|
||||
/// for more information.
|
||||
public subscript<Record: FetchableRecord>(_ scope: String) -> Record {
|
||||
guard let scopedRow = scopesTree[scope] else {
|
||||
// Programmer error
|
||||
let names = scopesTree.names
|
||||
if names.isEmpty {
|
||||
fatalError("missing scope `\(scope)` (row: \(self))")
|
||||
} else {
|
||||
fatalError("missing scope `\(scope)` (row: \(self), available scopes: \(names.sorted()))")
|
||||
}
|
||||
}
|
||||
guard scopedRow.containsNonNullValue else {
|
||||
// Programmer error
|
||||
fatalError("scope `\(scope)` only contains null values (row: \(self))")
|
||||
}
|
||||
return Record(row: scopedRow)
|
||||
try! decode(Record.self, forKey: scope)
|
||||
}
|
||||
|
||||
/// Returns the eventual record associated with the given scope.
|
||||
@@ -605,10 +569,7 @@ extension Row {
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support
|
||||
/// for more information.
|
||||
public subscript<Record: FetchableRecord>(_ scope: String) -> Record? {
|
||||
guard let scopedRow = scopesTree[scope], scopedRow.containsNonNullValue else {
|
||||
return nil
|
||||
}
|
||||
return Record(row: scopedRow)
|
||||
try! decodeIfPresent(Record.self, forKey: scope)
|
||||
}
|
||||
|
||||
/// Returns the records encoded in the given prefetched rows.
|
||||
@@ -630,21 +591,7 @@ extension Row {
|
||||
Collection: RangeReplaceableCollection,
|
||||
Collection.Element: FetchableRecord
|
||||
{
|
||||
guard let rows = prefetchedRows[key] else {
|
||||
// Programmer error
|
||||
let keys = prefetchedRows.keys
|
||||
if keys.isEmpty {
|
||||
fatalError("missing key for prefetched rows `\(key)` (row: \(self))")
|
||||
} else {
|
||||
fatalError("missing key for prefetched rows `\(key)` (row: \(self), available keys: \(keys.sorted()))")
|
||||
}
|
||||
}
|
||||
var collection = Collection()
|
||||
collection.reserveCapacity(rows.count)
|
||||
for row in rows {
|
||||
collection.append(Collection.Element(row: row))
|
||||
}
|
||||
return collection
|
||||
try! decode(Collection.self, forKey: key)
|
||||
}
|
||||
|
||||
/// Returns the set of records encoded in the given prefetched rows.
|
||||
@@ -661,20 +608,7 @@ extension Row {
|
||||
/// print(books.first!.title)
|
||||
/// // Prints "Moby-Dick"
|
||||
public subscript<Record: FetchableRecord & Hashable>(_ key: String) -> Set<Record> {
|
||||
guard let rows = prefetchedRows[key] else {
|
||||
// Programmer error
|
||||
let keys = prefetchedRows.keys
|
||||
if keys.isEmpty {
|
||||
fatalError("missing key for prefetched rows `\(key)` (row: \(self))")
|
||||
} else {
|
||||
fatalError("missing key for prefetched rows `\(key)` (row: \(self), available keys: \(keys.sorted()))")
|
||||
}
|
||||
}
|
||||
var set = Set<Record>(minimumCapacity: rows.count)
|
||||
for row in rows {
|
||||
set.insert(Record(row: row))
|
||||
}
|
||||
return set
|
||||
try! decode(Set<Record>.self, forKey: key)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -761,6 +695,492 @@ extension Row {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Throwing DatabaseValueConvertible Decoding Methods
|
||||
|
||||
extension Row {
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
///
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
/// righmost column.
|
||||
///
|
||||
/// If the SQLite value is NULL, the result is nil. Otherwise the SQLite
|
||||
/// value is converted to the requested type `Value`. If the conversion
|
||||
/// fail, a `RowDecodingError` is thrown.
|
||||
@inlinable
|
||||
func decodeIfPresent<Value: DatabaseValueConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
atIndex index: Int)
|
||||
throws -> Value?
|
||||
{
|
||||
try Value.decodeIfPresent(fromRow: self, atUncheckedIndex: checkedIndex(index))
|
||||
}
|
||||
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
///
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
/// righmost column.
|
||||
///
|
||||
/// If the SQLite value is NULL, or if the conversion fails, a
|
||||
/// `RowDecodingError` is thrown.
|
||||
@inlinable
|
||||
func decode<Value: DatabaseValueConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
atIndex index: Int)
|
||||
throws -> Value
|
||||
{
|
||||
try Value.decode(fromRow: self, atUncheckedIndex: checkedIndex(index))
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
///
|
||||
/// Column name lookup is case-insensitive, and when several columns have
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the column is missing or if the SQLite value is NULL, the result is
|
||||
/// nil. Otherwise the SQLite value is converted to the requested type
|
||||
/// `Value`. If the conversion fails, a `RowDecodingError` is thrown.
|
||||
@inlinable
|
||||
func decodeIfPresent<Value: DatabaseValueConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
forKey columnName: String)
|
||||
throws -> Value?
|
||||
{
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
return nil
|
||||
}
|
||||
return try Value.decodeIfPresent(fromRow: self, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
///
|
||||
/// Column name lookup is case-insensitive, and when several columns have
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the row does not contain the column, or if the SQLite value is NULL,
|
||||
/// or if the SQLite value can not be converted to `Value`, a
|
||||
/// `RowDecodingError` is thrown.
|
||||
@inlinable
|
||||
func decode<Value: DatabaseValueConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
forKey columnName: String)
|
||||
throws -> Value
|
||||
{
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self))
|
||||
}
|
||||
return try Value.decode(fromRow: self, atUncheckedIndex: index)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Throwing DatabaseValueConvertible & StatementColumnConvertible Decoding Methods
|
||||
|
||||
extension Row {
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
///
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
/// righmost column.
|
||||
///
|
||||
/// If the SQLite value is NULL, the result is nil. Otherwise the SQLite
|
||||
/// value is converted to the requested type `Value`. If the conversion
|
||||
/// fail, a `RowDecodingError` is thrown.
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
@inlinable
|
||||
func decodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
atIndex index: Int)
|
||||
throws -> Value?
|
||||
{
|
||||
try Value.fastDecodeIfPresent(fromRow: self, atUncheckedIndex: checkedIndex(index))
|
||||
}
|
||||
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
///
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
/// righmost column.
|
||||
///
|
||||
/// If the SQLite value is NULL, or if the conversion fails, a
|
||||
/// `RowDecodingError` is thrown.
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
@inlinable
|
||||
func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
atIndex index: Int)
|
||||
throws -> Value
|
||||
{
|
||||
try Value.fastDecode(fromRow: self, atUncheckedIndex: checkedIndex(index))
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
///
|
||||
/// Column name lookup is case-insensitive, and when several columns have
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the column is missing or if the SQLite value is NULL, the result is
|
||||
/// nil. Otherwise the SQLite value is converted to the requested type
|
||||
/// `Value`. If the conversion fails, a `RowDecodingError` is thrown.
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
@inlinable
|
||||
func decodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
forKey columnName: String)
|
||||
throws -> Value?
|
||||
{
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
return nil
|
||||
}
|
||||
return try Value.fastDecodeIfPresent(fromRow: self, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
///
|
||||
/// Column name lookup is case-insensitive, and when several columns have
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the row does not contain the column, or if the SQLite value is NULL,
|
||||
/// or if the SQLite value can not be converted to `Value`, a
|
||||
/// `RowDecodingError` is thrown.
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
@inlinable
|
||||
func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
forKey columnName: String)
|
||||
throws -> Value
|
||||
{
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self))
|
||||
}
|
||||
return try Value.fastDecode(fromRow: self, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
// Support for fast decoding in scoped rows
|
||||
@usableFromInline
|
||||
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Value
|
||||
{
|
||||
try impl.fastDecode(type, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
// Support for fast decoding in scoped rows
|
||||
@usableFromInline
|
||||
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Value?
|
||||
{
|
||||
try impl.fastDecodeIfPresent(type, atUncheckedIndex: index)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Throwing Data Decoding Methods
|
||||
|
||||
extension Row {
|
||||
/// Returns the optional Data at given index.
|
||||
///
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
/// righmost column.
|
||||
///
|
||||
/// If the SQLite value is NULL, the result is nil. If the SQLite value can
|
||||
/// not be converted to Data, a `RowDecodingError` is thrown.
|
||||
///
|
||||
/// The returned data does not owns its bytes: it must not be used longer
|
||||
/// than the row's lifetime.
|
||||
func decodeDataNoCopyIfPresent(atIndex index: Int) throws -> Data? {
|
||||
try impl.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: checkedIndex(index))
|
||||
}
|
||||
|
||||
/// Returns the Data at given index.
|
||||
///
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
/// righmost column.
|
||||
///
|
||||
/// If the SQLite value is NULL, or if the SQLite value can not be converted
|
||||
/// to Data, a `RowDecodingError` is thrown.
|
||||
///
|
||||
/// The returned data does not owns its bytes: it must not be used longer
|
||||
/// than the row's lifetime.
|
||||
func decodeDataNoCopy(atIndex index: Int) throws -> Data {
|
||||
try impl.fastDecodeDataNoCopy(atUncheckedIndex: checkedIndex(index))
|
||||
}
|
||||
|
||||
/// Returns the optional Data at given column.
|
||||
///
|
||||
/// Column name lookup is case-insensitive, and when several columns have
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the column is missing or if the SQLite value is NULL, the result is
|
||||
/// nil. If the SQLite value can not be converted to Data, a
|
||||
/// `RowDecodingError` is thrown.
|
||||
///
|
||||
/// The returned data does not owns its bytes: it must not be used longer
|
||||
/// than the row's lifetime.
|
||||
func decodeDataNoCopyIfPresent(forKey columnName: String) throws -> Data? {
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
return nil
|
||||
}
|
||||
return try impl.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the Data at given column.
|
||||
///
|
||||
/// Column name lookup is case-insensitive, and when several columns have
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the column is missing, or if the SQLite value is NULL, or if the
|
||||
/// SQLite value can not be converted to Data, a
|
||||
/// `RowDecodingError` is thrown.
|
||||
///
|
||||
/// The returned data does not owns its bytes: it must not be used longer
|
||||
/// than the row's lifetime.
|
||||
func decodeDataNoCopy(forKey columnName: String) throws -> Data {
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self))
|
||||
}
|
||||
return try impl.fastDecodeDataNoCopy(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
// Support for fast decoding in scoped rows
|
||||
@usableFromInline
|
||||
func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data {
|
||||
try impl.fastDecodeDataNoCopy(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
// Support for fast decoding in scoped rows
|
||||
@usableFromInline
|
||||
func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? {
|
||||
try impl.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: index)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Throwing Record Decoding Methods
|
||||
|
||||
extension Row {
|
||||
/// Returns the eventual record associated with the given scope.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let request = Book.including(optional: Book.author)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
///
|
||||
/// let author: Author? = row["author"]
|
||||
/// print(author.name)
|
||||
/// // Prints "Herman Melville"
|
||||
///
|
||||
/// Associated records stored in nested associations are available, too:
|
||||
///
|
||||
/// let request = Book.including(optional: Book.author.including(optional: Author.country))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
///
|
||||
/// let country: Country? = row["country"]
|
||||
/// print(country.name)
|
||||
/// // Prints "United States"
|
||||
///
|
||||
/// Nil is returned if the scope is not available, or contains only
|
||||
/// null values.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support
|
||||
/// for more information.
|
||||
func decodeIfPresent<Record: FetchableRecord>(
|
||||
_ type: Record.Type = Record.self,
|
||||
forKey scope: String)
|
||||
throws -> Record?
|
||||
{
|
||||
guard let scopedRow = scopesTree[scope], scopedRow.containsNonNullValue else {
|
||||
return nil
|
||||
}
|
||||
return Record(row: scopedRow)
|
||||
}
|
||||
|
||||
/// Returns the record associated with the given scope.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let request = Book.including(required: Book.author)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
///
|
||||
/// let author: Author = row["author"]
|
||||
/// print(author.name)
|
||||
/// // Prints "Herman Melville"
|
||||
///
|
||||
/// Associated records stored in nested associations are available, too:
|
||||
///
|
||||
/// let request = Book.including(required: Book.author.including(required: Author.country))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
///
|
||||
/// let country: Country = row["country"]
|
||||
/// print(country.name)
|
||||
/// // Prints "United States"
|
||||
///
|
||||
/// A fatal error is raised if the scope is not available, or contains only
|
||||
/// null values.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support
|
||||
/// for more information.
|
||||
func decode<Record: FetchableRecord>(
|
||||
_ type: Record.Type = Record.self,
|
||||
forKey scope: String)
|
||||
throws -> Record
|
||||
{
|
||||
guard let scopedRow = scopesTree[scope] else {
|
||||
let availableScopes = scopesTree.names
|
||||
if availableScopes.isEmpty {
|
||||
throw RowDecodingError.keyNotFound(
|
||||
.scope(scope),
|
||||
RowDecodingError.Context(
|
||||
decodingContext: RowDecodingContext(row: self),
|
||||
debugDescription: """
|
||||
scope not found: \(String(reflecting: scope))
|
||||
"""))
|
||||
} else {
|
||||
throw RowDecodingError.keyNotFound(
|
||||
.scope(scope),
|
||||
RowDecodingError.Context(
|
||||
decodingContext: RowDecodingContext(row: self),
|
||||
debugDescription: """
|
||||
scope not found: \(String(reflecting: scope)) - \
|
||||
available scopes: \(availableScopes.sorted())
|
||||
"""))
|
||||
}
|
||||
}
|
||||
guard scopedRow.containsNonNullValue else {
|
||||
throw RowDecodingError.valueMismatch(
|
||||
Record.self,
|
||||
RowDecodingError.Context(
|
||||
decodingContext: RowDecodingContext(row: self, key: .scope(scope)),
|
||||
debugDescription: """
|
||||
scope \(String(reflecting: scope)) only contains null values
|
||||
"""))
|
||||
}
|
||||
return Record(row: scopedRow)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Throwing Record RangeReplaceableCollection and Set Methods
|
||||
|
||||
extension Row {
|
||||
/// Returns the records encoded in the given prefetched rows.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// print(Author(row: row).name)
|
||||
/// // Prints "Herman Melville"
|
||||
///
|
||||
/// let books: [Book] = row["books"]
|
||||
/// print(books[0].title)
|
||||
/// // Prints "Moby-Dick"
|
||||
func decode<Collection>(
|
||||
_ type: Collection.Type = Collection.self,
|
||||
forKey key: String)
|
||||
throws -> Collection
|
||||
where
|
||||
Collection: RangeReplaceableCollection,
|
||||
Collection.Element: FetchableRecord
|
||||
{
|
||||
guard let rows = prefetchedRows[key] else {
|
||||
let availableKeys = prefetchedRows.keys
|
||||
if availableKeys.isEmpty {
|
||||
throw RowDecodingError.keyNotFound(
|
||||
.prefetchKey(key),
|
||||
RowDecodingError.Context(
|
||||
decodingContext: RowDecodingContext(row: self),
|
||||
debugDescription: """
|
||||
key for prefetched rows not found: \(String(reflecting: key))
|
||||
"""))
|
||||
} else {
|
||||
throw RowDecodingError.keyNotFound(
|
||||
.prefetchKey(key),
|
||||
RowDecodingError.Context(
|
||||
decodingContext: RowDecodingContext(row: self),
|
||||
debugDescription: """
|
||||
key for prefetched rows not found: \(String(reflecting: key)) \
|
||||
- available keys: \(availableKeys.sorted())
|
||||
"""))
|
||||
}
|
||||
}
|
||||
|
||||
var collection = Collection()
|
||||
collection.reserveCapacity(rows.count)
|
||||
for row in rows {
|
||||
collection.append(Collection.Element(row: row))
|
||||
}
|
||||
return collection
|
||||
}
|
||||
|
||||
/// Returns the set of records encoded in the given prefetched rows.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// print(Author(row: row).name)
|
||||
/// // Prints "Herman Melville"
|
||||
///
|
||||
/// let books: Set<Book> = row["books"]
|
||||
/// print(books.first!.title)
|
||||
/// // Prints "Moby-Dick"
|
||||
func decode<Record: FetchableRecord & Hashable>(
|
||||
_ type: Set<Record>.Type = Set<Record>.self,
|
||||
forKey key: String)
|
||||
throws -> Set<Record>
|
||||
{
|
||||
guard let rows = prefetchedRows[key] else {
|
||||
let availableKeys = prefetchedRows.keys
|
||||
if availableKeys.isEmpty {
|
||||
throw RowDecodingError.keyNotFound(
|
||||
.prefetchKey(key),
|
||||
RowDecodingError.Context(
|
||||
decodingContext: RowDecodingContext(row: self),
|
||||
debugDescription: """
|
||||
key for prefetched rows not found: \(String(reflecting: key))
|
||||
"""))
|
||||
} else {
|
||||
throw RowDecodingError.keyNotFound(
|
||||
.prefetchKey(key),
|
||||
RowDecodingError.Context(
|
||||
decodingContext: RowDecodingContext(row: self),
|
||||
debugDescription: """
|
||||
key for prefetched rows not found: \(String(reflecting: key)) \
|
||||
- available keys: \(availableKeys.sorted())
|
||||
"""))
|
||||
}
|
||||
}
|
||||
var set = Set<Record>(minimumCapacity: rows.count)
|
||||
for row in rows {
|
||||
set.insert(Record(row: row))
|
||||
}
|
||||
return set
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - RowCursor
|
||||
|
||||
/// A cursor of database rows. For example:
|
||||
@@ -1218,8 +1638,7 @@ extension Row {
|
||||
|
||||
/// Accesses the (ColumnName, DatabaseValue) pair at given index.
|
||||
public subscript(position: RowIndex) -> (String, DatabaseValue) {
|
||||
let index = position.index
|
||||
_checkIndex(index)
|
||||
let index = checkedIndex(position.index)
|
||||
return (
|
||||
impl.columnName(atUncheckedIndex: index),
|
||||
impl.databaseValue(atUncheckedIndex: index))
|
||||
@@ -1647,15 +2066,20 @@ protocol RowImpl {
|
||||
func columnName(atUncheckedIndex index: Int) -> String
|
||||
func hasNull(atUncheckedIndex index: Int) -> Bool
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue
|
||||
|
||||
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int)
|
||||
-> Value
|
||||
throws -> Value
|
||||
|
||||
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int)
|
||||
-> Value?
|
||||
func dataNoCopy(atUncheckedIndex index: Int) -> Data?
|
||||
throws -> Value?
|
||||
|
||||
func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data
|
||||
|
||||
func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data?
|
||||
|
||||
/// Returns the index of the leftmost column that matches *name* (case-insensitive)
|
||||
func index(forColumn name: String) -> Int?
|
||||
@@ -1694,29 +2118,38 @@ extension RowImpl {
|
||||
|
||||
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int) -> Value
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Value
|
||||
{
|
||||
// unless customized, use slow decoding (see StatementRowImpl and AdaptedRowImpl for customization)
|
||||
return Value.decode(
|
||||
from: databaseValue(atUncheckedIndex: index),
|
||||
conversionContext: ValueConversionContext(Row(impl: self)).atColumn(index))
|
||||
return try Value.decode(
|
||||
fromDatabaseValue: databaseValue(atUncheckedIndex: index),
|
||||
context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index)))
|
||||
}
|
||||
|
||||
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int) -> Value?
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Value?
|
||||
{
|
||||
// unless customized, use slow decoding (see StatementRowImpl and AdaptedRowImpl for customization)
|
||||
return Value.decodeIfPresent(
|
||||
from: databaseValue(atUncheckedIndex: index),
|
||||
conversionContext: ValueConversionContext(Row(impl: self)).atColumn(index))
|
||||
return try Value.decodeIfPresent(
|
||||
fromDatabaseValue: databaseValue(atUncheckedIndex: index),
|
||||
context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index)))
|
||||
}
|
||||
|
||||
func dataNoCopy(atUncheckedIndex index: Int) -> Data? {
|
||||
func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data {
|
||||
// unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization)
|
||||
return Data.decodeIfPresent(
|
||||
from: databaseValue(atUncheckedIndex: index),
|
||||
conversionContext: ValueConversionContext(Row(impl: self)).atColumn(index))
|
||||
return try Data.decode(
|
||||
fromDatabaseValue: databaseValue(atUncheckedIndex: index),
|
||||
context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index)))
|
||||
}
|
||||
|
||||
func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? {
|
||||
// unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization)
|
||||
return try Data.decodeIfPresent(
|
||||
fromDatabaseValue: databaseValue(atUncheckedIndex: index),
|
||||
context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1820,9 +2253,35 @@ private struct StatementRowImpl: RowImpl {
|
||||
return sqlite3_column_type(sqliteStatement, Int32(index)) == SQLITE_NULL
|
||||
}
|
||||
|
||||
func dataNoCopy(atUncheckedIndex index: Int) -> Data? {
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
|
||||
DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
}
|
||||
|
||||
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Value
|
||||
{
|
||||
try Value.fastDecode(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
context: RowDecodingContext(statement: statement, index: index))
|
||||
}
|
||||
|
||||
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Value?
|
||||
{
|
||||
try Value.fastDecodeIfPresent(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
context: RowDecodingContext(statement: statement, index: index))
|
||||
}
|
||||
|
||||
func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data {
|
||||
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
|
||||
return nil
|
||||
throw RowDecodingError.valueMismatch(Data.self, statement: statement, index: index)
|
||||
}
|
||||
guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else {
|
||||
return Data()
|
||||
@@ -1831,22 +2290,15 @@ private struct StatementRowImpl: RowImpl {
|
||||
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
|
||||
}
|
||||
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
|
||||
DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
}
|
||||
|
||||
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int) -> Value
|
||||
{
|
||||
Value.fastDecode(from: sqliteStatement, atUncheckedIndex: Int32(index))
|
||||
}
|
||||
|
||||
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int) -> Value?
|
||||
{
|
||||
Value.fastDecodeIfPresent(from: sqliteStatement, atUncheckedIndex: Int32(index))
|
||||
func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? {
|
||||
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
|
||||
return nil
|
||||
}
|
||||
guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else {
|
||||
return Data()
|
||||
}
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
|
||||
}
|
||||
|
||||
func columnName(atUncheckedIndex index: Int) -> String {
|
||||
@@ -1879,17 +2331,6 @@ private struct SQLiteStatementRowImpl: RowImpl {
|
||||
DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
}
|
||||
|
||||
func dataNoCopy(atUncheckedIndex index: Int) -> Data? {
|
||||
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
|
||||
return nil
|
||||
}
|
||||
guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else {
|
||||
return Data()
|
||||
}
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
|
||||
}
|
||||
|
||||
func index(forColumn name: String) -> Int? {
|
||||
let name = name.lowercased()
|
||||
for index in 0..<count where columnName(atUncheckedIndex: index).lowercased() == name {
|
||||
|
||||
@@ -494,23 +494,30 @@ struct AdaptedRowImpl: RowImpl {
|
||||
|
||||
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int) -> Value
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Value
|
||||
{
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return Value.fastDecode(from: base, atUncheckedIndex: mappedIndex)
|
||||
return try Value.fastDecode(fromRow: base, atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int) -> Value?
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Value?
|
||||
{
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return Value.fastDecodeIfPresent(from: base, atUncheckedIndex: mappedIndex)
|
||||
return try Value.fastDecodeIfPresent(fromRow: base, atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func dataNoCopy(atUncheckedIndex index: Int) -> Data? {
|
||||
func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data {
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return base.impl.dataNoCopy(atUncheckedIndex: mappedIndex)
|
||||
return try base.impl.fastDecodeDataNoCopy(atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? {
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return try base.impl.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func columnName(atUncheckedIndex index: Int) -> String {
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
/// A key that is used to decode a value in a row
|
||||
@usableFromInline
|
||||
enum RowKey: Hashable {
|
||||
/// A column name
|
||||
case columnName(String)
|
||||
|
||||
/// A column index
|
||||
case columnIndex(Int)
|
||||
|
||||
/// A scope
|
||||
case scope(String)
|
||||
|
||||
/// A key of prefetched rows
|
||||
case prefetchKey(String)
|
||||
}
|
||||
|
||||
/// A decoding error
|
||||
@usableFromInline
|
||||
enum RowDecodingError: Error {
|
||||
@usableFromInline
|
||||
struct Context: CustomDebugStringConvertible {
|
||||
/// A description of what went wrong, for debugging purposes.
|
||||
@usableFromInline
|
||||
let debugDescription: String
|
||||
|
||||
/// The row that could not be decoded
|
||||
let row: Row
|
||||
|
||||
/// Nil for RowDecodingError.keyNotFound, in order to avoid redundancy
|
||||
let key: RowKey?
|
||||
|
||||
/// The SQL query
|
||||
let sql: String?
|
||||
|
||||
/// The SQL query arguments
|
||||
let statementArguments: StatementArguments?
|
||||
|
||||
@usableFromInline
|
||||
init(decodingContext: RowDecodingContext, debugDescription: String) {
|
||||
self.debugDescription = debugDescription
|
||||
self.row = decodingContext.row
|
||||
self.key = decodingContext.key
|
||||
self.sql = decodingContext.sql
|
||||
self.statementArguments = decodingContext.statementArguments
|
||||
}
|
||||
}
|
||||
|
||||
case keyNotFound(RowKey, Context)
|
||||
case valueMismatch(Any.Type, Context)
|
||||
|
||||
var context: Context {
|
||||
switch self {
|
||||
case .keyNotFound(_, let context),
|
||||
.valueMismatch(_, let context):
|
||||
return context
|
||||
}
|
||||
}
|
||||
|
||||
/// Convenience method that builds the
|
||||
/// `could not decode <Type> from database value <value>` error message.
|
||||
static func valueMismatch(
|
||||
_ type: Any.Type,
|
||||
context: RowDecodingContext,
|
||||
databaseValue: DatabaseValue)
|
||||
-> Self
|
||||
{
|
||||
valueMismatch(
|
||||
type,
|
||||
RowDecodingError.Context(decodingContext: context, debugDescription: """
|
||||
could not decode \(type) from database value \(databaseValue)
|
||||
"""))
|
||||
}
|
||||
|
||||
/// Convenience method that builds the
|
||||
/// `could not decode <Type> from database value <value>` error message.
|
||||
@usableFromInline
|
||||
static func valueMismatch(
|
||||
_ type: Any.Type,
|
||||
sqliteStatement: SQLiteStatement,
|
||||
index: Int32,
|
||||
context: RowDecodingContext)
|
||||
-> Self
|
||||
{
|
||||
valueMismatch(
|
||||
type,
|
||||
context: context,
|
||||
databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index))
|
||||
}
|
||||
|
||||
/// Convenience method that builds the
|
||||
/// `could not decode <Type> from database value <value>` error message.
|
||||
@usableFromInline
|
||||
static func valueMismatch(
|
||||
_ type: Any.Type,
|
||||
statement: SelectStatement,
|
||||
index: Int)
|
||||
-> Self
|
||||
{
|
||||
valueMismatch(
|
||||
type,
|
||||
context: RowDecodingContext(statement: statement, index: index),
|
||||
databaseValue: DatabaseValue(sqliteStatement: statement.sqliteStatement, index: Int32(index)))
|
||||
}
|
||||
|
||||
/// Convenience method that builds the `column not found: <column>`
|
||||
/// error message.
|
||||
@usableFromInline
|
||||
static func columnNotFound(_ columnName: String, context: RowDecodingContext) -> Self {
|
||||
keyNotFound(
|
||||
.columnName(columnName),
|
||||
RowDecodingError.Context(decodingContext: context, debugDescription: """
|
||||
column not found: \(String(reflecting: columnName))
|
||||
"""))
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
struct RowDecodingContext {
|
||||
/// The row that is decoded
|
||||
let row: Row
|
||||
|
||||
let key: RowKey?
|
||||
|
||||
/// The SQL query
|
||||
let sql: String?
|
||||
|
||||
/// The SQL query arguments
|
||||
let statementArguments: StatementArguments?
|
||||
|
||||
@usableFromInline
|
||||
init(row: Row, key: RowKey? = nil) {
|
||||
if let statement = row.statement {
|
||||
self.key = key
|
||||
self.row = row.copy()
|
||||
self.sql = statement.sql
|
||||
self.statementArguments = statement.arguments
|
||||
} else if let sqliteStatement = row.sqliteStatement {
|
||||
self.key = key
|
||||
self.row = row.copy()
|
||||
self.sql = String(cString: sqlite3_sql(sqliteStatement)).trimmingCharacters(in: .sqlStatementSeparators)
|
||||
self.statementArguments = nil // Can't rebuild them
|
||||
} else {
|
||||
self.key = key
|
||||
self.row = row.copy()
|
||||
self.sql = nil
|
||||
self.statementArguments = nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Convenience initializer
|
||||
@usableFromInline
|
||||
init(statement: SelectStatement, index: Int) {
|
||||
self.key = .columnIndex(index)
|
||||
self.row = Row(copiedFromSQLiteStatement: statement.sqliteStatement, statement: statement)
|
||||
self.sql = statement.sql
|
||||
self.statementArguments = statement.arguments
|
||||
}
|
||||
}
|
||||
|
||||
extension RowDecodingError: CustomStringConvertible {
|
||||
@usableFromInline
|
||||
var description: String {
|
||||
let context = self.context
|
||||
let row = context.row
|
||||
var chunks: [String] = []
|
||||
|
||||
if let key = context.key {
|
||||
switch key {
|
||||
case let .columnIndex(columnIndex):
|
||||
let rowIndex = row.index(row.startIndex, offsetBy: columnIndex)
|
||||
let columnName = row.columnNames[rowIndex]
|
||||
chunks.append("column: \(String(reflecting: columnName))")
|
||||
chunks.append("column index: \(columnIndex)")
|
||||
|
||||
case let .columnName(columnName):
|
||||
if let columnIndex = row.index(forColumn: columnName) {
|
||||
chunks.append("column: \(String(reflecting: columnName))")
|
||||
chunks.append("column index: \(columnIndex)")
|
||||
} else {
|
||||
// column name is already mentionned in context.debugDescription
|
||||
}
|
||||
|
||||
case .prefetchKey:
|
||||
// key is already mentionned in context.debugDescription
|
||||
break
|
||||
|
||||
case .scope:
|
||||
// scope is already mentionned in context.debugDescription
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
chunks.append("row: \(row.description)")
|
||||
|
||||
if let sql = context.sql {
|
||||
chunks.append("sql: `\(sql)`")
|
||||
}
|
||||
|
||||
if let statementArguments = context.statementArguments {
|
||||
chunks.append("arguments: \(statementArguments)")
|
||||
}
|
||||
|
||||
return "\(context.debugDescription) - \(chunks.joined(separator: ", "))"
|
||||
}
|
||||
}
|
||||
+22
-143
@@ -16,11 +16,11 @@ public struct SQLLiteral {
|
||||
// Can't be qualified with a table alias
|
||||
case sql(String, StatementArguments = StatementArguments())
|
||||
// Does not need to be qualified with a table alias
|
||||
case subquery(DatabasePromise<_FetchRequest>)
|
||||
case subquery(SQLSubquery)
|
||||
// Cases below can be qualified with a table alias
|
||||
case expression(SQLExpression)
|
||||
case selectable(SQLSelectable)
|
||||
case orderingTerm(SQLOrderingTerm)
|
||||
case selection(SQLSelection)
|
||||
case ordering(SQLOrdering)
|
||||
|
||||
var isEmpty: Bool {
|
||||
switch self {
|
||||
@@ -40,14 +40,14 @@ public struct SQLLiteral {
|
||||
fatalError("Not implemented: turning an SQL parameter into an SQL literal value")
|
||||
}
|
||||
return sql
|
||||
case let .subquery(requestPromise):
|
||||
return try requestPromise.resolve(context.db)._requestSQL(context, forSingleResult: false)
|
||||
case let .subquery(subquery):
|
||||
return try subquery.sql(context)
|
||||
case let .expression(expression):
|
||||
return try expression._expressionSQL(context, wrappedInParenthesis: false)
|
||||
case let .selectable(selectable):
|
||||
return try selectable._resultColumnSQL(context)
|
||||
case let .orderingTerm(orderingTerm):
|
||||
return try orderingTerm._orderingTermSQL(context)
|
||||
return try expression.sql(context)
|
||||
case let .selection(selection):
|
||||
return try selection.sql(context)
|
||||
case let .ordering(ordering):
|
||||
return try ordering.sql(context)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,11 +60,11 @@ public struct SQLLiteral {
|
||||
// Subqueries don't need table alias
|
||||
return self
|
||||
case let .expression(expression):
|
||||
return .expression(expression._qualifiedExpression(with: alias))
|
||||
case let .selectable(selectable):
|
||||
return .selectable(selectable._qualifiedSelectable(with: alias))
|
||||
case let .orderingTerm(orderingTerm):
|
||||
return .orderingTerm(orderingTerm._qualifiedOrdering(with: alias))
|
||||
return .expression(expression.qualified(with: alias))
|
||||
case let .selection(selection):
|
||||
return .selection(selection.qualified(with: alias))
|
||||
case let .ordering(ordering):
|
||||
return .ordering(ordering.qualified(with: alias))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -95,8 +95,8 @@ public struct SQLLiteral {
|
||||
/// let emailLiteral = [columnLiteral, suffixLiteral].joined(separator: " || ")
|
||||
/// let request = User.select(emailLiteral.sqlExpression)
|
||||
/// let emails = try String.fetchAll(db, request)
|
||||
public init(_ expression: SQLExpression) {
|
||||
self.init(elements: [.expression(expression)])
|
||||
public init(_ expression: SQLSpecificExpressible) {
|
||||
self.init(elements: [.expression(expression.sqlExpression)])
|
||||
}
|
||||
|
||||
/// Returns true if this literal generates an empty SQL string
|
||||
@@ -172,15 +172,15 @@ extension SQLLiteral {
|
||||
/// SQLLiteral(sql: "? + ?", arguments: [1, 2]).sqlExpression
|
||||
/// SQLLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]).sqlExpression
|
||||
public var sqlExpression: SQLExpression {
|
||||
SQLExpressionLiteral(sqlLiteral: self)
|
||||
.literal(self)
|
||||
}
|
||||
|
||||
var sqlSelectable: SQLSelectable {
|
||||
SQLSelectionLiteral(sqlLiteral: self)
|
||||
var sqlSelection: SQLSelection {
|
||||
.literal(self)
|
||||
}
|
||||
|
||||
var sqlOrderingTerm: SQLOrderingTerm {
|
||||
SQLOrderingLiteral(sqlLiteral: self)
|
||||
var sqlOrdering: SQLOrdering {
|
||||
.literal(self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,124 +245,3 @@ extension SQLLiteral: ExpressibleByStringInterpolation {
|
||||
self.init(elements: sqlInterpolation.elements)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionLiteral
|
||||
|
||||
// TODO: remove public qualifier when GRDB5 fixits are removed.
|
||||
/// `SQLExpressionLiteral` is an expression built from a raw SQL snippet.
|
||||
///
|
||||
/// To build one, use the `SQLiteral.sqlExpression` property:
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// let column = Column("name")
|
||||
/// let literal: SQLLiteral = "\(column) = \(name)"
|
||||
/// let expression = literal.sqlExpression
|
||||
///
|
||||
/// Such expressions can feed query interface requests:
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// // SELECT * FROM player WHERE name = 'O''Brien'
|
||||
/// let players = try Player
|
||||
/// .filter(expression)
|
||||
/// .fetchAll(db)
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // FROM player
|
||||
/// // JOIN team WHERE team.id = player.teamID
|
||||
/// // WHERE player.name = 'O''Brien'
|
||||
/// let players = try Player
|
||||
/// .including(required: Player.team)
|
||||
/// .filter(expression)
|
||||
/// .fetchAll(db)
|
||||
/// }
|
||||
///
|
||||
/// See SQLLiteral for more information.
|
||||
///
|
||||
/// :nodoc:
|
||||
public struct SQLExpressionLiteral: SQLExpression {
|
||||
let sqlLiteral: SQLLiteral
|
||||
|
||||
// Prefer SQLLiteral.sqlExpression
|
||||
fileprivate init(sqlLiteral: SQLLiteral) {
|
||||
self.sqlLiteral = sqlLiteral
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
var resultSQL = try sqlLiteral.sql(context)
|
||||
|
||||
if wrappedInParenthesis {
|
||||
resultSQL = "(\(resultSQL))"
|
||||
}
|
||||
|
||||
return resultSQL
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
sqlLiteral.qualified(with: alias).sqlExpression
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLSelectionLiteral
|
||||
|
||||
struct SQLSelectionLiteral: SQLSelectable {
|
||||
let sqlLiteral: SQLLiteral
|
||||
|
||||
// Prefer SQLLiteral.sqlSelectable
|
||||
fileprivate init(sqlLiteral: SQLLiteral) {
|
||||
self.sqlLiteral = sqlLiteral
|
||||
}
|
||||
|
||||
func _columnCount(_ db: Database) throws -> Int {
|
||||
fatalError("""
|
||||
Selection literals don't known how many columns they contain. \
|
||||
To resolve this error, select one or several literal expressions instead. \
|
||||
See SQLLiteral.sqlExpression.
|
||||
""")
|
||||
}
|
||||
|
||||
func _count(distinct: Bool) -> _SQLCount? { nil }
|
||||
|
||||
func _countedSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
fatalError("""
|
||||
Selection literals can't be counted. \
|
||||
To resolve this error, select one or several literal expressions instead. \
|
||||
See SQLLiteral.sqlExpression.
|
||||
""")
|
||||
}
|
||||
|
||||
func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable {
|
||||
sqlLiteral.qualified(with: alias).sqlSelectable
|
||||
}
|
||||
|
||||
func _resultColumnSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
try sqlLiteral.sql(context)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLOrderingLiteral
|
||||
|
||||
struct SQLOrderingLiteral: SQLOrderingTerm {
|
||||
let sqlLiteral: SQLLiteral
|
||||
|
||||
// Prefer SQLLiteral.sqlOrderingTerm
|
||||
fileprivate init(sqlLiteral: SQLLiteral) {
|
||||
self.sqlLiteral = sqlLiteral
|
||||
}
|
||||
|
||||
func _orderingTermSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
try sqlLiteral.sql(context)
|
||||
}
|
||||
|
||||
func _qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm {
|
||||
sqlLiteral.qualified(with: alias).sqlOrderingTerm
|
||||
}
|
||||
|
||||
var _reversed: SQLOrderingTerm {
|
||||
fatalError("""
|
||||
Ordering literals can't be reversed. \
|
||||
To resolve this error, order by expression literals instead.
|
||||
""")
|
||||
}
|
||||
}
|
||||
@@ -102,6 +102,10 @@ public struct SQLRequest<RowDecoder> {
|
||||
}
|
||||
|
||||
extension SQLRequest: FetchRequest {
|
||||
public var sqlSubquery: SQLSubquery {
|
||||
.literal(sqlLiteral)
|
||||
}
|
||||
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
try SQLRequest<Int>("SELECT COUNT(*) FROM (\(self))").fetchOne(db)!
|
||||
}
|
||||
@@ -125,21 +129,6 @@ extension SQLRequest: FetchRequest {
|
||||
try statement.setArguments(context.arguments)
|
||||
return PreparedRequest(statement: statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// :nodoc
|
||||
public func _selectedColumnCount(_ db: Database) throws -> Int {
|
||||
// Compile request. We can freely use the statement cache because we
|
||||
// do not execute the statement or modify its arguments.
|
||||
let context = SQLGenerationContext(db)
|
||||
let sql = try _requestSQL(context, forSingleResult: false)
|
||||
let statement = try db.cachedSelectStatement(sql: sql)
|
||||
return statement.columnCount
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
|
||||
try sqlLiteral.sql(context)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLRequest: ExpressibleByStringInterpolation {
|
||||
|
||||
@@ -244,7 +244,7 @@ public class Statement {
|
||||
// It looks like sqlite3_bind_xxx() functions do not access the file system.
|
||||
// They should thus succeed, unless a GRDB bug: there is no point throwing any error.
|
||||
guard code == SQLITE_OK else {
|
||||
fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql).description)
|
||||
fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -255,7 +255,7 @@ public class Statement {
|
||||
// no point throwing any error.
|
||||
let code = sqlite3_clear_bindings(sqliteStatement)
|
||||
guard code == SQLITE_OK else {
|
||||
fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql).description)
|
||||
fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,32 +18,107 @@
|
||||
/// score = row["score"] // there
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// `StatementColumnConvertible` is already adopted by all Swift integer types,
|
||||
/// `Float`, `Double`, `String`, and `Bool`.
|
||||
public protocol StatementColumnConvertible {
|
||||
|
||||
/// Initializes a value from a raw SQLite statement pointer.
|
||||
/// Initializes a value from a raw SQLite statement pointer, if possible.
|
||||
///
|
||||
/// For example, here is the how Int64 adopts StatementColumnConvertible:
|
||||
///
|
||||
/// extension Int64: StatementColumnConvertible {
|
||||
/// init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
/// init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
/// self = sqlite3_column_int64(sqliteStatement, index)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// This initializer is never called for NULL database values: don't perform
|
||||
/// any extra check.
|
||||
/// This initializer is never called for NULL database values. Just return
|
||||
/// `nil` for failed conversions: GRDB will interpret a nil result as a
|
||||
/// decoding failure.
|
||||
///
|
||||
/// See https://www.sqlite.org/c3ref/column_blob.html for more information.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
init(sqliteStatement: SQLiteStatement, index: Int32)
|
||||
init?(sqliteStatement: SQLiteStatement, index: Int32)
|
||||
}
|
||||
|
||||
// MARK: - Conversions
|
||||
|
||||
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
@inlinable
|
||||
static func fastDecode(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: Int32,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Self
|
||||
{
|
||||
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL,
|
||||
let value = self.init(sqliteStatement: sqliteStatement, index: index)
|
||||
else {
|
||||
throw RowDecodingError.valueMismatch(
|
||||
Self.self,
|
||||
sqliteStatement: sqliteStatement,
|
||||
index: index,
|
||||
context: context())
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func fastDecode(
|
||||
fromRow row: Row,
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Self
|
||||
{
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return try fastDecode(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
// Support for fast decoding from adapted rows
|
||||
return try row.fastDecode(Self.self, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func fastDecodeIfPresent(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: Int32,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Self?
|
||||
{
|
||||
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
|
||||
return nil
|
||||
}
|
||||
guard let value = self.init(sqliteStatement: sqliteStatement, index: index) else {
|
||||
throw RowDecodingError.valueMismatch(
|
||||
Self.self,
|
||||
sqliteStatement: sqliteStatement,
|
||||
index: index,
|
||||
context: context())
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func fastDecodeIfPresent(
|
||||
fromRow row: Row,
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Self?
|
||||
{
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return try fastDecodeIfPresent(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
// Support for fast decoding from adapted rows
|
||||
return try row.fastDecodeIfPresent(Self.self, atUncheckedIndex: index)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Cursors
|
||||
|
||||
/// A cursor of database values extracted from a single column.
|
||||
/// For example:
|
||||
///
|
||||
@@ -92,7 +167,11 @@ public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & Sta
|
||||
_done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return Value.fastDecode(from: _sqliteStatement, atUncheckedIndex: _columnIndex)
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
return try! Value.fastDecode(
|
||||
fromStatement: _sqliteStatement,
|
||||
atUncheckedIndex: _columnIndex,
|
||||
context: RowDecodingContext(statement: _statement, index: Int(_columnIndex)))
|
||||
case let code:
|
||||
try _statement.didFail(withResultCode: code)
|
||||
}
|
||||
@@ -150,7 +229,11 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
_done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return Value.fastDecodeIfPresent(from: _sqliteStatement, atUncheckedIndex: _columnIndex)
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
return try! Value.fastDecodeIfPresent(
|
||||
fromStatement: _sqliteStatement,
|
||||
atUncheckedIndex: _columnIndex,
|
||||
context: RowDecodingContext(statement: _statement, index: Int(_columnIndex)))
|
||||
case let code:
|
||||
try _statement.didFail(withResultCode: code)
|
||||
}
|
||||
@@ -164,7 +247,6 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
/// See DatabaseValueConvertible for more information.
|
||||
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
|
||||
// MARK: Fetching From SelectStatement
|
||||
|
||||
/// Returns a cursor over values fetched from a prepared statement.
|
||||
|
||||
@@ -32,3 +32,77 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Conversions
|
||||
|
||||
extension Data {
|
||||
@inlinable
|
||||
static func fastDecodeNoCopy(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: Int32,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Data
|
||||
{
|
||||
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
|
||||
throw RowDecodingError.valueMismatch(
|
||||
Data.self,
|
||||
sqliteStatement: sqliteStatement,
|
||||
index: index,
|
||||
context: context())
|
||||
}
|
||||
guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else {
|
||||
return Data()
|
||||
}
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func fastDecodeNoCopy(
|
||||
fromRow row: Row,
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Data
|
||||
{
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return try fastDecodeNoCopy(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
// Support for fast decoding from adapted rows
|
||||
return try row.fastDecodeDataNoCopy(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func fastDecodeNoCopyIfPresent(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: Int32,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
-> Data?
|
||||
{
|
||||
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
|
||||
return nil
|
||||
}
|
||||
guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else {
|
||||
return Data()
|
||||
}
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func fastDecodeNoCopyIfPresent(
|
||||
fromRow row: Row,
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Data?
|
||||
{
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return fastDecodeNoCopyIfPresent(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
// Support for fast decoding from adapted rows
|
||||
return try row.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: index)
|
||||
}
|
||||
}
|
||||
@@ -69,9 +69,9 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
guard let cString = sqlite3_column_text(sqliteStatement, index) else {
|
||||
fatalConversionError(to: DatabaseDateComponents.self, sqliteStatement: sqliteStatement, index: index)
|
||||
return nil
|
||||
}
|
||||
let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen
|
||||
let optionalComponents = cString.withMemoryRebound(
|
||||
@@ -80,7 +80,7 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC
|
||||
SQLiteDateParser().components(cString: cString, length: length)
|
||||
}
|
||||
guard let components = optionalComponents else {
|
||||
fatalConversionError(to: DatabaseDateComponents.self, sqliteStatement: sqliteStatement, index: index)
|
||||
return nil
|
||||
}
|
||||
self.dateComponents = components.dateComponents
|
||||
self.format = components.format
|
||||
|
||||
@@ -119,18 +119,19 @@ extension Date: StatementColumnConvertible {
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_INTEGER, SQLITE_FLOAT:
|
||||
self.init(timeIntervalSince1970: sqlite3_column_double(sqliteStatement, index))
|
||||
case SQLITE_TEXT:
|
||||
let databaseDateComponents = DatabaseDateComponents(sqliteStatement: sqliteStatement, index: index)
|
||||
guard let date = Date(databaseDateComponents: databaseDateComponents) else {
|
||||
fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index)
|
||||
guard let components = DatabaseDateComponents(sqliteStatement: sqliteStatement, index: index),
|
||||
let date = Date(databaseDateComponents: components)
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate)
|
||||
default:
|
||||
fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,23 +50,23 @@ extension UUID: DatabaseValueConvertible {
|
||||
|
||||
extension UUID: StatementColumnConvertible {
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_TEXT:
|
||||
let string = String(cString: sqlite3_column_text(sqliteStatement, index)!)
|
||||
guard let uuid = UUID(uuidString: string) else {
|
||||
fatalConversionError(to: UUID.self, sqliteStatement: sqliteStatement, index: index)
|
||||
return nil
|
||||
}
|
||||
self.init(uuid: uuid.uuid)
|
||||
case SQLITE_BLOB:
|
||||
guard sqlite3_column_bytes(sqliteStatement, index) == 16,
|
||||
let blob = sqlite3_column_blob(sqliteStatement, index) else
|
||||
{
|
||||
fatalConversionError(to: UUID.self, sqliteStatement: sqliteStatement, index: index)
|
||||
return nil
|
||||
}
|
||||
self.init(uuid: blob.assumingMemoryBound(to: uuid_t.self).pointee)
|
||||
default:
|
||||
fatalConversionError(to: UUID.self, sqliteStatement: sqliteStatement, index: index)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,15 @@
|
||||
/// SQLExpressible is free for RawRepresentable types whose raw value
|
||||
/// is itself SQLExpressible.
|
||||
///
|
||||
/// // If the RawValue adopts SQLExpressible...
|
||||
/// enum Color : Int {
|
||||
/// case red
|
||||
/// case white
|
||||
/// case rose
|
||||
/// }
|
||||
///
|
||||
/// // ... then the RawRepresentable type can freely adopt SQLExpressible:
|
||||
/// extension Color : SQLExpressible { /* empty */ }
|
||||
extension SQLSelectable where Self: RawRepresentable, Self.RawValue: SQLSelectable {
|
||||
public var sqlSelection: SQLSelection {
|
||||
rawValue.sqlSelection
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLOrderingTerm where Self: RawRepresentable, Self.RawValue: SQLOrderingTerm {
|
||||
public var sqlOrdering: SQLOrdering {
|
||||
rawValue.sqlOrdering
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLExpressible where Self: RawRepresentable, Self.RawValue: SQLExpressible {
|
||||
/// Returns the raw value as an SQL expression.
|
||||
public var sqlExpression: SQLExpression {
|
||||
@@ -17,8 +17,8 @@ extension SQLExpressible where Self: RawRepresentable, Self.RawValue: SQLExpress
|
||||
}
|
||||
}
|
||||
|
||||
/// DatabaseValueConvertible is free for RawRepresentable types whose raw value
|
||||
/// is itself DatabaseValueConvertible.
|
||||
/// `DatabaseValueConvertible` is free for `RawRepresentable` types whose raw
|
||||
/// value is itself `DatabaseValueConvertible`.
|
||||
///
|
||||
/// // If the RawValue adopts DatabaseValueConvertible...
|
||||
/// enum Color : Int {
|
||||
@@ -27,16 +27,14 @@ extension SQLExpressible where Self: RawRepresentable, Self.RawValue: SQLExpress
|
||||
/// case rose
|
||||
/// }
|
||||
///
|
||||
/// // ... then the RawRepresentable type can freely adopt DatabaseValueConvertible:
|
||||
/// extension Color : DatabaseValueConvertible { /* empty */ }
|
||||
/// // ... then the RawRepresentable type can freely
|
||||
/// // adopt DatabaseValueConvertible:
|
||||
/// extension Color: DatabaseValueConvertible { }
|
||||
extension DatabaseValueConvertible where Self: RawRepresentable, Self.RawValue: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
rawValue.databaseValue
|
||||
}
|
||||
|
||||
/// Returns a value initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
RawValue.fromDatabaseValue(dbValue).flatMap { self.init(rawValue: $0) }
|
||||
}
|
||||
|
||||
@@ -96,13 +96,10 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = Int(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalConversionError(to: Int.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
guard let v = Int(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@@ -125,13 +122,10 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = Int8(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalConversionError(to: Int8.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
guard let v = Int8(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@@ -154,13 +148,10 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = Int16(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalConversionError(to: Int16.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
guard let v = Int16(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@@ -183,13 +174,10 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = Int32(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalConversionError(to: Int32.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
guard let v = Int32(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@@ -245,13 +233,10 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = UInt(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalConversionError(to: UInt.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
guard let v = UInt(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@@ -274,13 +259,10 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = UInt8(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalConversionError(to: UInt8.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
guard let v = UInt8(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@@ -303,13 +285,10 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = UInt16(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalConversionError(to: UInt16.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
guard let v = UInt16(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@@ -332,13 +311,10 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = UInt32(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalConversionError(to: UInt32.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
guard let v = UInt32(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@@ -361,13 +337,10 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = UInt64(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalConversionError(to: UInt64.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
guard let v = UInt64(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
|
||||
@@ -161,7 +161,7 @@ extension Database {
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError(DatabaseError(resultCode: code, message: lastErrorMessage).description)
|
||||
fatalError(DatabaseError(resultCode: code, message: lastErrorMessage))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,7 +195,10 @@ extension FilteredRequest {
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
extension SQLExpressionLiteral {
|
||||
@available(*, unavailable, message: "Build literal expressions with SQLLiteral.sqlExpression instead.")
|
||||
struct SQLExpressionLiteral: SQLSpecificExpressible {
|
||||
var sqlExpression: SQLExpression { preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "Build literal expressions with SQLLiteral.sqlExpression instead.")
|
||||
public var sql: String { preconditionFailure() }
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ extension TableRequest where Self: FilteredRequest {
|
||||
return none()
|
||||
}
|
||||
let alias = TableAlias()
|
||||
let matchExpression = SQLExpressionTableMatch(alias: alias, pattern: pattern.databaseValue)
|
||||
let matchExpression = SQLExpression.tableMatch(alias, pattern.sqlExpression)
|
||||
return self.aliased(alias).filter(matchExpression)
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,6 @@ extension ColumnExpression {
|
||||
/// If the search pattern is nil, SQLite will evaluate the expression
|
||||
/// to false.
|
||||
public func match(_ pattern: FTS3Pattern?) -> SQLExpression {
|
||||
SQLExpressionBinary(.match, self, pattern ?? DatabaseValue.null)
|
||||
.binary(.match, sqlExpression, pattern?.sqlExpression ?? .null)
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ extension TableRequest where Self: FilteredRequest {
|
||||
return none()
|
||||
}
|
||||
let alias = TableAlias()
|
||||
let matchExpression = SQLExpressionTableMatch(alias: alias, pattern: pattern.databaseValue)
|
||||
let matchExpression = SQLExpression.tableMatch(alias, pattern.sqlExpression)
|
||||
return self.aliased(alias).filter(matchExpression)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
/// A ForeignKey helps building associations when GRDB can't infer a foreign
|
||||
/// key from the database schema.
|
||||
///
|
||||
/// Sometimes the database schema does not define any foreign key between two
|
||||
/// tables. And sometimes, there are several foreign keys from a table
|
||||
/// to another:
|
||||
///
|
||||
/// | Table book | | Table person |
|
||||
/// | ------------ | | ------------ |
|
||||
/// | id | +-->• id |
|
||||
/// | authorId •---+ | name |
|
||||
/// | translatorId •---+
|
||||
/// | title |
|
||||
///
|
||||
/// When this happens, associations can't be automatically inferred from the
|
||||
/// database schema. GRDB will complain with a fatal error such as "Ambiguous
|
||||
/// foreign key from book to person", or "Could not infer foreign key from book
|
||||
/// to person".
|
||||
///
|
||||
/// Your help is needed. You have to instruct GRDB which foreign key to use:
|
||||
///
|
||||
/// struct Book: TableRecord {
|
||||
/// // Define foreign keys
|
||||
/// static let authorForeignKey = ForeignKey(["authorId"]))
|
||||
/// static let translatorForeignKey = ForeignKey(["translatorId"]))
|
||||
///
|
||||
/// // Use foreign keys to define associations:
|
||||
/// static let author = belongsTo(Person.self, using: authorForeignKey)
|
||||
/// static let translator = belongsTo(Person.self, using: translatorForeignKey)
|
||||
/// }
|
||||
///
|
||||
/// Foreign keys are always defined from the table that contains the columns at
|
||||
/// the origin of the foreign key. Person's symmetric HasMany associations reuse
|
||||
/// Book's foreign keys:
|
||||
///
|
||||
/// struct Person: TableRecord {
|
||||
/// static let writtenBooks = hasMany(Book.self, using: Book.authorForeignKey)
|
||||
/// static let translatedBooks = hasMany(Book.self, using: Book.translatorForeignKey)
|
||||
/// }
|
||||
///
|
||||
/// Foreign keys can also be defined from query interface columns:
|
||||
///
|
||||
/// struct Book: TableRecord {
|
||||
/// enum Columns: String, ColumnExpression {
|
||||
/// case id, title, authorId, translatorId
|
||||
/// }
|
||||
///
|
||||
/// static let authorForeignKey = ForeignKey([Columns.authorId]))
|
||||
/// static let translatorForeignKey = ForeignKey([Columns.translatorId]))
|
||||
/// }
|
||||
///
|
||||
/// When the destination table of a foreign key does not define any primary key,
|
||||
/// you need to provide the full definition of a foreign key:
|
||||
///
|
||||
/// struct Book: TableRecord {
|
||||
/// static let authorForeignKey = ForeignKey(["authorId"], to: ["id"]))
|
||||
/// static let author = belongsTo(Person.self, using: authorForeignKey)
|
||||
/// }
|
||||
public struct ForeignKey: Equatable {
|
||||
var originColumns: [String]
|
||||
var destinationColumns: [String]?
|
||||
|
||||
/// Creates a ForeignKey intended to define a record association.
|
||||
///
|
||||
/// struct Book: TableRecord {
|
||||
/// // Define foreign keys
|
||||
/// static let authorForeignKey = ForeignKey(["authorId"]))
|
||||
/// static let translatorForeignKey = ForeignKey(["translatorId"]))
|
||||
///
|
||||
/// // Use foreign keys to define associations:
|
||||
/// static let author = belongsTo(Person.self, using: authorForeignKey)
|
||||
/// static let translator = belongsTo(Person.self, using: translatorForeignKey)
|
||||
/// }
|
||||
///
|
||||
/// - parameter originColumns: The columns at the origin of the foreign key.
|
||||
/// - parameter destinationColumns: The columns at the destination of the
|
||||
/// foreign key. When nil (the default), GRDB automatically uses the
|
||||
/// primary key.
|
||||
public init(_ originColumns: [String], to destinationColumns: [String]? = nil) {
|
||||
self.originColumns = originColumns
|
||||
self.destinationColumns = destinationColumns
|
||||
}
|
||||
|
||||
/// Creates a ForeignKey intended to define a record association.
|
||||
///
|
||||
/// struct Book: TableRecord {
|
||||
/// // Define columns
|
||||
/// enum Columns: String, ColumnExpression {
|
||||
/// case id, title, authorId, translatorId
|
||||
/// }
|
||||
///
|
||||
/// // Define foreign keys
|
||||
/// static let authorForeignKey = ForeignKey([Columns.authorId]))
|
||||
/// static let translatorForeignKey = ForeignKey([Columns.translatorId]))
|
||||
///
|
||||
/// // Use foreign keys to define associations:
|
||||
/// static let author = belongsTo(Person.self, using: authorForeignKey)
|
||||
/// static let translator = belongsTo(Person.self, using: translatorForeignKey)
|
||||
/// }
|
||||
///
|
||||
/// - parameter originColumns: The columns at the origin of the foreign key.
|
||||
/// - parameter destinationColumns: The columns at the destination of the
|
||||
/// foreign key. When nil (the default), GRDB automatically uses the
|
||||
/// primary key.
|
||||
public init(_ originColumns: [ColumnExpression], to destinationColumns: [ColumnExpression]? = nil) {
|
||||
self.init(originColumns.map(\.name), to: destinationColumns?.map(\.name))
|
||||
}
|
||||
}
|
||||
@@ -127,7 +127,7 @@ extension Association {
|
||||
/// .select { db in [Column("color") }
|
||||
/// var request = Player.including(required: association)
|
||||
public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
|
||||
mapDestinationRelation { $0.select(selection) }
|
||||
mapDestinationRelation { $0.select { try selection($0).map(\.sqlSelection) } }
|
||||
}
|
||||
|
||||
/// Creates an association which appends *selection*.
|
||||
@@ -144,7 +144,7 @@ extension Association {
|
||||
/// .annotated(with: { db in [Column("name")] })
|
||||
/// var request = Player.including(required: association)
|
||||
public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
|
||||
mapDestinationRelation { $0.annotated(with: selection) }
|
||||
mapDestinationRelation { $0.annotated { try selection($0).map(\.sqlSelection) } }
|
||||
}
|
||||
|
||||
/// Creates an association with the provided *predicate promise* added to
|
||||
@@ -160,7 +160,7 @@ extension Association {
|
||||
/// let association = Player.team.filter { db in true }
|
||||
/// var request = Player.including(required: association)
|
||||
public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self {
|
||||
mapDestinationRelation { $0.filter(predicate) }
|
||||
mapDestinationRelation { $0.filter { try predicate($0).sqlExpression } }
|
||||
}
|
||||
|
||||
/// Creates an association with the provided *orderings promise*.
|
||||
@@ -188,7 +188,7 @@ extension Association {
|
||||
/// .order{ _ in [Column("name")] }
|
||||
/// var request = Player.including(required: association)
|
||||
public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self {
|
||||
mapDestinationRelation { $0.order(orderings) }
|
||||
mapDestinationRelation { $0.order { try orderings($0).map(\.sqlOrdering) } }
|
||||
}
|
||||
|
||||
/// Creates an association that reverses applied orderings.
|
||||
@@ -285,7 +285,7 @@ extension Association {
|
||||
/// .including(required: Player.team.aliased(teamAlias))
|
||||
/// .filter(sql: "custom.color = ?", arguments: ["red"])
|
||||
public func aliased(_ alias: TableAlias) -> Self {
|
||||
mapDestinationRelation { $0.qualified(with: alias) }
|
||||
mapDestinationRelation { $0.aliased(alias) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ extension AssociationToMany {
|
||||
///
|
||||
/// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db)
|
||||
public var count: AssociationAggregate<OriginRowDecoder> {
|
||||
let expression = SQLExpressionCountDistinct(SQLExpressionFastPrimaryKey())
|
||||
let expression = SQLExpression.countDistinct(.fastPrimaryKey)
|
||||
return makeAggregate(expression).forKey("\(key.singularizedName)Count")
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ extension AssociationToMany {
|
||||
/// let teams: [Team] = try Team.having(!Team.players.isEmpty())
|
||||
/// let teams: [Team] = try Team.having(Team.players.isEmpty() == false)
|
||||
public var isEmpty: AssociationAggregate<OriginRowDecoder> {
|
||||
let expression = SQLExpressionIsEmpty(SQLExpressionCountDistinct(SQLExpressionFastPrimaryKey()))
|
||||
let expression = SQLExpression.isEmpty(.countDistinct(.fastPrimaryKey))
|
||||
return makeAggregate(expression).forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)")
|
||||
}
|
||||
|
||||
@@ -80,7 +80,7 @@ extension AssociationToMany {
|
||||
///
|
||||
/// 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))
|
||||
let aggregate = makeAggregate(.function("AVG", [expression.sqlExpression]))
|
||||
if let column = expression as? ColumnExpression {
|
||||
let name = key.singularizedName
|
||||
return aggregate.forKey("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
|
||||
@@ -107,7 +107,7 @@ extension AssociationToMany {
|
||||
///
|
||||
/// 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))
|
||||
let aggregate = makeAggregate(.function("MAX", [expression.sqlExpression]))
|
||||
if let column = expression as? ColumnExpression {
|
||||
let name = key.singularizedName
|
||||
return aggregate.forKey("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
|
||||
@@ -134,7 +134,7 @@ extension AssociationToMany {
|
||||
///
|
||||
/// 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))
|
||||
let aggregate = makeAggregate(.function("MIN", [expression.sqlExpression]))
|
||||
if let column = expression as? ColumnExpression {
|
||||
let name = key.singularizedName
|
||||
return aggregate.forKey("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
|
||||
@@ -161,7 +161,7 @@ extension AssociationToMany {
|
||||
///
|
||||
/// 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))
|
||||
let aggregate = makeAggregate(.function("SUM", [expression.sqlExpression]))
|
||||
if let column = expression as? ColumnExpression {
|
||||
let name = key.singularizedName
|
||||
return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum")
|
||||
|
||||
@@ -74,20 +74,15 @@ public struct BelongsToAssociation<Origin, Destination>: AssociationToOne {
|
||||
}
|
||||
|
||||
init(
|
||||
from originTable: String,
|
||||
to destinationRelation: SQLRelation,
|
||||
key: String?,
|
||||
using foreignKey: ForeignKey?)
|
||||
{
|
||||
let destinationTable = destinationRelation.source.tableName
|
||||
|
||||
let foreignKeyRequest = SQLForeignKeyRequest(
|
||||
originTable: originTable,
|
||||
let foreignKeyCondition = SQLForeignKeyCondition(
|
||||
destinationTable: destinationTable,
|
||||
foreignKey: foreignKey)
|
||||
|
||||
let condition = SQLAssociationCondition.foreignKey(
|
||||
request: foreignKeyRequest,
|
||||
foreignKey: foreignKey,
|
||||
originIsLeft: true)
|
||||
|
||||
let associationKey: SQLAssociationKey
|
||||
@@ -99,7 +94,7 @@ public struct BelongsToAssociation<Origin, Destination>: AssociationToOne {
|
||||
|
||||
_sqlAssociation = _SQLAssociation(
|
||||
key: associationKey,
|
||||
condition: condition,
|
||||
condition: .foreignKey(foreignKeyCondition),
|
||||
relation: destinationRelation,
|
||||
cardinality: .toOne)
|
||||
}
|
||||
|
||||
@@ -74,20 +74,15 @@ public struct HasManyAssociation<Origin, Destination>: AssociationToMany {
|
||||
}
|
||||
|
||||
init(
|
||||
from originTable: String,
|
||||
to destinationRelation: SQLRelation,
|
||||
key: String?,
|
||||
using foreignKey: ForeignKey?)
|
||||
{
|
||||
let destinationTable = destinationRelation.source.tableName
|
||||
|
||||
let foreignKeyRequest = SQLForeignKeyRequest(
|
||||
originTable: destinationTable,
|
||||
destinationTable: originTable,
|
||||
foreignKey: foreignKey)
|
||||
|
||||
let condition = SQLAssociationCondition.foreignKey(
|
||||
request: foreignKeyRequest,
|
||||
let foreignKeyCondition = SQLForeignKeyCondition(
|
||||
destinationTable: destinationTable,
|
||||
foreignKey: foreignKey,
|
||||
originIsLeft: false)
|
||||
|
||||
let associationKey: SQLAssociationKey
|
||||
@@ -99,7 +94,7 @@ public struct HasManyAssociation<Origin, Destination>: AssociationToMany {
|
||||
|
||||
_sqlAssociation = _SQLAssociation(
|
||||
key: associationKey,
|
||||
condition: condition,
|
||||
condition: .foreignKey(foreignKeyCondition),
|
||||
relation: destinationRelation,
|
||||
cardinality: .toMany)
|
||||
}
|
||||
|
||||
@@ -76,20 +76,15 @@ public struct HasOneAssociation<Origin, Destination>: AssociationToOne {
|
||||
}
|
||||
|
||||
init(
|
||||
from originTable: String,
|
||||
to destinationRelation: SQLRelation,
|
||||
key: String?,
|
||||
using foreignKey: ForeignKey?)
|
||||
{
|
||||
let destinationTable = destinationRelation.source.tableName
|
||||
|
||||
let foreignKeyRequest = SQLForeignKeyRequest(
|
||||
originTable: destinationTable,
|
||||
destinationTable: originTable,
|
||||
foreignKey: foreignKey)
|
||||
|
||||
let condition = SQLAssociationCondition.foreignKey(
|
||||
request: foreignKeyRequest,
|
||||
let foreignKeyCondition = SQLForeignKeyCondition(
|
||||
destinationTable: destinationTable,
|
||||
foreignKey: foreignKey,
|
||||
originIsLeft: false)
|
||||
|
||||
let associationKey: SQLAssociationKey
|
||||
@@ -101,7 +96,7 @@ public struct HasOneAssociation<Origin, Destination>: AssociationToOne {
|
||||
|
||||
_sqlAssociation = _SQLAssociation(
|
||||
key: associationKey,
|
||||
condition: condition,
|
||||
condition: .foreignKey(foreignKeyCondition),
|
||||
relation: destinationRelation,
|
||||
cardinality: .toOne)
|
||||
}
|
||||
|
||||
@@ -6,13 +6,47 @@ public struct CommonTableExpression<RowDecoder> {
|
||||
/// For example:
|
||||
///
|
||||
/// // WITH answer AS (SELECT 42) ...
|
||||
/// let answer = CommonTableExpression<Void>(
|
||||
/// let answer = CommonTableExpression(
|
||||
/// named: "answer",
|
||||
/// sql: "SELECT 42")
|
||||
/// answer.tableName // "answer"
|
||||
public var tableName: String
|
||||
|
||||
var cte: SQLCTE
|
||||
|
||||
/// Creates a common table expression from a request.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // WITH p AS (SELECT * FROM player) ...
|
||||
/// let p = CommonTableExpression<Void>(
|
||||
/// named: "p",
|
||||
/// request: Player.all())
|
||||
///
|
||||
/// // WITH p AS (SELECT * FROM player) ...
|
||||
/// let p = CommonTableExpression<Void>(
|
||||
/// named: "p",
|
||||
/// request: SQLRequest<Player>(sql: "SELECT * FROM player"))
|
||||
///
|
||||
/// - parameter recursive: Whether this common table expression needs a
|
||||
/// `WITH RECURSIVE` sql clause.
|
||||
/// - parameter tableName: The table name of the common table expression.
|
||||
/// - parameter columns: The columns of the common table expression. If nil,
|
||||
/// the columns are the columns of the request.
|
||||
/// - parameter request: A request.
|
||||
private init<Request: SQLSubqueryable>(
|
||||
recursive: Bool = false,
|
||||
named tableName: String,
|
||||
columns: [String]? = nil,
|
||||
request: Request,
|
||||
type: RowDecoder.Type)
|
||||
{
|
||||
self.tableName = tableName
|
||||
self.cte = SQLCTE(
|
||||
columns: columns,
|
||||
sqlSubquery: request.sqlSubquery,
|
||||
isRecursive: recursive)
|
||||
}
|
||||
}
|
||||
|
||||
extension CommonTableExpression {
|
||||
@@ -36,18 +70,18 @@ extension CommonTableExpression {
|
||||
/// - parameter columns: The columns of the common table expression. If nil,
|
||||
/// the columns are the columns of the request.
|
||||
/// - parameter request: A request.
|
||||
public init<Request: FetchRequest>(
|
||||
public init<Request: SQLSubqueryable>(
|
||||
recursive: Bool = false,
|
||||
named tableName: String,
|
||||
columns: [String]? = nil,
|
||||
request: Request)
|
||||
{
|
||||
self.init(
|
||||
tableName: tableName,
|
||||
cte: SQLCTE(
|
||||
columns: columns,
|
||||
requestPromise: DatabasePromise(value: request),
|
||||
isRecursive: recursive))
|
||||
recursive: recursive,
|
||||
named: tableName,
|
||||
columns: columns,
|
||||
request: request,
|
||||
type: RowDecoder.self)
|
||||
}
|
||||
|
||||
/// Creates a common table expression from an SQL string and
|
||||
@@ -79,7 +113,8 @@ extension CommonTableExpression {
|
||||
recursive: recursive,
|
||||
named: tableName,
|
||||
columns: columns,
|
||||
request: SQLRequest<Void>(sql: sql, arguments: arguments))
|
||||
request: SQLRequest<Void>(sql: sql, arguments: arguments),
|
||||
type: RowDecoder.self)
|
||||
}
|
||||
|
||||
/// Creates a common table expression from an `SQLLiteral`.
|
||||
@@ -107,13 +142,113 @@ extension CommonTableExpression {
|
||||
recursive: recursive,
|
||||
named: tableName,
|
||||
columns: columns,
|
||||
request: SQLRequest<Void>(literal: sqlLiteral))
|
||||
request: SQLRequest<Void>(literal: sqlLiteral),
|
||||
type: RowDecoder.self)
|
||||
}
|
||||
}
|
||||
|
||||
extension CommonTableExpression where RowDecoder == Row {
|
||||
/// Creates a common table expression from a request.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // WITH p AS (SELECT * FROM player) ...
|
||||
/// let p = CommonTableExpression(
|
||||
/// named: "p",
|
||||
/// request: Player.all())
|
||||
///
|
||||
/// // WITH p AS (SELECT * FROM player) ...
|
||||
/// let p = CommonTableExpression(
|
||||
/// named: "p",
|
||||
/// request: SQLRequest<Player>(sql: "SELECT * FROM player"))
|
||||
///
|
||||
/// - parameter recursive: Whether this common table expression needs a
|
||||
/// `WITH RECURSIVE` sql clause.
|
||||
/// - parameter tableName: The table name of the common table expression.
|
||||
/// - parameter columns: The columns of the common table expression. If nil,
|
||||
/// the columns are the columns of the request.
|
||||
/// - parameter request: A request.
|
||||
public init<Request: SQLSubqueryable>(
|
||||
recursive: Bool = false,
|
||||
named tableName: String,
|
||||
columns: [String]? = nil,
|
||||
request: Request)
|
||||
{
|
||||
self.init(
|
||||
recursive: recursive,
|
||||
named: tableName,
|
||||
columns: columns,
|
||||
request: request,
|
||||
type: Row.self)
|
||||
}
|
||||
|
||||
/// Creates a common table expression from an SQL string and
|
||||
/// optional arguments.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // WITH p AS (SELECT * FROM player WHERE name = 'O''Brien') ...
|
||||
/// let p = CommonTableExpression(
|
||||
/// named: "p",
|
||||
/// sql: "SELECT * FROM player WHERE name = ?",
|
||||
/// arguments: ["O'Brien"])
|
||||
///
|
||||
/// - parameter recursive: Whether this common table expression needs a
|
||||
/// `WITH RECURSIVE` sql clause.
|
||||
/// - parameter tableName: The table name of the common table expression.
|
||||
/// - parameter columns: The columns of the common table expression. If nil,
|
||||
/// the columns are the columns of the request.
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - parameter arguments: Statement arguments.
|
||||
public init(
|
||||
recursive: Bool = false,
|
||||
named tableName: String,
|
||||
columns: [String]? = nil,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments())
|
||||
{
|
||||
self.init(
|
||||
recursive: recursive,
|
||||
named: tableName,
|
||||
columns: columns,
|
||||
request: SQLRequest<Void>(sql: sql, arguments: arguments),
|
||||
type: Row.self)
|
||||
}
|
||||
|
||||
/// Creates a common table expression from an `SQLLiteral`.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // WITH p AS (SELECT * FROM player WHERE name = 'O''Brien') ...
|
||||
/// let p = CommonTableExpression(
|
||||
/// named: "p",
|
||||
/// literal: "SELECT * FROM player WHERE name = \("O'Brien")")
|
||||
///
|
||||
/// - parameter recursive: Whether this common table expression needs a
|
||||
/// `WITH RECURSIVE` sql clause.
|
||||
/// - parameter tableName: The table name of the common table expression.
|
||||
/// - parameter columns: The columns of the common table expression. If nil,
|
||||
/// the columns are the columns of the request.
|
||||
/// - parameter sqlLiteral: An SQLLiteral.
|
||||
public init(
|
||||
recursive: Bool = false,
|
||||
named tableName: String,
|
||||
columns: [String]? = nil,
|
||||
literal sqlLiteral: SQLLiteral)
|
||||
{
|
||||
self.init(
|
||||
recursive: recursive,
|
||||
named: tableName,
|
||||
columns: columns,
|
||||
request: SQLRequest<Void>(literal: sqlLiteral),
|
||||
type: Row.self)
|
||||
}
|
||||
}
|
||||
|
||||
extension CommonTableExpression {
|
||||
var relationForAll: SQLRelation {
|
||||
.all(fromTable: tableName, selection: { _ in [AllColumns(cte: cte)] })
|
||||
let cte = self.cte
|
||||
return .all(fromTable: tableName, selection: { _ in [.allCTEColumns(cte)] })
|
||||
}
|
||||
|
||||
/// Creates a request for all rows of the common table expression.
|
||||
@@ -136,7 +271,7 @@ extension CommonTableExpression {
|
||||
/// // WITH answer AS (SELECT 42 AS value)
|
||||
/// // SELECT * FROM player
|
||||
/// // WHERE score = (SELECT * FROM answer)
|
||||
/// let answer = CommonTableExpression<Void>(
|
||||
/// let answer = CommonTableExpression(
|
||||
/// named: "answer",
|
||||
/// sql: "SELECT 42 AS value")
|
||||
/// let players = try Player
|
||||
@@ -150,14 +285,14 @@ extension CommonTableExpression {
|
||||
/// An SQL expression that checks the inclusion of an expression in a
|
||||
/// common table expression.
|
||||
///
|
||||
/// let playerNameCTE = CommonTableExpression<Void>(
|
||||
/// let playerNameCTE = CommonTableExpression(
|
||||
/// named: "playerName",
|
||||
/// request: Player.select(Column("name"))
|
||||
///
|
||||
/// // name IN playerName
|
||||
/// playerNameCTE.contains(Column("name"))
|
||||
public func contains(_ element: SQLExpressible) -> SQLExpression {
|
||||
SQLTableCollection.tableName(tableName).contains(element)
|
||||
SQLCollection.table(tableName).contains(element.sqlExpression)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,13 +309,14 @@ struct SQLCTE {
|
||||
///
|
||||
/// -- Column id
|
||||
/// WITH t(id) AS (SELECT 1) ...
|
||||
/// ~~
|
||||
var columns: [String]?
|
||||
|
||||
/// The common table expression request.
|
||||
/// The common table expression subquery.
|
||||
///
|
||||
/// WITH t AS (SELECT ...)
|
||||
/// ~~~~~~~~~~
|
||||
var requestPromise: DatabasePromise<_FetchRequest>
|
||||
var sqlSubquery: SQLSubquery
|
||||
|
||||
/// Whether this common table expression needs a `WITH RECURSIVE`
|
||||
/// sql clause.
|
||||
@@ -193,69 +329,7 @@ struct SQLCTE {
|
||||
return columns.count
|
||||
}
|
||||
|
||||
return try requestPromise.resolve(db)._selectedColumnCount(db)
|
||||
}
|
||||
}
|
||||
|
||||
extension TableRecord {
|
||||
/// Creates an association to a common table expression that you can join
|
||||
/// or include in another request.
|
||||
///
|
||||
/// The key of the returned association is the table name of the common
|
||||
/// table expression.
|
||||
///
|
||||
/// For example, you can build a request that fetches all chats with their
|
||||
/// latest message:
|
||||
///
|
||||
/// let latestMessageRequest = Message
|
||||
/// .annotated(with: max(Column("date")))
|
||||
/// .group(Column("chatID"))
|
||||
///
|
||||
/// let latestMessageCTE = CommonTableExpression<Void>(
|
||||
/// named: "latestMessage",
|
||||
/// request: latestMessageRequest)
|
||||
///
|
||||
/// let latestMessage = Chat.association(
|
||||
/// to: latestMessageCTE,
|
||||
/// on: { chat, latestMessage in
|
||||
/// chat[Column("id")] == latestMessage[Column("chatID")]
|
||||
/// })
|
||||
///
|
||||
/// // WITH latestMessage AS
|
||||
/// // (SELECT *, MAX(date) FROM message GROUP BY chatID)
|
||||
/// // SELECT chat.*, latestMessage.*
|
||||
/// // FROM chat
|
||||
/// // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID
|
||||
/// let request = Chat
|
||||
/// .with(latestMessageCTE)
|
||||
/// .including(optional: latestMessage)
|
||||
///
|
||||
/// - parameter cte: A common table expression.
|
||||
/// - parameter condition: A function that returns the joining clause.
|
||||
/// - parameter left: A `TableAlias` for the left table.
|
||||
/// - parameter right: A `TableAlias` for the right table.
|
||||
/// - returns: An association to the common table expression.
|
||||
public static func association<Destination>(
|
||||
to cte: CommonTableExpression<Destination>,
|
||||
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> SQLExpressible)
|
||||
-> JoinAssociation<Self, Destination>
|
||||
{
|
||||
JoinAssociation(to: cte.relationForAll, condition: .expression(condition))
|
||||
}
|
||||
|
||||
/// Creates an association to a common table expression that you can join
|
||||
/// or include in another request.
|
||||
///
|
||||
/// The key of the returned association is the table name of the common
|
||||
/// table expression.
|
||||
///
|
||||
/// - parameter cte: A common table expression.
|
||||
/// - returns: An association to the common table expression.
|
||||
public static func association<Destination>(
|
||||
to cte: CommonTableExpression<Destination>)
|
||||
-> JoinAssociation<Self, Destination>
|
||||
{
|
||||
JoinAssociation(to: cte.relationForAll, condition: .none)
|
||||
return try sqlSubquery.columnsCount(db)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,7 +350,9 @@ extension CommonTableExpression {
|
||||
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> SQLExpressible)
|
||||
-> JoinAssociation<RowDecoder, Destination>
|
||||
{
|
||||
JoinAssociation(to: cte.relationForAll, condition: .expression(condition))
|
||||
JoinAssociation(
|
||||
to: cte.relationForAll,
|
||||
condition: .expression { condition($0, $1).sqlExpression })
|
||||
}
|
||||
|
||||
/// Creates an association to a common table expression that you can join
|
||||
@@ -310,7 +386,9 @@ extension CommonTableExpression {
|
||||
-> JoinAssociation<RowDecoder, Destination>
|
||||
where Destination: TableRecord
|
||||
{
|
||||
JoinAssociation(to: Destination.relationForAll, condition: .expression(condition))
|
||||
JoinAssociation(
|
||||
to: Destination.relationForAll,
|
||||
condition: .expression { condition($0, $1).sqlExpression })
|
||||
}
|
||||
|
||||
/// Creates an association to a table record that you can join
|
||||
@@ -329,7 +407,7 @@ extension CommonTableExpression {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - QueryInterfaceRequest
|
||||
// MARK: - With
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
/// Returns a request which embeds the common table expression.
|
||||
@@ -344,7 +422,7 @@ extension QueryInterfaceRequest {
|
||||
/// .annotated(with: max(Column("date")))
|
||||
/// .group(Column("chatID"))
|
||||
///
|
||||
/// let latestMessageCTE = CommonTableExpression<Void>(
|
||||
/// let latestMessageCTE = CommonTableExpression(
|
||||
/// named: "latestMessage",
|
||||
/// request: latestMessageRequest)
|
||||
///
|
||||
@@ -383,7 +461,7 @@ extension TableRecord {
|
||||
/// .annotated(with: max(Column("date")))
|
||||
/// .group(Column("chatID"))
|
||||
///
|
||||
/// let latestMessageCTE = CommonTableExpression<Void>(
|
||||
/// let latestMessageCTE = CommonTableExpression(
|
||||
/// named: "latestMessage",
|
||||
/// request: latestMessageRequest)
|
||||
///
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
extension QueryInterfaceRequest where RowDecoder: TableRecord {
|
||||
|
||||
// MARK: - Association Aggregates
|
||||
|
||||
private func annotated(with aggregate: AssociationAggregate<RowDecoder>) -> QueryInterfaceRequest {
|
||||
var request = self
|
||||
let expressionPromise = aggregate.prepare(&request)
|
||||
if let key = aggregate.key {
|
||||
return request.annotated(with: { db in try [expressionPromise.resolve(db).forKey(key)] })
|
||||
} else {
|
||||
return request.annotated(with: { db in try [expressionPromise.resolve(db)] })
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a request which appends *aggregates* to the current selection.
|
||||
///
|
||||
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
|
||||
/// // FROM player LEFT JOIN book ...
|
||||
/// var request = Player.all()
|
||||
/// request = request.annotated(with: Player.books.count)
|
||||
public func annotated(with aggregates: AssociationAggregate<RowDecoder>...) -> QueryInterfaceRequest {
|
||||
annotated(with: aggregates)
|
||||
}
|
||||
|
||||
/// Creates a request which appends *aggregates* to the current selection.
|
||||
///
|
||||
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
|
||||
/// // FROM player LEFT JOIN book ...
|
||||
/// var request = Player.all()
|
||||
/// request = request.annotated(with: [Player.books.count])
|
||||
public func annotated(with aggregates: [AssociationAggregate<RowDecoder>]) -> QueryInterfaceRequest {
|
||||
aggregates.reduce(self) { request, aggregate in
|
||||
request.annotated(with: aggregate)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// 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)
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,10 @@ extension QueryInterfaceRequest {
|
||||
extension QueryInterfaceRequest: Refinable { }
|
||||
|
||||
extension QueryInterfaceRequest: FetchRequest {
|
||||
public var sqlSubquery: SQLSubquery {
|
||||
.query(query)
|
||||
}
|
||||
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
try query.fetchCount(db)
|
||||
}
|
||||
@@ -55,22 +59,12 @@ extension QueryInterfaceRequest: FetchRequest {
|
||||
let associations = query.relation.prefetchedAssociations
|
||||
if associations.isEmpty == false {
|
||||
// Eager loading of prefetched associations
|
||||
preparedRequest = preparedRequest.with(\.supplementaryFetch) { db, rows in
|
||||
try prefetch(db, associations: associations, into: rows, from: self)
|
||||
preparedRequest = preparedRequest.with(\.supplementaryFetch) { [query] db, rows in
|
||||
try prefetch(db, associations: associations, from: query, into: rows)
|
||||
}
|
||||
}
|
||||
return preparedRequest
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _selectedColumnCount(_ db: Database) throws -> Int {
|
||||
try SQLQueryGenerator(query: query).columnsCount(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
|
||||
try SQLQueryGenerator(query: query, forSingleResult: singleResult).requestSQL(context)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Request Derivation
|
||||
@@ -89,7 +83,7 @@ extension QueryInterfaceRequest: SelectionRequest {
|
||||
/// .select { db in [Column("id")] }
|
||||
/// .select { db in [Column("email")] }
|
||||
public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest {
|
||||
map(\.query) { $0.select(selection) }
|
||||
map(\.query) { $0.select { try selection($0).map(\.sqlSelection) } }
|
||||
}
|
||||
|
||||
/// Creates a request which selects *selection*, and fetches values of
|
||||
@@ -103,7 +97,7 @@ extension QueryInterfaceRequest: SelectionRequest {
|
||||
public func select<RowDecoder>(_ selection: [SQLSelectable], as type: RowDecoder.Type = RowDecoder.self)
|
||||
-> QueryInterfaceRequest<RowDecoder>
|
||||
{
|
||||
map(\.query, { $0.select(selection) }).asRequest(of: RowDecoder.self)
|
||||
select(selection).asRequest(of: RowDecoder.self)
|
||||
}
|
||||
|
||||
/// Creates a request which selects *selection*, and fetches values of
|
||||
@@ -169,7 +163,7 @@ extension QueryInterfaceRequest: SelectionRequest {
|
||||
as type: RowDecoder.Type = RowDecoder.self)
|
||||
-> QueryInterfaceRequest<RowDecoder>
|
||||
{
|
||||
select(sqlLiteral.sqlSelectable, as: type)
|
||||
select(sqlLiteral.sqlSelection, as: type)
|
||||
}
|
||||
|
||||
/// Creates a request which appends *selection promise*.
|
||||
@@ -180,7 +174,7 @@ extension QueryInterfaceRequest: SelectionRequest {
|
||||
/// .select([Column("id"), Column("email")])
|
||||
/// .annotated(with: { db in [Column("name")] })
|
||||
public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest {
|
||||
map(\.query) { $0.annotated(with: selection) }
|
||||
map(\.query) { $0.annotated { try selection($0).map(\.sqlSelection) } }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -192,7 +186,7 @@ extension QueryInterfaceRequest: FilteredRequest {
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter { db in true }
|
||||
public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest {
|
||||
map(\.query) { $0.filter(predicate) }
|
||||
map(\.query) { $0.filter { try predicate($0).sqlExpression } }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -211,7 +205,7 @@ extension QueryInterfaceRequest: OrderedRequest {
|
||||
/// .reversed()
|
||||
/// .order{ _ in [Column("name")] }
|
||||
public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceRequest {
|
||||
map(\.query) { $0.order(orderings) }
|
||||
map(\.query) { $0.order { try orderings($0).map(\.sqlOrdering) } }
|
||||
}
|
||||
|
||||
/// Creates a request that reverses applied orderings.
|
||||
@@ -242,13 +236,13 @@ extension QueryInterfaceRequest: OrderedRequest {
|
||||
extension QueryInterfaceRequest: AggregatingRequest {
|
||||
/// Creates a request grouped according to *expressions promise*.
|
||||
public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceRequest {
|
||||
map(\.query) { $0.group(expressions) }
|
||||
map(\.query) { $0.group { try expressions($0).map(\.sqlExpression) } }
|
||||
}
|
||||
|
||||
/// Creates a request with the provided *predicate promise* added to the
|
||||
/// eventual set of already applied predicates.
|
||||
public func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest {
|
||||
map(\.query) { $0.having(predicate) }
|
||||
map(\.query) { $0.having { try predicate($0).sqlExpression } }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -306,7 +300,7 @@ extension QueryInterfaceRequest: TableRequest {
|
||||
/// .aliased(playerAlias)
|
||||
/// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")])
|
||||
public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest {
|
||||
map(\.query) { $0.qualified(with: alias) }
|
||||
map(\.query) { $0.aliased(alias) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -355,6 +349,57 @@ extension QueryInterfaceRequest {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Aggregates
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
|
||||
private func annotated(with aggregate: AssociationAggregate<RowDecoder>) -> QueryInterfaceRequest {
|
||||
var request = self
|
||||
let expressionPromise = aggregate.prepare(&request)
|
||||
if let key = aggregate.key {
|
||||
return request.annotated(with: { db in try [expressionPromise.resolve(db).forKey(key)] })
|
||||
} else {
|
||||
return request.annotated(with: { db in try [expressionPromise.resolve(db)] })
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a request which appends *aggregates* to the current selection.
|
||||
///
|
||||
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
|
||||
/// // FROM player LEFT JOIN book ...
|
||||
/// var request = Player.all()
|
||||
/// request = request.annotated(with: Player.books.count)
|
||||
public func annotated(with aggregates: AssociationAggregate<RowDecoder>...) -> QueryInterfaceRequest {
|
||||
annotated(with: aggregates)
|
||||
}
|
||||
|
||||
/// Creates a request which appends *aggregates* to the current selection.
|
||||
///
|
||||
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
|
||||
/// // FROM player LEFT JOIN book ...
|
||||
/// var request = Player.all()
|
||||
/// request = request.annotated(with: [Player.books.count])
|
||||
public func annotated(with aggregates: [AssociationAggregate<RowDecoder>]) -> QueryInterfaceRequest {
|
||||
aggregates.reduce(self) { request, aggregate in
|
||||
request.annotated(with: aggregate)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// 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)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Batch Delete
|
||||
|
||||
extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
|
||||
@@ -449,12 +494,10 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
|
||||
/// }
|
||||
public struct ColumnAssignment {
|
||||
var column: ColumnExpression
|
||||
var value: SQLExpressible
|
||||
var value: SQLExpression
|
||||
|
||||
func sql(_ context: SQLGenerationContext) throws -> String {
|
||||
try column._expressionSQL(context, wrappedInParenthesis: false)
|
||||
+ " = "
|
||||
+ value.sqlExpression._expressionSQL(context, wrappedInParenthesis: false)
|
||||
try column.sqlExpression.sql(context) + " = " + value.sql(context)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -471,7 +514,7 @@ extension ColumnExpression {
|
||||
/// try Player.updateAll(db, Column("score").set(to: 0))
|
||||
/// }
|
||||
public func set(to value: SQLExpressible?) -> ColumnAssignment {
|
||||
ColumnAssignment(column: self, value: value ?? DatabaseValue.null)
|
||||
ColumnAssignment(column: self, value: value?.sqlExpression ?? .null)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -530,19 +573,19 @@ public func /= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssign
|
||||
// MARK: - Eager loading of hasMany associations
|
||||
|
||||
// CAUTION: Keep this code in sync with prefetchedRegion(_:_:)
|
||||
/// Append rows from prefetched associations into the `baseRows` argument.
|
||||
/// Append rows from prefetched associations into the `originRows` argument.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter associations: Prefetched associations.
|
||||
/// - parameter baseRows: The rows that need to be extended with prefetched rows.
|
||||
/// - parameter baseRequest: The request that was used to fetch `baseRows`.
|
||||
private func prefetch<RowDecoder>(
|
||||
/// - parameter originRows: The rows that need to be extended with prefetched rows.
|
||||
/// - parameter originQuery: The query that was used to fetch `originRows`.
|
||||
private func prefetch(
|
||||
_ db: Database,
|
||||
associations: [_SQLAssociation],
|
||||
into baseRows: [Row],
|
||||
from baseRequest: QueryInterfaceRequest<RowDecoder>) throws
|
||||
from originQuery: SQLQuery,
|
||||
into originRows: [Row]) throws
|
||||
{
|
||||
guard let firstBaseRow = baseRows.first else {
|
||||
guard let firstOriginRow = originRows.first else {
|
||||
// No rows -> no prefetch
|
||||
return
|
||||
}
|
||||
@@ -554,10 +597,9 @@ private func prefetch<RowDecoder>(
|
||||
// are not prefetched with including(all:)
|
||||
fatalError("Not implemented: prefetch association without any foreign key")
|
||||
|
||||
case let .foreignKey(request: foreignKeyRequest, originIsLeft: originIsLeft):
|
||||
let pivotMapping = try foreignKeyRequest
|
||||
.fetchForeignKeyMapping(db)
|
||||
.joinMapping(originIsLeft: originIsLeft)
|
||||
case let .foreignKey(pivotForeignKey):
|
||||
let originTable = originQuery.relation.source.tableName
|
||||
let pivotMapping = try pivotForeignKey.joinMapping(db, from: originTable)
|
||||
let pivotColumns = pivotMapping.map(\.right)
|
||||
let leftColumns = pivotMapping.map(\.left)
|
||||
|
||||
@@ -587,7 +629,7 @@ private func prefetch<RowDecoder>(
|
||||
// Otherwise, we fallback to the `(a = ? AND b = ?) OR ...`
|
||||
// condition (the one that may fail if there are too many
|
||||
// base rows).
|
||||
let usesCommonTableExpression = pivotMapping.count > 1 && SQLRowValue.isAvailable
|
||||
let usesCommonTableExpression = pivotMapping.count > 1 && SQLExpression.rowValuesAreAvailable
|
||||
|
||||
let prefetchRequest: QueryInterfaceRequest<Row>
|
||||
if usesCommonTableExpression {
|
||||
@@ -605,24 +647,25 @@ private func prefetch<RowDecoder>(
|
||||
// FROM country
|
||||
// JOIN passport ON passport.countryCode = country.code
|
||||
// AND (passport.a, passport.b) IN grdb_base
|
||||
let baseRequest = baseRequest.map(\.query.relation) { baseRelation in
|
||||
let originQuery = originQuery.map(\.relation) { baseRelation in
|
||||
// Ordering and including(all:) children are
|
||||
// useless, and we only need pivoting columns:
|
||||
baseRelation
|
||||
.unordered()
|
||||
.removingChildrenForPrefetchedAssociations()
|
||||
.selectOnly(leftColumns.map(Column.init))
|
||||
.selectOnly(leftColumns.map { SQLExpression.column($0).sqlSelection })
|
||||
}
|
||||
let baseCTE = CommonTableExpression<Void>(
|
||||
let originCTE = CommonTableExpression(
|
||||
named: "grdb_base",
|
||||
request: baseRequest)
|
||||
let pivotFilter = baseCTE.contains(SQLRowValue(pivotColumns.map(Column.init)))
|
||||
request: SQLSubquery.query(originQuery))
|
||||
let pivotRowValue = SQLExpression.rowValue(pivotColumns.map(SQLExpression.column))!
|
||||
let pivotFilter = originCTE.contains(pivotRowValue)
|
||||
|
||||
prefetchRequest = makePrefetchRequest(
|
||||
for: association,
|
||||
filteringPivotWith: pivotFilter,
|
||||
annotatedWith: pivotColumns)
|
||||
.with(baseCTE)
|
||||
.with(originCTE)
|
||||
} else {
|
||||
// HasMany: Author.including(all: Author.books)
|
||||
//
|
||||
@@ -636,7 +679,7 @@ private func prefetch<RowDecoder>(
|
||||
// FROM country
|
||||
// JOIN passport ON passport.countryCode = country.code
|
||||
// AND passport.citizenId IN (1, 2, 3)
|
||||
let pivotFilter = pivotMapping.joinExpression(leftRows: baseRows)
|
||||
let pivotFilter = pivotMapping.joinExpression(leftRows: originRows)
|
||||
|
||||
prefetchRequest = makePrefetchRequest(
|
||||
for: association,
|
||||
@@ -646,9 +689,9 @@ private func prefetch<RowDecoder>(
|
||||
|
||||
let prefetchedRows = try prefetchRequest.fetchAll(db)
|
||||
let prefetchedGroups = prefetchedRows.grouped(byDatabaseValuesOnColumns: pivotColumns.map { "grdb_\($0)" })
|
||||
let groupingIndexes = firstBaseRow.indexes(forColumns: leftColumns)
|
||||
let groupingIndexes = firstOriginRow.indexes(forColumns: leftColumns)
|
||||
|
||||
for row in baseRows {
|
||||
for row in originRows {
|
||||
let groupingKey = groupingIndexes.map { row.impl.databaseValue(atUncheckedIndex: $0) }
|
||||
let prefetchedRows = prefetchedGroups[groupingKey, default: []]
|
||||
row.prefetchedRows.setRows(prefetchedRows, forKeyPath: association.keyPath)
|
||||
@@ -694,7 +737,7 @@ func makePrefetchRequest(
|
||||
let pivotAlias = TableAlias()
|
||||
|
||||
let prefetchRelation = association
|
||||
.map(\.pivot.relation, { $0.qualified(with: pivotAlias).filter(pivotFilter) })
|
||||
.map(\.pivot.relation, { $0.aliased(pivotAlias).filter(pivotFilter) })
|
||||
.destinationRelation()
|
||||
.annotated(with: pivotColumns.map { pivotAlias[$0].forKey("grdb_\($0)") })
|
||||
|
||||
@@ -703,7 +746,12 @@ func makePrefetchRequest(
|
||||
|
||||
// CAUTION: Keep this code in sync with prefetch(_:associations:in:)
|
||||
/// Returns the region of prefetched associations
|
||||
func prefetchedRegion(_ db: Database, associations: [_SQLAssociation]) throws -> DatabaseRegion {
|
||||
func prefetchedRegion(
|
||||
_ db: Database,
|
||||
associations: [_SQLAssociation],
|
||||
from originTable: String)
|
||||
throws -> DatabaseRegion
|
||||
{
|
||||
try associations.reduce(into: DatabaseRegion()) { (region, association) in
|
||||
switch association.pivot.condition {
|
||||
case .expression:
|
||||
@@ -711,10 +759,8 @@ func prefetchedRegion(_ db: Database, associations: [_SQLAssociation]) throws ->
|
||||
// are not prefetched with including(all:)
|
||||
fatalError("Not implemented: prefetch association without any foreign key")
|
||||
|
||||
case let .foreignKey(request: foreignKeyRequest, originIsLeft: originIsLeft):
|
||||
let pivotMapping = try foreignKeyRequest
|
||||
.fetchForeignKeyMapping(db)
|
||||
.joinMapping(originIsLeft: originIsLeft)
|
||||
case let .foreignKey(pivotForeignKey):
|
||||
let pivotMapping = try pivotForeignKey.joinMapping(db, from: originTable)
|
||||
let prefetchRegion = try prefetchedRegion(db, association: association, pivotMapping: pivotMapping)
|
||||
region.formUnion(prefetchRegion)
|
||||
}
|
||||
|
||||
@@ -102,7 +102,7 @@ extension SelectionRequest {
|
||||
/// .select(literal: SQLLiteral(sql: "email"))
|
||||
public func select(literal sqlLiteral: SQLLiteral) -> Self {
|
||||
// NOT TESTED
|
||||
select(sqlLiteral.sqlSelectable)
|
||||
select(sqlLiteral.sqlSelection)
|
||||
}
|
||||
|
||||
/// Creates a request which appends *selection*.
|
||||
@@ -317,7 +317,7 @@ extension TableRequest where Self: OrderedRequest {
|
||||
public func orderByPrimaryKey() -> Self {
|
||||
let tableName = self.databaseTableName
|
||||
return order { db in
|
||||
try db.primaryKey(tableName).columns.map { Column($0) }
|
||||
try db.primaryKey(tableName).columns.map(SQLExpression.column)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -501,7 +501,7 @@ extension OrderedRequest {
|
||||
/// .order(sql: "name")
|
||||
public func order(literal sqlLiteral: SQLLiteral) -> Self {
|
||||
// NOT TESTED
|
||||
order(sqlLiteral.sqlOrderingTerm)
|
||||
order(sqlLiteral.sqlOrdering)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
/// let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db)
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift#the-query-interface
|
||||
public protocol ColumnExpression: SQLExpression {
|
||||
public protocol ColumnExpression: SQLSpecificExpressible {
|
||||
/// The unqualified name of a database column.
|
||||
///
|
||||
/// "score" is a valid unqualified name. "player.score" is not.
|
||||
@@ -25,14 +25,8 @@ public protocol ColumnExpression: SQLExpression {
|
||||
}
|
||||
|
||||
extension ColumnExpression {
|
||||
/// :nodoc:
|
||||
public func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
name.quotedDatabaseIdentifier
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
SQLQualifiedColumn(name, alias: alias)
|
||||
public var sqlExpression: SQLExpression {
|
||||
.column(name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,42 +54,6 @@ public struct Column: ColumnExpression, Equatable {
|
||||
}
|
||||
}
|
||||
|
||||
/// A qualified column in the database, as in `SELECT t.a FROM t`
|
||||
///
|
||||
/// :nodoc:
|
||||
struct SQLQualifiedColumn: ColumnExpression {
|
||||
var name: String
|
||||
let alias: TableAlias
|
||||
|
||||
/// Creates a column given its name.
|
||||
init(_ name: String, alias: TableAlias) {
|
||||
self.name = name
|
||||
self.alias = alias
|
||||
}
|
||||
|
||||
func _column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool) throws -> String? {
|
||||
if alias == self.alias {
|
||||
return name
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
if let qualifier = context.qualifier(for: alias) {
|
||||
return qualifier.quotedDatabaseIdentifier
|
||||
+ "."
|
||||
+ name.quotedDatabaseIdentifier
|
||||
}
|
||||
return name.quotedDatabaseIdentifier
|
||||
}
|
||||
|
||||
func _qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
// Never requalify
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Support for column enums:
|
||||
///
|
||||
/// struct Player {
|
||||
|
||||
@@ -130,7 +130,7 @@ public struct _SQLAssociation {
|
||||
|
||||
return SQLAssociationStep(
|
||||
key: key,
|
||||
condition: nextStep.condition.reversed,
|
||||
condition: nextStep.condition.reversed(to: step.relation.source.tableName),
|
||||
relation: relation,
|
||||
cardinality: .toOne)
|
||||
})
|
||||
|
||||
@@ -22,10 +22,10 @@ public struct SQLCollatedExpression: SQLOrderingTerm {
|
||||
/// Player.order(email.asc)
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
public var asc: SQLOrderingTerm {
|
||||
SQLOrdering.asc(sqlExpression)
|
||||
public var asc: SQLOrdering {
|
||||
.asc(sqlExpression)
|
||||
}
|
||||
|
||||
|
||||
/// Returns an ordering suitable for QueryInterfaceRequest.order()
|
||||
///
|
||||
/// let email: SQLCollatedExpression = Column("email").collating(.nocase)
|
||||
@@ -34,10 +34,10 @@ public struct SQLCollatedExpression: SQLOrderingTerm {
|
||||
/// Player.order(email.desc)
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
public var desc: SQLOrderingTerm {
|
||||
SQLOrdering.desc(sqlExpression)
|
||||
public var desc: SQLOrdering {
|
||||
.desc(sqlExpression)
|
||||
}
|
||||
|
||||
|
||||
#if GRDBCUSTOMSQLITE
|
||||
/// Returns an ordering suitable for QueryInterfaceRequest.order()
|
||||
///
|
||||
@@ -47,10 +47,10 @@ public struct SQLCollatedExpression: SQLOrderingTerm {
|
||||
/// Player.order(email.ascNullsLast)
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
public var ascNullsLast: SQLOrderingTerm {
|
||||
SQLOrdering.ascNullsLast(sqlExpression)
|
||||
public var ascNullsLast: SQLOrdering {
|
||||
.ascNullsLast(sqlExpression)
|
||||
}
|
||||
|
||||
|
||||
/// Returns an ordering suitable for QueryInterfaceRequest.order()
|
||||
///
|
||||
/// let email: SQLCollatedExpression = Column("email").collating(.nocase)
|
||||
@@ -59,8 +59,8 @@ public struct SQLCollatedExpression: SQLOrderingTerm {
|
||||
/// Player.order(email.descNullsFirst)
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
public var descNullsFirst: SQLOrderingTerm {
|
||||
SQLOrdering.descNullsFirst(sqlExpression)
|
||||
public var descNullsFirst: SQLOrdering {
|
||||
.descNullsFirst(sqlExpression)
|
||||
}
|
||||
#elseif !GRDBCIPHER
|
||||
/// Returns an ordering suitable for QueryInterfaceRequest.order()
|
||||
@@ -72,10 +72,10 @@ public struct SQLCollatedExpression: SQLOrderingTerm {
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
@available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *)
|
||||
public var ascNullsLast: SQLOrderingTerm {
|
||||
SQLOrdering.ascNullsLast(sqlExpression)
|
||||
public var ascNullsLast: SQLOrdering {
|
||||
.ascNullsLast(sqlExpression)
|
||||
}
|
||||
|
||||
|
||||
/// Returns an ordering suitable for QueryInterfaceRequest.order()
|
||||
///
|
||||
/// let email: SQLCollatedExpression = Column("email").collating(.nocase)
|
||||
@@ -85,32 +85,21 @@ public struct SQLCollatedExpression: SQLOrderingTerm {
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
@available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *)
|
||||
public var descNullsFirst: SQLOrderingTerm {
|
||||
SQLOrdering.descNullsFirst(sqlExpression)
|
||||
public var descNullsFirst: SQLOrdering {
|
||||
.descNullsFirst(sqlExpression)
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
init(_ expression: SQLExpression, collationName: Database.CollationName) {
|
||||
self.expression = expression
|
||||
self.collationName = collationName
|
||||
}
|
||||
|
||||
var sqlExpression: SQLExpression {
|
||||
SQLExpressionCollate(expression, collationName: collationName)
|
||||
.collated(expression, collationName)
|
||||
}
|
||||
|
||||
// MARK: SQLOrderingTerm
|
||||
|
||||
/// :nodoc:
|
||||
public func _orderingTermSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
try sqlExpression._orderingTermSQL(context)
|
||||
public var sqlOrdering: SQLOrdering {
|
||||
.expression(sqlExpression)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm {
|
||||
SQLCollatedExpression(expression._qualifiedExpression(with: alias), collationName: collationName)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public var _reversed: SQLOrderingTerm { desc }
|
||||
}
|
||||
@@ -1,13 +1,54 @@
|
||||
// MARK: - SQLCollection
|
||||
|
||||
/// Implementation details of `SQLCollection`.
|
||||
/// The right-hand side of the `IN` or `NOT IN` SQL operators
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol _SQLCollection {
|
||||
/// See https://sqlite.org/lang_expr.html#the_in_and_not_in_operators
|
||||
public struct SQLCollection {
|
||||
private var impl: Impl
|
||||
|
||||
private enum Impl {
|
||||
/// An array collection
|
||||
///
|
||||
/// id IN (1, 2, 3)
|
||||
/// ~~~~~~~~~
|
||||
case array([SQLExpression])
|
||||
|
||||
/// A subquery
|
||||
///
|
||||
/// score IN (SELECT ...)
|
||||
/// ~~~~~~~~~~~~
|
||||
case subquery(SQLSubquery)
|
||||
|
||||
/// A table
|
||||
///
|
||||
/// score IN table
|
||||
/// ~~~~~
|
||||
case table(String)
|
||||
}
|
||||
|
||||
static func array(_ expressions: [SQLExpression]) -> Self {
|
||||
self.init(impl: .array(expressions))
|
||||
}
|
||||
|
||||
static func subquery(_ subquery: SQLSubquery) -> Self {
|
||||
self.init(impl: .subquery(subquery))
|
||||
}
|
||||
|
||||
static func table(_ tableName: String) -> Self {
|
||||
self.init(impl: .table(tableName))
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLCollection {
|
||||
/// Returns a qualified collection.
|
||||
///
|
||||
/// :nodoc:
|
||||
func _qualifiedCollection(with alias: TableAlias) -> SQLCollection
|
||||
func qualified(with alias: TableAlias) -> SQLCollection {
|
||||
switch impl {
|
||||
case .subquery,
|
||||
.table:
|
||||
return self
|
||||
|
||||
case let .array(expressions):
|
||||
return .array(expressions.map { $0.qualified(with: alias) })
|
||||
}
|
||||
}
|
||||
|
||||
/// The expressions in the collection, if known.
|
||||
///
|
||||
@@ -18,88 +59,63 @@ public protocol _SQLCollection {
|
||||
/// let request = Player.filter(keys: [1, 2, 3])
|
||||
/// let regionObservation = DatabaseRegionObservation(tracking: request)
|
||||
/// let valueObservation = ValueObservation.tracking(request.fetchAll)
|
||||
///
|
||||
/// :nodoc:
|
||||
var _collectionExpressions: [SQLExpression]? { get }
|
||||
var collectionExpressions: [SQLExpression]? {
|
||||
switch impl {
|
||||
case .subquery,
|
||||
.table:
|
||||
return nil
|
||||
|
||||
case let .array(expressions):
|
||||
return expressions
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an SQL string that represents the collection.
|
||||
///
|
||||
/// - parameter context: An SQL generation context which accepts
|
||||
/// statement arguments.
|
||||
func _collectionSQL(_ context: SQLGenerationContext) throws -> String
|
||||
}
|
||||
|
||||
/// SQLCollection is the protocol for types that can be checked for inclusion.
|
||||
public protocol SQLCollection: _SQLCollection {
|
||||
/// Returns an expression that check whether the collection contains
|
||||
/// the expression.
|
||||
func contains(_ value: SQLExpressible) -> SQLExpression
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionsArray
|
||||
|
||||
/// SQLExpressionsArray wraps an array of expressions
|
||||
///
|
||||
/// SQLExpressionsArray([1, 2, 3])
|
||||
///
|
||||
/// :nodoc:
|
||||
struct SQLExpressionsArray: SQLCollection {
|
||||
let expressions: [SQLExpression]
|
||||
|
||||
var _collectionExpressions: [SQLExpression]? { expressions }
|
||||
|
||||
func _collectionSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
try "("
|
||||
+ expressions
|
||||
.map { try $0._expressionSQL(context, wrappedInParenthesis: false) }
|
||||
.joined(separator: ", ")
|
||||
+ ")"
|
||||
}
|
||||
|
||||
func contains(_ value: SQLExpressible) -> SQLExpression {
|
||||
guard let expression = expressions.first else {
|
||||
return false.databaseValue
|
||||
}
|
||||
|
||||
// With SQLite, `expr IN (NULL)` never succeeds.
|
||||
//
|
||||
// We must not provide special handling of NULL, because we can not
|
||||
// guess if our `expressions` array contains a value evaluates to NULL.
|
||||
|
||||
if expressions.count == 1 {
|
||||
// Output `expr = value` instead of `expr IN (value)`, because it
|
||||
// looks nicer. And make sure we do not produce 'expr IS NULL'.
|
||||
return SQLExpressionEqual(.equal, value.sqlExpression, expression)
|
||||
}
|
||||
|
||||
return SQLExpressionContains(value, self)
|
||||
}
|
||||
|
||||
func _qualifiedCollection(with alias: TableAlias) -> SQLCollection {
|
||||
SQLExpressionsArray(expressions: expressions.map { $0._qualifiedExpression(with: alias) })
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLTableCollection
|
||||
|
||||
/// SQLTableCollection aims at generating `value IN table` expressions.
|
||||
///
|
||||
/// :nodoc:
|
||||
enum SQLTableCollection: SQLCollection {
|
||||
case tableName(String)
|
||||
|
||||
var _collectionExpressions: [SQLExpression]? { nil }
|
||||
|
||||
func _collectionSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
switch self {
|
||||
case let .tableName(tableName):
|
||||
func sql(_ context: SQLGenerationContext) throws -> String {
|
||||
switch impl {
|
||||
case let .array(expressions):
|
||||
return try "("
|
||||
+ expressions.map { try $0.sql(context) }.joined(separator: ", ")
|
||||
+ ")"
|
||||
|
||||
case let .subquery(subquery):
|
||||
return try "("
|
||||
+ subquery.sql(context)
|
||||
+ ")"
|
||||
|
||||
case let .table(tableName):
|
||||
return tableName.quotedDatabaseIdentifier
|
||||
}
|
||||
}
|
||||
|
||||
func contains(_ value: SQLExpressible) -> SQLExpression {
|
||||
return SQLExpressionContains(value, self)
|
||||
/// Returns an expression that check whether the collection contains
|
||||
/// the expression.
|
||||
func contains(_ value: SQLExpression) -> SQLExpression {
|
||||
switch impl {
|
||||
case .subquery,
|
||||
.table:
|
||||
return .in(value, self)
|
||||
|
||||
case let .array(expressions):
|
||||
guard let expression = expressions.first else {
|
||||
return false.sqlExpression
|
||||
}
|
||||
|
||||
// With SQLite, `expr IN (NULL)` never succeeds.
|
||||
//
|
||||
// We must not provide special handling of NULL, because we can not
|
||||
// guess if our `expressions` array contains a value evaluates to NULL.
|
||||
|
||||
if expressions.count == 1 {
|
||||
// Output `expr = value` instead of `expr IN (value)`, because it
|
||||
// looks nicer. And make sure we do not produce 'expr IS NULL'.
|
||||
return .compare(.equal, value, expression)
|
||||
}
|
||||
|
||||
return .in(value, self)
|
||||
}
|
||||
}
|
||||
|
||||
func _qualifiedCollection(with alias: TableAlias) -> SQLCollection { self }
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
// MARK: - SQLExpressible
|
||||
|
||||
/// `SQLExpressible` is the protocol for all types that can be used as an
|
||||
/// SQL expression.
|
||||
///
|
||||
/// It is adopted by protocols like `DatabaseValueConvertible`, and types
|
||||
/// like `Column`.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
public protocol SQLExpressible {
|
||||
/// Returns an SQL expression.
|
||||
var sqlExpression: SQLExpression { get }
|
||||
}
|
||||
|
||||
// MARK: - SQLSpecificExpressible
|
||||
|
||||
/// SQLSpecificExpressible is a protocol for all database-specific types that can
|
||||
/// be turned into an SQL expression. Types whose existence is not purely
|
||||
/// dedicated to the database should adopt the SQLExpressible protocol instead.
|
||||
///
|
||||
/// For example, Column is a type that only exists to help you build requests,
|
||||
/// and it adopts SQLSpecificExpressible.
|
||||
///
|
||||
/// On the other side, Int adopts SQLExpressible (via DatabaseValueConvertible).
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol SQLSpecificExpressible: SQLExpressible {
|
||||
// SQLExpressible can be adopted by Swift standard types, and user
|
||||
// types, through the DatabaseValueConvertible protocol which inherits
|
||||
// from SQLExpressible.
|
||||
//
|
||||
// For example, Int adopts SQLExpressible through
|
||||
// DatabaseValueConvertible.
|
||||
//
|
||||
// SQLSpecificExpressible, on the other side, is not adopted by any
|
||||
// Swift standard type or any user type. It is only adopted by GRDB types,
|
||||
// such as Column and SQLExpression.
|
||||
//
|
||||
// This separation lets us define functions and operators that do not
|
||||
// spill out. The three declarations below have no chance overloading a
|
||||
// Swift-defined operator, or a user-defined operator:
|
||||
//
|
||||
// - ==(SQLExpressible, SQLSpecificExpressible)
|
||||
// - ==(SQLSpecificExpressible, SQLExpressible)
|
||||
// - ==(SQLSpecificExpressible, SQLSpecificExpressible)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -6,7 +6,7 @@
|
||||
///
|
||||
/// When the schema does not define any foreign key, we can still infer complete
|
||||
/// mapping from partial information and primary keys.
|
||||
struct SQLForeignKeyRequest: Equatable {
|
||||
struct SQLForeignKeyRequest {
|
||||
let originTable: String
|
||||
let destinationTable: String
|
||||
let originColumns: [String]?
|
||||
@@ -88,6 +88,29 @@ typealias JoinMapping = [(left: String, right: String)]
|
||||
|
||||
extension ForeignKeyMapping {
|
||||
/// Orient the foreign key mapping for a SQL join.
|
||||
///
|
||||
/// - parameter originIsLeft: Whether the table at the origin of a
|
||||
/// foreign key is on the left of a JOIN clause.
|
||||
///
|
||||
/// For example, the two requests below use the same
|
||||
/// `ForeignKeyMapping` from `book.authorID` (origin of the foreign key)
|
||||
/// to `author.id` (destination).
|
||||
///
|
||||
/// In the first request, the book origin is on the left of the
|
||||
/// join clause:
|
||||
///
|
||||
/// // SELECT book.*, author.*
|
||||
/// // FROM book
|
||||
/// // JOIN author ON author.id = book.authorID
|
||||
/// Book.including(required: Book.author)
|
||||
///
|
||||
/// In the second request, the book origin is on the right of the
|
||||
/// join clause:
|
||||
///
|
||||
/// // SELECT author.*, book.*
|
||||
/// // FROM author
|
||||
/// // JOIN book ON book.authorID = author.id
|
||||
/// Author.including(required: Author.books)
|
||||
func joinMapping(originIsLeft: Bool) -> JoinMapping {
|
||||
if originIsLeft {
|
||||
return map { (left: $0.origin, right: $0.destination) }
|
||||
|
||||
@@ -5,7 +5,7 @@ extension DatabaseFunction {
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#sql-functions
|
||||
public func callAsFunction(_ arguments: SQLExpressible...) -> SQLExpression {
|
||||
SQLExpressionFunction(name, arguments: arguments.map(\.sqlExpression))
|
||||
.function(name, arguments.map(\.sqlExpression))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ extension DatabaseFunction {
|
||||
/// // ABS(amount)
|
||||
/// abs(Column("amount"))
|
||||
public func abs(_ value: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionFunction("ABS", arguments: value)
|
||||
.function("ABS", [value.sqlExpression])
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ public func abs(_ value: SQLSpecificExpressible) -> SQLExpression {
|
||||
/// // AVG(length)
|
||||
/// average(Column("length"))
|
||||
public func average(_ value: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionFunction("AVG", arguments: value)
|
||||
.function("AVG", [value.sqlExpression])
|
||||
}
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ public func average(_ value: SQLSpecificExpressible) -> SQLExpression {
|
||||
/// // COUNT(email)
|
||||
/// count(Column("email"))
|
||||
public func count(_ counted: SQLSelectable) -> SQLExpression {
|
||||
SQLExpressionCount(counted)
|
||||
.count(counted.sqlSelection)
|
||||
}
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ public func count(_ counted: SQLSelectable) -> SQLExpression {
|
||||
/// // COUNT(DISTINCT email)
|
||||
/// count(distinct: Column("email"))
|
||||
public func count(distinct value: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionCountDistinct(value.sqlExpression)
|
||||
.countDistinct(value.sqlExpression)
|
||||
}
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ public func count(distinct value: SQLSpecificExpressible) -> SQLExpression {
|
||||
/// // IFNULL(name, 'Anonymous')
|
||||
/// Column("name") ?? "Anonymous"
|
||||
public func ?? (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
|
||||
SQLExpressionFunction("IFNULL", arguments: lhs, rhs)
|
||||
.function("IFNULL", [lhs.sqlExpression, rhs.sqlExpression])
|
||||
}
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ public func ?? (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi
|
||||
/// // LENGTH(name)
|
||||
/// length(Column("name"))
|
||||
public func length(_ value: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionFunction("LENGTH", arguments: value)
|
||||
.function("LENGTH", [value.sqlExpression])
|
||||
}
|
||||
|
||||
|
||||
@@ -83,7 +83,7 @@ public func length(_ value: SQLSpecificExpressible) -> SQLExpression {
|
||||
/// // MAX(score)
|
||||
/// max(Column("score"))
|
||||
public func max(_ value: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionFunction("MAX", arguments: value)
|
||||
.function("MAX", [value.sqlExpression])
|
||||
}
|
||||
|
||||
|
||||
@@ -94,7 +94,7 @@ public func max(_ value: SQLSpecificExpressible) -> SQLExpression {
|
||||
/// // MIN(score)
|
||||
/// min(Column("score"))
|
||||
public func min(_ value: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionFunction("MIN", arguments: value)
|
||||
.function("MIN", [value.sqlExpression])
|
||||
}
|
||||
|
||||
|
||||
@@ -105,7 +105,7 @@ public func min(_ value: SQLSpecificExpressible) -> SQLExpression {
|
||||
/// // SUM(amount)
|
||||
/// sum(Column("amount"))
|
||||
public func sum(_ value: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionFunction("SUM", arguments: value)
|
||||
.function("SUM", [value.sqlExpression])
|
||||
}
|
||||
|
||||
|
||||
@@ -227,7 +227,7 @@ public enum SQLDateModifier: SQLSpecificExpressible {
|
||||
case utc
|
||||
|
||||
public var sqlExpression: SQLExpression {
|
||||
rawValue.databaseValue
|
||||
rawValue.sqlExpression
|
||||
}
|
||||
|
||||
var rawValue: String {
|
||||
@@ -274,7 +274,7 @@ public enum SQLDateModifier: SQLSpecificExpressible {
|
||||
///
|
||||
/// For more information, see https://www.sqlite.org/lang_datefunc.html
|
||||
public func julianDay(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression {
|
||||
SQLExpressionFunction("JULIANDAY", arguments: [value.sqlExpression] + modifiers.map(\.sqlExpression))
|
||||
.function("JULIANDAY", [value.sqlExpression] + modifiers.map(\.sqlExpression))
|
||||
}
|
||||
|
||||
// MARK: DATETIME(...)
|
||||
@@ -289,5 +289,5 @@ public func julianDay(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModif
|
||||
///
|
||||
/// For more information, see https://www.sqlite.org/lang_datefunc.html
|
||||
public func dateTime(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression {
|
||||
SQLExpressionFunction("DATETIME", arguments: [value.sqlExpression] + modifiers.map(\.sqlExpression))
|
||||
.function("DATETIME", [value.sqlExpression] + modifiers.map(\.sqlExpression))
|
||||
}
|
||||
@@ -1,27 +1,5 @@
|
||||
// MARK: - Egality and Identity Operators (=, <>, IS, IS NOT)
|
||||
|
||||
// Outputs "x = y" or "x IS NULL"
|
||||
private func isEqual(_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression {
|
||||
switch (lhs, rhs) {
|
||||
case let (lhs, rhs as DatabaseValue):
|
||||
switch rhs.storage {
|
||||
case .null:
|
||||
return SQLExpressionEqual(.is, lhs, rhs)
|
||||
default:
|
||||
return SQLExpressionEqual(.equal, lhs, rhs)
|
||||
}
|
||||
case let (lhs as DatabaseValue, rhs):
|
||||
switch lhs.storage {
|
||||
case .null:
|
||||
return SQLExpressionEqual(.is, rhs, lhs)
|
||||
default:
|
||||
return SQLExpressionEqual(.equal, lhs, rhs)
|
||||
}
|
||||
default:
|
||||
return SQLExpressionEqual(.equal, lhs, rhs)
|
||||
}
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `=` SQL operator.
|
||||
///
|
||||
/// // name = 'Arthur'
|
||||
@@ -32,7 +10,7 @@ private func isEqual(_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpressio
|
||||
/// // name IS NULL
|
||||
/// Column("name") == nil
|
||||
public func == (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression {
|
||||
isEqual(lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null)
|
||||
.equal(lhs.sqlExpression, rhs?.sqlExpression ?? .null)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `=` SQL operator.
|
||||
@@ -45,7 +23,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpress
|
||||
/// // name IS NULL
|
||||
/// Column("name").collating(.nocase) == nil
|
||||
public func == (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression {
|
||||
SQLExpressionCollate(lhs.expression == rhs, collationName: lhs.collationName)
|
||||
.collated(lhs.expression == rhs, lhs.collationName)
|
||||
}
|
||||
|
||||
/// An SQL expression that checks the boolean value of an expression.
|
||||
@@ -59,9 +37,9 @@ public func == (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpressi
|
||||
/// Column("validated") == false
|
||||
public func == (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression {
|
||||
if rhs {
|
||||
return lhs.sqlExpression._is(.true)
|
||||
return lhs.sqlExpression.is(.true)
|
||||
} else {
|
||||
return lhs.sqlExpression._is(.false)
|
||||
return lhs.sqlExpression.is(.false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,7 +53,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression {
|
||||
/// // name IS NULL
|
||||
/// nil == Column("name")
|
||||
public func == (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
isEqual(lhs?.sqlExpression ?? DatabaseValue.null, rhs.sqlExpression)
|
||||
.equal(lhs?.sqlExpression ?? .null, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `=` SQL operator.
|
||||
@@ -88,7 +66,7 @@ public func == (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpress
|
||||
/// // name IS NULL
|
||||
/// nil == Column("name").collating(.nocase)
|
||||
public func == (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression {
|
||||
SQLExpressionCollate(lhs == rhs.expression, collationName: rhs.collationName)
|
||||
.collated(lhs == rhs.expression, rhs.collationName)
|
||||
}
|
||||
|
||||
/// An SQL expression that checks the boolean value of an expression.
|
||||
@@ -102,9 +80,9 @@ public func == (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpressi
|
||||
/// false == Column("validated")
|
||||
public func == (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
if lhs {
|
||||
return rhs.sqlExpression._is(.true)
|
||||
return rhs.sqlExpression.is(.true)
|
||||
} else {
|
||||
return rhs.sqlExpression._is(.false)
|
||||
return rhs.sqlExpression.is(.false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,7 +91,7 @@ public func == (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
/// // email = login
|
||||
/// Column("email") == Column("login")
|
||||
public func == (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
isEqual(lhs.sqlExpression, rhs.sqlExpression)
|
||||
.equal(lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<>` SQL operator.
|
||||
@@ -207,7 +185,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL
|
||||
/// // name IS 'Arthur'
|
||||
/// Column("name") === "Arthur"
|
||||
public func === (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression {
|
||||
SQLExpressionEqual(.is, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null)
|
||||
.compare(.is, lhs.sqlExpression, rhs?.sqlExpression ?? .null)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `IS` SQL operator.
|
||||
@@ -215,7 +193,7 @@ public func === (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpres
|
||||
/// // name IS 'Arthur' COLLATE NOCASE
|
||||
/// Column("name").collating(.nocase) === "Arthur"
|
||||
public func === (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression {
|
||||
SQLExpressionCollate(lhs.expression === rhs, collationName: lhs.collationName)
|
||||
.collated(lhs.expression === rhs, lhs.collationName)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `IS` SQL operator.
|
||||
@@ -224,9 +202,9 @@ public func === (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpress
|
||||
/// "Arthur" === Column("name")
|
||||
public func === (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
if let lhs = lhs {
|
||||
return SQLExpressionEqual(.is, lhs.sqlExpression, rhs.sqlExpression)
|
||||
return .compare(.is, lhs.sqlExpression, rhs.sqlExpression)
|
||||
} else {
|
||||
return SQLExpressionEqual(.is, rhs.sqlExpression, DatabaseValue.null)
|
||||
return .compare(.is, rhs.sqlExpression, .null)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -235,7 +213,7 @@ public func === (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpres
|
||||
/// // name IS 'Arthur' COLLATE NOCASE
|
||||
/// "Arthur" === Column("name").collating(.nocase)
|
||||
public func === (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression {
|
||||
SQLExpressionCollate(lhs === rhs.expression, collationName: rhs.collationName)
|
||||
.collated(lhs === rhs.expression, rhs.collationName)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `IS` SQL operator.
|
||||
@@ -243,7 +221,7 @@ public func === (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpress
|
||||
/// // email IS login
|
||||
/// Column("email") === Column("login")
|
||||
public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionEqual(.is, lhs.sqlExpression, rhs.sqlExpression)
|
||||
.compare(.is, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `IS NOT` SQL operator.
|
||||
@@ -293,7 +271,7 @@ public func !== (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQ
|
||||
/// // score < 18
|
||||
/// Column("score") < 18
|
||||
public func < (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
|
||||
SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression)
|
||||
.binary(.lessThan, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<` SQL operator.
|
||||
@@ -301,7 +279,7 @@ public func < (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio
|
||||
/// // name < 'Arthur' COLLATE NOCASE
|
||||
/// Column("name").collating(.nocase) < "Arthur"
|
||||
public func < (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression {
|
||||
SQLExpressionCollate(lhs.expression < rhs, collationName: lhs.collationName)
|
||||
.collated(lhs.expression < rhs, lhs.collationName)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<` SQL operator.
|
||||
@@ -309,7 +287,7 @@ public func < (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression
|
||||
/// // 18 < score
|
||||
/// 18 < Column("score")
|
||||
public func < (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression)
|
||||
.binary(.lessThan, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<` SQL operator.
|
||||
@@ -317,7 +295,7 @@ public func < (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio
|
||||
/// // 'Arthur' < name COLLATE NOCASE
|
||||
/// "Arthur" < Column("name").collating(.nocase)
|
||||
public func < (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression {
|
||||
SQLExpressionCollate(lhs < rhs.expression, collationName: rhs.collationName)
|
||||
.collated(lhs < rhs.expression, rhs.collationName)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<` SQL operator.
|
||||
@@ -325,7 +303,7 @@ public func < (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression
|
||||
/// // width < height
|
||||
/// Column("width") < Column("height")
|
||||
public func < (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression)
|
||||
.binary(.lessThan, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<=` SQL operator.
|
||||
@@ -333,7 +311,7 @@ public func < (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE
|
||||
/// // score <= 18
|
||||
/// Column("score") <= 18
|
||||
public func <= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
|
||||
SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
.binary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<=` SQL operator.
|
||||
@@ -341,7 +319,7 @@ public func <= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi
|
||||
/// // name <= 'Arthur' COLLATE NOCASE
|
||||
/// Column("name").collating(.nocase) <= "Arthur"
|
||||
public func <= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression {
|
||||
SQLExpressionCollate(lhs.expression <= rhs, collationName: lhs.collationName)
|
||||
.collated(lhs.expression <= rhs, lhs.collationName)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<=` SQL operator.
|
||||
@@ -349,7 +327,7 @@ public func <= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpressio
|
||||
/// // 18 <= score
|
||||
/// 18 <= Column("score")
|
||||
public func <= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
.binary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<=` SQL operator.
|
||||
@@ -357,7 +335,7 @@ public func <= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi
|
||||
/// // 'Arthur' <= name COLLATE NOCASE
|
||||
/// "Arthur" <= Column("name").collating(.nocase)
|
||||
public func <= (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression {
|
||||
SQLExpressionCollate(lhs <= rhs.expression, collationName: rhs.collationName)
|
||||
.collated(lhs <= rhs.expression, rhs.collationName)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<=` SQL operator.
|
||||
@@ -365,7 +343,7 @@ public func <= (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpressio
|
||||
/// // width <= height
|
||||
/// Column("width") <= Column("height")
|
||||
public func <= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
.binary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `>` SQL operator.
|
||||
@@ -373,7 +351,7 @@ public func <= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL
|
||||
/// // score > 18
|
||||
/// Column("score") > 18
|
||||
public func > (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
|
||||
SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression)
|
||||
.binary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `>` SQL operator.
|
||||
@@ -381,7 +359,7 @@ public func > (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio
|
||||
/// // name > 'Arthur' COLLATE NOCASE
|
||||
/// Column("name").collating(.nocase) > "Arthur"
|
||||
public func > (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression {
|
||||
SQLExpressionCollate(lhs.expression > rhs, collationName: lhs.collationName)
|
||||
.collated(lhs.expression > rhs, lhs.collationName)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `>` SQL operator.
|
||||
@@ -389,7 +367,7 @@ public func > (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression
|
||||
/// // 18 > score
|
||||
/// 18 > Column("score")
|
||||
public func > (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression)
|
||||
.binary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `>` SQL operator.
|
||||
@@ -397,7 +375,7 @@ public func > (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio
|
||||
/// // 'Arthur' > name COLLATE NOCASE
|
||||
/// "Arthur" > Column("name").collating(.nocase)
|
||||
public func > (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression {
|
||||
SQLExpressionCollate(lhs > rhs.expression, collationName: rhs.collationName)
|
||||
.collated(lhs > rhs.expression, rhs.collationName)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `>` SQL operator.
|
||||
@@ -405,7 +383,7 @@ public func > (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression
|
||||
/// // width > height
|
||||
/// Column("width") > Column("height")
|
||||
public func > (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression)
|
||||
.binary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `>=` SQL operator.
|
||||
@@ -413,7 +391,7 @@ public func > (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE
|
||||
/// // score >= 18
|
||||
/// Column("score") >= 18
|
||||
public func >= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
|
||||
SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
.binary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `>=` SQL operator.
|
||||
@@ -421,7 +399,7 @@ public func >= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi
|
||||
/// // name >= 'Arthur' COLLATE NOCASE
|
||||
/// Column("name").collating(.nocase) >= "Arthur"
|
||||
public func >= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression {
|
||||
SQLExpressionCollate(lhs.expression >= rhs, collationName: lhs.collationName)
|
||||
.collated(lhs.expression >= rhs, lhs.collationName)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `>=` SQL operator.
|
||||
@@ -429,7 +407,7 @@ public func >= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpressio
|
||||
/// // 18 >= score
|
||||
/// 18 >= Column("score")
|
||||
public func >= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
.binary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `>=` SQL operator.
|
||||
@@ -437,7 +415,7 @@ public func >= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi
|
||||
/// // 'Arthur' >= name COLLATE NOCASE
|
||||
/// "Arthur" >= Column("name").collating(.nocase)
|
||||
public func >= (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression {
|
||||
SQLExpressionCollate(lhs >= rhs.expression, collationName: rhs.collationName)
|
||||
.collated(lhs >= rhs.expression, rhs.collationName)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `>=` SQL operator.
|
||||
@@ -445,7 +423,7 @@ public func >= (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpressio
|
||||
/// // width >= height
|
||||
/// Column("width") >= Column("height")
|
||||
public func >= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
.binary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
// MARK: - Inclusion Operators (BETWEEN, IN)
|
||||
@@ -474,7 +452,10 @@ extension ClosedRange where Bound: SQLExpressible {
|
||||
/// // email BETWEEN 'A' AND 'B'
|
||||
/// ("A"..."B").contains(Column("email"))
|
||||
public func contains(_ element: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionBetween(element.sqlExpression, lowerBound.sqlExpression, upperBound.sqlExpression)
|
||||
.between(
|
||||
expression: element.sqlExpression,
|
||||
lowerBound: lowerBound.sqlExpression,
|
||||
upperBound: upperBound.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that checks the inclusion of an expression in a range.
|
||||
@@ -482,7 +463,7 @@ extension ClosedRange where Bound: SQLExpressible {
|
||||
/// // email BETWEEN 'A' AND 'B' COLLATE NOCASE
|
||||
/// ("A"..."B").contains(Column("email").collating(.nocase))
|
||||
public func contains(_ element: SQLCollatedExpression) -> SQLExpression {
|
||||
SQLExpressionCollate(contains(element.expression), collationName: element.collationName)
|
||||
.collated(contains(element.expression), element.collationName)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -502,7 +483,10 @@ extension CountableClosedRange where Bound: SQLExpressible {
|
||||
/// // id BETWEEN 1 AND 10
|
||||
/// (1...10).contains(Column("id"))
|
||||
public func contains(_ element: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionBetween(element.sqlExpression, lowerBound.sqlExpression, upperBound.sqlExpression)
|
||||
.between(
|
||||
expression: element.sqlExpression,
|
||||
lowerBound: lowerBound.sqlExpression,
|
||||
upperBound: upperBound.sqlExpression)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -513,16 +497,16 @@ 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)
|
||||
SQLCollection.array(map(\.sqlExpression)).contains(element.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that checks the inclusion of an expression in
|
||||
/// a sequence.
|
||||
///
|
||||
/// // name IN ('A', 'B') COLLATE NOCASE
|
||||
/// // (name COLLATE NOCASE) IN ('A', 'B')
|
||||
/// ["A", "B"].contains(Column("name").collating(.nocase))
|
||||
public func contains(_ element: SQLCollatedExpression) -> SQLExpression {
|
||||
SQLExpressionCollate(contains(element.expression), collationName: element.collationName)
|
||||
SQLCollection.array(map(\.sqlExpression)).contains(element.sqlExpression)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -533,16 +517,16 @@ 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)
|
||||
SQLCollection.array(map(\.sqlExpression)).contains(element.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that checks the inclusion of an expression in
|
||||
/// a sequence.
|
||||
///
|
||||
/// // name IN ('A', 'B') COLLATE NOCASE
|
||||
/// // (name COLLATE NOCASE) IN ('A', 'B')
|
||||
/// ["A", "B"].contains(Column("name").collating(.nocase))
|
||||
public func contains(_ element: SQLCollatedExpression) -> SQLExpression {
|
||||
SQLExpressionCollate(contains(element.expression), collationName: element.collationName)
|
||||
SQLCollection.array(map(\.sqlExpression)).contains(element.sqlExpression)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -554,7 +538,7 @@ extension Sequence where Self.Iterator.Element == SQLExpressible {
|
||||
/// // width * 2
|
||||
/// Column("width") * 2
|
||||
public func * (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
|
||||
SQLExpressionAssociativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
.associativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
}
|
||||
|
||||
/// An SQL arithmetic multiplication.
|
||||
@@ -562,7 +546,7 @@ public func * (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio
|
||||
/// // 2 * width
|
||||
/// 2 * Column("width")
|
||||
public func * (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionAssociativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
.associativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
}
|
||||
|
||||
/// An SQL arithmetic multiplication.
|
||||
@@ -570,7 +554,7 @@ public func * (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio
|
||||
/// // width * height
|
||||
/// Column("width") * Column("height")
|
||||
public func * (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionAssociativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
.associativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
}
|
||||
|
||||
/// An SQL arithmetic division.
|
||||
@@ -578,7 +562,7 @@ public func * (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE
|
||||
/// // width / 2
|
||||
/// Column("width") / 2
|
||||
public func / (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
|
||||
SQLExpressionBinary(.divide, lhs.sqlExpression, rhs.sqlExpression)
|
||||
.binary(.divide, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL arithmetic division.
|
||||
@@ -586,7 +570,7 @@ public func / (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio
|
||||
/// // 2 / width
|
||||
/// 2 / Column("width")
|
||||
public func / (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionBinary(.divide, lhs.sqlExpression, rhs.sqlExpression)
|
||||
.binary(.divide, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL arithmetic division.
|
||||
@@ -594,7 +578,7 @@ public func / (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio
|
||||
/// // width / height
|
||||
/// Column("width") / Column("height")
|
||||
public func / (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionBinary(.divide, lhs.sqlExpression, rhs.sqlExpression)
|
||||
.binary(.divide, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL arithmetic addition.
|
||||
@@ -602,7 +586,7 @@ public func / (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE
|
||||
/// // width + 2
|
||||
/// Column("width") + 2
|
||||
public func + (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
|
||||
SQLExpressionAssociativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
.associativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
}
|
||||
|
||||
/// An SQL arithmetic addition.
|
||||
@@ -610,7 +594,7 @@ public func + (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio
|
||||
/// // 2 + width
|
||||
/// 2 + Column("width")
|
||||
public func + (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionAssociativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
.associativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
}
|
||||
|
||||
/// An SQL arithmetic addition.
|
||||
@@ -618,7 +602,7 @@ public func + (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio
|
||||
/// // width + height
|
||||
/// Column("width") + Column("height")
|
||||
public func + (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionAssociativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
.associativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
}
|
||||
|
||||
/// A negated SQL arithmetic expression.
|
||||
@@ -626,7 +610,7 @@ public func + (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE
|
||||
/// // -width
|
||||
/// -Column("width")
|
||||
public prefix func - (value: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionUnary(.minus, value.sqlExpression)
|
||||
.unary(.minus, value.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL arithmetic substraction.
|
||||
@@ -634,7 +618,7 @@ public prefix func - (value: SQLSpecificExpressible) -> SQLExpression {
|
||||
/// // width - 2
|
||||
/// Column("width") - 2
|
||||
public func - (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
|
||||
SQLExpressionBinary(.subtract, lhs.sqlExpression, rhs.sqlExpression)
|
||||
.binary(.subtract, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL arithmetic substraction.
|
||||
@@ -642,7 +626,7 @@ public func - (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio
|
||||
/// // 2 - width
|
||||
/// 2 - Column("width")
|
||||
public func - (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionBinary(.subtract, lhs.sqlExpression, rhs.sqlExpression)
|
||||
.binary(.subtract, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL arithmetic substraction.
|
||||
@@ -650,7 +634,7 @@ public func - (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio
|
||||
/// // width - height
|
||||
/// Column("width") - Column("height")
|
||||
public func - (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionBinary(.subtract, lhs.sqlExpression, rhs.sqlExpression)
|
||||
.binary(.subtract, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
|
||||
@@ -661,7 +645,7 @@ public func - (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE
|
||||
/// // favorite AND 0
|
||||
/// Column("favorite") && false
|
||||
public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
|
||||
SQLExpressionAssociativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
.associativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
}
|
||||
|
||||
/// A logical SQL expression with the `AND` SQL operator.
|
||||
@@ -669,7 +653,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi
|
||||
/// // 0 AND favorite
|
||||
/// false && Column("favorite")
|
||||
public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionAssociativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
.associativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
}
|
||||
|
||||
/// A logical SQL expression with the `AND` SQL operator.
|
||||
@@ -677,7 +661,7 @@ public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi
|
||||
/// // email IS NOT NULL AND favorite
|
||||
/// Column("email") != nil && Column("favorite")
|
||||
public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionAssociativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
.associativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
}
|
||||
|
||||
/// A logical SQL expression with the `OR` SQL operator.
|
||||
@@ -685,7 +669,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL
|
||||
/// // favorite OR 1
|
||||
/// Column("favorite") || true
|
||||
public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
|
||||
SQLExpressionAssociativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
.associativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
}
|
||||
|
||||
/// A logical SQL expression with the `OR` SQL operator.
|
||||
@@ -693,7 +677,7 @@ public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi
|
||||
/// // 0 OR favorite
|
||||
/// true || Column("favorite")
|
||||
public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionAssociativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
.associativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
}
|
||||
|
||||
/// A logical SQL expression with the `OR` SQL operator.
|
||||
@@ -701,7 +685,7 @@ public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi
|
||||
/// // email IS NULL OR hidden
|
||||
/// Column("email") == nil || Column("hidden")
|
||||
public func || (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionAssociativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
.associativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
}
|
||||
|
||||
/// A negated logical SQL expression with the `NOT` SQL operator.
|
||||
@@ -714,7 +698,7 @@ public func || (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL
|
||||
/// // id NOT BETWEEN 1 AND 10
|
||||
/// !((1...10).contains(Column("id")))
|
||||
public prefix func ! (value: SQLSpecificExpressible) -> SQLExpression {
|
||||
value.sqlExpression._is(.falsey)
|
||||
value.sqlExpression.is(.falsey)
|
||||
}
|
||||
|
||||
// MARK: - Like Operator
|
||||
@@ -727,6 +711,6 @@ extension SQLSpecificExpressible {
|
||||
/// // email LIKE '%@example.com"
|
||||
/// Column("email").like("%@example.com")
|
||||
public func like(_ pattern: SQLExpressible) -> SQLExpression {
|
||||
SQLExpressionBinary(.like, self, pattern)
|
||||
.binary(.like, sqlExpression, pattern.sqlExpression)
|
||||
}
|
||||
}
|
||||
@@ -1,88 +1,130 @@
|
||||
/// Implementation details of `SQLOrderingTerm`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol _SQLOrderingTerm {
|
||||
/// The ordering term, reversed
|
||||
var _reversed: SQLOrderingTerm { get }
|
||||
/// The type that can be used as an SQL ordering term, as described at
|
||||
/// https://www.sqlite.org/syntax/ordering-term.html
|
||||
public struct SQLOrdering {
|
||||
private var impl: Impl
|
||||
|
||||
/// Returns a qualified ordering
|
||||
func _qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm
|
||||
private enum Impl {
|
||||
/// An expression
|
||||
///
|
||||
/// ORDER BY score
|
||||
case expression(SQLExpression)
|
||||
|
||||
/// An ascending expression
|
||||
///
|
||||
/// ORDER BY score ASC
|
||||
case asc(SQLExpression)
|
||||
|
||||
/// An descending expression
|
||||
///
|
||||
/// ORDER BY score DESC
|
||||
case desc(SQLExpression)
|
||||
|
||||
/// Only available from SQLite 3.30.0
|
||||
case ascNullsLast(SQLExpression)
|
||||
|
||||
/// Only available from SQLite 3.30.0
|
||||
case descNullsFirst(SQLExpression)
|
||||
|
||||
/// A literal SQL ordering
|
||||
case literal(SQLLiteral)
|
||||
}
|
||||
|
||||
/// Returns the SQL that feeds the `ORDER BY` clause.
|
||||
///
|
||||
/// - parameter context: An SQL generation context which accepts
|
||||
/// statement arguments.
|
||||
func _orderingTermSQL(_ context: SQLGenerationContext) throws -> String
|
||||
static func expression(_ expression: SQLExpression) -> SQLOrdering {
|
||||
self.init(impl: .expression(expression))
|
||||
}
|
||||
|
||||
static func asc(_ expression: SQLExpression) -> SQLOrdering {
|
||||
self.init(impl: .asc(expression))
|
||||
}
|
||||
|
||||
static func desc(_ expression: SQLExpression) -> SQLOrdering {
|
||||
self.init(impl: .desc(expression))
|
||||
}
|
||||
|
||||
static func ascNullsLast(_ expression: SQLExpression) -> SQLOrdering {
|
||||
self.init(impl: .ascNullsLast(expression))
|
||||
}
|
||||
|
||||
static func descNullsFirst(_ expression: SQLExpression) -> SQLOrdering {
|
||||
self.init(impl: .descNullsFirst(expression))
|
||||
}
|
||||
|
||||
static func literal(_ sqlLiteral: SQLLiteral) -> SQLOrdering {
|
||||
self.init(impl: .literal(sqlLiteral))
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLOrdering {
|
||||
func sql(_ context: SQLGenerationContext) throws -> String {
|
||||
switch impl {
|
||||
case .expression(let expression):
|
||||
return try expression.sql(context)
|
||||
case .asc(let expression):
|
||||
return try expression.sql(context) + " ASC"
|
||||
case .desc(let expression):
|
||||
return try expression.sql(context) + " DESC"
|
||||
case .ascNullsLast(let expression):
|
||||
return try expression.sql(context) + " ASC NULLS LAST"
|
||||
case .descNullsFirst(let expression):
|
||||
return try expression.sql(context) + " DESC NULLS FIRST"
|
||||
case .literal(let literal):
|
||||
return try literal.sql(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLOrdering {
|
||||
func qualified(with alias: TableAlias) -> SQLOrdering {
|
||||
switch impl {
|
||||
case .expression(let expression):
|
||||
return .expression(expression.qualified(with: alias))
|
||||
case .asc(let expression):
|
||||
return .asc(expression.qualified(with: alias))
|
||||
case .desc(let expression):
|
||||
return .desc(expression.qualified(with: alias))
|
||||
case .ascNullsLast(let expression):
|
||||
return .ascNullsLast(expression.qualified(with: alias))
|
||||
case .descNullsFirst(let expression):
|
||||
return .descNullsFirst(expression.qualified(with: alias))
|
||||
case .literal(let literal):
|
||||
return .literal(literal.qualified(with: alias))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLOrdering {
|
||||
var reversed: SQLOrdering {
|
||||
switch impl {
|
||||
case .expression(let expression):
|
||||
return .desc(expression)
|
||||
case .asc(let expression):
|
||||
return .desc(expression)
|
||||
case .desc(let expression):
|
||||
return .asc(expression)
|
||||
case .ascNullsLast(let expression):
|
||||
return .descNullsFirst(expression)
|
||||
case .descNullsFirst(let expression):
|
||||
return .ascNullsLast(expression)
|
||||
case .literal:
|
||||
fatalError("""
|
||||
Ordering literals can't be reversed. \
|
||||
To resolve this error, order by expression literals instead.
|
||||
""")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLOrderingTerm
|
||||
|
||||
/// The protocol for all types that can be used as an SQL ordering term, as
|
||||
/// described at https://www.sqlite.org/syntax/ordering-term.html
|
||||
public protocol SQLOrderingTerm: _SQLOrderingTerm { }
|
||||
|
||||
/// :nodoc:
|
||||
enum SQLOrdering: SQLOrderingTerm, Refinable {
|
||||
case asc(SQLExpression)
|
||||
case desc(SQLExpression)
|
||||
|
||||
// Only available from SQLite 3.30.0. This enum is not public, so those
|
||||
// cases don't harm as long as we don't expose them through public APIs.
|
||||
case ascNullsLast(SQLExpression)
|
||||
case descNullsFirst(SQLExpression)
|
||||
|
||||
var expression: SQLExpression {
|
||||
get {
|
||||
switch self {
|
||||
case .asc(let expression):
|
||||
return expression
|
||||
case .desc(let expression):
|
||||
return expression
|
||||
case .ascNullsLast(let expression):
|
||||
return expression
|
||||
case .descNullsFirst(let expression):
|
||||
return expression
|
||||
}
|
||||
}
|
||||
set {
|
||||
switch self {
|
||||
case .asc:
|
||||
self = .asc(newValue)
|
||||
case .desc:
|
||||
self = .desc(newValue)
|
||||
case .ascNullsLast:
|
||||
self = .ascNullsLast(newValue)
|
||||
case .descNullsFirst:
|
||||
self = .descNullsFirst(newValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func _orderingTermSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
switch self {
|
||||
case .asc(let expression):
|
||||
return try expression._expressionSQL(context, wrappedInParenthesis: false) + " ASC"
|
||||
case .desc(let expression):
|
||||
return try expression._expressionSQL(context, wrappedInParenthesis: false) + " DESC"
|
||||
case .ascNullsLast(let expression):
|
||||
return try expression._expressionSQL(context, wrappedInParenthesis: false) + " ASC NULLS LAST"
|
||||
case .descNullsFirst(let expression):
|
||||
return try expression._expressionSQL(context, wrappedInParenthesis: false) + " DESC NULLS FIRST"
|
||||
}
|
||||
}
|
||||
|
||||
func _qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm {
|
||||
map(\.expression) { $0._qualifiedExpression(with: alias) }
|
||||
}
|
||||
|
||||
var _reversed: SQLOrderingTerm {
|
||||
switch self {
|
||||
case .asc(let expression):
|
||||
return SQLOrdering.desc(expression)
|
||||
case .desc(let expression):
|
||||
return SQLOrdering.asc(expression)
|
||||
case .ascNullsLast(let expression):
|
||||
return SQLOrdering.descNullsFirst(expression)
|
||||
case .descNullsFirst(let expression):
|
||||
return SQLOrdering.ascNullsLast(expression)
|
||||
}
|
||||
}
|
||||
public protocol SQLOrderingTerm {
|
||||
/// Returns an SQL ordering.
|
||||
var sqlOrdering: SQLOrdering { get }
|
||||
}
|
||||
|
||||
extension SQLOrdering: SQLOrderingTerm {
|
||||
// Not a real deprecation, just a usage warning
|
||||
@available(*, deprecated, message: "Already QLOrdering:")
|
||||
public var sqlOrdering: SQLOrdering { self }
|
||||
}
|
||||
@@ -5,10 +5,7 @@ struct SQLQuery {
|
||||
var relation: SQLRelation
|
||||
var isDistinct: 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 havingExpressionPromise: DatabasePromise<SQLExpression?> = DatabasePromise(value: nil)
|
||||
var limit: SQLLimit?
|
||||
var ctes: OrderedDictionary<String, SQLCTE> = [:]
|
||||
}
|
||||
@@ -22,31 +19,34 @@ extension SQLQuery: Refinable {
|
||||
with(\.limit, SQLLimit(limit: limit, offset: offset))
|
||||
}
|
||||
|
||||
func qualified(with alias: TableAlias) -> Self {
|
||||
// We do not need to qualify group and having clauses. They will be
|
||||
// in SQLQueryGenerator.init()
|
||||
map(\.relation) { $0.qualified(with: alias) }
|
||||
func aliased(_ alias: TableAlias) -> Self {
|
||||
map(\.relation) { $0.aliased(alias) }
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLQuery: SelectionRequest {
|
||||
func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
|
||||
extension SQLQuery {
|
||||
func select(_ selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
|
||||
map(\.relation) { $0.select(selection) }
|
||||
}
|
||||
|
||||
func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
|
||||
// Convenience
|
||||
func select(_ expressions: SQLExpression...) -> Self {
|
||||
select { _ in expressions.map { .expression($0) } }
|
||||
}
|
||||
|
||||
func annotated(with selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
|
||||
map(\.relation) { $0.annotated(with: selection) }
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLQuery: FilteredRequest {
|
||||
func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self {
|
||||
extension SQLQuery {
|
||||
func filter(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
|
||||
map(\.relation) { $0.filter(predicate) }
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLQuery: OrderedRequest {
|
||||
func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self {
|
||||
extension SQLQuery {
|
||||
func order(_ orderings: @escaping (Database) throws -> [SQLOrdering]) -> Self {
|
||||
map(\.relation) { $0.order(orderings) }
|
||||
}
|
||||
|
||||
@@ -59,21 +59,25 @@ extension SQLQuery: OrderedRequest {
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLQuery: AggregatingRequest {
|
||||
func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self {
|
||||
with(\.groupPromise, DatabasePromise { db in try expressions(db).map(\.sqlExpression) })
|
||||
extension SQLQuery {
|
||||
func group(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self {
|
||||
with(\.groupPromise, DatabasePromise(expressions))
|
||||
}
|
||||
|
||||
func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self {
|
||||
map(\.havingExpressionsPromise) { havingExpressionsPromise in
|
||||
func having(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
|
||||
map(\.havingExpressionPromise) { promise in
|
||||
DatabasePromise { db in
|
||||
try havingExpressionsPromise.resolve(db) + [predicate(db).sqlExpression]
|
||||
if let filter = try promise.resolve(db) {
|
||||
return try filter && predicate(db)
|
||||
} else {
|
||||
return try predicate(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLQuery: _JoinableRequest {
|
||||
extension SQLQuery{
|
||||
func _including(all association: _SQLAssociation) -> Self {
|
||||
map(\.relation) { $0._including(all: association) }
|
||||
}
|
||||
@@ -112,16 +116,16 @@ extension SQLQuery {
|
||||
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 {
|
||||
guard let count = selection[0].count(distinct: isDistinct) else {
|
||||
return try fetchTrivialCount(db)
|
||||
}
|
||||
var countQuery = self.unordered()
|
||||
countQuery.isDistinct = false
|
||||
switch count {
|
||||
case .all:
|
||||
countQuery = countQuery.select(SQLExpressionCount(AllColumns()))
|
||||
countQuery = countQuery.select(.count(.allColumns))
|
||||
case .distinct(let expression):
|
||||
countQuery = countQuery.select(SQLExpressionCountDistinct(expression))
|
||||
countQuery = countQuery.select(.countDistinct(expression))
|
||||
}
|
||||
return try QueryInterfaceRequest(query: countQuery).fetchOne(db)!
|
||||
} else {
|
||||
@@ -134,15 +138,14 @@ extension SQLQuery {
|
||||
// SELECT expr1, expr2, ... FROM tableName ...
|
||||
// ->
|
||||
// SELECT COUNT(*) FROM tableName ...
|
||||
let countQuery = unordered().select(SQLExpressionCount(AllColumns()))
|
||||
let countQuery = unordered().select(SQLExpression.count(.allColumns))
|
||||
return try QueryInterfaceRequest(query: countQuery).fetchOne(db)!
|
||||
}
|
||||
}
|
||||
|
||||
// SELECT COUNT(*) FROM (self)
|
||||
func fetchTrivialCount(_ db: Database) throws -> Int {
|
||||
let request = QueryInterfaceRequest<Void>(query: unordered())
|
||||
let countRequest: SQLRequest<Int> = "SELECT COUNT(*) FROM (\(request))"
|
||||
let countRequest: SQLRequest<Int> = "SELECT COUNT(*) FROM (\(SQLSubquery.query(unordered())))"
|
||||
return try countRequest.fetchOne(db)!
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,21 +13,19 @@
|
||||
/// • selection
|
||||
///
|
||||
/// Other SQL clauses such as GROUP BY, LIMIT are defined one level up, in the
|
||||
/// SQLQuery type.
|
||||
/// `SQLQuery` type.
|
||||
///
|
||||
/// ## Promises
|
||||
///
|
||||
/// Filter and ordering are actually "promises", which are only resolved
|
||||
/// when a database connection is available. This is how we can implement
|
||||
/// requests such as `Record.filter(key: 1)` or `Record.orderByPrimaryKey()`:
|
||||
/// both need a database connection in order to introspect the primary key.
|
||||
/// Selection, filter, and ordering are "promises" which are resolved when a
|
||||
/// database connection is available. This is how we can implement requests such
|
||||
/// as `Record.filter(key: 1)` or `Record.orderByPrimaryKey()`: both need a
|
||||
/// database connection in order to introspect the primary key. For example:
|
||||
///
|
||||
/// // SELECT * FROM player
|
||||
/// // WHERE continent = 'EU'
|
||||
/// // ORDER BY code -- primary key infered from the database schema
|
||||
/// Country
|
||||
/// .filter(Column("continent") == "EU")
|
||||
/// .orderByPrimaryKey()
|
||||
/// // SELECT * FROM country ORDER BY code
|
||||
/// // ~~~~~~~~~~~~~
|
||||
/// // primary key infered from the database schema
|
||||
/// Country.orderByPrimaryKey()
|
||||
///
|
||||
/// ## Children
|
||||
///
|
||||
@@ -74,31 +72,27 @@
|
||||
/// // JOIN author ON author.id = book.id AND author.country = 'FR'
|
||||
/// Book.including(required: Book.author.filter(Column("country") == "FR"))
|
||||
///
|
||||
/// - `.allPrefetched`:
|
||||
/// - `.all`:
|
||||
///
|
||||
/// Such children are prefetched using several SQL requests:
|
||||
/// Such children are prefetched using an extra SQL request:
|
||||
///
|
||||
/// // SELECT * FROM countries WHERE continent = 'EU'
|
||||
/// // SELECT * FROM passport WHERE countryCode IN ('BE', 'DE', 'FR', ...)
|
||||
/// Country
|
||||
/// .filter(Column("continent") == "EU")
|
||||
/// .including(all: Country.passports)
|
||||
/// // SELECT * FROM countries;
|
||||
/// // SELECT * FROM passport
|
||||
/// // WHERE countryCode IN ('BE', 'DE', 'FR', ...);
|
||||
/// Country.including(all: Country.passports)
|
||||
///
|
||||
/// - `.allNotPrefetched`:
|
||||
/// - `.bridge`:
|
||||
///
|
||||
/// Such children are not joined, and not prefetched. They are used as
|
||||
/// intermediate children towards a prefetched child. In the example
|
||||
/// below, the country relation has a `.allNotPrefetched` child to
|
||||
/// passports, and the passport relation has a `.allPrefetched` child
|
||||
/// to citizens.
|
||||
/// below, the country relation has a `.bridge` child to passports, and the
|
||||
/// passport relation has an `.all` child to citizens.
|
||||
///
|
||||
/// // SELECT * FROM countries WHERE continent = 'EU'
|
||||
/// // SELECT * FROM countries;
|
||||
/// // SELECT citizens.* FROM citizens
|
||||
/// // JOIN passport ON passport.citizenId = citizens.id
|
||||
/// // AND passport.countryCode IN ('BE', 'DE', 'FR', ...)
|
||||
/// Country
|
||||
/// .filter(Column("continent") == "EU")
|
||||
/// .including(all: Country.citizens)
|
||||
/// // AND passport.countryCode IN ('BE', 'DE', 'FR', ...);
|
||||
/// Country.including(all: Country.citizens)
|
||||
struct SQLRelation {
|
||||
struct Child: Refinable {
|
||||
enum Kind {
|
||||
@@ -107,18 +101,9 @@ struct SQLRelation {
|
||||
// Record.including(required: association)
|
||||
case oneRequired
|
||||
// Record.including(all: association)
|
||||
case allPrefetched
|
||||
case all
|
||||
// Record.including(all: associationThroughPivot)
|
||||
case allNotPrefetched
|
||||
|
||||
var isSingular: Bool {
|
||||
switch self {
|
||||
case .oneOptional, .oneRequired:
|
||||
return true
|
||||
case .allPrefetched, .allNotPrefetched:
|
||||
return false
|
||||
}
|
||||
}
|
||||
case bridge
|
||||
}
|
||||
|
||||
var kind: Kind
|
||||
@@ -133,7 +118,7 @@ struct SQLRelation {
|
||||
switch kind {
|
||||
case .oneOptional, .oneRequired:
|
||||
return true
|
||||
case .allPrefetched, .allNotPrefetched:
|
||||
case .all, .bridge:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -145,7 +130,7 @@ struct SQLRelation {
|
||||
switch kind {
|
||||
case .oneOptional, .oneRequired:
|
||||
cardinality = .toOne
|
||||
case .allPrefetched, .allNotPrefetched:
|
||||
case .all, .bridge:
|
||||
cardinality = .toMany
|
||||
}
|
||||
|
||||
@@ -158,20 +143,18 @@ struct SQLRelation {
|
||||
}
|
||||
|
||||
var source: SQLSource
|
||||
var selectionPromise: DatabasePromise<[SQLSelectable]> = DatabasePromise(value: [])
|
||||
// Filter is an array of expressions that we'll join with the AND operator.
|
||||
// This gives nicer output in generated SQL: `(a AND b AND c)` instead of
|
||||
// `((a AND b) AND c)`.
|
||||
var filtersPromise: DatabasePromise<[SQLExpression]> = DatabasePromise(value: [])
|
||||
var selectionPromise: DatabasePromise<[SQLSelection]> = DatabasePromise(value: [])
|
||||
var filterPromise: DatabasePromise<SQLExpression?> = DatabasePromise(value: nil)
|
||||
var ordering: SQLRelation.Ordering = SQLRelation.Ordering()
|
||||
var children: OrderedDictionary<String, Child> = [:]
|
||||
|
||||
/// All prefetched associations (`including(all:)`), recursively
|
||||
var prefetchedAssociations: [_SQLAssociation] {
|
||||
children.flatMap { key, child -> [_SQLAssociation] in
|
||||
switch child.kind {
|
||||
case .allPrefetched:
|
||||
case .all:
|
||||
return [child.makeAssociationForKey(key)]
|
||||
case .oneOptional, .oneRequired, .allNotPrefetched:
|
||||
case .oneOptional, .oneRequired, .bridge:
|
||||
return child.relation.prefetchedAssociations.map { association in
|
||||
// Remove redundant pivot child
|
||||
let pivotKey = association.pivot.keyName
|
||||
@@ -190,7 +173,7 @@ extension SQLRelation {
|
||||
/// Convenience factory methods which selects all rows from a table.
|
||||
static func all(
|
||||
fromTable tableName: String,
|
||||
selection: @escaping (Database) -> [SQLSelectable] = { _ in [AllColumns()] })
|
||||
selection: @escaping (Database) -> [SQLSelection] = { _ in [.allColumns] })
|
||||
-> Self
|
||||
{
|
||||
SQLRelation(
|
||||
@@ -200,21 +183,27 @@ extension SQLRelation {
|
||||
}
|
||||
|
||||
extension SQLRelation: Refinable {
|
||||
func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
|
||||
func select(_ selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
|
||||
with(\.selectionPromise, DatabasePromise(selection))
|
||||
}
|
||||
|
||||
// Convenience
|
||||
func select(_ selection: [SQLSelectable]) -> Self {
|
||||
func select(_ selection: [SQLSelection]) -> Self {
|
||||
select { _ in selection }
|
||||
}
|
||||
|
||||
/// Removes all selections from chidren
|
||||
func selectOnly(_ selection: [SQLSelectable]) -> Self {
|
||||
select(selection).map(\.children, { $0.mapValues { $0.map(\.relation, { $0.selectOnly([]) }) } })
|
||||
func selectOnly(_ selection: [SQLSelection]) -> Self {
|
||||
self
|
||||
.select(selection)
|
||||
.map(\.children) { children in
|
||||
children.mapValues { child in
|
||||
child.map(\.relation) { $0.selectOnly([]) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
|
||||
func annotated(with selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
|
||||
map(\.selectionPromise) { selectionPromise in
|
||||
DatabasePromise { db in
|
||||
try selectionPromise.resolve(db) + selection(db)
|
||||
@@ -223,11 +212,28 @@ extension SQLRelation: Refinable {
|
||||
}
|
||||
|
||||
// Convenience
|
||||
func annotated(with selection: [SQLSelectable]) -> Self {
|
||||
func annotated(with selection: [SQLSelection]) -> Self {
|
||||
annotated(with: { _ in selection })
|
||||
}
|
||||
|
||||
func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self {
|
||||
func filter(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
|
||||
map(\.filterPromise) { promise in
|
||||
DatabasePromise { db in
|
||||
if let filter = try promise.resolve(db) {
|
||||
return try filter && predicate(db)
|
||||
} else {
|
||||
return try predicate(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Convenience
|
||||
func filter(_ predicate: SQLExpression) -> Self {
|
||||
filter { _ in predicate }
|
||||
}
|
||||
|
||||
func order(_ orderings: @escaping (Database) throws -> [SQLOrdering]) -> Self {
|
||||
with(\.ordering, SQLRelation.Ordering(orderings: orderings))
|
||||
}
|
||||
|
||||
@@ -236,22 +242,17 @@ extension SQLRelation: Refinable {
|
||||
}
|
||||
|
||||
func unordered() -> Self {
|
||||
self.with(\.ordering, SQLRelation.Ordering())
|
||||
.map(\.children, { $0.mapValues { $0.map(\.relation, { $0.unordered() }) } })
|
||||
self
|
||||
.with(\.ordering, SQLRelation.Ordering())
|
||||
.map(\.children) { children in
|
||||
children.mapValues { child in
|
||||
child.map(\.relation) { $0.unordered() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func qualified(with alias: TableAlias) -> Self {
|
||||
map(\.source) { $0.qualified(with: alias) }
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLRelation: FilteredRequest {
|
||||
func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self {
|
||||
map(\.filtersPromise) { filtersPromise in
|
||||
DatabasePromise { db in
|
||||
try filtersPromise.resolve(db) + [predicate(db).sqlExpression]
|
||||
}
|
||||
}
|
||||
func aliased(_ alias: TableAlias) -> Self {
|
||||
map(\.source) { $0.aliased(alias) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -289,12 +290,65 @@ extension SQLRelation {
|
||||
/// as HasManyThrough, which have any number of pivot relations between the
|
||||
/// origin and the destination.
|
||||
func appendingChild(for association: _SQLAssociation, kind: SQLRelation.Child.Kind) -> Self {
|
||||
// Preserve association cardinality in intermediate steps of
|
||||
// including(all:), and force desired cardinality otherwize
|
||||
let isSingular = (kind == .allNotPrefetched)
|
||||
? association.destination.cardinality.isSingular
|
||||
: kind.isSingular
|
||||
// Our goal here is to append a child with a correct (singular or
|
||||
// plural) key, so that the user can decode it later under the expected
|
||||
// name.
|
||||
//
|
||||
// To know if the child key should be singular or plural, we look at the
|
||||
// association, which may be to-one or to-many, and at the kind of the
|
||||
// child, which may be joined (singular), or prefetched (plural).
|
||||
//
|
||||
// We prefer the cardinality of the child kind, but for the specific
|
||||
// case of the `.bridge` child kind, involved in prefetched
|
||||
// has-many-through associations, where we user the cardinality of
|
||||
// the association instead.
|
||||
//
|
||||
// By prefering the cardinality of the child kind in general, we make it
|
||||
// possible to join to a plural association and decode it in a singular
|
||||
// key. In the example below, we have a singular kind `.oneRequired`,
|
||||
// a plural to-many association, and we use a singular key:
|
||||
//
|
||||
// // Decode a Player in the singular "player" key
|
||||
// //
|
||||
// // SELECT team.*, player.*
|
||||
// // FROM team
|
||||
// // JOIN player ON player.teamID = team.id
|
||||
// Team.joining(required: Team.players)
|
||||
//
|
||||
// The exception for has-many-through associations exists because the
|
||||
// pivot of the association may be singular, and may conflict with a
|
||||
// plural association with the same association key, as in the example
|
||||
// below:
|
||||
//
|
||||
// We want the child for the "captain" in the following request to be
|
||||
// registered under the singular "player" key, and not the plural
|
||||
// "players" key, so that it does not conflict with the other child
|
||||
// named "players" (we can not have two distinct children with the
|
||||
// same key):
|
||||
//
|
||||
// struct Team: TableRecord {
|
||||
// static let players = hasMany(Player.self)
|
||||
// static let captain = hasOne(Player.self).filter(Column("isCaptain") == true)
|
||||
// static let captainAwards = hasMany(Award.self, through: captain, using: Player.awards)
|
||||
// }
|
||||
// struct Player: TableRecord {
|
||||
// static let awards = hasMany(Award.self)
|
||||
// }
|
||||
// struct Award: TableRecord { }
|
||||
// let request = Team
|
||||
// .including(all: Team.captainAwards) // child "player" (with an "awards" child inside)
|
||||
// .including(all: Team.players) // child "players"
|
||||
let isSingular: Bool
|
||||
switch kind {
|
||||
case .oneOptional, .oneRequired:
|
||||
isSingular = true
|
||||
case .all:
|
||||
isSingular = false
|
||||
case .bridge:
|
||||
isSingular = association.destination.cardinality.isSingular
|
||||
}
|
||||
let childKey = association.destination.key.name(singular: isSingular)
|
||||
|
||||
let child = SQLRelation.Child(
|
||||
kind: kind,
|
||||
condition: association.destination.condition,
|
||||
@@ -337,10 +391,11 @@ extension SQLRelation {
|
||||
.appendingChild(child, forKey: childKey)
|
||||
|
||||
switch kind {
|
||||
case .oneRequired, .oneOptional, .allNotPrefetched:
|
||||
case .oneRequired, .oneOptional, .bridge:
|
||||
return appendingChild(for: reducedAssociation, kind: kind)
|
||||
case .allPrefetched:
|
||||
// Intermediate steps of indirect associations are not prefetched.
|
||||
case .all:
|
||||
// Intermediate steps of an indirect association are not prefetched:
|
||||
// use the `.bridge` kind.
|
||||
//
|
||||
// For example, the request below prefetches citizens, not
|
||||
// intermediate passports:
|
||||
@@ -350,7 +405,7 @@ extension SQLRelation {
|
||||
// static let citizens = hasMany(Citizens.self, through: passports, using: Passport.citizen)
|
||||
// }
|
||||
// let request = Country.including(all: Country.citizens)
|
||||
return appendingChild(for: reducedAssociation, kind: .allNotPrefetched)
|
||||
return appendingChild(for: reducedAssociation, kind: .bridge)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -382,16 +437,16 @@ extension SQLRelation {
|
||||
func removingChildrenForPrefetchedAssociations() -> Self {
|
||||
filteringChildren {
|
||||
switch $0.kind {
|
||||
case .allPrefetched, .allNotPrefetched: return false
|
||||
case .all, .bridge: return false
|
||||
case .oneRequired, .oneOptional: return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLRelation: _JoinableRequest {
|
||||
extension SQLRelation {
|
||||
func _including(all association: _SQLAssociation) -> Self {
|
||||
appendingChild(for: association, kind: .allPrefetched)
|
||||
appendingChild(for: association, kind: .all)
|
||||
}
|
||||
|
||||
func _including(optional association: _SQLAssociation) -> Self {
|
||||
@@ -417,7 +472,7 @@ struct SQLSource {
|
||||
var tableName: String
|
||||
var alias: TableAlias?
|
||||
|
||||
func qualified(with alias: TableAlias) -> SQLSource {
|
||||
func aliased(_ alias: TableAlias) -> SQLSource {
|
||||
if let sourceAlias = self.alias {
|
||||
alias.becomeProxy(of: sourceAlias)
|
||||
return self
|
||||
@@ -434,13 +489,13 @@ extension SQLRelation {
|
||||
/// SQLRelation.Ordering provides the order clause to SQLRelation.
|
||||
struct Ordering {
|
||||
private enum Element {
|
||||
case terms(DatabasePromise<[SQLOrderingTerm]>)
|
||||
case terms(DatabasePromise<[SQLOrdering]>)
|
||||
case ordering(SQLRelation.Ordering)
|
||||
|
||||
var reversed: Element {
|
||||
switch self {
|
||||
case .terms(let terms):
|
||||
return .terms(terms.map { $0.map(\._reversed) })
|
||||
return .terms(terms.map { $0.map(\.reversed) })
|
||||
case .ordering(let ordering):
|
||||
return .ordering(ordering.reversed)
|
||||
}
|
||||
@@ -449,13 +504,13 @@ extension SQLRelation {
|
||||
func qualified(with alias: TableAlias) -> Element {
|
||||
switch self {
|
||||
case .terms(let terms):
|
||||
return .terms(terms.map { $0.map { $0._qualifiedOrdering(with: alias) } })
|
||||
return .terms(terms.map { $0.map { $0.qualified(with: alias) } })
|
||||
case .ordering(let ordering):
|
||||
return .ordering(ordering.qualified(with: alias))
|
||||
}
|
||||
}
|
||||
|
||||
func resolve(_ db: Database) throws -> [SQLOrderingTerm] {
|
||||
func resolve(_ db: Database) throws -> [SQLOrdering] {
|
||||
switch self {
|
||||
case .terms(let terms):
|
||||
return try terms.resolve(db)
|
||||
@@ -481,7 +536,7 @@ extension SQLRelation {
|
||||
isReversed: false)
|
||||
}
|
||||
|
||||
init(orderings: @escaping (Database) throws -> [SQLOrderingTerm]) {
|
||||
init(orderings: @escaping (Database) throws -> [SQLOrdering]) {
|
||||
self.init(
|
||||
elements: [.terms(DatabasePromise(orderings))],
|
||||
isReversed: false)
|
||||
@@ -505,7 +560,7 @@ extension SQLRelation {
|
||||
isReversed: isReversed)
|
||||
}
|
||||
|
||||
func resolve(_ db: Database) throws -> [SQLOrderingTerm] {
|
||||
func resolve(_ db: Database) throws -> [SQLOrdering] {
|
||||
if isReversed {
|
||||
return try elements.flatMap { try $0.reversed.resolve(db) }
|
||||
} else {
|
||||
@@ -539,27 +594,7 @@ extension SQLRelation {
|
||||
/// author.request(for: Author.books)
|
||||
enum SQLAssociationCondition {
|
||||
/// A condition based on a foreign key.
|
||||
///
|
||||
/// originIsLeft is true if the table at the origin of the foreign key is on
|
||||
/// the left of the sql JOIN operator.
|
||||
///
|
||||
/// Let's consider the `book.authorId -> author.id` foreign key.
|
||||
/// Its origin table is `book`.
|
||||
///
|
||||
/// The origin table `book` is on the left of the JOIN operator for
|
||||
/// the BelongsTo association:
|
||||
///
|
||||
/// -- Book.including(required: Book.author)
|
||||
/// SELECT ... FROM book JOIN author ON author.id = book.authorId
|
||||
/// ~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
///
|
||||
/// The origin table `book`is on the right of the JOIN operator for
|
||||
/// the HasMany and HasOne associations:
|
||||
///
|
||||
/// -- Author.including(required: Author.books)
|
||||
/// SELECT ... FROM author JOIN book ON author.id = book.authorId
|
||||
/// ~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
case foreignKey(request: SQLForeignKeyRequest, originIsLeft: Bool)
|
||||
case foreignKey(SQLForeignKeyCondition)
|
||||
|
||||
/// A condition based on a function that returns an expression.
|
||||
///
|
||||
@@ -575,20 +610,102 @@ enum SQLAssociationCondition {
|
||||
/// player[Column("id")] == bonus[Column("playerID")]
|
||||
/// })
|
||||
/// Player.with(bonus).joining(required: association)
|
||||
case expression((_ left: TableAlias, _ right: TableAlias) -> SQLExpressible)
|
||||
case expression((_ left: TableAlias, _ right: TableAlias) -> SQLExpression?)
|
||||
|
||||
/// The condition that does not constrain the two associated tables
|
||||
/// in any way.
|
||||
static let none = expression({ _, _ in true })
|
||||
static let none = expression({ _, _ in nil })
|
||||
|
||||
var reversed: SQLAssociationCondition {
|
||||
func reversed(to destinationTable: String) -> SQLAssociationCondition {
|
||||
switch self {
|
||||
case let .foreignKey(request: request, originIsLeft: originIsLeft):
|
||||
return .foreignKey(request: request, originIsLeft: !originIsLeft)
|
||||
case let .foreignKey(foreignKey):
|
||||
return .foreignKey(foreignKey.reversed(to: destinationTable))
|
||||
case let .expression(condition):
|
||||
return .expression { condition($1, $0) }
|
||||
}
|
||||
}
|
||||
|
||||
func joinExpression(
|
||||
_ db: Database,
|
||||
leftAlias: TableAlias,
|
||||
rightAlias: TableAlias)
|
||||
throws -> SQLExpression?
|
||||
{
|
||||
switch self {
|
||||
case let .expression(condition):
|
||||
return condition(leftAlias, rightAlias)
|
||||
case let .foreignKey(foreignKey):
|
||||
return try foreignKey
|
||||
.joinMapping(db, from: leftAlias.tableName)
|
||||
.joinExpression(leftAlias: leftAlias, rightAlias: rightAlias)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An association condition based on a foreign key.
|
||||
struct SQLForeignKeyCondition: Equatable {
|
||||
/// The destination table of an association.
|
||||
///
|
||||
/// In `Author.hasMany(Book.self)`, the destination is `book`.
|
||||
var destinationTable: String
|
||||
|
||||
/// A user-provided foreign key. When nil, we introspect the database in
|
||||
/// order to look for a foreign key in the schema.
|
||||
var foreignKey: ForeignKey?
|
||||
|
||||
/// `originIsLeft` is true if the table at the origin of the foreign key is
|
||||
/// on the left of the sql JOIN operator.
|
||||
///
|
||||
/// Let's consider the `book.authorId -> author.id` foreign key.
|
||||
/// Its origin table is `book`.
|
||||
///
|
||||
/// The origin table `book` is on the left of the JOIN operator for
|
||||
/// the `BelongsTo` association:
|
||||
///
|
||||
/// -- Book.including(required: Book.author)
|
||||
/// SELECT ... FROM book JOIN author ON author.id = book.authorId
|
||||
/// ~~~~ ~~~~
|
||||
///
|
||||
/// The origin table `book`is on the right of the JOIN operator for
|
||||
/// the `HasMany` and `HasOne` associations:
|
||||
///
|
||||
/// -- Author.including(required: Author.books)
|
||||
/// SELECT ... FROM author JOIN book ON author.id = book.authorId
|
||||
/// ~~~~ ~~~~
|
||||
///
|
||||
/// See also `ForeignKeyMapping.joinMapping(originIsLeft:)`
|
||||
var originIsLeft: Bool
|
||||
|
||||
func reversed(to destinationTable: String) -> SQLForeignKeyCondition {
|
||||
SQLForeignKeyCondition(
|
||||
destinationTable: destinationTable,
|
||||
foreignKey: foreignKey,
|
||||
originIsLeft: !originIsLeft)
|
||||
}
|
||||
|
||||
/// Turns the foreign key condition into a `JoinMapping` that can feed an
|
||||
/// SQL JOIN clause.
|
||||
func joinMapping(_ db: Database, from originTable: String) throws -> JoinMapping {
|
||||
try foreignKeyRequest(from: originTable)
|
||||
.fetchForeignKeyMapping(db)
|
||||
.joinMapping(originIsLeft: originIsLeft)
|
||||
}
|
||||
|
||||
private func foreignKeyRequest(from originTable: String) -> SQLForeignKeyRequest {
|
||||
// Convert association destination/origin to
|
||||
// foreign key destination/origin.
|
||||
if originIsLeft {
|
||||
return SQLForeignKeyRequest(
|
||||
originTable: originTable,
|
||||
destinationTable: destinationTable,
|
||||
foreignKey: foreignKey)
|
||||
} else {
|
||||
return SQLForeignKeyRequest(
|
||||
originTable: destinationTable,
|
||||
destinationTable: originTable,
|
||||
foreignKey: foreignKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension JoinMapping {
|
||||
@@ -645,7 +762,10 @@ extension JoinMapping {
|
||||
.map({ mapping -> SQLExpression in
|
||||
let leftValue = leftRow.databaseValue(at: mapping.leftIndex)
|
||||
// Force `=` operator, because SQLite doesn't match foreign keys on NULL
|
||||
return SQLExpressionEqual(.equal, mapping.rightColumn, leftValue)
|
||||
return SQLExpression.compare(
|
||||
.equal,
|
||||
mapping.rightColumn.sqlExpression,
|
||||
leftValue.sqlExpression)
|
||||
})
|
||||
.joined(operator: .and)
|
||||
})
|
||||
@@ -653,7 +773,7 @@ extension JoinMapping {
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves the condition into SQL expressions which involve both left
|
||||
/// Resolves the condition into an SQL expression which involve both left
|
||||
/// and right tables.
|
||||
///
|
||||
/// SELECT * FROM left JOIN right ON (right.a = left.b)
|
||||
@@ -661,12 +781,10 @@ extension JoinMapping {
|
||||
///
|
||||
/// - 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.
|
||||
func joinExpressions(leftAlias: TableAlias) -> [SQLExpression] {
|
||||
map {
|
||||
Column($0.right) == SQLQualifiedColumn($0.left, alias: leftAlias)
|
||||
}
|
||||
/// - parameter rightAlias: A TableAlias for the table on the right of the
|
||||
/// JOIN operator.
|
||||
func joinExpression(leftAlias: TableAlias, rightAlias: TableAlias) -> SQLExpression {
|
||||
map { rightAlias[$0.right] == leftAlias[$0.left] }.joined(operator: .and)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -726,8 +844,12 @@ extension SQLRelation {
|
||||
return nil
|
||||
}
|
||||
|
||||
let mergedFiltersPromise = DatabasePromise<[SQLExpression]> { db in
|
||||
try self.filtersPromise.resolve(db) + other.filtersPromise.resolve(db)
|
||||
let mergedFilterPromise = DatabasePromise<SQLExpression?> { db in
|
||||
switch try (self.filterPromise.resolve(db), other.filterPromise.resolve(db)) {
|
||||
case let (lhs?, rhs?): return lhs && rhs
|
||||
case let (nil, expr?), let (expr?, nil): return expr
|
||||
case (nil, nil): return nil
|
||||
}
|
||||
}
|
||||
|
||||
var mergedChildren: OrderedDictionary<String, SQLRelation.Child> = [:]
|
||||
@@ -747,7 +869,7 @@ extension SQLRelation {
|
||||
}
|
||||
|
||||
// replace selection unless empty
|
||||
let mergedSelectionPromise = DatabasePromise { db -> [SQLSelectable] in
|
||||
let mergedSelectionPromise = DatabasePromise { db -> [SQLSelection] in
|
||||
let otherSelection = try other.selectionPromise.resolve(db)
|
||||
if otherSelection.isEmpty {
|
||||
return try self.selectionPromise.resolve(db)
|
||||
@@ -762,7 +884,7 @@ extension SQLRelation {
|
||||
return SQLRelation(
|
||||
source: mergedSource,
|
||||
selectionPromise: mergedSelectionPromise,
|
||||
filtersPromise: mergedFiltersPromise,
|
||||
filterPromise: mergedFilterPromise,
|
||||
ordering: mergedOrdering,
|
||||
children: mergedChildren)
|
||||
}
|
||||
@@ -793,8 +915,8 @@ extension SQLSource {
|
||||
extension SQLAssociationCondition {
|
||||
func merged(with other: SQLAssociationCondition) -> Self? {
|
||||
switch (self, other) {
|
||||
case let (.foreignKey(lr, lo), .foreignKey(rr, ro)):
|
||||
if lr == rr && lo == ro {
|
||||
case let (.foreignKey(lhs), .foreignKey(rhs)):
|
||||
if lhs == rhs {
|
||||
return self
|
||||
} else {
|
||||
// can't merge
|
||||
@@ -857,28 +979,28 @@ extension SQLRelation.Child.Kind {
|
||||
// .including(optional: association)
|
||||
return .oneOptional
|
||||
|
||||
case (.allPrefetched, .allPrefetched):
|
||||
case (.all, .all):
|
||||
// Equivalent to Record.including(all: association):
|
||||
//
|
||||
// Record
|
||||
// .including(all: association)
|
||||
// .including(all: association)
|
||||
return .allPrefetched
|
||||
return .all
|
||||
|
||||
case (.allPrefetched, .allNotPrefetched),
|
||||
(.allNotPrefetched, .allPrefetched):
|
||||
case (.all, .bridge),
|
||||
(.bridge, .all):
|
||||
// Record
|
||||
// .including(all: associationToDestinationThroughPivot)
|
||||
// .including(all: associationToPivot)
|
||||
fatalError("Not implemented: merging a direct association and an indirect one with including(all:)")
|
||||
|
||||
case (.allNotPrefetched, .allNotPrefetched):
|
||||
case (.bridge, .bridge):
|
||||
// Equivalent to Record.including(all: association)
|
||||
//
|
||||
// Record
|
||||
// .including(all: association)
|
||||
// .including(all: association)
|
||||
return .allNotPrefetched
|
||||
return .bridge
|
||||
|
||||
default:
|
||||
// Likely a programmer error:
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
/// A [row value](https://www.sqlite.org/rowvalue.html).
|
||||
///
|
||||
/// :nodoc:
|
||||
struct SQLRowValue: SQLExpression {
|
||||
let expressions: [SQLExpression]
|
||||
|
||||
/// SQLite row values were shipped in SQLite 3.15:
|
||||
/// https://www.sqlite.org/releaselog/3_15_0.html
|
||||
static let isAvailable = (sqlite3_libversion_number() >= 3015000)
|
||||
|
||||
/// - precondition: `expressions` is not empty
|
||||
init(_ expressions: [SQLExpression]) {
|
||||
assert(!expressions.isEmpty)
|
||||
self.expressions = expressions
|
||||
}
|
||||
|
||||
// MARK: - SQLExpression
|
||||
|
||||
func _column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool) throws -> String? {
|
||||
if let expression = expressions.first, expressions.count == 1 {
|
||||
return try expression._column(db, for: alias, acceptsBijection: acceptsBijection)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
if let expression = expressions.first, expressions.count == 1 {
|
||||
return try expression._expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis)
|
||||
}
|
||||
|
||||
let values = try expressions.map {
|
||||
try $0._expressionSQL(context, wrappedInParenthesis: false)
|
||||
}
|
||||
|
||||
return "("
|
||||
+ values.joined(separator: ", ")
|
||||
+ ")"
|
||||
}
|
||||
|
||||
func _identifyingColums(_ db: Database, for alias: TableAlias) throws -> Set<String> {
|
||||
if let expression = expressions.first, expressions.count == 1 {
|
||||
return try expression._identifyingColums(db, for: alias)
|
||||
}
|
||||
|
||||
return try expressions.reduce(into: []) { try $0.formUnion($1._identifyingColums(db, for: alias)) }
|
||||
}
|
||||
|
||||
var _isConstantInRequest: Bool {
|
||||
expressions.allSatisfy(\._isConstantInRequest)
|
||||
}
|
||||
|
||||
var _isTrue: Bool {
|
||||
if let expression = expressions.first, expressions.count == 1 {
|
||||
return expression._isTrue
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func _qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
SQLRowValue(expressions.map { $0._qualifiedExpression(with: alias) })
|
||||
}
|
||||
|
||||
// MARK: - SQLSelectable
|
||||
|
||||
var _isAggregate: Bool {
|
||||
expressions.contains(where: \._isAggregate)
|
||||
}
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
// MARK: - AllColumns
|
||||
|
||||
/// AllColumns is the `*` in `SELECT *`.
|
||||
///
|
||||
/// You use AllColumns in your custom implementation of
|
||||
/// TableRecord.databaseSelection.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct Player : TableRecord {
|
||||
/// static var databaseTableName = "player"
|
||||
/// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
|
||||
/// }
|
||||
///
|
||||
/// // SELECT *, rowid FROM player
|
||||
/// let request = Player.all()
|
||||
public struct AllColumns: SQLSelectable {
|
||||
// As long as the CTE is embedded here, the following request will fail
|
||||
// at runtime, in `_columnCount(_:)`, because we can't access the number of
|
||||
// columns in the CTE:
|
||||
//
|
||||
// let association = Player.association(to: cte)
|
||||
// Player.including(required: association.select(AllColumns(), ...))
|
||||
//
|
||||
// The need for this should not be frequent. And the user has
|
||||
// two workarounds:
|
||||
//
|
||||
// - provide explicit columns in the CTE definition.
|
||||
// - prefer `annotated(with:)` when she wants to extend the selection.
|
||||
//
|
||||
// TODO: Make `cteRequestOrAssociation.select(AllColumns())` possible.
|
||||
|
||||
/// When nil, select all columns from a regular database table.
|
||||
/// When not nil, select all columns from a common table expression.
|
||||
var cte: SQLCTE?
|
||||
|
||||
/// The `*` selection.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // SELECT * FROM player
|
||||
/// Player.select(AllColumns())
|
||||
public init() { }
|
||||
|
||||
/// The `*` selection for a common table expression.
|
||||
///
|
||||
/// WITH t AS (...) SELECT * FROM t
|
||||
init(cte: SQLCTE) {
|
||||
self.cte = cte
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _columnCount(_ db: Database) throws -> Int {
|
||||
if let cte = cte {
|
||||
return try cte.columnsCount(db)
|
||||
}
|
||||
|
||||
fatalError("Can't compute number of columns without an alias")
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _count(distinct: Bool) -> _SQLCount? {
|
||||
// SELECT DISTINCT * FROM tableName ...
|
||||
if distinct {
|
||||
// Can't count
|
||||
return nil
|
||||
}
|
||||
|
||||
// SELECT * FROM tableName ...
|
||||
// ->
|
||||
// SELECT COUNT(*) FROM tableName ...
|
||||
return .all
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _countedSQL(_ context: SQLGenerationContext) throws -> String { "*" }
|
||||
|
||||
/// :nodoc:
|
||||
public func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable {
|
||||
SQLQualifiedAllColumns(alias: alias, cte: cte)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _resultColumnSQL(_ context: SQLGenerationContext) throws -> String { "*" }
|
||||
}
|
||||
|
||||
// MARK: - SQLQualifiedAllColumns
|
||||
|
||||
/// _SQLQualifiedAllColumns is the `t.*` in `SELECT t.*`.
|
||||
///
|
||||
/// :nodoc:
|
||||
struct SQLQualifiedAllColumns: SQLSelectable {
|
||||
/// When nil, select all columns from a regular database table.
|
||||
/// When not nil, select all columns from a common table expression.
|
||||
var cte: SQLCTE?
|
||||
let alias: TableAlias
|
||||
|
||||
init(alias: TableAlias, cte: SQLCTE?) {
|
||||
self.alias = alias
|
||||
self.cte = cte
|
||||
}
|
||||
|
||||
func _columnCount(_ db: Database) throws -> Int {
|
||||
if let cte = cte {
|
||||
return try cte.columnsCount(db)
|
||||
} else {
|
||||
return try db.columns(in: alias.tableName).count
|
||||
}
|
||||
}
|
||||
|
||||
func _count(distinct: Bool) -> _SQLCount? { nil }
|
||||
|
||||
func _countedSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
if context.qualifier(for: alias) != nil {
|
||||
// SELECT COUNT(t.*) is invalid SQL
|
||||
fatalError("Not implemented, or invalid query")
|
||||
}
|
||||
|
||||
return "*"
|
||||
}
|
||||
|
||||
func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable {
|
||||
// Never requalify
|
||||
return self
|
||||
}
|
||||
|
||||
func _resultColumnSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
if let qualifier = context.qualifier(for: alias) {
|
||||
return qualifier.quotedDatabaseIdentifier + ".*"
|
||||
}
|
||||
return "*"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLAliasedExpression
|
||||
|
||||
/// :nodoc:
|
||||
struct SQLAliasedExpression: SQLSelectable {
|
||||
let expression: SQLExpression
|
||||
let name: String
|
||||
|
||||
init(_ expression: SQLExpression, name: String) {
|
||||
self.expression = expression
|
||||
self.name = name
|
||||
}
|
||||
|
||||
func _columnCount(_ db: Database) throws -> Int { 1 }
|
||||
|
||||
func _count(distinct: Bool) -> _SQLCount? {
|
||||
expression._count(distinct: distinct)
|
||||
}
|
||||
|
||||
func _countedSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
try expression._countedSQL(context)
|
||||
}
|
||||
|
||||
var _isAggregate: Bool { expression._isAggregate }
|
||||
|
||||
func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable {
|
||||
SQLAliasedExpression(expression._qualifiedExpression(with: alias), name: name)
|
||||
}
|
||||
|
||||
func _resultColumnSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
try expression._resultColumnSQL(context)
|
||||
+ " AS "
|
||||
+ name.quotedDatabaseIdentifier
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
/// Implementation details of `SQLSelectable`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol _SQLSelectable {
|
||||
/// Returns the number of columns in the selectable.
|
||||
func _columnCount(_ db: Database) throws -> Int
|
||||
|
||||
/// If the selectable can be counted, return how to count it.
|
||||
func _count(distinct: Bool) -> _SQLCount?
|
||||
|
||||
/// Returns the SQL that feeds the argument of the `COUNT` function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// COUNT(*)
|
||||
/// COUNT(id)
|
||||
/// ^---- countedSQL
|
||||
///
|
||||
/// - parameter context: An SQL generation context which accepts
|
||||
/// statement arguments.
|
||||
func _countedSQL(_ context: SQLGenerationContext) throws -> String
|
||||
|
||||
/// Returns true if the selectable is an aggregate.
|
||||
///
|
||||
/// When in doubt, returns false.
|
||||
///
|
||||
/// SELECT * -- false
|
||||
/// SELECT score -- false
|
||||
/// SELECT COUNT(*) -- true
|
||||
/// SELECT MAX(score) -- true
|
||||
/// SELECT MAX(score) + 1 -- true
|
||||
///
|
||||
/// This method makes it possible to avoid inserting `LIMIT 1` to the SQL
|
||||
/// of some requests:
|
||||
///
|
||||
/// // SELECT MAX("score") FROM "player"
|
||||
/// try Player.select(max(Column("score")), as: Int.self).fetchOne(db)
|
||||
///
|
||||
/// // SELECT "score" FROM "player" LIMIT 1
|
||||
/// try Player.select(Column("score"), as: Int.self).fetchOne(db)
|
||||
var _isAggregate: Bool { get }
|
||||
|
||||
/// Returns a qualified selectable
|
||||
func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable
|
||||
|
||||
/// Returns the SQL that feeds the selection of a `SELECT` statement.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// 1
|
||||
/// name
|
||||
/// COUNT(*)
|
||||
/// (score + bonus) AS total
|
||||
///
|
||||
/// See https://sqlite.org/syntax/result-column.html
|
||||
///
|
||||
/// - parameter context: An SQL generation context which accepts
|
||||
/// statement arguments.
|
||||
func _resultColumnSQL(_ context: SQLGenerationContext) throws -> String
|
||||
}
|
||||
|
||||
/// SQLSelectable is the protocol for types that can be selected, as
|
||||
/// described at https://www.sqlite.org/syntax/result-column.html
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol SQLSelectable: _SQLSelectable { }
|
||||
|
||||
/// :nodoc:
|
||||
public enum _SQLCount {
|
||||
/// Represents `COUNT(*)`
|
||||
case all
|
||||
|
||||
/// Represents `COUNT(DISTINCT expression)`
|
||||
case distinct(SQLExpression)
|
||||
}
|
||||
|
||||
extension SQLSelectable {
|
||||
/// :nodoc:
|
||||
public var _isAggregate: Bool { false }
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
/// The type that can be selected, as described at
|
||||
/// https://www.sqlite.org/syntax/result-column.html
|
||||
public struct SQLSelection {
|
||||
private var impl: Impl
|
||||
|
||||
private enum Impl {
|
||||
/// All columns
|
||||
///
|
||||
/// SELECT *
|
||||
case allColumns
|
||||
|
||||
/// All columns from a table
|
||||
///
|
||||
/// SELECT player.*
|
||||
case qualifiedAllColumns(TableAlias)
|
||||
|
||||
// As long as the CTE is embedded here, the following request will fail
|
||||
// at runtime, in `columnCount(_:)`, because we can't access the number of
|
||||
// columns in the CTE:
|
||||
//
|
||||
// let association = Player.association(to: cte)
|
||||
// Player.including(required: association.select(AllColumns(), ...))
|
||||
//
|
||||
// The need for this should not be frequent. And the user has
|
||||
// two workarounds:
|
||||
//
|
||||
// - provide explicit columns in the CTE definition.
|
||||
// - prefer `annotated(with:)` when she wants to extend the selection.
|
||||
//
|
||||
// TODO: Make `cteRequestOrAssociation.select(AllColumns())` possible.
|
||||
/// All columns from a common table expression
|
||||
case allCTEColumns(SQLCTE)
|
||||
|
||||
case qualifiedAllCTEColumns(SQLCTE, TableAlias)
|
||||
|
||||
/// An expression
|
||||
///
|
||||
/// SELECT id
|
||||
/// SELECT LENGTH(name)
|
||||
case expression(SQLExpression)
|
||||
|
||||
/// An aliased expression
|
||||
///
|
||||
/// SELECT score + bonud AS totalScore
|
||||
case aliasedExpression(SQLExpression, String)
|
||||
|
||||
/// A literal SQL selection
|
||||
case literal(SQLLiteral)
|
||||
}
|
||||
|
||||
static let allColumns = SQLSelection(impl: .allColumns)
|
||||
|
||||
static func qualifiedAllColumns(_ alias: TableAlias) -> Self {
|
||||
self.init(impl: .qualifiedAllColumns(alias))
|
||||
}
|
||||
|
||||
static func allCTEColumns(_ cte: SQLCTE) -> Self {
|
||||
self.init(impl: .allCTEColumns(cte))
|
||||
}
|
||||
|
||||
static func qualifiedAllCTEColumns(_ cte: SQLCTE, _ alias: TableAlias) -> Self {
|
||||
self.init(impl: .qualifiedAllCTEColumns(cte, alias))
|
||||
}
|
||||
|
||||
static func expression(_ expression: SQLExpression) -> Self {
|
||||
self.init(impl: .expression(expression))
|
||||
}
|
||||
|
||||
static func aliasedExpression(_ expression: SQLExpression, _ name: String) -> Self {
|
||||
self.init(impl: .aliasedExpression(expression, name))
|
||||
}
|
||||
|
||||
static func literal(_ sqlLiteral: SQLLiteral) -> Self {
|
||||
self.init(impl: .literal(sqlLiteral))
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLSelection {
|
||||
/// Returns the number of columns in the selection.
|
||||
func columnCount(_ db: Database) throws -> Int {
|
||||
switch impl {
|
||||
case .allColumns:
|
||||
// Likely a GRDB bug
|
||||
fatalError("Can't compute number of columns without an alias")
|
||||
|
||||
case let .qualifiedAllColumns(alias):
|
||||
return try db.columns(in: alias.tableName).count
|
||||
|
||||
case let .allCTEColumns(cte):
|
||||
return try cte.columnsCount(db)
|
||||
|
||||
case let .qualifiedAllCTEColumns(cte, _):
|
||||
return try cte.columnsCount(db)
|
||||
|
||||
case .expression,
|
||||
.aliasedExpression:
|
||||
return 1
|
||||
|
||||
case .literal:
|
||||
fatalError("""
|
||||
Selection literals don't known how many columns they contain. \
|
||||
To resolve this error, select one or several literal expressions instead. \
|
||||
See SQLLiteral.sqlExpression.
|
||||
""")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLSelection {
|
||||
/// If the selection can be counted, return how to count it.
|
||||
func count(distinct: Bool) -> SQLCount? {
|
||||
switch impl {
|
||||
case .allColumns,
|
||||
.allCTEColumns:
|
||||
// SELECT DISTINCT * FROM tableName ...
|
||||
if distinct {
|
||||
// Can't count
|
||||
return nil
|
||||
}
|
||||
|
||||
// SELECT * FROM tableName ...
|
||||
// ->
|
||||
// SELECT COUNT(*) FROM tableName ...
|
||||
return .all
|
||||
|
||||
case .qualifiedAllColumns,
|
||||
.qualifiedAllCTEColumns:
|
||||
return nil
|
||||
|
||||
case let .expression(expression),
|
||||
let .aliasedExpression(expression, _):
|
||||
if distinct {
|
||||
// SELECT DISTINCT expr FROM tableName ...
|
||||
// ->
|
||||
// SELECT COUNT(DISTINCT expr) FROM tableName ...
|
||||
return .distinct(expression)
|
||||
} else {
|
||||
// SELECT expr FROM tableName ...
|
||||
// ->
|
||||
// SELECT COUNT(*) FROM tableName ...
|
||||
return .all
|
||||
}
|
||||
|
||||
case .literal:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the SQL that feeds the argument of the `COUNT` function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// COUNT(*)
|
||||
/// COUNT(id)
|
||||
/// ^---- countedSQL
|
||||
///
|
||||
/// - parameter context: An SQL generation context which accepts
|
||||
/// statement arguments.
|
||||
func countedSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
switch impl {
|
||||
case .allColumns,
|
||||
.allCTEColumns:
|
||||
return "*"
|
||||
|
||||
case let .qualifiedAllColumns(alias),
|
||||
let .qualifiedAllCTEColumns(_, alias):
|
||||
if context.qualifier(for: alias) != nil {
|
||||
// SELECT COUNT(t.*) is invalid SQL
|
||||
fatalError("Not implemented, or invalid query")
|
||||
}
|
||||
return "*"
|
||||
|
||||
case let .expression(expression),
|
||||
let .aliasedExpression(expression, _):
|
||||
return try expression.sql(context)
|
||||
|
||||
case .literal:
|
||||
fatalError("""
|
||||
Selection literals can't be counted. \
|
||||
To resolve this error, select one or several literal expressions instead. \
|
||||
See SQLLiteral.sqlExpression.
|
||||
""")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLSelection {
|
||||
/// Returns the SQL that feeds the selection of a `SELECT` statement.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// 1
|
||||
/// name
|
||||
/// COUNT(*)
|
||||
/// (score + bonus) AS total
|
||||
///
|
||||
/// See https://sqlite.org/syntax/result-column.html
|
||||
///
|
||||
/// - parameter context: An SQL generation context which accepts
|
||||
/// statement arguments.
|
||||
func sql(_ context: SQLGenerationContext) throws -> String {
|
||||
switch impl {
|
||||
case .allColumns,
|
||||
.allCTEColumns:
|
||||
return "*"
|
||||
|
||||
case let .qualifiedAllColumns(alias),
|
||||
let .qualifiedAllCTEColumns(_, alias):
|
||||
if let qualifier = context.qualifier(for: alias) {
|
||||
return qualifier.quotedDatabaseIdentifier + ".*"
|
||||
}
|
||||
return "*"
|
||||
|
||||
case let .expression(expression):
|
||||
return try expression.sql(context)
|
||||
|
||||
case let .aliasedExpression(expression, name):
|
||||
return try expression.sql(context) + " AS " + name.quotedDatabaseIdentifier
|
||||
|
||||
case let .literal(sqlLiteral):
|
||||
return try sqlLiteral.sql(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLSelection {
|
||||
/// Returns true if the selection is an aggregate.
|
||||
///
|
||||
/// When in doubt, returns false.
|
||||
///
|
||||
/// SELECT * -- false
|
||||
/// SELECT score -- false
|
||||
/// SELECT COUNT(*) -- true
|
||||
/// SELECT MAX(score) -- true
|
||||
/// SELECT MAX(score) + 1 -- true
|
||||
///
|
||||
/// This method makes it possible to avoid inserting `LIMIT 1` to the SQL
|
||||
/// of some requests:
|
||||
///
|
||||
/// // SELECT MAX("score") FROM "player"
|
||||
/// try Player.select(max(Column("score")), as: Int.self).fetchOne(db)
|
||||
///
|
||||
/// // SELECT "score" FROM "player" LIMIT 1
|
||||
/// try Player.select(Column("score"), as: Int.self).fetchOne(db)
|
||||
var isAggregate: Bool {
|
||||
switch impl {
|
||||
case let .expression(expression),
|
||||
let .aliasedExpression(expression, _):
|
||||
return expression.isAggregate
|
||||
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLSelection {
|
||||
/// Returns a qualified selection
|
||||
func qualified(with alias: TableAlias) -> SQLSelection {
|
||||
switch impl {
|
||||
case .qualifiedAllColumns,
|
||||
.qualifiedAllCTEColumns:
|
||||
return self
|
||||
|
||||
case .allColumns:
|
||||
return .qualifiedAllColumns(alias)
|
||||
|
||||
case let .allCTEColumns(cte):
|
||||
return .qualifiedAllCTEColumns(cte, alias)
|
||||
|
||||
case let .expression(expression):
|
||||
return .expression(expression.qualified(with: alias))
|
||||
|
||||
case let .aliasedExpression(expression, name):
|
||||
return .aliasedExpression(expression.qualified(with: alias), name)
|
||||
|
||||
case let .literal(sqlLiteral):
|
||||
return .literal(sqlLiteral.qualified(with: alias))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum SQLCount {
|
||||
/// Represents `COUNT(*)`
|
||||
case all
|
||||
|
||||
/// Represents `COUNT(DISTINCT expression)`
|
||||
case distinct(SQLExpression)
|
||||
}
|
||||
|
||||
// MARK: - SQLSelectable
|
||||
|
||||
/// SQLSelectable is the protocol for types that can be selected, as
|
||||
/// described at https://www.sqlite.org/syntax/result-column.html
|
||||
public protocol SQLSelectable {
|
||||
/// Returns an SQL selection.
|
||||
var sqlSelection: SQLSelection { get }
|
||||
}
|
||||
|
||||
extension SQLSelection: SQLSelectable {
|
||||
// Not a real deprecation, just a usage warning
|
||||
@available(*, deprecated, message: "Already SQLSelection")
|
||||
public var sqlSelection: SQLSelection { self }
|
||||
}
|
||||
|
||||
// MARK: - AllColumns
|
||||
|
||||
/// AllColumns is the `*` in `SELECT *`.
|
||||
///
|
||||
/// You use AllColumns in your custom implementation of
|
||||
/// TableRecord.databaseSelection.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct Player : TableRecord {
|
||||
/// static var databaseTableName = "player"
|
||||
/// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
|
||||
/// }
|
||||
///
|
||||
/// // SELECT *, rowid FROM player
|
||||
/// let request = Player.all()
|
||||
public struct AllColumns: SQLSelectable {
|
||||
/// The `*` selection.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // SELECT * FROM player
|
||||
/// Player.select(AllColumns())
|
||||
public init() { }
|
||||
|
||||
public var sqlSelection: SQLSelection {
|
||||
.allColumns
|
||||
}
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
// MARK: - SQL Ordering Support
|
||||
|
||||
/// :nodoc:
|
||||
extension SQLSpecificExpressible {
|
||||
|
||||
/// Returns a value that can be used as an argument to QueryInterfaceRequest.order()
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
public var asc: SQLOrderingTerm {
|
||||
SQLOrdering.asc(sqlExpression)
|
||||
}
|
||||
|
||||
/// Returns a value that can be used as an argument to QueryInterfaceRequest.order()
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
public var desc: SQLOrderingTerm {
|
||||
SQLOrdering.desc(sqlExpression)
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE
|
||||
/// Returns a value that can be used as an argument to QueryInterfaceRequest.order()
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
public var ascNullsLast: SQLOrderingTerm {
|
||||
SQLOrdering.ascNullsLast(sqlExpression)
|
||||
}
|
||||
|
||||
/// Returns a value that can be used as an argument to QueryInterfaceRequest.order()
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
public var descNullsFirst: SQLOrderingTerm {
|
||||
SQLOrdering.descNullsFirst(sqlExpression)
|
||||
}
|
||||
#elseif !GRDBCIPHER
|
||||
/// Returns a value that can be used as an argument to QueryInterfaceRequest.order()
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
@available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *)
|
||||
public var ascNullsLast: SQLOrderingTerm {
|
||||
SQLOrdering.ascNullsLast(sqlExpression)
|
||||
}
|
||||
|
||||
/// Returns a value that can be used as an argument to QueryInterfaceRequest.order()
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
@available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *)
|
||||
public var descNullsFirst: SQLOrderingTerm {
|
||||
SQLOrdering.descNullsFirst(sqlExpression)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
// MARK: - SQL Selection Support
|
||||
|
||||
/// :nodoc:
|
||||
extension SQLSpecificExpressible {
|
||||
/// Give the expression the given SQL name.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // SELECT (width * height) AS area FROM shape
|
||||
/// let area = (Column("width") * Column("height")).forKey("area")
|
||||
/// let request = Shape.select(area)
|
||||
/// if let row = try Row.fetchOne(db, request) {
|
||||
/// let area: Int = row["area"]
|
||||
/// }
|
||||
public func forKey(_ key: String) -> SQLSelectable {
|
||||
SQLAliasedExpression(sqlExpression, name: key)
|
||||
}
|
||||
|
||||
/// Give the expression the same SQL name as the coding key.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct Shape: Decodable, FetchableRecord, TableRecord {
|
||||
/// let width: Int
|
||||
/// let height: Int
|
||||
/// let area: Int
|
||||
///
|
||||
/// static let databaseSelection: [SQLSelectable] = [
|
||||
/// Column(CodingKeys.width),
|
||||
/// Column(CodingKeys.height),
|
||||
/// (Column(CodingKeys.width) * Column(CodingKeys.height)).forKey(CodingKeys.area),
|
||||
/// ]
|
||||
/// }
|
||||
///
|
||||
/// // SELECT width, height, (width * height) AS area FROM shape
|
||||
/// let shapes: [Shape] = try Shape.fetchAll(db)
|
||||
public func forKey(_ key: CodingKey) -> SQLSelectable {
|
||||
forKey(key.stringValue)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - SQL Collations Support
|
||||
|
||||
/// :nodoc:
|
||||
extension SQLSpecificExpressible {
|
||||
|
||||
/// Returns a collated expression.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// Player.filter(Column("email").collating(.nocase) == "contact@example.com")
|
||||
public func collating(_ collation: Database.CollationName) -> SQLCollatedExpression {
|
||||
SQLCollatedExpression(sqlExpression, collationName: collation)
|
||||
}
|
||||
|
||||
/// Returns a collated expression.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// Player.filter(Column("name").collating(.localizedStandardCompare) == "Hervé")
|
||||
public func collating(_ collation: DatabaseCollation) -> SQLCollatedExpression {
|
||||
SQLCollatedExpression(sqlExpression, collationName: Database.CollationName(rawValue: collation.name))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
/// The type that can be embedded as a subquery.
|
||||
public struct SQLSubquery {
|
||||
private var impl: Impl
|
||||
|
||||
private enum Impl {
|
||||
/// A literal SQL query
|
||||
case literal(SQLLiteral)
|
||||
|
||||
/// A query interface query
|
||||
case query(SQLQuery)
|
||||
}
|
||||
|
||||
static func literal(_ sqlLiteral: SQLLiteral) -> Self {
|
||||
self.init(impl: .literal(sqlLiteral))
|
||||
}
|
||||
|
||||
static func query(_ query: SQLQuery) -> Self {
|
||||
self.init(impl: .query(query))
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLSubquery {
|
||||
/// The number of columns selected by the subquery.
|
||||
///
|
||||
/// This method makes it possible to find the columns of a CTE in a request
|
||||
/// that includes a CTE association:
|
||||
///
|
||||
/// // WITH cte AS (SELECT 1 AS a, 2 AS b)
|
||||
/// // SELECT player.*, cte.*
|
||||
/// // FROM player
|
||||
/// // JOIN cte
|
||||
/// let cte = CommonTableExpression(named: "cte", sql: "SELECT 1 AS a, 2 AS b")
|
||||
/// let request = Player
|
||||
/// .with(cte)
|
||||
/// .including(required: Player.association(to: cte))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// // We know that "SELECT 1 AS a, 2 AS b" selects two columns,
|
||||
/// // so we can find cte columns in the row:
|
||||
/// row.scopes["cte"] // [a:1, b:2]
|
||||
func columnsCount(_ db: Database) throws -> Int {
|
||||
switch impl {
|
||||
case let .literal(sqlLiteral):
|
||||
// Compile request. We can freely use the statement cache because we
|
||||
// do not execute the statement or modify its arguments.
|
||||
let context = SQLGenerationContext(db)
|
||||
let sql = try sqlLiteral.sql(context)
|
||||
let statement = try db.cachedSelectStatement(sql: sql)
|
||||
return statement.columnCount
|
||||
|
||||
case let .query(query):
|
||||
return try SQLQueryGenerator(query: query).columnsCount(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLSubquery {
|
||||
/// Returns the subquery SQL.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // SELECT *
|
||||
/// // FROM "player"
|
||||
/// // WHERE "score" = (SELECT MAX("score") FROM "player")
|
||||
/// let maxScore = Player.select(max(Column("score")))
|
||||
/// let players = try Player
|
||||
/// .filter(Column("score") == maxScore)
|
||||
/// .fetchAll(db)
|
||||
///
|
||||
/// - parameter context: An SQL generation context.
|
||||
/// - parameter singleResult: A hint that a single result row will be
|
||||
/// consumed. Implementations can optionally use it to optimize the
|
||||
/// generated SQL, for example by adding a `LIMIT 1` SQL clause.
|
||||
/// - returns: An SQL string.
|
||||
func sql(_ context: SQLGenerationContext) throws -> String {
|
||||
switch impl {
|
||||
case let .literal(sqlLiteral):
|
||||
return try sqlLiteral.sql(context)
|
||||
|
||||
case let .query(query):
|
||||
return try SQLQueryGenerator(query: query, forSingleResult: false).requestSQL(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLSubqueryable
|
||||
|
||||
/// The protocol for types that can be embedded as a subquery.
|
||||
public protocol SQLSubqueryable: SQLSpecificExpressible {
|
||||
var sqlSubquery: SQLSubquery { get }
|
||||
}
|
||||
|
||||
extension SQLSubquery: SQLSubqueryable {
|
||||
// Not a real deprecation, just a usage warning
|
||||
@available(*, deprecated, message: "Already SQLSubquery")
|
||||
public var sqlSubquery: SQLSubquery { self }
|
||||
}
|
||||
|
||||
extension SQLSubqueryable {
|
||||
/// Returns a subquery expression.
|
||||
public var sqlExpression: SQLExpression {
|
||||
.subquery(sqlSubquery)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLSubqueryable {
|
||||
/// Returns an expression that checks the inclusion of the expression in
|
||||
/// the subquery.
|
||||
///
|
||||
/// // 1000 IN (SELECT score FROM player)
|
||||
/// let request = Player.select(Column("score"), as: Int.self)
|
||||
/// let condition = request.contains(1000)
|
||||
public func contains(_ element: SQLExpressible) -> SQLExpression {
|
||||
SQLCollection.subquery(sqlSubquery).contains(element.sqlExpression)
|
||||
}
|
||||
|
||||
/// Returns an expression that checks the inclusion of the expression in
|
||||
/// the subquery.
|
||||
///
|
||||
/// // name COLLATE NOCASE IN (SELECT name FROM player)
|
||||
/// let request = Player.select(Column("name"), as: String.self)
|
||||
/// let condition = request.contains(Column("name").collating(.nocase))
|
||||
public func contains(_ element: SQLCollatedExpression) -> SQLExpression {
|
||||
SQLCollection.subquery(sqlSubquery).contains(element.sqlExpression)
|
||||
}
|
||||
}
|
||||
@@ -9,9 +9,7 @@
|
||||
/// and columns.
|
||||
///
|
||||
/// - It gathers SQL arguments in order to prevent SQL injection.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class SQLGenerationContext {
|
||||
final class SQLGenerationContext {
|
||||
private enum Parent {
|
||||
case none(db: Database, argumentsSink: StatementArgumentsSink)
|
||||
case context(SQLGenerationContext)
|
||||
@@ -63,15 +61,20 @@ public final class SQLGenerationContext {
|
||||
///
|
||||
/// - parameter parent: A parent context.
|
||||
/// - parameter aliases: An array of table aliases to disambiguate.
|
||||
init(
|
||||
private init(
|
||||
parent: SQLGenerationContext,
|
||||
aliases: [TableAlias] = [])
|
||||
aliases: [TableAlias])
|
||||
{
|
||||
self.parent = .context(parent)
|
||||
self.resolvedNames = aliases.resolvedNames
|
||||
self.ownAliases = Set(aliases)
|
||||
}
|
||||
|
||||
/// Returns a generation context suitable for subqueries.
|
||||
func subqueryContext(aliases: [TableAlias] = []) -> SQLGenerationContext {
|
||||
SQLGenerationContext(parent: self, aliases: aliases)
|
||||
}
|
||||
|
||||
/// Returns whether arguments could be appended.
|
||||
///
|
||||
/// A false result means that the generation context does not support
|
||||
@@ -374,26 +377,26 @@ public class TableAlias: Hashable {
|
||||
|
||||
/// Returns a qualified value that is able to resolve ambiguities in
|
||||
/// joined queries.
|
||||
public subscript(_ selectable: SQLSelectable) -> SQLSelectable {
|
||||
selectable._qualifiedSelectable(with: self)
|
||||
public subscript(_ selectable: SQLSelectable) -> SQLSelection {
|
||||
selectable.sqlSelection.qualified(with: self)
|
||||
}
|
||||
|
||||
/// Returns a qualified expression that is able to resolve ambiguities in
|
||||
/// joined queries.
|
||||
public subscript(_ expression: SQLExpression) -> SQLExpression {
|
||||
expression._qualifiedExpression(with: self)
|
||||
public subscript(_ expression: SQLSpecificExpressible & SQLSelectable & SQLOrderingTerm) -> SQLExpression {
|
||||
expression.sqlExpression.qualified(with: self)
|
||||
}
|
||||
|
||||
/// Returns a qualified ordering that is able to resolve ambiguities in
|
||||
/// joined queries.
|
||||
public subscript(_ ordering: SQLOrderingTerm) -> SQLOrderingTerm {
|
||||
ordering._qualifiedOrdering(with: self)
|
||||
public subscript(_ ordering: SQLOrderingTerm) -> SQLOrdering {
|
||||
ordering.sqlOrdering.qualified(with: self)
|
||||
}
|
||||
|
||||
/// Returns a qualified columnn that is able to resolve ambiguities in
|
||||
/// joined queries.
|
||||
public subscript(_ column: String) -> SQLExpression {
|
||||
Column(column)._qualifiedExpression(with: self)
|
||||
.qualifiedColumn(column, self)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
@@ -413,7 +416,7 @@ public class TableAlias: Hashable {
|
||||
/// }
|
||||
public var exists: SQLExpression {
|
||||
// TODO: this fails with SQL views. Can we do something?
|
||||
SQLExpressionQualifiedFastPrimaryKey(alias: self) != nil
|
||||
SQLExpression.qualifiedFastPrimaryKey(self) != nil
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
|
||||
@@ -3,7 +3,7 @@ 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 havingExpressionPromise: DatabasePromise<SQLExpression?>
|
||||
private let limit: SQLLimit?
|
||||
private let singleResult: Bool
|
||||
private let ctes: OrderedDictionary<String, SQLCTE>
|
||||
@@ -47,10 +47,10 @@ struct SQLQueryGenerator: Refinable {
|
||||
// `HAVING MAX(year) < 2000` INTO `HAVING MAX(book.year) < 2000`.
|
||||
let sourceAlias = relation.source.alias
|
||||
groupPromise = query.groupPromise?.map {
|
||||
$0.map { $0._qualifiedExpression(with: sourceAlias) }
|
||||
$0.map { $0.qualified(with: sourceAlias) }
|
||||
}
|
||||
havingExpressionsPromise = query.havingExpressionsPromise.map {
|
||||
$0.map { $0._qualifiedExpression(with: sourceAlias) }
|
||||
havingExpressionPromise = query.havingExpressionPromise.map {
|
||||
$0.map { $0.qualified(with: sourceAlias) }
|
||||
}
|
||||
|
||||
limit = query.limit
|
||||
@@ -61,10 +61,7 @@ struct SQLQueryGenerator: Refinable {
|
||||
}
|
||||
|
||||
func requestSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
// Build an SQL generation context with all aliases found in the query,
|
||||
// so that we can disambiguate tables that are used several times with
|
||||
// SQL aliases.
|
||||
let context = SQLGenerationContext(parent: context, aliases: relation.allAliases)
|
||||
let context = context.subqueryContext(aliases: relation.allAliases)
|
||||
|
||||
var sql = try commonTableExpressionsPrefix(context)
|
||||
sql += "SELECT"
|
||||
@@ -75,7 +72,10 @@ struct SQLQueryGenerator: Refinable {
|
||||
|
||||
let selection = try relation.selectionPromise.resolve(context.db)
|
||||
GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with an empty selection")
|
||||
sql += try " " + selection.map { try $0._resultColumnSQL(context) }.joined(separator: ", ")
|
||||
sql += " "
|
||||
sql += try selection
|
||||
.map { try $0.sql(context) }
|
||||
.joined(separator: ", ")
|
||||
|
||||
sql += " FROM "
|
||||
sql += try relation.source.sql(context)
|
||||
@@ -88,31 +88,30 @@ struct SQLQueryGenerator: Refinable {
|
||||
}
|
||||
}
|
||||
|
||||
let filters = try relation.filtersPromise.resolve(context.db)
|
||||
if filters.isEmpty == false {
|
||||
let filter = try relation.filterPromise.resolve(context.db)
|
||||
if let filter = filter {
|
||||
sql += " WHERE "
|
||||
sql += try filters.joined(operator: .and)._expressionSQL(context, wrappedInParenthesis: false)
|
||||
sql += try filter.sql(context)
|
||||
}
|
||||
|
||||
let groupExpressions = try groupPromise?.resolve(context.db) ?? []
|
||||
if !groupExpressions.isEmpty {
|
||||
sql += " GROUP BY "
|
||||
sql += try groupExpressions
|
||||
.map { try $0._expressionSQL(context, wrappedInParenthesis: false) }
|
||||
.map { try $0.sql(context) }
|
||||
.joined(separator: ", ")
|
||||
}
|
||||
|
||||
let havingExpressions = try havingExpressionsPromise.resolve(context.db)
|
||||
if havingExpressions.isEmpty == false {
|
||||
if let havingExpression = try havingExpressionPromise.resolve(context.db) {
|
||||
sql += " HAVING "
|
||||
sql += try havingExpressions.joined(operator: .and)._expressionSQL(context, wrappedInParenthesis: false)
|
||||
sql += try havingExpression.sql(context)
|
||||
}
|
||||
|
||||
let orderings = try relation.ordering.resolve(context.db)
|
||||
if !orderings.isEmpty {
|
||||
sql += " ORDER BY "
|
||||
sql += try orderings
|
||||
.map { try $0._orderingTermSQL(context) }
|
||||
.map { try $0.sql(context) }
|
||||
.joined(separator: ", ")
|
||||
}
|
||||
|
||||
@@ -120,7 +119,7 @@ struct SQLQueryGenerator: Refinable {
|
||||
if try singleResult && !expectsSingleResult(
|
||||
context.db,
|
||||
selection: selection,
|
||||
filters: filters,
|
||||
filter: filter,
|
||||
groupExpressions: groupExpressions)
|
||||
{
|
||||
limit = SQLLimit(limit: 1, offset: limit?.offset)
|
||||
@@ -146,7 +145,7 @@ struct SQLQueryGenerator: Refinable {
|
||||
.selectionPromise
|
||||
.resolve(db)
|
||||
.reduce(0) {
|
||||
try $0 + $1._columnCount(db)
|
||||
try $0 + $1.columnCount(db)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,7 +179,11 @@ struct SQLQueryGenerator: Refinable {
|
||||
// Note that the request `parent.none().including(all: children)` is
|
||||
// different. Since `parent.none()` is provably empty, its region
|
||||
// is empty, and we thus avoid this code branch.
|
||||
try statement.databaseRegion.formUnion(prefetchedRegion(db, associations: prefetchedAssociations))
|
||||
let region = try prefetchedRegion(
|
||||
db,
|
||||
associations: prefetchedAssociations,
|
||||
from: relation.source.tableName)
|
||||
statement.databaseRegion.formUnion(region)
|
||||
}
|
||||
|
||||
return statement
|
||||
@@ -196,8 +199,9 @@ struct SQLQueryGenerator: Refinable {
|
||||
}
|
||||
|
||||
// The filter knows better
|
||||
let filter = try relation.filtersPromise.resolve(db).joined(operator: .and)
|
||||
guard let rowIDs = try filter._identifyingRowIDs(db, for: relation.source.alias) else {
|
||||
guard let filter = try relation.filterPromise.resolve(db),
|
||||
let rowIDs = try filter.identifyingRowIDs(db, for: relation.source.alias)
|
||||
else {
|
||||
return selectedRegion
|
||||
}
|
||||
|
||||
@@ -210,8 +214,8 @@ struct SQLQueryGenerator: Refinable {
|
||||
/// If false, we don't know how many rows this query returns.
|
||||
private func expectsSingleResult(
|
||||
_ db: Database,
|
||||
selection: [SQLSelectable],
|
||||
filters: [SQLExpression],
|
||||
selection: [SQLSelection],
|
||||
filter: SQLExpression?,
|
||||
groupExpressions: [SQLExpression])
|
||||
throws -> Bool
|
||||
{
|
||||
@@ -222,18 +226,16 @@ struct SQLQueryGenerator: Refinable {
|
||||
|
||||
// Do we filter on a unique key?
|
||||
let tableName = relation.source.tableName
|
||||
if try db.tableExists(tableName) { // skip views
|
||||
let identifyingColums = try filters
|
||||
.joined(operator: .and)
|
||||
._identifyingColums(db, for: relation.source.alias)
|
||||
if try db.table(tableName, hasUniqueKey: identifyingColums) {
|
||||
// Filter by unique key: guaranteed single row!
|
||||
return true
|
||||
}
|
||||
if try db.tableExists(tableName), // skip views
|
||||
let identifyingColums = try filter?.identifyingColums(db, for: relation.source.alias),
|
||||
try db.table(tableName, hasUniqueKey: identifyingColums)
|
||||
{
|
||||
// Filter by unique key: guaranteed single row!
|
||||
return true
|
||||
}
|
||||
|
||||
// Do we aggregate without grouping?
|
||||
if groupExpressions.isEmpty && selection.contains(where: \._isAggregate) {
|
||||
if groupExpressions.isEmpty && selection.contains(where: \.isAggregate) {
|
||||
// Selection contains an aggregate function: guaranteed single row!Ë
|
||||
return true
|
||||
}
|
||||
@@ -253,18 +255,18 @@ struct SQLQueryGenerator: Refinable {
|
||||
var sql = try commonTableExpressionsPrefix(context)
|
||||
sql += try "DELETE FROM " + relation.source.sql(context)
|
||||
|
||||
let filters = try relation.filtersPromise.resolve(db)
|
||||
if filters.isEmpty == false {
|
||||
if let filter = try relation.filterPromise.resolve(db) {
|
||||
sql += " WHERE "
|
||||
sql += try filters
|
||||
.joined(operator: .and)
|
||||
._expressionSQL(context, wrappedInParenthesis: false)
|
||||
sql += try filter.sql(context)
|
||||
}
|
||||
|
||||
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 "
|
||||
sql += try orderings
|
||||
.map { try $0.sql(context) }
|
||||
.joined(separator: ", ")
|
||||
}
|
||||
sql += " LIMIT " + limit.sql
|
||||
}
|
||||
@@ -287,13 +289,13 @@ struct SQLQueryGenerator: Refinable {
|
||||
let tableName = relation.source.tableName
|
||||
let alias = TableAlias(tableName: tableName)
|
||||
let context = SQLGenerationContext(db, aliases: [alias])
|
||||
let subqueryContext = SQLGenerationContext(parent: context, aliases: relation.allAliases)
|
||||
let primaryKey = SQLExpressionFastPrimaryKey()
|
||||
let subqueryContext = context.subqueryContext(aliases: relation.allAliases)
|
||||
let primaryKey = SQLExpression.fastPrimaryKey
|
||||
|
||||
var sql = "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE "
|
||||
sql += try alias[primaryKey]._expressionSQL(context, wrappedInParenthesis: false)
|
||||
sql += try alias[primaryKey].sql(context)
|
||||
sql += " IN ("
|
||||
sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).requestSQL(subqueryContext)
|
||||
sql += try map(\.relation, { $0.selectOnly([.expression(primaryKey)]) }).requestSQL(subqueryContext)
|
||||
sql += ")"
|
||||
|
||||
let statement = try db.makeUpdateStatement(sql: sql)
|
||||
@@ -334,23 +336,23 @@ struct SQLQueryGenerator: Refinable {
|
||||
|
||||
sql += try relation.source.sql(context)
|
||||
|
||||
let assignmentsSQL = try assignments
|
||||
sql += " SET "
|
||||
sql += try assignments
|
||||
.map { try $0.sql(context) }
|
||||
.joined(separator: ", ")
|
||||
sql += " SET " + assignmentsSQL
|
||||
|
||||
let filters = try relation.filtersPromise.resolve(db)
|
||||
if filters.isEmpty == false {
|
||||
if let filter = try relation.filterPromise.resolve(db) {
|
||||
sql += " WHERE "
|
||||
sql += try filters
|
||||
.joined(operator: .and)
|
||||
._expressionSQL(context, wrappedInParenthesis: false)
|
||||
sql += try filter.sql(context)
|
||||
}
|
||||
|
||||
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 "
|
||||
sql += try orderings
|
||||
.map { try $0.sql(context) }
|
||||
.joined(separator: ", ")
|
||||
}
|
||||
sql += " LIMIT " + limit.sql
|
||||
}
|
||||
@@ -385,8 +387,8 @@ struct SQLQueryGenerator: Refinable {
|
||||
let tableName = relation.source.tableName
|
||||
let alias = TableAlias(tableName: tableName)
|
||||
let context = SQLGenerationContext(db, aliases: [alias])
|
||||
let subqueryContext = SQLGenerationContext(parent: context, aliases: relation.allAliases)
|
||||
let primaryKey = SQLExpressionFastPrimaryKey()
|
||||
let subqueryContext = context.subqueryContext(aliases: relation.allAliases)
|
||||
let primaryKey = SQLExpression.fastPrimaryKey
|
||||
|
||||
// UPDATE table...
|
||||
var sql = "UPDATE "
|
||||
@@ -396,16 +398,16 @@ struct SQLQueryGenerator: Refinable {
|
||||
sql += tableName.quotedDatabaseIdentifier
|
||||
|
||||
// SET column = value...
|
||||
let assignmentsSQL = try assignments
|
||||
sql += " SET "
|
||||
sql += try assignments
|
||||
.map { try $0.sql(context) }
|
||||
.joined(separator: ", ")
|
||||
sql += " SET " + assignmentsSQL
|
||||
|
||||
// WHERE id IN (SELECT id FROM ...)
|
||||
sql += " WHERE "
|
||||
sql += try alias[primaryKey]._expressionSQL(context, wrappedInParenthesis: false)
|
||||
sql += try alias[primaryKey].sql(context)
|
||||
sql += " IN ("
|
||||
sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).requestSQL(subqueryContext)
|
||||
sql += try map(\.relation, { $0.selectOnly([.expression(primaryKey)]) }).requestSQL(subqueryContext)
|
||||
sql += ")"
|
||||
|
||||
let statement = try db.makeUpdateStatement(sql: sql)
|
||||
@@ -427,14 +429,14 @@ struct SQLQueryGenerator: Refinable {
|
||||
var columnsSQL = ""
|
||||
if let columns = cte.columns, !columns.isEmpty {
|
||||
columnsSQL = "("
|
||||
+ columns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")
|
||||
+ ")"
|
||||
columnsSQL += columns
|
||||
.map(\.quotedDatabaseIdentifier)
|
||||
.joined(separator: ", ")
|
||||
columnsSQL += ")"
|
||||
}
|
||||
let cteContext = SQLGenerationContext(parent: context)
|
||||
let requestSQL = try cte.requestPromise
|
||||
.resolve(context.db)
|
||||
._requestSQL(cteContext, forSingleResult: false)
|
||||
return "\(tableName.quotedDatabaseIdentifier)\(columnsSQL) AS (\(requestSQL))"
|
||||
let cteContext = context.subqueryContext()
|
||||
let subquerySQL = try cte.sqlSubquery.sql(cteContext)
|
||||
return "\(tableName.quotedDatabaseIdentifier)\(columnsSQL) AS (\(subquerySQL))"
|
||||
}
|
||||
.joined(separator: ", ")
|
||||
sql += " "
|
||||
@@ -467,7 +469,7 @@ struct SQLQueryGenerator: Refinable {
|
||||
|
||||
var groupingColumns: Set<String> = []
|
||||
for expression in groupExpressions {
|
||||
guard let column = try expression._column(db, for: relation.source.alias, acceptsBijection: true) else {
|
||||
guard let column = try expression.column(db, for: relation.source.alias, acceptsBijection: true) else {
|
||||
// Grouping by something which is not a column: assume non
|
||||
// unique grouping.
|
||||
return .nonUnique
|
||||
@@ -541,14 +543,14 @@ private struct SQLQualifiedRelation {
|
||||
let source: SQLQualifiedSource
|
||||
|
||||
/// The selection from source, not including selection of joined relations
|
||||
private var sourceSelectionPromise: DatabasePromise<[SQLSelectable]>
|
||||
private var sourceSelectionPromise: DatabasePromise<[SQLSelection]>
|
||||
|
||||
/// The full selection, including selection of joined relations
|
||||
///
|
||||
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
|
||||
/// |
|
||||
/// • selectionPromise
|
||||
var selectionPromise: DatabasePromise<[SQLSelectable]> {
|
||||
var selectionPromise: DatabasePromise<[SQLSelection]> {
|
||||
DatabasePromise { db in
|
||||
let selection = try self.sourceSelectionPromise.resolve(db)
|
||||
return try self.joins.values.reduce(into: selection) { selection, join in
|
||||
@@ -562,8 +564,8 @@ private struct SQLQualifiedRelation {
|
||||
///
|
||||
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
|
||||
/// |
|
||||
/// • filtersPromise
|
||||
let filtersPromise: DatabasePromise<[SQLExpression]>
|
||||
/// • filterPromise
|
||||
let filterPromise: DatabasePromise<SQLExpression?>
|
||||
|
||||
/// The ordering of source, not including ordering of joined relations
|
||||
private let sourceOrdering: SQLRelation.Ordering
|
||||
@@ -599,10 +601,10 @@ private struct SQLQualifiedRelation {
|
||||
joins = relation.children.compactMapValues { SQLQualifiedJoin($0) }
|
||||
let sourceAlias = source.alias
|
||||
sourceSelectionPromise = relation.selectionPromise.map {
|
||||
$0.map { $0._qualifiedSelectable(with: sourceAlias) }
|
||||
$0.map { $0.qualified(with: sourceAlias) }
|
||||
}
|
||||
filtersPromise = relation.filtersPromise.map {
|
||||
$0.map { $0._qualifiedExpression(with: sourceAlias) }
|
||||
filterPromise = relation.filterPromise.map {
|
||||
$0.map { $0.qualified(with: sourceAlias) }
|
||||
}
|
||||
sourceOrdering = relation.ordering.qualified(with: sourceAlias)
|
||||
}
|
||||
@@ -626,7 +628,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) {
|
||||
try $0 + $1._columnCount(db)
|
||||
try $0 + $1.columnCount(db)
|
||||
}
|
||||
|
||||
// Recursively build adapters for each joined relation with a selection.
|
||||
@@ -668,9 +670,9 @@ private struct SQLQualifiedRelation {
|
||||
}
|
||||
|
||||
/// Removes all selections from joins
|
||||
func selectOnly(_ selection: [SQLSelectable]) -> Self {
|
||||
func selectOnly(_ selection: [SQLSelection]) -> Self {
|
||||
let sourceSelectionPromise = DatabasePromise(value: selection.map {
|
||||
$0._qualifiedSelectable(with: source.alias)
|
||||
$0.qualified(with: source.alias)
|
||||
})
|
||||
return self
|
||||
.with(\.sourceSelectionPromise, sourceSelectionPromise)
|
||||
@@ -712,7 +714,7 @@ private struct SQLQualifiedJoin: Refinable {
|
||||
self = .innerJoin
|
||||
case .oneOptional:
|
||||
self = .leftJoin
|
||||
case .allPrefetched, .allNotPrefetched:
|
||||
case .all, .bridge:
|
||||
// Eager loading of to-many associations is not implemented with joins
|
||||
return nil
|
||||
}
|
||||
@@ -737,7 +739,7 @@ private struct SQLQualifiedJoin: Refinable {
|
||||
}
|
||||
|
||||
/// Removes all selections from joins
|
||||
func selectOnly(_ selection: [SQLSelectable]) -> SQLQualifiedJoin {
|
||||
func selectOnly(_ selection: [SQLSelection]) -> SQLQualifiedJoin {
|
||||
map(\.relation) { $0.selectOnly(selection) }
|
||||
}
|
||||
|
||||
@@ -765,33 +767,27 @@ private struct SQLQualifiedJoin: Refinable {
|
||||
|
||||
// JOIN table...
|
||||
var sql = try "\(kind.rawValue) \(relation.source.sql(context))"
|
||||
let rightAlias = relation.source.alias
|
||||
|
||||
// ... ON <join conditions>
|
||||
var joinExpressions: [SQLExpression]
|
||||
switch condition {
|
||||
case let .expression(condition):
|
||||
joinExpressions = [condition(leftAlias, rightAlias).sqlExpression]
|
||||
|
||||
case let .foreignKey(request: foreignKeyRequest, originIsLeft: originIsLeft):
|
||||
joinExpressions = try foreignKeyRequest
|
||||
.fetchForeignKeyMapping(context.db)
|
||||
.joinMapping(originIsLeft: originIsLeft)
|
||||
.joinExpressions(leftAlias: leftAlias)
|
||||
// ... ON <join conditions> AND <other filters>
|
||||
let rightAlias = relation.source.alias
|
||||
var conditions: [SQLExpression] = []
|
||||
|
||||
if let expression = try condition.joinExpression(context.db,
|
||||
leftAlias: leftAlias,
|
||||
rightAlias: rightAlias)
|
||||
{
|
||||
conditions.append(expression)
|
||||
}
|
||||
|
||||
// ... ON ... AND <other filters>
|
||||
joinExpressions += try relation.filtersPromise.resolve(context.db)
|
||||
if let filter = try relation.filterPromise.resolve(context.db) {
|
||||
conditions.append(filter.qualified(with: rightAlias))
|
||||
}
|
||||
|
||||
// Avoid generating on ON clause for trivially true conditions
|
||||
joinExpressions = joinExpressions.filter { !$0._isTrue }
|
||||
|
||||
if joinExpressions.isEmpty == false {
|
||||
let joiningSQL = try joinExpressions
|
||||
if conditions.isEmpty == false {
|
||||
sql += " ON "
|
||||
sql += try conditions
|
||||
.joined(operator: .and)
|
||||
._qualifiedExpression(with: rightAlias)
|
||||
._expressionSQL(context, wrappedInParenthesis: false)
|
||||
sql += " ON \(joiningSQL)"
|
||||
.sql(context)
|
||||
}
|
||||
|
||||
for (_, join) in relation.joins {
|
||||
|
||||
@@ -57,7 +57,7 @@ extension SQLInterpolation {
|
||||
{
|
||||
let alias = TableAlias(name: tableAlias ?? T.databaseTableName)
|
||||
elements.append(contentsOf: T.databaseSelection
|
||||
.map { CollectionOfOne(.selectable($0._qualifiedSelectable(with: alias))) }
|
||||
.map { CollectionOfOne(.selection($0.sqlSelection.qualified(with: alias))) }
|
||||
.joined(separator: CollectionOfOne(.sql(", "))))
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@ extension SQLInterpolation {
|
||||
public mutating func appendInterpolation<T>(_ selection: T)
|
||||
where T: SQLSelectable
|
||||
{
|
||||
elements.append(.selectable(selection))
|
||||
elements.append(.selection(selection.sqlSelection))
|
||||
}
|
||||
|
||||
/// Appends the selectable SQL, or NULL if it is nil.
|
||||
@@ -84,7 +84,7 @@ extension SQLInterpolation {
|
||||
@_disfavoredOverload
|
||||
public mutating func appendInterpolation(_ selection: SQLSelectable?) {
|
||||
if let selection = selection {
|
||||
elements.append(.selectable(selection))
|
||||
elements.append(.selection(selection.sqlSelection))
|
||||
} else {
|
||||
appendLiteral("NULL")
|
||||
}
|
||||
@@ -101,7 +101,7 @@ extension SQLInterpolation {
|
||||
public mutating func appendInterpolation<T>(_ orderingTerm: T)
|
||||
where T: SQLOrderingTerm
|
||||
{
|
||||
elements.append(.orderingTerm(orderingTerm))
|
||||
elements.append(.ordering(orderingTerm.sqlOrdering))
|
||||
}
|
||||
|
||||
/// Appends the ordering SQL.
|
||||
@@ -112,23 +112,11 @@ extension SQLInterpolation {
|
||||
/// """
|
||||
@_disfavoredOverload
|
||||
public mutating func appendInterpolation(_ orderingTerm: SQLOrderingTerm) {
|
||||
elements.append(.orderingTerm(orderingTerm))
|
||||
elements.append(.ordering(orderingTerm.sqlOrdering))
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressible
|
||||
|
||||
/// Appends the expression SQL.
|
||||
///
|
||||
/// // SELECT name FROM player
|
||||
/// let request: SQLRequest<String> = """
|
||||
/// SELECT \(Column("name")) FROM player
|
||||
/// """
|
||||
public mutating func appendInterpolation<T>(_ expressible: T)
|
||||
where T: SQLExpressible
|
||||
{
|
||||
elements.append(.expression(expressible.sqlExpression))
|
||||
}
|
||||
|
||||
/// Appends the expression SQL.
|
||||
///
|
||||
/// // SELECT name FROM player
|
||||
@@ -193,7 +181,7 @@ extension SQLInterpolation {
|
||||
appendInterpolation(Column(key.stringValue))
|
||||
}
|
||||
|
||||
// MARK: - SQLRequestProtocol
|
||||
// MARK: - FetchRequest
|
||||
|
||||
/// Appends the request SQL (not wrapped inside parentheses).
|
||||
///
|
||||
@@ -205,10 +193,10 @@ extension SQLInterpolation {
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT * FROM player WHERE score = (\(subquery))
|
||||
/// """
|
||||
public mutating func appendInterpolation<T>(_ request: T)
|
||||
where T: FetchRequest & SQLExpression
|
||||
public mutating func appendInterpolation<T>(_ subquery: T)
|
||||
where T: SQLSubqueryable & SQLExpressible & SQLSelectable & SQLOrderingTerm
|
||||
{
|
||||
elements.append(.subquery(DatabasePromise(value: request)))
|
||||
elements.append(.subquery(subquery.sqlSubquery))
|
||||
}
|
||||
|
||||
// MARK: - Sequence
|
||||
@@ -231,7 +219,14 @@ extension SQLInterpolation {
|
||||
public mutating func appendInterpolation<T>(_ sequence: T)
|
||||
where T: Sequence, T.Element: SQLExpressible
|
||||
{
|
||||
appendInterpolation(sequence.lazy.map(\.sqlExpression))
|
||||
let e: [SQLLiteral.Element] = sequence.map { .expression($0.sqlExpression) }
|
||||
if e.isEmpty {
|
||||
appendLiteral("(SELECT NULL WHERE NULL)")
|
||||
} else {
|
||||
appendLiteral("(")
|
||||
elements.append(contentsOf: e.map(CollectionOfOne.init(_:)).joined(separator: CollectionOfOne(.sql(","))))
|
||||
appendLiteral(")")
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends a sequence of expressions, wrapped in parentheses.
|
||||
@@ -250,16 +245,9 @@ extension SQLInterpolation {
|
||||
/// SELECT * FROM player WHERE a IN \(expressions)
|
||||
/// """
|
||||
public mutating func appendInterpolation<T>(_ sequence: T)
|
||||
where T: Sequence, T.Element == SQLExpression
|
||||
where T: Sequence, T.Element == SQLExpressible
|
||||
{
|
||||
let e: [SQLLiteral.Element] = sequence.map { .expression($0.sqlExpression) }
|
||||
if e.isEmpty {
|
||||
appendLiteral("(SELECT NULL WHERE NULL)")
|
||||
} else {
|
||||
appendLiteral("(")
|
||||
elements.append(contentsOf: e.map(CollectionOfOne.init(_:)).joined(separator: CollectionOfOne(.sql(","))))
|
||||
appendLiteral(")")
|
||||
}
|
||||
appendInterpolation(sequence.lazy.map(\.sqlExpression))
|
||||
}
|
||||
|
||||
// When a value is both an expression and a sequence of expressions,
|
||||
@@ -271,12 +259,12 @@ extension SQLInterpolation {
|
||||
elements.append(.expression(expressible.sqlExpression))
|
||||
}
|
||||
|
||||
// MARK: Common Table Expressions
|
||||
// MARK: - Common Table Expressions
|
||||
|
||||
/// Appends the table name of the common table expression.
|
||||
///
|
||||
/// // WITH "cte" AS (...) SELECT * FROM "cte"
|
||||
/// let cte = CommonTableExpression<Void>(named: "cte", ...)
|
||||
/// let cte = CommonTableExpression(named: "cte", ...)
|
||||
/// let request: SQLRequest<Row> = """
|
||||
/// WITH \(definitionFor: cte) SELECT * FROM \(cte)
|
||||
/// """
|
||||
@@ -287,7 +275,7 @@ extension SQLInterpolation {
|
||||
/// Appends the definition of the common table expression.
|
||||
///
|
||||
/// // WITH "cte" AS (...) SELECT * FROM "cte"
|
||||
/// let cte = CommonTableExpression<Void>(named: "cte", ...)
|
||||
/// let cte = CommonTableExpression(named: "cte", ...)
|
||||
/// let request: SQLRequest<Row> = """
|
||||
/// WITH \(definitionFor: cte) SELECT * FROM \(cte)
|
||||
/// """
|
||||
@@ -302,7 +290,29 @@ extension SQLInterpolation {
|
||||
}
|
||||
|
||||
elements.append(.sql(" AS ("))
|
||||
elements.append(.subquery(cte.cte.requestPromise))
|
||||
elements.append(.subquery(cte.cte.sqlSubquery))
|
||||
elements.append(.sql(")"))
|
||||
}
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// Appends the name of the collation.
|
||||
///
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT * FROM player
|
||||
/// ORDER BY name COLLATING \(DatabaseCollation.localizedCaseInsensitiveCompare)
|
||||
/// """
|
||||
public mutating func appendInterpolation(_ collation: DatabaseCollation) {
|
||||
elements.append(.sql(collation.name))
|
||||
}
|
||||
|
||||
/// Appends the name of the collation.
|
||||
///
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT * FROM player
|
||||
/// ORDER BY email COLLATING \(.nocase)
|
||||
/// """
|
||||
public mutating func appendInterpolation(_ collation: Database.CollationName) {
|
||||
elements.append(.sql(collation.rawValue))
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
// MARK: - Associations to TableRecord
|
||||
|
||||
extension TableRecord {
|
||||
/// Creates a "Belongs To" association between Self and the destination
|
||||
/// type, based on a database foreign key.
|
||||
@@ -63,7 +65,6 @@ extension TableRecord {
|
||||
where Destination: TableRecord
|
||||
{
|
||||
BelongsToAssociation(
|
||||
from: databaseTableName,
|
||||
to: Destination.relationForAll,
|
||||
key: key,
|
||||
using: foreignKey)
|
||||
@@ -133,12 +134,150 @@ extension TableRecord {
|
||||
where Destination: TableRecord
|
||||
{
|
||||
HasManyAssociation(
|
||||
from: databaseTableName,
|
||||
to: Destination.relationForAll,
|
||||
key: key,
|
||||
using: foreignKey)
|
||||
}
|
||||
|
||||
/// Creates a "Has one" association between Self and the destination type,
|
||||
/// based on a database foreign key.
|
||||
///
|
||||
/// struct Demographics: TableRecord { ... }
|
||||
/// struct Country: TableRecord {
|
||||
/// static let demographics = hasOne(Demographics.self)
|
||||
/// }
|
||||
///
|
||||
/// The association will let you define requests that load both the source
|
||||
/// and the destination type:
|
||||
///
|
||||
/// // A request for all countries with their demographic profile:
|
||||
/// let request = Country.including(optional: Country.demographics)
|
||||
///
|
||||
/// To consume those requests, define a type that adopts both the
|
||||
/// FetchableRecord and Decodable protocols:
|
||||
///
|
||||
/// struct CountryInfo: FetchableRecord, Decodable {
|
||||
/// var country: Country
|
||||
/// var demographics: Demographics?
|
||||
/// }
|
||||
///
|
||||
/// let countryInfos = try dbQueue.read { db in
|
||||
/// return try CountryInfo.fetchAll(db, request)
|
||||
/// }
|
||||
/// for countryInfo in countryInfos {
|
||||
/// print("\(countryInfo.country.name) has \(countryInfo.demographics.population) citizens")
|
||||
/// }
|
||||
///
|
||||
/// It is recommended that you define, alongside the static association, a
|
||||
/// property with the same name:
|
||||
///
|
||||
/// struct Country: TableRecord, EncodableRecord {
|
||||
/// static let demographics = hasOne(Demographics.self)
|
||||
/// var demographics: QueryInterfaceRequest<Demographics> {
|
||||
/// return request(for: Country.demographics)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// This property will let you navigate from the source type to the
|
||||
/// destination type:
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let country: Country = ...
|
||||
/// let demographics = try country.demographics.fetchOne(db) // Demographics?
|
||||
/// }
|
||||
///
|
||||
/// - parameters:
|
||||
/// - destination: The record type at the other side of the association.
|
||||
/// - key: An eventual decoding key for the association. By default, it
|
||||
/// is `destination.databaseTableName`.
|
||||
/// - foreignKey: An eventual foreign key. You need to provide an
|
||||
/// explicit foreign key when GRDB can't infer one from the database
|
||||
/// schema. This happens when the schema does not define any foreign
|
||||
/// key from the destination table, or when the schema defines several
|
||||
/// foreign keys from the destination table.
|
||||
public static func hasOne<Destination>(
|
||||
_ destination: Destination.Type,
|
||||
key: String? = nil,
|
||||
using foreignKey: ForeignKey? = nil)
|
||||
-> HasOneAssociation<Self, Destination>
|
||||
where Destination: TableRecord
|
||||
{
|
||||
HasOneAssociation(
|
||||
to: Destination.relationForAll,
|
||||
key: key,
|
||||
using: foreignKey)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Associations to CommonTableExpression
|
||||
|
||||
extension TableRecord {
|
||||
/// Creates an association to a common table expression that you can join
|
||||
/// or include in another request.
|
||||
///
|
||||
/// The key of the returned association is the table name of the common
|
||||
/// table expression.
|
||||
///
|
||||
/// For example, you can build a request that fetches all chats with their
|
||||
/// latest message:
|
||||
///
|
||||
/// let latestMessageRequest = Message
|
||||
/// .annotated(with: max(Column("date")))
|
||||
/// .group(Column("chatID"))
|
||||
///
|
||||
/// let latestMessageCTE = CommonTableExpression(
|
||||
/// named: "latestMessage",
|
||||
/// request: latestMessageRequest)
|
||||
///
|
||||
/// let latestMessage = Chat.association(
|
||||
/// to: latestMessageCTE,
|
||||
/// on: { chat, latestMessage in
|
||||
/// chat[Column("id")] == latestMessage[Column("chatID")]
|
||||
/// })
|
||||
///
|
||||
/// // WITH latestMessage AS
|
||||
/// // (SELECT *, MAX(date) FROM message GROUP BY chatID)
|
||||
/// // SELECT chat.*, latestMessage.*
|
||||
/// // FROM chat
|
||||
/// // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID
|
||||
/// let request = Chat
|
||||
/// .with(latestMessageCTE)
|
||||
/// .including(optional: latestMessage)
|
||||
///
|
||||
/// - parameter cte: A common table expression.
|
||||
/// - parameter condition: A function that returns the joining clause.
|
||||
/// - parameter left: A `TableAlias` for the left table.
|
||||
/// - parameter right: A `TableAlias` for the right table.
|
||||
/// - returns: An association to the common table expression.
|
||||
public static func association<Destination>(
|
||||
to cte: CommonTableExpression<Destination>,
|
||||
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> SQLExpressible)
|
||||
-> JoinAssociation<Self, Destination>
|
||||
{
|
||||
JoinAssociation(
|
||||
to: cte.relationForAll,
|
||||
condition: .expression { condition($0, $1).sqlExpression })
|
||||
}
|
||||
|
||||
/// Creates an association to a common table expression that you can join
|
||||
/// or include in another request.
|
||||
///
|
||||
/// The key of the returned association is the table name of the common
|
||||
/// table expression.
|
||||
///
|
||||
/// - parameter cte: A common table expression.
|
||||
/// - returns: An association to the common table expression.
|
||||
public static func association<Destination>(
|
||||
to cte: CommonTableExpression<Destination>)
|
||||
-> JoinAssociation<Self, Destination>
|
||||
{
|
||||
JoinAssociation(to: cte.relationForAll, condition: .none)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - "Through" Associations
|
||||
|
||||
extension TableRecord {
|
||||
/// Creates a "Has Many Through" association between Self and the
|
||||
/// destination type.
|
||||
///
|
||||
@@ -221,76 +360,6 @@ extension TableRecord {
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a "Has one" association between Self and the destination type,
|
||||
/// based on a database foreign key.
|
||||
///
|
||||
/// struct Demographics: TableRecord { ... }
|
||||
/// struct Country: TableRecord {
|
||||
/// static let demographics = hasOne(Demographics.self)
|
||||
/// }
|
||||
///
|
||||
/// The association will let you define requests that load both the source
|
||||
/// and the destination type:
|
||||
///
|
||||
/// // A request for all countries with their demographic profile:
|
||||
/// let request = Country.including(optional: Country.demographics)
|
||||
///
|
||||
/// To consume those requests, define a type that adopts both the
|
||||
/// FetchableRecord and Decodable protocols:
|
||||
///
|
||||
/// struct CountryInfo: FetchableRecord, Decodable {
|
||||
/// var country: Country
|
||||
/// var demographics: Demographics?
|
||||
/// }
|
||||
///
|
||||
/// let countryInfos = try dbQueue.read { db in
|
||||
/// return try CountryInfo.fetchAll(db, request)
|
||||
/// }
|
||||
/// for countryInfo in countryInfos {
|
||||
/// print("\(countryInfo.country.name) has \(countryInfo.demographics.population) citizens")
|
||||
/// }
|
||||
///
|
||||
/// It is recommended that you define, alongside the static association, a
|
||||
/// property with the same name:
|
||||
///
|
||||
/// struct Country: TableRecord, EncodableRecord {
|
||||
/// static let demographics = hasOne(Demographics.self)
|
||||
/// var demographics: QueryInterfaceRequest<Demographics> {
|
||||
/// return request(for: Country.demographics)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// This property will let you navigate from the source type to the
|
||||
/// destination type:
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let country: Country = ...
|
||||
/// let demographics = try country.demographics.fetchOne(db) // Demographics?
|
||||
/// }
|
||||
///
|
||||
/// - parameters:
|
||||
/// - destination: The record type at the other side of the association.
|
||||
/// - key: An eventual decoding key for the association. By default, it
|
||||
/// is `destination.databaseTableName`.
|
||||
/// - foreignKey: An eventual foreign key. You need to provide an
|
||||
/// explicit foreign key when GRDB can't infer one from the database
|
||||
/// schema. This happens when the schema does not define any foreign
|
||||
/// key from the destination table, or when the schema defines several
|
||||
/// foreign keys from the destination table.
|
||||
public static func hasOne<Destination>(
|
||||
_ destination: Destination.Type,
|
||||
key: String? = nil,
|
||||
using foreignKey: ForeignKey? = nil)
|
||||
-> HasOneAssociation<Self, Destination>
|
||||
where Destination: TableRecord
|
||||
{
|
||||
HasOneAssociation(
|
||||
from: databaseTableName,
|
||||
to: Destination.relationForAll,
|
||||
key: key,
|
||||
using: foreignKey)
|
||||
}
|
||||
|
||||
/// Creates a "Has One Through" association between Self and the
|
||||
/// destination type.
|
||||
///
|
||||
@@ -374,114 +443,7 @@ extension TableRecord {
|
||||
}
|
||||
}
|
||||
|
||||
/// A ForeignKey helps building associations when GRDB can't infer a foreign
|
||||
/// key from the database schema.
|
||||
///
|
||||
/// Sometimes the database schema does not define any foreign key between two
|
||||
/// tables. And sometimes, there are several foreign keys from a table
|
||||
/// to another:
|
||||
///
|
||||
/// | Table book | | Table person |
|
||||
/// | ------------ | | ------------ |
|
||||
/// | id | +-->• id |
|
||||
/// | authorId •---+ | name |
|
||||
/// | translatorId •---+
|
||||
/// | title |
|
||||
///
|
||||
/// When this happens, associations can't be automatically inferred from the
|
||||
/// database schema. GRDB will complain with a fatal error such as "Ambiguous
|
||||
/// foreign key from book to person", or "Could not infer foreign key from book
|
||||
/// to person".
|
||||
///
|
||||
/// Your help is needed. You have to instruct GRDB which foreign key to use:
|
||||
///
|
||||
/// struct Book: TableRecord {
|
||||
/// // Define foreign keys
|
||||
/// static let authorForeignKey = ForeignKey(["authorId"]))
|
||||
/// static let translatorForeignKey = ForeignKey(["translatorId"]))
|
||||
///
|
||||
/// // Use foreign keys to define associations:
|
||||
/// static let author = belongsTo(Person.self, using: authorForeignKey)
|
||||
/// static let translator = belongsTo(Person.self, using: translatorForeignKey)
|
||||
/// }
|
||||
///
|
||||
/// Foreign keys are always defined from the table that contains the columns at
|
||||
/// the origin of the foreign key. Person's symmetric HasMany associations reuse
|
||||
/// Book's foreign keys:
|
||||
///
|
||||
/// struct Person: TableRecord {
|
||||
/// static let writtenBooks = hasMany(Book.self, using: Book.authorForeignKey)
|
||||
/// static let translatedBooks = hasMany(Book.self, using: Book.translatorForeignKey)
|
||||
/// }
|
||||
///
|
||||
/// Foreign keys can also be defined from query interface columns:
|
||||
///
|
||||
/// struct Book: TableRecord {
|
||||
/// enum Columns: String, ColumnExpression {
|
||||
/// case id, title, authorId, translatorId
|
||||
/// }
|
||||
///
|
||||
/// static let authorForeignKey = ForeignKey([Columns.authorId]))
|
||||
/// static let translatorForeignKey = ForeignKey([Columns.translatorId]))
|
||||
/// }
|
||||
///
|
||||
/// When the destination table of a foreign key does not define any primary key,
|
||||
/// you need to provide the full definition of a foreign key:
|
||||
///
|
||||
/// struct Book: TableRecord {
|
||||
/// static let authorForeignKey = ForeignKey(["authorId"], to: ["id"]))
|
||||
/// static let author = belongsTo(Person.self, using: authorForeignKey)
|
||||
/// }
|
||||
public struct ForeignKey {
|
||||
var originColumns: [String]
|
||||
var destinationColumns: [String]?
|
||||
|
||||
/// Creates a ForeignKey intended to define a record association.
|
||||
///
|
||||
/// struct Book: TableRecord {
|
||||
/// // Define foreign keys
|
||||
/// static let authorForeignKey = ForeignKey(["authorId"]))
|
||||
/// static let translatorForeignKey = ForeignKey(["translatorId"]))
|
||||
///
|
||||
/// // Use foreign keys to define associations:
|
||||
/// static let author = belongsTo(Person.self, using: authorForeignKey)
|
||||
/// static let translator = belongsTo(Person.self, using: translatorForeignKey)
|
||||
/// }
|
||||
///
|
||||
/// - parameter originColumns: The columns at the origin of the foreign key.
|
||||
/// - parameter destinationColumns: The columns at the destination of the
|
||||
/// foreign key. When nil (the default), GRDB automatically uses the
|
||||
/// primary key.
|
||||
public init(_ originColumns: [String], to destinationColumns: [String]? = nil) {
|
||||
self.originColumns = originColumns
|
||||
self.destinationColumns = destinationColumns
|
||||
}
|
||||
|
||||
/// Creates a ForeignKey intended to define a record association.
|
||||
///
|
||||
/// struct Book: TableRecord {
|
||||
/// // Define columns
|
||||
/// enum Columns: String, ColumnExpression {
|
||||
/// case id, title, authorId, translatorId
|
||||
/// }
|
||||
///
|
||||
/// // Define foreign keys
|
||||
/// static let authorForeignKey = ForeignKey([Columns.authorId]))
|
||||
/// static let translatorForeignKey = ForeignKey([Columns.translatorId]))
|
||||
///
|
||||
/// // Use foreign keys to define associations:
|
||||
/// static let author = belongsTo(Person.self, using: authorForeignKey)
|
||||
/// static let translator = belongsTo(Person.self, using: translatorForeignKey)
|
||||
/// }
|
||||
///
|
||||
/// - parameter originColumns: The columns at the origin of the foreign key.
|
||||
/// - parameter destinationColumns: The columns at the destination of the
|
||||
/// foreign key. When nil (the default), GRDB automatically uses the
|
||||
/// primary key.
|
||||
public init(_ originColumns: [ColumnExpression], to destinationColumns: [ColumnExpression]? = nil) {
|
||||
self.init(originColumns.map(\.name), to: destinationColumns?.map(\.name))
|
||||
}
|
||||
}
|
||||
// MARK: - Request for associated records
|
||||
|
||||
extension TableRecord where Self: EncodableRecord {
|
||||
/// Creates a request that fetches the associated record(s).
|
||||
@@ -506,15 +468,14 @@ extension TableRecord where Self: EncodableRecord {
|
||||
// TODO: find a use case?
|
||||
fatalError("Not implemented: request association without any foreign key")
|
||||
|
||||
case let .foreignKey(request: foreignKeyRequest, originIsLeft: originIsLeft):
|
||||
case let .foreignKey(foreignKey):
|
||||
let destinationRelation = association
|
||||
._sqlAssociation
|
||||
.map(\.pivot.relation, { pivotRelation in
|
||||
pivotRelation.filter { db in
|
||||
// Filter the pivot on self
|
||||
try foreignKeyRequest
|
||||
.fetchForeignKeyMapping(db)
|
||||
.joinMapping(originIsLeft: originIsLeft)
|
||||
try foreignKey
|
||||
.joinMapping(db, from: Self.databaseTableName)
|
||||
.joinExpression(leftRows: [PersistenceContainer(db, self)])
|
||||
}
|
||||
})
|
||||
@@ -524,10 +485,9 @@ extension TableRecord where Self: EncodableRecord {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Joining Methods
|
||||
|
||||
extension TableRecord {
|
||||
|
||||
// MARK: - Associations
|
||||
|
||||
/// Creates a request that prefetches an association.
|
||||
public static func including<A: AssociationToMany>(all association: A)
|
||||
-> QueryInterfaceRequest<Self>
|
||||
@@ -575,9 +535,11 @@ extension TableRecord {
|
||||
{
|
||||
all().joining(required: association)
|
||||
}
|
||||
|
||||
// MARK: - Association Aggregates
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Aggregates
|
||||
|
||||
extension TableRecord {
|
||||
/// Creates a request with *aggregates* appended to the selection.
|
||||
///
|
||||
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
|
||||
|
||||
@@ -3,7 +3,7 @@ extension TableRecord {
|
||||
// MARK: Request Derivation
|
||||
|
||||
static var relationForAll: SQLRelation {
|
||||
.all(fromTable: databaseTableName, selection: { _ in databaseSelection })
|
||||
.all(fromTable: databaseTableName, selection: { _ in databaseSelection.map(\.sqlSelection) })
|
||||
}
|
||||
|
||||
/// Creates a request which fetches all records.
|
||||
|
||||
@@ -57,7 +57,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
// Don't use DecodingError.keyNotFound:
|
||||
// We need to specifically recognize missing columns in order to
|
||||
// provide correct feedback.
|
||||
throw MissingColumnError(column: key.stringValue)
|
||||
throw RowDecodingError.columnNotFound(key.stringValue, context: RowDecodingContext(row: row))
|
||||
}
|
||||
// TODO: test
|
||||
// See DatabaseValueConversionErrorTests.testDecodableFetchableRecord2
|
||||
@@ -96,20 +96,22 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
}
|
||||
|
||||
// swiftlint:disable comma
|
||||
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { decoder.row[key.stringValue] }
|
||||
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { decoder.row[key.stringValue] }
|
||||
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { decoder.row[key.stringValue] }
|
||||
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { decoder.row[key.stringValue] }
|
||||
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { decoder.row[key.stringValue] }
|
||||
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { decoder.row[key.stringValue] }
|
||||
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { decoder.row[key.stringValue] }
|
||||
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { decoder.row[key.stringValue] }
|
||||
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { decoder.row[key.stringValue] }
|
||||
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { decoder.row[key.stringValue] }
|
||||
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { decoder.row[key.stringValue] }
|
||||
func decode(_ type: Float.Type, forKey key: Key) throws -> Float { decoder.row[key.stringValue] }
|
||||
func decode(_ type: Double.Type, forKey key: Key) throws -> Double { decoder.row[key.stringValue] }
|
||||
func decode(_ type: String.Type, forKey key: Key) throws -> String { decoder.row[key.stringValue] }
|
||||
// swiftlint:disable line_length
|
||||
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { try decoder.row.decode(forKey: key.stringValue) }
|
||||
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { try decoder.row.decode(forKey: key.stringValue) }
|
||||
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { try decoder.row.decode(forKey: key.stringValue) }
|
||||
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { try decoder.row.decode(forKey: key.stringValue) }
|
||||
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { try decoder.row.decode(forKey: key.stringValue) }
|
||||
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { try decoder.row.decode(forKey: key.stringValue) }
|
||||
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { try decoder.row.decode(forKey: key.stringValue) }
|
||||
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { try decoder.row.decode(forKey: key.stringValue) }
|
||||
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { try decoder.row.decode(forKey: key.stringValue) }
|
||||
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { try decoder.row.decode(forKey: key.stringValue) }
|
||||
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { try decoder.row.decode(forKey: key.stringValue) }
|
||||
func decode(_ type: Float.Type, forKey key: Key) throws -> Float { try decoder.row.decode(forKey: key.stringValue) }
|
||||
func decode(_ type: Double.Type, forKey key: Key) throws -> Double { try decoder.row.decode(forKey: key.stringValue) }
|
||||
func decode(_ type: String.Type, forKey key: Key) throws -> String { try decoder.row.decode(forKey: key.stringValue) }
|
||||
// swiftlint:enable line_length
|
||||
// swiftlint:enable comma
|
||||
|
||||
func decodeIfPresent<T>(_ type: T.Type, forKey key: Key) throws -> T? where T: Decodable {
|
||||
@@ -121,11 +123,13 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
// Prefer DatabaseValueConvertible decoding over Decodable.
|
||||
// This allows decoding Date from String, or DatabaseValue from NULL.
|
||||
if type == Date.self {
|
||||
return R.databaseDateDecodingStrategy.decodeIfPresent(fromRow: row, columnAtIndex: index) as! T?
|
||||
return try R.databaseDateDecodingStrategy.decodeIfPresent(
|
||||
fromRow: row,
|
||||
atUncheckedIndex: index) as! T?
|
||||
} else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type {
|
||||
return type.fastDecodeIfPresent(from: row, atUncheckedIndex: index) as! T?
|
||||
return try type.fastDecodeIfPresent(fromRow: row, atUncheckedIndex: index) as! T?
|
||||
} else if let type = T.self as? DatabaseValueConvertible.Type {
|
||||
return type.decodeIfPresent(from: row, atUncheckedIndex: index) as! T?
|
||||
return try type.decodeIfPresent(fromRow: row, atUncheckedIndex: index) as! T?
|
||||
} else if row.impl.hasNull(atUncheckedIndex: index) {
|
||||
return nil
|
||||
} else {
|
||||
@@ -151,11 +155,11 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
// Prefer DatabaseValueConvertible decoding over Decodable.
|
||||
// This allows decoding Date from String, or DatabaseValue from NULL.
|
||||
if type == Date.self {
|
||||
return R.databaseDateDecodingStrategy.decode(fromRow: row, columnAtIndex: index) as! T
|
||||
return try R.databaseDateDecodingStrategy.decode(fromRow: row, atUncheckedIndex: index) as! T
|
||||
} else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type {
|
||||
return type.fastDecode(from: row, atUncheckedIndex: index) as! T
|
||||
return try type.fastDecode(fromRow: row, atUncheckedIndex: index) as! T
|
||||
} else if let type = T.self as? DatabaseValueConvertible.Type {
|
||||
return type.decode(from: row, atUncheckedIndex: index) as! T
|
||||
return try type.decode(fromRow: row, atUncheckedIndex: index) as! T
|
||||
} else {
|
||||
return try decode(type, fromRow: row, columnAtIndex: index, key: key)
|
||||
}
|
||||
@@ -246,16 +250,8 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
// Prefer FetchableRecord decoding over Decodable.
|
||||
return type.init(row: row) as! T
|
||||
} else {
|
||||
do {
|
||||
let decoder = _RowDecoder(row: row, codingPath: codingPath)
|
||||
return try T(from: decoder)
|
||||
} catch let error as MissingColumnError {
|
||||
// Support for DatabaseValueConversionErrorTests.testDecodableFetchableRecord2
|
||||
fatalConversionError(
|
||||
to: type,
|
||||
from: nil,
|
||||
conversionContext: ValueConversionContext(row).atColumn(error.column))
|
||||
}
|
||||
let decoder = _RowDecoder(row: row, codingPath: codingPath)
|
||||
return try T(from: decoder)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,12 +276,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
return try T(from: columnDecoder)
|
||||
} catch is JSONRequiredError {
|
||||
// Decode from JSON
|
||||
guard let data = row.dataNoCopy(atIndex: index) else {
|
||||
fatalConversionError(
|
||||
to: T.self,
|
||||
from: row[index],
|
||||
conversionContext: ValueConversionContext(row).atColumn(index))
|
||||
}
|
||||
let data = try row.decodeDataNoCopy(atIndex: index)
|
||||
return try R
|
||||
.databaseJSONDecoder(for: key.stringValue)
|
||||
.decode(type.self, from: data)
|
||||
@@ -375,30 +366,30 @@ extension ColumnDecoder: SingleValueDecodingContainer {
|
||||
row.hasNull(atIndex: columnIndex)
|
||||
}
|
||||
|
||||
func decode(_ type: Bool.Type ) throws -> Bool { row[columnIndex] }
|
||||
func decode(_ type: Int.Type ) throws -> Int { row[columnIndex] }
|
||||
func decode(_ type: Int8.Type ) throws -> Int8 { row[columnIndex] }
|
||||
func decode(_ type: Int16.Type ) throws -> Int16 { row[columnIndex] }
|
||||
func decode(_ type: Int32.Type ) throws -> Int32 { row[columnIndex] }
|
||||
func decode(_ type: Int64.Type ) throws -> Int64 { row[columnIndex] }
|
||||
func decode(_ type: UInt.Type ) throws -> UInt { row[columnIndex] }
|
||||
func decode(_ type: UInt8.Type ) throws -> UInt8 { row[columnIndex] }
|
||||
func decode(_ type: UInt16.Type) throws -> UInt16 { row[columnIndex] }
|
||||
func decode(_ type: UInt32.Type) throws -> UInt32 { row[columnIndex] }
|
||||
func decode(_ type: UInt64.Type) throws -> UInt64 { row[columnIndex] }
|
||||
func decode(_ type: Float.Type ) throws -> Float { row[columnIndex] }
|
||||
func decode(_ type: Double.Type) throws -> Double { row[columnIndex] }
|
||||
func decode(_ type: String.Type) throws -> String { row[columnIndex] }
|
||||
func decode(_ type: Bool.Type ) throws -> Bool { try row.decode(atIndex: columnIndex) }
|
||||
func decode(_ type: Int.Type ) throws -> Int { try row.decode(atIndex: columnIndex) }
|
||||
func decode(_ type: Int8.Type ) throws -> Int8 { try row.decode(atIndex: columnIndex) }
|
||||
func decode(_ type: Int16.Type ) throws -> Int16 { try row.decode(atIndex: columnIndex) }
|
||||
func decode(_ type: Int32.Type ) throws -> Int32 { try row.decode(atIndex: columnIndex) }
|
||||
func decode(_ type: Int64.Type ) throws -> Int64 { try row.decode(atIndex: columnIndex) }
|
||||
func decode(_ type: UInt.Type ) throws -> UInt { try row.decode(atIndex: columnIndex) }
|
||||
func decode(_ type: UInt8.Type ) throws -> UInt8 { try row.decode(atIndex: columnIndex) }
|
||||
func decode(_ type: UInt16.Type) throws -> UInt16 { try row.decode(atIndex: columnIndex) }
|
||||
func decode(_ type: UInt32.Type) throws -> UInt32 { try row.decode(atIndex: columnIndex) }
|
||||
func decode(_ type: UInt64.Type) throws -> UInt64 { try row.decode(atIndex: columnIndex) }
|
||||
func decode(_ type: Float.Type ) throws -> Float { try row.decode(atIndex: columnIndex) }
|
||||
func decode(_ type: Double.Type) throws -> Double { try row.decode(atIndex: columnIndex) }
|
||||
func decode(_ type: String.Type) throws -> String { try row.decode(atIndex: columnIndex) }
|
||||
|
||||
func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
|
||||
// Prefer DatabaseValueConvertible decoding over Decodable.
|
||||
// This allows decoding Date from String, or DatabaseValue from NULL.
|
||||
if type == Date.self {
|
||||
return R.databaseDateDecodingStrategy.decode(fromRow: row, columnAtIndex: columnIndex) as! T
|
||||
return try R.databaseDateDecodingStrategy.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T
|
||||
} else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type {
|
||||
return type.fastDecode(from: row, atUncheckedIndex: columnIndex) as! T
|
||||
return try type.fastDecode(fromRow: row, atUncheckedIndex: columnIndex) as! T
|
||||
} else if let type = T.self as? DatabaseValueConvertible.Type {
|
||||
return type.decode(from: row, atUncheckedIndex: columnIndex) as! T
|
||||
return try type.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T
|
||||
} else {
|
||||
return try T(from: self)
|
||||
}
|
||||
@@ -408,11 +399,6 @@ extension ColumnDecoder: SingleValueDecodingContainer {
|
||||
/// The error that triggers JSON decoding
|
||||
private struct JSONRequiredError: Error { }
|
||||
|
||||
/// The error for missing columns
|
||||
private struct MissingColumnError: Error {
|
||||
var column: String
|
||||
}
|
||||
|
||||
@available(macOS 10.12, watchOS 3.0, tvOS 10.0, *)
|
||||
private var iso8601Formatter: ISO8601DateFormatter = {
|
||||
let formatter = ISO8601DateFormatter()
|
||||
@@ -422,36 +408,49 @@ private var iso8601Formatter: ISO8601DateFormatter = {
|
||||
|
||||
extension DatabaseDateDecodingStrategy {
|
||||
@inline(__always)
|
||||
fileprivate func decodeIfPresent(fromRow row: Row, columnAtIndex index: Int) -> Date? {
|
||||
fileprivate func decodeIfPresent(fromRow row: Row, atUncheckedIndex index: Int) throws -> Date? {
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return decodeIfPresent(
|
||||
sqliteStatement: sqliteStatement,
|
||||
index: Int32(index))
|
||||
return try decodeIfPresent(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
} else {
|
||||
return decodeIfPresent(
|
||||
from: row[index],
|
||||
conversionContext: ValueConversionContext(row).atColumn(index))
|
||||
return try decodeIfPresent(
|
||||
fromDatabaseValue: row[index],
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
fileprivate func decode(fromRow row: Row, columnAtIndex index: Int) -> Date {
|
||||
fileprivate func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Date {
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return decode(
|
||||
sqliteStatement: sqliteStatement,
|
||||
index: Int32(index))
|
||||
return try decode(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
} else {
|
||||
return decode(
|
||||
from: row[index],
|
||||
conversionContext: ValueConversionContext(row).atColumn(index))
|
||||
return try decode(
|
||||
fromDatabaseValue: row[index],
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
fileprivate func decode(sqliteStatement: SQLiteStatement, index: Int32) -> Date {
|
||||
fileprivate func decode(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: Int32,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Date
|
||||
{
|
||||
switch self {
|
||||
case .deferredToDate:
|
||||
return Date(sqliteStatement: sqliteStatement, index: index)
|
||||
guard let date = Date(sqliteStatement: sqliteStatement, index: index) else {
|
||||
throw RowDecodingError.valueMismatch(
|
||||
Date.self,
|
||||
context: context(),
|
||||
databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index))
|
||||
}
|
||||
return date
|
||||
case .timeIntervalSinceReferenceDate:
|
||||
let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index)
|
||||
return Date(timeIntervalSinceReferenceDate: timeInterval)
|
||||
@@ -465,7 +464,10 @@ extension DatabaseDateDecodingStrategy {
|
||||
if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) {
|
||||
let string = String(sqliteStatement: sqliteStatement, index: index)
|
||||
guard let date = iso8601Formatter.date(from: string) else {
|
||||
fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index)
|
||||
throw RowDecodingError.valueMismatch(
|
||||
Date.self,
|
||||
context: context(),
|
||||
databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index))
|
||||
}
|
||||
return date
|
||||
} else {
|
||||
@@ -474,51 +476,62 @@ extension DatabaseDateDecodingStrategy {
|
||||
case .formatted(let formatter):
|
||||
let string = String(sqliteStatement: sqliteStatement, index: index)
|
||||
guard let date = formatter.date(from: string) else {
|
||||
fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index)
|
||||
throw RowDecodingError.valueMismatch(
|
||||
Date.self,
|
||||
context: context(),
|
||||
databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index))
|
||||
}
|
||||
return date
|
||||
case .custom(let format):
|
||||
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
|
||||
guard let date = format(dbValue) else {
|
||||
fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index)
|
||||
throw RowDecodingError.valueMismatch(
|
||||
Date.self,
|
||||
context: context(),
|
||||
databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index))
|
||||
}
|
||||
return date
|
||||
}
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
fileprivate func decodeIfPresent(sqliteStatement: SQLiteStatement, index: Int32) -> Date? {
|
||||
fileprivate func decodeIfPresent(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: Int32,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Date?
|
||||
{
|
||||
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
|
||||
return nil
|
||||
}
|
||||
return decode(sqliteStatement: sqliteStatement, index: index)
|
||||
return try decode(fromStatement: sqliteStatement, atUncheckedIndex: index, context: context())
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
fileprivate func decode(
|
||||
from dbValue: DatabaseValue,
|
||||
conversionContext: @autoclosure () -> ValueConversionContext?)
|
||||
-> Date
|
||||
fromDatabaseValue dbValue: DatabaseValue,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Date
|
||||
{
|
||||
if let date = dateFromDatabaseValue(dbValue) {
|
||||
return date
|
||||
} else {
|
||||
fatalConversionError(to: Date.self, from: dbValue, conversionContext: conversionContext())
|
||||
throw RowDecodingError.valueMismatch(Date.self, context: context(), databaseValue: dbValue)
|
||||
}
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
fileprivate func decodeIfPresent(
|
||||
from dbValue: DatabaseValue,
|
||||
conversionContext: @autoclosure () -> ValueConversionContext?)
|
||||
-> Date?
|
||||
fromDatabaseValue dbValue: DatabaseValue,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Date?
|
||||
{
|
||||
if dbValue.isNull {
|
||||
return nil
|
||||
} else if let date = dateFromDatabaseValue(dbValue) {
|
||||
return date
|
||||
} else {
|
||||
fatalConversionError(to: Date.self, from: dbValue, conversionContext: conversionContext())
|
||||
throw RowDecodingError.valueMismatch(Date.self, context: context(), databaseValue: dbValue)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -133,7 +133,7 @@ extension TableRecord {
|
||||
public static func numberOfSelectedColumns(_ db: Database) throws -> Int {
|
||||
let alias = TableAlias(tableName: databaseTableName)
|
||||
return try databaseSelection
|
||||
.map { try $0._qualifiedSelectable(with: alias)._columnCount(db) }
|
||||
.map { try $0.sqlSelection.qualified(with: alias).columnCount(db) }
|
||||
.reduce(0, +)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,6 +52,11 @@ func GRDBPrecondition(
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func fatalError(_ error: Error) -> Never {
|
||||
try! { throw error }()
|
||||
}
|
||||
|
||||
// Workaround Swift inconvenience around factory methods of non-final classes
|
||||
func cast<T, U>(_ value: T) -> U? {
|
||||
value as? U
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
56043297228F00A9009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043295228F00A9009D3FE2 /* OrderedDictionaryTests.swift */; };
|
||||
560432A6228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A5228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift */; };
|
||||
560432A7228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A5228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift */; };
|
||||
5604484E25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5604484C25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift */; };
|
||||
5604484F25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5604484C25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift */; };
|
||||
56057C592291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56057C572291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift */; };
|
||||
56057C5A2291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56057C572291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift */; };
|
||||
56057C652291C7E500A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56057C642291C7E500A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */; };
|
||||
@@ -54,6 +56,8 @@
|
||||
562205FE1E420EA2005860AC /* DatabasePoolConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */; };
|
||||
562205FF1E420EA2005860AC /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; };
|
||||
562206091E420EB2005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */; };
|
||||
56231E6225CEBF08001DFD2F /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56231E6025CEBF06001DFD2F /* RowDecodingError.swift */; };
|
||||
56231E6325CEBF08001DFD2F /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56231E6025CEBF06001DFD2F /* RowDecodingError.swift */; };
|
||||
5623931B1DECC02000A6B01F /* RowFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393171DECC02000A6B01F /* RowFetchTests.swift */; };
|
||||
5623931F1DECC02000A6B01F /* RowFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393171DECC02000A6B01F /* RowFetchTests.swift */; };
|
||||
562393331DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; };
|
||||
@@ -68,6 +72,8 @@
|
||||
562393701DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */; };
|
||||
562393751DEE104400A6B01F /* MapCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393711DEE104400A6B01F /* MapCursorTests.swift */; };
|
||||
562393791DEE104400A6B01F /* MapCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393711DEE104400A6B01F /* MapCursorTests.swift */; };
|
||||
56256EDE25D1BC07008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256EDD25D1BC07008C2BDD /* ForeignKey.swift */; };
|
||||
56256EDF25D1BC07008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256EDD25D1BC07008C2BDD /* ForeignKey.swift */; };
|
||||
562756461E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
|
||||
5627564A1E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
|
||||
562EA8291F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
|
||||
@@ -148,8 +154,6 @@
|
||||
56419C9B24A51D7F004967E1 /* PublisherExpectation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A8124A51614004967E1 /* PublisherExpectation.swift */; };
|
||||
564448861EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
|
||||
5644488A1EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
|
||||
5644DE7820F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7620F8C8E9001FFDDE /* DatabaseValueConversion.swift */; };
|
||||
5644DE7920F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7620F8C8E9001FFDDE /* DatabaseValueConversion.swift */; };
|
||||
5644DE7F20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */; };
|
||||
5644DE8020F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */; };
|
||||
564B3D72239BDBD6007BF308 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */; };
|
||||
@@ -234,8 +238,6 @@
|
||||
5656A8762295BD56001FF3FF /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A83C2295BD56001FF3FF /* RequestProtocols.swift */; };
|
||||
5656A8772295BD56001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A83D2295BD56001FF3FF /* TableRecord+QueryInterfaceRequest.swift */; };
|
||||
5656A8782295BD56001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A83D2295BD56001FF3FF /* TableRecord+QueryInterfaceRequest.swift */; };
|
||||
5656A87B2295BD56001FF3FF /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A83F2295BD56001FF3FF /* QueryInterfaceRequest+Association.swift */; };
|
||||
5656A87C2295BD56001FF3FF /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A83F2295BD56001FF3FF /* QueryInterfaceRequest+Association.swift */; };
|
||||
5656A87D2295BD56001FF3FF /* SQLAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8412295BD56001FF3FF /* SQLAssociation.swift */; };
|
||||
5656A87E2295BD56001FF3FF /* SQLAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8412295BD56001FF3FF /* SQLAssociation.swift */; };
|
||||
5656A87F2295BD56001FF3FF /* SQLForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8422295BD56001FF3FF /* SQLForeignKeyRequest.swift */; };
|
||||
@@ -248,22 +250,12 @@
|
||||
5656A8862295BD56001FF3FF /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8452295BD56001FF3FF /* SQLOrdering.swift */; };
|
||||
5656A8872295BD56001FF3FF /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8462295BD56001FF3FF /* SQLOperators.swift */; };
|
||||
5656A8882295BD56001FF3FF /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8462295BD56001FF3FF /* SQLOperators.swift */; };
|
||||
5656A8892295BD56001FF3FF /* SQLExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8472295BD56001FF3FF /* SQLExpressible.swift */; };
|
||||
5656A88A2295BD56001FF3FF /* SQLExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8472295BD56001FF3FF /* SQLExpressible.swift */; };
|
||||
5656A88B2295BD56001FF3FF /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8482295BD56001FF3FF /* SQLExpression+QueryInterface.swift */; };
|
||||
5656A88C2295BD56001FF3FF /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8482295BD56001FF3FF /* SQLExpression+QueryInterface.swift */; };
|
||||
5656A88D2295BD56001FF3FF /* SQLSelectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8492295BD56001FF3FF /* SQLSelectable.swift */; };
|
||||
5656A88E2295BD56001FF3FF /* SQLSelectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8492295BD56001FF3FF /* SQLSelectable.swift */; };
|
||||
5656A88F2295BD56001FF3FF /* Column.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84A2295BD56001FF3FF /* Column.swift */; };
|
||||
5656A8902295BD56001FF3FF /* Column.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84A2295BD56001FF3FF /* Column.swift */; };
|
||||
5656A8912295BD56001FF3FF /* SQLSpecificExpressible+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84B2295BD56001FF3FF /* SQLSpecificExpressible+QueryInterface.swift */; };
|
||||
5656A8922295BD56001FF3FF /* SQLSpecificExpressible+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84B2295BD56001FF3FF /* SQLSpecificExpressible+QueryInterface.swift */; };
|
||||
5656A8932295BD56001FF3FF /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84C2295BD56001FF3FF /* SQLFunctions.swift */; };
|
||||
5656A8942295BD56001FF3FF /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84C2295BD56001FF3FF /* SQLFunctions.swift */; };
|
||||
5656A8972295BD56001FF3FF /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84E2295BD56001FF3FF /* SQLRelation.swift */; };
|
||||
5656A8982295BD56001FF3FF /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84E2295BD56001FF3FF /* SQLRelation.swift */; };
|
||||
5656A8992295BD56001FF3FF /* SQLSelectable+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84F2295BD56001FF3FF /* SQLSelectable+QueryInterface.swift */; };
|
||||
5656A89A2295BD56001FF3FF /* SQLSelectable+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84F2295BD56001FF3FF /* SQLSelectable+QueryInterface.swift */; };
|
||||
5656A89B2295BD56001FF3FF /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8502295BD56001FF3FF /* SQLQuery.swift */; };
|
||||
5656A89C2295BD56001FF3FF /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8502295BD56001FF3FF /* SQLQuery.swift */; };
|
||||
5656A8A72295BF44001FF3FF /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8A52295BF44001FF3FF /* DatabasePromise.swift */; };
|
||||
@@ -364,6 +356,10 @@
|
||||
567F45AF1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
|
||||
568068341EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
|
||||
568068381EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
|
||||
568ECB0D25D904CA00B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB0C25D904CA00B71526 /* SQLSelection.swift */; };
|
||||
568ECB0E25D904CA00B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB0C25D904CA00B71526 /* SQLSelection.swift */; };
|
||||
568ECB3525D91CEF00B71526 /* SQLSubquery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB3425D91CEE00B71526 /* SQLSubquery.swift */; };
|
||||
568ECB3625D91CEF00B71526 /* SQLSubquery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB3425D91CEE00B71526 /* SQLSubquery.swift */; };
|
||||
5690C3291D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; };
|
||||
5690C32D1D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; };
|
||||
5690C33A1D23E7D200E59934 /* FoundationDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3361D23E7D200E59934 /* FoundationDateTests.swift */; };
|
||||
@@ -487,8 +483,6 @@
|
||||
56D507651F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; };
|
||||
56D51D021EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; };
|
||||
56D51D051EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; };
|
||||
56D8B40D257D0FBE008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B40B257D0FBE008AA1F7 /* SQLRowValue.swift */; };
|
||||
56D8B40E257D0FBE008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B40B257D0FBE008AA1F7 /* SQLRowValue.swift */; };
|
||||
56DAA2D51DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; };
|
||||
56DAA2D91DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; };
|
||||
56DAA2DD1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; };
|
||||
@@ -764,6 +758,7 @@
|
||||
56012B80257404A300B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = "<group>"; };
|
||||
56043295228F00A9009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = "<group>"; };
|
||||
560432A5228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = "<group>"; };
|
||||
5604484C25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = "<group>"; };
|
||||
56057C572291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyRowScopeTests.swift; sourceTree = "<group>"; };
|
||||
56057C642291C7E500A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughRowScopeTests.swift; sourceTree = "<group>"; };
|
||||
5605F1491C672E4000235C62 /* CGFloat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloat.swift; sourceTree = "<group>"; };
|
||||
@@ -797,6 +792,7 @@
|
||||
561CFA7B2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordUpdateTests.swift; sourceTree = "<group>"; };
|
||||
561CFA9F2376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = "<group>"; };
|
||||
561CFAA32376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = "<group>"; };
|
||||
56231E6025CEBF06001DFD2F /* RowDecodingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowDecodingError.swift; sourceTree = "<group>"; };
|
||||
562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = "<group>"; };
|
||||
5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = "<group>"; };
|
||||
5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = "<group>"; };
|
||||
@@ -805,6 +801,7 @@
|
||||
562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FlattenCursorTests.swift; sourceTree = "<group>"; };
|
||||
562393711DEE104400A6B01F /* MapCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MapCursorTests.swift; sourceTree = "<group>"; };
|
||||
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = "<group>"; };
|
||||
56256EDD25D1BC07008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = "<group>"; };
|
||||
562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = "<group>"; };
|
||||
562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = "<group>"; };
|
||||
562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = "<group>"; };
|
||||
@@ -858,7 +855,6 @@
|
||||
56419A8024A51614004967E1 /* Inverted.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Inverted.swift; sourceTree = "<group>"; };
|
||||
56419A8124A51614004967E1 /* PublisherExpectation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PublisherExpectation.swift; sourceTree = "<group>"; };
|
||||
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
|
||||
5644DE7620F8C8E9001FFDDE /* DatabaseValueConversion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversion.swift; sourceTree = "<group>"; };
|
||||
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>"; };
|
||||
@@ -902,21 +898,15 @@
|
||||
5656A83B2295BD56001FF3FF /* QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequest.swift; sourceTree = "<group>"; };
|
||||
5656A83C2295BD56001FF3FF /* RequestProtocols.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestProtocols.swift; sourceTree = "<group>"; };
|
||||
5656A83D2295BD56001FF3FF /* TableRecord+QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+QueryInterfaceRequest.swift"; sourceTree = "<group>"; };
|
||||
5656A83F2295BD56001FF3FF /* QueryInterfaceRequest+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "QueryInterfaceRequest+Association.swift"; sourceTree = "<group>"; };
|
||||
5656A8412295BD56001FF3FF /* SQLAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLAssociation.swift; sourceTree = "<group>"; };
|
||||
5656A8422295BD56001FF3FF /* SQLForeignKeyRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLForeignKeyRequest.swift; sourceTree = "<group>"; };
|
||||
5656A8432295BD56001FF3FF /* SQLCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollection.swift; sourceTree = "<group>"; };
|
||||
5656A8442295BD56001FF3FF /* SQLExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpression.swift; sourceTree = "<group>"; };
|
||||
5656A8452295BD56001FF3FF /* SQLOrdering.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOrdering.swift; sourceTree = "<group>"; };
|
||||
5656A8462295BD56001FF3FF /* SQLOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperators.swift; sourceTree = "<group>"; };
|
||||
5656A8472295BD56001FF3FF /* SQLExpressible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpressible.swift; sourceTree = "<group>"; };
|
||||
5656A8482295BD56001FF3FF /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = "<group>"; };
|
||||
5656A8492295BD56001FF3FF /* SQLSelectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectable.swift; sourceTree = "<group>"; };
|
||||
5656A84A2295BD56001FF3FF /* Column.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Column.swift; sourceTree = "<group>"; };
|
||||
5656A84B2295BD56001FF3FF /* SQLSpecificExpressible+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLSpecificExpressible+QueryInterface.swift"; sourceTree = "<group>"; };
|
||||
5656A84C2295BD56001FF3FF /* SQLFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunctions.swift; sourceTree = "<group>"; };
|
||||
5656A84E2295BD56001FF3FF /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = "<group>"; };
|
||||
5656A84F2295BD56001FF3FF /* SQLSelectable+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLSelectable+QueryInterface.swift"; sourceTree = "<group>"; };
|
||||
5656A8502295BD56001FF3FF /* SQLQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQuery.swift; sourceTree = "<group>"; };
|
||||
5656A8A52295BF44001FF3FF /* DatabasePromise.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePromise.swift; sourceTree = "<group>"; };
|
||||
5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = "<group>"; };
|
||||
@@ -977,6 +967,8 @@
|
||||
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
|
||||
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
|
||||
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
|
||||
568ECB0C25D904CA00B71526 /* SQLSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelection.swift; sourceTree = "<group>"; };
|
||||
568ECB3425D91CEE00B71526 /* SQLSubquery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSubquery.swift; sourceTree = "<group>"; };
|
||||
5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = "<group>"; };
|
||||
5690C3361D23E7D200E59934 /* FoundationDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateTests.swift; sourceTree = "<group>"; };
|
||||
5690C33F1D23E82A00E59934 /* Data.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Data.swift; sourceTree = "<group>"; };
|
||||
@@ -1083,7 +1075,6 @@
|
||||
56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS4.swift; sourceTree = "<group>"; };
|
||||
56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = "<group>"; };
|
||||
56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = "<group>"; };
|
||||
56D8B40B257D0FBE008AA1F7 /* SQLRowValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRowValue.swift; sourceTree = "<group>"; };
|
||||
56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCursorTests.swift; sourceTree = "<group>"; };
|
||||
56DAA2DA1DE9C827006E10C8 /* Cursor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cursor.swift; sourceTree = "<group>"; };
|
||||
56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1475,6 +1466,7 @@
|
||||
56DF0013228DDB8200D611F3 /* AssociationPrefetchingCodableRecordTests.swift */,
|
||||
569BBA29228DE53200478429 /* AssociationPrefetchingFetchableRecordTests.swift */,
|
||||
560432A5228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift */,
|
||||
5604484C25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift */,
|
||||
56DF0014228DDB8200D611F3 /* AssociationPrefetchingRowTests.swift */,
|
||||
560714EB227DD10F0091BB10 /* AssociationPrefetchingSQLTests.swift */,
|
||||
5653EB5E20961FB100F46237 /* AssociationRowScopeSearchTests.swift */,
|
||||
@@ -1486,6 +1478,7 @@
|
||||
5656A8252295BD56001FF3FF /* QueryInterface */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56256EDD25D1BC07008C2BDD /* ForeignKey.swift */,
|
||||
5656A82F2295BD56001FF3FF /* FTS3+QueryInterface.swift */,
|
||||
5656A8282295BD56001FF3FF /* FTS5+QueryInterface.swift */,
|
||||
5656A8302295BD56001FF3FF /* Request */,
|
||||
@@ -1523,7 +1516,6 @@
|
||||
5656A8332295BD56001FF3FF /* Association */,
|
||||
56012B80257404A300B4925B /* CommonTableExpression.swift */,
|
||||
5656A83B2295BD56001FF3FF /* QueryInterfaceRequest.swift */,
|
||||
5656A83F2295BD56001FF3FF /* QueryInterfaceRequest+Association.swift */,
|
||||
5656A83C2295BD56001FF3FF /* RequestProtocols.swift */,
|
||||
);
|
||||
path = Request;
|
||||
@@ -1552,19 +1544,15 @@
|
||||
5656A8412295BD56001FF3FF /* SQLAssociation.swift */,
|
||||
56F34FF024B0F0D8007513FC /* SQLCollatedExpression.swift */,
|
||||
5656A8432295BD56001FF3FF /* SQLCollection.swift */,
|
||||
5656A8472295BD56001FF3FF /* SQLExpressible.swift */,
|
||||
5656A8442295BD56001FF3FF /* SQLExpression.swift */,
|
||||
5656A8482295BD56001FF3FF /* SQLExpression+QueryInterface.swift */,
|
||||
5656A8422295BD56001FF3FF /* SQLForeignKeyRequest.swift */,
|
||||
5656A84C2295BD56001FF3FF /* SQLFunctions.swift */,
|
||||
5656A8462295BD56001FF3FF /* SQLOperators.swift */,
|
||||
5656A8452295BD56001FF3FF /* SQLOrdering.swift */,
|
||||
5656A8502295BD56001FF3FF /* SQLQuery.swift */,
|
||||
5656A84E2295BD56001FF3FF /* SQLRelation.swift */,
|
||||
56D8B40B257D0FBE008AA1F7 /* SQLRowValue.swift */,
|
||||
5656A8492295BD56001FF3FF /* SQLSelectable.swift */,
|
||||
5656A84F2295BD56001FF3FF /* SQLSelectable+QueryInterface.swift */,
|
||||
5656A84B2295BD56001FF3FF /* SQLSpecificExpressible+QueryInterface.swift */,
|
||||
568ECB0C25D904CA00B71526 /* SQLSelection.swift */,
|
||||
568ECB3425D91CEE00B71526 /* SQLSubquery.swift */,
|
||||
);
|
||||
path = SQL;
|
||||
sourceTree = "<group>";
|
||||
@@ -1774,12 +1762,12 @@
|
||||
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
|
||||
566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */,
|
||||
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
|
||||
5644DE7620F8C8E9001FFDDE /* DatabaseValueConversion.swift */,
|
||||
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
|
||||
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
|
||||
5636E9BB1D22574100B9B05F /* FetchRequest.swift */,
|
||||
56A238761B9C75030082EB20 /* Row.swift */,
|
||||
567404871CEF84C8003ED5CC /* RowAdapter.swift */,
|
||||
56231E6025CEBF06001DFD2F /* RowDecodingError.swift */,
|
||||
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
|
||||
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
|
||||
56E9FAC32210468500C703A8 /* SQLInterpolation.swift */,
|
||||
@@ -2283,7 +2271,6 @@
|
||||
F3BA801A1CFB2876003DC1BA /* StatementColumnConvertible.swift in Sources */,
|
||||
566B91381FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
56CEB4FF1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
|
||||
5656A8922295BD56001FF3FF /* SQLSpecificExpressible+QueryInterface.swift in Sources */,
|
||||
5698AD3A1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
|
||||
5656A8742295BD56001FF3FF /* QueryInterfaceRequest.swift in Sources */,
|
||||
566B91181FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
|
||||
@@ -2291,7 +2278,6 @@
|
||||
5674A7051F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
|
||||
563082EB2430B6CD00C14A05 /* DatabaseCancellable.swift in Sources */,
|
||||
F3BA800D1CFB2871003DC1BA /* DatabasePool.swift in Sources */,
|
||||
5656A87C2295BD56001FF3FF /* QueryInterfaceRequest+Association.swift in Sources */,
|
||||
F3BA800B1CFB286D003DC1BA /* Database.swift in Sources */,
|
||||
F3BA80341CFB28A4003DC1BA /* Record.swift in Sources */,
|
||||
56C0539422ACEECD0029D27D /* Fetch.swift in Sources */,
|
||||
@@ -2302,15 +2288,16 @@
|
||||
F3BA80101CFB2876003DC1BA /* DatabaseReader.swift in Sources */,
|
||||
563B8FBA24A1D036007A48C9 /* ReceiveValuesOn.swift in Sources */,
|
||||
564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */,
|
||||
56231E6225CEBF08001DFD2F /* RowDecodingError.swift in Sources */,
|
||||
5656A8942295BD56001FF3FF /* SQLFunctions.swift in Sources */,
|
||||
5659F49D1EA8D989004A4992 /* Pool.swift in Sources */,
|
||||
563A4B72242E7CE60075D8CF /* ValueObservationScheduler.swift in Sources */,
|
||||
5674A6F61F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */,
|
||||
5656A88A2295BD56001FF3FF /* SQLExpressible.swift in Sources */,
|
||||
5698AC3C1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
|
||||
5698AD171DAAD16F0056AF8C /* FTS5Tokenizer.swift in Sources */,
|
||||
569BBA4C229170B300478429 /* Inflections+English.swift in Sources */,
|
||||
5656A8762295BD56001FF3FF /* RequestProtocols.swift in Sources */,
|
||||
568ECB3625D91CEF00B71526 /* SQLSubquery.swift in Sources */,
|
||||
561729552235340E0006E219 /* EncodableRecord.swift in Sources */,
|
||||
5656A87E2295BD56001FF3FF /* SQLAssociation.swift in Sources */,
|
||||
F3BA80131CFB2876003DC1BA /* DatabaseValue.swift in Sources */,
|
||||
@@ -2327,17 +2314,17 @@
|
||||
56D51D051EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
|
||||
56DF37A823D77AA0009AAA05 /* Refinable.swift in Sources */,
|
||||
F3BA80151CFB2876003DC1BA /* DatabaseWriter.swift in Sources */,
|
||||
56256EDF25D1BC07008C2BDD /* ForeignKey.swift in Sources */,
|
||||
F3BA800A1CFB286A003DC1BA /* Configuration.swift in Sources */,
|
||||
5656A86C2295BD56001FF3FF /* HasManyAssociation.swift in Sources */,
|
||||
5656A88E2295BD56001FF3FF /* SQLSelectable.swift in Sources */,
|
||||
5671FC251DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
|
||||
5656A8862295BD56001FF3FF /* SQLOrdering.swift in Sources */,
|
||||
F3BA80311CFB289F003DC1BA /* Migration.swift in Sources */,
|
||||
F3BA801D1CFB288C003DC1BA /* DatabaseDateComponents.swift in Sources */,
|
||||
5674A6ED1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */,
|
||||
568ECB0E25D904CA00B71526 /* SQLSelection.swift in Sources */,
|
||||
5657AB141D10899D006283EF /* URL.swift in Sources */,
|
||||
56F34FF224B0F0D8007513FC /* SQLCollatedExpression.swift in Sources */,
|
||||
5644DE7920F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */,
|
||||
56DAA2E01DE9C827006E10C8 /* Cursor.swift in Sources */,
|
||||
F3BA800C1CFB286F003DC1BA /* DatabaseError.swift in Sources */,
|
||||
5656A8782295BD56001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
|
||||
@@ -2360,7 +2347,6 @@
|
||||
F3BA80331CFB28A4003DC1BA /* PersistableRecord.swift in Sources */,
|
||||
5656A8802295BD56001FF3FF /* SQLForeignKeyRequest.swift in Sources */,
|
||||
56B964BE1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
|
||||
56D8B40E257D0FBE008AA1F7 /* SQLRowValue.swift in Sources */,
|
||||
561408A1221596A100DAD589 /* GRDB-5.0.swift in Sources */,
|
||||
F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */,
|
||||
56FBFED72210731100945324 /* SQLRequest.swift in Sources */,
|
||||
@@ -2370,7 +2356,6 @@
|
||||
5656A8702295BD56001FF3FF /* Association.swift in Sources */,
|
||||
563B8F9C249E74E5007A48C9 /* Trace.swift in Sources */,
|
||||
5656A89C2295BD56001FF3FF /* SQLQuery.swift in Sources */,
|
||||
5656A88C2295BD56001FF3FF /* SQLExpression+QueryInterface.swift in Sources */,
|
||||
5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
|
||||
5656A85C2295BD56001FF3FF /* TableDefinition.swift in Sources */,
|
||||
5656A8562295BD56001FF3FF /* FTS5+QueryInterface.swift in Sources */,
|
||||
@@ -2382,7 +2367,6 @@
|
||||
5613ED6221A95E6100DC7A68 /* ValueObservation.swift in Sources */,
|
||||
F3BA80361CFB28A4003DC1BA /* TableRecord.swift in Sources */,
|
||||
567071F5208A00BE006AD95A /* SQLiteDateParser.swift in Sources */,
|
||||
5656A89A2295BD56001FF3FF /* SQLSelectable+QueryInterface.swift in Sources */,
|
||||
F3BA80271CFB2891003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
|
||||
5657AABE1D107001006283EF /* NSData.swift in Sources */,
|
||||
5674A6E61F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
|
||||
@@ -2550,6 +2534,7 @@
|
||||
561CFA7E2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */,
|
||||
56B964D21DA521450002DA19 /* FTS5RecordTests.swift in Sources */,
|
||||
F3BA80F91CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */,
|
||||
5604484F25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */,
|
||||
56A5EF161EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */,
|
||||
F3BA80DA1CFB300E003DC1BA /* DatabaseTimestampTests.swift in Sources */,
|
||||
563EF443216131F5007DAACD /* AssociationAggregateTests.swift in Sources */,
|
||||
@@ -2644,7 +2629,6 @@
|
||||
F3BA80761CFB2E55003DC1BA /* StatementColumnConvertible.swift in Sources */,
|
||||
566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
56CEB4FC1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
|
||||
5656A8912295BD56001FF3FF /* SQLSpecificExpressible+QueryInterface.swift in Sources */,
|
||||
5698AD371DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
|
||||
5656A8732295BD56001FF3FF /* QueryInterfaceRequest.swift in Sources */,
|
||||
566B91151FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
|
||||
@@ -2652,7 +2636,6 @@
|
||||
5674A7041F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
|
||||
563082EA2430B6CD00C14A05 /* DatabaseCancellable.swift in Sources */,
|
||||
F3BA80691CFB2E55003DC1BA /* DatabasePool.swift in Sources */,
|
||||
5656A87B2295BD56001FF3FF /* QueryInterfaceRequest+Association.swift in Sources */,
|
||||
F3BA80671CFB2E55003DC1BA /* Database.swift in Sources */,
|
||||
F3BA80901CFB2E7A003DC1BA /* Record.swift in Sources */,
|
||||
56C0539322ACEECD0029D27D /* Fetch.swift in Sources */,
|
||||
@@ -2663,15 +2646,16 @@
|
||||
F3BA806C1CFB2E55003DC1BA /* DatabaseReader.swift in Sources */,
|
||||
563B8FBB24A1D036007A48C9 /* ReceiveValuesOn.swift in Sources */,
|
||||
564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */,
|
||||
56231E6325CEBF08001DFD2F /* RowDecodingError.swift in Sources */,
|
||||
5656A8932295BD56001FF3FF /* SQLFunctions.swift in Sources */,
|
||||
5659F49A1EA8D989004A4992 /* Pool.swift in Sources */,
|
||||
563A4B71242E7CE60075D8CF /* ValueObservationScheduler.swift in Sources */,
|
||||
5674A6F51F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */,
|
||||
5656A8892295BD56001FF3FF /* SQLExpressible.swift in Sources */,
|
||||
5698AC391D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
|
||||
5698AD161DAAD16F0056AF8C /* FTS5Tokenizer.swift in Sources */,
|
||||
569BBA4D229170B300478429 /* Inflections+English.swift in Sources */,
|
||||
5656A8752295BD56001FF3FF /* RequestProtocols.swift in Sources */,
|
||||
568ECB3525D91CEF00B71526 /* SQLSubquery.swift in Sources */,
|
||||
561729562235340E0006E219 /* EncodableRecord.swift in Sources */,
|
||||
5656A87D2295BD56001FF3FF /* SQLAssociation.swift in Sources */,
|
||||
F3BA806F1CFB2E55003DC1BA /* DatabaseValue.swift in Sources */,
|
||||
@@ -2688,17 +2672,17 @@
|
||||
56D51D021EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
|
||||
56DF37A723D77AA0009AAA05 /* Refinable.swift in Sources */,
|
||||
F3BA80711CFB2E55003DC1BA /* DatabaseWriter.swift in Sources */,
|
||||
56256EDE25D1BC07008C2BDD /* ForeignKey.swift in Sources */,
|
||||
F3BA80661CFB2E55003DC1BA /* Configuration.swift in Sources */,
|
||||
5656A86B2295BD56001FF3FF /* HasManyAssociation.swift in Sources */,
|
||||
5656A88D2295BD56001FF3FF /* SQLSelectable.swift in Sources */,
|
||||
5671FC221DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
|
||||
5656A8852295BD56001FF3FF /* SQLOrdering.swift in Sources */,
|
||||
F3BA808D1CFB2E75003DC1BA /* Migration.swift in Sources */,
|
||||
F3BA80791CFB2E61003DC1BA /* DatabaseDateComponents.swift in Sources */,
|
||||
5674A6EC1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */,
|
||||
568ECB0D25D904CA00B71526 /* SQLSelection.swift in Sources */,
|
||||
5657AB111D10899D006283EF /* URL.swift in Sources */,
|
||||
56F34FF124B0F0D8007513FC /* SQLCollatedExpression.swift in Sources */,
|
||||
5644DE7820F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */,
|
||||
56DAA2DD1DE9C827006E10C8 /* Cursor.swift in Sources */,
|
||||
F3BA80681CFB2E55003DC1BA /* DatabaseError.swift in Sources */,
|
||||
5656A8772295BD56001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
|
||||
@@ -2721,7 +2705,6 @@
|
||||
F3BA808F1CFB2E7A003DC1BA /* PersistableRecord.swift in Sources */,
|
||||
5656A87F2295BD56001FF3FF /* SQLForeignKeyRequest.swift in Sources */,
|
||||
56B964BB1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
|
||||
56D8B40D257D0FBE008AA1F7 /* SQLRowValue.swift in Sources */,
|
||||
561408A0221596A100DAD589 /* GRDB-5.0.swift in Sources */,
|
||||
F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */,
|
||||
56FBFED62210731100945324 /* SQLRequest.swift in Sources */,
|
||||
@@ -2731,7 +2714,6 @@
|
||||
5656A86F2295BD56001FF3FF /* Association.swift in Sources */,
|
||||
563B8F9B249E74E5007A48C9 /* Trace.swift in Sources */,
|
||||
5656A89B2295BD56001FF3FF /* SQLQuery.swift in Sources */,
|
||||
5656A88B2295BD56001FF3FF /* SQLExpression+QueryInterface.swift in Sources */,
|
||||
5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
|
||||
5656A85B2295BD56001FF3FF /* TableDefinition.swift in Sources */,
|
||||
5656A8552295BD56001FF3FF /* FTS5+QueryInterface.swift in Sources */,
|
||||
@@ -2743,7 +2725,6 @@
|
||||
5613ED6121A95E6100DC7A68 /* ValueObservation.swift in Sources */,
|
||||
F3BA80921CFB2E7A003DC1BA /* TableRecord.swift in Sources */,
|
||||
567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */,
|
||||
5656A8992295BD56001FF3FF /* SQLSelectable+QueryInterface.swift in Sources */,
|
||||
F3BA80831CFB2E67003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
|
||||
5657AABB1D107001006283EF /* NSData.swift in Sources */,
|
||||
5674A6E51F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
|
||||
@@ -2911,6 +2892,7 @@
|
||||
561CFA7D2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */,
|
||||
5623936C1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */,
|
||||
F3BA80E01CFB300F003DC1BA /* DatabaseTimestampTests.swift in Sources */,
|
||||
5604484E25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */,
|
||||
56A5EF121EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */,
|
||||
F3BA80B21CFB2FC5003DC1BA /* DatabaseTests.swift in Sources */,
|
||||
563EF442216131F5007DAACD /* AssociationAggregateTests.swift in Sources */,
|
||||
|
||||
@@ -50,7 +50,14 @@ TEST_ACTIONS = clean build build-for-testing test-without-building
|
||||
|
||||
# When adding support for an Xcode version, look for available devices with
|
||||
# `xcrun xctrace list devices` (or the deprecated `instruments -s devices`).
|
||||
ifeq ($(XCODEVERSION),12.3)
|
||||
ifeq ($(XCODEVERSION),12.4)
|
||||
MAX_SWIFT_VERSION = 5.3
|
||||
MIN_SWIFT_VERSION = 5.2
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 12,OS=14.4"
|
||||
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5s,OS=11.4"
|
||||
MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV 4K,OS=14.3"
|
||||
MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4"
|
||||
else ifeq ($(XCODEVERSION),12.3)
|
||||
MAX_SWIFT_VERSION = 5.3
|
||||
MIN_SWIFT_VERSION = 5.2
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 12,OS=14.3"
|
||||
@@ -424,10 +431,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.3.0 \
|
||||
--module-version 5.3.0 \
|
||||
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.5.0 \
|
||||
--module-version 5.5.0 \
|
||||
--module GRDB \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/5.3/ \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/5.5/ \
|
||||
--output Documentation/Reference \
|
||||
--xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS
|
||||
else
|
||||
|
||||
@@ -11,13 +11,13 @@
|
||||
|
||||
---
|
||||
|
||||
**Latest release**: January 9, 2021 • version 5.3.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
|
||||
**Latest release**: March 3, 2021 • version 5.5.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
|
||||
|
||||
**Requirements**: iOS 10.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ • SQLite 3.8.5+ • Swift 5.2+ / Xcode 11.4+
|
||||
|
||||
| Swift version | GRDB version |
|
||||
| -------------- | ----------------------------------------------------------- |
|
||||
| **Swift 5.2+** | **v5.3.0** |
|
||||
| **Swift 5.2+** | **v5.5.0** |
|
||||
| Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
|
||||
| Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
|
||||
| Swift 4.2 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
|
||||
@@ -278,7 +278,7 @@ Documentation
|
||||
|
||||
#### Reference
|
||||
|
||||
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.3/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
|
||||
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.5/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
|
||||
|
||||
#### Getting Started
|
||||
|
||||
@@ -472,7 +472,7 @@ let dbQueue = try DatabaseQueue(
|
||||
configuration: config)
|
||||
```
|
||||
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.3/Structs/Configuration.html) for more details.
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.5/Structs/Configuration.html) for more details.
|
||||
|
||||
|
||||
## Database Pools
|
||||
@@ -552,7 +552,7 @@ let dbPool = try DatabasePool(
|
||||
configuration: config)
|
||||
```
|
||||
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.3/Structs/Configuration.html) for more details.
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.5/Structs/Configuration.html) for more details.
|
||||
|
||||
|
||||
Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information.
|
||||
@@ -612,7 +612,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.3/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
|
||||
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.5/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.
|
||||
|
||||
@@ -815,7 +815,7 @@ try dbQueue.read { db in
|
||||
|
||||
- **Cursors are granted with direct access to SQLite,** unlike arrays and sets that have to take the time to copy database values. If you look after extra performance, you may prefer cursors.
|
||||
|
||||
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.3/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
|
||||
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.5/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
|
||||
@@ -898,7 +898,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.3/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
|
||||
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.5/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:
|
||||
|
||||
@@ -1183,7 +1183,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.3/Structs/StatementArguments.html):
|
||||
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let url: URL = ...
|
||||
@@ -1592,7 +1592,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.3/Structs/Configuration.html) configuration flag:
|
||||
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.5/Structs/Configuration.html) configuration flag:
|
||||
|
||||
```swift
|
||||
// fatal error: A transaction has been left opened at the end of a database access
|
||||
@@ -1706,7 +1706,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.3/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
|
||||
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
|
||||
|
||||
```swift
|
||||
updateStatement.arguments = ["name": "Arthur", "score": 1000]
|
||||
@@ -2483,7 +2483,7 @@ try Place.fetchSet(db, sql: "SELECT ...", arguments:...) // Set<Place>
|
||||
try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place?
|
||||
```
|
||||
|
||||
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.3/Structs/StatementArguments.html) for more information about the query arguments.
|
||||
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.5/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()`.
|
||||
|
||||
@@ -2864,7 +2864,7 @@ protocol EncodableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.3/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.3/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.3/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
|
||||
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.5/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.5/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.5/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).
|
||||
|
||||
@@ -4329,7 +4329,7 @@ Player // SELECT * FROM player
|
||||
```
|
||||
|
||||
|
||||
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.3/Structs/StatementArguments.html):
|
||||
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate)
|
||||
@@ -4388,6 +4388,8 @@ Feed [requests](#requests) with SQL expressions built from your Swift code:
|
||||
|
||||
### SQL Operators
|
||||
|
||||
GRDB comes with a Swift version of many SQLite [built-in operators](https://sqlite.org/lang_expr.html#operators), listed below. But not all: see [Adding support for missing SQL functions or operators](#adding-support-for-missing-sql-functions-or-operators).
|
||||
|
||||
- `=`, `<>`, `<`, `<=`, `>`, `>=`, `IS`, `IS NOT`
|
||||
|
||||
Comparison operators are based on the Swift operators `==`, `!=`, `===`, `!==`, `<`, `<=`, `>`, `>=`:
|
||||
@@ -4577,6 +4579,8 @@ Feed [requests](#requests) with SQL expressions built from your Swift code:
|
||||
|
||||
### SQL Functions
|
||||
|
||||
GRDB comes with a Swift version of many SQLite [built-in functions](https://sqlite.org/lang_corefunc.html), listed below. But not all: see [Adding support for missing SQL functions or operators](#adding-support-for-missing-sql-functions-or-operators).
|
||||
|
||||
- `ABS`, `AVG`, `COUNT`, `DATETIME`, `JULIANDAY`, `LENGTH`, `MAX`, `MIN`, `SUM`:
|
||||
|
||||
Those are based on the `abs`, `average`, `count`, `dateTime`, `julianDay`, `length`, `max`, `min` and `sum` Swift functions:
|
||||
@@ -4642,6 +4646,22 @@ Feed [requests](#requests) with SQL expressions built from your Swift code:
|
||||
Player.select(f.apply(nameColumn))
|
||||
```
|
||||
|
||||
### Adding support for missing SQL functions or operators
|
||||
|
||||
When you spot an SQL function or operator that misses its Swift version, you can define it right into your application code.
|
||||
|
||||
For example, you can add support for the `DATE` function, thanks to [SQL Interpolation]:
|
||||
|
||||
```swift
|
||||
func date(_ value: SQLExpressible) -> SQLExpression {
|
||||
SQLLiteral("DATE(\(value))").sqlExpression
|
||||
}
|
||||
|
||||
// SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23'
|
||||
let createdAt = Column("createdAt")
|
||||
let request = Player.filter(date(createdAt) == "2020-01-23")
|
||||
```
|
||||
|
||||
|
||||
## Fetching from Requests
|
||||
|
||||
@@ -4996,7 +5016,7 @@ try Player.customRequest().fetchAll(db) // [Player]
|
||||
|
||||
- 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.3/Structs/AnyFetchRequest.html): a type-erased request.
|
||||
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.5/Structs/AnyFetchRequest.html): a type-erased request.
|
||||
|
||||
|
||||
## Joined Queries Support
|
||||
@@ -6170,7 +6190,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan
|
||||
|
||||
### DatabaseRegion
|
||||
|
||||
**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.3/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**.
|
||||
**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.5/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.
|
||||
|
||||
@@ -6180,7 +6200,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.3/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF).
|
||||
For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/5.5/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF).
|
||||
|
||||
|
||||
#### The DatabaseRegionConvertible Protocol
|
||||
@@ -7300,7 +7320,7 @@ try snapshot2.read { db in
|
||||
|
||||
### DatabaseWriter and DatabaseReader Protocols
|
||||
|
||||
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.3/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.3/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only.
|
||||
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.5/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.5/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:
|
||||
|
||||
@@ -7975,7 +7995,7 @@ When this is the case, there are two possible explanations:
|
||||
try db.execute(sql: "UPDATE player SET name = ?", arguments: [name])
|
||||
```
|
||||
|
||||
For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.3/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp).
|
||||
For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.5/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp).
|
||||
|
||||
|
||||
|
||||
@@ -8137,4 +8157,4 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv
|
||||
[Sharing a Database]: Documentation/SharingADatabase.md
|
||||
[FAQ]: #faq
|
||||
[Database Observation]: #database-changes-observation
|
||||
[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.3/Structs/SQLRequest.html
|
||||
[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.5/Structs/SQLRequest.html
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>5.3.0</string>
|
||||
<string>5.5.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
- [ ] deprecate ScopeAdapter(base, scopes), because base.addingScopes has a better implementation
|
||||
- [ ] https://github.com/groue/GRDB.swift/issues/514
|
||||
- [ ] Test NOT TESTED methods
|
||||
|
||||
- [ ] Get inspiration from the templates at https://github.com/woocommerce/woocommerce-ios/tree/develop/.github (https://github.com/woocommerce/woocommerce-ios/pull/3523)
|
||||
|
||||
## Documentation
|
||||
|
||||
@@ -15,6 +15,12 @@
|
||||
|
||||
## Features
|
||||
|
||||
- [ ] Grab all FTS tokens in a string
|
||||
- [ ] GRDB 6: decoding errors
|
||||
- [ ] GRDB 6: conflict resolution in persistence methods
|
||||
- [ ] Long run edition. Use case: user edits the database (CRUD) but the application wants to commmit and the end of the editing session.
|
||||
* Create an edition SQLite connection with an open transaction (a new kind of DatabaseWriter with a save() method)
|
||||
* All other writes will fail with SQLITE_BUSY. Unless they are schedules in a target dispatch queue which is paused during the edition.
|
||||
- [ ] Can we use generated columns to makes it convenient to index on inserted JSON objects? https://github.com/apple/swift-package-manager/pull/3090#issuecomment-740091760
|
||||
- [ ] DatabaseMigrator.publisher(in:)
|
||||
- [ ] Look at [@FetchRequest](https://developer.apple.com/documentation/swiftui/fetchrequest): managed object context is stored in the environment, and error processing happens somewhere else (where?).
|
||||
|
||||
@@ -432,4 +432,664 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Three Steps
|
||||
|
||||
func testHasManyHasManyHasMany() throws {
|
||||
struct A: TableRecord, EncodableRecord {
|
||||
static let bs = hasMany(B.self)
|
||||
static let cs = hasMany(C.self, through: bs, using: B.cs)
|
||||
static let dsThroughCs = hasMany(D.self, through: cs, using: C.ds)
|
||||
static let dsThroughBs = hasMany(D.self, through: bs, using: B.ds)
|
||||
func encode(to container: inout PersistenceContainer) {
|
||||
container["id"] = 1
|
||||
}
|
||||
}
|
||||
struct B: TableRecord {
|
||||
static let cs = hasMany(C.self)
|
||||
static let ds = hasMany(D.self, through: cs, using: C.ds)
|
||||
}
|
||||
struct C: TableRecord {
|
||||
static let ds = hasMany(D.self)
|
||||
}
|
||||
struct D: 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")
|
||||
}
|
||||
try db.create(table: "d") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("cId").references("c")
|
||||
}
|
||||
|
||||
try testHasManyWithThreeSteps(
|
||||
db, bs: A.bs, cs: A.cs, dsThroughCs: A.dsThroughCs, dsThroughBs: A.dsThroughBs,
|
||||
bsCondition: "\"b\".\"aId\" = \"a\".\"id\"",
|
||||
csCondition: "\"c\".\"bId\" = \"b\".\"id\"",
|
||||
dsCondition: "\"d\".\"cId\" = \"c\".\"id\"")
|
||||
|
||||
try assertEqualSQL(db, A().request(for: A.dsThroughCs), """
|
||||
SELECT "d".* \
|
||||
FROM "d" \
|
||||
JOIN "c" ON "c"."id" = "d"."cId" \
|
||||
JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."aId" = 1)
|
||||
""")
|
||||
try assertEqualSQL(db, A().request(for: A.dsThroughBs), """
|
||||
SELECT "d".* \
|
||||
FROM "d" \
|
||||
JOIN "c" ON "c"."id" = "d"."cId" \
|
||||
JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."aId" = 1)
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
func testBelongsToHasManyHasMany() throws {
|
||||
struct A: TableRecord, EncodableRecord {
|
||||
static let b = belongsTo(B.self)
|
||||
static let cs = hasMany(C.self, through: b, using: B.cs)
|
||||
static let dsThroughCs = hasMany(D.self, through: cs, using: C.ds)
|
||||
static let dsThroughB = hasMany(D.self, through: b, using: B.ds)
|
||||
func encode(to container: inout PersistenceContainer) {
|
||||
container["bId"] = 1
|
||||
}
|
||||
}
|
||||
struct B: TableRecord {
|
||||
static let cs = hasMany(C.self)
|
||||
static let ds = hasMany(D.self, through: cs, using: C.ds)
|
||||
}
|
||||
struct C: TableRecord {
|
||||
static let ds = 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: "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")
|
||||
}
|
||||
try db.create(table: "a") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("bId").references("b")
|
||||
}
|
||||
|
||||
try testHasManyWithThreeSteps(
|
||||
db, bs: A.b, cs: A.cs, dsThroughCs: A.dsThroughCs, dsThroughBs: A.dsThroughB,
|
||||
bsCondition: "\"b\".\"id\" = \"a\".\"bId\"",
|
||||
csCondition: "\"c\".\"bId\" = \"b\".\"id\"",
|
||||
dsCondition: "\"d\".\"cId\" = \"c\".\"id\"")
|
||||
|
||||
try assertEqualSQL(db, A().request(for: A.dsThroughCs), """
|
||||
SELECT "d".* FROM "d" \
|
||||
JOIN "c" ON "c"."id" = "d"."cId" \
|
||||
JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."id" = 1)
|
||||
""")
|
||||
try assertEqualSQL(db, A().request(for: A.dsThroughB), """
|
||||
SELECT "d".* FROM "d" \
|
||||
JOIN "c" ON "c"."id" = "d"."cId" \
|
||||
JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."id" = 1)
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
func testHasManyHasManyBelongsTo() throws {
|
||||
struct A: TableRecord, EncodableRecord {
|
||||
static let bs = hasMany(B.self)
|
||||
static let cs = hasMany(C.self, through: bs, using: B.cs)
|
||||
static let dsThroughCs = hasMany(D.self, through: cs, using: C.d)
|
||||
static let dsThroughBs = hasMany(D.self, through: bs, using: B.ds)
|
||||
func encode(to container: inout PersistenceContainer) {
|
||||
container["id"] = 1
|
||||
}
|
||||
}
|
||||
struct B: TableRecord {
|
||||
static let cs = hasMany(C.self)
|
||||
static let ds = hasMany(D.self, through: cs, using: C.d)
|
||||
}
|
||||
struct C: TableRecord {
|
||||
static let d = belongsTo(D.self)
|
||||
}
|
||||
struct D: TableRecord {
|
||||
}
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "a") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
}
|
||||
try db.create(table: "d") { 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")
|
||||
t.column("dId").references("d")
|
||||
}
|
||||
|
||||
try testHasManyWithThreeSteps(
|
||||
db, bs: A.bs, cs: A.cs, dsThroughCs: A.dsThroughCs, dsThroughBs: A.dsThroughBs,
|
||||
bsCondition: "\"b\".\"aId\" = \"a\".\"id\"",
|
||||
csCondition: "\"c\".\"bId\" = \"b\".\"id\"",
|
||||
dsCondition: "\"d\".\"id\" = \"c\".\"dId\"")
|
||||
|
||||
try assertEqualSQL(db, A().request(for: A.dsThroughCs), """
|
||||
SELECT "d".* FROM "d" \
|
||||
JOIN "c" ON "c"."dId" = "d"."id" \
|
||||
JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."aId" = 1)
|
||||
""")
|
||||
try assertEqualSQL(db, A().request(for: A.dsThroughBs), """
|
||||
SELECT "d".* FROM "d" \
|
||||
JOIN "c" ON "c"."dId" = "d"."id" \
|
||||
JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."aId" = 1)
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
private func testHasManyWithThreeSteps<BsAssociation, CsAssociation, DsCsAssociation, DsBsAssociation>(
|
||||
_ db: Database,
|
||||
bs: BsAssociation,
|
||||
cs: CsAssociation,
|
||||
dsThroughCs: DsCsAssociation,
|
||||
dsThroughBs: DsBsAssociation,
|
||||
bsCondition: String,
|
||||
csCondition: String,
|
||||
dsCondition: String) throws
|
||||
where
|
||||
BsAssociation: Association,
|
||||
CsAssociation: Association,
|
||||
DsCsAssociation: Association,
|
||||
DsBsAssociation: Association,
|
||||
BsAssociation.OriginRowDecoder: TableRecord,
|
||||
BsAssociation.OriginRowDecoder == CsAssociation.OriginRowDecoder,
|
||||
BsAssociation.OriginRowDecoder == DsCsAssociation.OriginRowDecoder,
|
||||
BsAssociation.OriginRowDecoder == DsBsAssociation.OriginRowDecoder
|
||||
{
|
||||
let A = CsAssociation.OriginRowDecoder.self
|
||||
|
||||
do {
|
||||
for request in [
|
||||
A.including(optional: dsThroughCs),
|
||||
A.including(optional: dsThroughBs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "d".* \
|
||||
FROM "a" \
|
||||
LEFT JOIN "b" ON \(bsCondition) \
|
||||
LEFT JOIN "c" ON \(csCondition) \
|
||||
LEFT JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.including(required: dsThroughCs),
|
||||
A.including(required: dsThroughBs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "d".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
JOIN "c" ON \(csCondition) \
|
||||
JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.joining(optional: dsThroughCs),
|
||||
A.joining(optional: dsThroughBs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".* \
|
||||
FROM "a" \
|
||||
LEFT JOIN "b" ON \(bsCondition) \
|
||||
LEFT JOIN "c" ON \(csCondition) \
|
||||
LEFT JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.joining(required: dsThroughCs),
|
||||
A.joining(required: dsThroughBs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
JOIN "c" ON \(csCondition) \
|
||||
JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
do {
|
||||
for request in [
|
||||
A.including(optional: dsThroughCs).including(optional: bs),
|
||||
A.including(optional: dsThroughBs).including(optional: bs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "b".*, "d".* \
|
||||
FROM "a" \
|
||||
LEFT JOIN "b" ON \(bsCondition) \
|
||||
LEFT JOIN "c" ON \(csCondition) \
|
||||
LEFT JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.including(required: dsThroughCs).including(optional: bs),
|
||||
A.including(required: dsThroughBs).including(optional: bs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "b".*, "d".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
JOIN "c" ON \(csCondition) \
|
||||
JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.joining(optional: dsThroughCs).including(optional: bs),
|
||||
A.joining(optional: dsThroughBs).including(optional: bs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "b".* \
|
||||
FROM "a" \
|
||||
LEFT JOIN "b" ON \(bsCondition) \
|
||||
LEFT JOIN "c" ON \(csCondition) \
|
||||
LEFT JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.joining(required: dsThroughCs).including(optional: bs),
|
||||
A.joining(required: dsThroughBs).including(optional: bs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "b".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
JOIN "c" ON \(csCondition) \
|
||||
JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
for request in [
|
||||
A.including(optional: dsThroughCs).including(required: bs),
|
||||
A.including(optional: dsThroughBs).including(required: bs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "b".*, "d".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
LEFT JOIN "c" ON \(csCondition) \
|
||||
LEFT JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.including(required: dsThroughCs).including(required: bs),
|
||||
A.including(required: dsThroughBs).including(required: bs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "b".*, "d".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
JOIN "c" ON \(csCondition) \
|
||||
JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.joining(optional: dsThroughCs).including(required: bs),
|
||||
A.joining(optional: dsThroughBs).including(required: bs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "b".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
LEFT JOIN "c" ON \(csCondition) \
|
||||
LEFT JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.joining(required: dsThroughCs).including(required: bs),
|
||||
A.joining(required: dsThroughBs).including(required: bs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "b".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
JOIN "c" ON \(csCondition) \
|
||||
JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
for request in [
|
||||
A.including(optional: dsThroughCs).joining(optional: bs),
|
||||
A.including(optional: dsThroughBs).joining(optional: bs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "d".* \
|
||||
FROM "a" \
|
||||
LEFT JOIN "b" ON \(bsCondition) \
|
||||
LEFT JOIN "c" ON \(csCondition) \
|
||||
LEFT JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.including(required: dsThroughCs).joining(optional: bs),
|
||||
A.including(required: dsThroughBs).joining(optional: bs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "d".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
JOIN "c" ON \(csCondition) \
|
||||
JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.joining(optional: dsThroughCs).joining(optional: bs),
|
||||
A.joining(optional: dsThroughBs).joining(optional: bs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".* \
|
||||
FROM "a" \
|
||||
LEFT JOIN "b" ON \(bsCondition) \
|
||||
LEFT JOIN "c" ON \(csCondition) \
|
||||
LEFT JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.joining(required: dsThroughCs).joining(optional: bs),
|
||||
A.joining(required: dsThroughBs).joining(optional: bs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
JOIN "c" ON \(csCondition) \
|
||||
JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
for request in [
|
||||
A.including(optional: dsThroughCs).joining(required: bs),
|
||||
A.including(optional: dsThroughBs).joining(required: bs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "d".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
LEFT JOIN "c" ON \(csCondition) \
|
||||
LEFT JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.including(required: dsThroughCs).joining(required: bs),
|
||||
A.including(required: dsThroughBs).joining(required: bs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "d".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
JOIN "c" ON \(csCondition) \
|
||||
JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.joining(optional: dsThroughCs).joining(required: bs),
|
||||
A.joining(optional: dsThroughBs).joining(required: bs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
LEFT JOIN "c" ON \(csCondition) \
|
||||
LEFT JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.joining(required: dsThroughCs).joining(required: bs),
|
||||
A.joining(required: dsThroughBs).joining(required: bs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
JOIN "c" ON \(csCondition) \
|
||||
JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
do {
|
||||
for request in [
|
||||
A.including(optional: dsThroughCs).including(optional: cs),
|
||||
A.including(optional: dsThroughBs).including(optional: cs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "c".*, "d".* \
|
||||
FROM "a" \
|
||||
LEFT JOIN "b" ON \(bsCondition) \
|
||||
LEFT JOIN "c" ON \(csCondition) \
|
||||
LEFT JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.including(required: dsThroughCs).including(optional: cs),
|
||||
A.including(required: dsThroughBs).including(optional: cs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "c".*, "d".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
JOIN "c" ON \(csCondition) \
|
||||
JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.joining(optional: dsThroughCs).including(optional: cs),
|
||||
A.joining(optional: dsThroughBs).including(optional: cs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "c".* \
|
||||
FROM "a" \
|
||||
LEFT JOIN "b" ON \(bsCondition) \
|
||||
LEFT JOIN "c" ON \(csCondition) \
|
||||
LEFT JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.joining(required: dsThroughCs).including(optional: cs),
|
||||
A.joining(required: dsThroughBs).including(optional: cs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "c".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
JOIN "c" ON \(csCondition) \
|
||||
JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
for request in [
|
||||
A.including(optional: dsThroughCs).including(required: cs),
|
||||
A.including(optional: dsThroughBs).including(required: cs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "c".*, "d".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
JOIN "c" ON \(csCondition) \
|
||||
LEFT JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.including(required: dsThroughCs).including(required: cs),
|
||||
A.including(required: dsThroughBs).including(required: cs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "c".*, "d".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
JOIN "c" ON \(csCondition) \
|
||||
JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.joining(optional: dsThroughCs).including(required: cs),
|
||||
A.joining(optional: dsThroughBs).including(required: cs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "c".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
JOIN "c" ON \(csCondition) \
|
||||
LEFT JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.joining(required: dsThroughCs).including(required: cs),
|
||||
A.joining(required: dsThroughBs).including(required: cs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "c".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
JOIN "c" ON \(csCondition) \
|
||||
JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
for request in [
|
||||
A.including(optional: dsThroughCs).joining(optional: cs),
|
||||
A.including(optional: dsThroughBs).joining(optional: cs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "d".* \
|
||||
FROM "a" \
|
||||
LEFT JOIN "b" ON \(bsCondition) \
|
||||
LEFT JOIN "c" ON \(csCondition) \
|
||||
LEFT JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.including(required: dsThroughCs).joining(optional: cs),
|
||||
A.including(required: dsThroughBs).joining(optional: cs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "d".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
JOIN "c" ON \(csCondition) \
|
||||
JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.joining(optional: dsThroughCs).joining(optional: cs),
|
||||
A.joining(optional: dsThroughBs).joining(optional: cs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".* \
|
||||
FROM "a" \
|
||||
LEFT JOIN "b" ON \(bsCondition) \
|
||||
LEFT JOIN "c" ON \(csCondition) \
|
||||
LEFT JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.joining(required: dsThroughCs).joining(optional: cs),
|
||||
A.joining(required: dsThroughBs).joining(optional: cs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
JOIN "c" ON \(csCondition) \
|
||||
JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
for request in [
|
||||
A.including(optional: dsThroughCs).joining(required: cs),
|
||||
A.including(optional: dsThroughBs).joining(required: cs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "d".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
JOIN "c" ON \(csCondition) \
|
||||
LEFT JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.including(required: dsThroughCs).joining(required: cs),
|
||||
A.including(required: dsThroughBs).joining(required: cs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "d".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
JOIN "c" ON \(csCondition) \
|
||||
JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.joining(optional: dsThroughCs).joining(required: cs),
|
||||
A.joining(optional: dsThroughBs).joining(required: cs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
JOIN "c" ON \(csCondition) \
|
||||
LEFT JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
for request in [
|
||||
A.joining(required: dsThroughCs).joining(required: cs),
|
||||
A.joining(required: dsThroughBs).joining(required: cs)]
|
||||
{
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON \(bsCondition) \
|
||||
JOIN "c" ON \(csCondition) \
|
||||
JOIN "d" ON \(dsCondition)
|
||||
""")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,693 @@
|
||||
import XCTest
|
||||
@testable import GRDB
|
||||
|
||||
class AssociationPrefetchingRelationTests: GRDBTestCase {
|
||||
func testAssociationKeyInflections() {
|
||||
do {
|
||||
let key = SQLAssociationKey.inflected("player")
|
||||
XCTAssertEqual(key.baseName, "player")
|
||||
XCTAssertEqual(key.singularizedName, "player")
|
||||
XCTAssertEqual(key.pluralizedName, "players")
|
||||
XCTAssertEqual(key.name(singular: true), "player")
|
||||
XCTAssertEqual(key.name(singular: false), "players")
|
||||
}
|
||||
do {
|
||||
let key = SQLAssociationKey.fixedSingular("player")
|
||||
XCTAssertEqual(key.baseName, "player")
|
||||
XCTAssertEqual(key.singularizedName, "player")
|
||||
XCTAssertEqual(key.pluralizedName, "players")
|
||||
XCTAssertEqual(key.name(singular: true), "player")
|
||||
XCTAssertEqual(key.name(singular: false), "players")
|
||||
}
|
||||
do {
|
||||
let key = SQLAssociationKey.fixedSingular("players")
|
||||
XCTAssertEqual(key.baseName, "players")
|
||||
XCTAssertEqual(key.singularizedName, "players")
|
||||
XCTAssertEqual(key.pluralizedName, "players")
|
||||
XCTAssertEqual(key.name(singular: true), "players")
|
||||
XCTAssertEqual(key.name(singular: false), "players")
|
||||
}
|
||||
do {
|
||||
let key = SQLAssociationKey.fixedPlural("player")
|
||||
XCTAssertEqual(key.baseName, "player")
|
||||
XCTAssertEqual(key.singularizedName, "player")
|
||||
XCTAssertEqual(key.pluralizedName, "player")
|
||||
XCTAssertEqual(key.name(singular: true), "player")
|
||||
XCTAssertEqual(key.name(singular: false), "player")
|
||||
}
|
||||
do {
|
||||
let key = SQLAssociationKey.fixedPlural("players")
|
||||
XCTAssertEqual(key.baseName, "players")
|
||||
XCTAssertEqual(key.singularizedName, "player")
|
||||
XCTAssertEqual(key.pluralizedName, "players")
|
||||
XCTAssertEqual(key.name(singular: true), "player")
|
||||
XCTAssertEqual(key.name(singular: false), "players")
|
||||
}
|
||||
do {
|
||||
let key = SQLAssociationKey.fixed("player")
|
||||
XCTAssertEqual(key.baseName, "player")
|
||||
XCTAssertEqual(key.singularizedName, "player")
|
||||
XCTAssertEqual(key.pluralizedName, "player")
|
||||
XCTAssertEqual(key.name(singular: true), "player")
|
||||
XCTAssertEqual(key.name(singular: false), "player")
|
||||
}
|
||||
do {
|
||||
let key = SQLAssociationKey.fixed("players")
|
||||
XCTAssertEqual(key.baseName, "players")
|
||||
XCTAssertEqual(key.singularizedName, "players")
|
||||
XCTAssertEqual(key.pluralizedName, "players")
|
||||
XCTAssertEqual(key.name(singular: true), "players")
|
||||
XCTAssertEqual(key.name(singular: false), "players")
|
||||
}
|
||||
}
|
||||
|
||||
func testOneStep() {
|
||||
let cardinalities: [SQLAssociationCardinality] = [
|
||||
.toOne,
|
||||
.toMany,
|
||||
]
|
||||
|
||||
let keys: [SQLAssociationKey] = [
|
||||
.inflected("player"),
|
||||
.fixedSingular("player"),
|
||||
.fixedSingular("players"),
|
||||
.fixedPlural("player"),
|
||||
.fixedPlural("players"),
|
||||
.fixed("player"),
|
||||
]
|
||||
|
||||
for cardinality in cardinalities {
|
||||
for key in keys {
|
||||
|
||||
let relation = SQLRelation.all(fromTable: "ignored")
|
||||
|
||||
let association = _SQLAssociation(
|
||||
key: key,
|
||||
condition: .none,
|
||||
relation: .all(fromTable: "ignored"),
|
||||
cardinality: cardinality)
|
||||
|
||||
for relation in [
|
||||
relation._joining(optional: association),
|
||||
relation._including(optional: association),
|
||||
] {
|
||||
do {
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneOptional)
|
||||
}
|
||||
do {
|
||||
let relation = relation._joining(optional: association)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneOptional)
|
||||
}
|
||||
do {
|
||||
let relation = relation._joining(required: association)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
}
|
||||
do {
|
||||
let relation = relation._including(optional: association)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneOptional)
|
||||
}
|
||||
do {
|
||||
let relation = relation._including(required: association)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
}
|
||||
if key.name(singular: true) != key.name(singular: false) {
|
||||
let relation = relation._including(all: association)
|
||||
XCTAssertEqual(relation.children.count, 2)
|
||||
XCTAssertEqual(relation.children[0].key, key.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneOptional)
|
||||
XCTAssertEqual(relation.children[1].key, key.name(singular: false))
|
||||
XCTAssertEqual(relation.children[1].value.kind, .all)
|
||||
}
|
||||
}
|
||||
|
||||
for relation in [
|
||||
relation._joining(required: association),
|
||||
relation._including(required: association),
|
||||
] {
|
||||
do {
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
}
|
||||
do {
|
||||
let relation = relation._joining(optional: association)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
}
|
||||
do {
|
||||
let relation = relation._joining(required: association)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
}
|
||||
do {
|
||||
let relation = relation._including(optional: association)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
}
|
||||
do {
|
||||
let relation = relation._including(required: association)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
}
|
||||
if key.name(singular: true) != key.name(singular: false) {
|
||||
let relation = relation._including(all: association)
|
||||
XCTAssertEqual(relation.children.count, 2)
|
||||
XCTAssertEqual(relation.children[0].key, key.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
XCTAssertEqual(relation.children[1].key, key.name(singular: false))
|
||||
XCTAssertEqual(relation.children[1].value.kind, .all)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let relation = relation._including(all: association)
|
||||
do {
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key.name(singular: false))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .all)
|
||||
}
|
||||
if key.name(singular: true) != key.name(singular: false) {
|
||||
let relation = relation._joining(optional: association)
|
||||
XCTAssertEqual(relation.children.count, 2)
|
||||
XCTAssertEqual(relation.children[0].key, key.name(singular: false))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .all)
|
||||
XCTAssertEqual(relation.children[1].key, key.name(singular: true))
|
||||
XCTAssertEqual(relation.children[1].value.kind, .oneOptional)
|
||||
}
|
||||
if key.name(singular: true) != key.name(singular: false) {
|
||||
let relation = relation._joining(required: association)
|
||||
XCTAssertEqual(relation.children.count, 2)
|
||||
XCTAssertEqual(relation.children[0].key, key.name(singular: false))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .all)
|
||||
XCTAssertEqual(relation.children[1].key, key.name(singular: true))
|
||||
XCTAssertEqual(relation.children[1].value.kind, .oneRequired)
|
||||
}
|
||||
if key.name(singular: true) != key.name(singular: false) {
|
||||
let relation = relation._including(optional: association)
|
||||
XCTAssertEqual(relation.children.count, 2)
|
||||
XCTAssertEqual(relation.children[0].key, key.name(singular: false))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .all)
|
||||
XCTAssertEqual(relation.children[1].key, key.name(singular: true))
|
||||
XCTAssertEqual(relation.children[1].value.kind, .oneOptional)
|
||||
}
|
||||
if key.name(singular: true) != key.name(singular: false) {
|
||||
let relation = relation._including(required: association)
|
||||
XCTAssertEqual(relation.children.count, 2)
|
||||
XCTAssertEqual(relation.children[0].key, key.name(singular: false))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .all)
|
||||
XCTAssertEqual(relation.children[1].key, key.name(singular: true))
|
||||
XCTAssertEqual(relation.children[1].value.kind, .oneRequired)
|
||||
}
|
||||
do {
|
||||
let relation = relation._including(all: association)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key.name(singular: false))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .all)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testTwoSteps() {
|
||||
let cardinalities: [SQLAssociationCardinality] = [
|
||||
.toOne,
|
||||
.toMany,
|
||||
]
|
||||
|
||||
let keys1: [SQLAssociationKey] = [
|
||||
.inflected("player"),
|
||||
.fixedSingular("player"),
|
||||
.fixedSingular("players"),
|
||||
.fixedPlural("player"),
|
||||
.fixedPlural("players"),
|
||||
.fixed("player"),
|
||||
]
|
||||
|
||||
let keys2: [SQLAssociationKey] = [
|
||||
.inflected("award"),
|
||||
.fixedSingular("award"),
|
||||
.fixedSingular("awards"),
|
||||
.fixedPlural("award"),
|
||||
.fixedPlural("awards"),
|
||||
.fixed("award"),
|
||||
]
|
||||
|
||||
for cardinality1 in cardinalities {
|
||||
for key1 in keys1 {
|
||||
for cardinality2 in cardinalities {
|
||||
for key2 in keys2 {
|
||||
let relation = SQLRelation.all(fromTable: "ignored")
|
||||
|
||||
let association1 = _SQLAssociation(
|
||||
key: key1,
|
||||
condition: .none,
|
||||
relation: .all(fromTable: "ignored"),
|
||||
cardinality: cardinality1)
|
||||
|
||||
let association2 = _SQLAssociation(
|
||||
key: key2,
|
||||
condition: .none,
|
||||
relation: .all(fromTable: "ignored"),
|
||||
cardinality: cardinality2)
|
||||
|
||||
let association = association2.through(association1)
|
||||
|
||||
for relation in [
|
||||
relation._joining(optional: association),
|
||||
relation._including(optional: association),
|
||||
] {
|
||||
do {
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneOptional)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneOptional)
|
||||
}
|
||||
do {
|
||||
do {
|
||||
let relation = relation._joining(optional: association1)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneOptional)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneOptional)
|
||||
}
|
||||
do {
|
||||
let relation = relation._joining(required: association1)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneOptional)
|
||||
}
|
||||
do {
|
||||
let relation = relation._including(optional: association1)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneOptional)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneOptional)
|
||||
}
|
||||
do {
|
||||
let relation = relation._including(required: association1)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneOptional)
|
||||
}
|
||||
if !cardinality1.isSingular && key1.name(singular: true) != key1.name(singular: false) {
|
||||
let relation = relation._including(all: association1)
|
||||
XCTAssertEqual(relation.children.count, 2)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneOptional)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneOptional)
|
||||
XCTAssertEqual(relation.children[1].key, key1.name(singular: false))
|
||||
XCTAssertEqual(relation.children[1].value.kind, .all)
|
||||
XCTAssertEqual(relation.children[1].value.relation.children.count, 0)
|
||||
}
|
||||
}
|
||||
do {
|
||||
do {
|
||||
let relation = relation._joining(optional: association)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneOptional)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneOptional)
|
||||
}
|
||||
do {
|
||||
let relation = relation._joining(required: association)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired)
|
||||
}
|
||||
do {
|
||||
let relation = relation._including(optional: association)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneOptional)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneOptional)
|
||||
}
|
||||
do {
|
||||
let relation = relation._including(required: association)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired)
|
||||
}
|
||||
if !cardinality1.isSingular && key1.name(singular: true) != key1.name(singular: false) {
|
||||
let relation = relation._including(all: association)
|
||||
XCTAssertEqual(relation.children.count, 2)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneOptional)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneOptional)
|
||||
XCTAssertEqual(relation.children[1].key, key1.name(singular: cardinality1.isSingular))
|
||||
XCTAssertEqual(relation.children[1].value.kind, .bridge)
|
||||
XCTAssertEqual(relation.children[1].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[1].value.relation.children[0].key, key2.name(singular: false))
|
||||
XCTAssertEqual(relation.children[1].value.relation.children[0].value.kind, .all)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for relation in [
|
||||
relation._joining(required: association),
|
||||
relation._including(required: association),
|
||||
] {
|
||||
do {
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired)
|
||||
}
|
||||
do {
|
||||
do {
|
||||
let relation = relation._joining(optional: association1)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired)
|
||||
}
|
||||
do {
|
||||
let relation = relation._joining(required: association1)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired)
|
||||
}
|
||||
do {
|
||||
let relation = relation._including(optional: association1)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired)
|
||||
}
|
||||
do {
|
||||
let relation = relation._including(required: association1)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired)
|
||||
}
|
||||
if !cardinality1.isSingular && key1.name(singular: true) != key1.name(singular: false) {
|
||||
let relation = relation._including(all: association1)
|
||||
XCTAssertEqual(relation.children.count, 2)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired)
|
||||
XCTAssertEqual(relation.children[1].key, key1.name(singular: false))
|
||||
XCTAssertEqual(relation.children[1].value.kind, .all)
|
||||
XCTAssertEqual(relation.children[1].value.relation.children.count, 0)
|
||||
}
|
||||
}
|
||||
do {
|
||||
do {
|
||||
let relation = relation._joining(optional: association)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired)
|
||||
}
|
||||
do {
|
||||
let relation = relation._joining(required: association)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired)
|
||||
}
|
||||
do {
|
||||
let relation = relation._including(optional: association)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired)
|
||||
}
|
||||
do {
|
||||
let relation = relation._including(required: association)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired)
|
||||
}
|
||||
if !cardinality1.isSingular && key1.name(singular: true) != key1.name(singular: false) {
|
||||
let relation = relation._including(all: association)
|
||||
XCTAssertEqual(relation.children.count, 2)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired)
|
||||
XCTAssertEqual(relation.children[1].key, key1.name(singular: cardinality1.isSingular))
|
||||
XCTAssertEqual(relation.children[1].value.kind, .bridge)
|
||||
XCTAssertEqual(relation.children[1].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[1].value.relation.children[0].key, key2.name(singular: false))
|
||||
XCTAssertEqual(relation.children[1].value.relation.children[0].value.kind, .all)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let relation = relation._including(all: association)
|
||||
do {
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: cardinality1.isSingular))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .bridge)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: false))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .all)
|
||||
}
|
||||
|
||||
// TODO: here we see the problem: it should be possible to merge association1 when it is singular.
|
||||
if !cardinality1.isSingular && key1.name(singular: true) != key1.name(singular: false) {
|
||||
let relation = relation._joining(optional: association1)
|
||||
XCTAssertEqual(relation.children.count, 2)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: cardinality1.isSingular))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .bridge)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: false))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .all)
|
||||
XCTAssertEqual(relation.children[1].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[1].value.kind, .oneOptional)
|
||||
XCTAssertEqual(relation.children[1].value.relation.children.count, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testThreeSteps() {
|
||||
let cardinalities: [SQLAssociationCardinality] = [
|
||||
.toOne,
|
||||
.toMany,
|
||||
]
|
||||
|
||||
let keys1: [SQLAssociationKey] = [
|
||||
.inflected("player"),
|
||||
.fixedSingular("player"),
|
||||
.fixedSingular("players"),
|
||||
.fixedPlural("player"),
|
||||
.fixedPlural("players"),
|
||||
.fixed("player"),
|
||||
]
|
||||
|
||||
let keys2: [SQLAssociationKey] = [
|
||||
.inflected("award"),
|
||||
.fixedSingular("award"),
|
||||
.fixedSingular("awards"),
|
||||
.fixedPlural("award"),
|
||||
.fixedPlural("awards"),
|
||||
.fixed("award"),
|
||||
]
|
||||
|
||||
let keys3: [SQLAssociationKey] = [
|
||||
.inflected("sponsor"),
|
||||
.fixedSingular("sponsor"),
|
||||
.fixedSingular("sponsors"),
|
||||
.fixedPlural("sponsor"),
|
||||
.fixedPlural("sponsors"),
|
||||
.fixed("sponsor"),
|
||||
]
|
||||
|
||||
for cardinality1 in cardinalities {
|
||||
for key1 in keys1 {
|
||||
for cardinality2 in cardinalities {
|
||||
for key2 in keys2 {
|
||||
for cardinality3 in cardinalities {
|
||||
for key3 in keys3 {
|
||||
let relation = SQLRelation.all(fromTable: "ignored")
|
||||
|
||||
let association1 = _SQLAssociation(
|
||||
key: key1,
|
||||
condition: .none,
|
||||
relation: .all(fromTable: "ignored"),
|
||||
cardinality: cardinality1)
|
||||
|
||||
let association2 = _SQLAssociation(
|
||||
key: key2,
|
||||
condition: .none,
|
||||
relation: .all(fromTable: "ignored"),
|
||||
cardinality: cardinality2)
|
||||
|
||||
let association3 = _SQLAssociation(
|
||||
key: key3,
|
||||
condition: .none,
|
||||
relation: .all(fromTable: "ignored"),
|
||||
cardinality: cardinality3)
|
||||
|
||||
for association in [
|
||||
association3.through(association2.through(association1)),
|
||||
association3.through(association2).through(association1),
|
||||
] {
|
||||
|
||||
for relation in [
|
||||
relation._joining(optional: association),
|
||||
relation._including(optional: association),
|
||||
] {
|
||||
do {
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneOptional)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneOptional)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].key, key3.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].value.kind, .oneOptional)
|
||||
}
|
||||
do {
|
||||
let relation = relation._joining(optional: association1)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneOptional)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneOptional)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].key, key3.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].value.kind, .oneOptional)
|
||||
}
|
||||
}
|
||||
|
||||
for relation in [
|
||||
relation._joining(required: association),
|
||||
relation._including(required: association),
|
||||
] {
|
||||
do {
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].key, key3.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].value.kind, .oneRequired)
|
||||
}
|
||||
do {
|
||||
let relation = relation._joining(optional: association1)
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .oneRequired)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].key, key3.name(singular: true))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].value.kind, .oneRequired)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let relation = relation._including(all: association)
|
||||
do {
|
||||
XCTAssertEqual(relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: cardinality1.isSingular))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .bridge)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: cardinality2.isSingular))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .bridge)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].key, key3.name(singular: false))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].value.kind, .all)
|
||||
}
|
||||
// TODO: here we see the problem: it should be possible to merge association1 when it is singular.
|
||||
if !cardinality1.isSingular && key1.name(singular: true) != key1.name(singular: false) {
|
||||
let relation = relation._joining(optional: association1)
|
||||
XCTAssertEqual(relation.children.count, 2)
|
||||
XCTAssertEqual(relation.children[0].key, key1.name(singular: cardinality1.isSingular))
|
||||
XCTAssertEqual(relation.children[0].value.kind, .bridge)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: cardinality2.isSingular))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .bridge)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children.count, 1)
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].key, key3.name(singular: false))
|
||||
XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].value.kind, .all)
|
||||
XCTAssertEqual(relation.children[1].key, key1.name(singular: true))
|
||||
XCTAssertEqual(relation.children[1].value.kind, .oneOptional)
|
||||
XCTAssertEqual(relation.children[1].value.relation.children.count, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -937,8 +937,8 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
|
||||
// This request is an example of what users are unlikely to
|
||||
// want, because of the shared key between the two different
|
||||
// pivot associations.
|
||||
// However, A.hasMany(C.self) does not conflict. Thos is an
|
||||
// indirect proof that it feeds an association kt, "as", which
|
||||
// However, A.hasMany(C.self) does not conflict. This is an
|
||||
// indirect proof that it feeds an association key, "as", which
|
||||
// is distinc from "a" (A.hasOne(C.self)).
|
||||
let request = A
|
||||
.including(all: A
|
||||
|
||||
@@ -2,6 +2,29 @@ import XCTest
|
||||
import GRDB
|
||||
|
||||
class CommonTableExpressionTests: GRDBTestCase {
|
||||
func testInitializers() {
|
||||
// Implicit generic RowDecoder type is Row
|
||||
func acceptRowCTE(_ cte: CommonTableExpression<Row>) { }
|
||||
do {
|
||||
let cte = CommonTableExpression(named: "foo", sql: "")
|
||||
acceptRowCTE(cte)
|
||||
}
|
||||
do {
|
||||
let cte = CommonTableExpression(named: "foo", literal: "")
|
||||
acceptRowCTE(cte)
|
||||
}
|
||||
do {
|
||||
let cte = CommonTableExpression(named: "foo", request: SQLRequest<Void>(""))
|
||||
acceptRowCTE(cte)
|
||||
}
|
||||
|
||||
// Explicit type
|
||||
struct S { }
|
||||
_ = CommonTableExpression<S>(named: "foo", sql: "")
|
||||
_ = CommonTableExpression<S>(named: "foo", literal: "")
|
||||
_ = CommonTableExpression<S>(named: "foo", request: SQLRequest<Void>(""))
|
||||
}
|
||||
|
||||
func testQuery() throws {
|
||||
struct T: TableRecord { }
|
||||
try makeDatabaseQueue().write { db in
|
||||
@@ -11,7 +34,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
|
||||
// Just add a WITH clause: sql + arguments
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(
|
||||
let cte = CommonTableExpression(
|
||||
named: "cte",
|
||||
sql: "SELECT ?",
|
||||
arguments: ["O'Brien"])
|
||||
@@ -25,7 +48,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
|
||||
// Just add a WITH clause: sql interpolation
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(
|
||||
let cte = CommonTableExpression(
|
||||
named: "cte",
|
||||
literal: "SELECT \("O'Brien")")
|
||||
let request = T.all()
|
||||
@@ -39,7 +62,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
// Just add a WITH clause: query interface request
|
||||
do {
|
||||
let cteRequest = T.all()
|
||||
let cte = CommonTableExpression<Void>(named: "cte", request: cteRequest)
|
||||
let cte = CommonTableExpression(named: "cte", request: cteRequest)
|
||||
let request = T.all()
|
||||
.with(cte)
|
||||
try assertEqualSQL(db, request, """
|
||||
@@ -51,7 +74,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
// Just add a WITH clause: sql request
|
||||
do {
|
||||
let cteRequest: SQLRequest<Int> = "SELECT \("O'Brien")"
|
||||
let cte = CommonTableExpression<Void>(named: "cte", request: cteRequest)
|
||||
let cte = CommonTableExpression(named: "cte", request: cteRequest)
|
||||
let request = T.all()
|
||||
.with(cte)
|
||||
try assertEqualSQL(db, request, """
|
||||
@@ -62,7 +85,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
|
||||
// Include query interface request as a CTE
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(named: "cte", request: T.all())
|
||||
let cte = CommonTableExpression(named: "cte", request: T.all())
|
||||
let request = T.all()
|
||||
.with(cte)
|
||||
.including(optional: T.association(to: cte, on: { (left, right) in left["id"] > right["id"] }))
|
||||
@@ -76,7 +99,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
|
||||
// Include SQL request as a CTE
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(
|
||||
let cte = CommonTableExpression(
|
||||
named: "cte",
|
||||
literal: "SELECT 1 as id")
|
||||
let request = T.all()
|
||||
@@ -92,7 +115,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
|
||||
// Include a filtered SQL request as a CTE
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(
|
||||
let cte = CommonTableExpression(
|
||||
named: "cte",
|
||||
literal: "SELECT 1 AS a")
|
||||
let request = T.all()
|
||||
@@ -108,7 +131,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
|
||||
// Include SQL request as a CTE (empty columns)
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(
|
||||
let cte = CommonTableExpression(
|
||||
named: "cte",
|
||||
columns: [],
|
||||
literal: "SELECT 1 AS id")
|
||||
@@ -125,7 +148,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
|
||||
// Include SQL request as a CTE (custom column name)
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(
|
||||
let cte = CommonTableExpression(
|
||||
named: "cte",
|
||||
columns: ["id", "a"],
|
||||
literal: "SELECT 1, 2")
|
||||
@@ -142,7 +165,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
|
||||
// Include SQL request as a CTE (empty ON clause)
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(
|
||||
let cte = CommonTableExpression(
|
||||
named: "cte",
|
||||
literal: "SELECT \("O'Brien")")
|
||||
let request = T.all()
|
||||
@@ -158,7 +181,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
|
||||
// Join query interface request as a CTE
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(named: "cte", request: T.all())
|
||||
let cte = CommonTableExpression(named: "cte", request: T.all())
|
||||
let request = T.all()
|
||||
.with(cte)
|
||||
.joining(required: T.association(to: cte, on: { (left, right) in left["id"] > right["id"] }))
|
||||
@@ -172,7 +195,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
|
||||
// Include filtered CTE
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(named: "cte", request: T.all())
|
||||
let cte = CommonTableExpression(named: "cte", request: T.all())
|
||||
let request = T.all()
|
||||
.with(cte)
|
||||
.including(required: T.association(to: cte).filter(Column("id") > 0))
|
||||
@@ -186,7 +209,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
|
||||
// Include ordered CTE
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(named: "cte", request: T.all())
|
||||
let cte = CommonTableExpression(named: "cte", request: T.all())
|
||||
let request = T.all()
|
||||
.with(cte)
|
||||
.including(required: T.association(to: cte).order(Column("id")))
|
||||
@@ -201,7 +224,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
|
||||
// Aliased CTE
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(named: "cte", request: T.all())
|
||||
let cte = CommonTableExpression(named: "cte", request: T.all())
|
||||
let alias = TableAlias()
|
||||
let request = T.all()
|
||||
.with(cte)
|
||||
@@ -218,7 +241,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
|
||||
// Include one CTE twice with same key and condition
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(named: "cte", request: T.all())
|
||||
let cte = CommonTableExpression(named: "cte", request: T.all())
|
||||
let request = T.all()
|
||||
.with(cte)
|
||||
.including(required: T.association(to: cte, on: { (left, right) in left["id"] > right["id"] }))
|
||||
@@ -233,7 +256,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
|
||||
// Include one CTE twice with same key but different condition (last condition wins)
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(named: "cte", request: T.all())
|
||||
let cte = CommonTableExpression(named: "cte", request: T.all())
|
||||
let request = T.all()
|
||||
.with(cte)
|
||||
.including(required: T.association(to: cte, on: { (left, right) in left["id"] > right["id"] }))
|
||||
@@ -248,7 +271,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
|
||||
// Include one CTE twice with different keys
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(named: "cte", request: T.all())
|
||||
let cte = CommonTableExpression(named: "cte", request: T.all())
|
||||
let request = T.all()
|
||||
.with(cte)
|
||||
.including(required: T.association(to: cte, on: { (left, right) in left["id"] > right["id"] }).forKey("a"))
|
||||
@@ -291,7 +314,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
|
||||
// Use CTE as a subquery
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(named: "cte", request: T.all())
|
||||
let cte = CommonTableExpression(named: "cte", request: T.all())
|
||||
let request = T.all()
|
||||
.with(cte)
|
||||
.annotated(with: cte.all())
|
||||
@@ -303,7 +326,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
|
||||
// Use CTE as a collection
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(named: "cte", request: T.all())
|
||||
let cte = CommonTableExpression(named: "cte", request: T.all())
|
||||
let request = T.all()
|
||||
.with(cte)
|
||||
.filter(cte.contains(Column("id")))
|
||||
@@ -317,7 +340,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
|
||||
// Use filtered CTE as a subquery
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(named: "cte", request: T.all())
|
||||
let cte = CommonTableExpression(named: "cte", request: T.all())
|
||||
let request = T.all()
|
||||
.with(cte)
|
||||
.annotated(with: cte.all().filter(Column("id") > 1))
|
||||
@@ -330,7 +353,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
|
||||
// Select from a CTE
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(named: "cte", request: T.all())
|
||||
let cte = CommonTableExpression(named: "cte", request: T.all())
|
||||
let request = cte.all().with(cte)
|
||||
try assertEqualSQL(db, request, """
|
||||
WITH "cte" AS (SELECT * FROM "t") \
|
||||
@@ -343,7 +366,8 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
func testFetchFromCTE() throws {
|
||||
try makeDatabaseQueue().read { db in
|
||||
do {
|
||||
let answer = CommonTableExpression<Row>(
|
||||
// Default row decoder is Row
|
||||
let answer = CommonTableExpression(
|
||||
named: "answer",
|
||||
sql: "SELECT 42 AS value")
|
||||
let row = try answer.all().with(answer).fetchOne(db)
|
||||
@@ -372,7 +396,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("score", .integer)
|
||||
}
|
||||
let answer = CommonTableExpression<Void>(
|
||||
let answer = CommonTableExpression(
|
||||
named: "answer",
|
||||
sql: "SELECT 42 AS value")
|
||||
let request = Player
|
||||
@@ -430,7 +454,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
.annotated(with: max(Column("date")))
|
||||
.group(Column("chatID"))
|
||||
|
||||
let latestPostCTE = CommonTableExpression<Void>(
|
||||
let latestPostCTE = CommonTableExpression(
|
||||
named: "latestPost",
|
||||
request: latestPostRequest)
|
||||
|
||||
@@ -490,7 +514,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
func testInterpolation() throws {
|
||||
try makeDatabaseQueue().read { db in
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(
|
||||
let cte = CommonTableExpression(
|
||||
named: "cte",
|
||||
literal: "SELECT \("O'Brien")")
|
||||
let request: SQLRequest<Void> = """
|
||||
@@ -503,7 +527,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
""")
|
||||
}
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(
|
||||
let cte = CommonTableExpression(
|
||||
named: "cte",
|
||||
literal: "SELECT \("O'Brien")")
|
||||
let request: SQLRequest<Void> = """
|
||||
@@ -516,7 +540,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
""")
|
||||
}
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(
|
||||
let cte = CommonTableExpression(
|
||||
named: "cte",
|
||||
columns: [],
|
||||
literal: "SELECT \("O'Brien")")
|
||||
@@ -530,7 +554,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
""")
|
||||
}
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(
|
||||
let cte = CommonTableExpression(
|
||||
named: "cte",
|
||||
columns: ["name"],
|
||||
literal: "SELECT \("O'Brien")")
|
||||
@@ -544,7 +568,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
""")
|
||||
}
|
||||
do {
|
||||
let cte = CommonTableExpression<Void>(
|
||||
let cte = CommonTableExpression(
|
||||
named: "cte",
|
||||
columns: ["name", "score"],
|
||||
literal: "SELECT \("O'Brien"), 12")
|
||||
@@ -567,7 +591,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
struct T: Encodable, PersistableRecord { }
|
||||
let cte = CommonTableExpression<Void>(named: "cte", sql: "SELECT 1")
|
||||
let cte = CommonTableExpression(named: "cte", sql: "SELECT 1")
|
||||
|
||||
try T.with(cte).updateAll(db, Column("a").set(to: cte.all()))
|
||||
XCTAssertEqual(lastSQLQuery, """
|
||||
@@ -583,7 +607,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
struct T: Encodable, PersistableRecord { }
|
||||
let cte = CommonTableExpression<Void>(named: "cte", sql: "SELECT 1")
|
||||
let cte = CommonTableExpression(named: "cte", sql: "SELECT 1")
|
||||
|
||||
try T.with(cte)
|
||||
.filter(cte.contains(Column("a")))
|
||||
|
||||
@@ -114,10 +114,18 @@ private class UserFetchableRecord2 : FetchableRecord {
|
||||
// MARK: - StatementColumnConvertible
|
||||
|
||||
private struct UserStatementColumnConvertible1 : StatementColumnConvertible {
|
||||
init?(sqliteStatement: SQLiteStatement, index: Int32) { }
|
||||
}
|
||||
|
||||
private struct UserStatementColumnConvertible2 : StatementColumnConvertible {
|
||||
init(sqliteStatement: SQLiteStatement, index: Int32) { }
|
||||
}
|
||||
|
||||
private class UserStatementColumnConvertible2 : StatementColumnConvertible {
|
||||
private class UserStatementColumnConvertible3 : StatementColumnConvertible {
|
||||
required init?(sqliteStatement: SQLiteStatement, index: Int32) { }
|
||||
}
|
||||
|
||||
private class UserStatementColumnConvertible4 : StatementColumnConvertible {
|
||||
required init(sqliteStatement: SQLiteStatement, index: Int32) { }
|
||||
}
|
||||
|
||||
|
||||
@@ -11,55 +11,85 @@ class DataMemoryTests: GRDBTestCase {
|
||||
// https://forums.swift.org/t/swift-5-how-to-test-data-bytesnocopydeallocator/20299/2?u=gwendal.roue
|
||||
let data = Data(repeating: 0xaa, count: 15)
|
||||
|
||||
let rows = try Row.fetchCursor(db, sql: "SELECT ?", arguments: [data])
|
||||
while let row = try rows.next() {
|
||||
let blobPointer = sqlite3_column_blob(row.sqliteStatement, 0)
|
||||
|
||||
do {
|
||||
// This data should be copied:
|
||||
let copiedData: Data = row[0]
|
||||
XCTAssertEqual(copiedData, data)
|
||||
copiedData.withUnsafeBytes {
|
||||
XCTAssertNotEqual($0.baseAddress, blobPointer)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
// This data should not be copied
|
||||
let nonCopiedData = row.dataNoCopy(atIndex: 0)!
|
||||
XCTAssertEqual(nonCopiedData, data)
|
||||
nonCopiedData.withUnsafeBytes {
|
||||
XCTAssertEqual($0.baseAddress, blobPointer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let row = try Row.fetchOne(db, sql: "SELECT ?", arguments: [data])!
|
||||
let dbValue = row.first!.1 // TODO: think about exposing a (column:,databaseValue:) tuple
|
||||
switch dbValue.storage {
|
||||
case .blob(let data):
|
||||
data.withUnsafeBytes { buffer in
|
||||
do {
|
||||
let rows = try Row.fetchCursor(db, sql: "SELECT ?", arguments: [data])
|
||||
while let row = try rows.next() {
|
||||
let blobPointer = sqlite3_column_blob(row.sqliteStatement, 0)
|
||||
|
||||
do {
|
||||
// This data should not be copied:
|
||||
let nonCopiedData: Data = row[0]
|
||||
XCTAssertEqual(nonCopiedData, data)
|
||||
nonCopiedData.withUnsafeBytes { nonCopiedBuffer in
|
||||
XCTAssertEqual(nonCopiedBuffer.baseAddress, buffer.baseAddress
|
||||
)
|
||||
// This data should be copied:
|
||||
let copiedData: Data = row[0]
|
||||
XCTAssertEqual(copiedData, data)
|
||||
copiedData.withUnsafeBytes {
|
||||
XCTAssertNotEqual($0.baseAddress, blobPointer)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
// This data should not be copied:
|
||||
// This data should not be copied
|
||||
let nonCopiedData = row.dataNoCopy(atIndex: 0)!
|
||||
XCTAssertEqual(nonCopiedData, data)
|
||||
nonCopiedData.withUnsafeBytes { nonCopiedBuffer in
|
||||
XCTAssertEqual(nonCopiedBuffer.baseAddress, buffer.baseAddress)
|
||||
nonCopiedData.withUnsafeBytes {
|
||||
XCTAssertEqual($0.baseAddress, blobPointer)
|
||||
}
|
||||
}
|
||||
}
|
||||
default:
|
||||
XCTFail("Not a blob")
|
||||
}
|
||||
|
||||
do {
|
||||
let adapter = ScopeAdapter(["nested": SuffixRowAdapter(fromIndex: 0)])
|
||||
let rows = try Row.fetchCursor(db, sql: "SELECT ?", arguments: [data], adapter: adapter)
|
||||
while let row = try rows.next() {
|
||||
let blobPointer = sqlite3_column_blob(row.unadapted.sqliteStatement, 0)
|
||||
let nestedRow = row.scopes["nested"]!
|
||||
|
||||
do {
|
||||
// This data should be copied:
|
||||
let copiedData: Data = nestedRow[0]
|
||||
XCTAssertEqual(copiedData, data)
|
||||
copiedData.withUnsafeBytes {
|
||||
XCTAssertNotEqual($0.baseAddress, blobPointer)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
// This data should not be copied
|
||||
let nonCopiedData = nestedRow.dataNoCopy(atIndex: 0)!
|
||||
XCTAssertEqual(nonCopiedData, data)
|
||||
nonCopiedData.withUnsafeBytes {
|
||||
XCTAssertEqual($0.baseAddress, blobPointer)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let row = try Row.fetchOne(db, sql: "SELECT ?", arguments: [data])!
|
||||
let dbValue = row.first!.1 // TODO: think about exposing a (column:,databaseValue:) tuple
|
||||
switch dbValue.storage {
|
||||
case .blob(let data):
|
||||
data.withUnsafeBytes { buffer in
|
||||
do {
|
||||
// This data should not be copied:
|
||||
let nonCopiedData: Data = row[0]
|
||||
XCTAssertEqual(nonCopiedData, data)
|
||||
nonCopiedData.withUnsafeBytes { nonCopiedBuffer in
|
||||
XCTAssertEqual(nonCopiedBuffer.baseAddress, buffer.baseAddress)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
// This data should not be copied:
|
||||
let nonCopiedData = row.dataNoCopy(atIndex: 0)!
|
||||
XCTAssertEqual(nonCopiedData, data)
|
||||
nonCopiedData.withUnsafeBytes { nonCopiedBuffer in
|
||||
XCTAssertEqual(nonCopiedBuffer.baseAddress, buffer.baseAddress)
|
||||
}
|
||||
}
|
||||
}
|
||||
default:
|
||||
XCTFail("Not a blob")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +39,10 @@ private enum StrategyFormatted: StrategyProvider {
|
||||
}
|
||||
|
||||
private enum StrategyCustom: StrategyProvider {
|
||||
static let strategy: DatabaseDateDecodingStrategy = .custom { _ in
|
||||
static let strategy: DatabaseDateDecodingStrategy = .custom { dbValue in
|
||||
if dbValue == "invalid".databaseValue {
|
||||
return nil
|
||||
}
|
||||
return Date(timeIntervalSinceReferenceDate: 123456)
|
||||
}
|
||||
}
|
||||
@@ -187,6 +190,28 @@ extension DatabaseDateDecodingStrategyTests {
|
||||
XCTAssertEqual(calendar.component(.second, from: date), 3)
|
||||
XCTAssertTrue(abs(calendar.component(.nanosecond, from: date) - 4_000_000) < 10) // We actually get 4_000_008. Some precision is lost during the DateComponents -> Date conversion. Not a big deal.
|
||||
}
|
||||
|
||||
// TODO GRDB6: uncomment test
|
||||
// // error
|
||||
// do {
|
||||
// try test(db, strategy: StrategyDeferredToDate.self, databaseValue: "Yesterday") { date in
|
||||
// XCTFail("Unexpected Date")
|
||||
// }
|
||||
// } catch let error as RowDecodingError {
|
||||
// switch error {
|
||||
// case .valueMismatch:
|
||||
// XCTAssertEqual(error.description, """
|
||||
// could not decode Date from database value "Yesterday" - \
|
||||
// column: "date", \
|
||||
// column index: 0, \
|
||||
// row: [date:"Yesterday"], \
|
||||
// sql: `SELECT ? AS date`, \
|
||||
// arguments: ["Yesterday"]
|
||||
// """)
|
||||
// default:
|
||||
// XCTFail("Unexpected Error")
|
||||
// }
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -208,6 +233,30 @@ extension DatabaseDateDecodingStrategyTests {
|
||||
try test(db, strategy: StrategyTimeIntervalSinceReferenceDate.self, databaseValue: 123.456) { date in
|
||||
XCTAssertEqual(date, Date(timeIntervalSinceReferenceDate: 123.456))
|
||||
}
|
||||
|
||||
// TODO GRDB6: uncomment test
|
||||
// // error
|
||||
// do {
|
||||
// try test(db, strategy: StrategyTimeIntervalSinceReferenceDate.self, databaseValue: "Yesterday") { date in
|
||||
// // Decoding from SQLite statement works:
|
||||
// // "Yesterday" is decoded as 0.
|
||||
// XCTAssertEqual(date, Date(timeIntervalSinceReferenceDate: 0))
|
||||
// }
|
||||
// } catch let error as RowDecodingError {
|
||||
// // Decoding from DatabaseValue does not work:
|
||||
// // "Yesterday" is not decoded as 0.
|
||||
// switch error {
|
||||
// case .valueMismatch:
|
||||
// XCTAssertEqual(error.description, """
|
||||
// could not decode Date from database value "Yesterday" - \
|
||||
// column: "date", \
|
||||
// column index: 0, \
|
||||
// row: [date:"Yesterday"]
|
||||
// """)
|
||||
// default:
|
||||
// XCTFail("Unexpected Error")
|
||||
// }
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -229,6 +278,30 @@ extension DatabaseDateDecodingStrategyTests {
|
||||
try test(db, strategy: StrategyTimeIntervalSince1970.self, databaseValue: 123.456) { date in
|
||||
XCTAssertEqual(date, Date(timeIntervalSince1970: 123.456))
|
||||
}
|
||||
|
||||
// TODO GRDB6: uncomment test
|
||||
// // error
|
||||
// do {
|
||||
// try test(db, strategy: StrategyTimeIntervalSince1970.self, databaseValue: "Yesterday") { date in
|
||||
// // Decoding from SQLite statement works:
|
||||
// // "Yesterday" is decoded as 0.
|
||||
// XCTAssertEqual(date, Date(timeIntervalSince1970: 0))
|
||||
// }
|
||||
// } catch let error as RowDecodingError {
|
||||
// // Decoding from DatabaseValue does not work:
|
||||
// // "Yesterday" is not decoded as 0.
|
||||
// switch error {
|
||||
// case .valueMismatch:
|
||||
// XCTAssertEqual(error.description, """
|
||||
// could not decode Date from database value "Yesterday" - \
|
||||
// column: "date", \
|
||||
// column index: 0, \
|
||||
// row: [date:"Yesterday"]
|
||||
// """)
|
||||
// default:
|
||||
// XCTFail("Unexpected Error")
|
||||
// }
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -260,6 +333,30 @@ extension DatabaseDateDecodingStrategyTests {
|
||||
try test(db, strategy: StrategyMillisecondsSince1970.self, databaseValue: 123456.789) { date in
|
||||
XCTAssertEqual(date, Date(timeIntervalSince1970: 123456.789 / 1000))
|
||||
}
|
||||
|
||||
// TODO GRDB6: uncomment test
|
||||
// // error
|
||||
// do {
|
||||
// try test(db, strategy: StrategyMillisecondsSince1970.self, databaseValue: "Yesterday") { date in
|
||||
// // Decoding from SQLite statement works:
|
||||
// // "Yesterday" is decoded as 0.
|
||||
// XCTAssertEqual(date, Date(timeIntervalSince1970: 0))
|
||||
// }
|
||||
// } catch let error as RowDecodingError {
|
||||
// // Decoding from DatabaseValue does not work:
|
||||
// // "Yesterday" is not decoded as 0.
|
||||
// switch error {
|
||||
// case .valueMismatch:
|
||||
// XCTAssertEqual(error.description, """
|
||||
// could not decode Date from database value "Yesterday" - \
|
||||
// column: "date", \
|
||||
// column index: 0, \
|
||||
// row: [date:"Yesterday"]
|
||||
// """)
|
||||
// default:
|
||||
// XCTFail("Unexpected Error")
|
||||
// }
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -287,6 +384,28 @@ extension DatabaseDateDecodingStrategyTests {
|
||||
XCTAssertEqual(calendar.component(.second, from: date), 7)
|
||||
XCTAssertEqual(calendar.component(.nanosecond, from: date), 0)
|
||||
}
|
||||
|
||||
// TODO GRDB6: uncomment test
|
||||
// // error
|
||||
// do {
|
||||
// try test(db, strategy: StrategyIso8601.self, databaseValue: "Yesterday") { date in
|
||||
// XCTFail("Unexpected Date")
|
||||
// }
|
||||
// } catch let error as RowDecodingError {
|
||||
// switch error {
|
||||
// case .valueMismatch:
|
||||
// XCTAssertEqual(error.description, """
|
||||
// could not decode Date from database value "Yesterday" - \
|
||||
// column: "date", \
|
||||
// column index: 0, \
|
||||
// row: [date:"Yesterday"], \
|
||||
// sql: `SELECT ? AS date`, \
|
||||
// arguments: ["Yesterday"]
|
||||
// """)
|
||||
// default:
|
||||
// XCTFail("Unexpected Error")
|
||||
// }
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -313,6 +432,28 @@ extension DatabaseDateDecodingStrategyTests {
|
||||
XCTAssertEqual(calendar.component(.second, from: date), 55)
|
||||
XCTAssertEqual(calendar.component(.nanosecond, from: date), 0)
|
||||
}
|
||||
|
||||
// TODO GRDB6: uncomment test
|
||||
// // error
|
||||
// do {
|
||||
// try test(db, strategy: StrategyFormatted.self, databaseValue: "Yesterday") { date in
|
||||
// XCTFail("Unexpected Date")
|
||||
// }
|
||||
// } catch let error as RowDecodingError {
|
||||
// switch error {
|
||||
// case .valueMismatch:
|
||||
// XCTAssertEqual(error.description, """
|
||||
// could not decode Date from database value "Yesterday" - \
|
||||
// column: "date", \
|
||||
// column index: 0, \
|
||||
// row: [date:"Yesterday"], \
|
||||
// sql: `SELECT ? AS date`, \
|
||||
// arguments: ["Yesterday"]
|
||||
// """)
|
||||
// default:
|
||||
// XCTFail("Unexpected Error")
|
||||
// }
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -326,9 +467,31 @@ extension DatabaseDateDecodingStrategyTests {
|
||||
try testNullDecoding(db, strategy: StrategyCustom.self)
|
||||
|
||||
// Date
|
||||
try test(db, strategy: StrategyCustom.self, databaseValue: "whatever") { date in
|
||||
try test(db, strategy: StrategyCustom.self, databaseValue: "valid") { date in
|
||||
XCTAssertEqual(date, Date(timeIntervalSinceReferenceDate: 123456))
|
||||
}
|
||||
|
||||
// TODO GRDB6: uncomment test
|
||||
// // error
|
||||
// do {
|
||||
// try test(db, strategy: StrategyCustom.self, databaseValue: "invalid") { date in
|
||||
// XCTFail("Unexpected Date")
|
||||
// }
|
||||
// } catch let error as RowDecodingError {
|
||||
// switch error {
|
||||
// case .valueMismatch:
|
||||
// XCTAssertEqual(error.description, """
|
||||
// could not decode Date from database value "invalid" - \
|
||||
// column: "date", \
|
||||
// column index: 0, \
|
||||
// row: [date:"invalid"], \
|
||||
// sql: `SELECT ? AS date`, \
|
||||
// arguments: ["invalid"]
|
||||
// """)
|
||||
// default:
|
||||
// XCTFail("Unexpected Error")
|
||||
// }
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -135,7 +135,7 @@ class DatabaseQueueTests: GRDBTestCase {
|
||||
try dbQueue.write { _ in
|
||||
dispatchPrecondition(condition: .onQueue(targetQueue))
|
||||
}
|
||||
dbQueue.read { _ in
|
||||
try dbQueue.read { _ in
|
||||
dispatchPrecondition(condition: .onQueue(targetQueue))
|
||||
}
|
||||
}
|
||||
@@ -185,7 +185,7 @@ class DatabaseQueueTests: GRDBTestCase {
|
||||
try dbQueue.write { _ in
|
||||
dispatchPrecondition(condition: .onQueue(targetQueue))
|
||||
}
|
||||
dbQueue.read { _ in
|
||||
try dbQueue.read { _ in
|
||||
dispatchPrecondition(condition: .onQueue(targetQueue))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -378,7 +378,7 @@ class DatabaseTests : GRDBTestCase {
|
||||
|
||||
func testMaximumStatementArgumentCount() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let count = dbQueue.read { $0.maximumStatementArgumentCount }
|
||||
let count = try dbQueue.read { $0.maximumStatementArgumentCount }
|
||||
// 999 should be safe: https://www.sqlite.org/limits.html
|
||||
XCTAssertGreaterThanOrEqual(count, 999)
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -6,40 +6,40 @@ class DatabaseValueConvertibleEscapingTests: GRDBTestCase {
|
||||
|
||||
func testNull() throws {
|
||||
try makeDatabaseQueue().inDatabase { db in
|
||||
try XCTAssertEqual(DatabaseValue.null.quotedSQL(db), "NULL")
|
||||
try XCTAssertEqual(DatabaseValue.null.sqlExpression.quotedSQL(db), "NULL")
|
||||
}
|
||||
}
|
||||
|
||||
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'''")
|
||||
try XCTAssertEqual("".sqlExpression.quotedSQL(db), "''")
|
||||
try XCTAssertEqual("foo".sqlExpression.quotedSQL(db), "'foo'")
|
||||
try XCTAssertEqual("\"foo\"".sqlExpression.quotedSQL(db), #"'"foo"'"#)
|
||||
try XCTAssertEqual("'foo'".sqlExpression.quotedSQL(db), "'''foo'''")
|
||||
}
|
||||
}
|
||||
|
||||
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")
|
||||
try XCTAssertEqual(0.sqlExpression.quotedSQL(db), "0")
|
||||
try XCTAssertEqual(Int64.min.sqlExpression.quotedSQL(db), "-9223372036854775808")
|
||||
try XCTAssertEqual(Int64.max.sqlExpression.quotedSQL(db), "9223372036854775807")
|
||||
}
|
||||
}
|
||||
|
||||
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")
|
||||
try XCTAssertEqual(0.0.sqlExpression.quotedSQL(db), "0.0")
|
||||
try XCTAssertEqual(1.0.sqlExpression.quotedSQL(db), "1.0")
|
||||
try XCTAssertEqual((-1.0).sqlExpression.quotedSQL(db), "-1.0")
|
||||
try XCTAssertEqual(1.5.sqlExpression.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'")
|
||||
try XCTAssertEqual(Data().sqlExpression.quotedSQL(db), "X''")
|
||||
try XCTAssertEqual("foo".data(using: .utf8)!.sqlExpression.quotedSQL(db), "X'666F6F'")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -44,10 +44,19 @@ class FetchRequestTests: GRDBTestCase {
|
||||
t.column("id", .integer).primaryKey()
|
||||
}
|
||||
|
||||
let derivedExpression = request.contains(0)
|
||||
let sqlRequest: SQLRequest<Row> = "SELECT \(derivedExpression)"
|
||||
let statement = try sqlRequest.makePreparedRequest(db, forSingleResult: false).statement
|
||||
XCTAssertEqual(statement.sql, "SELECT ? IN (SELECT id FROM table1)")
|
||||
do {
|
||||
let derivedExpression = request.contains(0)
|
||||
let sqlRequest: SQLRequest<Row> = "SELECT \(derivedExpression)"
|
||||
let statement = try sqlRequest.makePreparedRequest(db, forSingleResult: false).statement
|
||||
XCTAssertEqual(statement.sql, "SELECT ? IN (SELECT id FROM table1)")
|
||||
}
|
||||
|
||||
do {
|
||||
let derivedExpression = request.contains("arthur".databaseValue.collating(.nocase))
|
||||
let sqlRequest: SQLRequest<Row> = "SELECT \(derivedExpression)"
|
||||
let statement = try sqlRequest.makePreparedRequest(db, forSingleResult: false).statement
|
||||
XCTAssertEqual(statement.sql, "SELECT (? COLLATE NOCASE) IN (SELECT id FROM table1)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -165,25 +165,43 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
|
||||
func testContainsWithCollation() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
try dbQueue.read { db in
|
||||
// Reminder of the SQLite behavior
|
||||
// https://sqlite.org/datatype3.html#assigning_collating_sequences_from_sql
|
||||
// > If an explicit collating sequence is required on an IN operator
|
||||
// > it should be applied to the left operand, like this:
|
||||
// > "x COLLATE nocase IN (y,z, ...)".
|
||||
try XCTAssertFalse(Bool.fetchOne(db, sql: "SELECT 'arthur' IN ('ARTHUR') COLLATE NOCASE")!)
|
||||
try XCTAssertTrue(Bool.fetchOne(db, sql: "SELECT 'arthur' COLLATE NOCASE IN ('ARTHUR')")!)
|
||||
}
|
||||
|
||||
// Array.contains(): IN operator
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(["arthur", "barbara"].contains(Col.name.collating(.nocase)))),
|
||||
"SELECT * FROM \"readers\" WHERE \"name\" IN ('arthur', 'barbara') COLLATE NOCASE")
|
||||
"SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')")
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(!["arthur", "barbara"].contains(Col.name.collating(.nocase)))),
|
||||
"SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) NOT IN ('arthur', 'barbara')")
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter((["arthur", "barbara"] as [SQLExpressible]).contains(Col.name.collating(.nocase)))),
|
||||
"SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')")
|
||||
|
||||
// Sequence.contains(): IN operator
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(AnySequence(["arthur", "barbara"]).contains(Col.name.collating(.nocase)))),
|
||||
"SELECT * FROM \"readers\" WHERE \"name\" IN ('arthur', 'barbara') COLLATE NOCASE")
|
||||
"SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')")
|
||||
|
||||
// Sequence.contains(): = operator
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(AnySequence([Col.name]).contains(Col.name.collating(.nocase)))),
|
||||
"SELECT * FROM \"readers\" WHERE \"name\" = \"name\" COLLATE NOCASE")
|
||||
"SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) = \"name\"")
|
||||
|
||||
// Sequence.contains(): false
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(EmptyCollection<Int>().contains(Col.name.collating(.nocase)))),
|
||||
"SELECT * FROM \"readers\" WHERE 0 COLLATE NOCASE")
|
||||
"SELECT * FROM \"readers\" WHERE 0")
|
||||
|
||||
// ClosedInterval: BETWEEN operator
|
||||
let closedInterval = "A"..."z"
|
||||
@@ -1361,19 +1379,19 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
|
||||
CREATE TABLE compoundPrimaryKeyRecord (a INTEGER, b INTEGER, PRIMARY KEY (a, b));
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, IntegerPrimaryKeyRecord.select(SQLExpressionFastPrimaryKey()), """
|
||||
try assertEqualSQL(db, IntegerPrimaryKeyRecord.select(SQLExpression.fastPrimaryKey), """
|
||||
SELECT "id" FROM "integerPrimaryKeyRecord"
|
||||
""")
|
||||
try assertEqualSQL(db, UUIDRecord.select(SQLExpressionFastPrimaryKey()), """
|
||||
try assertEqualSQL(db, UUIDRecord.select(SQLExpression.fastPrimaryKey), """
|
||||
SELECT "rowid" FROM "uuidRecord"
|
||||
""")
|
||||
try assertEqualSQL(db, UUIDRecordWithoutRowID.select(SQLExpressionFastPrimaryKey()), """
|
||||
try assertEqualSQL(db, UUIDRecordWithoutRowID.select(SQLExpression.fastPrimaryKey), """
|
||||
SELECT "uuid" FROM "uuidRecordWithoutRowID"
|
||||
""")
|
||||
try assertEqualSQL(db, RowIDRecord.select(SQLExpressionFastPrimaryKey()), """
|
||||
try assertEqualSQL(db, RowIDRecord.select(SQLExpression.fastPrimaryKey), """
|
||||
SELECT "rowid" FROM "rowIDRecord"
|
||||
""")
|
||||
try assertEqualSQL(db, CompoundPrimaryKeyRecord.select(SQLExpressionFastPrimaryKey()), """
|
||||
try assertEqualSQL(db, CompoundPrimaryKeyRecord.select(SQLExpression.fastPrimaryKey), """
|
||||
SELECT "rowid" FROM "compoundPrimaryKeyRecord"
|
||||
""")
|
||||
}
|
||||
|
||||
@@ -33,6 +33,8 @@ extension Color32 : SQLExpressible { }
|
||||
extension Color64 : SQLExpressible { }
|
||||
extension Color : SQLExpressible { }
|
||||
extension Grape : SQLExpressible { }
|
||||
extension Wrapper: SQLOrderingTerm where RawValue: SQLOrderingTerm { }
|
||||
extension Wrapper: SQLSelectable where RawValue: SQLSelectable { }
|
||||
extension Wrapper: SQLExpressible where RawValue: SQLExpressible { }
|
||||
|
||||
extension Color32 : DatabaseValueConvertible { }
|
||||
|
||||
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user