mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-01 04:38:44 +00:00
Compare commits
333
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af13c91744 | ||
|
|
b5dea2164f | ||
|
|
148897ad73 | ||
|
|
095bfde072 | ||
|
|
fabdb73785 | ||
|
|
f30f970cf2 | ||
|
|
1c2499528c | ||
|
|
766e731bf9 | ||
|
|
b9496a01e1 | ||
|
|
1554c80fdb | ||
|
|
61ee7cc3f7 | ||
|
|
0f481e7867 | ||
|
|
ed3397176a | ||
|
|
5f4c64ceda | ||
|
|
e5a810105a | ||
|
|
a46b2ad127 | ||
|
|
3ccac4098a | ||
|
|
a4e8bbe2da | ||
|
|
52bc7eb7c6 | ||
|
|
e8802fb010 | ||
|
|
885f43dbad | ||
|
|
5dfab017e5 | ||
|
|
35d6ac0041 | ||
|
|
eae64b587a | ||
|
|
fb6ae07722 | ||
|
|
491e17f62e | ||
|
|
f521002e74 | ||
|
|
bbaee79618 | ||
|
|
64951c84d7 | ||
|
|
5996b64469 | ||
|
|
65b2fecdfc | ||
|
|
232086e50e | ||
|
|
8f7feda27c | ||
|
|
6aa6c4d4b5 | ||
|
|
afc360cf78 | ||
|
|
5673d73738 | ||
|
|
4a894f2b43 | ||
|
|
83cd6d1469 | ||
|
|
0b2e5d836f | ||
|
|
b9576aedbe | ||
|
|
2f549d21bf | ||
|
|
4d6958b52a | ||
|
|
588b2677e7 | ||
|
|
66e52eea40 | ||
|
|
975cbaa7e8 | ||
|
|
9e265f7ebc | ||
|
|
37522f3766 | ||
|
|
4980beda69 | ||
|
|
69b9c7331f | ||
|
|
28375f5c1a | ||
|
|
e019617a50 | ||
|
|
8ff0c456dc | ||
|
|
744b0c5661 | ||
|
|
c6003143c4 | ||
|
|
b0545bcfb0 | ||
|
|
3976feb6ab | ||
|
|
002399ff1a | ||
|
|
cdc21531fc | ||
|
|
7afe011b69 | ||
|
|
12809f5891 | ||
|
|
7fd51f440a | ||
|
|
4f0d3b31e1 | ||
|
|
36039fb6a3 | ||
|
|
e66e59cd21 | ||
|
|
a3279c9f63 | ||
|
|
5ed64ea8f8 | ||
|
|
62763ece52 | ||
|
|
c50f698eae | ||
|
|
31e2b01c10 | ||
|
|
7fd786955c | ||
|
|
af13283aa7 | ||
|
|
6a5d196c2d | ||
|
|
6959ac80b5 | ||
|
|
0c4e483e9e | ||
|
|
f9c162b657 | ||
|
|
c0f537c5e6 | ||
|
|
8895d590a0 | ||
|
|
a44c518e31 | ||
|
|
0571d9b3b8 | ||
|
|
c0a3e61253 | ||
|
|
c02901b335 | ||
|
|
ee2d6d8074 | ||
|
|
b51dc81c3a | ||
|
|
47199ed72b | ||
|
|
28bddb04fa | ||
|
|
c34615ced3 | ||
|
|
a5ffc52dbe | ||
|
|
fd61a5f1ea | ||
|
|
0f70e9d9c9 | ||
|
|
d4f1102976 | ||
|
|
1591948c10 | ||
|
|
43de1c24a7 | ||
|
|
481f6e93e5 | ||
|
|
6887441264 | ||
|
|
e017eddf4f | ||
|
|
53d75c37aa | ||
|
|
331990ce33 | ||
|
|
63a52acb34 | ||
|
|
6958a10a08 | ||
|
|
5d14b3d6db | ||
|
|
de0709163c | ||
|
|
8c872fccfc | ||
|
|
46867877fd | ||
|
|
622ecda283 | ||
|
|
5f9911ff0d | ||
|
|
eaf830c05c | ||
|
|
064dec5095 | ||
|
|
89521a7288 | ||
|
|
76d4e38cd1 | ||
|
|
c56a56a2f3 | ||
|
|
02d3518194 | ||
|
|
67892d7cdb | ||
|
|
0e091124a2 | ||
|
|
2402185235 | ||
|
|
f406062b81 | ||
|
|
7bf25925c7 | ||
|
|
8dd8a57de3 | ||
|
|
fa8a8f0b87 | ||
|
|
fa2c489ee4 | ||
|
|
2cb0baf88e | ||
|
|
1ab23dfa52 | ||
|
|
bd29585461 | ||
|
|
f1cd6dbae8 | ||
|
|
a91d9b23e0 | ||
|
|
7eb348cb2a | ||
|
|
ab4ae144ac | ||
|
|
09899e9bcf | ||
|
|
2625653532 | ||
|
|
ea26dea687 | ||
|
|
4a17281bd7 | ||
|
|
e9ba3e6ccc | ||
|
|
9692410e7d | ||
|
|
b69dfb1709 | ||
|
|
4307eedbc0 | ||
|
|
521f9e498a | ||
|
|
e7ce5f13e7 | ||
|
|
55c0abef8b | ||
|
|
9489174b98 | ||
|
|
b086b99821 | ||
|
|
984dea156c | ||
|
|
1297a781fd | ||
|
|
c4f9ddd688 | ||
|
|
fcff9b34ba | ||
|
|
914ad1b882 | ||
|
|
b13922b76e | ||
|
|
f6f4839e07 | ||
|
|
c5aeec3385 | ||
|
|
21b22ab3fb | ||
|
|
39eb57fe64 | ||
|
|
bbacfd5ec1 | ||
|
|
7bbec01dec | ||
|
|
969f28945c | ||
|
|
869f6cb3b3 | ||
|
|
607e53b04e | ||
|
|
051fdb37b6 | ||
|
|
db963cbbb2 | ||
|
|
13120063e0 | ||
|
|
be02e920d2 | ||
|
|
901b9c6fe6 | ||
|
|
64f5e6bdca | ||
|
|
178727fd5b | ||
|
|
791a8ed41b | ||
|
|
d9083a7bf5 | ||
|
|
e355af3584 | ||
|
|
5b39494125 | ||
|
|
4f709e8e4f | ||
|
|
63448fb0bc | ||
|
|
989a0e82eb | ||
|
|
8ba05a011d | ||
|
|
659e6a53bb | ||
|
|
8a7ab17349 | ||
|
|
3113e20f69 | ||
|
|
e44dc8486a | ||
|
|
21a2206443 | ||
|
|
f38c2ff754 | ||
|
|
8ad880e20d | ||
|
|
50cec3fce7 | ||
|
|
c9c652dddc | ||
|
|
edde38837e | ||
|
|
c4443eead8 | ||
|
|
7c023d5c1f | ||
|
|
99a06f1c05 | ||
|
|
0c2b5318bf | ||
|
|
c47316a846 | ||
|
|
529b042b8a | ||
|
|
5aa1184e68 | ||
|
|
a912c5cbe5 | ||
|
|
3753bd8d6d | ||
|
|
a6f7d9ba86 | ||
|
|
fdc47d7158 | ||
|
|
8aa4807f9b | ||
|
|
339fbdf1ce | ||
|
|
ada972d78d | ||
|
|
085c8f5953 | ||
|
|
1f4db99a37 | ||
|
|
076813826f | ||
|
|
fcb6049381 | ||
|
|
4c88d792f0 | ||
|
|
9d64a32814 | ||
|
|
77db650464 | ||
|
|
0e8a42aedc | ||
|
|
8ad096ae35 | ||
|
|
ac436a2770 | ||
|
|
0133ff9056 | ||
|
|
178fb8688a | ||
|
|
0b5f7e960b | ||
|
|
ae3c491661 | ||
|
|
8548d7a727 | ||
|
|
daab7aef2c | ||
|
|
ba9b4db197 | ||
|
|
cab795a4a9 | ||
|
|
b331a715ef | ||
|
|
48e214b4b3 | ||
|
|
65beb24d41 | ||
|
|
e1c7150714 | ||
|
|
cc93f43ee4 | ||
|
|
33174fce8e | ||
|
|
cb8611587c | ||
|
|
6e7555514a | ||
|
|
8b1efb2c80 | ||
|
|
8388486289 | ||
|
|
c3dcd7636e | ||
|
|
464b77bdcd | ||
|
|
fe437fb7e3 | ||
|
|
1a2a6898eb | ||
|
|
de2a37fb89 | ||
|
|
1d5604815d | ||
|
|
4de5059373 | ||
|
|
850040c51e | ||
|
|
eb0983facd | ||
|
|
9e974a4c96 | ||
|
|
609fcf6a6d | ||
|
|
5e61d38272 | ||
|
|
cdbca5d215 | ||
|
|
9bda5fc41b | ||
|
|
04d35381a6 | ||
|
|
1f27e724c9 | ||
|
|
b22afd7f17 | ||
|
|
ed3d1e1ac4 | ||
|
|
4521e6b37d | ||
|
|
42718db49d | ||
|
|
e08df854dd | ||
|
|
f4b7d99aab | ||
|
|
4dd8042894 | ||
|
|
4583bbfa90 | ||
|
|
a655974eb0 | ||
|
|
d4fc1d9566 | ||
|
|
f9b554d00a | ||
|
|
6b733cfc0a | ||
|
|
f0aec27095 | ||
|
|
092b0d0e44 | ||
|
|
d2a22ddd97 | ||
|
|
9c6ff6a1c0 | ||
|
|
a4dca3390a | ||
|
|
ea6a052b73 | ||
|
|
f49fab0cff | ||
|
|
37faf0a1fd | ||
|
|
4b5a6b503a | ||
|
|
2a85b1230b | ||
|
|
3eb17fdbb7 | ||
|
|
5400217bb6 | ||
|
|
71083a5586 | ||
|
|
37279dfad2 | ||
|
|
8be0976bd1 | ||
|
|
7623a96034 | ||
|
|
424df6dee3 | ||
|
|
48b6faa45e | ||
|
|
bac7b6b0e5 | ||
|
|
174766925a | ||
|
|
9d5cb15380 | ||
|
|
284ebbd3ef | ||
|
|
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
+13
-13
@@ -26,6 +26,19 @@ git:
|
||||
|
||||
jobs:
|
||||
include:
|
||||
|
||||
###########################################
|
||||
## Test GRDB Xcode 11.4
|
||||
|
||||
- name: "Test GRDB Xcode 11.4 - GRDBiOS iOS maxTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
script: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
|
||||
- name: "Test GRDB Xcode 11.4 - GRDBiOS iOS minTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
###########################################
|
||||
## Test GRDB Xcode 12.2
|
||||
@@ -146,16 +159,3 @@ jobs:
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
script: make test_install_customSQLite
|
||||
|
||||
###########################################
|
||||
## Test GRDB Xcode 11.4
|
||||
|
||||
- name: "Test GRDB Xcode 11.4 - GRDBiOS iOS maxTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
script: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
|
||||
- name: "Test GRDB Xcode 11.4 - GRDBiOS iOS minTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
@@ -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.
|
||||
|
||||
+173
@@ -7,6 +7,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 5.x Releases
|
||||
|
||||
- `5.8.x` Releases - [5.8.0](#580)
|
||||
- `5.7.x` Releases - [5.7.0](#570) | [5.7.1](#571) | [5.7.2](#572) | [5.7.3](#573) | [5.7.4](#574)
|
||||
- `5.6.x` Releases - [5.6.0](#560)
|
||||
- `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)
|
||||
@@ -68,6 +73,174 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
- [0.110.0](#01100), ...
|
||||
|
||||
---
|
||||
|
||||
## 5.8.0
|
||||
|
||||
Released May 16, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.7.4...v5.8.0)
|
||||
|
||||
- **New**: Support for the `ESCAPE` clause with the `LIKE` operator.
|
||||
- **New**: You can now define an `SQLRequest` without any generic qualifier (which defaults to `Row`):
|
||||
|
||||
```swift
|
||||
let request = SQLRequest("SELECT ...")
|
||||
```
|
||||
- **New**: [#967](https://github.com/groue/GRDB.swift/pull/967) by [@steipete](https://github.com/steipete): Make SelectStatement conform to CustomStringConvertible
|
||||
- **Fixed**: The `DerivableRequest.limit(_:offset:)` method was ill-designed, and removed from the documentation. It is unfortunately impossible to deprecate it without triggering warnings on the legit use cases (on `QueryInterfaceRequest`).
|
||||
- **Fixed**: [#973](https://github.com/groue/GRDB.swift/pull/973): Restore access to attached databases from record types
|
||||
- **Fixed**: [#974](https://github.com/groue/GRDB.swift/pull/974): Provide access to included associations when root table is not selected
|
||||
- **Documentation Update**: A new [Query Interface Organization](Documentation/QueryInterfaceOrganization.md) document reveals the relationship between the various components of the GRDB query builder.
|
||||
|
||||
## 5.7.4
|
||||
|
||||
Released April 11, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.7.3...v5.7.4)
|
||||
|
||||
- **New**: [#953](https://github.com/groue/GRDB.swift/pull/953): Refactor the SwiftUI demo app
|
||||
- **Fixed**: [#955](https://github.com/groue/GRDB.swift/pull/955) by [@steipete](https://github.com/steipete): Robustness of @Query in the SwiftUI demo app
|
||||
- **Fixed**: [#956](https://github.com/groue/GRDB.swift/pull/956): Fix case-sensitivity of region-based database observation
|
||||
- **New**: [#958](https://github.com/groue/GRDB.swift/pull/958) by [@chrisballinger](https://github.com/chrisballinger): Always add userInfo to databaseJSONDecoder and databaseJSONEncoder
|
||||
- **New**: [#960](https://github.com/groue/GRDB.swift/pull/960) by [@MartinP7r](https://github.com/MartinP7r): Add tests for userInfo being applied to database encoder/decoder
|
||||
|
||||
|
||||
## 5.7.3
|
||||
|
||||
Released April 5, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.7.2...v5.7.3)
|
||||
|
||||
- **Fixed**: [#950](https://github.com/groue/GRDB.swift/pull/950) by [@MartinP7r](https://github.com/MartinP7r): Fix memory consumption when encoding JSON columns
|
||||
- **Fixed**: [#951](https://github.com/groue/GRDB.swift/pull/951) by [@alexwlchan](https://github.com/alexwlchan): Fix documentation typo
|
||||
- **Fixed**: [#952](https://github.com/groue/GRDB.swift/pull/952) by [@holsety](https://github.com/holsety): Fix documentation typo
|
||||
- **Documentation Update**: [#953](https://github.com/groue/GRDB.swift/pull/953): Refactor the SwiftUI demo app
|
||||
|
||||
#### 5.7.2
|
||||
|
||||
- **Fixed**: Really fix breaking change and restore `SQLLiteral` as a deprecated alias for `SQL`.
|
||||
|
||||
#### 5.7.1
|
||||
|
||||
- **Fixed**: Fix breaking change and restore `SQLLiteral` as a deprecated alias for `SQL`.
|
||||
|
||||
## 5.7.0
|
||||
|
||||
Released March 28, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.6.0...v5.7.0)
|
||||
|
||||
- **New**: [#947](https://github.com/groue/GRDB.swift/pull/947) by [@chrisballinger](https://github.com/chrisballinger): Allow access to Encoder from KeyedEncodingContainer
|
||||
|
||||
- **New**: Record types that adopt the standard [Identifiable](https://developer.apple.com/documentation/swift/identifiable) protocol have gained type-safe methods that deal with the primary key. For example:
|
||||
|
||||
```swift
|
||||
let player = try Player.fetchOne(db, id: 42)
|
||||
try Player.deleteAll(db, ids: [1, 2, 3])
|
||||
```
|
||||
|
||||
See the new [Identifiable Records](README.md#identifiable-records) documentation chapter for more information.
|
||||
|
||||
- **New**: `SQLLiteral` has more use cases than initialy expected, and is renamed `SQL`.
|
||||
|
||||
- **New**: [`SQL` literal](Documentation/SQLInterpolation.md#sql-literal) can now be directly used as an expression, an ordering term, or a selection item.:
|
||||
|
||||
```swift
|
||||
let name = "O'Brien"
|
||||
let request = Player
|
||||
.select(SQL("id, score"), ...)
|
||||
.filter(SQL("name = \(name)") && ...)
|
||||
.order(SQL("score DESC"), ...)
|
||||
```
|
||||
|
||||
- **New**: Table creation DSL now supports columns and constraints defined with raw SQL String or [SQL literal](Documentation/SQLInterpolation.md#sql-literal):
|
||||
|
||||
```swift
|
||||
try db.create(table: "player") do { t in
|
||||
t.column(sql: "id INTEGER PRIMARY KEY AUTOINCREMENT")
|
||||
t.column(literal: "name TEXT DEFAULT \("Anonymous")")
|
||||
t.constraint(sql: "CHECK (LENGTH(name) > 0)")
|
||||
t.constraint(literal: "CHECK (LENGTH(name) <= \(100))")
|
||||
}
|
||||
```
|
||||
|
||||
- **New**: Prepared statements can profit from [SQL Interpolation](Documentation/SQLInterpolation.md):
|
||||
|
||||
```swift
|
||||
let updateStatement = try db.makeUpdateStatement(literal: "INSERT ...")
|
||||
let selectStatement = try db.makeSelectStatement(literal: "SELECT ...")
|
||||
// ~~~~~~~
|
||||
```
|
||||
|
||||
- **New**: [DatabaseMigrator](Documentation/Migrations.md#asynchronous-migrations) can now asynchronously migrate a database. A Combine publisher is also available.
|
||||
|
||||
- **New**: Added support for the `EXISTS` and `NOT EXISTS` subquery operators. See the updated [SQL Operators](README.md#sql-operators) documentation.
|
||||
|
||||
- **New**: `Foundation.Decimal` can now be stored in the database, and all Foundation number types can be decoded from decimal numbers stored as strings. See the [NSNumber, NSDecimalNumber, and Decimal](README.md#nsnumber-nsdecimalnumber-and-decimal) chapter for details.
|
||||
|
||||
## 5.6.0
|
||||
|
||||
Released March 12, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.5.0...v5.6.0)
|
||||
|
||||
- **Fixed**: [#933](https://github.com/groue/GRDB.swift/pull/933): Fix DatabaseMigrator.eraseDatabaseOnSchemaChange in the context of shared databases
|
||||
|
||||
- **Fixed**: [#934](https://github.com/groue/GRDB.swift/pull/934): Fix a crash in the ValueObservation publisher
|
||||
|
||||
- **New**: [#936](https://github.com/groue/GRDB.swift/pull/936): Complete Associations and the DerivableRequest Protocol
|
||||
|
||||
- **New**: Database cursors can feed more standard Swift collections: `Array(cursor, minimumCapacity: ...)`, `Dictionary(uniqueKeysWithValues: cursor)`, etc (see [Cursors](README.md#cursors)).
|
||||
|
||||
- **Documentation update**: The [Associations Guide](Documentation/AssociationsBasics.md) has gained a new [Further Refinements to Associations](Documentation/AssociationsBasics.md#further-refinements-to-associations) chapter which shows the new association methods brought by [#936](https://github.com/groue/GRDB.swift/pull/936).
|
||||
|
||||
- **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has an updated [Define Record Requests](Documentation/GoodPracticesForDesigningRecordTypes.md#define-record-requests) chapter, now that the `DerivableRequest` protocol has access to `limit`, `distinct`, `group`, `having`, association aggregates, and common table expressions.
|
||||
|
||||
- **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has a new chapter of good practices: [Record Types Hide Intimate Database Details](Documentation/GoodPracticesForDesigningRecordTypes.md#record-types-hide-intimate-database-details).
|
||||
|
||||
- **Documentation update**: A new [Single-Row Tables](Documentation/SingleRowTables.md) guide provides guidance for designing tables that store configuration values, user preferences, and generally some global application state.
|
||||
|
||||
## 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
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ GRDB Associations
|
||||
- [Sorting Associations]
|
||||
- [Ordered Associations]
|
||||
- [Columns Selected by an Association]
|
||||
- [Further Refinements to Associations]
|
||||
- [Table Aliases]
|
||||
- [Refining Association Requests]
|
||||
- [Fetching Values from Associations]
|
||||
@@ -88,7 +89,7 @@ struct BookInfo {
|
||||
|
||||
let books = try Book.fetchAll(db)
|
||||
let bookInfos = books.map { book -> BookInfo in
|
||||
let author = try Author.fetchOne(db, key: book.authorId)
|
||||
let author = try Author.fetchOne(db, id: book.authorId)
|
||||
return BookInfo(book: book, author: author)
|
||||
}
|
||||
```
|
||||
@@ -781,6 +782,7 @@ Fetch requests do not visit the database until you fetch values from them. This
|
||||
- [Sorting Associations]
|
||||
- [Ordered Associations]
|
||||
- [Columns Selected by an Association]
|
||||
- [Further Refinements to Associations]
|
||||
- [Table Aliases]
|
||||
- [Refining Association Requests]
|
||||
|
||||
@@ -855,14 +857,18 @@ Before we describe them in detail, let's see a few requests they can build:
|
||||
let request = Author
|
||||
.including(all: Author.books)
|
||||
|
||||
/// All authors with their awarded books
|
||||
let request = Author
|
||||
.including(all: Author.books.having(Book.awards.isEmpty == false))
|
||||
|
||||
/// All books with their respective author
|
||||
let request = Book
|
||||
.including(required: Book.author)
|
||||
|
||||
/// All books with their respective author, sorted by title
|
||||
let request = Book
|
||||
.order(Column("title"))
|
||||
.including(required: Book.author)
|
||||
.order(Column("title"))
|
||||
|
||||
/// All books written by a French author
|
||||
let request = Book
|
||||
@@ -941,7 +947,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
|
||||
@@ -1044,7 +1064,7 @@ let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
|
||||
|
||||
**You can filter associated records.**
|
||||
|
||||
The `filter(_:)`, `filter(key:)` and `filter(keys:)` methods, that you already know for [filtering simple requests](../README.md#requests), can filter associated records as well:
|
||||
The `filter(_:)`, `filter(id:)`, `filter(ids:)`, `filter(key:)` and `filter(keys:)` methods, that you already know for [filtering simple requests](../README.md#requests), can filter associated records as well:
|
||||
|
||||
```swift
|
||||
// SELECT book.*
|
||||
@@ -1221,7 +1241,6 @@ let teamInfos = try Team
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
|
||||
## Columns Selected by an Association
|
||||
|
||||
By default, associated records include all their columns:
|
||||
@@ -1248,6 +1267,104 @@ let request = Book.including(required: restrictedAuthor)
|
||||
To specify the default selection for all inclusions of a given type, see [Columns Selected by a Request](../README.md#columns-selected-by-a-request).
|
||||
|
||||
|
||||
## Further Refinements to Associations
|
||||
|
||||
Associations support more refinements:
|
||||
|
||||
- `distinct`
|
||||
|
||||
Fetch all authors with the kinds of books they write (novels, poems, plays, etc):
|
||||
|
||||
```swift
|
||||
struct AuthorInfo: Decodable, FetchableRecord {
|
||||
var author: Author
|
||||
var bookKinds: Set<Book.Kind>
|
||||
}
|
||||
|
||||
let distinctBookKinds = Author.books
|
||||
.select(Column("kind"))
|
||||
.distinct()
|
||||
.forKey("bookKinds")
|
||||
|
||||
let authorInfos: [AuthorInfo] = try Author
|
||||
.including(all: distinctBookKinds)
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
- `group`, `having`
|
||||
|
||||
Fetch all authors with the year of their latest book for each kind (novels, poems, plays, etc):
|
||||
|
||||
```swift
|
||||
struct BookKindInfo: Decodable {
|
||||
var kind: Book.Kind
|
||||
var maxYear: Int
|
||||
}
|
||||
|
||||
struct AuthorInfo: Decodable, FetchableRecord {
|
||||
var author: Author
|
||||
var bookKindInfos: [BookKindInfo]
|
||||
}
|
||||
|
||||
let bookKindInfos = Author.books
|
||||
.select(
|
||||
Column("kind"),
|
||||
max(Column("year")).forKey("maxYear"))
|
||||
.group(Column("kind"))
|
||||
.forKey("bookKindInfos")
|
||||
|
||||
let authorInfos: [AuthorInfo] = try Author
|
||||
.including(all: bookKindInfos)
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
- [Association Aggregates]
|
||||
|
||||
Fetch all authors with their awarded books:
|
||||
|
||||
```swift
|
||||
struct AuthorInfo: FetchableRecord, Decodable {
|
||||
var author: Author
|
||||
var awardedBooks: [Book]
|
||||
}
|
||||
|
||||
let awardedBooks = Author.books
|
||||
.having(Book.awards.isEmpty == false)
|
||||
.forKey("awardedBooks")
|
||||
|
||||
let authorInfos: [AuthorInfo] = try Author
|
||||
.including(all: awardedBooks)
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
- [Common Table Expressions]
|
||||
|
||||
Association can use their own CTEs:
|
||||
|
||||
```swift
|
||||
struct AuthorInfo: FetchableRecord, Decodable {
|
||||
var author: Author
|
||||
var specialBooks: [Book]
|
||||
}
|
||||
|
||||
let specialCTE = CommonTableExpression(...)
|
||||
let specialBooks = Author.books
|
||||
.with(specialCTE)
|
||||
... // use the CTE in the book association
|
||||
.forKey("specialBooks")
|
||||
|
||||
let authorInfos = try Author
|
||||
.including(all: specialBooks)
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
> :warning: **Warning**: associations refined with `limit`, `distinct`, `group`, `having`, or association aggregates can only be used with `including(all:)`. You will get a fatal error if you use them with other joining methods: `including(required:)`, etc.
|
||||
|
||||
|
||||
## Table Aliases
|
||||
|
||||
In all examples we have seen so far, all associated records are joined, included, filtered, and sorted independently. We could not filter them on conditions that involve several records, for example.
|
||||
@@ -2433,6 +2550,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
[Choosing Between BelongsTo and HasOne]: #choosing-between-belongsto-and-hasone
|
||||
[Self Joins]: #self-joins
|
||||
[Ordered Associations]: #ordered-associations
|
||||
[Further Refinements to Associations]: #further-refinements-to-associations
|
||||
[The Types of Associations]: #the-types-of-associations
|
||||
[FetchableRecord]: ../README.md#fetchablerecord-protocols
|
||||
[migration]: Migrations.md
|
||||
@@ -2483,4 +2601,5 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[FAQ]: ../README.md#faq-associations
|
||||
[common table expressions]: CommonTableExpressions.md
|
||||
[Common Table Expressions]: CommonTableExpressions.md
|
||||
[Associations to Common Table Expressions]: CommonTableExpressions.md#associations-to-common-table-expressions
|
||||
@@ -46,6 +46,19 @@ let newPlayerCount = dbQueue.writePublisher { db -> Int in
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>Asynchronously migrate the database</strong></summary>
|
||||
|
||||
This publisher migrates a database:
|
||||
|
||||
```swift
|
||||
// DatabasePublishers.Migrate
|
||||
let migrator: DatabaseMigrator = ...
|
||||
let publisher = migrator.migratePublisher(dbQueue)
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>Observe changes in database values</strong></summary>
|
||||
|
||||
@@ -99,11 +112,12 @@ let cancellable = publisher.sink(
|
||||
|
||||
# Asynchronous Database Access
|
||||
|
||||
GRDB provide publishers that perform asynchronous database accesses.
|
||||
GRDB provide publishers that perform asynchronous database accesses:
|
||||
|
||||
- [`readPublisher(receiveOn:value:)`]
|
||||
- [`writePublisher(receiveOn:updates:)`]
|
||||
- [`writePublisher(receiveOn:updates:thenRead:)`]
|
||||
- [`migratePublisher(_:receiveOn:)`]
|
||||
|
||||
|
||||
#### `DatabaseReader.readPublisher(receiveOn:value:)`
|
||||
@@ -125,7 +139,7 @@ When you use a [database pool], reads are generally non-blocking, unless the max
|
||||
|
||||
This publisher can be subscribed from any thread. A new database access starts on every subscription.
|
||||
|
||||
The fetched value is published on the main queue, unless you provide a specific scheduler to the `receiveOn` argument.
|
||||
The fetched value is published on the main queue, unless you provide a specific [scheduler] to the `receiveOn` argument.
|
||||
|
||||
|
||||
#### `DatabaseWriter.writePublisher(receiveOn:updates:)`
|
||||
@@ -321,6 +335,7 @@ See [DatabaseRegionObservation] for more information.
|
||||
[`readPublisher(receiveOn:value:)`]: #databasereaderreadpublisherreceiveonvalue
|
||||
[`writePublisher(receiveOn:updates:)`]: #databasewriterwritepublisherreceiveonupdates
|
||||
[`writePublisher(receiveOn:updates:thenRead:)`]: #databasewriterwritepublisherreceiveonupdatesthenread
|
||||
[`migratePublisher(_:receiveOn:)`]: Migrations.md#asynchronous-migrations
|
||||
[configured]: ../README.md#databasepool-configuration
|
||||
[database pool]: ../README.md#database-pools
|
||||
[database queue]: ../README.md#database-queues
|
||||
|
||||
@@ -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,27 +40,27 @@ 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 request = SQLRequest("SELECT \(name)")
|
||||
let playerNameCTE = CommonTableExpression(
|
||||
named: "playerName",
|
||||
request: requests)
|
||||
request: request)
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
/* Begin PBXBuildFile section */
|
||||
56026CAC25B8A7EF00D1DF3F /* PlayerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */; };
|
||||
56026CAD25B8A7EF00D1DF3F /* AppDatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */; };
|
||||
5671722A261A185300423B6F /* Query.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717229261A185300423B6F /* Query.swift */; };
|
||||
5671723A261B23C800423B6F /* PlayerList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717239261B23C800423B6F /* PlayerList.swift */; };
|
||||
56717252261B334D00423B6F /* PlayerRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717251261B334D00423B6F /* PlayerRequestTests.swift */; };
|
||||
567C3E1A2520B6DE0011F6E9 /* GRDBCombineDemoApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */; };
|
||||
567C3E1E2520B6DF0011F6E9 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */; };
|
||||
567C3E212520B6DF0011F6E9 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */; };
|
||||
@@ -16,15 +19,15 @@
|
||||
567C3E4F2520B70E0011F6E9 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 567C3E3B2520B7000011F6E9 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
|
||||
567C3E5D2520B75C0011F6E9 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E532520B75C0011F6E9 /* Player.swift */; };
|
||||
567C3E5E2520B75C0011F6E9 /* Persistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E542520B75C0011F6E9 /* Persistence.swift */; };
|
||||
567C3E5F2520B75C0011F6E9 /* PlayerListViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E562520B75C0011F6E9 /* PlayerListViewModel.swift */; };
|
||||
567C3E602520B75C0011F6E9 /* PlayerFormViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E572520B75C0011F6E9 /* PlayerFormViewModel.swift */; };
|
||||
567C3E612520B75D0011F6E9 /* PlayerForm.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E592520B75C0011F6E9 /* PlayerForm.swift */; };
|
||||
567C3E622520B75D0011F6E9 /* PlayerList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5A2520B75C0011F6E9 /* PlayerList.swift */; };
|
||||
567C3E632520B75D0011F6E9 /* PlayerCreationSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5B2520B75C0011F6E9 /* PlayerCreationSheet.swift */; };
|
||||
567C3E612520B75D0011F6E9 /* PlayerFormView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E592520B75C0011F6E9 /* PlayerFormView.swift */; };
|
||||
567C3E622520B75D0011F6E9 /* AppView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5A2520B75C0011F6E9 /* AppView.swift */; };
|
||||
567C3E632520B75D0011F6E9 /* PlayerCreationView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */; };
|
||||
567C3E642520B75D0011F6E9 /* PlayerEditionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */; };
|
||||
567C3E662520B7880011F6E9 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E652520B7880011F6E9 /* AppDatabase.swift */; };
|
||||
567C3E792520BB650011F6E9 /* Localizable.stringsdict in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E752520BB650011F6E9 /* Localizable.stringsdict */; };
|
||||
567C3E7A2520BB650011F6E9 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */; };
|
||||
56B6D1092619EC1B003CC455 /* PlayerRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D1082619EC1B003CC455 /* PlayerRequest.swift */; };
|
||||
78E2F9E6261EEC22005D1F7F /* GRDBCombineDemoUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78E2F9E5261EEC22005D1F7F /* GRDBCombineDemoUITests.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
@@ -98,6 +101,13 @@
|
||||
remoteGlobalIDString = 56E5D7C91B4D3FED00430942;
|
||||
remoteInfo = GRDBiOS;
|
||||
};
|
||||
78E2F9E8261EEC22005D1F7F /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 567C3E0E2520B6DE0011F6E9 /* Project object */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 567C3E152520B6DE0011F6E9;
|
||||
remoteInfo = GRDBCombineDemo;
|
||||
};
|
||||
/* End PBXContainerItemProxy section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
@@ -119,6 +129,9 @@
|
||||
56026C9C25B8A7D000D1DF3F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerTests.swift; sourceTree = "<group>"; };
|
||||
56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabaseTests.swift; sourceTree = "<group>"; };
|
||||
56717229261A185300423B6F /* Query.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Query.swift; sourceTree = "<group>"; };
|
||||
56717239261B23C800423B6F /* PlayerList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerList.swift; sourceTree = "<group>"; };
|
||||
56717251261B334D00423B6F /* PlayerRequestTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequestTests.swift; sourceTree = "<group>"; };
|
||||
567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBCombineDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GRDBCombineDemoApp.swift; sourceTree = "<group>"; };
|
||||
567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
|
||||
@@ -127,15 +140,17 @@
|
||||
567C3E292520B7000011F6E9 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = "<group>"; };
|
||||
567C3E532520B75C0011F6E9 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = "<group>"; };
|
||||
567C3E542520B75C0011F6E9 /* Persistence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistence.swift; sourceTree = "<group>"; };
|
||||
567C3E562520B75C0011F6E9 /* PlayerListViewModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerListViewModel.swift; sourceTree = "<group>"; };
|
||||
567C3E572520B75C0011F6E9 /* PlayerFormViewModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerFormViewModel.swift; sourceTree = "<group>"; };
|
||||
567C3E592520B75C0011F6E9 /* PlayerForm.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerForm.swift; sourceTree = "<group>"; };
|
||||
567C3E5A2520B75C0011F6E9 /* PlayerList.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerList.swift; sourceTree = "<group>"; };
|
||||
567C3E5B2520B75C0011F6E9 /* PlayerCreationSheet.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerCreationSheet.swift; sourceTree = "<group>"; };
|
||||
567C3E592520B75C0011F6E9 /* PlayerFormView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerFormView.swift; sourceTree = "<group>"; };
|
||||
567C3E5A2520B75C0011F6E9 /* AppView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppView.swift; sourceTree = "<group>"; };
|
||||
567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerCreationView.swift; sourceTree = "<group>"; };
|
||||
567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionView.swift; sourceTree = "<group>"; };
|
||||
567C3E652520B7880011F6E9 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
|
||||
567C3E762520BB650011F6E9 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.stringsdict; name = en; path = en.lproj/Localizable.stringsdict; sourceTree = "<group>"; };
|
||||
567C3E782520BB650011F6E9 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
|
||||
56B6D1082619EC1B003CC455 /* PlayerRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequest.swift; sourceTree = "<group>"; };
|
||||
78E2F9E3261EEC22005D1F7F /* GRDBCombineDemoUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCombineDemoUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
78E2F9E5261EEC22005D1F7F /* GRDBCombineDemoUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GRDBCombineDemoUITests.swift; sourceTree = "<group>"; };
|
||||
78E2F9E7261EEC22005D1F7F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
@@ -154,6 +169,13 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
78E2F9E0261EEC22005D1F7F /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
@@ -162,6 +184,7 @@
|
||||
children = (
|
||||
56026C9C25B8A7D000D1DF3F /* Info.plist */,
|
||||
56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */,
|
||||
56717251261B334D00423B6F /* PlayerRequestTests.swift */,
|
||||
56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */,
|
||||
);
|
||||
path = GRDBCombineDemoTests;
|
||||
@@ -191,6 +214,7 @@
|
||||
567C3E292520B7000011F6E9 /* GRDB.xcodeproj */,
|
||||
567C3E182520B6DE0011F6E9 /* GRDBCombineDemo */,
|
||||
56026C9925B8A7D000D1DF3F /* GRDBCombineDemoTests */,
|
||||
78E2F9E4261EEC22005D1F7F /* GRDBCombineDemoUITests */,
|
||||
567C3E172520B6DE0011F6E9 /* Products */,
|
||||
567C3E4D2520B70E0011F6E9 /* Frameworks */,
|
||||
);
|
||||
@@ -201,6 +225,7 @@
|
||||
children = (
|
||||
567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */,
|
||||
56026C9825B8A7D000D1DF3F /* GRDBCombineDemoTests.xctest */,
|
||||
78E2F9E3261EEC22005D1F7F /* GRDBCombineDemoUITests.xctest */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
@@ -212,10 +237,11 @@
|
||||
567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */,
|
||||
567C3E542520B75C0011F6E9 /* Persistence.swift */,
|
||||
567C3E532520B75C0011F6E9 /* Player.swift */,
|
||||
56B6D1082619EC1B003CC455 /* PlayerRequest.swift */,
|
||||
56717229261A185300423B6F /* Query.swift */,
|
||||
567C3E1F2520B6DF0011F6E9 /* Preview Content */,
|
||||
56185BC125B8047D00B9C30F /* Resources */,
|
||||
56185BC225B8048B00B9C30F /* Support */,
|
||||
567C3E552520B75C0011F6E9 /* ViewModels */,
|
||||
567C3E582520B75C0011F6E9 /* Views */,
|
||||
);
|
||||
path = GRDBCombineDemo;
|
||||
@@ -251,26 +277,27 @@
|
||||
name = Frameworks;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
567C3E552520B75C0011F6E9 /* ViewModels */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567C3E562520B75C0011F6E9 /* PlayerListViewModel.swift */,
|
||||
567C3E572520B75C0011F6E9 /* PlayerFormViewModel.swift */,
|
||||
);
|
||||
path = ViewModels;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
567C3E582520B75C0011F6E9 /* Views */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567C3E592520B75C0011F6E9 /* PlayerForm.swift */,
|
||||
567C3E5A2520B75C0011F6E9 /* PlayerList.swift */,
|
||||
567C3E5B2520B75C0011F6E9 /* PlayerCreationSheet.swift */,
|
||||
567C3E5A2520B75C0011F6E9 /* AppView.swift */,
|
||||
567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */,
|
||||
567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */,
|
||||
567C3E592520B75C0011F6E9 /* PlayerFormView.swift */,
|
||||
56717239261B23C800423B6F /* PlayerList.swift */,
|
||||
);
|
||||
path = Views;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
78E2F9E4261EEC22005D1F7F /* GRDBCombineDemoUITests */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
78E2F9E5261EEC22005D1F7F /* GRDBCombineDemoUITests.swift */,
|
||||
78E2F9E7261EEC22005D1F7F /* Info.plist */,
|
||||
);
|
||||
path = GRDBCombineDemoUITests;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
@@ -311,13 +338,31 @@
|
||||
productReference = 567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */;
|
||||
productType = "com.apple.product-type.application";
|
||||
};
|
||||
78E2F9E2261EEC22005D1F7F /* GRDBCombineDemoUITests */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 78E2F9F3261EEC22005D1F7F /* Build configuration list for PBXNativeTarget "GRDBCombineDemoUITests" */;
|
||||
buildPhases = (
|
||||
78E2F9DF261EEC22005D1F7F /* Sources */,
|
||||
78E2F9E0261EEC22005D1F7F /* Frameworks */,
|
||||
78E2F9E1261EEC22005D1F7F /* Resources */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
78E2F9E9261EEC22005D1F7F /* PBXTargetDependency */,
|
||||
);
|
||||
name = GRDBCombineDemoUITests;
|
||||
productName = GRDBCombineDemoUITests;
|
||||
productReference = 78E2F9E3261EEC22005D1F7F /* GRDBCombineDemoUITests.xctest */;
|
||||
productType = "com.apple.product-type.bundle.ui-testing";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
567C3E0E2520B6DE0011F6E9 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastSwiftUpdateCheck = 1230;
|
||||
LastSwiftUpdateCheck = 1250;
|
||||
LastUpgradeCheck = 1200;
|
||||
TargetAttributes = {
|
||||
56026C9725B8A7D000D1DF3F = {
|
||||
@@ -327,6 +372,10 @@
|
||||
567C3E152520B6DE0011F6E9 = {
|
||||
CreatedOnToolsVersion = 12.0;
|
||||
};
|
||||
78E2F9E2261EEC22005D1F7F = {
|
||||
CreatedOnToolsVersion = 12.5;
|
||||
TestTargetID = 567C3E152520B6DE0011F6E9;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = 567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBCombineDemo" */;
|
||||
@@ -350,6 +399,7 @@
|
||||
targets = (
|
||||
567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */,
|
||||
56026C9725B8A7D000D1DF3F /* GRDBCombineDemoTests */,
|
||||
78E2F9E2261EEC22005D1F7F /* GRDBCombineDemoUITests */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
@@ -432,6 +482,13 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
78E2F9E1261EEC22005D1F7F /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
@@ -441,6 +498,7 @@
|
||||
files = (
|
||||
56026CAC25B8A7EF00D1DF3F /* PlayerTests.swift in Sources */,
|
||||
56026CAD25B8A7EF00D1DF3F /* AppDatabaseTests.swift in Sources */,
|
||||
56717252261B334D00423B6F /* PlayerRequestTests.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -448,16 +506,25 @@
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
5671722A261A185300423B6F /* Query.swift in Sources */,
|
||||
567C3E5E2520B75C0011F6E9 /* Persistence.swift in Sources */,
|
||||
567C3E5D2520B75C0011F6E9 /* Player.swift in Sources */,
|
||||
567C3E612520B75D0011F6E9 /* PlayerForm.swift in Sources */,
|
||||
567C3E632520B75D0011F6E9 /* PlayerCreationSheet.swift in Sources */,
|
||||
56B6D1092619EC1B003CC455 /* PlayerRequest.swift in Sources */,
|
||||
5671723A261B23C800423B6F /* PlayerList.swift in Sources */,
|
||||
567C3E612520B75D0011F6E9 /* PlayerFormView.swift in Sources */,
|
||||
567C3E632520B75D0011F6E9 /* PlayerCreationView.swift in Sources */,
|
||||
567C3E662520B7880011F6E9 /* AppDatabase.swift in Sources */,
|
||||
567C3E622520B75D0011F6E9 /* PlayerList.swift in Sources */,
|
||||
567C3E622520B75D0011F6E9 /* AppView.swift in Sources */,
|
||||
567C3E642520B75D0011F6E9 /* PlayerEditionView.swift in Sources */,
|
||||
567C3E1A2520B6DE0011F6E9 /* GRDBCombineDemoApp.swift in Sources */,
|
||||
567C3E5F2520B75C0011F6E9 /* PlayerListViewModel.swift in Sources */,
|
||||
567C3E602520B75C0011F6E9 /* PlayerFormViewModel.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
78E2F9DF261EEC22005D1F7F /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
78E2F9E6261EEC22005D1F7F /* GRDBCombineDemoUITests.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -474,6 +541,11 @@
|
||||
name = GRDBiOS;
|
||||
targetProxy = 567C3E512520B71C0011F6E9 /* PBXContainerItemProxy */;
|
||||
};
|
||||
78E2F9E9261EEC22005D1F7F /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
target = 567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */;
|
||||
targetProxy = 78E2F9E8261EEC22005D1F7F /* PBXContainerItemProxy */;
|
||||
};
|
||||
/* End PBXTargetDependency section */
|
||||
|
||||
/* Begin PBXVariantGroup section */
|
||||
@@ -659,7 +731,7 @@
|
||||
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_ASSET_PATHS = "\"GRDBCombineDemo/Preview Content\"";
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
DEVELOPMENT_TEAM = "";
|
||||
ENABLE_PREVIEWS = YES;
|
||||
INFOPLIST_FILE = GRDBCombineDemo/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
|
||||
@@ -681,7 +753,7 @@
|
||||
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_ASSET_PATHS = "\"GRDBCombineDemo/Preview Content\"";
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
DEVELOPMENT_TEAM = "";
|
||||
ENABLE_PREVIEWS = YES;
|
||||
INFOPLIST_FILE = GRDBCombineDemo/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
|
||||
@@ -696,6 +768,44 @@
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
78E2F9EA261EEC22005D1F7F /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_TEAM = "";
|
||||
INFOPLIST_FILE = GRDBCombineDemoUITests/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.groue.GRDBCombineDemoUITests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_TARGET_NAME = GRDBCombineDemo;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
78E2F9EB261EEC22005D1F7F /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_TEAM = "";
|
||||
INFOPLIST_FILE = GRDBCombineDemoUITests/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.groue.GRDBCombineDemoUITests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_TARGET_NAME = GRDBCombineDemo;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
@@ -726,6 +836,15 @@
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
78E2F9F3261EEC22005D1F7F /* Build configuration list for PBXNativeTarget "GRDBCombineDemoUITests" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
78E2F9EA261EEC22005D1F7F /* Debug */,
|
||||
78E2F9EB261EEC22005D1F7F /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
};
|
||||
rootObject = 567C3E0E2520B6DE0011F6E9 /* Project object */;
|
||||
|
||||
+10
@@ -38,6 +38,16 @@
|
||||
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "78E2F9E2261EEC22005D1F7F"
|
||||
BuildableName = "GRDBCombineDemoUITests.xctest"
|
||||
BlueprintName = "GRDBCombineDemoUITests"
|
||||
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
|
||||
@@ -54,9 +54,25 @@ struct AppDatabase {
|
||||
// MARK: - Database Access: Writes
|
||||
|
||||
extension AppDatabase {
|
||||
/// A validation error that prevents some players from being saved into
|
||||
/// the database.
|
||||
enum ValidationError: LocalizedError {
|
||||
case missingName
|
||||
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .missingName:
|
||||
return "Please provide a name"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Saves (inserts or updates) a player. When the method returns, the
|
||||
/// player is present in the database, and its id is not nil.
|
||||
func savePlayer(_ player: inout Player) throws {
|
||||
if player.name.isEmpty {
|
||||
throw ValidationError.missingName
|
||||
}
|
||||
try dbWriter.write { db in
|
||||
try player.save(db)
|
||||
}
|
||||
@@ -65,7 +81,7 @@ extension AppDatabase {
|
||||
/// Delete the specified players
|
||||
func deletePlayers(ids: [Int64]) throws {
|
||||
try dbWriter.write { db in
|
||||
_ = try Player.deleteAll(db, keys: ids)
|
||||
_ = try Player.deleteAll(db, ids: ids)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,6 +128,25 @@ extension AppDatabase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static let uiTestPlayers = [
|
||||
Player(id: nil, name: "Arthur", score: 5),
|
||||
Player(id: nil, name: "Barbara", score: 6),
|
||||
Player(id: nil, name: "Craig", score: 8),
|
||||
Player(id: nil, name: "David", score: 4),
|
||||
Player(id: nil, name: "Elena", score: 1),
|
||||
Player(id: nil, name: "Frederik", score: 2),
|
||||
Player(id: nil, name: "Gilbert", score: 7),
|
||||
Player(id: nil, name: "Henriette", score: 3)]
|
||||
|
||||
func createPlayersForUITests() throws {
|
||||
try dbWriter.write { db in
|
||||
try AppDatabase.uiTestPlayers.forEach { player in
|
||||
var mutablePlayer = player
|
||||
try mutablePlayer.save(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Support for `createRandomPlayersIfEmpty()` and `refreshPlayers()`.
|
||||
private func createRandomPlayers(_ db: Database) throws {
|
||||
@@ -125,19 +160,8 @@ extension AppDatabase {
|
||||
// MARK: - Database Access: Reads
|
||||
|
||||
extension AppDatabase {
|
||||
/// Returns a publisher that tracks changes in players ordered by name
|
||||
func playersOrderedByNamePublisher() -> AnyPublisher<[Player], Error> {
|
||||
ValueObservation
|
||||
.tracking(Player.all().orderedByName().fetchAll)
|
||||
.publisher(in: dbWriter, scheduling: .immediate)
|
||||
.eraseToAnyPublisher()
|
||||
}
|
||||
|
||||
/// Returns a publisher that tracks changes in players ordered by score
|
||||
func playersOrderedByScorePublisher() -> AnyPublisher<[Player], Error> {
|
||||
ValueObservation
|
||||
.tracking(Player.all().orderedByScore().fetchAll)
|
||||
.publisher(in: dbWriter, scheduling: .immediate)
|
||||
.eraseToAnyPublisher()
|
||||
/// Provides a read-only access to the database
|
||||
var databaseReader: DatabaseReader {
|
||||
dbWriter
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,23 @@
|
||||
import GRDB
|
||||
import SwiftUI
|
||||
|
||||
@main
|
||||
struct GRDBCombineDemoApp: App {
|
||||
let appDatabase = AppDatabase.shared
|
||||
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
PlayerList(viewModel: PlayerListViewModel(database: appDatabase))
|
||||
AppView().environment(\.appDatabase, AppDatabase.shared)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Let SwiftUI views access the database through the SwiftUI environment
|
||||
private struct AppDatabaseKey: EnvironmentKey {
|
||||
static let defaultValue: AppDatabase? = nil
|
||||
}
|
||||
|
||||
extension EnvironmentValues {
|
||||
var appDatabase: AppDatabase? {
|
||||
get { self[AppDatabaseKey.self] }
|
||||
set { self[AppDatabaseKey.self] = newValue }
|
||||
}
|
||||
}
|
||||
@@ -6,13 +6,20 @@ extension AppDatabase {
|
||||
|
||||
private static func makeShared() -> AppDatabase {
|
||||
do {
|
||||
// Create a folder for storing the SQLite database, as well as
|
||||
// Pick 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)
|
||||
|
||||
// Support for tests: delete the database if requested
|
||||
if CommandLine.arguments.contains("-reset") {
|
||||
try? fileManager.removeItem(at: folderURL)
|
||||
}
|
||||
|
||||
// Create the database folder if needed
|
||||
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
|
||||
|
||||
// Connect to a database on disk
|
||||
@@ -23,8 +30,14 @@ extension AppDatabase {
|
||||
// Create the AppDatabase
|
||||
let appDatabase = try AppDatabase(dbPool)
|
||||
|
||||
// Populate the database if it is empty, for better demo purpose.
|
||||
try appDatabase.createRandomPlayersIfEmpty()
|
||||
// Prepare the database with test fixtures if requested
|
||||
if CommandLine.arguments.contains("-fixedTestData") {
|
||||
try appDatabase.createPlayersForUITests()
|
||||
} else {
|
||||
// Otherwise, populate the database if it is empty, for better
|
||||
// demo purpose.
|
||||
try appDatabase.createRandomPlayersIfEmpty()
|
||||
}
|
||||
|
||||
return appDatabase
|
||||
} catch {
|
||||
|
||||
@@ -2,7 +2,8 @@ import GRDB
|
||||
|
||||
/// The Player struct.
|
||||
///
|
||||
/// Identifiable conformance supports SwiftUI list animations.
|
||||
/// Identifiable conformance supports SwiftUI list animations, and type-safe
|
||||
/// GRDB primary key methods.
|
||||
/// Equatable conformance supports tests.
|
||||
struct Player: Identifiable, Equatable {
|
||||
/// The player id.
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import GRDB
|
||||
|
||||
/// A player request defines how to feed the player list
|
||||
struct PlayerRequest {
|
||||
enum Ordering {
|
||||
case byScore
|
||||
case byName
|
||||
}
|
||||
|
||||
var ordering: Ordering
|
||||
}
|
||||
|
||||
/// Make `PlayerRequest` able to be used with the `@Query` property wrapper.
|
||||
extension PlayerRequest: Queryable {
|
||||
static var defaultValue: [Player] { [] }
|
||||
|
||||
func fetchValue(_ db: Database) throws -> [Player] {
|
||||
switch ordering {
|
||||
case .byScore: return try Player.all().orderedByScore().fetchAll(db)
|
||||
case .byName: return try Player.all().orderedByName().fetchAll(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
//
|
||||
// Query.swift
|
||||
//
|
||||
// A property wrapper inspired from
|
||||
// https://davedelong.com/blog/2021/04/03/core-data-and-swiftui/
|
||||
//
|
||||
|
||||
import Combine
|
||||
import GRDB
|
||||
import SwiftUI
|
||||
|
||||
/// The protocol that feeds the `@Query` property wrapper.
|
||||
protocol Queryable: Equatable {
|
||||
/// The type of the fetched value
|
||||
associatedtype Value
|
||||
|
||||
/// The default value, used whenever the database is not available
|
||||
static var defaultValue: Value { get }
|
||||
|
||||
/// Fetches the database value
|
||||
func fetchValue(_ db: Database) throws -> Value
|
||||
}
|
||||
|
||||
/// The property wrapper that observes a database query
|
||||
@propertyWrapper
|
||||
struct Query<Query: Queryable>: DynamicProperty {
|
||||
/// The database reader that makes it possible to observe the database
|
||||
@Environment(\.appDatabase?.databaseReader) private var databaseReader: DatabaseReader?
|
||||
@StateObject private var core = Core()
|
||||
private var baseQuery: Query
|
||||
|
||||
/// The fetched value
|
||||
var wrappedValue: Query.Value {
|
||||
core.value ?? Query.defaultValue
|
||||
}
|
||||
|
||||
/// A binding to the query, that lets your views modify it.
|
||||
///
|
||||
/// This is how the demo app changes the player ordering.
|
||||
var projectedValue: Binding<Query> {
|
||||
Binding(
|
||||
get: { core.query ?? baseQuery },
|
||||
set: {
|
||||
core.usesBaseQuery = false
|
||||
core.query = $0
|
||||
})
|
||||
}
|
||||
|
||||
init(_ query: Query) {
|
||||
baseQuery = query
|
||||
}
|
||||
|
||||
func update() {
|
||||
guard let databaseReader = databaseReader else {
|
||||
fatalError("Attempting to use @Query without any database in the environment")
|
||||
}
|
||||
// Feed core with necessary information, and make sure tracking has started
|
||||
if core.usesBaseQuery { core.query = baseQuery }
|
||||
core.startTrackingIfNecessary(in: databaseReader)
|
||||
}
|
||||
|
||||
private class Core: ObservableObject {
|
||||
private(set) var value: Query.Value?
|
||||
var databaseReader: DatabaseReader?
|
||||
var usesBaseQuery = true
|
||||
var query: Query? {
|
||||
willSet {
|
||||
if query != newValue {
|
||||
// Stop tracking, and tell SwiftUI about the update
|
||||
objectWillChange.send()
|
||||
cancellable = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
private var cancellable: AnyCancellable?
|
||||
|
||||
init() { }
|
||||
|
||||
func startTrackingIfNecessary(in databaseReader: DatabaseReader) {
|
||||
if databaseReader !== self.databaseReader {
|
||||
// Database has changed. Stop tracking.
|
||||
self.databaseReader = databaseReader
|
||||
cancellable = nil
|
||||
}
|
||||
|
||||
guard let query = query else {
|
||||
// No query set
|
||||
return
|
||||
}
|
||||
|
||||
guard cancellable == nil else {
|
||||
// Already tracking
|
||||
return
|
||||
}
|
||||
|
||||
cancellable = ValueObservation
|
||||
.tracking(query.fetchValue)
|
||||
.publisher(
|
||||
in: databaseReader,
|
||||
scheduling: .immediate)
|
||||
.sink(
|
||||
receiveCompletion: { _ in
|
||||
// Ignore errors
|
||||
},
|
||||
receiveValue: { [weak self] value in
|
||||
guard let self = self else { return }
|
||||
// Tell SwiftUI about the new value
|
||||
self.objectWillChange.send()
|
||||
self.value = value
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
-67
@@ -1,67 +0,0 @@
|
||||
import Combine
|
||||
import Foundation
|
||||
|
||||
/// The view model that validates and saves an edited player into the database.
|
||||
///
|
||||
/// It feeds `PlayerForm`, `PlayerCreationSheet` and `PlayerEditionView`.
|
||||
final class PlayerFormViewModel: ObservableObject {
|
||||
/// A validation error that prevents the player from being saved into
|
||||
/// the database.
|
||||
enum ValidationError: LocalizedError {
|
||||
case missingName
|
||||
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .missingName:
|
||||
return "Please give a name to this player."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Published var name: String = ""
|
||||
@Published var score: String = ""
|
||||
|
||||
private let database: AppDatabase
|
||||
private var player: Player
|
||||
|
||||
init(database: AppDatabase, player: Player) {
|
||||
self.database = database
|
||||
self.player = player
|
||||
updateViewFromPlayer()
|
||||
}
|
||||
|
||||
// MARK: - Manage the Player Form
|
||||
|
||||
/// Validates and saves the player into the database.
|
||||
func savePlayer() throws {
|
||||
if name.isEmpty {
|
||||
throw ValidationError.missingName
|
||||
}
|
||||
player.name = name
|
||||
player.score = Int(score) ?? 0
|
||||
try database.savePlayer(&player)
|
||||
}
|
||||
|
||||
/// Resets form values to the original player values.
|
||||
func reset() {
|
||||
updateViewFromPlayer()
|
||||
}
|
||||
|
||||
/// Edits a new player
|
||||
func editNewPlayer() {
|
||||
player = .new()
|
||||
updateViewFromPlayer()
|
||||
}
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
private func updateViewFromPlayer() {
|
||||
self.name = player.name
|
||||
if player.score == 0 && player.id == nil {
|
||||
// Avoid displaying "0" for a new player: it does not look good.
|
||||
self.score = ""
|
||||
} else {
|
||||
self.score = "\(player.score)"
|
||||
}
|
||||
}
|
||||
}
|
||||
-118
@@ -1,118 +0,0 @@
|
||||
import Combine
|
||||
import Foundation
|
||||
|
||||
/// The view model that feeds `PlayerList`, and performs list modifications
|
||||
/// in the database.
|
||||
final class PlayerListViewModel: ObservableObject {
|
||||
enum Ordering {
|
||||
case byScore
|
||||
case byName
|
||||
}
|
||||
|
||||
struct PlayerList {
|
||||
var players: [Player]
|
||||
var animatedChanges: Bool
|
||||
}
|
||||
|
||||
/// The list ordering
|
||||
@Published var ordering: Ordering = .byScore
|
||||
|
||||
/// The players in the list
|
||||
@Published var playerList = PlayerList(players: [], animatedChanges: false)
|
||||
|
||||
/// The view model that edits a new player
|
||||
let newPlayerViewModel: PlayerFormViewModel
|
||||
|
||||
private let database: AppDatabase
|
||||
private var playersCancellable: AnyCancellable?
|
||||
|
||||
init(database: AppDatabase) {
|
||||
self.database = database
|
||||
newPlayerViewModel = PlayerFormViewModel(database: database, player: .new())
|
||||
playersCancellable = playersPublisher(in: database)
|
||||
.scan(nil) { (previousList: PlayerList?, players: [Player]) in
|
||||
if previousList == nil {
|
||||
// Do not animate first view update
|
||||
return PlayerList(players: players, animatedChanges: false)
|
||||
} else {
|
||||
return PlayerList(players: players, animatedChanges: true)
|
||||
}
|
||||
}
|
||||
.compactMap { $0 }
|
||||
.sink { [weak self] playerList in
|
||||
self?.playerList = playerList
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Players List Management
|
||||
|
||||
/// Deletes all players
|
||||
func deleteAllPlayers() {
|
||||
// Eventual error presentation is left as an exercise for the reader.
|
||||
try! database.deleteAllPlayers()
|
||||
}
|
||||
|
||||
func deletePlayers(atOffsets offsets: IndexSet) {
|
||||
// Eventual error presentation is left as an exercise for the reader.
|
||||
let playerIDs = offsets.compactMap { playerList.players[$0].id }
|
||||
try! database.deletePlayers(ids: playerIDs)
|
||||
}
|
||||
|
||||
/// Refreshes the list of players
|
||||
func refreshPlayers() {
|
||||
// Eventual error presentation is left as an exercise for the reader.
|
||||
try! database.refreshPlayers()
|
||||
}
|
||||
|
||||
/// Spawns many concurrent database updates, for demo purpose
|
||||
func stressTest() {
|
||||
for _ in 0..<50 {
|
||||
DispatchQueue.global().async {
|
||||
self.refreshPlayers()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Change Player Ordering
|
||||
|
||||
/// Toggles between the available orderings
|
||||
func toggleOrdering() {
|
||||
switch ordering {
|
||||
case .byName:
|
||||
ordering = .byScore
|
||||
case .byScore:
|
||||
ordering = .byName
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Player Edition
|
||||
|
||||
/// Returns a view model suitable for editing a player.
|
||||
func formViewModel(for player: Player) -> PlayerFormViewModel {
|
||||
PlayerFormViewModel(database: database, player: player)
|
||||
}
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
/// Returns a publisher of the players in the list
|
||||
private func playersPublisher(in database: AppDatabase) -> AnyPublisher<[Player], Never> {
|
||||
// Players depend on the current ordering
|
||||
$ordering.map { ordering -> AnyPublisher<[Player], Error> in
|
||||
switch ordering {
|
||||
case .byScore:
|
||||
return database.playersOrderedByScorePublisher()
|
||||
case .byName:
|
||||
return database.playersOrderedByNamePublisher()
|
||||
}
|
||||
}
|
||||
.map { playersPublisher in
|
||||
// Turn database errors into an empty players list.
|
||||
// Eventual error presentation is left as an exercise for the reader.
|
||||
playersPublisher.catch { error in
|
||||
Just<[Player]>([])
|
||||
}
|
||||
}
|
||||
.switchToLatest()
|
||||
.eraseToAnyPublisher()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import SwiftUI
|
||||
|
||||
/// The main application view
|
||||
struct AppView: View {
|
||||
/// Database access
|
||||
@Environment(\.appDatabase) private var appDatabase
|
||||
|
||||
/// The `players` property is kept up-to-date with the list of players.
|
||||
@Query(PlayerRequest(ordering: .byScore)) private var players: [Player]
|
||||
|
||||
/// Tracks the presentation of the player creation sheet.
|
||||
@State private var newPlayerIsPresented = false
|
||||
|
||||
// If you want to define the query on initialization, you will prefer:
|
||||
//
|
||||
// @Query<PlayerRequest> private var players: [Player]
|
||||
//
|
||||
// init(initialOrdering: PlayerRequest.Ordering) {
|
||||
// _players = Query(PlayerRequest(ordering: initialOrdering))
|
||||
// }
|
||||
|
||||
var body: some View {
|
||||
NavigationView {
|
||||
PlayerList(players: players)
|
||||
.navigationBarTitle(Text("\(players.count) Players"))
|
||||
.navigationBarItems(
|
||||
leading: HStack {
|
||||
EditButton()
|
||||
newPlayerButton
|
||||
},
|
||||
trailing: ToggleOrderingButton(ordering: $players.ordering))
|
||||
.toolbar { toolbarContent }
|
||||
}
|
||||
}
|
||||
|
||||
private var toolbarContent: some ToolbarContent {
|
||||
ToolbarItemGroup(placement: .bottomBar) {
|
||||
Button(
|
||||
action: { try? appDatabase?.deleteAllPlayers() },
|
||||
label: { Image(systemName: "trash").imageScale(.large) })
|
||||
Spacer()
|
||||
Button(
|
||||
action: { try? appDatabase?.refreshPlayers() },
|
||||
label: { Image(systemName: "arrow.clockwise").imageScale(.large) })
|
||||
}
|
||||
}
|
||||
|
||||
/// The button that presents the player creation sheet.
|
||||
private var newPlayerButton: some View {
|
||||
Button(
|
||||
action: { newPlayerIsPresented = true },
|
||||
label: { Image(systemName: "plus") })
|
||||
.accessibility(label: Text("New Player"))
|
||||
.sheet(
|
||||
isPresented: $newPlayerIsPresented,
|
||||
content: {
|
||||
PlayerCreationView(dismissAction: {
|
||||
newPlayerIsPresented = false
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private struct ToggleOrderingButton: View {
|
||||
@Binding var ordering: PlayerRequest.Ordering
|
||||
|
||||
var body: some View {
|
||||
switch ordering {
|
||||
case .byName:
|
||||
Button(
|
||||
action: { ordering = .byScore },
|
||||
label: {
|
||||
HStack {
|
||||
Text("Name")
|
||||
Image(systemName: "arrowtriangle.up.fill")
|
||||
}
|
||||
})
|
||||
case .byScore:
|
||||
Button(
|
||||
action: { ordering = .byName },
|
||||
label: {
|
||||
HStack {
|
||||
Text("Score")
|
||||
Image(systemName: "arrowtriangle.down.fill")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct AppView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
Group {
|
||||
// Preview a database of random players
|
||||
AppView().environment(\.appDatabase, .random())
|
||||
|
||||
// Preview an empty database
|
||||
AppView().environment(\.appDatabase, .empty())
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
-16
@@ -1,36 +1,37 @@
|
||||
import SwiftUI
|
||||
|
||||
/// The Player creation sheet
|
||||
struct PlayerCreationSheet: View {
|
||||
/// Manages the player form
|
||||
let viewModel: PlayerFormViewModel
|
||||
|
||||
/// The view that creates a new player.
|
||||
struct PlayerCreationView: View {
|
||||
/// Executed when user cancels or saves the new user.
|
||||
let dismissAction: () -> Void
|
||||
|
||||
@Environment(\.appDatabase) private var appDatabase
|
||||
@State private var name = ""
|
||||
@State private var score = ""
|
||||
@State private var errorAlertIsPresented = false
|
||||
@State private var errorAlertTitle = ""
|
||||
|
||||
var body: some View {
|
||||
NavigationView {
|
||||
PlayerForm(viewModel: viewModel)
|
||||
PlayerFormView(name: $name, score: $score)
|
||||
.alert(
|
||||
isPresented: $errorAlertIsPresented,
|
||||
content: { Alert(title: Text(errorAlertTitle)) })
|
||||
.navigationBarTitle("New Player")
|
||||
.navigationBarItems(
|
||||
leading: Button(
|
||||
action: self.dismissAction,
|
||||
action: dismissAction,
|
||||
label: { Text("Cancel") }),
|
||||
trailing: Button(
|
||||
action: self.save,
|
||||
action: save,
|
||||
label: { Text("Save") }))
|
||||
}
|
||||
}
|
||||
|
||||
private func save() {
|
||||
do {
|
||||
try viewModel.savePlayer()
|
||||
var player = Player(id: nil, name: name, score: Int(score) ?? 0)
|
||||
try appDatabase?.savePlayer(&player)
|
||||
dismissAction()
|
||||
} catch {
|
||||
errorAlertTitle = (error as? LocalizedError)?.errorDescription ?? "An error occurred"
|
||||
@@ -41,12 +42,7 @@ struct PlayerCreationSheet: View {
|
||||
|
||||
struct PlayerCreationSheet_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
let viewModel = PlayerFormViewModel(
|
||||
database: .empty(),
|
||||
player: .new())
|
||||
|
||||
return PlayerCreationSheet(
|
||||
viewModel: viewModel,
|
||||
dismissAction: { })
|
||||
PlayerCreationView(dismissAction: { })
|
||||
.environment(\.appDatabase, .empty())
|
||||
}
|
||||
}
|
||||
+14
-15
@@ -1,28 +1,27 @@
|
||||
import SwiftUI
|
||||
|
||||
/// The Player edition view, designed to be the destination of
|
||||
/// a NavigationLink.
|
||||
/// The view that edits an existing player.
|
||||
struct PlayerEditionView: View {
|
||||
/// Manages the player form
|
||||
let viewModel: PlayerFormViewModel
|
||||
@Environment(\.appDatabase) private var appDatabase
|
||||
@State var player: Player
|
||||
|
||||
var body: some View {
|
||||
PlayerForm(viewModel: viewModel)
|
||||
.onDisappear(perform: {
|
||||
// Ignore validation errors
|
||||
try? self.viewModel.savePlayer()
|
||||
})
|
||||
PlayerFormView(
|
||||
name: $player.name,
|
||||
score: Binding(
|
||||
get: { "\(player.score)" },
|
||||
set: { player.score = Int($0) ?? 0 }))
|
||||
.onDisappear {
|
||||
// save and ignore error
|
||||
try? appDatabase?.savePlayer(&player)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerEditionView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
let viewModel = PlayerFormViewModel(
|
||||
database: .empty(),
|
||||
player: .newRandom())
|
||||
|
||||
return NavigationView {
|
||||
PlayerEditionView(viewModel: viewModel)
|
||||
NavigationView {
|
||||
PlayerEditionView(player: Player.newRandom())
|
||||
.navigationBarTitle("Player Edition")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
import SwiftUI
|
||||
|
||||
/// The Player editing form, embedded in both
|
||||
/// `PlayerCreationSheet` and `PlayerEditionView`.
|
||||
struct PlayerForm: View {
|
||||
/// Manages the player form
|
||||
@ObservedObject var viewModel: PlayerFormViewModel
|
||||
|
||||
var body: some View {
|
||||
List {
|
||||
TextField("Name", text: $viewModel.name)
|
||||
TextField("Score", text: $viewModel.score)
|
||||
.keyboardType(.numberPad)
|
||||
}
|
||||
.listStyle(GroupedListStyle())
|
||||
// Make sure the form is reset, in case a previous edition ended
|
||||
// with a validation error.
|
||||
//
|
||||
// The bug we want to prevent is the following:
|
||||
//
|
||||
// 1. Launch the app
|
||||
// 2. Tap a player
|
||||
// 3. Erase the name so that validation fails
|
||||
// 4. Hit the back button
|
||||
// 5. Tap the same player
|
||||
// 6. Bug: the form displays an empty name.
|
||||
.onAppear(perform: viewModel.reset)
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerFormView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
let viewModel = PlayerFormViewModel(
|
||||
database: .empty(),
|
||||
player: .newRandom())
|
||||
|
||||
return PlayerForm(viewModel: viewModel)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import SwiftUI
|
||||
|
||||
/// The Player editing form, embedded in both
|
||||
/// `PlayerCreationView` and `PlayerEditionView`.
|
||||
struct PlayerFormView: View {
|
||||
@Binding var name: String
|
||||
@Binding var score: String
|
||||
|
||||
var body: some View {
|
||||
List {
|
||||
TextField("Name", text: $name)
|
||||
.accessibility(label: Text("Player Name"))
|
||||
TextField("Score", text: $score).keyboardType(.numberPad)
|
||||
.accessibility(label: Text("Player Score"))
|
||||
}
|
||||
.listStyle(InsetGroupedListStyle())
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerFormView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
Group {
|
||||
PlayerFormView(
|
||||
name: .constant(""),
|
||||
score: .constant(""))
|
||||
PlayerFormView(
|
||||
name: .constant(Player.randomName()),
|
||||
score: .constant("\(Player.randomScore())"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,117 +1,35 @@
|
||||
import SwiftUI
|
||||
|
||||
/// The list of players
|
||||
struct PlayerList: View {
|
||||
/// Manages the list of players
|
||||
@ObservedObject var viewModel: PlayerListViewModel
|
||||
/// Database access
|
||||
@Environment(\.appDatabase) private var appDatabase
|
||||
|
||||
/// Controls the presentation of the player creation sheet.
|
||||
@State private var newPlayerIsPresented = false
|
||||
/// The players in the list
|
||||
var players: [Player]
|
||||
|
||||
var body: some View {
|
||||
NavigationView {
|
||||
VStack {
|
||||
playerList
|
||||
toolbar
|
||||
}
|
||||
.navigationBarTitle(Text("\(viewModel.playerList.players.count) Players"))
|
||||
.navigationBarItems(
|
||||
leading: HStack {
|
||||
EditButton()
|
||||
newPlayerButton
|
||||
},
|
||||
trailing: toggleOrderingButton)
|
||||
}
|
||||
}
|
||||
|
||||
private var playerList: some View {
|
||||
List {
|
||||
ForEach(viewModel.playerList.players) { player in
|
||||
NavigationLink(destination: self.editionView(for: player)) {
|
||||
PlayerRow(player: player)
|
||||
.animation(nil)
|
||||
ForEach(players) { player in
|
||||
NavigationLink(destination: editionView(for: player)) {
|
||||
PlayerRow(player: player).animation(nil)
|
||||
}
|
||||
}
|
||||
.onDelete(perform: { offsets in
|
||||
self.viewModel.deletePlayers(atOffsets: offsets)
|
||||
let playerIds = offsets.compactMap { players[$0].id }
|
||||
try? appDatabase?.deletePlayers(ids: playerIds)
|
||||
})
|
||||
}
|
||||
.animation(.default)
|
||||
.listStyle(PlainListStyle())
|
||||
.animation(viewModel.playerList.animatedChanges ? .default : nil)
|
||||
}
|
||||
|
||||
private var toolbar: some View {
|
||||
HStack {
|
||||
Button(
|
||||
action: viewModel.deleteAllPlayers,
|
||||
label: { Image(systemName: "trash").imageScale(.large) })
|
||||
Spacer()
|
||||
Button(
|
||||
action: viewModel.refreshPlayers,
|
||||
label: { Image(systemName: "arrow.clockwise").imageScale(.large) })
|
||||
Spacer()
|
||||
Button(
|
||||
action: viewModel.stressTest,
|
||||
label: { Image(systemName: "tornado").imageScale(.large) })
|
||||
}
|
||||
|
||||
.padding()
|
||||
}
|
||||
|
||||
/// The button that toggles between name/score ordering.
|
||||
private var toggleOrderingButton: some View {
|
||||
switch viewModel.ordering {
|
||||
case .byName:
|
||||
return Button(action: viewModel.toggleOrdering, label: {
|
||||
HStack {
|
||||
Text("Name")
|
||||
Image(systemName: "arrowtriangle.up.fill")
|
||||
.imageScale(.small)
|
||||
}
|
||||
})
|
||||
case .byScore:
|
||||
return Button(action: viewModel.toggleOrdering, label: {
|
||||
HStack {
|
||||
Text("Score")
|
||||
Image(systemName: "arrowtriangle.down.fill")
|
||||
.imageScale(.small)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The view that edits a player in the list.
|
||||
private func editionView(for player: Player) -> some View {
|
||||
PlayerEditionView(
|
||||
viewModel: viewModel.formViewModel(for: player))
|
||||
.navigationBarTitle(player.name)
|
||||
}
|
||||
|
||||
/// The button that presents the player creation sheet.
|
||||
private var newPlayerButton: some View {
|
||||
Button(
|
||||
action: {
|
||||
// Make sure we do not edit a previously created player.
|
||||
self.viewModel.newPlayerViewModel.editNewPlayer()
|
||||
self.newPlayerIsPresented = true
|
||||
},
|
||||
label: { Image(systemName: "plus").imageScale(.large) })
|
||||
.sheet(
|
||||
isPresented: $newPlayerIsPresented,
|
||||
content: { self.newPlayerCreationSheet })
|
||||
}
|
||||
|
||||
/// The player creation sheet.
|
||||
private var newPlayerCreationSheet: some View {
|
||||
PlayerCreationSheet(
|
||||
viewModel: self.viewModel.newPlayerViewModel,
|
||||
dismissAction: {
|
||||
self.newPlayerIsPresented = false
|
||||
})
|
||||
PlayerEditionView(player: player).navigationBarTitle(player.name)
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerRow: View {
|
||||
private struct PlayerRow: View {
|
||||
var player: Player
|
||||
|
||||
var body: some View {
|
||||
@@ -123,9 +41,14 @@ struct PlayerRow: View {
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerListView_Previews: PreviewProvider {
|
||||
struct PlayerList_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
let viewModel = PlayerListViewModel(database: .random())
|
||||
return PlayerList(viewModel: viewModel)
|
||||
NavigationView {
|
||||
PlayerList(players: [
|
||||
Player(id: 1, name: "Arthur", score: 100),
|
||||
Player(id: 2, name: "Barbara", score: 1000),
|
||||
])
|
||||
.navigationTitle("Preview")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -143,112 +143,4 @@ class AppDatabaseTests: XCTestCase {
|
||||
let players = try dbQueue.read(Player.fetchAll)
|
||||
XCTAssertEqual(players, [player])
|
||||
}
|
||||
|
||||
func test_playersOrderedByNamePublisher_publishes_well_ordered_players() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
}
|
||||
|
||||
// When we observe players and wait for the first value
|
||||
let exp = expectation(description: "Players")
|
||||
var players: [Player]?
|
||||
let cancellable = appDatabase.playersOrderedByNamePublisher().sink { completion in
|
||||
if case let .failure(error) = completion {
|
||||
XCTFail("Unexpected error \(error)")
|
||||
}
|
||||
} receiveValue: {
|
||||
players = $0
|
||||
exp.fulfill()
|
||||
}
|
||||
withExtendedLifetime(cancellable) {
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
}
|
||||
|
||||
// Then the players are the two players ordered by name
|
||||
XCTAssertEqual(players, [player1, player2])
|
||||
}
|
||||
|
||||
func test_playersOrderedByNamePublisher_publishes_right_on_subscripion() throws {
|
||||
// Our SwiftUI views have no "waiting" state, and must be fed with
|
||||
// players without any delay in order to avoid any rendering glitch.
|
||||
// This test makes sure `playersOrderedByNamePublisher` publishes right
|
||||
// on subscription.
|
||||
|
||||
// Given a players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we observe players
|
||||
var players: [Player]?
|
||||
_ = appDatabase.playersOrderedByNamePublisher().sink { completion in
|
||||
if case let .failure(error) = completion {
|
||||
XCTFail("Unexpected error \(error)")
|
||||
}
|
||||
} receiveValue: {
|
||||
players = $0
|
||||
}
|
||||
|
||||
// Then the players are published right on subscription
|
||||
XCTAssertNotNil(players)
|
||||
}
|
||||
|
||||
func test_playersOrderedByScorePublisher_publishes_well_ordered_players() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
}
|
||||
|
||||
// When we observe players and wait for the first value
|
||||
let exp = expectation(description: "Players")
|
||||
var players: [Player]?
|
||||
let cancellable = appDatabase.playersOrderedByScorePublisher().sink { completion in
|
||||
if case let .failure(error) = completion {
|
||||
XCTFail("Unexpected error \(error)")
|
||||
}
|
||||
} receiveValue: {
|
||||
players = $0
|
||||
exp.fulfill()
|
||||
}
|
||||
withExtendedLifetime(cancellable) {
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
}
|
||||
|
||||
// Then the players are the two players ordered by score descending
|
||||
XCTAssertEqual(players, [player2, player1])
|
||||
}
|
||||
|
||||
func test_playersOrderedByScorePublisher_publishes_right_on_subscripion() throws {
|
||||
// Our SwiftUI views have no "waiting" state, and must be fed with
|
||||
// players without any delay in order to avoid any rendering glitch.
|
||||
// This test makes sure `playersOrderedByScorePublisher` publishes right
|
||||
// on subscription.
|
||||
|
||||
// Given a players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we observe players
|
||||
var players: [Player]?
|
||||
_ = appDatabase.playersOrderedByScorePublisher().sink { completion in
|
||||
if case let .failure(error) = completion {
|
||||
XCTFail("Unexpected error \(error)")
|
||||
}
|
||||
} receiveValue: {
|
||||
players = $0
|
||||
}
|
||||
|
||||
// Then the players are published right on subscription
|
||||
XCTAssertNotNil(players)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
@testable import GRDBCombineDemo
|
||||
|
||||
class PlayerRequestTests: XCTestCase {
|
||||
func test_PlayerRequest_byName_fetches_well_ordered_players() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
}
|
||||
|
||||
// When we fetch players ordered by name
|
||||
let playerRequest = PlayerRequest(ordering: .byName)
|
||||
let players = try dbQueue.read(playerRequest.fetchValue)
|
||||
|
||||
// Then the players are the two players ordered by name
|
||||
XCTAssertEqual(players, [player1, player2])
|
||||
}
|
||||
|
||||
func test_PlayerRequest_byScore_fetches_well_ordered_players() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
}
|
||||
|
||||
// When we fetch players ordered by score
|
||||
let playerRequest = PlayerRequest(ordering: .byScore)
|
||||
let players = try dbQueue.read(playerRequest.fetchValue)
|
||||
|
||||
// Then the players are the two players ordered by score descending
|
||||
XCTAssertEqual(players, [player2, player1])
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
//
|
||||
// GRDBCombineDemoUITests.swift
|
||||
// GRDBCombineDemoUITests
|
||||
//
|
||||
// Created by Peter Steinberger on 08.04.21.
|
||||
//
|
||||
|
||||
import XCTest
|
||||
|
||||
class GRDBCombineDemoUITests: XCTestCase {
|
||||
|
||||
override func setUpWithError() throws {
|
||||
// In UI tests it is usually best to stop immediately when a failure occurs.
|
||||
continueAfterFailure = false
|
||||
}
|
||||
|
||||
override func tearDownWithError() throws {
|
||||
}
|
||||
|
||||
func runApp() -> XCUIApplication {
|
||||
// UI tests must launch the application that they test.
|
||||
let app = XCUIApplication()
|
||||
// We enforce a fresh database to ensure 8 random players.
|
||||
app.launchArguments = ["-reset", "-fixedTestData"]
|
||||
app.launch()
|
||||
return app
|
||||
}
|
||||
|
||||
// This test, introduced in 481f6e93, tests the @Query fix added in
|
||||
// 68874412. The fix expresses itself when a view defines an @Query
|
||||
// property that is replaced in the view initializer, as in 481f6e93.
|
||||
//
|
||||
// It happens that I did not find that this particular view setup was suited
|
||||
// for a demo app. The demo has to find a delicate balance, not too trivial,
|
||||
// but without gratuitous complexity.
|
||||
//
|
||||
// I simplified the demo app in a5ffc52d, and we no longer have any view
|
||||
// that defines an @Query property which is replaced in the view
|
||||
// initializer. This means that this test no longer checks against
|
||||
// 68874412 regressions!
|
||||
//
|
||||
// Whenever the @Query property wrapper ships with GRDB itself, make sure
|
||||
// we test for those regressions!
|
||||
func testInitialSortingIsByScore() throws {
|
||||
let app = runApp()
|
||||
|
||||
let getFirstCell = { () -> XCUIElement in
|
||||
app.tables.element(boundBy: 0).cells.element(boundBy: 0)
|
||||
}
|
||||
|
||||
// Given default sorting, Henriette must be on top
|
||||
XCTAssertEqual(getFirstCell().label, "Craig, 8 points")
|
||||
|
||||
// Reverse sorting will bring Arthur on top (sort by name)
|
||||
app.buttons["Score"].tap()
|
||||
XCTAssertEqual(getFirstCell().label, "Arthur, 5 points")
|
||||
}
|
||||
|
||||
func testListAndAddPlayer() throws {
|
||||
let app = runApp()
|
||||
|
||||
// Ensure we have 8 players visible
|
||||
XCTAssert(app.tables.cells.count == 8)
|
||||
|
||||
// add a player
|
||||
app.buttons["New Player"].tap()
|
||||
|
||||
let playerNameField = app.textFields["Player Name"]
|
||||
playerNameField.tap()
|
||||
playerNameField.typeText("Tim Apple")
|
||||
|
||||
app.buttons["Save"].tap()
|
||||
|
||||
// This is suboptimal, but we need to wait for the animation to finish
|
||||
// A better way could be to disable animations globally,
|
||||
// and/or a hook to detect when the async fetch completes.
|
||||
sleep(2)
|
||||
|
||||
XCTAssert(app.tables.cells.count == 9)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -3,7 +3,7 @@ Combine + SwiftUI Demo Application
|
||||
|
||||
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBCombineDemo/Screenshot.png" width="50%">
|
||||
|
||||
**This demo application is a Combine + SwiftUI application, based on the MVVM design pattern.** For a demo application that uses UIKit, see [GRDBDemoiOS](../GRDBDemoiOS/README.md).
|
||||
**This demo application is a Combine + SwiftUI application.** For a demo application that uses UIKit, see [GRDBDemoiOS](../GRDBDemoiOS/README.md).
|
||||
|
||||
> :point_up: **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration.
|
||||
|
||||
@@ -19,7 +19,7 @@ The topics covered in this demo are:
|
||||
|
||||
- [GRDBCombineDemoApp.swift](GRDBCombineDemo/GRDBCombineDemoApp.swift)
|
||||
|
||||
`GRDBCombineDemoApp` feeds the app views with a database.
|
||||
`GRDBCombineDemoApp` feeds the app views with a database, through the SwiftUI environment.
|
||||
|
||||
- [AppDatabase.swift](GRDBCombineDemo/AppDatabase.swift)
|
||||
|
||||
@@ -31,18 +31,19 @@ The topics covered in this demo are:
|
||||
|
||||
- [Player.swift](GRDBCombineDemo/Player.swift)
|
||||
|
||||
`Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records). It defines the database requests used by the application.
|
||||
`Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records).
|
||||
|
||||
- [PlayerList.swift](GRDBCombineDemo/Views/PlayerList.swift) and [PlayerListViewModel.swift](GRDBCombineDemo/ViewModels/PlayerListViewModel.swift)
|
||||
- [PlayerRequest.swift](GRDBCombineDemo/PlayerRequest.swift), [Query.swift](GRDBCombineDemo/Query.swift), [AppView.swift](GRDBCombineDemo/Views/AppView.swift)
|
||||
|
||||
`PlayerList` is the SwiftUI view that displays the list of players, fed by `PlayerListViewModel`.
|
||||
|
||||
- [PlayerForm.swift](GRDBCombineDemo/Views/PlayerForm.swift), [PlayerEditionView.swift](GRDBCombineDemo/Views/PlayerEditionView.swift), [PlayerCreationSheet.swift](GRDBCombineDemo/Views/PlayerCreationSheet.swift) and [PlayerFormViewModel.swift](GRDBCombineDemo/ViewModels/PlayerFormViewModel.swift).
|
||||
`PlayerRequest` defines the player requests used by the app (sorted by score, or by name).
|
||||
|
||||
`PlayerForm` is the SwiftUI view that displays a Player editing form. It is embedded in `PlayerEditionView` and `PlayerCreationSheet`, two SwiftUI views that edit or create a player. All those views are fed by `PlayerFormViewModel`.
|
||||
`PlayerRequest` feeds the `@Query` property wrapper. `@Query`, inspired by [this article](https://davedelong.com/blog/2021/04/03/core-data-and-swiftui/), allows SwiftUI views to display up-to-date database content thanks to GRDB's [ValueObservation](../../../README.md#valueobservation).
|
||||
|
||||
`AppView` is the SwiftUI view that uses `@Query` in order to feed its player list.
|
||||
|
||||
- [GRDBCombineDemoTests](GRDBCombineDemoTests)
|
||||
|
||||
- Test the database schema
|
||||
- Test the `Player` record and its requests
|
||||
- Test the `PlayerRequest` methods that feed the list of players.
|
||||
- Test the `AppDatabase` methods that let the app access the database.
|
||||
+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">
|
||||
|
||||
@@ -64,7 +64,7 @@ extension AppDatabase {
|
||||
/// Delete the specified players
|
||||
func deletePlayers(ids: [Int64]) throws {
|
||||
try dbWriter.write { db in
|
||||
_ = try Player.deleteAll(db, keys: ids)
|
||||
_ = try Player.deleteAll(db, ids: ids)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,8 +2,9 @@ import GRDB
|
||||
|
||||
/// The Player struct.
|
||||
///
|
||||
/// Identifiable conformance supports type-safe GRDB primary key methods.
|
||||
/// Hashable conformance supports table view updates
|
||||
struct Player: Hashable {
|
||||
struct Player: Identifiable, Hashable {
|
||||
/// The player id.
|
||||
///
|
||||
/// Int64 is the recommended type for auto-incremented database ids.
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -3,7 +3,7 @@ UIKit Demo Application
|
||||
|
||||
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBDemoiOS/Screenshot.png" width="50%">
|
||||
|
||||
**This demo application is a storyboard-based UIKit application, based on the MVC design pattern.** For a demo application that uses Combine and SwiftUI, see [GRDBCombineDemo](../GRDBCombineDemo/README.md).
|
||||
**This demo application is a storyboard-based UIKit application.** For a demo application that uses Combine and SwiftUI, see [GRDBCombineDemo](../GRDBCombineDemo/README.md).
|
||||
|
||||
> :point_up: **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration.
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
Demo Applications
|
||||
=================
|
||||
|
||||
- [UIKit Demo Application](GRDBDemoiOS/README.md): a storyboard-based UIKit application, based on the MVC design pattern.
|
||||
- [Combine + SwiftUI Demo Application](GRDBCombineDemo/README.md): a Combine + SwiftUI application, based on the MVVM design pattern.
|
||||
|
||||
- [UIKit Demo Application](GRDBDemoiOS/README.md): a storyboard-based UIKit application.
|
||||
- [Combine + SwiftUI Demo Application](GRDBCombineDemo/README.md): a Combine + SwiftUI application.
|
||||
@@ -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.8/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.8/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
|
||||
@@ -387,16 +387,16 @@ let publisher = observation
|
||||
|
||||
> :question: This change makes it possible to concatenate subqueries with the UNION operator.
|
||||
|
||||
4. In order to extract raw SQL string from an [SQLLiteral], you now need a database connection:
|
||||
4. In order to extract raw SQL string from an [SQL literal], you now need a database connection:
|
||||
|
||||
```swift
|
||||
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
|
||||
// BEFORE: GRDB 4
|
||||
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
print(query.sql) // prints "UPDATE player SET name = ? WHERE id = ?"
|
||||
print(query.arguments) // prints ["O'Brien", 42]
|
||||
|
||||
// NEW: GRDB 5
|
||||
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
let (sql, arguments) = try dbQueue.read(query.build)
|
||||
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
|
||||
print(arguments) // prints ["O'Brien", 42]
|
||||
@@ -506,7 +506,7 @@ let publisher = observation
|
||||
[Custom SQL functions]: ../README.md#custom-sql-functions
|
||||
[Batch updates]: ../README.md#update-requests
|
||||
[SQL Interpolation]: SQLInterpolation.md
|
||||
[SQLLiteral]: SQLInterpolation.md#sqlliteral
|
||||
[SQL literal]: SQLInterpolation.md#sql-literal
|
||||
[SQLRequest]: ../README.md#custom-requests
|
||||
[QueryInterfaceRequest]: ../README.md#requests
|
||||
[Combine publishers]: Combine.md
|
||||
|
||||
@@ -9,6 +9,8 @@ To support this guide, we'll design a simple library application that lets the u
|
||||
|
||||
- [Trust SQLite More Than Yourself]
|
||||
- [Persistable Record Types are Responsible for Their Tables]
|
||||
- [Record Types Hide Intimate Database Details]
|
||||
- [Singleton Records]
|
||||
- [Define Record Requests]
|
||||
- [Compose Records]
|
||||
- [How to Design Database Managers]
|
||||
@@ -96,13 +98,13 @@ Define one record type per database table, and make it adopt a [PersistableRecor
|
||||
In this sample code, we'll use Codable structs, but there are [other ways](../README.md#examples-of-record-definitions) to define records.
|
||||
|
||||
```swift
|
||||
struct Author: Codable {
|
||||
struct Author: Codable, Identifiable {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
var country: String?
|
||||
}
|
||||
|
||||
struct Book: Codable {
|
||||
struct Book: Codable, Identifiable {
|
||||
var id: Int64?
|
||||
var authorId: Int64
|
||||
var title: String
|
||||
@@ -138,12 +140,108 @@ That's it. The `Author` type can read and write in the `author` database table.
|
||||
> print(author.id!) // Guaranteed non-nil id
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> :bulb: **Tip**: When the database table has a single-column primary key, have your record type adopt the standard [Identifiable] protocol. This allows GRDB to define type-safe id-related methods:
|
||||
>
|
||||
> ```swift
|
||||
> let authorID: Int64 = ...
|
||||
> let author: Author? = try dbQueue.read { db in
|
||||
> try Author.fetchOne(db, id: authorID)
|
||||
> }
|
||||
> ```
|
||||
|
||||
Since `Author` and `Book` can insert, update, and delete rows in the `author` and `book` database tables, they are *responsible for modifying those database tables*.
|
||||
Now that `Author` and `Book` can read and write in their own database tables, they are responsible for it. Make sure each record type deals with one database table, and only one database table!
|
||||
|
||||
Applying the **[Single Responsibility Principle]** has a consequence: don't even try to have an author responsible for its books. Don't add a `books: [Book]` property in Author. Don't let Author write in the `book` table. When a new fellow coworker joins your team and asks you "who is saving books in the database?", you don't want to answer "it depends." You want to confidently answer: "the Book type".
|
||||
|
||||
> :bulb: **Tip**: Make sure each record type deals with one database table, and only one database table.
|
||||
## Record Types Hide Intimate Database Details
|
||||
|
||||
The application uses `Book` and `Author` as regular structs, using their properties. Each of those properties matches a column in the database (`Book.title`, `Author.id`), and is defined with a Swift type that is natively supported by SQLite (`String`, `Int`, etc.)
|
||||
|
||||
Sometimes, it happens that raw database column names and types are not a very good fit for the application.
|
||||
|
||||
Let's look at three examples:
|
||||
|
||||
1. Authors write books, and more specifically novels, poems, essays, or theatre plays. Let's add a `kind` column in the database. For easy debugging of the database contents, a book kind is represented as a string ("novel", "essay", etc.):
|
||||
|
||||
```swift
|
||||
try db.create(table: "book") { t in
|
||||
...
|
||||
t.column("kind", .text).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
In Swift, it is not a good practice to use `String` for the type of the `kind` property. We want an enum instead:
|
||||
|
||||
```swift
|
||||
struct Book: Codable {
|
||||
enum Kind: String, Codable {
|
||||
case novel, poems, essay, play
|
||||
}
|
||||
var id: Int64?
|
||||
var authorId: Int64
|
||||
var title: String
|
||||
var kind: Kind
|
||||
}
|
||||
```
|
||||
|
||||
In order to make it possible to use `Book.Kind` in book requests (see [Define Record Requests] below), we add this conformance:
|
||||
|
||||
```swift
|
||||
extension Book.Kind: DatabaseValueConvertible { }
|
||||
```
|
||||
|
||||
> :bulb: Records can pick the best suited [Value] type for their column properties (Bool, Int, String, Date, etc.) Thanks to its enum property, the `Book` record prevents unknown book kinds from entering the database.
|
||||
|
||||
2. GPS coordinates are usually stored in two distinct `latitude` and `longitude` columns. But the standard way to deal with such coordinate is a single `CLLocationCoordinate2D` struct.
|
||||
|
||||
When this happens, keep column properties private, and provide sensible accessors instead:
|
||||
|
||||
```swift
|
||||
struct Place: Codable {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
private var latitude: CLLocationDegrees
|
||||
private var longitude: CLLocationDegrees
|
||||
|
||||
var coordinate: CLLocationCoordinate2D {
|
||||
get {
|
||||
CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
|
||||
}
|
||||
set {
|
||||
latitude = newValue.latitude
|
||||
longitude = newValue.longitude
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: Private properties make it possible to hide raw columns from the rest of the application.
|
||||
|
||||
3. The record below exposes a `price: Decimal` property ($12.00), backed by an integer column that stores a quantity of cents (1200). An integer column is preferred because it allows SQLite to compute exact sums of prices.
|
||||
|
||||
```swift
|
||||
struct Product: Codable {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
private var priceCents: Int
|
||||
|
||||
var price: Decimal {
|
||||
get { Decimal(priceCents) / 100 }
|
||||
set { priceCents = NSDecimalNumber(decimal: newValue * 100).intValue }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: Private properties allow records to choose both their best database representation, and at the same time, their best Swift interface.
|
||||
|
||||
**Generally speaking**, record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. When needed, you can even [validate values](../README.md#customizing-the-persistence-methods) before they enter the database.
|
||||
|
||||
|
||||
## Singleton Records
|
||||
|
||||
**Singleton Records** are records that store configuration values, user preferences, and generally some global application state. They are backed by a database table that contains a single row.
|
||||
|
||||
The recommended setup for such records is described in the [Single-Row Tables](SingleRowTables.md) guide. Go check it, and come back when you're done!
|
||||
|
||||
|
||||
## Define Record Requests
|
||||
@@ -166,7 +264,7 @@ extension Author {
|
||||
}
|
||||
```
|
||||
|
||||
Otherwise, declare a plain String enum that conforms to the ColumnExpression protocol:
|
||||
Otherwise, declare a plain `String` enum that conforms to the `ColumnExpression` protocol:
|
||||
|
||||
```swift
|
||||
// For a non-codable record
|
||||
@@ -178,31 +276,50 @@ extension Author {
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: **Tip**: Define commonly used requests in a constrained extension of the `DerivableRequest` protocol.
|
||||
|
||||
The `DerivableRequest` protocol generally lets you filter, sort, and join or include associations (we'll talk about associations in the [Compose Records] chapter below).
|
||||
|
||||
Here is how you define those requests:
|
||||
Those columns let you define requests:
|
||||
|
||||
```swift
|
||||
// Some requests of Author --------------------v
|
||||
try dbQueue.read { db in
|
||||
// Order authors by name, in a localized case-insensitive fashion
|
||||
let sortedAuthors: [Author] = try Author.all()
|
||||
.order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
.fetchAll(db)
|
||||
|
||||
// French authors
|
||||
let frenchAuthors: [Author] = try Author.all()
|
||||
.filter(Author.Columns.country == "France")
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: **Tip**: Define commonly used requests in a constrained extension of the `DerivableRequest` protocol.
|
||||
|
||||
When you find yourself build similar requests over and over in your application, you may want to define a reusable and composable request vocabulary. This will avoid repetition in your app, ease refactoring, and enable [testability](DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift).
|
||||
|
||||
To do so, extend the `DerivableRequest` protocol. It generally lets you filter, sort, leverage associations (we'll talk about associations in the [Compose Records] chapter below), etc:
|
||||
|
||||
```swift
|
||||
// Author requests ~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
extension DerivableRequest where RowDecoder == Author {
|
||||
|
||||
/// Returns a request for all authors ordered by name, in a localized
|
||||
/// case-insensitive fashion
|
||||
/// Order authors by name, in a localized case-insensitive fashion
|
||||
func orderByName() -> Self {
|
||||
let name = Author.Columns.name
|
||||
return order(name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
|
||||
/// Returns a request for all authors from a country
|
||||
/// Filters authors from a country
|
||||
func filter(country: String) -> Self {
|
||||
filter(Author.Columns.country == country)
|
||||
}
|
||||
|
||||
/// Filters authors with at least one book
|
||||
func havingBooks() -> Self {
|
||||
having(Author.books.isEmpty == false)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Those methods defined on the `DerivableRequest` protocol hide intimate database details. They allow you to compose database requests in a fluent style:
|
||||
Those methods encapsulate intimate database details, and allow you to compose database requests in a fluent and legible style:
|
||||
|
||||
```swift
|
||||
try dbQueue.read { db in
|
||||
@@ -214,72 +331,55 @@ try dbQueue.read { db in
|
||||
.filter(country: "France")
|
||||
.fetchAll(db)
|
||||
|
||||
let sortedSpanishAuthors: [Author] = try Author.all()
|
||||
let sortedSpanishAuthorsHavingBooks: [Author] = try Author.all()
|
||||
.filter(country: "Spain")
|
||||
.havingBooks()
|
||||
.orderByName()
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
Those customized request methods are also available on record associations, because associations conform to the `DerivableRequest` protocol:
|
||||
Because they are defined in an extension of the `DerivableRequest` protocol, our customized methods can decorate both requests and associations. See how the implementation of `filter(authorCountry:)` for books, below, uses the `filter(country:)` for authors:
|
||||
|
||||
```swift
|
||||
// Some requests of Book
|
||||
// Book requests ~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
extension DerivableRequest where RowDecoder == Book {
|
||||
/// Returns a request for all books from a country
|
||||
/// Filters books by kind
|
||||
func filter(kind: Book.Kind) -> Self {
|
||||
filter(Book.Columns.kind == kind)
|
||||
}
|
||||
|
||||
/// Filters books from a country
|
||||
func filter(authorCountry: String) -> Self {
|
||||
// A book is from a country if it can be
|
||||
// joined with an author from that country:
|
||||
// ---------------------------v
|
||||
// Books do not have any country column. But their author has one.
|
||||
// A book is from a country if it can be joined to an author from this country:
|
||||
joining(required: Book.author.filter(country: authorCountry))
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.read { db in
|
||||
let italianBooks = try Book.all()
|
||||
let italianNovels: [Book] = try Book.all()
|
||||
.filter(kind: .novel)
|
||||
.filter(authorCountry: "Italy")
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
Not *every requests* can be expressed on `DerivableRequest`. For example, [Association Aggregates] are out of scope. When this happens, define your requests in a constrained extension to `QueryInterfaceRequest`:
|
||||
Extensions to the `DerivableRequest` protocol can not change the type of requests. This has to be expressed in an extension to `QueryInterfaceRequest`. For example:
|
||||
|
||||
```swift
|
||||
// More requests of Author -------------------------v
|
||||
// Author requests ~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
extension QueryInterfaceRequest where RowDecoder == Author {
|
||||
/// Returns a request for all authors with at least one book
|
||||
func havingBooks() -> QueryInterfaceRequest<Author> {
|
||||
having(Author.books.isEmpty == false)
|
||||
// Selects author ids
|
||||
func id() -> QueryInterfaceRequest<Int64> {
|
||||
select(Author.Columns.id)
|
||||
}
|
||||
}
|
||||
|
||||
// IDs of French authors
|
||||
let ids: [Int64] = try Author.all().filter(country: "France").id().fetchAll(db)
|
||||
```
|
||||
|
||||
Those requests defined on `QueryInterfaceRequest` still compose fluently:
|
||||
|
||||
```swift
|
||||
try dbQueue.read { db in
|
||||
let sortedFrenchAuthorsHavingBooks = try Author.all()
|
||||
.filter(country: "France")
|
||||
.havingBooks() // <-
|
||||
.orderByName()
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
Finally, when it happens that a request only makes sense when defined on the Record type itself, just go ahead and define a static method or property of your Record type:
|
||||
|
||||
```swift
|
||||
extension MySingletonRecord {
|
||||
/// The one any only record stored in the database
|
||||
static let shared = all().limit(1)
|
||||
}
|
||||
|
||||
let singleton = try dbQueue.read { db
|
||||
try MySingletonRecord.shared.fetchOne(db)
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Compose Records
|
||||
|
||||
We'd like to navigate from books to authors and vice-versa: we may want to know an author's books, or a book's author.
|
||||
@@ -358,7 +458,7 @@ Granted with primitive and derived record types, your application will load the
|
||||
let authorId = 123
|
||||
let authorInfo: AuthorInfo? = try dbQueue.read { db in
|
||||
let request = Author
|
||||
.filter(key: authorId)
|
||||
.filter(id: authorId)
|
||||
.including(all: Author.books)
|
||||
return try AuthorInfo.fetchOne(db, request)
|
||||
}
|
||||
@@ -374,7 +474,7 @@ Granted with primitive and derived record types, your application will load the
|
||||
let bookId = 123
|
||||
let bookInfo: BookInfo? = try dbQueue.read { db in
|
||||
let request = Book
|
||||
.filter(key: bookId)
|
||||
.filter(id: bookId)
|
||||
.including(required: Book.author)
|
||||
return try BookInfo.fetchOne(db, request)
|
||||
}
|
||||
@@ -411,7 +511,7 @@ Those properties provide an alternative way to feed our application:
|
||||
}
|
||||
let authorId = 123
|
||||
let authorInfo: AuthorInfo? = try dbQueue.read { db in
|
||||
guard let author = try Author.fetchOne(db, key: authorId) else {
|
||||
guard let author = try Author.fetchOne(db, id: authorId) else {
|
||||
return nil
|
||||
}
|
||||
let books = try author.books.fetchAll(db)
|
||||
@@ -430,7 +530,7 @@ Those properties provide an alternative way to feed our application:
|
||||
}
|
||||
let bookId = 123
|
||||
let bookInfo: BookInfo? = try dbQueue.read { db in
|
||||
guard let book = try Book.fetchOne(db, key: bookId) else {
|
||||
guard let book = try Book.fetchOne(db, id: bookId) else {
|
||||
return nil
|
||||
}
|
||||
guard let author = try book.author.fetchOne(db) else {
|
||||
@@ -472,7 +572,7 @@ class NaiveLibraryManager {
|
||||
func author(id: Int64) -> Author? {
|
||||
do {
|
||||
return try dbQueue.read { db in
|
||||
try Author.fetchOne(db, key: id)
|
||||
try Author.fetchOne(db, id: id)
|
||||
}
|
||||
} catch {
|
||||
return nil
|
||||
@@ -482,7 +582,7 @@ class NaiveLibraryManager {
|
||||
func book(id: Int64) -> Book? {
|
||||
do {
|
||||
return try dbQueue.read { db in
|
||||
try Book.fetchOne(db, key: id)
|
||||
try Book.fetchOne(db, id: id)
|
||||
}
|
||||
} catch {
|
||||
return nil
|
||||
@@ -531,13 +631,13 @@ class ImprovedLibraryManager {
|
||||
|
||||
func author(id: Int64) throws -> Author? {
|
||||
try dbQueue.read { db in
|
||||
try Author.fetchOne(db, key: id)
|
||||
try Author.fetchOne(db, id: id)
|
||||
}
|
||||
}
|
||||
|
||||
func book(id: Int64) throws -> Book? {
|
||||
try dbQueue.read { db in
|
||||
try Book.fetchOne(db, key: id)
|
||||
try Book.fetchOne(db, id: id)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -611,7 +711,7 @@ extension LibraryManager {
|
||||
|
||||
func bookInfo(bookId: Int64) throws -> BookInfo? {
|
||||
try dbQueue.read { db in
|
||||
guard let book = try Book.fetchOne(db, key: bookId) else {
|
||||
guard let book = try Book.fetchOne(db, id: bookId) else {
|
||||
return nil
|
||||
}
|
||||
guard let author = try book.author.fetchOne(db) else {
|
||||
@@ -631,7 +731,7 @@ extension LibraryManager {
|
||||
|
||||
func authorInfo(authorId: Int64) throws -> AuthorInfo? {
|
||||
try dbQueue.read { db in
|
||||
guard let author = try Author.fetchOne(db, key: authorId) else {
|
||||
guard let author = try Author.fetchOne(db, id: authorId) else {
|
||||
return nil
|
||||
}
|
||||
let books = try author.books.fetchAll(db)
|
||||
@@ -696,7 +796,6 @@ Instead, have a look at [Database Observation]:
|
||||
[Django]: https://docs.djangoproject.com/en/2.0/topics/db/
|
||||
[record protocols]: ../README.md#record-protocols-overview
|
||||
[Separation of Concerns]: https://en.wikipedia.org/wiki/Separation_of_concerns
|
||||
[Single Responsibility Principle]: https://en.wikipedia.org/wiki/Single_responsibility_principle
|
||||
[Single Source of Truth]: https://en.wikipedia.org/wiki/Single_source_of_truth
|
||||
[Divide and Conquer]: https://en.wikipedia.org/wiki/Divide_and_rule
|
||||
[Why Adopt GRDB?]: WhyAdoptGRDB.md
|
||||
@@ -713,6 +812,8 @@ Instead, have a look at [Database Observation]:
|
||||
[TransactionObserver]: ../README.md#transactionobserver-protocol
|
||||
[Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself
|
||||
[Persistable Record Types are Responsible for Their Tables]: #persistable-record-types-are-responsible-for-their-tables
|
||||
[Record Types Hide Intimate Database Details]: #record-types-hide-intimate-database-details
|
||||
[Singleton Records]: #singleton-records
|
||||
[Define Record Requests]: #define-record-requests
|
||||
[Compose Records]: #compose-records
|
||||
[How to Design Database Managers]: #how-to-design-database-managers
|
||||
@@ -727,3 +828,5 @@ Instead, have a look at [Database Observation]:
|
||||
[Codable Record]: ../README.md#codable-records
|
||||
[CodingKeys]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
|
||||
[Combine Support]: Combine.md
|
||||
[Value]: ../README.md#values
|
||||
[Identifiable]: https://developer.apple.com/documentation/swift/identifiable
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 498 KiB |
@@ -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.8/Structs/DatabaseMigrator.html) for more migrator methods.
|
||||
|
||||
|
||||
## The `eraseDatabaseOnSchemaChange` Option
|
||||
@@ -119,4 +119,26 @@ migrator.registerMigration("AddNotNullCheckOnName") { db in
|
||||
}
|
||||
```
|
||||
|
||||
## Asynchronous Migrations
|
||||
|
||||
`DatabaseMigrator` provides two ways to migrate a database in an asynchronous way.
|
||||
|
||||
The `asyncMigrate(_:completion:)` method:
|
||||
|
||||
```swift
|
||||
// Completes in a protected dispatch queue that can write in the database
|
||||
migrator.asyncMigrate(dbQueue, completion: { db, error in
|
||||
if let error = error {
|
||||
// Some error occurred during migrations
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
The `migratePublisher(_:receiveOn:)` [Combine](https://developer.apple.com/documentation/combine) publisher:
|
||||
|
||||
```swift
|
||||
// DatabasePublishers.Migrate
|
||||
let publisher = migrator.migratePublisher(dbQueue)
|
||||
```
|
||||
|
||||
This publisher completes on the main queue, unless you provide a specific [scheduler](https://developer.apple.com/documentation/combine/scheduler) to the `receiveOn` argument.
|
||||
@@ -8,16 +8,39 @@ configuration.prepareDatabase { db in
|
||||
}
|
||||
let dbQueue = DatabaseQueue(configuration: configuration)
|
||||
|
||||
try! dbQueue.inDatabase { db in
|
||||
struct Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
var score: Int
|
||||
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
|
||||
try db.execute(sql: "INSERT INTO player (name, score) VALUES (?, ?)", arguments: ["Arthur", 1000])
|
||||
try db.execute(sql: "INSERT INTO player (name, score) VALUES (?, ?)", arguments: ["Barbara", 1000])
|
||||
do {
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try player.insert(db)
|
||||
player = Player(id: nil, name: "Barbara", score: 100)
|
||||
try player.insert(db)
|
||||
}
|
||||
|
||||
let names = try String.fetchAll(db, sql: "SELECT name FROM player")
|
||||
print(names)
|
||||
do {
|
||||
let players = try Player.fetchAll(db)
|
||||
for player in players {
|
||||
print(player)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let count = try Player.fetchCount(db)
|
||||
print(count)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,632 @@
|
||||
Query Interface Organization
|
||||
============================
|
||||
|
||||
**The [query interface] is a Swift API that approximates the [SQLite SELECT query grammar](https://sqlite.org/lang_select.html) through a hierarchy of values and protocols.**
|
||||
|
||||
This document exposes its inner organization, so that you can leverage the most of those types and protocols when you want it.
|
||||
|
||||
In the diagram below, protocols are pale blue and have rounded corners, and standard types are grey rectangles. Solid arrows read "inherits from", and dashed arrows read "produces". Generic types are marked as such, as well as "PATs" (protocols with associated types).
|
||||
|
||||
<img src="https://github.com/groue/GRDB.swift/raw/development/Documentation/Images/QueryInterfaceOrganization2.png" width="100%">
|
||||
|
||||
Diagram items are described below:
|
||||
|
||||
- [Association]
|
||||
- [Column]
|
||||
- [ColumnExpression]
|
||||
- [DatabaseRegionConvertible]
|
||||
- [DatabaseValue]
|
||||
- [DatabaseValueConvertible]
|
||||
- [DerivableRequest]
|
||||
- [FetchRequest]
|
||||
- [Int, String, Date…]
|
||||
- [QueryInterfaceRequest]
|
||||
- [SQL]
|
||||
- [SQLExpression]
|
||||
- [SQLExpressible]
|
||||
- [SQLOrderingTerm]
|
||||
- [SQLOrdering]
|
||||
- [SQLRequest]
|
||||
- [SQLSelectable]
|
||||
- [SQLSelection]
|
||||
- [SQLSpecificExpressible]
|
||||
- [SQLSubquery]
|
||||
- [SQLSubqueryable]
|
||||
|
||||
---
|
||||
|
||||
### Association
|
||||
|
||||
`Association` is the protocol for all [associations]. It is adopted by `BelongsToAssociation`, `HasManyAssociation`, etc. It conforms to [DerivableRequest].
|
||||
|
||||
```swift
|
||||
protocol Association: DerivableRequest {
|
||||
associatedtype OriginRowDecoder
|
||||
func forKey(_ key: String) -> Self
|
||||
}
|
||||
```
|
||||
|
||||
Association has two sub-protocols:
|
||||
|
||||
```swift
|
||||
protocol AssociationToOne: Association { }
|
||||
protocol AssociationToMany: Association { }
|
||||
```
|
||||
|
||||
`AssociationToMany`, adopted by `HasManyAssociation` and `HasManyThroughAssociation`, leverages [association aggregates].
|
||||
|
||||
### Column
|
||||
|
||||
`Column` is the type for database columns. It conforms to [ColumnExpression].
|
||||
|
||||
```swift
|
||||
Column("name")
|
||||
Column("id")
|
||||
Column.rowID
|
||||
```
|
||||
|
||||
|
||||
### ColumnExpression
|
||||
|
||||
`ColumnExpression` is the protocol for database columns. It is adopted by [Column]. It conforms to [SQLSpecificExpressible].
|
||||
|
||||
```swift
|
||||
protocol ColumnExpression: SQLSpecificExpressible {
|
||||
/// The name of a database column.
|
||||
var name: String { get }
|
||||
}
|
||||
```
|
||||
|
||||
Columns can be used, for example, to query database rows:
|
||||
|
||||
```swift
|
||||
let row = try Row.fetchOne(db, sql: "SELECT 'Arthur' AS name")!
|
||||
let name: String = row[Column("name")] // "Arthur"
|
||||
```
|
||||
|
||||
Columns are special expressions that allow some optimizations and niceties:
|
||||
|
||||
- Database observation: When a request is limited to a known list of rowids in a database table, changes applied to other rows do not trigger the observation. GRDB needs column expressions in order to apply this optimization:
|
||||
|
||||
```swift
|
||||
// Optimized Observations
|
||||
ValueObservation.tracking { db in
|
||||
try Player.fetchOne(db, id: 1)
|
||||
// or
|
||||
try Player.filter(Column("id") == 1).fetchOne(db)
|
||||
}
|
||||
|
||||
// Non-optimized observations
|
||||
ValueObservation.tracking { db in
|
||||
try SQLRequest<Player>("SELECT * FROM player WHERE id = 1").fetchOne(db)
|
||||
// or
|
||||
try Player.filter(sql: "id = 1").fetchOne(db)
|
||||
}
|
||||
```
|
||||
|
||||
- SQL generation: when it generates SQL queries, GRDB appends `LIMIT 1` or not, depending on the primary key and unique indexes used on the queried table. GRDB needs column expressions in order to improve its SQL generation:
|
||||
|
||||
```swift
|
||||
// Nicer SQL
|
||||
// SELECT * FROM player WHERE id = 1
|
||||
try Player.fetchOne(db, id: 1)
|
||||
try Player.filter(Column("id") == 1).fetchOne(db)
|
||||
|
||||
// Less nice SQL
|
||||
// SELECT * FROM player WHERE id = 1 LIMIT 1
|
||||
try Player.filter(sql: "id = 1").fetchOne(db)
|
||||
```
|
||||
|
||||
### DatabaseRegionConvertible
|
||||
|
||||
`DatabaseRegionConvertible` is the protocol for observable requests. It is adopted by [FetchRequest].
|
||||
|
||||
```swift
|
||||
protocol DatabaseRegionConvertible {
|
||||
func databaseRegion(_ db: Database) throws -> DatabaseRegion
|
||||
}
|
||||
```
|
||||
|
||||
DatabaseRegionConvertible feeds [DatabaseRegionObservation], which tracks database transactions that impact a particular database region:
|
||||
|
||||
```swift
|
||||
let request = Player.all()
|
||||
let observation = DatabaseRegionObservation(tracking: request)
|
||||
let observer = try observation.start(in: dbQueue) { (db: Database) in
|
||||
print("Players were changed")
|
||||
}
|
||||
```
|
||||
|
||||
### DatabaseValue
|
||||
|
||||
`DatabaseValue` is the type for SQL values (integers, doubles, strings, blobs, and NULL). It conforms to [SQLSpecificExpressible].
|
||||
|
||||
You generally build a DatabaseValue from a [DatabaseValueConvertible] type:
|
||||
|
||||
```swift
|
||||
1.databaseValue
|
||||
"Hello".databaseValue
|
||||
DatabaseValue.null
|
||||
```
|
||||
|
||||
The query interface will sometimes not accept raw [SQLExpressible] values such as [Int, String, Date], etc. In this case, turn those values into DatabaseValue so that you leverage APIs that need [SQLSpecificExpressible]. For example:
|
||||
|
||||
```swift
|
||||
// SQL: firstName || ' ' || lastName
|
||||
let fullname = [
|
||||
Column("firstName"),
|
||||
" ".databaseValue,
|
||||
Column("lastName"),
|
||||
].joined(operator: .concat)
|
||||
```
|
||||
|
||||
### DatabaseValueConvertible
|
||||
|
||||
`DatabaseValueConvertible` is the protocol for types that can provide [DatabaseValue]: SQL integers, doubles, strings, blobs, and NULL. It is adopted by [Int, String, Date], etc. It conforms to [SQLExpressible] because all SQL values are SQL expressions.
|
||||
|
||||
```swift
|
||||
protocol DatabaseValueConvertible: SQLExpressible {
|
||||
/// Returns a value that can be stored in the database.
|
||||
var databaseValue: DatabaseValue { get }
|
||||
|
||||
/// Returns a value initialized from `dbValue`, if possible.
|
||||
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self?
|
||||
}
|
||||
```
|
||||
|
||||
### DerivableRequest
|
||||
|
||||
`DerivableRequest` is the protocol for query interface requests and associations that can be refined. It is adopted by [QueryInterfaceRequest] and [Association].
|
||||
|
||||
```swift
|
||||
protocol DerivableRequest: AggregatingRequest, FilteredRequest,
|
||||
JoinableRequest, OrderedRequest,
|
||||
SelectionRequest, TableRequest
|
||||
{
|
||||
func distinct() -> Self
|
||||
func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> Self
|
||||
}
|
||||
```
|
||||
|
||||
- `AggregatingRequest` provides grouping methods such as `groupByPrimaryKey()`
|
||||
- `FilteredRequest` provides filtering methods such as `filter(expression)` or `filter(id: value)`
|
||||
- `JoinableRequest` provides association methods such as `joining(required: association)` or `including(all: association)`
|
||||
- `OrderedRequest` provides ordering methods such as `order(ordering)` or `reversed()`
|
||||
- `SelectionRequest` provides selection methods such as `select(selection)` or `annotated(with: selection)`
|
||||
- `TableRequest` provides table targeting methods such as `aliased(tableAlias)`
|
||||
|
||||
DerivableRequest makes it possible to build reusable code snippets that apply to both requests and associations. You'll read more about it in the [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md) and [Associations](AssociationsBasics.md).
|
||||
|
||||
### FetchRequest
|
||||
|
||||
`FetchRequest` is the protocol for requests that can fetch. It is adopted by [QueryInterfaceRequest] and [SQLRequest]. It conforms to [SQLSubqueryable] and [DatabaseRegionConvertible].
|
||||
|
||||
```swift
|
||||
protocol FetchRequest: SQLSubqueryable, DatabaseRegionConvertible {
|
||||
/// The type that tells how fetched database rows should be interpreted.
|
||||
associatedtype RowDecoder
|
||||
|
||||
/// Returns a PreparedRequest that is ready to be executed.
|
||||
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
|
||||
|
||||
/// Returns the number of rows fetched by the request.
|
||||
func fetchCount(_ db: Database) throws -> Int
|
||||
}
|
||||
```
|
||||
|
||||
FetchRequest can fetch values from the database as long as its `RowDecoder` associated type is `Row`, a [DatabaseValueConvertible] type, or a [FetchableRecord] type.
|
||||
|
||||
```swift
|
||||
let row: Row? = try SQLRequest<Row>("SELECT * FROM player").fetchOne(db)
|
||||
let players: [Player] = try Player.all().fetchAll(db)
|
||||
```
|
||||
|
||||
FetchRequest usually executes a single SQL query:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player
|
||||
let request = Player.all()
|
||||
try request.fetchAll(db)
|
||||
```
|
||||
|
||||
This single SQL query is exposed through `makePreparedRequest(_:forSingleResult:)`:
|
||||
|
||||
```swift
|
||||
let request = Player.all()
|
||||
let preparedRequest = try request.makePreparedRequest(db)
|
||||
print(preparedRequest.statement.sql) // SELECT * FROM player
|
||||
```
|
||||
|
||||
But not all fetch requests execute a single SQL query. A [QueryInterfaceRequest] that involves [associations] can execute several:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player
|
||||
// SELECT * FROM award WHERE playerId IN (...)
|
||||
struct PlayerInfo: Decodable, FetchableRecord {
|
||||
var player: Player
|
||||
var awards: [Award]
|
||||
}
|
||||
let playerInfos = try Player
|
||||
.including(all: Player.awards)
|
||||
.asRequest(of: PlayerInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
Those supplementary SQL queries are an implementation detail of `PreparedRequest`, and are not currently exposed.
|
||||
|
||||
### Int, String, Date…
|
||||
|
||||
The basic value types conform to [DatabaseValueConvertible] so that they can feed database queries with [DatabaseValue]:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player WHERE name = 'O''Brien'
|
||||
// ~~~~~~~~~~
|
||||
Player.filter(Column("name") == "O'Brien")
|
||||
```
|
||||
|
||||
### QueryInterfaceRequest
|
||||
|
||||
`QueryInterfaceRequest` is the type of fetch requests built by the GRDB query builder. It conforms to [FetchRequest] and [DerivableRequest].
|
||||
|
||||
It is generic on the type of fetched values:
|
||||
|
||||
```swift
|
||||
struct PlayerInfo: Decodable, FetchableRecord {
|
||||
var player: Player
|
||||
var awards: [Award]
|
||||
}
|
||||
|
||||
// QueryInterfaceRequest<Player>
|
||||
let playerRequest = Player.all()
|
||||
|
||||
// QueryInterfaceRequest<String>
|
||||
let nameRequest = Player.select(Column("name"), as: String.self)
|
||||
|
||||
// QueryInterfaceRequest<PlayerInfo>
|
||||
let playerInfoRequest = Player
|
||||
.including(all: Player.awards)
|
||||
.asRequest(of: PlayerInfo.self)
|
||||
|
||||
try playerRequest.fetchAll(db) // [Player]
|
||||
try nameRequest.fetchAll(db) // [String]
|
||||
try playerInfoRequest.fetchAll(db) // [PlayerInfo]
|
||||
```
|
||||
|
||||
For more information on QueryInterfaceRequest, see [Requests](../README.md#requests) and [Associations](AssociationsBasics.md).
|
||||
|
||||
### SQL
|
||||
|
||||
`SQL` is the type for SQL literals that support [SQL Interpolation]. It can feed all GRDB APIs that have a `literal` argument:
|
||||
|
||||
```swift
|
||||
let literal: SQL = "SELECT * FROM player"
|
||||
let request = SQLRequest<Player>(literal: literal)
|
||||
let players: [Player] = try request.fetchAll(db)
|
||||
```
|
||||
|
||||
`SQL` conforms to [SQLSpecificExpressible], and thus behaves as an [SQLite expression](https://sqlite.org/syntax/expr.html) by default:
|
||||
|
||||
```swift
|
||||
let literal: SQL = "name = \("O'Brien")"
|
||||
let request = Player.filter(literal)
|
||||
let players: [Player] = try request.fetchAll(db)
|
||||
```
|
||||
|
||||
:warning: **Warning**: Not all SQL snippets are expressions. It is not recommended to pass `SQL` literals around, or you may end up forgetting their content, and eventually generate invalid SQL. When possible, prefer building an explicit [SQLExpression], [SQLOrdering], [SQLSelection], [SQLRequest], or [SQLSubquery], depending on what you want to express:
|
||||
|
||||
```swift
|
||||
// SQLExpression
|
||||
SQL("name = \("O'Brien")").sqlExpression
|
||||
|
||||
// SQLOrdering
|
||||
SQL("name DESC)").sqlOrdering
|
||||
|
||||
// SQLSelection
|
||||
SQL("score + bonus AS total)").sqlSelection
|
||||
SQL("*").sqlSelection
|
||||
|
||||
// SQLRequest
|
||||
SQLRequest<Player>(literal: "SELECT * FROM player")
|
||||
|
||||
// SQLSubquery
|
||||
SQLRequest(literal: "SELECT * FROM player").sqlSubquery
|
||||
```
|
||||
|
||||
### SQLExpression
|
||||
|
||||
`SQLExpression` is the opaque type for all [SQLite expressions](https://sqlite.org/syntax/expr.html). It adopts [SQLSpecificExpressible], and is built from [SQLExpressible].
|
||||
|
||||
```swift
|
||||
struct SQLExpression: SQLSpecificExpressible {
|
||||
// opaque implementation
|
||||
}
|
||||
```
|
||||
|
||||
Functions and methods that build an SQL expression should return an SQLExpression value:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player WHERE LENGTH(name) > 0
|
||||
let expression = length(Column("name")) > 0 // SQLExpression
|
||||
Player.filter(expression)
|
||||
```
|
||||
|
||||
When it looks like GRDB APIs are unable to build a particular expression, use [SQL]:
|
||||
|
||||
```swift
|
||||
func date(_ value: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQL("DATE(\(value))").sqlExpression
|
||||
}
|
||||
|
||||
// SELECT * FROM player WHERE DATE(createdAt) = '2020-01-23'
|
||||
let request = Player.filter(date(Column("createdAt")) == "2020-01-23")
|
||||
```
|
||||
|
||||
This technique, based on [SQL Interpolation], is composable and works well even when several tables are involved. See how the `createdAt` column below is correctly attributed to the `player` table:
|
||||
|
||||
```swift
|
||||
// SELECT player.*, team.* FROM player
|
||||
// JOIN team ON team.id = player.teamId
|
||||
// WHERE DATE(player.createdAt) = '2020-01-23'
|
||||
let request = Player
|
||||
.filter(date(Column("createdAt")) == "2020-01-23")
|
||||
.including(required: Player.team)
|
||||
```
|
||||
|
||||
### SQLExpressible
|
||||
|
||||
`SQLExpressible` is the protocol for all [SQLite expressions](https://sqlite.org/syntax/expr.html). It is adopted by [Column], [SQL], [SQLExpression], and also [Int, String, Date], etc. It has an `sqlExpression` property which returns an [SQLExpression].
|
||||
|
||||
```swift
|
||||
protocol SQLExpressible {
|
||||
var sqlExpression: SQLExpression { get }
|
||||
}
|
||||
```
|
||||
|
||||
SQLExpressible-conforming types include types which are not directly related to SQL, such as [Int, String, Date], etc. Because of this, SQLExpressible has limited powers that prevent misuses and API pollution. For full-fledged SQL expressions, see [SQLSpecificExpressible]. For example, compare:
|
||||
|
||||
```swift
|
||||
Player.filter(1) // Compiler warning (will become an error in the next major release)
|
||||
Player.select(1) // Compiler error
|
||||
Player.order("name") // Compiler error
|
||||
length("name") // Compiler error
|
||||
"name".desc // Compiler error
|
||||
```
|
||||
|
||||
```swift
|
||||
Player.filter(id: 1) // OK
|
||||
Player.filter(1.databaseValue) // Odd, but OK
|
||||
Player.select(1.databaseValue) // Odd, but OK
|
||||
Player.order(Column("name")) // OK
|
||||
length(Column("name")) // OK
|
||||
Column("name").desc // OK
|
||||
```
|
||||
|
||||
### SQLOrderingTerm
|
||||
|
||||
`SQLOrderingTerm` is the protocol for all [SQLite ordering terms](https://sqlite.org/syntax/ordering-term.html). It is adopted by [SQLSpecificExpressible]. It has an `sqlOrdering` property which returns an [SQLOrdering].
|
||||
|
||||
```swift
|
||||
protocol SQLOrderingTerm {
|
||||
var sqlOrdering: SQLOrdering { get }
|
||||
}
|
||||
```
|
||||
|
||||
SQLOrderingTerm feeds the `order()` method of the query interface:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player
|
||||
// ORDER BY score DESC, name COLLATE ...
|
||||
Player.order(
|
||||
Column("score").desc,
|
||||
Column("name").collating(.localizedCaseInsensitiveCompare))
|
||||
```
|
||||
|
||||
All [SQLSpecificExpressible] values are ordering terms. [SQLExpressible] values are not: `Player.order("name")` does not compile. Instead, use:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player ORDER BY name -- Order according to a column
|
||||
Player.order(Column("name"))
|
||||
|
||||
// SELECT * FROM player ORDER BY 'name' -- Order according to a constant string (why not)
|
||||
Player.order("name".databaseValue)
|
||||
```
|
||||
|
||||
### SQLOrdering
|
||||
|
||||
`SQLOrdering` is the opaque type for all [SQLite ordering terms](https://sqlite.org/syntax/ordering-term.html). An SQLOrdering adopts and is built from [SQLOrderingTerm].
|
||||
|
||||
```swift
|
||||
struct SQLOrdering: SQLOrderingTerm {
|
||||
// opaque implementation
|
||||
}
|
||||
```
|
||||
|
||||
Functions and methods that build ordering terms should return an SQLOrdering value:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player ORDER BY score DESC
|
||||
let ordering = Column("score").desc // SQLOrdering
|
||||
Player.order(ordering)
|
||||
```
|
||||
|
||||
To build an SQLOrdering without applying any `DESC` or `ASC` qualifier, use `sqlOrdering` (from [SQLOrderingTerm], inherited by [SQLSpecificExpressible], [ColumnExpression]...):
|
||||
|
||||
```swift
|
||||
let ordering = Column("score").sqlOrdering // SQLOrdering
|
||||
```
|
||||
|
||||
### SQLRequest
|
||||
|
||||
`SQLRequest` is the type of fetch requests expressed with raw SQL. It conforms to [FetchRequest].
|
||||
|
||||
It is generic on the type of fetched values (which defaults to `Row`):
|
||||
|
||||
```swift
|
||||
let rowRequest = SQLRequest(sql: "SELECT * FROM player") // SQLRequest<Row>
|
||||
let playerRequest = SQLRequest<Player>(sql: "SELECT * FROM player") // SQLRequest<Player>
|
||||
let nameRequest = SQLRequest<String>(sql: "SELECT name FROM player") // SQLRequest<String>
|
||||
|
||||
try rowRequest.fetchAll(db) // [Row]
|
||||
try playerRequest.fetchAll(db) // [Player]
|
||||
try nameRequest.fetchAll(db) // [String]
|
||||
|
||||
try rowRequest.fetchOne(db) // Row?
|
||||
try playerRequest.fetchOne(db) // Player?
|
||||
try nameRequest.fetchOne(db) // String?
|
||||
```
|
||||
|
||||
SQLRequest supports [SQL Interpolation]:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player WHERE name = 'O''Brien'
|
||||
let playerRequest: SQLRequest<Player> = """
|
||||
SELECT * FROM player WHERE name = \("O'Brien")
|
||||
"""
|
||||
```
|
||||
|
||||
### SQLSelectable
|
||||
|
||||
`SQLSelectable` is the protocol for all [SQLite result columns](https://sqlite.org/syntax/result-column.html). It is adopted by [SQLSpecificExpressible]. It has an `sqlSelection` property which returns an [SQLSelection].
|
||||
|
||||
```swift
|
||||
protocol SQLSelectable {
|
||||
var sqlSelection: SQLSelection { get }
|
||||
}
|
||||
```
|
||||
|
||||
SQLSelectable feeds the `select()` method of the query interface:
|
||||
|
||||
```swift
|
||||
Player.select(AllColumns())
|
||||
Player.select(Column("name"), Column("score"))
|
||||
```
|
||||
|
||||
All [SQLSpecificExpressible] values are selectable. Other selectable values are:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player
|
||||
Player.select(AllColumns())
|
||||
|
||||
// SELECT MAX(score) AS maxScore FROM player
|
||||
Player.select(max(Column("score")).forKey("maxScore"))
|
||||
```
|
||||
|
||||
[SQLExpressible] values are not selectable: `Player.select("name")` does not compile. Instead, use:
|
||||
|
||||
```swift
|
||||
// SELECT name FROM player -- Selects a column
|
||||
Player.select(Column("name"))
|
||||
|
||||
// SELECT 'name' FROM player -- Selects a constant string (why not)
|
||||
Player.select("name".databaseValue)
|
||||
```
|
||||
|
||||
### SQLSelection
|
||||
|
||||
`SQLSelection` is the opaque type for all [SQLite result columns](https://sqlite.org/syntax/result-column.html). An SQLSelection adopts and is built from [SQLSelectable].
|
||||
|
||||
```swift
|
||||
struct SQLSelection: SQLSelectable {
|
||||
// opaque implementation
|
||||
}
|
||||
```
|
||||
|
||||
Functions and methods that build result columns should return an SQLSelection value:
|
||||
|
||||
```swift
|
||||
// SELECT (score + bonus) AS total
|
||||
let selection = (Column("score") + Column("bonus")).forKey("total") // SQLSelection
|
||||
Player.select(selection)
|
||||
```
|
||||
|
||||
### SQLSpecificExpressible
|
||||
|
||||
`SQLSpecificExpressible` is the protocol for all SQL expressions, except values such as [Int, String, Date], etc. It conforms to [SQLExpressible], [SQLSelectable], and [SQLOrderingTerm]. It is adopted by [Column], [SQL], and [SQLExpression]. It is also adopted through [SQLSubqueryable] by [QueryInterfaceRequest] and [SQLRequest].
|
||||
|
||||
```swift
|
||||
protocol SQLSpecificExpressible: SQLExpressible, SQLSelectable, SQLOrderingTerm { }
|
||||
```
|
||||
|
||||
Use SQLSpecificExpressible when you want to operate on expressions, except [Int, String, Date] and other types which are not directly related to SQL. For example, the built-in `length(_:)` GRDB function accepts SQLSpecificExpressible:
|
||||
|
||||
```swift
|
||||
/// The LENGTH SQL function
|
||||
func length(_ value: SQLSpecificExpressible) -> SQLExpression { ... }
|
||||
|
||||
length(Column("name")) // OK
|
||||
length("name") // Compiler error
|
||||
```
|
||||
|
||||
### SQLSubquery
|
||||
|
||||
`SQLSubquery` is the opaque type for all [SQLite SELECT queries](https://sqlite.org/syntax/select-stmt.html). An SQLSubquery adopts and is built from [SQLSubqueryable].
|
||||
|
||||
```swift
|
||||
struct SQLSubquery: SQLSubqueryable {
|
||||
// opaque implementation
|
||||
}
|
||||
```
|
||||
|
||||
### SQLSubqueryable
|
||||
|
||||
`SQLSubqueryable` is the protocol for all [SQLite SELECT queries](https://sqlite.org/syntax/select-stmt.html). It conforms to [SQLSpecificExpressible], and is adopted by [FetchRequest], [QueryInterfaceRequest], [SQLRequest]. It has an `sqlSubquery` property which returns an [SQLSubquery].
|
||||
|
||||
```swift
|
||||
protocol SQLSubqueryable: SQLSpecificExpressible {
|
||||
var sqlSubquery: SQLSubquery { get }
|
||||
}
|
||||
```
|
||||
|
||||
SQLSubqueryable provides the GRDB support for subqueries. Its [SQLSpecificExpressible] facet lets you use any request as an expression:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player
|
||||
// WHERE score >= (SELECT AVG(score) FROM player)
|
||||
let averageScore = Player.select(average(Column("score")))
|
||||
Player.filter(Column("score") >= averageScore)
|
||||
```
|
||||
|
||||
SQLSubqueryable has the `contains(_:)` and `exists()` methods that support the `value IN (subquery)` and `EXISTS (subquery)` expressions.
|
||||
|
||||
Use SQLSubqueryable in order to define a function that requires a subquery argument:
|
||||
|
||||
```swift
|
||||
func myRequest(_ nameSubquery: SQLSubqueryable) -> SQLRequest<Player> {
|
||||
"""
|
||||
SELECT * FROM player
|
||||
WHERE name IN (\(nameSubquery) UNION ...)
|
||||
"""
|
||||
}
|
||||
|
||||
myRequest(SQLRequest("SELECT ..."))
|
||||
myRequest(Player.select(...).filter(...))
|
||||
```
|
||||
|
||||
[Association]: #association
|
||||
[associations]: AssociationsBasics.md
|
||||
[association aggregates]: AssociationsBasics.md#association-aggregates
|
||||
[Column]: #column
|
||||
[ColumnExpression]: #columnexpression
|
||||
[DatabaseRegionConvertible]: #databaseregionconvertible
|
||||
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
|
||||
[DatabaseValue]: #databasevalue
|
||||
[DatabaseValueConvertible]: #databasevalueconvertible
|
||||
[DerivableRequest]: #derivablerequest
|
||||
[FetchableRecord]: ../README.md#fetchablerecord-protocol
|
||||
[FetchRequest]: #fetchrequest
|
||||
[Int, String, Date…]: #int-string-date
|
||||
[Int, String, Date]: #int-string-date
|
||||
[query interface]: ../README.md#the-query-interface
|
||||
[QueryInterfaceRequest]: #queryinterfacerequest
|
||||
[SQL]: #sql
|
||||
[SQL Interpolation]: SQLInterpolation.md
|
||||
[SQLExpression]: #sqlexpression
|
||||
[SQLExpressible]: #sqlexpressible
|
||||
[SQLOrderingTerm]: #sqlorderingterm
|
||||
[SQLOrdering]: #sqlordering
|
||||
[SQLRequest]: #sqlrequest
|
||||
[SQLSelectable]: #sqlselectable
|
||||
[SQLSelection]: #sqlselection
|
||||
[SQLSpecificExpressible]: #sqlspecificexpressible
|
||||
[SQLSubquery]: #sqlsubquery
|
||||
[SQLSubqueryable]: #sqlsubqueryable
|
||||
@@ -22,7 +22,7 @@ try dbQueue.write { db in
|
||||
SQL Interpolation is an answer to these troubles. It is available in Swift 5.
|
||||
|
||||
- [Introduction]
|
||||
- [SQLLiteral]
|
||||
- [SQL Literal]
|
||||
- [SQL Interpolation and the Query Interface]
|
||||
- [SQL Interpolation and Record Protocols]
|
||||
- [SQL Interpolation Reference]
|
||||
@@ -73,38 +73,38 @@ Plain SQL strings are indeed still available, and SQL interpolation only kicks i
|
||||
```
|
||||
|
||||
|
||||
## SQLLiteral
|
||||
## SQL Literal
|
||||
|
||||
**SQLLiteral** is the type that looks like a plain String, but profits from SQL interpolation:
|
||||
**`SQL`** is the type that looks like a plain String, but profits from SQL interpolation:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
try db.execute(literal: query)
|
||||
}
|
||||
```
|
||||
|
||||
**SQLLiteral is not a Swift String.** You can not use the `execute(literal:)` method with a String argument:
|
||||
**`SQL` is not a Swift String.** You can not use the `execute(literal:)` method with a String argument:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
let query = "UPDATE player SET name = \(name) WHERE id = \(id)" // a regular String
|
||||
// Compiler error:
|
||||
// Cannot convert value of type 'String' to expected argument type 'SQLLiteral'
|
||||
// Cannot convert value of type 'String' to expected argument type 'SQL'
|
||||
try db.execute(literal: query)
|
||||
}
|
||||
```
|
||||
|
||||
SQLLiteral can build your queries step by step, with regular operators and methods:
|
||||
`SQL` can build your queries step by step, with regular operators and methods:
|
||||
|
||||
```swift
|
||||
// +, +=, append
|
||||
var query: SQLLiteral = "UPDATE player "
|
||||
var query: SQL = "UPDATE player "
|
||||
query += "SET name = \(name) "
|
||||
query.append(literal: "WHERE id = \(id)")
|
||||
|
||||
// joined(), joined(separator:)
|
||||
let components: [SQLLiteral] = [
|
||||
let components: [SQL] = [
|
||||
"UPDATE player",
|
||||
"SET name = \(name)",
|
||||
"WHERE id = \(id)"
|
||||
@@ -115,7 +115,7 @@ let query = components.joined(separator: " ")
|
||||
Extract the plain SQL string from a literal:
|
||||
|
||||
```swift
|
||||
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
let (sql, arguments) = try dbQueue.read(query.build)
|
||||
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
|
||||
print(arguments) // prints ["O'Brien", 42]
|
||||
@@ -124,17 +124,17 @@ print(arguments) // prints ["O'Brien", 42]
|
||||
Build a literal from a plain SQL string:
|
||||
|
||||
```swift
|
||||
let query = SQLLiteral(
|
||||
let query = SQL(
|
||||
sql: "UPDATE player SET name = ? WHERE id = ?",
|
||||
arguments: [name, id])
|
||||
```
|
||||
|
||||
SQLLiteral can embed any [value], as we have seen above, but not only. Please keep on reading the next chapter, or jump directly to the [SQL Interpolation Reference].
|
||||
`SQL` can embed any [value], as we have seen above, but not only. Please keep on reading the next chapter, or jump directly to the [SQL Interpolation Reference].
|
||||
|
||||
|
||||
## SQL Interpolation and the Query Interface
|
||||
|
||||
SQL Interpolation and SQLLiteral let you embed raw SQL snippets in [query interface requests].
|
||||
SQL Interpolation and `SQL` let you embed raw SQL snippets in [query interface requests].
|
||||
|
||||
For example:
|
||||
|
||||
@@ -143,25 +143,37 @@ For example:
|
||||
let request = Player.filter(literal: "name = \("O'Brien")")
|
||||
```
|
||||
|
||||
You can also build literal expressions from other expressions. For example, let's call the `DATE` SQLite function on a query interface column:
|
||||
You can also build literals from other expressions. For example, let's call the `DATE` SQLite function on a query interface column:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23'
|
||||
// SELECT * FROM player WHERE DATE(createdAt) = '2020-01-23'
|
||||
let createdAt = Column("createdAt")
|
||||
let creationDay = SQLLiteral("DATE(\(createdAt))").sqlExpression
|
||||
let creationDay = SQL("DATE(\(createdAt))")
|
||||
let request = Player.filter(creationDay == "2020-01-23")
|
||||
```
|
||||
|
||||
Such literal expressions can be returned by Swift functions:
|
||||
Such literals play well with the query interface, even when several tables are involved with [associations](AssociationsBasics.md):
|
||||
|
||||
```swift
|
||||
func date(_ value: SQLExpressible) -> SQLExpression {
|
||||
SQLLiteral("DATE(\(value))").sqlExpression
|
||||
// SELECT player.*, team.*
|
||||
// FROM player
|
||||
// JOIN team ON team.id = player.teamID
|
||||
// WHERE DATE(player.createdAt) = '2020-01-23'
|
||||
// ~~~~~~~~~~~~~~~~~~~~~~
|
||||
// automatic table disambiguation
|
||||
let request = Player
|
||||
.filter(creationDay == "2020-01-23")
|
||||
.including(required: Player.team)
|
||||
```
|
||||
|
||||
This allows you to define Swift functions that you can use in all circumstances:
|
||||
|
||||
```swift
|
||||
func date(_ expression: SQLExpressible) -> SQLExpression {
|
||||
SQL("DATE(\(expression))").sqlExpression
|
||||
}
|
||||
|
||||
// SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23'
|
||||
let createdAt = Column("createdAt")
|
||||
let request = Player.filter(date(createdAt) == "2020-01-23")
|
||||
let request = Player.filter(date(Column("createdAt")) == "2020-01-23")
|
||||
```
|
||||
|
||||
|
||||
@@ -334,7 +346,7 @@ Let's extend Player with database methods.
|
||||
extension Player: Decodable, FetchableRecord, TableRecord {
|
||||
/// A complex request
|
||||
static func complexRequest() -> SQLRequest<Player> {
|
||||
let query: SQLLiteral = "SELECT \(columnsOf: self) "
|
||||
let query: SQL = "SELECT \(columnsOf: self) "
|
||||
query += "FROM \(self) "
|
||||
query += "JOIN \(Team.self) ON ..."
|
||||
query += "GROUP BY ..."
|
||||
@@ -343,7 +355,7 @@ Let's extend Player with database methods.
|
||||
}
|
||||
```
|
||||
|
||||
This last request shows how to build an SQLRequest from an [SQLLiteral]. You will need SQLLiteral when the request can not be written in a single stroke.
|
||||
This last request shows how to build an SQLRequest from an [SQL Literal]. You will need `SQL` when the request can not be written in a single stroke.
|
||||
|
||||
|
||||
|
||||
@@ -431,7 +443,7 @@ This chapter lists all kinds of supported interpolations.
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player WHERE score = (SELECT MAX(score) FROM player)
|
||||
let subquery: SQLRequest<Int> = "SELECT MAX(score) FROM player"
|
||||
let subquery = SQLRequest("SELECT MAX(score) FROM player")
|
||||
"SELECT * FROM player WHERE score = (\(subquery))"
|
||||
|
||||
// SELECT * FROM player WHERE score = (SELECT MAX(score) FROM player)
|
||||
@@ -449,11 +461,11 @@ This chapter lists all kinds of supported interpolations.
|
||||
"WITH \(definitionFor: cte) SELECT * FROM \(cte)"
|
||||
```
|
||||
|
||||
- SQLLiteral:
|
||||
- `SQL` literal:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player WHERE name = 'O''Brien'
|
||||
let condition: SQLLiteral = "name = \("O'Brien")"
|
||||
let condition: SQL = "name = \("O'Brien")"
|
||||
"SELECT * FROM player WHERE \(literal: condition)"
|
||||
```
|
||||
|
||||
@@ -468,7 +480,7 @@ This chapter lists all kinds of supported interpolations.
|
||||
```
|
||||
|
||||
[Introduction]: #introduction
|
||||
[SQLLiteral]: #sqlliteral
|
||||
[SQL Literal]: #sql-literal
|
||||
[SQL Interpolation and the Query Interface]: #sql-interpolation-and-the-query-interface
|
||||
[SQL Interpolation and Record Protocols]: #sql-interpolation-and-record-protocols
|
||||
[SQL Interpolation Reference]: #sql-interpolation-reference
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
Single-Row Tables
|
||||
=================
|
||||
|
||||
Let's talk about database tables that should contain a single row.
|
||||
|
||||
Such tables can store configuration values, user preferences, and generally some global application state. They are a suitable alternative to `UserDefaults` in some applications, especially when configuration refers to values found in other database tables, and database integrity is a concern.
|
||||
|
||||
An alternative way to store such configuration is a table of key-value pairs: two columns, and one row for each configuration value. This technique works, but it has a few drawbacks: you will have to deal with the various types of configuration values (strings, integers, dates, etc), and you won't be able to define foreign keys. This is why we won't explore key-value tables.
|
||||
|
||||
This guide helps you implementing a single-row table with GRDB, with recommendations on the database schema, migrations, and the design of a matching [record] type.
|
||||
|
||||
- [The Single-Row Table]
|
||||
- [The Single-Row Record]
|
||||
- [Wrap-Up]
|
||||
|
||||
|
||||
## The Single-Row Table
|
||||
|
||||
As always with GRDB, everything starts at the level of the database schema. Putting the robust SQLite on our side is always a good idea, because we have to write less code, and this helps shipping less bugs.
|
||||
|
||||
We want to instruct SQLite that our table must never contain more than one row. We will never have to wonder what to do if we were unlucky enough to find two rows with conflicting values in this table.
|
||||
|
||||
SQLite is not able to guarantee that the table is never empty, so we have to deal with two cases: either the table is empty, or it contains one row.
|
||||
|
||||
Those two cases can create a nagging question for the application. By default, inserts fail when the row already exists, and updates fail when the table is empty. In order to avoid those errors, we will have the app perform an insert in case of a failed update (in the [The Single-Row Record] chapter). And we instruct SQLite to just replace the eventual existing row in case of conflicting inserts:
|
||||
|
||||
```swift
|
||||
// CREATE TABLE appConfiguration (
|
||||
// id INTEGER PRIMARY KEY ON CONFLICT REPLACE CHECK (id = 1),
|
||||
// flag BOOLEAN NOT NULL,
|
||||
// ...)
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// Single row guarantee
|
||||
t.column("id", .integer)
|
||||
// Have inserts replace the existing row
|
||||
.primaryKey(onConflict: .replace)
|
||||
// Make sure the id column is always 1
|
||||
.check { $0 == 1 }
|
||||
|
||||
// The configuration colums
|
||||
t.column("flag", .boolean).notNull()
|
||||
// ... other columns
|
||||
}
|
||||
```
|
||||
|
||||
When you use [migrations], you may wonder if it is a good idea or not to perform an initial insert just after the table is created. Well, this is not recommended:
|
||||
|
||||
```swift
|
||||
// NOT RECOMMENDED
|
||||
migrator.registerMigration("appConfiguration") { db in
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// Single row guarantee
|
||||
t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 }
|
||||
|
||||
// Define sensible defaults for each column
|
||||
t.column("flag", .boolean).notNull()
|
||||
.defaults(to: false)
|
||||
// ... other columns
|
||||
}
|
||||
|
||||
// Populate the table
|
||||
try db.execute(sql: "INSERT INTO appConfiguration DEFAULT VALUES")
|
||||
}
|
||||
```
|
||||
|
||||
It is not a good idea to populate the table in a migration, for two reasons:
|
||||
|
||||
1. This is not a hard guarantee that the table will never be empty. As a consequence, this won't prevent your Swift code from dealing with the possibility of a missing row. On top of that, the Swift code that deals with the missing row may not use the same default values as the SQLite schema (a [DRY] violation), with unclear consequences.
|
||||
|
||||
2. Migrations that are shipped in the wild should *never* change, because you want to control the state of the databases installed on your users' devices, regardless of the application version they install first, regardless of how many application versions are skipped when they download an upgrade, etc. By inserting an initial row in a migration, you make it difficult for your application to adjust the sensible default values in the future, while keeping a clear idea of the various installation and upgrade scenarios.
|
||||
|
||||
The recommended migration creates the table, nothing more:
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
migrator.registerMigration("appConfiguration") { db in
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// Single row guarantee
|
||||
t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 }
|
||||
|
||||
// The configuration colums
|
||||
t.column("flag", .boolean).notNull()
|
||||
// ... other columns
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## The Single-Row Record
|
||||
|
||||
Now that the database schema has been defined, we can define the [record] type that will help the application access the single row:
|
||||
|
||||
```swift
|
||||
struct AppConfiguration: Codable {
|
||||
// Support for the single row guarantee
|
||||
private var id = 1
|
||||
|
||||
// The configuration properties
|
||||
var flag: Bool
|
||||
// ... other properties
|
||||
}
|
||||
```
|
||||
|
||||
In case the database table would be empty, we need a default configuration:
|
||||
|
||||
```swift
|
||||
extension AppConfiguration {
|
||||
/// The default configuration
|
||||
static let `default` = AppConfiguration(flag: false, ...)
|
||||
}
|
||||
```
|
||||
|
||||
We make our record able to access the database:
|
||||
|
||||
```swift
|
||||
extension AppConfiguration: FetchableRecord, PersistableRecord {
|
||||
```
|
||||
|
||||
We have seen in the [The Single-Row Table] chapter that by default, updates throw an error if the database table is empty. To avoid this error, we instruct GRDB to perform an insert in case of a failed update (see [Persistence Methods] for more information):
|
||||
|
||||
```swift
|
||||
// Customize the default PersistableRecord behavior
|
||||
func update(_ db: Database, columns: Set<String>) throws {
|
||||
do {
|
||||
try performUpdate(db, columns: columns)
|
||||
} catch PersistenceError.recordNotFound {
|
||||
// No row was updated: perform an insert
|
||||
try performInsert(db)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The standard GRDB method `fetchOne` returns an optional which is nil when the database table is empty. As a convenience, let's define a method that returns a non-optional (replacing the missing row with `default`):
|
||||
|
||||
```swift
|
||||
/// Returns the persisted configuration, or the default one if the
|
||||
/// database table is empty.
|
||||
static func fetch(_ db: Database) throws -> AppConfiguration {
|
||||
try fetchOne(db) ?? .default
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And that's it! Now we can use our singleton record:
|
||||
|
||||
```swift
|
||||
// READ
|
||||
let config = try dbQueue.read { db in
|
||||
try AppConfiguration.fetch(db)
|
||||
}
|
||||
if config.flag {
|
||||
// ...
|
||||
}
|
||||
|
||||
// WRITE
|
||||
try dbQueue.write { db in
|
||||
var config = try AppConfiguration.fetch(db)
|
||||
|
||||
// Update some config values
|
||||
try config.updateChanges(db) {
|
||||
$0.flag = true
|
||||
}
|
||||
|
||||
// Other possible ways to write config:
|
||||
try config.update(db)
|
||||
try config.save(db)
|
||||
try config.insert(db)
|
||||
}
|
||||
```
|
||||
|
||||
The three `update`, `save` and `insert` methods can be used interchangeably: all three make sure the configuration is stored in the database.
|
||||
|
||||
The `updateChanges` method only updates the values changed by its closure argument (and performs an insert if the database table is empty).
|
||||
|
||||
See [Persistence Methods] for more information.
|
||||
|
||||
|
||||
## Wrap-Up
|
||||
|
||||
We all love to copy and paste, don't we? Just customize the template code below:
|
||||
|
||||
```swift
|
||||
// Table creation
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// Single row guarantee
|
||||
t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 }
|
||||
|
||||
// The configuration columns
|
||||
t.column("flag", .boolean).notNull()
|
||||
// ... other columns
|
||||
}
|
||||
```
|
||||
|
||||
```swift
|
||||
//
|
||||
// AppConfiguration.swift
|
||||
//
|
||||
|
||||
import GRDB
|
||||
|
||||
struct AppConfiguration: Codable {
|
||||
// Support for the single row guarantee
|
||||
private var id = 1
|
||||
|
||||
// The configuration properties
|
||||
var flag: Bool
|
||||
// ... other properties
|
||||
}
|
||||
|
||||
extension AppConfiguration {
|
||||
/// The default configuration
|
||||
static let `default` = AppConfiguration(flag: false, ...)
|
||||
}
|
||||
|
||||
// Database Access
|
||||
extension AppConfiguration: FetchableRecord, PersistableRecord {
|
||||
// Customize the default PersistableRecord behavior
|
||||
func update(_ db: Database, columns: Set<String>) throws {
|
||||
do {
|
||||
try performUpdate(db, columns: columns)
|
||||
} catch PersistenceError.recordNotFound {
|
||||
// No row was updated: perform an insert
|
||||
try performInsert(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the persisted configuration, or the default one if the
|
||||
/// database table is empty.
|
||||
static func fetch(_ db: Database) throws -> AppConfiguration {
|
||||
try fetchOne(db) ?? .default
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
[migrations]: Migrations.md
|
||||
[record]: ../README.md#records
|
||||
[The Single-Row Table]: #the-single-row-table
|
||||
[The Single-Row Record]: #the-single-row-record
|
||||
[Wrap-Up]: #wrap-up
|
||||
[DRY]: https://en.wikipedia.org/wiki/Don%27t_repeat_yourself
|
||||
[Persistence Methods]: ../README.md#persistence-methods
|
||||
@@ -1,956 +0,0 @@
|
||||
Tutorial: Building a Database Access Layer
|
||||
==========================================
|
||||
|
||||
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBDemoiOS/Screenshot.png" width="50%">
|
||||
|
||||
**This tutorial builds and explains a database access layer for a UIKit or SwiftUI application**. See the [demo applications] for sample code.
|
||||
|
||||
The target audience has basic database knowledge, and knows what tables and columns are. The tutorial visits high-level GRDB features: record types, query interface, database observation. Raw SQL is also provided, so that you can choose your favorite way to use SQLite.
|
||||
|
||||
The setup of Xcode projects, view controllers, or SwiftUI is not discussed. Refer to the demo apps for sample code.
|
||||
|
||||
When you want an explanation about some particular recommendation or piece of code, expand the design notes marked with an ℹ️.
|
||||
|
||||
As you can see in the [screenshot], the demo application displays the list of players stored in the database. The application user can sort players by name or by score. She can add, edit, and delete players. The list of players can be "refreshed". For demo purpose, refreshing players performs random modifications to the players. The tornado icon exercices multi-threading robustness by spawning many concurrent refreshes.
|
||||
|
||||
Let's start!
|
||||
|
||||
- [The Database Service]
|
||||
- [The Shared Application Database]
|
||||
- [The Database Schema]
|
||||
- [The Player Struct]
|
||||
- [Saving Players]
|
||||
- [Deleting Players]
|
||||
- [Fetching Players]
|
||||
- [Refreshing Players]
|
||||
- [Sorting Players]
|
||||
- [Observing Players]
|
||||
- [The Initial Application State]
|
||||
- [Testing the Database]
|
||||
|
||||
## The Database Service
|
||||
|
||||
The database service (or database manager, or persistence layer) is a class named `AppDatabase` that grants access to the SQLite database of players. It fetches the list of players, inserts new players, etc.
|
||||
|
||||
`AppDatabase` accesses the database through a GRDB [database connection]. In the application, the service uses a `DatabasePool` connection that leverages the advantages of the SQLite [WAL mode]. Tests use a service that connects to an in-memory database, with `DatabaseQueue`, so that they can run as fast as possible. SwiftUI previews also run with in-memory databases.
|
||||
|
||||
Database pools and queues share a common protocol: `DatabaseWriter`. This is what the `AppDatabase` service needs, in order to support both:
|
||||
|
||||
```swift
|
||||
// File: AppDatabase.swift
|
||||
import GRDB
|
||||
|
||||
final class AppDatabase {
|
||||
/// Creates an `AppDatabase`.
|
||||
init(_ dbWriter: DatabaseWriter) throws {
|
||||
self.dbWriter = dbWriter
|
||||
}
|
||||
|
||||
/// Provides access to the database.
|
||||
private let dbWriter: DatabaseWriter
|
||||
}
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>ℹ️ Design Notes</summary>
|
||||
|
||||
> :point_right: The `dbWriter` property is private: this allows `AppDatabase` to restrict the operations that can be performed on the database.
|
||||
>
|
||||
> :point_right: The initializer is not private: we can freely create `AppDatabase` instances, for the application, and for tests.
|
||||
>
|
||||
> :point_right: The initializer is declared with the `throws` qualifier, because it will be extended, below in this guide, in order to prepare the database for application use.
|
||||
|
||||
</details>
|
||||
|
||||
> ✅ At this stage, we have an `AppDatabase` class which encapsulates access to the database. It supports both WAL databases, and in-memory databases, so that it can feed the application, tests, and SwiftUI previews.
|
||||
|
||||
## The Shared Application Database
|
||||
|
||||
Our app uses a single database file, so we want a "shared" database: `AppDatabase.shared`.
|
||||
|
||||
The shared `AppDatabase` instance opens a file named "db.sqlite" stored in a "database" folder. The database is created if the file does not already exist:
|
||||
|
||||
```swift
|
||||
// File: Persistence.swift
|
||||
import GRDB
|
||||
|
||||
extension AppDatabase {
|
||||
/// The database for the application
|
||||
static let shared = makeShared()
|
||||
|
||||
private static func makeShared() -> AppDatabase {
|
||||
do {
|
||||
// Create a folder for storing the SQLite database
|
||||
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
|
||||
let dbURL = folderURL.appendingPathComponent("db.sqlite")
|
||||
let dbPool = try DatabasePool(path: dbURL.path)
|
||||
|
||||
// Create the AppDatabase
|
||||
let appDatabase = try AppDatabase(dbPool)
|
||||
return appDatabase
|
||||
} catch {
|
||||
fatalError("Unresolved error \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The [Combine + SwiftUI Demo Application] defines more instances of `AppDatabase`, such as en empty players database suitable for some SwiftUI previews:
|
||||
|
||||
```swift
|
||||
// File: Persistence.swift
|
||||
|
||||
extension AppDatabase {
|
||||
/// Creates an empty database for SwiftUI previews
|
||||
static func empty() -> AppDatabase {
|
||||
// Connect to an in-memory database
|
||||
let dbQueue = DatabaseQueue()
|
||||
return try! AppDatabase(dbQueue)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>ℹ️ Design Notes</summary>
|
||||
|
||||
> :point_right: Some applications will prefer to manage the shared `AppDatabase` instance differently, for example with some dependency injection technique. In this case, you will not define `AppDatabase.shared`.
|
||||
>
|
||||
> Just make sure that there exists a single instance of `DatabaseQueue` or `DatabasePool` for any given database file. This is because multiple instances would compete for database access, and sometimes throw errors. Get inspiration from `AppDatabase.makeShared()`, above, in order to create the single instance of database service used by the application.
|
||||
>
|
||||
> :point_right: The database is stored in its own directory, so that you can easily:
|
||||
>
|
||||
> - Set up [data protection].
|
||||
> - Remove the database as well as its companion [temporary files](https://sqlite.org/tempfiles.html) from disk in a single stroke.
|
||||
>
|
||||
> :point_right: `AppDatabase.shared` is created from a `DatabasePool` in order to profit from the SQLite [WAL mode].
|
||||
>
|
||||
> :point_right: Any error which prevents the application from opening the database has the application crash. You will have to adapt this sample code if you intend to build an app that is able to run without a working database. For example, you could modify `AppDatabase` so that it feeds from a `Result<DatabaseWriter, Error>` instead of a plain `DatabaseWriter` - but your mileage may vary. This sample code has the error bubble up in crash reports, which is arguably better than displaying a blank screen without any error reporting.
|
||||
|
||||
</details>
|
||||
|
||||
> ✅ At this stage, we have an `AppDatabase.shared` object which vends an empty database. We'll add methods and properties to `AppDatabase`, as we discover the needs of our application.
|
||||
|
||||
## The Database Schema
|
||||
|
||||
Now that we have an empty database, let's define its schema: the database table(s) that will store our application data. A good database schema will have SQLite manage the database integrity for you, and make sure it is impossible to store invalid data in the database: this is an important step!
|
||||
|
||||
Our database has one table, `player`, where each row contains the attributes of a player: a unique identifier (aka *primary key*), a name, and a score. The identifier makes it possible to instruct the database to perform operations on a specific player. We'll make sure all players have a name and a score (we'll prevent *NULL* values from entering those columns).
|
||||
|
||||
In order to define the schema and create the `player` table, it is recommended to use [migrations]. All applications around us evolve as time passes, and ship several versions: it is likely our app will do the same. The database schema evolves as well, as we add features and fix bugs in our app. That's exactly what migrations are for: they represent the building steps of our database schema, as our app goes through its versions.
|
||||
|
||||
The migrations are defined in the `AppDatabase.migrator` property, in which we register the *initial migration*:
|
||||
|
||||
```swift
|
||||
private var migrator: DatabaseMigrator {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
migrator.registerMigration("initial") { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
}
|
||||
|
||||
// Migrations for future application versions will be inserted here:
|
||||
// migrator.registerMigration(...) { db in
|
||||
// ...
|
||||
// }
|
||||
|
||||
return migrator
|
||||
}
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Raw SQL version</summary>
|
||||
|
||||
> Some readers like to write SQL. Please be welcome:
|
||||
>
|
||||
> ```swift
|
||||
> private var migrator: DatabaseMigrator {
|
||||
> var migrator = DatabaseMigrator()
|
||||
>
|
||||
> migrator.registerMigration("initial") { db in
|
||||
> try db.execute(sql: """
|
||||
> CREATE TABLE player (
|
||||
> id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
> name TEXT NOT NULL,
|
||||
> score INTEGER NOT NULL
|
||||
> )
|
||||
> """)
|
||||
> }
|
||||
>
|
||||
> return migrator
|
||||
> }
|
||||
> ```
|
||||
|
||||
</details>
|
||||
|
||||
The migrations are now defined, but they are not applied yet. Let's modify the `AppDatabase` initializer, and *migrate* the database. It means that unapplied migrations are run. In the end, we are sure that the database schema is exactly what we want it to be:
|
||||
|
||||
```swift
|
||||
/// Creates an `AppDatabase` from a database connection,
|
||||
/// and make sure the database schema is ready.
|
||||
init(_ dbWriter: DatabaseWriter) throws {
|
||||
self.dbWriter = dbWriter
|
||||
try migrator.migrate(dbWriter)
|
||||
}
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>ℹ️ Design Notes</summary>
|
||||
|
||||
> :point_right: GRDB is a library that fosters robust database schemas, defined right at the SQLite level, because you can't build a safer haven for your precious users' data. There is no such thing as "automatic schema definition" or "automatic migrations" based on annotated Swift models. See [Trust SQLite More Than Yourself] for a longer explanation of this policy.
|
||||
>
|
||||
> :point_right: The database table for players is named `player`, because GRDB recommends that table names are English, singular, and camel-cased (`player`, `country`, `postalAddress`, etc.) Such names will help you using [Associations] when you need them. Database table names that follow another naming convention are totally OK, but you will have to perform extra configuration.
|
||||
>
|
||||
> :point_right: The primary key for players is an auto-incremented column named `id`. It also could have been a UUID column named `uuid`. GRDB generally accepts all primary keys, even if they are not named `id`, even if they span several columns, without any extra setup. Yet `id` is a frequent convention.
|
||||
>
|
||||
> :point_right: The `id` column is [autoincremented](https://sqlite.org/autoinc.html), in order to avoid id reuse. Reused ids can trip up [database observation] tools: a deletion followed by an insertion with the same id could be interpreted as an update, with unintended consequences.
|
||||
|
||||
</details>
|
||||
|
||||
> ✅ At this stage, we have an `AppDatabase.shared` object which vends a database that contains a `player` table.
|
||||
|
||||
## The Player Struct
|
||||
|
||||
The application will insert, edit, display, and delete players. Let's *model* a player with a dedicated type:
|
||||
|
||||
```swift
|
||||
// File: Player.swift
|
||||
|
||||
/// A Player
|
||||
struct Player {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
var score: Int
|
||||
}
|
||||
```
|
||||
|
||||
With its `name` and `score` properties, it can feed our application screens. With its `id` property, it can talk to `AppDatabase`, whenever we need to perform operations of a particular player (such as saving changes performed on a player).
|
||||
|
||||
The type of `id` is `Int64?`, because it matches the `id` column in the `player` table (SQLite integer primary keys are 64-bit integers, even on 32-bit platforms). When the id is nil, the player is not yet saved in the database. When the id is not nil, it is the identifier of a player in the database.
|
||||
|
||||
The `name` and `score` properties are regular `String` and `Int`. They are not optional because the `player` table was created with "not null" constraints on those database columns: we do not want to insert nil names, and we are sure we won't fetch nil names either.
|
||||
|
||||
> ✅ Now we have a `Player` type that fits the columns of the `player` database table, and is able to deal with all application needs. This is what GRDB calls a [record type]. At this stage, `Player` has no database power yet.
|
||||
|
||||
## Saving Players
|
||||
|
||||
The user application inserts player by tapping the "+" button on the top left of the [screen], which displays a form. The user fills the name and score fields, and hits the "Done" button.
|
||||
|
||||
The same form screen is pushed when the user taps a player in the list. The app then updates the player when the user hits the back button.
|
||||
|
||||
The `AppDatabase` service supports both these use cases by providing a `savePlayer(_:)` method.
|
||||
|
||||
We can write it with raw SQL:
|
||||
|
||||
<details>
|
||||
<summary>Raw SQL version</summary>
|
||||
|
||||
> ```swift
|
||||
> // File: AppDatabase.swift
|
||||
>
|
||||
> extension AppDatabase {
|
||||
> /// Saves (inserts or updates) a player. When the method returns, the
|
||||
> /// player is present in the database, and its id is not nil.
|
||||
> func savePlayer(_ player: inout Player) throws {
|
||||
> try dbWriter.write { db in
|
||||
> try save(db, player: &player)
|
||||
> }
|
||||
> }
|
||||
>
|
||||
> /// Saves (inserts or updates) a player. When the method returns, the
|
||||
> /// player is present in the database, and its id is not nil.
|
||||
> private func save(_ db: Database, player: inout Player) throws {
|
||||
> if let id = player.id {
|
||||
> // Player has an id: update
|
||||
> try db.execute(literal: """
|
||||
> UPDATE player
|
||||
> SET name = \(player.name),
|
||||
> score = \(player.score)
|
||||
> WHERE id = \(id)
|
||||
> """)
|
||||
>
|
||||
> if db.changesCount == 0 {
|
||||
> // Player was not updated. This means that is was not
|
||||
> // present in the database. So let's insert it with its id.
|
||||
> try db.execute(literal: """
|
||||
> INSERT INTO player (id, name, score)
|
||||
> VALUES (\(player.id), \(player.name), \(player.score))
|
||||
> """)
|
||||
> }
|
||||
> } else {
|
||||
> // Player has no id: insert
|
||||
> try db.execute(literal: """
|
||||
> INSERT INTO player (name, score)
|
||||
> VALUES (\(player.name), \(player.score))
|
||||
> """)
|
||||
> player.id = db.lastInsertedRowID
|
||||
> }
|
||||
> }
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> The `savePlayer(_:)` method calls a private helper method `save(_:player:)`. This helper method will be reused later in the tutorial.
|
||||
>
|
||||
> Note that the helper method uses the `execute(literal:)` method, which avoids [SQL injection], thanks to [SQL Interpolation].
|
||||
|
||||
</details>
|
||||
|
||||
SQL is just fine, but we can also make `Player` a [persistable record], so that you do not have to write the SQL queries that perform common persistence operations.
|
||||
|
||||
In our specific case, the `Player` struct adopts the `MutablePersistableRecord` protocol, because the `player` database table has an autoincremented id:
|
||||
|
||||
- "Persistable": players can be inserted, updated and deleted.
|
||||
- "Mutable": a player is modified (mutated) upon insertion, because its `id` property is set from the autoincremented SQLite id.
|
||||
|
||||
Conformance to `MutablePersistableRecord` is easy for types that adopt the standard [Encodable] protocol:
|
||||
|
||||
```swift
|
||||
// File: Player.swift
|
||||
|
||||
// Give Player database powers
|
||||
extension Player: Encodable, MutablePersistableRecord {
|
||||
/// Updates a player id after it has been inserted in the database.
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In this tutorial, the name of the database table matches the name of the type, and so do columns and properties: we do not have to configure anything.
|
||||
|
||||
<details>
|
||||
<summary>Avoiding Encodable</summary>
|
||||
|
||||
The `Encodable` protocol is handy, but you may prefer not to use it. In this case, you have to fulfill the `MutablePersistableRecord` requirements:
|
||||
|
||||
```swift
|
||||
// File: Player.swift
|
||||
|
||||
// Give Player database powers
|
||||
extension Player: MutablePersistableRecord {
|
||||
/// Defines the values persisted in the database
|
||||
func encode(to container: inout PersistenceContainer) {
|
||||
container["id"] = id
|
||||
container["name"] = name
|
||||
container["score"] = score
|
||||
}
|
||||
|
||||
/// Updates a player id after it has been inserted in the database.
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
Thanks to persistable records, we now support both inserts and updates:
|
||||
|
||||
```swift
|
||||
// File: AppDatabase.swift
|
||||
|
||||
extension AppDatabase {
|
||||
/// Saves (inserts or updates) a player. When the method returns, the
|
||||
/// 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Usage:
|
||||
|
||||
```swift
|
||||
// Inserts a player
|
||||
var player = Player(id: nil, name: "Arthur", score: 0)
|
||||
try AppDatabase.shared.savePlayer(player)
|
||||
print("Player id is \(player.id)") // Prints "Player id is 1"
|
||||
|
||||
// Updates a player
|
||||
player.score = 1000
|
||||
try AppDatabase.shared.savePlayer(player)
|
||||
```
|
||||
|
||||
> ✅ At this stage, we can save players in the database.
|
||||
|
||||
## Deleting Players
|
||||
|
||||
The application can delete players:
|
||||
|
||||
- The "Trash" icon at the bottom left of the [screen] deletes all players.
|
||||
- The "Edit" button at the top left of the screen lets the user delete individual players.
|
||||
- The player list supports the swipe to delete gesture.
|
||||
|
||||
The `AppDatabase` service supports these use cases with two new methods:
|
||||
|
||||
```swift
|
||||
// File: AppDatabase.swift
|
||||
|
||||
extension AppDatabase {
|
||||
/// Delete the specified players
|
||||
func deletePlayers(ids: [Int64]) throws {
|
||||
try dbWriter.write { db in
|
||||
_ = try Player.deleteAll(db, keys: ids)
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete all players
|
||||
func deleteAllPlayers() throws {
|
||||
try dbWriter.write { db in
|
||||
_ = try Player.deleteAll(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Both `deleteAll(_:)` and `deleteAll(_:keys:)` methods are available for all persistable records.
|
||||
|
||||
<details>
|
||||
<summary>Raw SQL version</summary>
|
||||
|
||||
> If you do not want to make `Player` a persistable record, you can fallback to raw SQL:
|
||||
>
|
||||
> ```swift
|
||||
> // File: AppDatabase.swift
|
||||
>
|
||||
> extension AppDatabase {
|
||||
> /// Delete the specified players
|
||||
> func deletePlayers(ids: [Int64]) throws {
|
||||
> try dbWriter.write { db in
|
||||
> try db.execute(literal: """
|
||||
> DELETE FROM player WHERE id IN \(ids)
|
||||
> """)
|
||||
> }
|
||||
> }
|
||||
>
|
||||
> /// Delete all players
|
||||
> func deleteAllPlayers() throws {
|
||||
> try dbWriter.write { db in
|
||||
> try db.execute(sql: "DELETE FROM player")
|
||||
> }
|
||||
> }
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> The `deletePlayers(ids:)` method above uses [SQL Interpolation] so that you can embed an array of ids right inside your SQL query (`WHERE id IN \(ids)`). The "really raw" SQL version below is a little more involved:
|
||||
>
|
||||
> ```swift
|
||||
> func deletePlayers(ids: [Int64]) throws {
|
||||
> try dbWriter.write { db in
|
||||
> if ids.isEmpty {
|
||||
> // Avoid SQL syntax error
|
||||
> return
|
||||
> }
|
||||
> // DELETE FROM player WHERE id IN (?, ?, ...)
|
||||
> // ~~~~~~~~~
|
||||
> // as many question marks as there are ids
|
||||
> let placeholders = databaseQuestionMarks(count: ids.count)
|
||||
> let query = "DELETE FROM player WHERE id IN (\(placeholders))"
|
||||
> try db.execute(sql: query, arguments: StatementArguments(ids))
|
||||
> }
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> All the techniques we have seen avoid [SQL injection].
|
||||
|
||||
</details>
|
||||
|
||||
> ✅ At this stage, we can delete all or individual players from the database.
|
||||
|
||||
## Fetching Players
|
||||
|
||||
GRDB record types also provide fetching methods, when they adopt the [FetchableRecord] protocol.
|
||||
|
||||
This protocol is "free" when `Player` adopts the [Decodable] protocol:
|
||||
|
||||
```swift
|
||||
// File: Player.swift
|
||||
|
||||
extension Player: Decodable, FetchableRecord { }
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Avoiding Decodable</summary>
|
||||
|
||||
The `Decodable` protocol is handy, but you may prefer not to use it. In this case, you have to fulfill the [FetchableRecord] requirement:
|
||||
|
||||
```swift
|
||||
// File: Player.swift
|
||||
|
||||
extension Player: FetchableRecord {
|
||||
/// Creates a player from a database row
|
||||
init(row: Row) {
|
||||
id = row["id"]
|
||||
name = row["name"]
|
||||
score = row["score"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
> ✅ At this stage, we can turn raw database rows into players.
|
||||
|
||||
## Refreshing Players
|
||||
|
||||
The refresh button at the bottom center of the [screen] applies random transformations to the player database. The `AppDatabase` service supports this use cases by providing a `refreshPlayers()` method.
|
||||
|
||||
```swift
|
||||
// File: AppDatabase.swift
|
||||
|
||||
extension AppDatabase {
|
||||
/// Refresh all players (by performing some random changes, for demo purpose).
|
||||
func refreshPlayers() throws {
|
||||
try dbWriter.write { db in
|
||||
if try Player.fetchCount(db) == 0 {
|
||||
// When database is empty, insert new random players
|
||||
try createRandomPlayers(db)
|
||||
} else {
|
||||
// Insert a player
|
||||
if Bool.random() {
|
||||
var player = Player.newRandom()
|
||||
try player.save(db)
|
||||
}
|
||||
|
||||
// Delete a random player
|
||||
if Bool.random() {
|
||||
try Player.order(sql: "RANDOM()").limit(1).deleteAll(db)
|
||||
}
|
||||
|
||||
// Update some players
|
||||
for var player in try Player.fetchAll(db) where Bool.random() {
|
||||
try player.updateChanges(db) {
|
||||
$0.score = Player.randomScore()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func createRandomPlayers(_ db: Database) throws {
|
||||
for _ in 0..<8 {
|
||||
var player = Player.newRandom()
|
||||
try player.save(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The `AppDatabase.refreshPlayers()` method calls a private helper method `createRandomPlayers(_:)`. This helper method will be reused later in the tutorial.
|
||||
|
||||
Refreshing players needs some support from the `Player` record type, so that we can build random players:
|
||||
|
||||
```swift
|
||||
// File: Player.swift
|
||||
|
||||
extension Player {
|
||||
private static let names = ["Arthur", "Anita", ...]
|
||||
|
||||
/// Creates a new player with random name and random score
|
||||
static func newRandom() -> Player {
|
||||
Player(id: nil, name: randomName(), score: randomScore())
|
||||
}
|
||||
|
||||
/// Returns a random name
|
||||
static func randomName() -> String {
|
||||
names.randomElement()!
|
||||
}
|
||||
|
||||
/// Returns a random score
|
||||
static func randomScore() -> Int {
|
||||
10 * Int.random(in: 0...100)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Raw SQL version</summary>
|
||||
|
||||
> Let's write `AppDatabase.refreshPlayers()` without any support from SQL generation provided by record protocols:
|
||||
>
|
||||
> ```swift
|
||||
> // File: AppDatabase.swift
|
||||
>
|
||||
> extension AppDatabase {
|
||||
> /// Refresh all players (by performing some random changes, for demo purpose).
|
||||
> func refreshPlayers() throws {
|
||||
> try dbWriter.write { db in
|
||||
> if try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM player") == 0 {
|
||||
> // When database is empty, insert new random players
|
||||
> try createRandomPlayers(db)
|
||||
> } else {
|
||||
> // Insert a player
|
||||
> if Bool.random() {
|
||||
> var player = Player.newRandom()
|
||||
> try save(db, player: &player)
|
||||
> }
|
||||
>
|
||||
> // Delete a random player
|
||||
> if Bool.random() {
|
||||
> try db.execute(sql: """
|
||||
> DELETE FROM player
|
||||
> ORDER BY RANDOM()
|
||||
> LIMIT 1
|
||||
> """)
|
||||
> }
|
||||
>
|
||||
> // Update some players
|
||||
> let ids = try Int64.fetchAll(db, sql: "SELECT id FROM player")
|
||||
> for id in ids where Bool.random() {
|
||||
> try db.execute(literal: """
|
||||
> UPDATE player
|
||||
> SET score = \(Player.randomScore())
|
||||
> WHERE id = \(id)
|
||||
> """)
|
||||
> }
|
||||
> }
|
||||
> }
|
||||
> }
|
||||
>
|
||||
> private func createRandomPlayers(_ db: Database) throws {
|
||||
> for _ in 0..<8 {
|
||||
> var player = Player.newRandom()
|
||||
> try save(db, player: &player)
|
||||
> }
|
||||
> }
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> The `save(_:player:)` method was defined, with raw SQL, in [Saving Players].
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>ℹ️ Design Notes</summary>
|
||||
|
||||
> The role of the `AppDatabase` service is to provide a set of [ACID] transformations, that fully control the state of the database. Either a player is saved, either it is not. Players are refreshed, or they are not. If our application would synchronize its local database with some remote server, we would want players to be fully synchronized, or not at all. Intermediate states such as partially saved, deleted, refreshed, or synchronized players must be avoided, in order to make the application robust. After all, errors happen, and even hard crashes. Thanks to the ACID guarantees provided by SQLite, errors and crashes are unable to threaten important database invariants.
|
||||
>
|
||||
> **The added value of the `AppDatabase` service is to provide one method per database transformation needed by the app.** All those methods perform **a single GRDB write**, in order to profit from all ACID guarantees of SQLite transactions. Refreshing players is one of those transformations. Saving a player is another, which supports the user interface for editing of creating players.
|
||||
>
|
||||
> :bulb: **Tip**: when two distinct service methods want to reuse a piece of code, we extract it in a helper method such as `createRandomPlayers(_:)` above. Unlike service methods, helper methods access the database through their `Database` argument, not through the `dbWriter` property.
|
||||
|
||||
</details>
|
||||
|
||||
> ✅ At this stage, we can modify players in a controlled and robust way.
|
||||
|
||||
## Sorting Players
|
||||
|
||||
The application [screen] displays a list of players. The user can choose the order of players by tapping the button at the top right of the screen. The app supports two orderings: by descending score, and by ascending name.
|
||||
|
||||
In this chapter, we will not describe how the applications keeps its screen synchronized with the content of the database. This will be the topic of [Observing Players].
|
||||
|
||||
Here we will extend the `Player` record type so that it provides the **database requests** needed by the application.
|
||||
|
||||
<details>
|
||||
<summary>ℹ️ Design Notes</summary>
|
||||
|
||||
> With GRDB, record types are responsible of their table: they know how data is stored in the database. This is why `Player` is better suited to know what sorting players by name, or by score, means.
|
||||
>
|
||||
> On the other side, `Player` does not perform database fetches on its own. Actual database fetches are performed by the application, depending on the user actions, by invoking methods on `AppDatabase.shared`.
|
||||
>
|
||||
> `Player` *defines* database requests, and `AppDatabase` *executes* those requests.
|
||||
|
||||
</details>
|
||||
|
||||
We made `Player` a full-fledged record type in the previous chapters. Record types can profit from the [query interface], a Swift way to build database requests.
|
||||
|
||||
In order to build requests that sort by score or by name, we need to define columns. When the `Player` type is [Codable], we can profit from its `CodingKeys` so that the compiler makes sure we do not make any typo:
|
||||
|
||||
```swift
|
||||
// File: Player.swift
|
||||
extension Player {
|
||||
// Player columns are defined from CodingKeys
|
||||
fileprivate enum Columns {
|
||||
static let name = Column(CodingKeys.name)
|
||||
static let score = Column(CodingKeys.score)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>ℹ️ Design Notes</summary>
|
||||
|
||||
> `Player.Columns` is declared `fileprivate`. The goal is to prevent other application files from messing with the intimate relationship between the `Player` record type and the `player` database table.
|
||||
>
|
||||
> Some apps eventually need to relax the visibility of those columns. Until they really have to, though, `fileprivate` is the recommended default for columns.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Avoiding Codable</summary>
|
||||
|
||||
The `Codable` protocol is handy, but you may prefer not to use it. In this case, define columns as a String enum:
|
||||
|
||||
```swift
|
||||
// File: Player.swift
|
||||
extension Player {
|
||||
// Player columns
|
||||
fileprivate enum Columns: String, ColumnExpression {
|
||||
case name
|
||||
case score
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
Following advice from the [Good Practices for Designing Record Types], we can now define player requests in an extension of the `DerivableRequest` protocol:
|
||||
|
||||
```swift
|
||||
// File: Player.swift
|
||||
|
||||
/// Define some player requests used by the application.
|
||||
extension DerivableRequest where RowDecoder == Player {
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let players: [Player] = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByName().fetchAll(db)
|
||||
/// }
|
||||
func orderedByName() -> Self {
|
||||
// Sort by name in a localized case insensitive fashion
|
||||
order(Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
|
||||
/// A request of players ordered by score.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// 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 {
|
||||
// Sort by descending score, and then by name, in a
|
||||
// localized case insensitive fashion
|
||||
order(
|
||||
Player.Columns.score.desc,
|
||||
Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Names are sorted according to the `localizedCaseInsensitiveCompare` collation. See [String Comparison](../README.md#string-comparison) for more information.
|
||||
|
||||
Writing an "extension of the `DerivableRequest` protocol" may sound intimidating. Well, don't be shy, and look at the sample code above: it contains inline documentation which describes the usage of those requests. Is it more clear now? `DerivableRequest` makes it possible to extend the query interface with custom requests, and also to hide some database implementation details inside a dedicated record type.
|
||||
|
||||
If you know the [Active Record](https://guides.rubyonrails.org/active_record_querying.html) Ruby library, you may be reminded of [scopes](https://guides.rubyonrails.org/active_record_querying.html#scopes):
|
||||
|
||||
```ruby
|
||||
# player.rb
|
||||
class Player < ApplicationRecord
|
||||
scope :ordered_by_name, -> { order(name: :asc) }
|
||||
end
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Raw SQL version</summary>
|
||||
|
||||
> You can build SQL requests with `SQLRequest`, which profits from [SQL Interpolation]. If you have the `Player` type conform to [FetchableRecord], those requests will be able to fetch. Otherwise, we'll have to fetch raw database rows and we will have more work to do. But those requests can still be defined:
|
||||
>
|
||||
> ```swift
|
||||
> // File: Player.swift
|
||||
>
|
||||
> /// Define some player requests used by the application.
|
||||
> extension Player {
|
||||
> /// A request of players ordered by name.
|
||||
> ///
|
||||
> /// For example:
|
||||
> ///
|
||||
> /// let players: [Player] = try dbWriter.read { db in
|
||||
> /// try Player.orderedByName().fetchAll(db)
|
||||
> /// }
|
||||
> static func orderedByName() -> SQLRequest<Player> {
|
||||
> // Sort by name in a localized case insensitive fashion
|
||||
> """
|
||||
> SELECT * FROM player
|
||||
> ORDER BY name COLLATING \(.localizedCaseInsensitiveCompare)
|
||||
> """
|
||||
> }
|
||||
>
|
||||
> /// A request of players ordered by score.
|
||||
> ///
|
||||
> /// For example:
|
||||
> ///
|
||||
> /// let players: [Player] = try dbWriter.read { db in
|
||||
> /// try Player.orderedByScore().fetchAll(db)
|
||||
> /// }
|
||||
> static func orderedByScore() -> SQLRequest<Player> {
|
||||
> // Sort by descending score, and then by name, in a
|
||||
> // localized case insensitive fashion
|
||||
> """
|
||||
> SELECT * FROM player
|
||||
> ORDER BY score DESC,
|
||||
> name COLLATING \(.localizedCaseInsensitiveCompare)
|
||||
> """
|
||||
> }
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> Compared to query interface requests, raw SQL requests lose two benefits:
|
||||
>
|
||||
> - SQL requests are not composable together. You can not reuse them. For example:
|
||||
>
|
||||
> ```swift
|
||||
> // A request from a future version of our app.
|
||||
> // Request composition is only possible for query interface requests.
|
||||
> let request = Player.all()
|
||||
> .filter(team: .red)
|
||||
> .including(all: Player.awards)
|
||||
> .orderedByName()
|
||||
> ```
|
||||
>
|
||||
> - SQL requests do not auto-optimize when you are only interested in the first row:
|
||||
>
|
||||
> ```swift
|
||||
> // No automatic appending of `LIMIT 1`, as query interface requests do.
|
||||
> let bestPlayer: Player? = try dbWriter.read { db in
|
||||
> try Player.orderedByScore().fetchOne(db)
|
||||
> }
|
||||
> ```
|
||||
|
||||
</details>
|
||||
|
||||
> ✅ At this stage, we have defined the database requests that can feed the list of players in the application.
|
||||
|
||||
## Observing Players
|
||||
|
||||
Some elements that are visible in the application [screen] do not depend on the database: action buttons, and the selected ordering. Those are transient information that live in a UIKit controller, or a SwiftUI view.
|
||||
|
||||
The database content on screen is:
|
||||
|
||||
- The number of players (in the navigation title).
|
||||
- The list of all players.
|
||||
|
||||
Those two elements are not independent. We want them to be always consistent: if there are twelve players in the list, the title must be "12 Players".
|
||||
|
||||
|
||||
|
||||
In the previous [Sorting Players] chapter, we built database requests for players, one sorted by name, one sorted by score. Now is time to fetch those players from those requests.
|
||||
|
||||
More precisely, we will **observe** the requests of players. This will make it much easier to display an always-accurate list of players in the app. We will not have to remember to update the list whenever the player database is updated.
|
||||
|
||||
> ✅ At this stage, we can feed UIViewControllers and SwiftUI with an always fresh list of players.
|
||||
|
||||
## The Initial Application State
|
||||
|
||||
Let's perform a little polishing step, so that the first time the application is launched, it is already populated with a few players. We write a demo application, and a demo is nicer when the user can play right away.
|
||||
|
||||
To this end, we create a new `AppDatabase.createRandomPlayersIfEmpty()` method. It reuses the `createRandomPlayers(_:)` helper method defined in the [Refreshing Players] chapter:
|
||||
|
||||
```swift
|
||||
// File: AppDatabase.swift
|
||||
|
||||
extension AppDatabase {
|
||||
/// Create random players if the database is empty.
|
||||
func createRandomPlayersIfEmpty() throws {
|
||||
try dbWriter.write { db in
|
||||
if try Player.fetchCount(db) == 0 {
|
||||
try createRandomPlayers(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And we modify `AppDatabase.makeShared()` so that the application never boots with an empty database:
|
||||
|
||||
```swift
|
||||
// File: Persistence.swift
|
||||
import GRDB
|
||||
|
||||
extension AppDatabase {
|
||||
/// The database for the application
|
||||
static let shared = makeShared()
|
||||
|
||||
private static func makeShared() -> AppDatabase {
|
||||
do {
|
||||
// Create a folder for storing the SQLite database
|
||||
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
|
||||
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.
|
||||
try appDatabase.createRandomPlayersIfEmpty()
|
||||
|
||||
return appDatabase
|
||||
} catch {
|
||||
fatalError("Unresolved error \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>ℹ️ Design Notes</summary>
|
||||
|
||||
> We do not call `createRandomPlayersIfEmpty()` from the `AppDatabase` initializer, or from its migrator, because we also need to create empty databases (for tests, or some SwiftUI previews). The correct place is indeed `makeShared()`, the method that creates the database for the application itself.
|
||||
|
||||
</details>
|
||||
|
||||
> ✅ At this stage, we have a polished Database Access Layer that makes sure the demo app looks good.
|
||||
|
||||
## Testing the Database
|
||||
|
||||
[The Database Service]: #the-database-service
|
||||
[The Shared Application Database]: #the-shared-application-database
|
||||
[The Database Schema]: #the-database-schema
|
||||
[The Player Struct]: #the-player-struct
|
||||
[Saving Players]: #saving-players
|
||||
[Deleting Players]: #deleting-players
|
||||
[Fetching Players]: #fetching-players
|
||||
[Refreshing Players]: #refreshing-players
|
||||
[Sorting Players]: #sorting-players
|
||||
[Observing Players]: #observing-players
|
||||
[The Initial Application State]: #the-initial-application-state
|
||||
[Testing the Database]: #testing-the-database
|
||||
|
||||
[demo applications]: DemoApps
|
||||
[UIKit demo application]: DemoApps/GRDBDemoiOS/README.md
|
||||
[Combine + SwiftUI Demo Application]: DemoApps/GRDBCombineDemo/README.md
|
||||
[database connection]: https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
[DatabaseQueue]: ../README.md#database-queues
|
||||
[DatabasePool]: ../README.md#database-pools
|
||||
[migrations]: Migrations.md
|
||||
[Codable]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
|
||||
[Encodable]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
|
||||
[Decodable]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
|
||||
[record type]: ../README.md#records
|
||||
[persistable record]: ../README.md#persistablerecord-protocol
|
||||
[FetchableRecord]: ../README.md#fetchablerecord-protocol
|
||||
[WAL mode]: https://sqlite.org/wal.html
|
||||
[data protection]: ../README.md#data-protection
|
||||
[Associations]: AssociationsBasics.md
|
||||
[Sharing a database]: SharingADatabase.md
|
||||
[database observation]: ../README.md#database-changes-observation
|
||||
[SQL Interpolation]: SQLInterpolation.md
|
||||
[SQL injection]: ../README.md#avoiding-sql-injection
|
||||
[screenshot]: https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBDemoiOS/Screenshot.png
|
||||
[screen]: https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBDemoiOS/Screenshot.png
|
||||
[ACID]: https://en.wikipedia.org/wiki/ACID
|
||||
[query interface]: ../README.md#the-query-interface
|
||||
[Good Practices for Designing Record Types]: GoodPracticesForDesigningRecordTypes.md
|
||||
[Trust SQLite More Than Yourself]: GoodPracticesForDesigningRecordTypes.md#trust-sqlite-more-than-yourself
|
||||
@@ -283,8 +283,6 @@ while let row = try rows.next() {
|
||||
|
||||
If this little tour of GRDB has convinced you, the real trip starts here: [GRDB].
|
||||
|
||||
And if you happen to maintain an Objective-C application that uses FMDB, checkout [GRDBObjc]. It provides FMDB-compatible bindings to GRDB, so that you can inject sweet drops of Swift into your app, at your own pace, and at minimal cost.
|
||||
|
||||
Happy GRDB! :gift:
|
||||
|
||||
[Concurrency Guide]: ../README.md#concurrency
|
||||
@@ -296,7 +294,6 @@ Happy GRDB! :gift:
|
||||
[Fluent]: https://github.com/vapor/fluent
|
||||
[FMDB]: http://github.com/ccgus/fmdb
|
||||
[GRDB]: http://github.com/groue/GRDB.swift
|
||||
[GRDBObjc]: http://github.com/groue/GRDBObjc
|
||||
[PersistableRecord]: ../README.md#records
|
||||
[Realm]: http://realm.io
|
||||
[FetchableRecord]: ../README.md#records
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '5.3.0'
|
||||
s.version = '5.8.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
+116
-122
@@ -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 */; };
|
||||
@@ -39,8 +42,6 @@
|
||||
5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; };
|
||||
5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; };
|
||||
5605F1881C69111300235C62 /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; };
|
||||
5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; };
|
||||
5605F18E1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; };
|
||||
560714E3227DD0810091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714E2227DD0810091BB10 /* AssociationPrefetchingSQLTests.swift */; };
|
||||
560714E4227DD0810091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714E2227DD0810091BB10 /* AssociationPrefetchingSQLTests.swift */; };
|
||||
5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; };
|
||||
@@ -128,6 +129,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 +265,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 */; };
|
||||
@@ -277,6 +279,9 @@
|
||||
564CE5AE21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */; };
|
||||
564CE5BE21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */; };
|
||||
564CE5BF21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */; };
|
||||
564D4F7E261C6DC200F55856 /* CaseInsensitiveIdentifierTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564D4F7D261C6DC200F55856 /* CaseInsensitiveIdentifierTests.swift */; };
|
||||
564D4F7F261C6DC200F55856 /* CaseInsensitiveIdentifierTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564D4F7D261C6DC200F55856 /* CaseInsensitiveIdentifierTests.swift */; };
|
||||
564D4F80261C6DC200F55856 /* CaseInsensitiveIdentifierTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564D4F7D261C6DC200F55856 /* CaseInsensitiveIdentifierTests.swift */; };
|
||||
564E73DF203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; };
|
||||
564E73E0203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; };
|
||||
564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; };
|
||||
@@ -329,9 +334,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 */; };
|
||||
@@ -369,7 +371,6 @@
|
||||
565490D81D5AE252005622CB /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; };
|
||||
565490D91D5AE252005622CB /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; };
|
||||
565490DA1D5AE252005622CB /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; };
|
||||
565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; };
|
||||
565490DF1D5AE252005622CB /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; };
|
||||
565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; };
|
||||
565490E21D5AE252005622CB /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.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 */; };
|
||||
@@ -473,6 +472,10 @@
|
||||
56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
|
||||
56703298212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
|
||||
567156181CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */; };
|
||||
56717271261C68E900423B6F /* CaseInsensitiveIdentifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717270261C68E900423B6F /* CaseInsensitiveIdentifier.swift */; };
|
||||
56717272261C68EA00423B6F /* CaseInsensitiveIdentifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717270261C68E900423B6F /* CaseInsensitiveIdentifier.swift */; };
|
||||
56717273261C68EA00423B6F /* CaseInsensitiveIdentifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717270261C68E900423B6F /* CaseInsensitiveIdentifier.swift */; };
|
||||
56717274261C68EA00423B6F /* CaseInsensitiveIdentifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717270261C68E900423B6F /* CaseInsensitiveIdentifier.swift */; };
|
||||
5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; };
|
||||
5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; };
|
||||
5671FC261DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; };
|
||||
@@ -529,9 +532,28 @@
|
||||
5682D723239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */; };
|
||||
56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */; };
|
||||
568735A21CEDE16C009B9116 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 5687359E1CEDE16C009B9116 /* Betty.jpeg */; };
|
||||
56894F752606576600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F742606576600268F4D /* FoundationDecimalTests.swift */; };
|
||||
56894F762606576700268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F742606576600268F4D /* FoundationDecimalTests.swift */; };
|
||||
56894F772606576700268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F742606576600268F4D /* FoundationDecimalTests.swift */; };
|
||||
56894FB72606589700268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F94260657D600268F4D /* Decimal.swift */; };
|
||||
56894FC82606589B00268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F94260657D600268F4D /* Decimal.swift */; };
|
||||
56894FD12606589C00268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F94260657D600268F4D /* Decimal.swift */; };
|
||||
56894FD22606589D00268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F94260657D600268F4D /* Decimal.swift */; };
|
||||
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 +748,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,19 +834,15 @@
|
||||
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 */; };
|
||||
56D91AA92205F2F100770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA82205F2F000770D8D /* DatabasePromise.swift */; };
|
||||
56D91AAA2205F2F100770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA82205F2F000770D8D /* DatabasePromise.swift */; };
|
||||
56D91AAB2205F2F100770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA82205F2F000770D8D /* DatabasePromise.swift */; };
|
||||
56D91AB02205F8AC00770D8D /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */; };
|
||||
56D91AB12205F8AC00770D8D /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */; };
|
||||
56D91AB22205F8AC00770D8D /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */; };
|
||||
56DA7CF7260FA9D400A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DA7CF6260FA9D400A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */; };
|
||||
56DA7CF8260FA9D400A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DA7CF6260FA9D400A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */; };
|
||||
56DA7CF9260FA9D400A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DA7CF6260FA9D400A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */; };
|
||||
56DAA2D21DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; };
|
||||
56DAA2D61DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; };
|
||||
56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; };
|
||||
@@ -861,9 +870,9 @@
|
||||
56E9FACB221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FACA221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift */; };
|
||||
56E9FACC221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FACA221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift */; };
|
||||
56E9FACD221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FACA221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift */; };
|
||||
56E9FAD8221053DD00C703A8 /* SQLLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAD7221053DC00C703A8 /* SQLLiteral.swift */; };
|
||||
56E9FAD9221053DD00C703A8 /* SQLLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAD7221053DC00C703A8 /* SQLLiteral.swift */; };
|
||||
56E9FADA221053DD00C703A8 /* SQLLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAD7221053DC00C703A8 /* SQLLiteral.swift */; };
|
||||
56E9FAD8221053DD00C703A8 /* SQL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAD7221053DC00C703A8 /* SQL.swift */; };
|
||||
56E9FAD9221053DD00C703A8 /* SQL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAD7221053DC00C703A8 /* SQL.swift */; };
|
||||
56E9FADA221053DD00C703A8 /* SQL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAD7221053DC00C703A8 /* SQL.swift */; };
|
||||
56EA63C5209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */; };
|
||||
56EA63C6209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */; };
|
||||
56EA86951C91DFE7002BB4DF /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; };
|
||||
@@ -886,9 +895,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 */; };
|
||||
@@ -906,7 +912,6 @@
|
||||
AAA4DC7B230F1E0600C74B15 /* TableRecord+QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8AA2295BFD6001FF3FF /* TableRecord+QueryInterfaceRequest.swift */; };
|
||||
AAA4DC7C230F1E0600C74B15 /* SQLExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */; };
|
||||
AAA4DC7D230F1E0600C74B15 /* EncodableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */; };
|
||||
AAA4DC7E230F1E0600C74B15 /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; };
|
||||
AAA4DC7F230F1E0600C74B15 /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */; };
|
||||
AAA4DC80230F1E0600C74B15 /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; };
|
||||
AAA4DC81230F1E0600C74B15 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFA20944C7B00F46237 /* Association.swift */; };
|
||||
@@ -914,7 +919,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 +940,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 */; };
|
||||
@@ -961,13 +963,11 @@
|
||||
AAA4DCB4230F1E0600C74B15 /* HasOneThroughAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */; };
|
||||
AAA4DCB5230F1E0600C74B15 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238781B9C75030082EB20 /* Statement.swift */; };
|
||||
AAA4DCB6230F1E0600C74B15 /* ReadWriteBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */; };
|
||||
AAA4DCB7230F1E0600C74B15 /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */; };
|
||||
AAA4DCB8230F1E0600C74B15 /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; };
|
||||
AAA4DCB9230F1E0600C74B15 /* Data.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C33F1D23E82A00E59934 /* Data.swift */; };
|
||||
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 +990,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 +1000,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 */; };
|
||||
AAA4DCE5230F1E0600C74B15 /* SQL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAD7221053DC00C703A8 /* SQL.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 +1246,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>"; };
|
||||
@@ -1261,7 +1258,6 @@
|
||||
5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+RawRepresentable.swift"; sourceTree = "<group>"; };
|
||||
5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = "<group>"; };
|
||||
5605F1861C69111300235C62 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = "<group>"; };
|
||||
5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollatedExpression.swift; sourceTree = "<group>"; };
|
||||
560714E2227DD0810091BB10 /* AssociationPrefetchingSQLTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingSQLTests.swift; sourceTree = "<group>"; };
|
||||
5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = "<group>"; };
|
||||
560A37A31C8F625000949E71 /* DatabasePool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePool.swift; sourceTree = "<group>"; };
|
||||
@@ -1294,6 +1290,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,13 +1346,13 @@
|
||||
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>"; };
|
||||
564CE59621B7A8B500652B19 /* RemoveDuplicates.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RemoveDuplicates.swift; sourceTree = "<group>"; };
|
||||
564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = "<group>"; };
|
||||
564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = "<group>"; };
|
||||
564D4F7D261C6DC200F55856 /* CaseInsensitiveIdentifierTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CaseInsensitiveIdentifierTests.swift; sourceTree = "<group>"; };
|
||||
564E73DE203D50B9000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = "<group>"; };
|
||||
564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = "<group>"; };
|
||||
564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = "<group>"; };
|
||||
@@ -1379,7 +1376,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 +1401,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,10 +1419,12 @@
|
||||
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>"; };
|
||||
567156701CB18050007DC145 /* EncryptionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncryptionTests.swift; sourceTree = "<group>"; };
|
||||
56717270261C68E900423B6F /* CaseInsensitiveIdentifier.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CaseInsensitiveIdentifier.swift; sourceTree = "<group>"; };
|
||||
5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3TokenizerDescriptor.swift; sourceTree = "<group>"; };
|
||||
5672DE581CDB72520022BA81 /* DatabaseQueueBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueBackupTests.swift; sourceTree = "<group>"; };
|
||||
5672DE661CDB751D0022BA81 /* DatabasePoolBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolBackupTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1454,7 +1450,12 @@
|
||||
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = "<group>"; };
|
||||
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>"; };
|
||||
56894F742606576600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = "<group>"; };
|
||||
56894F94260657D600268F4D /* Decimal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Decimal.swift; 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,16 +1572,13 @@
|
||||
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>"; };
|
||||
56DA7CEA260FA9A400A8D97B /* RecordInitializersTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordInitializersTests.swift; sourceTree = "<group>"; };
|
||||
56DA7CF6260FA9D400A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordMinimalNonOptionalPrimaryKeySingleTests.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>"; };
|
||||
@@ -1593,7 +1591,7 @@
|
||||
56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleFetchTests.swift; sourceTree = "<group>"; };
|
||||
56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertibleFetchTests.swift; sourceTree = "<group>"; };
|
||||
56E9FACA221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "SQLInterpolation+QueryInterface.swift"; sourceTree = "<group>"; };
|
||||
56E9FAD7221053DC00C703A8 /* SQLLiteral.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLLiteral.swift; sourceTree = "<group>"; };
|
||||
56E9FAD7221053DC00C703A8 /* SQL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQL.swift; sourceTree = "<group>"; };
|
||||
56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DerivableRequestTests.swift; sourceTree = "<group>"; };
|
||||
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderTests.swift; sourceTree = "<group>"; };
|
||||
56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReadOnlyTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1604,7 +1602,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>"; };
|
||||
@@ -1710,13 +1707,14 @@
|
||||
5605F14C1C672E4000235C62 /* DatabaseDateComponents.swift */,
|
||||
5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */,
|
||||
5605F14F1C672E4000235C62 /* Date.swift */,
|
||||
56894F94260657D600268F4D /* Decimal.swift */,
|
||||
5657AAB81D107001006283EF /* NSData.swift */,
|
||||
5605F1501C672E4000235C62 /* NSNull.swift */,
|
||||
5605F1511C672E4000235C62 /* NSNumber.swift */,
|
||||
5605F1521C672E4000235C62 /* NSString.swift */,
|
||||
C96C0F242084A442006B2981 /* SQLiteDateParser.swift */,
|
||||
5657AB0E1D10899D006283EF /* URL.swift */,
|
||||
56A8C22F1D1914540096E9D4 /* UUID.swift */,
|
||||
C96C0F242084A442006B2981 /* SQLiteDateParser.swift */,
|
||||
);
|
||||
path = Foundation;
|
||||
sourceTree = "<group>";
|
||||
@@ -1816,7 +1814,9 @@
|
||||
56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */,
|
||||
56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */,
|
||||
56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */,
|
||||
56DA7CF6260FA9D400A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */,
|
||||
56A238261B9C74A90082EB20 /* RecordMinimalPrimaryKeyRowIDTests.swift */,
|
||||
56DA7CEA260FA9A400A8D97B /* RecordInitializersTests.swift */,
|
||||
56A238271B9C74A90082EB20 /* RecordMinimalPrimaryKeySingleTests.swift */,
|
||||
6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */,
|
||||
5698ACCD1DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift */,
|
||||
@@ -1882,6 +1882,7 @@
|
||||
56300B6D1C53F592005A543B /* QueryInterface */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56256ED825D1B316008C2BDD /* ForeignKey.swift */,
|
||||
56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterface.swift */,
|
||||
56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */,
|
||||
5656A8182295B044001FF3FF /* Request */,
|
||||
@@ -2002,6 +2003,7 @@
|
||||
56DF001A228DDBA300D611F3 /* AssociationPrefetchingCodableRecordTests.swift */,
|
||||
569BBA20228DE51800478429 /* AssociationPrefetchingFetchableRecordTests.swift */,
|
||||
560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */,
|
||||
5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */,
|
||||
56DF0019228DDBA200D611F3 /* AssociationPrefetchingRowTests.swift */,
|
||||
560714E2227DD0810091BB10 /* AssociationPrefetchingSQLTests.swift */,
|
||||
5653EAC820944B4D00F46237 /* AssociationRowScopeSearchTests.swift */,
|
||||
@@ -2049,21 +2051,15 @@
|
||||
56CEB5401EAA359A00BFAF62 /* Column.swift */,
|
||||
56D91AA82205F2F000770D8D /* DatabasePromise.swift */,
|
||||
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 */,
|
||||
56D91AAF2205F8AC00770D8D /* SQLQuery.swift */,
|
||||
568ECA9E25D7E53E00B71526 /* SQLOrdering.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 +2070,6 @@
|
||||
5653EAF720944BC900F46237 /* Association */,
|
||||
56012B742574048B00B4925B /* CommonTableExpression.swift */,
|
||||
56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */,
|
||||
5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */,
|
||||
5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */,
|
||||
);
|
||||
path = Request;
|
||||
@@ -2083,6 +2078,7 @@
|
||||
5659F4861EA8D94E004A4992 /* Utils */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56717270261C68E900423B6F /* CaseInsensitiveIdentifier.swift */,
|
||||
563EF4492161F179007DAACD /* Inflections.swift */,
|
||||
569BBA482291707D00478429 /* Inflections+English.swift */,
|
||||
566BE7172342542F00A8254B /* LockedBox.swift */,
|
||||
@@ -2161,6 +2157,7 @@
|
||||
569978D31B539038005EBEED /* Private */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
564D4F7D261C6DC200F55856 /* CaseInsensitiveIdentifierTests.swift */,
|
||||
563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */,
|
||||
569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */,
|
||||
563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */,
|
||||
@@ -2300,16 +2297,16 @@
|
||||
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 */,
|
||||
56E9FAD7221053DC00C703A8 /* SQL.swift */,
|
||||
569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */,
|
||||
56E9FAD7221053DC00C703A8 /* SQLLiteral.swift */,
|
||||
56FBFED82210731A00945324 /* SQLRequest.swift */,
|
||||
56A238781B9C75030082EB20 /* Statement.swift */,
|
||||
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
|
||||
@@ -2388,6 +2385,7 @@
|
||||
5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */,
|
||||
5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */,
|
||||
5690C3361D23E7D200E59934 /* FoundationDateTests.swift */,
|
||||
56894F742606576600268F4D /* FoundationDecimalTests.swift */,
|
||||
5657AB301D108BA9006283EF /* FoundationNSDataTests.swift */,
|
||||
56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */,
|
||||
561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */,
|
||||
@@ -2455,8 +2453,8 @@
|
||||
DC37742D19C8CC90004FCF85 /* GRDB */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56A2386F1B9C75030082EB20 /* Core */,
|
||||
56A2FA3524424D2A00E97D23 /* Export.swift */,
|
||||
56A2386F1B9C75030082EB20 /* Core */,
|
||||
56D7E449221595FE0052464B /* Fixit */,
|
||||
5698AC291D9E5A480056AF8C /* FTS */,
|
||||
56A238911B9C750B0082EB20 /* Migration */,
|
||||
@@ -2876,37 +2874,34 @@
|
||||
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 */,
|
||||
5656A8B22295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
|
||||
56D91AB22205F8AC00770D8D /* SQLQuery.swift in Sources */,
|
||||
56B964B71DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
|
||||
5653EB0B20944C7C00F46237 /* Association.swift in Sources */,
|
||||
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 */,
|
||||
56894FD12606589C00268F4D /* Decimal.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,8 +2921,9 @@
|
||||
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 */,
|
||||
56E9FAD9221053DD00C703A8 /* SQL.swift in Sources */,
|
||||
563082E62430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */,
|
||||
56B964A31DA51B4C0002DA19 /* FTS5.swift in Sources */,
|
||||
56D91AAB2205F2F100770D8D /* DatabasePromise.swift in Sources */,
|
||||
@@ -2954,12 +2950,11 @@
|
||||
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 */,
|
||||
5674A7071F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
|
||||
565490C61D5AE236005622CB /* Statement.swift in Sources */,
|
||||
56CEB5071EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
|
||||
@@ -2970,7 +2965,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 +2983,14 @@
|
||||
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 */,
|
||||
56717273261C68EA00423B6F /* CaseInsensitiveIdentifier.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 +3018,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 */,
|
||||
@@ -3032,7 +3027,6 @@
|
||||
5656A8B12295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
|
||||
56CEB5561EAA359A00BFAF62 /* SQLExpression.swift in Sources */,
|
||||
5674A6F91F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */,
|
||||
5605F18E1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */,
|
||||
566475D61D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
|
||||
5698AD381DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
|
||||
56012BA8257404E000B4925B /* CommonTableExpression.swift in Sources */,
|
||||
@@ -3041,10 +3035,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 +3059,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,17 +3081,16 @@
|
||||
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 */,
|
||||
5659F4931EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
|
||||
56D91AB12205F8AC00770D8D /* SQLQuery.swift in Sources */,
|
||||
56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */,
|
||||
5690C3431D23E82A00E59934 /* Data.swift in Sources */,
|
||||
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 */,
|
||||
@@ -3117,15 +3108,15 @@
|
||||
56D91AAA2205F2F100770D8D /* DatabasePromise.swift in Sources */,
|
||||
566BE71F2342542F00A8254B /* LockedBox.swift in Sources */,
|
||||
5698AC7B1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */,
|
||||
56894FC82606589B00268F4D /* Decimal.swift in Sources */,
|
||||
569D6DDF220EF9E100A058A9 /* SQLInterpolation.swift in Sources */,
|
||||
56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */,
|
||||
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 +3124,19 @@
|
||||
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 */,
|
||||
56717272261C68EA00423B6F /* CaseInsensitiveIdentifier.swift in Sources */,
|
||||
5613ED3621A95A5C00DC7A68 /* Map.swift in Sources */,
|
||||
566475A51D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */,
|
||||
56E9FAD8221053DD00C703A8 /* SQLLiteral.swift in Sources */,
|
||||
56E9FAD8221053DD00C703A8 /* SQL.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 */,
|
||||
@@ -3172,9 +3162,11 @@
|
||||
563EF45421631E21007DAACD /* QueryInterfacePromiseTests.swift in Sources */,
|
||||
56A238501B9C74A90082EB20 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
|
||||
564448871EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
|
||||
56894F762606576700268F4D /* FoundationDecimalTests.swift in Sources */,
|
||||
56A238461B9C74A90082EB20 /* RowFromDictionaryTests.swift in Sources */,
|
||||
569C1EB51CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */,
|
||||
562EA82A1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */,
|
||||
56DA7CF8260FA9D400A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */,
|
||||
564A50C81BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift in Sources */,
|
||||
56E8CE111BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift in Sources */,
|
||||
56300B691C53D25E005A543B /* QueryInterfaceExpressionsTests.swift in Sources */,
|
||||
@@ -3287,6 +3279,7 @@
|
||||
56419C5924A51999004967E1 /* Finished.swift in Sources */,
|
||||
56A2386A1B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */,
|
||||
56A2383E1B9C74A90082EB20 /* DatabaseValueTests.swift in Sources */,
|
||||
564D4F7F261C6DC200F55856 /* CaseInsensitiveIdentifierTests.swift in Sources */,
|
||||
567156181CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */,
|
||||
56EA86951C91DFE7002BB4DF /* DatabaseReaderTests.swift in Sources */,
|
||||
56A8C2471D1918F00096E9D4 /* FoundationNSUUIDTests.swift in Sources */,
|
||||
@@ -3312,6 +3305,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 */,
|
||||
@@ -3398,9 +3392,11 @@
|
||||
563EF45321631E21007DAACD /* QueryInterfacePromiseTests.swift in Sources */,
|
||||
56D4966D1D81309E008276D7 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */,
|
||||
564448831EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
|
||||
56894F752606576600268F4D /* FoundationDecimalTests.swift in Sources */,
|
||||
56D496811D813131008276D7 /* TransactionObserverSavepointsTests.swift in Sources */,
|
||||
56D496AB1D8132CA008276D7 /* DatabasePoolFunctionTests.swift in Sources */,
|
||||
562EA8261F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */,
|
||||
56DA7CF7260FA9D400A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */,
|
||||
56D496691D813086008276D7 /* QueryInterfaceExpressionsTests.swift in Sources */,
|
||||
562393691DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */,
|
||||
562205F21E420E47005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */,
|
||||
@@ -3513,6 +3509,7 @@
|
||||
56FEB8F8248403000081AF83 /* DatabaseTraceTests.swift in Sources */,
|
||||
56419C5124A51998004967E1 /* Finished.swift in Sources */,
|
||||
56176C5E1EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */,
|
||||
564D4F7E261C6DC200F55856 /* CaseInsensitiveIdentifierTests.swift in Sources */,
|
||||
56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */,
|
||||
56D496641D81304E008276D7 /* FoundationUUIDTests.swift in Sources */,
|
||||
56D496921D81316E008276D7 /* RowFromDictionaryLiteralTests.swift in Sources */,
|
||||
@@ -3538,6 +3535,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 +3609,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 */,
|
||||
@@ -3619,7 +3618,6 @@
|
||||
AAA4DC7B230F1E0600C74B15 /* TableRecord+QueryInterfaceRequest.swift in Sources */,
|
||||
AAA4DC7C230F1E0600C74B15 /* SQLExpression.swift in Sources */,
|
||||
AAA4DC7D230F1E0600C74B15 /* EncodableRecord+Encodable.swift in Sources */,
|
||||
AAA4DC7E230F1E0600C74B15 /* SQLCollatedExpression.swift in Sources */,
|
||||
AAA4DC7F230F1E0600C74B15 /* SQLOperators.swift in Sources */,
|
||||
AAA4DC80230F1E0600C74B15 /* FTS5CustomTokenizer.swift in Sources */,
|
||||
56012BB2257404E200B4925B /* CommonTableExpression.swift in Sources */,
|
||||
@@ -3628,10 +3626,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 +3650,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,17 +3672,16 @@
|
||||
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 */,
|
||||
AAA4DCB6230F1E0600C74B15 /* ReadWriteBox.swift in Sources */,
|
||||
AAA4DCB7230F1E0600C74B15 /* SQLQuery.swift in Sources */,
|
||||
AAA4DCB8230F1E0600C74B15 /* Migration.swift in Sources */,
|
||||
AAA4DCB9230F1E0600C74B15 /* Data.swift in Sources */,
|
||||
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 */,
|
||||
@@ -3704,15 +3699,15 @@
|
||||
AAA4DCCE230F1E0600C74B15 /* DatabasePromise.swift in Sources */,
|
||||
566BE7212342542F00A8254B /* LockedBox.swift in Sources */,
|
||||
AAA4DCCF230F1E0600C74B15 /* VirtualTableModule.swift in Sources */,
|
||||
56894FD22606589D00268F4D /* Decimal.swift in Sources */,
|
||||
AAA4DCD0230F1E0600C74B15 /* SQLInterpolation.swift in Sources */,
|
||||
AAA4DCD1230F1E0600C74B15 /* DatabaseError.swift in Sources */,
|
||||
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 +3715,19 @@
|
||||
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 */,
|
||||
56717274261C68EA00423B6F /* CaseInsensitiveIdentifier.swift in Sources */,
|
||||
AAA4DCE3230F1E0600C74B15 /* Map.swift in Sources */,
|
||||
AAA4DCE4230F1E0600C74B15 /* SQLSelectable+QueryInterface.swift in Sources */,
|
||||
AAA4DCE5230F1E0600C74B15 /* SQLLiteral.swift in Sources */,
|
||||
AAA4DCE5230F1E0600C74B15 /* SQL.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 */,
|
||||
@@ -3759,9 +3753,11 @@
|
||||
AAA4DD14230F262000C74B15 /* QueryInterfacePromiseTests.swift in Sources */,
|
||||
AAA4DD15230F262000C74B15 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
|
||||
AAA4DD16230F262000C74B15 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
|
||||
56894F772606576700268F4D /* FoundationDecimalTests.swift in Sources */,
|
||||
AAA4DD17230F262000C74B15 /* RowFromDictionaryTests.swift in Sources */,
|
||||
AAA4DD18230F262000C74B15 /* SchedulingWatchdogTests.swift in Sources */,
|
||||
AAA4DD19230F262000C74B15 /* CompilationProtocolTests.swift in Sources */,
|
||||
56DA7CF9260FA9D400A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */,
|
||||
AAA4DD1A230F262000C74B15 /* DatabaseCollationTests.swift in Sources */,
|
||||
AAA4DD1B230F262000C74B15 /* StatementColumnConvertibleFetchTests.swift in Sources */,
|
||||
AAA4DD1C230F262000C74B15 /* QueryInterfaceExpressionsTests.swift in Sources */,
|
||||
@@ -3874,6 +3870,7 @@
|
||||
56419C6124A5199B004967E1 /* Finished.swift in Sources */,
|
||||
AAA4DD79230F262000C74B15 /* RecordSubClassTests.swift in Sources */,
|
||||
AAA4DD7A230F262000C74B15 /* DatabaseValueTests.swift in Sources */,
|
||||
564D4F80261C6DC200F55856 /* CaseInsensitiveIdentifierTests.swift in Sources */,
|
||||
AAA4DD7B230F262000C74B15 /* DatabaseQueueReadOnlyTests.swift in Sources */,
|
||||
AAA4DD7C230F262000C74B15 /* DatabaseReaderTests.swift in Sources */,
|
||||
AAA4DD7D230F262000C74B15 /* FoundationNSUUIDTests.swift in Sources */,
|
||||
@@ -3899,6 +3896,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,8 +3970,8 @@
|
||||
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 */,
|
||||
563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
5656A8B02295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
|
||||
@@ -3992,11 +3990,10 @@
|
||||
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 +4013,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 +4024,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 +4052,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 */,
|
||||
@@ -4067,13 +4060,14 @@
|
||||
568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */,
|
||||
5605F15D1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */,
|
||||
567ECE4F2222E431009245CA /* GRDB-5.0.swift in Sources */,
|
||||
56894FB72606589700268F4D /* Decimal.swift in Sources */,
|
||||
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,10 +4075,12 @@
|
||||
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 */,
|
||||
56E9FADA221053DD00C703A8 /* SQLLiteral.swift in Sources */,
|
||||
56E9FADA221053DD00C703A8 /* SQL.swift in Sources */,
|
||||
56717271261C68E900423B6F /* CaseInsensitiveIdentifier.swift in Sources */,
|
||||
C96C0F2B2084A442006B2981 /* SQLiteDateParser.swift in Sources */,
|
||||
56781B0B243F86E600650A83 /* Refinable.swift in Sources */,
|
||||
56A238871B9C75030082EB20 /* Row.swift in Sources */,
|
||||
@@ -4092,10 +4088,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 */,
|
||||
|
||||
@@ -108,6 +108,9 @@ public struct Configuration {
|
||||
/// The function argument is run when an SQLite connection is opened,
|
||||
/// before the connection is made available for database access methods.
|
||||
///
|
||||
/// This method can be called several times. The preparation functions are
|
||||
/// run in the same order.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
@@ -115,8 +118,21 @@ public struct Configuration {
|
||||
/// try db.execute(sql: "PRAGMA kdf_iter = 10000")
|
||||
/// }
|
||||
///
|
||||
/// This method can be called several times. The setup functions are run in
|
||||
/// the same order.
|
||||
/// When you use a `DatabasePool`, preparation functions are called for
|
||||
/// the writer connection and all reader connections. You can distinguish
|
||||
/// them by querying `db.configuration.readonly`:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// if db.configuration.readonly {
|
||||
/// // reader connection
|
||||
/// } else {
|
||||
/// // writer connection
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// On newly created databases, `DatabasePool` the WAL mode is activated
|
||||
/// after the preparation functions have run.
|
||||
public mutating func prepareDatabase(_ setup: @escaping (Database) throws -> Void) {
|
||||
setups.append(setup)
|
||||
}
|
||||
|
||||
+148
-21
@@ -9,13 +9,16 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// MARK: - Array, Sequence, Dictionary, Set extensions
|
||||
// MARK: - RangeReplaceableCollection, Sequence, Dictionary, Set extensions
|
||||
|
||||
extension Array {
|
||||
/// Creates an array containing the elements of a cursor.
|
||||
extension RangeReplaceableCollection {
|
||||
/// Creates a collection containing the elements of a cursor.
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
|
||||
/// let strings = try Array(cursor) // ["foo", "bar"]
|
||||
/// // [String]
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Array(cursor)
|
||||
///
|
||||
/// - parameter cursor: The cursor whose elements feed the collection.
|
||||
@inlinable
|
||||
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
|
||||
self.init()
|
||||
@@ -23,24 +26,161 @@ extension Array {
|
||||
append(element)
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a collection containing the elements of a cursor.
|
||||
///
|
||||
/// // [String]
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Array(cursor, minimumCapacity: 100)
|
||||
///
|
||||
/// - parameter cursor: The cursor whose elements feed the collection.
|
||||
/// - parameter minimumCapacity: Prepares the returned collection to store
|
||||
/// the specified number of elements.
|
||||
@inlinable
|
||||
public init<C: Cursor>(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element {
|
||||
self.init()
|
||||
reserveCapacity(minimumCapacity)
|
||||
while let element = try cursor.next() {
|
||||
append(element)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Dictionary {
|
||||
/// Creates a new dictionary whose keys are the groupings returned by the
|
||||
/// given closure and whose values are arrays of the elements that returned
|
||||
/// each key.
|
||||
public init<C: Cursor>(grouping values: C, by keyForValue: (C.Element) throws -> Key)
|
||||
///
|
||||
/// // [Int64: [Player]]
|
||||
/// let cursor = try Player.fetchCursor(db)
|
||||
/// let dictionary = try Dictionary(grouping: cursor, by: { $0.teamID })
|
||||
///
|
||||
/// - parameter cursor: A cursor of values to group into a dictionary.
|
||||
/// - parameter keyForValue: A closure that returns a key for each element
|
||||
/// in the cursor.
|
||||
public init<C: Cursor>(grouping cursor: C, by keyForValue: (C.Element) throws -> Key)
|
||||
throws where Value == [C.Element]
|
||||
{
|
||||
self.init()
|
||||
while let value = try values.next() {
|
||||
while let value = try cursor.next() {
|
||||
try self[keyForValue(value), default: []].append(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new dictionary whose keys are the groupings returned by the
|
||||
/// given closure and whose values are arrays of the elements that returned
|
||||
/// each key.
|
||||
///
|
||||
/// // [Int64: [Player]]
|
||||
/// let cursor = try Player.fetchCursor(db)
|
||||
/// let dictionary = try Dictionary(
|
||||
/// minimumCapacity: 100,
|
||||
/// grouping: cursor,
|
||||
/// by: { $0.teamID })
|
||||
///
|
||||
/// - parameter minimumCapacity: The minimum number of key-value pairs that
|
||||
/// the newly created dictionary should be able to store without
|
||||
/// reallocating its storage buffer.
|
||||
/// - parameter cursor: A cursor of values to group into a dictionary.
|
||||
/// - parameter keyForValue: A closure that returns a key for each element
|
||||
/// in the cursor.
|
||||
public init<C: Cursor>(minimumCapacity: Int, grouping cursor: C, by keyForValue: (C.Element) throws -> Key)
|
||||
throws where Value == [C.Element]
|
||||
{
|
||||
self.init(minimumCapacity: minimumCapacity)
|
||||
while let value = try cursor.next() {
|
||||
try self[keyForValue(value), default: []].append(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new dictionary from the key-value pairs in the given cursor.
|
||||
///
|
||||
/// You use this initializer to create a dictionary when you have a cursor
|
||||
/// of key-value tuples with unique keys. Passing a cursor with duplicate
|
||||
/// keys to this initializer results in a fatal error.
|
||||
///
|
||||
/// // [Int64: Player]
|
||||
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
|
||||
/// let playerByID = try Dictionary(uniqueKeysWithValues: cursor)
|
||||
///
|
||||
/// - parameter keysAndValues: A cursor of key-value pairs to use for the
|
||||
/// new dictionary. Every key in `keysAndValues` must be unique.
|
||||
/// - precondition: The cursor must not have duplicate keys.
|
||||
public init<C: Cursor>(uniqueKeysWithValues keysAndValues: C)
|
||||
throws where C.Element == (Key, Value)
|
||||
{
|
||||
self.init()
|
||||
while let (key, value) = try keysAndValues.next() {
|
||||
if updateValue(value, forKey: key) != nil {
|
||||
fatalError("Duplicate values for key: '\(String(describing: key))'")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new dictionary from the key-value pairs in the given cursor.
|
||||
///
|
||||
/// You use this initializer to create a dictionary when you have a cursor
|
||||
/// of key-value tuples with unique keys. Passing a cursor with duplicate
|
||||
/// keys to this initializer results in a fatal error.
|
||||
///
|
||||
/// // [Int64: Player]
|
||||
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
|
||||
/// let playerByID = try Dictionary(
|
||||
/// minimumCapacity: 100,
|
||||
/// uniqueKeysWithValues: cursor)
|
||||
///
|
||||
/// - parameter minimumCapacity: The minimum number of key-value pairs that
|
||||
/// the newly created dictionary should be able to store without
|
||||
/// reallocating its storage buffer.
|
||||
/// - parameter keysAndValues: A cursor of key-value pairs to use for the
|
||||
/// new dictionary. Every key in `keysAndValues` must be unique.
|
||||
/// - precondition: The cursor must not have duplicate keys.
|
||||
public init<C: Cursor>(minimumCapacity: Int, uniqueKeysWithValues keysAndValues: C)
|
||||
throws where C.Element == (Key, Value)
|
||||
{
|
||||
self.init(minimumCapacity: minimumCapacity)
|
||||
while let (key, value) = try keysAndValues.next() {
|
||||
if updateValue(value, forKey: key) != nil {
|
||||
fatalError("Duplicate values for key: '\(String(describing: key))'")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Set {
|
||||
/// Creates a set containing the elements of a cursor.
|
||||
///
|
||||
/// // Set<String>
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Set(cursor)
|
||||
///
|
||||
/// - parameter cursor: A cursor of values to gather into a set.
|
||||
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
|
||||
self.init()
|
||||
while let element = try cursor.next() {
|
||||
insert(element)
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a set containing the elements of a cursor.
|
||||
///
|
||||
/// // Set<String>
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Set(cursor, minimumCapacity: 100)
|
||||
///
|
||||
/// - parameter cursor: A cursor of values to gather into a set.
|
||||
/// - parameter minimumCapacity: The minimum number of elements that the
|
||||
/// newly created set should be able to store without reallocating its
|
||||
/// storage buffer.
|
||||
public init<C: Cursor>(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element {
|
||||
self.init(minimumCapacity: minimumCapacity)
|
||||
while let element = try cursor.next() {
|
||||
insert(element)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult: Cursor>(
|
||||
@@ -51,19 +191,6 @@ extension Sequence {
|
||||
}
|
||||
}
|
||||
|
||||
extension Set {
|
||||
/// Creates a set containing the elements of a cursor.
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'foo'")
|
||||
/// let strings = try Set(cursor) // ["foo"]
|
||||
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
|
||||
self.init()
|
||||
while let element = try cursor.next() {
|
||||
insert(element)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Cursor
|
||||
|
||||
/// A type that supplies the values of some external resource, one at a time.
|
||||
|
||||
+259
-72
@@ -1,4 +1,51 @@
|
||||
extension Database {
|
||||
/// A SQLite schema. See https://sqlite.org/lang_naming.html
|
||||
enum SchemaIdentifier: Hashable {
|
||||
/// The main database
|
||||
case main
|
||||
|
||||
/// The temp database
|
||||
case temp
|
||||
|
||||
/// An attached database: https://sqlite.org/lang_attach.html
|
||||
case attached(String)
|
||||
|
||||
/// The name of the schema in SQL queries
|
||||
var sql: String {
|
||||
switch self {
|
||||
case .main: return "main"
|
||||
case .temp: return "temp"
|
||||
case let .attached(name): return name
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of the master sqlite table
|
||||
var masterTableName: String { // swiftlint:disable:this inclusive_language
|
||||
switch self {
|
||||
case .main: return "sqlite_master"
|
||||
case .temp: return "sqlite_temp_master"
|
||||
case let .attached(name): return "\(name).sqlite_master"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A table identifier
|
||||
struct TableIdentifier {
|
||||
/// The SQLite schema
|
||||
var schemaID: SchemaIdentifier
|
||||
|
||||
/// The table name
|
||||
var name: String
|
||||
|
||||
/// Returns the receiver, quoted for safe insertion as an identifier in
|
||||
/// an SQL query.
|
||||
///
|
||||
/// // SELECT * FROM temp.player
|
||||
/// db.execute(sql: "SELECT * FROM \(table.quotedDatabaseIdentifier)")
|
||||
var quotedDatabaseIdentifier: String {
|
||||
"\(schemaID.sql).\(name.quotedDatabaseIdentifier)"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Database Schema
|
||||
|
||||
@@ -28,9 +75,41 @@ extension Database {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether a table exists.
|
||||
/// The list of database schemas, in the order of SQLite resolution:
|
||||
/// temp, main, then attached databases.
|
||||
func schemaIdentifiers() throws -> [SchemaIdentifier] {
|
||||
if let schemaIdentifiers = schemaCache.schemaIdentifiers {
|
||||
return schemaIdentifiers
|
||||
}
|
||||
|
||||
var schemaIdentifiers = try Row
|
||||
.fetchAll(self, sql: "PRAGMA database_list")
|
||||
.map { row -> SchemaIdentifier in
|
||||
switch row[1] as String {
|
||||
case "main": return .main
|
||||
case "temp": return .temp
|
||||
case let other: return .attached(other)
|
||||
}
|
||||
}
|
||||
|
||||
// Temp schema shadows other schema: put it first
|
||||
if let tempIdx = schemaIdentifiers.firstIndex(of: .temp) {
|
||||
schemaIdentifiers.swapAt(tempIdx, 0)
|
||||
}
|
||||
|
||||
schemaCache.schemaIdentifiers = schemaIdentifiers
|
||||
return schemaIdentifiers
|
||||
}
|
||||
|
||||
/// Returns whether a table exists in the main or temp schema.
|
||||
public func tableExists(_ name: String) throws -> Bool {
|
||||
try exists(type: .table, name: name)
|
||||
try schemaIdentifiers().contains {
|
||||
try exists(type: .table, name: name, in: $0)
|
||||
}
|
||||
}
|
||||
|
||||
private func tableExists(_ table: TableIdentifier) throws -> Bool {
|
||||
try exists(type: .table, name: table.name, in: table.schemaID)
|
||||
}
|
||||
|
||||
/// Returns whether a table is an internal SQLite table.
|
||||
@@ -73,26 +152,30 @@ extension Database {
|
||||
Self.isGRDBInternalTable(tableName)
|
||||
}
|
||||
|
||||
/// Returns whether a view exists.
|
||||
/// Returns whether a view exists in the main or temp schema.
|
||||
public func viewExists(_ name: String) throws -> Bool {
|
||||
try exists(type: .view, name: name)
|
||||
try schemaIdentifiers().contains {
|
||||
try exists(type: .view, name: name, in: $0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether a trigger exists.
|
||||
/// Returns whether a trigger exists in the main or temp schema.
|
||||
public func triggerExists(_ name: String) throws -> Bool {
|
||||
try exists(type: .trigger, name: name)
|
||||
try schemaIdentifiers().contains {
|
||||
try exists(type: .trigger, name: name, in: $0)
|
||||
}
|
||||
}
|
||||
|
||||
private func exists(type: SchemaObjectType, name: String) throws -> Bool {
|
||||
private func exists(type: SchemaObjectType, name: String, in schemaID: SchemaIdentifier) throws -> Bool {
|
||||
// SQlite identifiers are case-insensitive, case-preserving:
|
||||
// http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html
|
||||
let name = name.lowercased()
|
||||
return try schema()
|
||||
return try schema(schemaID)
|
||||
.names(ofType: type)
|
||||
.contains { $0.lowercased() == name }
|
||||
}
|
||||
|
||||
/// The primary key for table named `tableName`.
|
||||
/// The primary key for table named `tableName`, in the main or temp schema.
|
||||
///
|
||||
/// All tables have a primary key, even when it is not explicit. When a
|
||||
/// table has no explicit primary key, the result is the hidden
|
||||
@@ -100,10 +183,20 @@ extension Database {
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
public func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo {
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try primaryKey(TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
return result
|
||||
}
|
||||
}
|
||||
throw DatabaseError.noSuchTable(tableName)
|
||||
}
|
||||
|
||||
/// Returns nil if table does not exist
|
||||
private func primaryKey(_ table: TableIdentifier) throws -> PrimaryKeyInfo? {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
|
||||
if let primaryKey = schemaCache.primaryKey(tableName) {
|
||||
return primaryKey
|
||||
if let primaryKey = schemaCache[table.schemaID].primaryKey(table.name) {
|
||||
return primaryKey.value
|
||||
}
|
||||
|
||||
// https://www.sqlite.org/pragma.html
|
||||
@@ -130,7 +223,11 @@ extension Database {
|
||||
// 1 | name | TEXT | 0 | NULL | 0 |
|
||||
// 2 | score | INTEGER | 0 | NULL | 0 |
|
||||
|
||||
let columns = try self.columns(in: tableName)
|
||||
guard let columns = try self.columns(in: table) else {
|
||||
// table does not exist
|
||||
schemaCache[table.schemaID].set(primaryKey: .missing, forTable: table.name)
|
||||
return nil
|
||||
}
|
||||
|
||||
let primaryKey: PrimaryKeyInfo
|
||||
let pkColumns = columns
|
||||
@@ -168,14 +265,14 @@ extension Database {
|
||||
if pkColumn.type.uppercased() == "INTEGER" {
|
||||
primaryKey = .rowID(pkColumn.name)
|
||||
} else {
|
||||
primaryKey = try .regular([pkColumn.name], tableHasRowID: tableHasRowID(tableName))
|
||||
primaryKey = try .regular([pkColumn.name], tableHasRowID: tableHasRowID(table))
|
||||
}
|
||||
default:
|
||||
// Multi-columns primary key
|
||||
primaryKey = try .regular(pkColumns.map(\.name), tableHasRowID: tableHasRowID(tableName))
|
||||
primaryKey = try .regular(pkColumns.map(\.name), tableHasRowID: tableHasRowID(table))
|
||||
}
|
||||
|
||||
schemaCache.set(primaryKey: primaryKey, forTable: tableName)
|
||||
schemaCache[table.schemaID].set(primaryKey: .value(primaryKey), forTable: table.name)
|
||||
return primaryKey
|
||||
}
|
||||
|
||||
@@ -186,18 +283,28 @@ extension Database {
|
||||
}
|
||||
|
||||
/// Returns whether the table has a rowid column.
|
||||
private func tableHasRowID(_ tableName: String) throws -> Bool {
|
||||
///
|
||||
/// - precondition: table exists.
|
||||
private func tableHasRowID(_ table: TableIdentifier) throws -> Bool {
|
||||
// Not need to cache the result, because this information feeds
|
||||
// `PrimaryKeyInfo`, which is cached.
|
||||
do {
|
||||
_ = try makeSelectStatement(sql: "SELECT rowid FROM \(tableName.quotedDatabaseIdentifier)")
|
||||
// Use a distinctive alias so that we better understand in the
|
||||
// future why this query appears in the error log.
|
||||
// https://github.com/groue/GRDB.swift/issues/945#issuecomment-804896196
|
||||
//
|
||||
// TODO: find a way to know if a table is WITHOUT ROWID without
|
||||
// generating an error.
|
||||
_ = try makeSelectStatement(sql: """
|
||||
SELECT rowid AS checkWithoutRowidOptimization FROM \(table.quotedDatabaseIdentifier)
|
||||
""")
|
||||
return true
|
||||
} catch DatabaseError.SQLITE_ERROR {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// The indexes on table named `tableName`.
|
||||
/// The indexes on table named `tableName`, in the main or temp schema.
|
||||
///
|
||||
/// Only indexes on columns are returned. Indexes on expressions are
|
||||
/// not returned.
|
||||
@@ -207,21 +314,35 @@ extension Database {
|
||||
///
|
||||
/// If you want to know if a set of columns uniquely identify a row, prefer
|
||||
/// `table(_:hasUniqueKey:)` instead.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
public func indexes(on tableName: String) throws -> [IndexInfo] {
|
||||
if let indexes = schemaCache.indexes(on: tableName) {
|
||||
return indexes
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try indexes(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
return result
|
||||
}
|
||||
}
|
||||
throw DatabaseError.noSuchTable(tableName)
|
||||
}
|
||||
|
||||
/// Returns nil if table does not exist
|
||||
private func indexes(on table: TableIdentifier) throws -> [IndexInfo]? {
|
||||
if let indexes = schemaCache[table.schemaID].indexes(on: table.name) {
|
||||
return indexes.value
|
||||
}
|
||||
|
||||
let indexes = try Row
|
||||
// [seq:0 name:"index" unique:0 origin:"c" partial:0]
|
||||
.fetchAll(self, sql: "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))")
|
||||
.fetchAll(self, sql: "PRAGMA \(table.schemaID.sql).index_list(\(table.name.quotedDatabaseIdentifier))")
|
||||
.compactMap { row -> IndexInfo? in
|
||||
let indexName: String = row[1]
|
||||
let unique: Bool = row[2]
|
||||
|
||||
let indexInfoRows = try Row
|
||||
// [seqno:0 cid:2 name:"column"]
|
||||
.fetchAll(self, sql: "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))")
|
||||
.fetchAll(self, sql: """
|
||||
PRAGMA \(table.schemaID.sql).index_info(\(indexName.quotedDatabaseIdentifier))
|
||||
""")
|
||||
// Sort by rank
|
||||
.sorted(by: { ($0[0] as Int) < ($1[0] as Int) })
|
||||
var columns: [String] = []
|
||||
@@ -243,12 +364,13 @@ extension Database {
|
||||
if indexes.isEmpty {
|
||||
// PRAGMA index_list doesn't throw any error when table does
|
||||
// not exist. So let's check if table exists:
|
||||
if try tableExists(tableName) == false {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
if try tableExists(table) == false {
|
||||
schemaCache[table.schemaID].set(indexes: .missing, forTable: table.name)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
schemaCache.set(indexes: indexes, forTable: tableName)
|
||||
schemaCache[table.schemaID].set(indexes: .value(indexes), forTable: table.name)
|
||||
return indexes
|
||||
}
|
||||
|
||||
@@ -263,17 +385,32 @@ extension Database {
|
||||
try columnsForUniqueKey(Array(columns), in: tableName) != nil
|
||||
}
|
||||
|
||||
/// The foreign keys defined on table named `tableName`.
|
||||
/// The foreign keys defined on table named `tableName`, in the main or temp schema.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo] {
|
||||
if let foreignKeys = schemaCache.foreignKeys(on: tableName) {
|
||||
return foreignKeys
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try foreignKeys(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
return result
|
||||
}
|
||||
}
|
||||
throw DatabaseError.noSuchTable(tableName)
|
||||
}
|
||||
|
||||
/// Returns nil if table does not exist
|
||||
private func foreignKeys(on table: TableIdentifier) throws -> [ForeignKeyInfo]? {
|
||||
if let foreignKeys = schemaCache[table.schemaID].foreignKeys(on: table.name) {
|
||||
return foreignKeys.value
|
||||
}
|
||||
|
||||
var rawForeignKeys: [(
|
||||
destinationTable: String,
|
||||
mapping: [(origin: String, destination: String?, seq: Int)])] = []
|
||||
var previousId: Int? = nil
|
||||
for row in try Row.fetchAll(self, sql: "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") {
|
||||
for row in try Row.fetchAll(self, sql: """
|
||||
PRAGMA \(table.schemaID.sql).foreign_key_list(\(table.name.quotedDatabaseIdentifier))
|
||||
""")
|
||||
{
|
||||
// row = [id:0 seq:0 table:"parents" from:"parentId" to:"id" on_update:"..." on_delete:"..." match:"..."]
|
||||
let id: Int = row[0]
|
||||
let seq: Int = row[1]
|
||||
@@ -295,8 +432,9 @@ extension Database {
|
||||
if rawForeignKeys.isEmpty {
|
||||
// PRAGMA foreign_key_list doesn't throw any error when table does
|
||||
// not exist. So let's check if table exists:
|
||||
if try tableExists(tableName) == false {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
if try tableExists(table) == false {
|
||||
schemaCache[table.schemaID].set(foreignKeys: .missing, forTable: table.name)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -319,36 +457,51 @@ extension Database {
|
||||
return ForeignKeyInfo(destinationTable: destinationTable, mapping: completeMapping)
|
||||
}
|
||||
|
||||
schemaCache.set(foreignKeys: foreignKeys, forTable: tableName)
|
||||
schemaCache[table.schemaID].set(foreignKeys: .value(foreignKeys), forTable: table.name)
|
||||
return foreignKeys
|
||||
}
|
||||
|
||||
/// Returns the actual name of the database table
|
||||
func canonicalTableName(_ tableName: String) throws -> String {
|
||||
guard let name = try schema().canonicalName(tableName, ofType: .table) else {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
/// Returns the actual name of the database table, in the main or temp
|
||||
/// schema, or nil if the table does not exist.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
func canonicalTableName(_ tableName: String) throws -> String? {
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try schema(schemaIdentifier).canonicalName(tableName, ofType: .table) {
|
||||
return result
|
||||
}
|
||||
}
|
||||
return name
|
||||
return nil
|
||||
}
|
||||
|
||||
func schema() throws -> SchemaInfo {
|
||||
if let schemaInfo = schemaCache.schemaInfo {
|
||||
func schema(_ schemaID: SchemaIdentifier) throws -> SchemaInfo {
|
||||
if let schemaInfo = schemaCache[schemaID].schemaInfo {
|
||||
return schemaInfo
|
||||
}
|
||||
let schemaInfo = try SchemaInfo(self)
|
||||
schemaCache.schemaInfo = schemaInfo
|
||||
let schemaInfo = try SchemaInfo(self, masterTableName: schemaID.masterTableName)
|
||||
schemaCache[schemaID].schemaInfo = schemaInfo
|
||||
return schemaInfo
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
/// The columns in the table named `tableName`
|
||||
/// The columns in the table named `tableName`, in the main or temp schema.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
public func columns(in tableName: String) throws -> [ColumnInfo] {
|
||||
if let columns = schemaCache.columns(in: tableName) {
|
||||
return columns
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try columns(in: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
return result
|
||||
}
|
||||
}
|
||||
throw DatabaseError.noSuchTable(tableName)
|
||||
}
|
||||
|
||||
/// Returns nil if table does not exist
|
||||
private func columns(in table: TableIdentifier) throws -> [ColumnInfo]? {
|
||||
if let columns = schemaCache[table.schemaID].columns(in: table.name) {
|
||||
return columns.value
|
||||
}
|
||||
|
||||
// https://www.sqlite.org/pragma.html
|
||||
@@ -396,27 +549,35 @@ extension Database {
|
||||
if sqlite3_libversion_number() < 3008005 {
|
||||
// Work around a bug in SQLite where PRAGMA table_info would
|
||||
// return a result even after the table was deleted.
|
||||
if try !tableExists(tableName) {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
if try !tableExists(table) {
|
||||
schemaCache[table.schemaID].set(columns: .missing, forTable: table.name)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
columnInfoQuery = "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))"
|
||||
columnInfoQuery = "PRAGMA \(table.schemaID.sql).table_info(\(table.name.quotedDatabaseIdentifier))"
|
||||
} else {
|
||||
// For our purposes, we look for generated columns, not hidden
|
||||
// columns. The "hidden" column magic numbers come from the SQLite
|
||||
// source code. The values 2 and 3 refer to virtual and stored
|
||||
// generated columns, respectively. Search for COLFLAG_VIRTUAL in
|
||||
// https://www.sqlite.org/cgi/src/file?name=src/pragma.c&ci=fca8dc8b578f215a
|
||||
columnInfoQuery = "SELECT * FROM pragma_table_xinfo('\(tableName)') WHERE hidden IN (0,2,3)"
|
||||
// Use PRAGMA table_xinfo so that we can load generated columns
|
||||
columnInfoQuery = "PRAGMA \(table.schemaID.sql).table_xinfo(\(table.name.quotedDatabaseIdentifier))"
|
||||
}
|
||||
let columns = try ColumnInfo
|
||||
.fetchAll(self, sql: columnInfoQuery)
|
||||
.filter {
|
||||
// Purpose: keep generated columns, but discard hidden ones.
|
||||
// The "hidden" column magic numbers come from the SQLite
|
||||
// source code. The values 2 and 3 refer to virtual and stored
|
||||
// generated columns, respectively, and 1 refer to hidden one.
|
||||
// Search for COLFLAG_HIDDEN in
|
||||
// https://www.sqlite.org/cgi/src/file?name=src/pragma.c&ci=fca8dc8b578f215a
|
||||
$0.hidden != 1
|
||||
}
|
||||
.sorted(by: { $0.cid < $1.cid })
|
||||
if columns.isEmpty {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
// Table does not exist
|
||||
schemaCache[table.schemaID].set(columns: .missing, forTable: table.name)
|
||||
return nil
|
||||
}
|
||||
|
||||
schemaCache.set(columns: columns, forTable: tableName)
|
||||
schemaCache[table.schemaID].set(columns: .value(columns), forTable: table.name)
|
||||
return columns
|
||||
}
|
||||
|
||||
@@ -461,22 +622,29 @@ extension Database {
|
||||
/// A column of a database table.
|
||||
///
|
||||
/// This type closely matches the information returned by the
|
||||
/// `table_info` pragma.
|
||||
/// `table_info` and `table_xinfo` pragmas.
|
||||
///
|
||||
/// > CREATE TABLE player (
|
||||
/// id INTEGER PRIMARY KEY,
|
||||
/// firstName TEXT,
|
||||
/// lastName TEXT)
|
||||
/// > PRAGMA table_info("player")
|
||||
/// cid name type notnull dflt_value pk
|
||||
/// ---- ----- ------- -------- ---------- ---
|
||||
/// 0 id INTEGER 0 NULL 1
|
||||
/// 1 name TEXT 0 NULL 0
|
||||
/// 2 score INTEGER 0 NULL 0
|
||||
/// sqlite> CREATE TABLE player (
|
||||
/// ...> id INTEGER PRIMARY KEY,
|
||||
/// ...> firstName TEXT,
|
||||
/// ...> lastName TEXT);
|
||||
/// sqlite> PRAGMA table_info(player);
|
||||
/// cid name type notnull dflt_value pk
|
||||
/// ------ ---------- ---------- ---------- ---------- -----
|
||||
/// 0 id INTEGER 0 1
|
||||
/// 1 firstName TEXT 0 0
|
||||
/// 2 lastName TEXT 0 0
|
||||
/// sqlite> PRAGMA table_xinfo(player);
|
||||
/// cid name type notnull dflt_value pk hidden
|
||||
/// ------ ---------- ---------- ---------- ---------- ----- ----------
|
||||
/// 0 id INTEGER 0 1 0
|
||||
/// 1 firstName TEXT 0 0 0
|
||||
/// 2 lastName TEXT 0 0 0
|
||||
///
|
||||
/// See `Database.columns(in:)` and https://www.sqlite.org/pragma.html#pragma_table_info
|
||||
public struct ColumnInfo: FetchableRecord {
|
||||
let cid: Int
|
||||
let hidden: Int?
|
||||
|
||||
/// The column name
|
||||
public let name: String
|
||||
@@ -533,6 +701,7 @@ public struct ColumnInfo: FetchableRecord {
|
||||
isNotNull = row["notnull"]
|
||||
defaultValueSQL = row["dflt_value"]
|
||||
primaryKeyIndex = row["pk"]
|
||||
hidden = row["hidden"]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -669,6 +838,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
|
||||
@@ -701,11 +888,10 @@ enum SchemaObjectType: String {
|
||||
struct SchemaInfo: Equatable {
|
||||
private var objects: Set<SchemaObject>
|
||||
|
||||
init(_ db: Database) throws {
|
||||
/// - parameter masterTable: "sqlite_master" or "sqlite_temp_master"
|
||||
init(_ db: Database, masterTableName: String) throws { // swiftlint:disable:this inclusive_language
|
||||
objects = try Set(SchemaObject.fetchCursor(db, sql: """
|
||||
SELECT type, name, tbl_name, sql, 0 AS isTemporary FROM sqlite_master \
|
||||
UNION \
|
||||
SELECT type, name, tbl_name, sql, 1 FROM sqlite_temp_master
|
||||
SELECT type, name, tbl_name, sql FROM \(masterTableName)
|
||||
"""))
|
||||
}
|
||||
|
||||
@@ -724,7 +910,9 @@ struct SchemaInfo: Equatable {
|
||||
/// try db.schema().canonicalName("foobar", ofType: .table) // "FooBar"
|
||||
func canonicalName(_ name: String, ofType type: SchemaObjectType) -> String? {
|
||||
let name = name.lowercased()
|
||||
return objects.first { $0.name.lowercased() == name }?.name
|
||||
return objects
|
||||
.first { $0.type == type.rawValue && $0.name.lowercased() == name }?
|
||||
.name
|
||||
}
|
||||
|
||||
private struct SchemaObject: Codable, Hashable, FetchableRecord {
|
||||
@@ -732,6 +920,5 @@ struct SchemaInfo: Equatable {
|
||||
var name: String
|
||||
var tbl_name: String?
|
||||
var sql: String?
|
||||
var isTemporary: Bool
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,37 @@ extension Database {
|
||||
try makeSelectStatement(sql: sql, prepFlags: 0)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: An SelectStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// A fatal error is raised otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try makeSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try makeSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try makeSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
public func makeSelectStatement(literal sqlLiteral: SQL) throws -> SelectStatement {
|
||||
let (sql, arguments) = try sqlLiteral.build(self)
|
||||
let statement = try makeSelectStatement(sql: sql)
|
||||
if arguments.isEmpty == false {
|
||||
// Crash if arguments do not match
|
||||
statement.arguments = arguments
|
||||
}
|
||||
return statement
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0)
|
||||
@@ -66,6 +97,36 @@ extension Database {
|
||||
try makeUpdateStatement(sql: sql, prepFlags: 0)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// A fatal error is raised otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try makeUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = ?
|
||||
/// """)
|
||||
/// try makeUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = \("O'Brien")
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try makeUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = ?, score = \(10)
|
||||
/// """)
|
||||
public func makeUpdateStatement(literal sqlLiteral: SQL) throws -> UpdateStatement {
|
||||
let (sql, arguments) = try sqlLiteral.build(self)
|
||||
let statement = try makeUpdateStatement(sql: sql)
|
||||
if arguments.isEmpty == false {
|
||||
// Crash if arguments do not match
|
||||
statement.arguments = arguments
|
||||
}
|
||||
return statement
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)", prepFlags: 0)
|
||||
@@ -121,23 +182,17 @@ extension Database {
|
||||
/// - arguments: Statement arguments.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func execute(sql: String, arguments: StatementArguments = StatementArguments()) throws {
|
||||
try execute(literal: SQLLiteral(sql: sql, arguments: arguments))
|
||||
try execute(literal: SQL(sql: sql, arguments: arguments))
|
||||
}
|
||||
|
||||
/// Executes one or several SQL statements, separated by semi-colons.
|
||||
///
|
||||
/// try db.execute(literal: SQLLiteral(
|
||||
/// sql: "INSERT INTO player (name) VALUES (:name)",
|
||||
/// arguments: ["name": "Arthur"]))
|
||||
/// Literals allow you to safely embed raw values in your SQL, without any
|
||||
/// risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// try db.execute(literal: SQLLiteral(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// """, arguments: ["Arthur", "Barbara", "O'Brien"]))
|
||||
///
|
||||
/// With Swift 5, you can safely embed raw values in your SQL queries,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
/// try db.execute(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"))
|
||||
/// """)
|
||||
///
|
||||
/// try db.execute(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"));
|
||||
@@ -147,9 +202,9 @@ extension Database {
|
||||
///
|
||||
/// This method may throw a DatabaseError.
|
||||
///
|
||||
/// - parameter sqlLiteral: An SQLLiteral.
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func execute(literal sqlLiteral: SQLLiteral) throws {
|
||||
public func execute(literal sqlLiteral: SQL) throws {
|
||||
// This method is like sqlite3_exec (https://www.sqlite.org/c3ref/exec.html)
|
||||
// It adds support for arguments, and the tricky part is to consume
|
||||
// arguments as statements are executed.
|
||||
|
||||
+33
-24
@@ -6,6 +6,7 @@ public typealias SQLiteConnection = OpaquePointer
|
||||
/// A raw SQLite function argument.
|
||||
typealias SQLiteValue = OpaquePointer
|
||||
|
||||
@usableFromInline
|
||||
let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_destructor_type.self)
|
||||
|
||||
/// A Database connection.
|
||||
@@ -125,8 +126,27 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// MARK: - Internal properties
|
||||
|
||||
// Caches
|
||||
struct SchemaCache {
|
||||
var schemaIdentifiers: [SchemaIdentifier]?
|
||||
fileprivate var schemas: [SchemaIdentifier: DatabaseSchemaCache] = [:]
|
||||
|
||||
subscript(schemaID: SchemaIdentifier) -> DatabaseSchemaCache { // internal so that it can be tested
|
||||
get {
|
||||
schemas[schemaID] ?? DatabaseSchemaCache()
|
||||
}
|
||||
set {
|
||||
schemas[schemaID] = newValue
|
||||
}
|
||||
}
|
||||
|
||||
mutating func clear() {
|
||||
schemaIdentifiers = nil
|
||||
schemas.removeAll()
|
||||
}
|
||||
}
|
||||
|
||||
var _lastSchemaVersion: Int32? // Support for clearSchemaCacheIfNeeded()
|
||||
var schemaCache: DatabaseSchemaCache // internal so that it can be tested
|
||||
var schemaCache = SchemaCache()
|
||||
lazy var internalStatementCache = StatementCache(database: self)
|
||||
lazy var publicStatementCache = StatementCache(database: self)
|
||||
|
||||
@@ -170,13 +190,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
init(
|
||||
path: String,
|
||||
description: String,
|
||||
configuration: Configuration,
|
||||
schemaCache: DatabaseSchemaCache) throws
|
||||
configuration: Configuration) throws
|
||||
{
|
||||
self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
|
||||
self.description = description
|
||||
self.configuration = configuration
|
||||
self.schemaCache = schemaCache
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -449,7 +467,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))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -866,7 +884,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
arguments: @autoclosure () -> StatementArguments? = nil)
|
||||
throws
|
||||
{
|
||||
if isInsideTransactionBlock && !isInsideTransaction {
|
||||
if isInsideTransactionBlock && sqlite3_get_autocommit(sqliteConnection) != 0 {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_ABORT,
|
||||
message: "Transaction was aborted",
|
||||
@@ -993,11 +1011,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
return
|
||||
}
|
||||
|
||||
// If the savepoint is top-level, we'll use ROLLBACK TRANSACTION in
|
||||
// order to perform the special error handling of rollbacks (see
|
||||
// the rollback method).
|
||||
let topLevelSavepoint = !isInsideTransaction
|
||||
|
||||
// Begin savepoint
|
||||
//
|
||||
// We use a single name for savepoints because there is no need
|
||||
@@ -1031,7 +1044,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
isInsideTransactionBlock = wasInsideTransactionBlock
|
||||
|
||||
try execute(sql: "RELEASE SAVEPOINT grdb")
|
||||
assert(!topLevelSavepoint || !isInsideTransaction)
|
||||
assert(sqlite3_get_autocommit(sqliteConnection) == 0)
|
||||
needsRollback = false
|
||||
case .rollback:
|
||||
needsRollback = true
|
||||
@@ -1043,15 +1056,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
if needsRollback {
|
||||
do {
|
||||
if topLevelSavepoint {
|
||||
try rollback()
|
||||
} else {
|
||||
// Rollback, and release the savepoint.
|
||||
// Rollback alone is not enough to clear the savepoint from
|
||||
// the SQLite savepoint stack.
|
||||
try execute(sql: "ROLLBACK TRANSACTION TO SAVEPOINT grdb")
|
||||
try execute(sql: "RELEASE SAVEPOINT grdb")
|
||||
}
|
||||
// Rollback, and release the savepoint.
|
||||
// Rollback alone is not enough to clear the savepoint from
|
||||
// the SQLite savepoint stack.
|
||||
try execute(sql: "ROLLBACK TRANSACTION TO SAVEPOINT grdb")
|
||||
try execute(sql: "RELEASE SAVEPOINT grdb")
|
||||
} catch {
|
||||
if firstError == nil {
|
||||
firstError = error
|
||||
@@ -1074,7 +1083,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
public func beginTransaction(_ kind: TransactionKind? = nil) throws {
|
||||
let kind = kind ?? configuration.defaultTransactionKind
|
||||
try execute(sql: "BEGIN \(kind.rawValue) TRANSACTION")
|
||||
assert(isInsideTransaction)
|
||||
assert(sqlite3_get_autocommit(sqliteConnection) == 0)
|
||||
}
|
||||
|
||||
/// Rollbacks a database transaction.
|
||||
@@ -1121,13 +1130,13 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
if isInsideTransaction {
|
||||
try execute(sql: "ROLLBACK TRANSACTION")
|
||||
}
|
||||
assert(!isInsideTransaction)
|
||||
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
|
||||
}
|
||||
|
||||
/// Commits a database transaction.
|
||||
public func commit() throws {
|
||||
try execute(sql: "COMMIT TRANSACTION")
|
||||
assert(!isInsideTransaction)
|
||||
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
|
||||
}
|
||||
|
||||
// MARK: - Memory Management
|
||||
|
||||
@@ -248,9 +248,14 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
///
|
||||
/// This initializer is not public because library user is not supposed to
|
||||
/// be exposed to raw result codes.
|
||||
@usableFromInline
|
||||
init(resultCode: CInt, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
|
||||
self.init(resultCode: ResultCode(rawValue: resultCode), message: message, sql: sql, arguments: arguments)
|
||||
}
|
||||
|
||||
static func noSuchTable(_ tableName: String) -> Self {
|
||||
DatabaseError(message: "no such table: \(tableName)")
|
||||
}
|
||||
}
|
||||
|
||||
// Support for `catch DatabaseError.SQLITE_XXX`
|
||||
|
||||
@@ -107,6 +107,18 @@ public final class DatabaseFunction: Hashable {
|
||||
self.kind = .aggregate { Aggregate() }
|
||||
}
|
||||
|
||||
/// Returns an SQL expression that applies the function.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#sql-functions
|
||||
public func callAsFunction(_ arguments: SQLExpressible...) -> SQLExpression {
|
||||
switch kind {
|
||||
case .aggregate:
|
||||
return .function(name, arguments.map(\.sqlExpression))
|
||||
case .function:
|
||||
return .aggregate(name, arguments.map(\.sqlExpression))
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls sqlite3_create_function_v2
|
||||
/// See https://sqlite.org/c3ref/create_function.html
|
||||
func install(in db: Database) {
|
||||
@@ -130,7 +142,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 +158,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))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -42,7 +42,6 @@ public final class DatabasePool: DatabaseWriter {
|
||||
writer = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
schemaCache: DatabaseSchemaCache(),
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "writer")
|
||||
|
||||
@@ -60,7 +59,6 @@ public final class DatabasePool: DatabaseWriter {
|
||||
return try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: readerConfiguration,
|
||||
schemaCache: DatabaseSchemaCache(),
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "reader.\(readerCount)")
|
||||
})
|
||||
@@ -717,6 +715,22 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, and returns the result.
|
||||
///
|
||||
/// Updates are guaranteed an exclusive access to the database. They wait
|
||||
/// until all pending writes and reads are completed. They postpone all
|
||||
/// other writes and reads until they are completed.
|
||||
///
|
||||
/// - important: Reads executed by concurrent *database snapshots* are not
|
||||
/// considered: they can run concurrently with the barrier updates.
|
||||
/// - parameter updates: The updates to the database.
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
readerPool.asyncBarrier {
|
||||
self.writer.sync(updates)
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// wrapped inside a transaction, and returns the result.
|
||||
///
|
||||
|
||||
@@ -36,7 +36,6 @@ public final class DatabaseQueue: DatabaseWriter {
|
||||
writer = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
schemaCache: DatabaseSchemaCache(),
|
||||
defaultLabel: "GRDB.DatabaseQueue")
|
||||
|
||||
setupSuspension()
|
||||
@@ -60,7 +59,6 @@ public final class DatabaseQueue: DatabaseWriter {
|
||||
writer = try! SerializedDatabase(
|
||||
path: ":memory:",
|
||||
configuration: configuration,
|
||||
schemaCache: DatabaseSchemaCache(),
|
||||
defaultLabel: "GRDB.DatabaseQueue")
|
||||
}
|
||||
|
||||
@@ -190,9 +188,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 +219,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 +232,7 @@ extension DatabaseQueue {
|
||||
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.endReadOnly()
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -236,6 +245,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 +258,7 @@ extension DatabaseQueue {
|
||||
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.endReadOnly()
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -289,9 +302,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 +324,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 +335,7 @@ extension DatabaseQueue {
|
||||
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.endReadOnly()
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -386,6 +406,17 @@ extension DatabaseQueue {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, and returns the result.
|
||||
///
|
||||
/// Eventual concurrent database accesses are postponed until the updates
|
||||
/// are completed.
|
||||
///
|
||||
/// - parameter updates: The updates to the database.
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
writer.async(updates)
|
||||
}
|
||||
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, and returns the result.
|
||||
///
|
||||
|
||||
@@ -120,7 +120,7 @@ public protocol DatabaseReader: AnyObject {
|
||||
/// database updates are not visible inside the block:
|
||||
///
|
||||
/// try reader.asyncRead { dbResult in
|
||||
/// do (
|
||||
/// do {
|
||||
/// let db = try dbResult.get()
|
||||
/// // Those two values are guaranteed to be equal, even if the
|
||||
/// // `player` table is modified between the two requests:
|
||||
|
||||
@@ -30,9 +30,9 @@
|
||||
/// let request = Player.filter(key: 1)
|
||||
/// let region = try request.databaseRegion(db)
|
||||
public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
private let tableRegions: [String: TableRegion]?
|
||||
private let tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
|
||||
|
||||
private init(tableRegions: [String: TableRegion]?) {
|
||||
private init(tableRegions: [CaseInsensitiveIdentifier: TableRegion]?) {
|
||||
self.tableRegions = tableRegions
|
||||
}
|
||||
|
||||
@@ -64,16 +64,20 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
///
|
||||
/// - parameter table: A table name.
|
||||
public init(table: String) {
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: nil)])
|
||||
}
|
||||
|
||||
/// Full columns in a table: (some columns in a table) × (all rows)
|
||||
init(table: String, columns: Set<String>) {
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
let columns = Set(columns.map(CaseInsensitiveIdentifier.init))
|
||||
self.init(tableRegions: [table: TableRegion(columns: columns, rowIds: nil)])
|
||||
}
|
||||
|
||||
/// Full rows in a table: (all columns in a table) × (some rows)
|
||||
init(table: String, rowIds: Set<Int64>) {
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: rowIds)])
|
||||
}
|
||||
|
||||
@@ -86,7 +90,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
guard let tableRegions = tableRegions else { return other }
|
||||
guard let otherTableRegions = other.tableRegions else { return self }
|
||||
|
||||
var tableRegionsIntersection: [String: TableRegion] = [:]
|
||||
var tableRegionsIntersection: [CaseInsensitiveIdentifier: TableRegion] = [:]
|
||||
for (table, tableRegion) in tableRegions {
|
||||
guard let otherTableRegion = otherTableRegions
|
||||
.first(where: { (otherTable, _) in otherTable == table })?
|
||||
@@ -105,6 +109,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
return DatabaseRegion(table: table, rowIds: rowIds)
|
||||
}
|
||||
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
guard let tableRegion = tableRegions[table] else {
|
||||
return self
|
||||
}
|
||||
@@ -123,7 +128,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
guard let tableRegions = tableRegions else { return .fullDatabase }
|
||||
guard let otherTableRegions = other.tableRegions else { return .fullDatabase }
|
||||
|
||||
var tableRegionsUnion: [String: TableRegion] = [:]
|
||||
var tableRegionsUnion: [CaseInsensitiveIdentifier: TableRegion] = [:]
|
||||
let tableNames = Set(tableRegions.keys).union(Set(otherTableRegions.keys))
|
||||
for table in tableNames {
|
||||
let tableRegion = tableRegions[table]
|
||||
@@ -148,24 +153,39 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
self = union(other)
|
||||
}
|
||||
|
||||
/// Returns a region suitable for database observation by removing views.
|
||||
/// Returns a region suitable for database observation
|
||||
func observableRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
// SQLite does not expose schema changes to the
|
||||
// TransactionObserver protocol. By removing internal SQLite tables from
|
||||
// the observed region, we optimize database observation.
|
||||
//
|
||||
// And by canonicalizing table names, we remove views, and help the
|
||||
// `isModified` methods.
|
||||
try ignoringInternalSQLiteTables().canonicalTables(db)
|
||||
}
|
||||
|
||||
/// Returns a region only made of actual tables with their canonical names.
|
||||
/// Canonical names help the `isModified` methods.
|
||||
///
|
||||
/// We can do it because modifications only happen in actual tables. And we
|
||||
/// want to do it because we have a fast path for regions that span a
|
||||
/// single table.
|
||||
func ignoringViews(_ db: Database) throws -> DatabaseRegion {
|
||||
/// This method removes views (assuming no table exists with the same name
|
||||
/// as a view).
|
||||
private func canonicalTables(_ db: Database) throws -> DatabaseRegion {
|
||||
guard let tableRegions = tableRegions else { return .fullDatabase }
|
||||
let viewNames = try db.schema().names(ofType: .view)
|
||||
guard viewNames.isEmpty == false else { return self }
|
||||
let filteredRegions = tableRegions.filter { viewNames.contains($0.key) == false }
|
||||
return DatabaseRegion(tableRegions: filteredRegions)
|
||||
var region = DatabaseRegion()
|
||||
for (table, tableRegion) in tableRegions {
|
||||
if let canonicalTableName = try db.canonicalTableName(table.rawValue) {
|
||||
let table = CaseInsensitiveIdentifier(rawValue: canonicalTableName)
|
||||
region.formUnion(DatabaseRegion(tableRegions: [table: tableRegion]))
|
||||
}
|
||||
}
|
||||
return region
|
||||
}
|
||||
|
||||
/// Returns a region which doesn't contain any SQLite internal table.
|
||||
func ignoringInternalSQLiteTables() -> DatabaseRegion {
|
||||
private func ignoringInternalSQLiteTables() -> DatabaseRegion {
|
||||
guard let tableRegions = tableRegions else { return .fullDatabase }
|
||||
let filteredRegions = tableRegions.filter {
|
||||
!Database.isSQLiteInternalTable($0.key)
|
||||
!Database.isSQLiteInternalTable($0.key.rawValue)
|
||||
}
|
||||
return DatabaseRegion(tableRegions: filteredRegions)
|
||||
}
|
||||
@@ -192,7 +212,7 @@ extension DatabaseRegion {
|
||||
return true
|
||||
}
|
||||
|
||||
guard let tableRegion = tableRegions[event.tableName] else {
|
||||
guard let tableRegion = tableRegions[CaseInsensitiveIdentifier(rawValue: event.tableName)] else {
|
||||
// FTS4 (and maybe other virtual tables) perform unadvertised
|
||||
// changes. For example, an "INSERT INTO document ..." statement
|
||||
// advertises an insertion in the `document` table, but the
|
||||
@@ -240,11 +260,11 @@ extension DatabaseRegion {
|
||||
return "empty"
|
||||
}
|
||||
return tableRegions
|
||||
.sorted(by: { (l, r) in l.key < r.key })
|
||||
.sorted(by: { (l, r) in l.key.rawValue < r.key.rawValue })
|
||||
.map({ (table, tableRegion) in
|
||||
var desc = table
|
||||
var desc = table.rawValue
|
||||
if let columns = tableRegion.columns {
|
||||
desc += "(" + columns.sorted().joined(separator: ",") + ")"
|
||||
desc += "(" + columns.map(\.rawValue).sorted().joined(separator: ",") + ")"
|
||||
} else {
|
||||
desc += "(*)"
|
||||
}
|
||||
@@ -258,7 +278,7 @@ extension DatabaseRegion {
|
||||
}
|
||||
|
||||
private struct TableRegion: Equatable {
|
||||
var columns: Set<String>? // nil means "all columns"
|
||||
var columns: Set<CaseInsensitiveIdentifier>? // nil means "all columns"
|
||||
var rowIds: Set<Int64>? // nil means "all rowids"
|
||||
|
||||
var isEmpty: Bool {
|
||||
@@ -268,7 +288,7 @@ private struct TableRegion: Equatable {
|
||||
}
|
||||
|
||||
func intersection(_ other: TableRegion) -> TableRegion {
|
||||
let columnsIntersection: Set<String>?
|
||||
let columnsIntersection: Set<CaseInsensitiveIdentifier>?
|
||||
switch (self.columns, other.columns) {
|
||||
case let (nil, columns), let (columns, nil):
|
||||
columnsIntersection = columns
|
||||
@@ -288,7 +308,7 @@ private struct TableRegion: Equatable {
|
||||
}
|
||||
|
||||
func union(_ other: TableRegion) -> TableRegion {
|
||||
let columnsUnion: Set<String>?
|
||||
let columnsUnion: Set<CaseInsensitiveIdentifier>?
|
||||
switch (self.columns, other.columns) {
|
||||
case (nil, _), (_, nil):
|
||||
columnsUnion = nil
|
||||
|
||||
@@ -91,7 +91,7 @@ extension DatabaseRegionObservation {
|
||||
// Use unsafeReentrantWrite so that observation can start from any
|
||||
// dispatch queue.
|
||||
return try dbWriter.unsafeReentrantWrite { db -> TransactionObserver in
|
||||
let region = try observedRegion(db).ignoringViews(db)
|
||||
let region = try observedRegion(db).observableRegion(db)
|
||||
let observer = DatabaseRegionObserver(region: region, onChange: onChange)
|
||||
db.add(transactionObserver: observer, extent: extent)
|
||||
return observer
|
||||
|
||||
@@ -1,10 +1,30 @@
|
||||
/// A thread-unsafe database schema cache
|
||||
struct DatabaseSchemaCache {
|
||||
/// A cached value
|
||||
///
|
||||
/// We cache both hits and misses, because we often query both the temp
|
||||
/// schema and the main schema: not remembering misses would have us
|
||||
/// perform too many database queries.
|
||||
enum Presence<T> {
|
||||
/// Value does not exist in the schema.
|
||||
case missing
|
||||
|
||||
/// Value exists in the schema.
|
||||
case value(T)
|
||||
|
||||
var value: T? {
|
||||
switch self {
|
||||
case .missing: return nil
|
||||
case let .value(value): return value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var schemaInfo: SchemaInfo?
|
||||
private var primaryKeys: [String: PrimaryKeyInfo] = [:]
|
||||
private var columns: [String: [ColumnInfo]] = [:]
|
||||
private var indexes: [String: [IndexInfo]] = [:]
|
||||
private var foreignKeys: [String: [ForeignKeyInfo]] = [:]
|
||||
private var primaryKeys: [String: Presence<PrimaryKeyInfo>] = [:]
|
||||
private var columns: [String: Presence<[ColumnInfo]>] = [:]
|
||||
private var indexes: [String: Presence<[IndexInfo]>] = [:]
|
||||
private var foreignKeys: [String: Presence<[ForeignKeyInfo]>] = [:]
|
||||
|
||||
mutating func clear() {
|
||||
primaryKeys = [:]
|
||||
@@ -14,35 +34,35 @@ struct DatabaseSchemaCache {
|
||||
schemaInfo = nil
|
||||
}
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
|
||||
func primaryKey(_ table: String) -> Presence<PrimaryKeyInfo>? {
|
||||
primaryKeys[table]
|
||||
}
|
||||
|
||||
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
|
||||
mutating func set(primaryKey: Presence<PrimaryKeyInfo>, forTable table: String) {
|
||||
primaryKeys[table] = primaryKey
|
||||
}
|
||||
|
||||
func columns(in table: String) -> [ColumnInfo]? {
|
||||
func columns(in table: String) -> Presence<[ColumnInfo]>? {
|
||||
columns[table]
|
||||
}
|
||||
|
||||
mutating func set(columns: [ColumnInfo], forTable table: String) {
|
||||
mutating func set(columns: Presence<[ColumnInfo]>, forTable table: String) {
|
||||
self.columns[table] = columns
|
||||
}
|
||||
|
||||
func indexes(on table: String) -> [IndexInfo]? {
|
||||
func indexes(on table: String) -> Presence<[IndexInfo]>? {
|
||||
indexes[table]
|
||||
}
|
||||
|
||||
mutating func set(indexes: [IndexInfo], forTable table: String) {
|
||||
mutating func set(indexes: Presence<[IndexInfo]>, forTable table: String) {
|
||||
self.indexes[table] = indexes
|
||||
}
|
||||
|
||||
func foreignKeys(on table: String) -> [ForeignKeyInfo]? {
|
||||
func foreignKeys(on table: String) -> Presence<[ForeignKeyInfo]>? {
|
||||
foreignKeys[table]
|
||||
}
|
||||
|
||||
mutating func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
|
||||
mutating func set(foreignKeys: Presence<[ForeignKeyInfo]>, forTable table: String) {
|
||||
self.foreignKeys[table] = foreignKeys
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,6 @@ public class DatabaseSnapshot: DatabaseReader {
|
||||
serializedDatabase = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
schemaCache: DatabaseSchemaCache(),
|
||||
defaultLabel: defaultLabel,
|
||||
purpose: purpose)
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -86,6 +86,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
|
||||
|
||||
// MARK: - Not Public
|
||||
|
||||
@inlinable
|
||||
init(storage: Storage) {
|
||||
self.storage = storage
|
||||
}
|
||||
@@ -115,6 +116,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 +139,24 @@ 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 {
|
||||
}
|
||||
|
||||
extension DatabaseValue: StatementBinding {
|
||||
@inlinable
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
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)
|
||||
}
|
||||
return sqlite3_bind_null(sqliteStatement, index)
|
||||
case .int64(let int64):
|
||||
return int64.bind(to: sqliteStatement, at: index)
|
||||
case .double(let double):
|
||||
return double.bind(to: sqliteStatement, at: index)
|
||||
case .string(let string):
|
||||
return string.bind(to: sqliteStatement, at: index)
|
||||
case .blob(let data):
|
||||
return data.bind(to: sqliteStatement, at: index)
|
||||
}
|
||||
}
|
||||
|
||||
/// :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
|
||||
@@ -264,6 +221,7 @@ extension DatabaseValue {
|
||||
// DatabaseValueConvertible
|
||||
extension DatabaseValue {
|
||||
/// Returns self
|
||||
@inlinable
|
||||
public var databaseValue: DatabaseValue {
|
||||
self
|
||||
}
|
||||
@@ -276,9 +234,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)
|
||||
}
|
||||
}
|
||||
@@ -14,21 +14,112 @@
|
||||
/// try String.fetchOne(statement, arguments:...) // String?
|
||||
///
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
public protocol DatabaseValueConvertible: SQLExpressible {
|
||||
public protocol DatabaseValueConvertible: SQLExpressible, StatementBinding {
|
||||
/// Returns a value that can be stored in the database.
|
||||
var databaseValue: DatabaseValue { get }
|
||||
|
||||
/// Returns a value initialized from *dbValue*, if possible.
|
||||
/// Returns a value initialized from `dbValue`, if possible.
|
||||
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self?
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible {
|
||||
/// :nodoc:
|
||||
public var sqlExpression: SQLExpression {
|
||||
databaseValue
|
||||
.databaseValue(databaseValue)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
databaseValue.bind(to: sqliteStatement, at: index)
|
||||
}
|
||||
}
|
||||
|
||||
// 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 +168,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 +227,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)
|
||||
}
|
||||
|
||||
@@ -70,6 +70,16 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// - throws: The error thrown by the updates.
|
||||
func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T
|
||||
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, and returns the result.
|
||||
///
|
||||
/// Updates are guaranteed an exclusive access to the database. They wait
|
||||
/// until all pending writes and reads are completed. They postpone all
|
||||
/// other writes and reads until they are completed.
|
||||
///
|
||||
/// - parameter updates: The updates to the database.
|
||||
func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
|
||||
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
/// wrapped inside a transaction.
|
||||
///
|
||||
@@ -620,6 +630,10 @@ public final class AnyDatabaseWriter: DatabaseWriter {
|
||||
try base.barrierWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
base.asyncBarrierWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
public func asyncWrite<T>(
|
||||
_ updates: @escaping (Database) throws -> T,
|
||||
completion: @escaping (Database, Result<T, Error>) -> Void)
|
||||
|
||||
+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: ", "))"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
/// `SQL` helps you build SQL literal with
|
||||
/// [SQL Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md).
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// let name: String = ...
|
||||
/// let id: Int64 = ...
|
||||
/// let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
/// try db.execute(literal: query)
|
||||
/// }
|
||||
public struct SQL {
|
||||
/// `SQL` is an array of elements which can be qualified with table
|
||||
/// aliases. This is how `SQL` can blend well in the query interface.
|
||||
enum Element {
|
||||
// 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(SQLSubquery)
|
||||
// Cases below can be qualified with a table alias
|
||||
case expression(SQLExpression)
|
||||
case selection(SQLSelection)
|
||||
case ordering(SQLOrdering)
|
||||
|
||||
var isEmpty: Bool {
|
||||
switch self {
|
||||
case let .sql(sql, _):
|
||||
return sql.isEmpty
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func sql(_ context: SQLGenerationContext) throws -> String {
|
||||
switch self {
|
||||
case let .sql(sql, arguments):
|
||||
if context.append(arguments: arguments) == false {
|
||||
// We don't know how to look for `?` in sql and
|
||||
// replace them with literals.
|
||||
fatalError("Not implemented: turning an SQL parameter into an SQL literal value")
|
||||
}
|
||||
return sql
|
||||
case let .subquery(subquery):
|
||||
return try subquery.sql(context)
|
||||
case let .expression(expression):
|
||||
return try expression.sql(context)
|
||||
case let .selection(selection):
|
||||
return try selection.sql(context)
|
||||
case let .ordering(ordering):
|
||||
return try ordering.sql(context)
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func qualified(with alias: TableAlias) -> Element {
|
||||
switch self {
|
||||
case .sql:
|
||||
// Can't qualify raw SQL string
|
||||
return self
|
||||
case .subquery:
|
||||
// Subqueries don't need table alias
|
||||
return self
|
||||
case let .expression(expression):
|
||||
return .expression(expression.qualified(with: alias))
|
||||
case let .selection(selection):
|
||||
return .selection(selection.qualified(with: alias))
|
||||
case let .ordering(ordering):
|
||||
return .ordering(ordering.qualified(with: alias))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private(set) var elements: [Element]
|
||||
|
||||
init(elements: [Element]) {
|
||||
self.elements = elements
|
||||
}
|
||||
|
||||
/// Creates an `SQL` literal from a plain SQL string, and
|
||||
/// eventual arguments.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let query = SQL(
|
||||
/// sql: "UPDATE player SET name = ? WHERE id = ?",
|
||||
/// arguments: [name, id])
|
||||
public init(sql: String, arguments: StatementArguments = StatementArguments()) {
|
||||
self.init(elements: [.sql(sql, arguments)])
|
||||
}
|
||||
|
||||
/// Creates an `SQL` literal from an SQL expression.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let columnLiteral = SQL(Column("username"))
|
||||
/// let suffixLiteral = SQL("@example.com".databaseValue)
|
||||
/// let emailLiteral = [columnLiteral, suffixLiteral].joined(separator: " || ")
|
||||
/// let request = User.select(emailLiteral.sqlExpression)
|
||||
/// let emails = try String.fetchAll(db, request)
|
||||
public init(_ expression: SQLSpecificExpressible) {
|
||||
self.init(elements: [.expression(expression.sqlExpression)])
|
||||
}
|
||||
|
||||
/// Returns true if this literal generates an empty SQL string
|
||||
public var isEmpty: Bool {
|
||||
elements.allSatisfy(\.isEmpty)
|
||||
}
|
||||
|
||||
/// Turn a `SQL` literal into raw SQL and arguments.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A tuple made of a raw SQL string, and statement arguments.
|
||||
public func build(_ db: Database) throws -> (sql: String, arguments: StatementArguments) {
|
||||
let context = SQLGenerationContext(db)
|
||||
let sql = try self.sql(context)
|
||||
return (sql: sql, arguments: context.arguments)
|
||||
}
|
||||
|
||||
/// Returns the literal SQL string given an SQL generation context.
|
||||
func sql(_ context: SQLGenerationContext) throws -> String {
|
||||
try elements.map { try $0.sql(context) }.joined()
|
||||
}
|
||||
|
||||
func qualified(with alias: TableAlias) -> SQL {
|
||||
SQL(elements: elements.map { $0.qualified(with: alias) })
|
||||
}
|
||||
}
|
||||
|
||||
extension SQL {
|
||||
/// Returns the `SQL` literal produced by the concatenation of two literals.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// let selection: SQL = "SELECT * FROM player "
|
||||
/// let condition: SQL = "WHERE name = \(name)"
|
||||
/// let query = selection + condition
|
||||
public static func + (lhs: SQL, rhs: SQL) -> SQL {
|
||||
var result = lhs
|
||||
result += rhs
|
||||
return result
|
||||
}
|
||||
|
||||
/// Appends an `SQL` literal to the receiver.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQL = "SELECT * FROM player "
|
||||
/// query += "WHERE name = \(name)"
|
||||
public static func += (lhs: inout SQL, rhs: SQL) {
|
||||
lhs.elements += rhs.elements
|
||||
}
|
||||
|
||||
/// Appends an `SQL` literal to the receiver.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQL = "SELECT * FROM player "
|
||||
/// query.append(literal: "WHERE name = \(name)")
|
||||
public mutating func append(literal sqlLiteral: SQL) {
|
||||
self += sqlLiteral
|
||||
}
|
||||
|
||||
/// Appends a plain SQL string to the receiver, and eventual arguments.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQL = "SELECT * FROM player "
|
||||
/// query.append(sql: "WHERE name = ?", arguments: [name])
|
||||
public mutating func append(sql: String, arguments: StatementArguments = StatementArguments()) {
|
||||
self += SQL(sql: sql, arguments: arguments)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQL: SQLSpecificExpressible {
|
||||
/// Creates a literal SQL expression.
|
||||
///
|
||||
/// Use this property when you need an explicit `SQLExpression`.
|
||||
/// For example:
|
||||
///
|
||||
/// func date(_ value: SQLExpressible) -> SQLExpression {
|
||||
/// SQL("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")
|
||||
public var sqlExpression: SQLExpression {
|
||||
.literal(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQL: SQLSelectable {
|
||||
public var sqlSelection: SQLSelection {
|
||||
.literal(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQL: SQLOrderingTerm {
|
||||
public var sqlOrdering: SQLOrdering {
|
||||
.literal(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence where Element == SQL {
|
||||
/// Returns the concatenated `SQL` literal of this sequence of literals,
|
||||
/// inserting the given separator between each element.
|
||||
///
|
||||
/// let components: [SQL] = [
|
||||
/// "UPDATE player",
|
||||
/// "SET name = \(name)",
|
||||
/// "WHERE id = \(id)"
|
||||
/// ]
|
||||
/// let query = components.joined(separator: " ")
|
||||
public func joined(separator: String = "") -> SQL {
|
||||
if separator.isEmpty {
|
||||
return SQL(elements: flatMap(\.elements))
|
||||
} else {
|
||||
return SQL(elements: Array(map(\.elements).joined(separator: CollectionOfOne(.sql(separator)))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Collection where Element == SQL {
|
||||
/// Returns the concatenated `SQL` literal of this collection of literals,
|
||||
/// inserting the given SQL separator between each element.
|
||||
///
|
||||
/// let components: [SQL] = [
|
||||
/// "UPDATE player",
|
||||
/// "SET name = \(name)",
|
||||
/// "WHERE id = \(id)"
|
||||
/// ]
|
||||
/// let query = components.joined(separator: " ")
|
||||
public func joined(separator: String = "") -> SQL {
|
||||
if separator.isEmpty {
|
||||
return SQL(elements: flatMap(\.elements))
|
||||
} else {
|
||||
return SQL(elements: Array(map(\.elements).joined(separator: CollectionOfOne(.sql(separator)))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ExpressibleByStringInterpolation
|
||||
|
||||
extension SQL: ExpressibleByStringInterpolation {
|
||||
/// :nodoc
|
||||
public init(unicodeScalarLiteral: String) {
|
||||
self.init(sql: unicodeScalarLiteral, arguments: [])
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(extendedGraphemeClusterLiteral: String) {
|
||||
self.init(sql: extendedGraphemeClusterLiteral, arguments: [])
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(stringLiteral: String) {
|
||||
self.init(sql: stringLiteral, arguments: [])
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(stringInterpolation sqlInterpolation: SQLInterpolation) {
|
||||
self.init(elements: sqlInterpolation.elements)
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,52 @@
|
||||
/// :nodoc:
|
||||
public struct SQLInterpolation: StringInterpolationProtocol {
|
||||
var elements: [SQLLiteral.Element]
|
||||
var elements: [SQL.Element]
|
||||
|
||||
public init(literalCapacity: Int, interpolationCount: Int) {
|
||||
elements = []
|
||||
elements.reserveCapacity(interpolationCount + 1)
|
||||
}
|
||||
|
||||
/// "SELECT * FROM player"
|
||||
public mutating func appendLiteral(_ sql: String) {
|
||||
if sql.isEmpty { return }
|
||||
elements.append(.sql(sql))
|
||||
}
|
||||
|
||||
/// "SELECT * FROM \(sql: "player")"
|
||||
/// Appends a raw SQL snippet, with eventual arguments.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// "SELECT * FROM \(sql: "player")"
|
||||
/// "SELECT * FROM player WHERE \(sql: "name = ?", arguments: ["O'Brien"])"
|
||||
public mutating func appendInterpolation(sql: String, arguments: StatementArguments = StatementArguments()) {
|
||||
elements.append(.sql(sql, arguments))
|
||||
}
|
||||
|
||||
/// "SELECT * FROM player WHERE \(literal: condition)"
|
||||
public mutating func appendInterpolation(literal sqlLiteral: SQLLiteral) {
|
||||
/// Appends a raw `SQL` literal.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// "SELECT * FROM \(SQL("player"))"
|
||||
/// "SELECT * FROM player WHERE \(SQL("name = \("O'Brien")"))"
|
||||
public mutating func appendInterpolation(_ sqlLiteral: SQL) {
|
||||
elements.append(contentsOf: sqlLiteral.elements)
|
||||
}
|
||||
|
||||
/// Appends a String expression.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// "SELECT * FROM player WHERE name = \("O'Brien")"
|
||||
public mutating func appendInterpolation<S: StringProtocol>(_ string: S) {
|
||||
elements.append(.expression(String(string).sqlExpression))
|
||||
}
|
||||
|
||||
/// Appends a raw `SQL` literal.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// "SELECT * FROM player WHERE \(literal: "name = \("O'Brien")")"
|
||||
public mutating func appendInterpolation(literal sqlLiteral: SQL) {
|
||||
elements.append(contentsOf: sqlLiteral.elements)
|
||||
}
|
||||
}
|
||||
@@ -1,368 +0,0 @@
|
||||
/// SQLLiteral is a type which support [SQL
|
||||
/// Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md).
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// let name: String = ...
|
||||
/// let id: Int64 = ...
|
||||
/// let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
/// try db.execute(literal: query)
|
||||
/// }
|
||||
public struct SQLLiteral {
|
||||
/// SQLLiteral is an array of elements which can be qualified with
|
||||
/// table aliases.
|
||||
enum Element {
|
||||
// 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>)
|
||||
// Cases below can be qualified with a table alias
|
||||
case expression(SQLExpression)
|
||||
case selectable(SQLSelectable)
|
||||
case orderingTerm(SQLOrderingTerm)
|
||||
|
||||
var isEmpty: Bool {
|
||||
switch self {
|
||||
case let .sql(sql, _):
|
||||
return sql.isEmpty
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func sql(_ context: SQLGenerationContext) throws -> String {
|
||||
switch self {
|
||||
case let .sql(sql, arguments):
|
||||
if context.append(arguments: arguments) == false {
|
||||
// We don't know how to look for `?` in sql and
|
||||
// replace them with literals.
|
||||
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 .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)
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func qualified(with alias: TableAlias) -> Element {
|
||||
switch self {
|
||||
case .sql:
|
||||
// Can't qualify raw SQL string
|
||||
return self
|
||||
case .subquery:
|
||||
// Subqueries don't need table alias
|
||||
return self
|
||||
case let .expression(expression):
|
||||
return .expression(expression._qualifiedExpression(with: alias))
|
||||
case let .selectable(selectable):
|
||||
return .selectable(selectable._qualifiedSelectable(with: alias))
|
||||
case let .orderingTerm(orderingTerm):
|
||||
return .orderingTerm(orderingTerm._qualifiedOrdering(with: alias))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private(set) var elements: [Element]
|
||||
|
||||
init(elements: [Element]) {
|
||||
self.elements = elements
|
||||
}
|
||||
|
||||
/// Creates an SQLLiteral from a plain SQL string, and eventual arguments.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let query = SQLLiteral(
|
||||
/// sql: "UPDATE player SET name = ? WHERE id = ?",
|
||||
/// arguments: [name, id])
|
||||
public init(sql: String, arguments: StatementArguments = StatementArguments()) {
|
||||
self.init(elements: [.sql(sql, arguments)])
|
||||
}
|
||||
|
||||
/// Creates an SQLLiteral from an SQL expression.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let columnLiteral = SQLLiteral(Column("username"))
|
||||
/// let suffixLiteral = SQLLiteral("@example.com".databaseValue)
|
||||
/// 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)])
|
||||
}
|
||||
|
||||
/// Returns true if this literal generates an empty SQL string
|
||||
public var isEmpty: Bool {
|
||||
elements.allSatisfy(\.isEmpty)
|
||||
}
|
||||
|
||||
/// Turn a SQLLiteral into raw SQL and arguments.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A tuple made of a raw SQL string, and statement arguments.
|
||||
public func build(_ db: Database) throws -> (sql: String, arguments: StatementArguments) {
|
||||
let context = SQLGenerationContext(db)
|
||||
let sql = try self.sql(context)
|
||||
return (sql: sql, arguments: context.arguments)
|
||||
}
|
||||
|
||||
/// Returns the literal SQL string given an SQL generation context.
|
||||
func sql(_ context: SQLGenerationContext) throws -> String {
|
||||
try elements.map { try $0.sql(context) }.joined()
|
||||
}
|
||||
|
||||
func qualified(with alias: TableAlias) -> SQLLiteral {
|
||||
SQLLiteral(elements: elements.map { $0.qualified(with: alias) })
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLLiteral {
|
||||
/// Returns the SQLLiteral produced by the concatenation of two literals.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// let selection: SQLLiteral = "SELECT * FROM player "
|
||||
/// let condition: SQLLiteral = "WHERE name = \(name)"
|
||||
/// let query = selection + condition
|
||||
public static func + (lhs: SQLLiteral, rhs: SQLLiteral) -> SQLLiteral {
|
||||
var result = lhs
|
||||
result += rhs
|
||||
return result
|
||||
}
|
||||
|
||||
/// Appends an SQLLiteral to the receiver.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQLLiteral = "SELECT * FROM player "
|
||||
/// query += "WHERE name = \(name)"
|
||||
public static func += (lhs: inout SQLLiteral, rhs: SQLLiteral) {
|
||||
lhs.elements += rhs.elements
|
||||
}
|
||||
|
||||
/// Appends an SQLLiteral to the receiver.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQLLiteral = "SELECT * FROM player "
|
||||
/// query.append(literal: "WHERE name = \(name)")
|
||||
public mutating func append(literal sqlLiteral: SQLLiteral) {
|
||||
self += sqlLiteral
|
||||
}
|
||||
|
||||
/// Appends a plain SQL string to the receiver, and eventual arguments.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQLLiteral = "SELECT * FROM player "
|
||||
/// query.append(sql: "WHERE name = ?", arguments: [name])
|
||||
public mutating func append(sql: String, arguments: StatementArguments = StatementArguments()) {
|
||||
self += SQLLiteral(sql: sql, arguments: arguments)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLLiteral {
|
||||
/// Creates a literal SQL expression.
|
||||
///
|
||||
/// SQLLiteral(sql: "1 + 2").sqlExpression
|
||||
/// SQLLiteral(sql: "? + ?", arguments: [1, 2]).sqlExpression
|
||||
/// SQLLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]).sqlExpression
|
||||
public var sqlExpression: SQLExpression {
|
||||
SQLExpressionLiteral(sqlLiteral: self)
|
||||
}
|
||||
|
||||
var sqlSelectable: SQLSelectable {
|
||||
SQLSelectionLiteral(sqlLiteral: self)
|
||||
}
|
||||
|
||||
var sqlOrderingTerm: SQLOrderingTerm {
|
||||
SQLOrderingLiteral(sqlLiteral: self)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence where Element == SQLLiteral {
|
||||
/// Returns the concatenated SQLLiteral of this sequence of literals,
|
||||
/// inserting the given separator between each element.
|
||||
///
|
||||
/// let components: [SQLLiteral] = [
|
||||
/// "UPDATE player",
|
||||
/// "SET name = \(name)",
|
||||
/// "WHERE id = \(id)"
|
||||
/// ]
|
||||
/// let query = components.joined(separator: " ")
|
||||
public func joined(separator: String = "") -> SQLLiteral {
|
||||
if separator.isEmpty {
|
||||
return SQLLiteral(elements: flatMap(\.elements))
|
||||
} else {
|
||||
return SQLLiteral(elements: Array(map(\.elements).joined(separator: CollectionOfOne(.sql(separator)))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Collection where Element == SQLLiteral {
|
||||
/// Returns the concatenated SQLLiteral of this collection of literals,
|
||||
/// inserting the given SQL separator between each element.
|
||||
///
|
||||
/// let components: [SQLLiteral] = [
|
||||
/// "UPDATE player",
|
||||
/// "SET name = \(name)",
|
||||
/// "WHERE id = \(id)"
|
||||
/// ]
|
||||
/// let query = components.joined(separator: " ")
|
||||
public func joined(separator: String = "") -> SQLLiteral {
|
||||
if separator.isEmpty {
|
||||
return SQLLiteral(elements: flatMap(\.elements))
|
||||
} else {
|
||||
return SQLLiteral(elements: Array(map(\.elements).joined(separator: CollectionOfOne(.sql(separator)))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ExpressibleByStringInterpolation
|
||||
|
||||
extension SQLLiteral: ExpressibleByStringInterpolation {
|
||||
/// :nodoc
|
||||
public init(unicodeScalarLiteral: String) {
|
||||
self.init(sql: unicodeScalarLiteral, arguments: [])
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(extendedGraphemeClusterLiteral: String) {
|
||||
self.init(sql: extendedGraphemeClusterLiteral, arguments: [])
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(stringLiteral: String) {
|
||||
self.init(sql: stringLiteral, arguments: [])
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(stringInterpolation sqlInterpolation: SQLInterpolation) {
|
||||
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.
|
||||
""")
|
||||
}
|
||||
}
|
||||
+78
-51
@@ -15,9 +15,22 @@ public struct SQLRequest<RowDecoder> {
|
||||
/// The request adapter
|
||||
public var adapter: RowAdapter?
|
||||
|
||||
private(set) var sqlLiteral: SQLLiteral
|
||||
private(set) var sqlLiteral: SQL
|
||||
let cache: Cache?
|
||||
|
||||
private init(
|
||||
literal sqlLiteral: SQL,
|
||||
adapter: RowAdapter?,
|
||||
fromCache cache: Cache?,
|
||||
type: RowDecoder.Type)
|
||||
{
|
||||
self.sqlLiteral = sqlLiteral
|
||||
self.adapter = adapter
|
||||
self.cache = cache
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLRequest {
|
||||
/// Creates a request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
///
|
||||
@@ -42,66 +55,95 @@ public struct SQLRequest<RowDecoder> {
|
||||
cached: Bool = false)
|
||||
{
|
||||
self.init(
|
||||
literal: SQLLiteral(sql: sql, arguments: arguments),
|
||||
literal: SQL(sql: sql, arguments: arguments),
|
||||
adapter: adapter,
|
||||
fromCache: cached ? .public : nil)
|
||||
fromCache: cached ? .public : nil,
|
||||
type: RowDecoder.self)
|
||||
}
|
||||
|
||||
/// Creates a request from an SQLLiteral, and optional row adapter.
|
||||
/// Creates a request from an `SQL` literal, and optional row adapter.
|
||||
///
|
||||
/// let request = SQLRequest<String>(literal: SQLLiteral(sql: """
|
||||
/// SELECT name FROM player
|
||||
/// """))
|
||||
/// let request = SQLRequest<Player>(literal: SQLLiteral(sql: """
|
||||
/// SELECT * FROM player WHERE name = ?
|
||||
/// """, arguments: ["O'Brien"]))
|
||||
///
|
||||
/// With Swift 5, you can safely embed raw values in your SQL queries,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
/// Literals allow you to safely embed raw values in your SQL, without any
|
||||
/// risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// let name = "O'brien"
|
||||
/// let request = SQLRequest<Player>(literal: """
|
||||
/// SELECT * FROM player WHERE name = \("O'brien")
|
||||
/// SELECT * FROM player WHERE name = \(name)
|
||||
/// """)
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqlLiteral: An SQLLiteral.
|
||||
/// - sqlLiteral: An `SQL` literal.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: A SQLRequest
|
||||
public init(literal sqlLiteral: SQLLiteral, adapter: RowAdapter? = nil, cached: Bool = false) {
|
||||
self.init(literal: sqlLiteral, adapter: adapter, fromCache: cached ? .public : nil)
|
||||
public init(literal sqlLiteral: SQL, adapter: RowAdapter? = nil, cached: Bool = false) {
|
||||
self.init(
|
||||
literal: sqlLiteral,
|
||||
adapter: adapter,
|
||||
fromCache: cached ? .public : nil,
|
||||
type: RowDecoder.self)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLRequest where RowDecoder == Row {
|
||||
/// Creates a request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
///
|
||||
/// let request = SQLRequest(sql: """
|
||||
/// SELECT * FROM player WHERE id = ?
|
||||
/// """, arguments: [1])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: A SQLRequest
|
||||
public init(
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil,
|
||||
cached: Bool = false)
|
||||
{
|
||||
self.init(
|
||||
literal: SQL(sql: sql, arguments: arguments),
|
||||
adapter: adapter,
|
||||
fromCache: cached ? .public : nil,
|
||||
type: Row.self)
|
||||
}
|
||||
|
||||
/// Creates a request from an SQLLiteral, and optional row adapter.
|
||||
/// Creates a request from an `SQL` literal, and optional row adapter.
|
||||
///
|
||||
/// let request = SQLRequest<String>(literal: SQLLiteral(sql: """
|
||||
/// SELECT name FROM player
|
||||
/// """))
|
||||
/// let request = SQLRequest<Player>(literal: SQLLiteral(sql: """
|
||||
/// SELECT * FROM player WHERE name = ?
|
||||
/// """, arguments: ["O'Brien"]))
|
||||
/// Literals allow you to safely embed raw values in your SQL, without any
|
||||
/// risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// With Swift 5, you can safely embed raw values in your SQL queries,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// let request = SQLRequest<Player>(literal: """
|
||||
/// SELECT * FROM player WHERE name = \("O'brien")
|
||||
/// let name = "O'brien"
|
||||
/// let request = SQLRequest(literal: """
|
||||
/// SELECT * FROM player WHERE name = \(name)
|
||||
/// """)
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqlLiteral: An SQLLiteral.
|
||||
/// - sqlLiteral: An `SQL` literal.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - cache: The eventual cache
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: A SQLRequest
|
||||
init(literal sqlLiteral: SQLLiteral, adapter: RowAdapter? = nil, fromCache cache: Cache?) {
|
||||
self.sqlLiteral = sqlLiteral
|
||||
self.adapter = adapter
|
||||
self.cache = cache
|
||||
public init(literal sqlLiteral: SQL, adapter: RowAdapter? = nil, cached: Bool = false) {
|
||||
self.init(
|
||||
literal: sqlLiteral,
|
||||
adapter: adapter,
|
||||
fromCache: cached ? .public : nil,
|
||||
type: Row.self)
|
||||
}
|
||||
}
|
||||
|
||||
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 +167,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 {
|
||||
@@ -160,6 +187,6 @@ extension SQLRequest: ExpressibleByStringInterpolation {
|
||||
|
||||
/// :nodoc:
|
||||
public init(stringInterpolation sqlInterpolation: SQLInterpolation) {
|
||||
self.init(literal: SQLLiteral(stringInterpolation: sqlInterpolation))
|
||||
self.init(literal: SQL(stringInterpolation: sqlInterpolation))
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,6 @@ final class SerializedDatabase {
|
||||
init(
|
||||
path: String,
|
||||
configuration: Configuration = Configuration(),
|
||||
schemaCache: DatabaseSchemaCache,
|
||||
defaultLabel: String,
|
||||
purpose: String? = nil)
|
||||
throws
|
||||
@@ -47,8 +46,7 @@ final class SerializedDatabase {
|
||||
self.db = try Database(
|
||||
path: path,
|
||||
description: identifier,
|
||||
configuration: config,
|
||||
schemaCache: schemaCache)
|
||||
configuration: config)
|
||||
self.queue = configuration.makeDispatchQueue(label: identifier)
|
||||
SchedulingWatchdog.allowDatabase(db, onQueue: queue)
|
||||
try queue.sync {
|
||||
|
||||
+52
-34
@@ -19,6 +19,8 @@ public class Statement {
|
||||
|
||||
/// The SQL query
|
||||
public var sql: String {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
|
||||
// trim white space and semicolumn for homogeneous output
|
||||
return String(cString: sqlite3_sql(sqliteStatement))
|
||||
.trimmingCharacters(in: .sqlStatementSeparators)
|
||||
@@ -35,6 +37,7 @@ public class Statement {
|
||||
sqlite3_stmt_readonly(sqliteStatement) != 0
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
unowned let database: Database
|
||||
|
||||
/// Creates a prepared statement. Returns nil if the compiled string is
|
||||
@@ -95,6 +98,7 @@ public class Statement {
|
||||
sqlite3_finalize(sqliteStatement)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
final func reset() throws {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
let code = sqlite3_reset(sqliteStatement)
|
||||
@@ -106,9 +110,12 @@ public class Statement {
|
||||
|
||||
// MARK: Arguments
|
||||
|
||||
@usableFromInline
|
||||
var argumentsNeedValidation = true
|
||||
var _arguments = StatementArguments()
|
||||
|
||||
@usableFromInline
|
||||
var _arguments = StatementArguments()
|
||||
|
||||
lazy var sqliteArgumentCount: Int = {
|
||||
Int(sqlite3_bind_parameter_count(self.sqliteStatement))
|
||||
}()
|
||||
@@ -188,8 +195,6 @@ public class Statement {
|
||||
bind(value, at: index)
|
||||
} else if let value = valuesIterator.next() {
|
||||
bind(value, at: index)
|
||||
} else {
|
||||
bind(.null, at: index)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -224,52 +229,47 @@ public class Statement {
|
||||
}
|
||||
|
||||
// 1-based index
|
||||
private func bind(_ dbValue: DatabaseValue, at index: Int32) {
|
||||
let code: Int32
|
||||
switch dbValue.storage {
|
||||
case .null:
|
||||
code = sqlite3_bind_null(sqliteStatement, index)
|
||||
case .int64(let int64):
|
||||
code = sqlite3_bind_int64(sqliteStatement, index, int64)
|
||||
case .double(let double):
|
||||
code = sqlite3_bind_double(sqliteStatement, index, double)
|
||||
case .string(let string):
|
||||
code = sqlite3_bind_text(sqliteStatement, index, string, -1, SQLITE_TRANSIENT)
|
||||
case .blob(let data):
|
||||
code = data.withUnsafeBytes {
|
||||
sqlite3_bind_blob(sqliteStatement, index, $0.baseAddress, Int32($0.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
@inlinable
|
||||
func bind<T: StatementBinding>(_ value: T, at index: CInt) {
|
||||
let code = value.bind(to: sqliteStatement, at: index)
|
||||
|
||||
// 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))
|
||||
}
|
||||
}
|
||||
|
||||
// Don't make this one public unless we keep the arguments property in sync.
|
||||
private func clearBindings() {
|
||||
@usableFromInline
|
||||
func clearBindings() {
|
||||
// It looks like sqlite3_clear_bindings() does not access the file system.
|
||||
// This function call should thus succeed, unless a GRDB bug: there is
|
||||
// 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))
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func prepare(withArguments arguments: StatementArguments?) {
|
||||
func reset(withArguments arguments: StatementArguments?) {
|
||||
// Force arguments validity: it is a programmer error to provide
|
||||
// arguments that do not match the statement.
|
||||
if let arguments = arguments {
|
||||
try! setArguments(arguments)
|
||||
} else if argumentsNeedValidation {
|
||||
try! reset()
|
||||
try! validateArguments(self.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Statement: CustomStringConvertible {
|
||||
public var description: String {
|
||||
"SQL: \(sql), Arguments: \(arguments)"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Statement Preparation
|
||||
|
||||
extension Statement {
|
||||
@@ -388,12 +388,6 @@ public final class SelectStatement: Statement {
|
||||
try StatementCursor(statement: self, arguments: arguments)
|
||||
}
|
||||
|
||||
/// Utility function for cursors
|
||||
func reset(withArguments arguments: StatementArguments? = nil) {
|
||||
prepare(withArguments: arguments)
|
||||
try! reset()
|
||||
}
|
||||
|
||||
/// Utility function for cursors
|
||||
@usableFromInline
|
||||
func didFail(withResultCode resultCode: Int32) throws -> Never {
|
||||
@@ -542,8 +536,7 @@ public final class UpdateStatement: Statement {
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func execute(arguments: StatementArguments? = nil) throws {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
prepare(withArguments: arguments)
|
||||
try reset()
|
||||
reset(withArguments: arguments)
|
||||
|
||||
// Statement does not know how to execute itself, because it does not
|
||||
// know how to handle its errors, or if truncate optimisation should be
|
||||
@@ -552,6 +545,17 @@ public final class UpdateStatement: Statement {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - StatementBinding
|
||||
|
||||
public protocol StatementBinding {
|
||||
/// Binds a statement argument.
|
||||
///
|
||||
/// - parameter sqliteStatement: An SQLite statement.
|
||||
/// - parameter index: 1-based index to statement arguments
|
||||
/// - returns: the code returned by the `sqlite3_bind_xxx` function.
|
||||
func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt
|
||||
}
|
||||
|
||||
// MARK: - StatementArguments
|
||||
|
||||
/// StatementArguments provide values to argument placeholders in raw
|
||||
@@ -636,8 +640,8 @@ public final class UpdateStatement: Statement {
|
||||
public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral
|
||||
{
|
||||
private(set) var values: [DatabaseValue] = []
|
||||
private(set) var namedValues: [String: DatabaseValue] = [:]
|
||||
private(set) var values: [DatabaseValue]
|
||||
private(set) var namedValues: [String: DatabaseValue]
|
||||
|
||||
public var isEmpty: Bool {
|
||||
values.isEmpty && namedValues.isEmpty
|
||||
@@ -648,6 +652,8 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
|
||||
/// Creates empty StatementArguments.
|
||||
public init() {
|
||||
values = .init()
|
||||
namedValues = .init()
|
||||
}
|
||||
|
||||
// MARK: Positional Arguments
|
||||
@@ -661,6 +667,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
/// - returns: A StatementArguments.
|
||||
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Element == DatabaseValueConvertible? {
|
||||
values = sequence.map { $0?.databaseValue ?? .null }
|
||||
namedValues = .init()
|
||||
}
|
||||
|
||||
/// Creates statement arguments from a sequence of optional values.
|
||||
@@ -672,6 +679,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
/// - returns: A StatementArguments.
|
||||
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Element: DatabaseValueConvertible {
|
||||
values = sequence.map(\.databaseValue)
|
||||
namedValues = .init()
|
||||
}
|
||||
|
||||
/// Creates statement arguments from any array. The result is nil unless all
|
||||
@@ -690,6 +698,11 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
self.init(values)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
mutating func set(databaseValues: [DatabaseValue]) {
|
||||
self.values = databaseValues
|
||||
namedValues.removeAll(keepingCapacity: true)
|
||||
}
|
||||
|
||||
// MARK: Named Arguments
|
||||
|
||||
@@ -703,6 +716,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
/// - returns: A StatementArguments.
|
||||
public init(_ dictionary: [String: DatabaseValueConvertible?]) {
|
||||
namedValues = dictionary.mapValues { $0?.databaseValue ?? .null }
|
||||
values = .init()
|
||||
}
|
||||
|
||||
/// Creates statement arguments from a sequence of (key, value) pairs, such
|
||||
@@ -716,7 +730,11 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
public init<Sequence>(_ sequence: Sequence)
|
||||
where Sequence: Swift.Sequence, Sequence.Element == (String, DatabaseValueConvertible?)
|
||||
{
|
||||
namedValues = Dictionary(uniqueKeysWithValues: sequence.map { ($0.0, $0.1?.databaseValue ?? .null) })
|
||||
namedValues = .init(minimumCapacity: sequence.underestimatedCount)
|
||||
for (key, value) in sequence {
|
||||
namedValues[key] = value?.databaseValue ?? .null
|
||||
}
|
||||
values = .init()
|
||||
}
|
||||
|
||||
/// Creates statement arguments from [AnyHashable: Any].
|
||||
|
||||
@@ -55,7 +55,7 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
invalidatesDatabaseSchemaCache = true
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_ALTER_TABLE, SQLITE_DETACH,
|
||||
case SQLITE_ATTACH, SQLITE_DETACH, SQLITE_ALTER_TABLE,
|
||||
SQLITE_CREATE_INDEX, SQLITE_CREATE_TABLE,
|
||||
SQLITE_CREATE_TEMP_INDEX, SQLITE_CREATE_TEMP_TABLE,
|
||||
SQLITE_CREATE_TEMP_TRIGGER, SQLITE_CREATE_TEMP_VIEW,
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -13,6 +13,7 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@inlinable
|
||||
public var databaseValue: DatabaseValue {
|
||||
DatabaseValue(storage: .blob(self))
|
||||
}
|
||||
@@ -31,4 +32,85 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
withUnsafeBytes {
|
||||
sqlite3_bind_blob(sqliteStatement, index, $0.baseAddress, Int32($0.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// Decimal adopts DatabaseValueConvertible
|
||||
extension Decimal: DatabaseValueConvertible {
|
||||
public var databaseValue: DatabaseValue {
|
||||
NSDecimalNumber(decimal: self)
|
||||
.description(withLocale: Locale(identifier: "en_US_POSIX"))
|
||||
.databaseValue
|
||||
}
|
||||
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64):
|
||||
return self.init(int64)
|
||||
case .double(let double):
|
||||
return self.init(double)
|
||||
case let .string(string):
|
||||
// Must match NSNumber.fromDatabaseValue(_:)
|
||||
return self.init(string: string, locale: posixLocale)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Decimal adopts StatementColumnConvertible
|
||||
extension Decimal: StatementColumnConvertible {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_INTEGER:
|
||||
self.init(sqlite3_column_int64(sqliteStatement, index))
|
||||
case SQLITE_FLOAT:
|
||||
self.init(sqlite3_column_double(sqliteStatement, index))
|
||||
case SQLITE_TEXT:
|
||||
self.init(
|
||||
string: String(cString: sqlite3_column_text(sqliteStatement, index)!),
|
||||
locale: posixLocale)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private let posixLocale = Locale(identifier: "en_US_POSIX")
|
||||
#endif
|
||||
@@ -71,9 +71,15 @@ extension NSNumber: DatabaseValueConvertible {
|
||||
return self.init(value: int64)
|
||||
case .double(let double):
|
||||
return self.init(value: double)
|
||||
case let .string(string):
|
||||
// Must match Decimal.fromDatabaseValue(_:)
|
||||
guard let decimal = Decimal(string: string, locale: posixLocale) else { return nil }
|
||||
return NSDecimalNumber(decimal: decimal) as? Self
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private let posixLocale = Locale(identifier: "en_US_POSIX")
|
||||
#endif
|
||||
@@ -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,15 @@ extension SQLExpressible where Self: RawRepresentable, Self.RawValue: SQLExpress
|
||||
}
|
||||
}
|
||||
|
||||
/// DatabaseValueConvertible is free for RawRepresentable types whose raw value
|
||||
/// is itself DatabaseValueConvertible.
|
||||
extension StatementBinding where Self: RawRepresentable, Self.RawValue: StatementBinding {
|
||||
@inlinable
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
rawValue.bind(to: sqliteStatement, at: index)
|
||||
}
|
||||
}
|
||||
|
||||
/// `DatabaseValueConvertible` is free for `RawRepresentable` types whose raw
|
||||
/// value is itself `DatabaseValueConvertible`.
|
||||
///
|
||||
/// // If the RawValue adopts DatabaseValueConvertible...
|
||||
/// enum Color : Int {
|
||||
@@ -27,16 +34,15 @@ 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.
|
||||
@inlinable
|
||||
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) }
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@inlinable
|
||||
public var databaseValue: DatabaseValue {
|
||||
(self ? 1 : 0).databaseValue
|
||||
}
|
||||
@@ -85,6 +86,11 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, self ? 1 : 0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Int adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -96,16 +102,14 @@ 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.
|
||||
@inlinable
|
||||
public var databaseValue: DatabaseValue {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
@@ -114,6 +118,11 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { Int(exactly: $0) }
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// Int8 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -125,16 +134,14 @@ 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.
|
||||
@inlinable
|
||||
public var databaseValue: DatabaseValue {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
@@ -143,6 +150,11 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int8? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { Int8(exactly: $0) }
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// Int16 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -154,16 +166,14 @@ 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.
|
||||
@inlinable
|
||||
public var databaseValue: DatabaseValue {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
@@ -172,6 +182,11 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int16? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { Int16(exactly: $0) }
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// Int32 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -183,16 +198,14 @@ 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.
|
||||
@inlinable
|
||||
public var databaseValue: DatabaseValue {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
@@ -201,6 +214,11 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int32? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { Int32(exactly: $0) }
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// Int64 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -217,6 +235,7 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@inlinable
|
||||
public var databaseValue: DatabaseValue {
|
||||
DatabaseValue(storage: .int64(self))
|
||||
}
|
||||
@@ -234,6 +253,11 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, self)
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -245,16 +269,14 @@ 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.
|
||||
@inlinable
|
||||
public var databaseValue: DatabaseValue {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
@@ -263,6 +285,11 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { UInt(exactly: $0) }
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt8 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -274,16 +301,14 @@ 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.
|
||||
@inlinable
|
||||
public var databaseValue: DatabaseValue {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
@@ -292,6 +317,11 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt8? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { UInt8(exactly: $0) }
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt16 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -303,16 +333,14 @@ 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.
|
||||
@inlinable
|
||||
public var databaseValue: DatabaseValue {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
@@ -321,6 +349,11 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt16? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { UInt16(exactly: $0) }
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt32 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -332,16 +365,14 @@ 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.
|
||||
@inlinable
|
||||
public var databaseValue: DatabaseValue {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
@@ -350,6 +381,11 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt32? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { UInt32(exactly: $0) }
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt64 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -361,16 +397,14 @@ 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.
|
||||
@inlinable
|
||||
public var databaseValue: DatabaseValue {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
@@ -379,6 +413,11 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt64? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { UInt64(exactly: $0) }
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// Double adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -395,6 +434,7 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@inlinable
|
||||
public var databaseValue: DatabaseValue {
|
||||
DatabaseValue(storage: .double(self))
|
||||
}
|
||||
@@ -410,6 +450,11 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_double(sqliteStatement, index, self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Float adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -426,6 +471,7 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@inlinable
|
||||
public var databaseValue: DatabaseValue {
|
||||
Double(self).databaseValue
|
||||
}
|
||||
@@ -441,6 +487,11 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_double(sqliteStatement, index, Double(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// String adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -457,6 +508,7 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@inlinable
|
||||
public var databaseValue: DatabaseValue {
|
||||
DatabaseValue(storage: .string(self))
|
||||
}
|
||||
@@ -474,6 +526,11 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_text(sqliteStatement, index, self, -1, SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -202,84 +202,86 @@ class DatabaseObservationBroker {
|
||||
/// statement, and returns the authorizer that should be used during
|
||||
/// statement execution.
|
||||
func updateStatementWillExecute(_ statement: UpdateStatement) -> StatementAuthorizer? {
|
||||
// As statement executes, it may trigger database changes that will
|
||||
// be notified to transaction observers. As a consequence, observers
|
||||
// may disable themselves with stopObservingDatabaseChangesUntilNextTransaction()
|
||||
//
|
||||
// This method takes no argument, and requires access to the "current
|
||||
// broker", which is a per-thread global stored in
|
||||
// SchedulingWatchdog.current:
|
||||
SchedulingWatchdog.current!.databaseObservationBroker = self
|
||||
|
||||
// Fill statementObservations with observations that are interested in
|
||||
// the kind of events performed by the statement.
|
||||
//
|
||||
// Those statementObservations will be notified of individual changes
|
||||
// in databaseWillChange() and databaseDidChange().
|
||||
let eventKinds = statement.databaseEventKinds
|
||||
|
||||
// If any observer observes row deletions, we'll have to disable
|
||||
// [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
|
||||
// so that observers are notified.
|
||||
var observesRowDeletion = false
|
||||
|
||||
switch eventKinds.count {
|
||||
case 0:
|
||||
// Statement has no effect on any database table.
|
||||
if transactionObservations.isEmpty == false {
|
||||
// As statement executes, it may trigger database changes that will
|
||||
// be notified to transaction observers. As a consequence, observers
|
||||
// may disable themselves with stopObservingDatabaseChangesUntilNextTransaction()
|
||||
//
|
||||
// For example: PRAGMA foreign_keys = ON
|
||||
statementObservations = []
|
||||
case 1:
|
||||
// We'll execute a simple statement without any side effect.
|
||||
// Eventual database events will thus all have the same kind. All
|
||||
// detabase events can be notified to interested observations.
|
||||
// This method takes no argument, and requires access to the "current
|
||||
// broker", which is a per-thread global stored in
|
||||
// SchedulingWatchdog.current:
|
||||
SchedulingWatchdog.current!.databaseObservationBroker = self
|
||||
|
||||
// Fill statementObservations with observations that are interested in
|
||||
// the kind of events performed by the statement.
|
||||
//
|
||||
// For example, if one observes all deletions in the table T, then
|
||||
// all individual deletions of DELETE FROM T are notified:
|
||||
let eventKind = eventKinds[0]
|
||||
statementObservations = transactionObservations.compactMap { observation in
|
||||
guard observation.observes(eventsOfKind: eventKind) else {
|
||||
// observation is not interested
|
||||
return nil
|
||||
}
|
||||
|
||||
if case .delete = eventKind {
|
||||
observesRowDeletion = true
|
||||
}
|
||||
|
||||
// observation will be notified of all individual events
|
||||
return (observation, DatabaseEventPredicate.true)
|
||||
}
|
||||
default:
|
||||
// We'll execute a complex statement with side effects performed by
|
||||
// an SQL trigger or a foreign key action. Eventual database events
|
||||
// may not all have the same kind: we need to filter them before
|
||||
// notifying interested observations.
|
||||
//
|
||||
// For example, if DELETE FROM T1 generates deletions in T1 and T2
|
||||
// by the mean of a foreign key action, then when one only observes
|
||||
// deletions in T1, one must not be notified of deletions in T2:
|
||||
statementObservations = transactionObservations.compactMap { observation in
|
||||
let observedKinds = eventKinds.filter(observation.observes)
|
||||
if observedKinds.isEmpty {
|
||||
// observation is not interested
|
||||
return nil
|
||||
}
|
||||
|
||||
for eventKind in observedKinds {
|
||||
// Those statementObservations will be notified of individual changes
|
||||
// in databaseWillChange() and databaseDidChange().
|
||||
let eventKinds = statement.databaseEventKinds
|
||||
|
||||
switch eventKinds.count {
|
||||
case 0:
|
||||
// Statement has no effect on any database table.
|
||||
//
|
||||
// For example: PRAGMA foreign_keys = ON
|
||||
statementObservations = []
|
||||
case 1:
|
||||
// We'll execute a simple statement without any side effect.
|
||||
// Eventual database events will thus all have the same kind. All
|
||||
// detabase events can be notified to interested observations.
|
||||
//
|
||||
// For example, if one observes all deletions in the table T, then
|
||||
// all individual deletions of DELETE FROM T are notified:
|
||||
let eventKind = eventKinds[0]
|
||||
statementObservations = transactionObservations.compactMap { observation in
|
||||
guard observation.observes(eventsOfKind: eventKind) else {
|
||||
// observation is not interested
|
||||
return nil
|
||||
}
|
||||
|
||||
if case .delete = eventKind {
|
||||
observesRowDeletion = true
|
||||
break
|
||||
}
|
||||
|
||||
// observation will be notified of all individual events
|
||||
return (observation, DatabaseEventPredicate.true)
|
||||
}
|
||||
default:
|
||||
// We'll execute a complex statement with side effects performed by
|
||||
// an SQL trigger or a foreign key action. Eventual database events
|
||||
// may not all have the same kind: we need to filter them before
|
||||
// notifying interested observations.
|
||||
//
|
||||
// For example, if DELETE FROM T1 generates deletions in T1 and T2
|
||||
// by the mean of a foreign key action, then when one only observes
|
||||
// deletions in T1, one must not be notified of deletions in T2:
|
||||
statementObservations = transactionObservations.compactMap { observation in
|
||||
let observedKinds = eventKinds.filter(observation.observes)
|
||||
if observedKinds.isEmpty {
|
||||
// observation is not interested
|
||||
return nil
|
||||
}
|
||||
|
||||
for eventKind in observedKinds {
|
||||
if case .delete = eventKind {
|
||||
observesRowDeletion = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// observation will only be notified of individual events that
|
||||
// match one of the observed kinds.
|
||||
return (
|
||||
observation,
|
||||
DatabaseEventPredicate.matching(
|
||||
observedKinds: observedKinds,
|
||||
advertisedKinds: eventKinds))
|
||||
}
|
||||
|
||||
// observation will only be notified of individual events that
|
||||
// match one of the observed kinds.
|
||||
return (
|
||||
observation,
|
||||
DatabaseEventPredicate.matching(
|
||||
observedKinds: observedKinds,
|
||||
advertisedKinds: eventKinds))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -327,8 +329,10 @@ class DatabaseObservationBroker {
|
||||
|
||||
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
|
||||
// Undo updateStatementWillExecute
|
||||
statementObservations = []
|
||||
SchedulingWatchdog.current!.databaseObservationBroker = nil
|
||||
if transactionObservations.isEmpty == false {
|
||||
statementObservations = []
|
||||
SchedulingWatchdog.current!.databaseObservationBroker = nil
|
||||
}
|
||||
|
||||
// Has statement any effect on transaction/savepoints?
|
||||
if let transactionEffect = statement.transactionEffect {
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+24
-12
@@ -183,8 +183,8 @@ extension QueryInterfaceRequest {
|
||||
}
|
||||
|
||||
extension SQLExpression {
|
||||
@available(*, unavailable, message: "Use SQLLiteral initializer instead")
|
||||
public var sqlLiteral: SQLLiteral
|
||||
@available(*, unavailable, message: "Use SQL initializer instead")
|
||||
public var sqlLiteral: SQL
|
||||
{ preconditionFailure() }
|
||||
}
|
||||
|
||||
@@ -194,26 +194,35 @@ extension FilteredRequest {
|
||||
{ preconditionFailure() }
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "SQL")
|
||||
public typealias SQLLiteral = SQL
|
||||
|
||||
/// :nodoc:
|
||||
extension SQLExpressionLiteral {
|
||||
@available(*, unavailable, message: "Build literal expressions with SQLLiteral.sqlExpression instead.")
|
||||
@available(*, unavailable, message: "Build literal expressions with SQL.sqlExpression instead.")
|
||||
struct SQLExpressionLiteral: SQLSpecificExpressible {
|
||||
var sqlExpression: SQLExpression { preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "Build literal expressions with SQL.sqlExpression instead.")
|
||||
public var sql: String { preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "Build literal expressions with SQLLiteral.sqlExpression instead.")
|
||||
@available(*, unavailable, message: "Build literal expressions with SQL.sqlExpression instead.")
|
||||
public var arguments: StatementArguments { preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "Build literal expressions with SQLLiteral.sqlExpression instead.")
|
||||
@available(*, unavailable, message: "Build literal expressions with SQL.sqlExpression instead.")
|
||||
public init(sql: String, arguments: StatementArguments = StatementArguments())
|
||||
{ preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "Build literal expressions with SQLLiteral.sqlExpression instead.")
|
||||
public init(literal sqlLiteral: SQLLiteral)
|
||||
@available(*, unavailable, message: "Build literal expressions with SQL.sqlExpression instead.")
|
||||
public init(literal sqlLiteral: SQL)
|
||||
{ preconditionFailure() }
|
||||
}
|
||||
|
||||
extension SQLLiteral {
|
||||
@available(*, deprecated, renamed: "SQL")
|
||||
public typealias SQLiteral = SQL
|
||||
|
||||
extension SQL {
|
||||
@available(*, unavailable, message: "Use SQL interpolation instead.")
|
||||
public func mapSQL(_ transform: @escaping (String) -> String) -> SQLLiteral
|
||||
public func mapSQL(_ transform: @escaping (String) -> String) -> SQL
|
||||
{ preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "Use the build(_:) method instead.")
|
||||
@@ -223,8 +232,11 @@ extension SQLLiteral {
|
||||
public var arguments: StatementArguments { preconditionFailure() }
|
||||
}
|
||||
|
||||
@available(*, unavailable, renamed: "SQLAssociativeBinaryOperator")
|
||||
typealias SQLLogicalBinaryOperator = SQLAssociativeBinaryOperator
|
||||
@available(*, unavailable, renamed: "SQLExpression.AssociativeBinaryOperator")
|
||||
typealias SQLLogicalBinaryOperator = SQLExpression.AssociativeBinaryOperator
|
||||
|
||||
@available(*, deprecated, renamed: "SQLExpression")
|
||||
typealias SQLCollatedExpression = SQLExpression
|
||||
|
||||
extension SQLRequest {
|
||||
@available(*, unavailable, renamed: "RowDecoder")
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
#if canImport(Combine)
|
||||
import Combine
|
||||
#endif
|
||||
import Foundation
|
||||
|
||||
/// A DatabaseMigrator registers and applies database migrations.
|
||||
///
|
||||
/// Migrations are named blocks of SQL statements that are guaranteed to be
|
||||
@@ -119,53 +124,32 @@ public struct DatabaseMigrator {
|
||||
/// - throws: An eventual error thrown by the registered migration blocks.
|
||||
public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws {
|
||||
try writer.barrierWriteWithoutTransaction { db in
|
||||
if eraseDatabaseOnSchemaChange {
|
||||
var needsErase = false
|
||||
try db.inTransaction(.deferred) {
|
||||
let appliedIdentifiers = try self.appliedIdentifiers(db)
|
||||
let knownIdentifiers = Set(migrations.map { $0.identifier })
|
||||
if !appliedIdentifiers.isSubset(of: knownIdentifiers) {
|
||||
// Database contains an unknown migration
|
||||
needsErase = true
|
||||
return .commit
|
||||
}
|
||||
|
||||
if let lastAppliedIdentifier = migrations.lazy
|
||||
.map({ $0.identifier })
|
||||
.last(where: { appliedIdentifiers.contains($0) })
|
||||
{
|
||||
// Database has been partially migrated.
|
||||
//
|
||||
// Create a temporary witness database (on disk, just in case
|
||||
// migrations would involve a lot of data).
|
||||
var witnessConfiguration = writer.configuration
|
||||
witnessConfiguration.targetQueue = nil // Avoid deadlocks
|
||||
witnessConfiguration.label = "GRDB.DatabaseMigrator.temporary"
|
||||
let witness = try DatabaseQueue(path: "", configuration: witnessConfiguration)
|
||||
|
||||
// Grab schema of migrated witness database
|
||||
let witnessSchema: SchemaInfo = try witness.writeWithoutTransaction { db in
|
||||
try runMigrations(db, upTo: lastAppliedIdentifier)
|
||||
return try db.schema()
|
||||
}
|
||||
|
||||
// Erase database if we detect a schema change
|
||||
if try db.schema() != witnessSchema {
|
||||
needsErase = true
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
|
||||
return .commit
|
||||
}
|
||||
|
||||
if needsErase {
|
||||
try db.erase()
|
||||
try migrate(db, upTo: targetIdentifier)
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterate migrations in the same order as they were registered. If a
|
||||
/// migration has not yet been applied, its block is executed in
|
||||
/// a transaction.
|
||||
///
|
||||
/// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool)
|
||||
/// where migrations should apply.
|
||||
/// - parameter completion: A closure that is called in a protected dispatch
|
||||
/// queue that can write in the database, with the eventual
|
||||
/// migration error.
|
||||
public func asyncMigrate(
|
||||
_ writer: DatabaseWriter,
|
||||
completion: @escaping (Database, Error?) -> Void)
|
||||
{
|
||||
writer.asyncBarrierWriteWithoutTransaction { db in
|
||||
do {
|
||||
if let lastMigration = self.migrations.last {
|
||||
try self.migrate(db, upTo: lastMigration.identifier)
|
||||
}
|
||||
completion(db, nil)
|
||||
} catch {
|
||||
completion(db, error)
|
||||
}
|
||||
|
||||
// Migrate to target schema
|
||||
try runMigrations(db, upTo: targetIdentifier)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,4 +270,144 @@ public struct DatabaseMigrator {
|
||||
try migration.run(db)
|
||||
}
|
||||
}
|
||||
|
||||
private func migrate(_ db: Database, upTo targetIdentifier: String) throws {
|
||||
if eraseDatabaseOnSchemaChange {
|
||||
var needsErase = false
|
||||
try db.inTransaction(.deferred) {
|
||||
let appliedIdentifiers = try self.appliedIdentifiers(db)
|
||||
let knownIdentifiers = Set(migrations.map { $0.identifier })
|
||||
if !appliedIdentifiers.isSubset(of: knownIdentifiers) {
|
||||
// Database contains an unknown migration
|
||||
needsErase = true
|
||||
return .commit
|
||||
}
|
||||
|
||||
if let lastAppliedIdentifier = migrations
|
||||
.map(\.identifier)
|
||||
.last(where: { appliedIdentifiers.contains($0) })
|
||||
{
|
||||
// Some migrations were already applied.
|
||||
//
|
||||
// Let's migrate a temporary database up to the same
|
||||
// level, and compare the database schemas. If they
|
||||
// differ, we'll erase the database.
|
||||
let tmpSchema: SchemaInfo = try {
|
||||
// Make sure the temporary database is configured
|
||||
// just as the migrated database
|
||||
var tmpConfig = db.configuration
|
||||
tmpConfig.targetQueue = nil // Avoid deadlocks
|
||||
tmpConfig.label = "GRDB.DatabaseMigrator.temporary"
|
||||
|
||||
// Create the temporary database on disk, just in
|
||||
// case migrations would involve a lot of data.
|
||||
//
|
||||
// SQLite supports temporary on-disk databases, but
|
||||
// those are not guaranteed to accept the
|
||||
// preparation functions provided by the user.
|
||||
//
|
||||
// See https://github.com/groue/GRDB.swift/issues/931
|
||||
// for an issue created by such databases.
|
||||
//
|
||||
// So let's create a "regular" temporary database:
|
||||
let tmpURL = URL(fileURLWithPath: NSTemporaryDirectory())
|
||||
.appendingPathComponent(ProcessInfo().globallyUniqueString)
|
||||
defer {
|
||||
try? FileManager().removeItem(at: tmpURL)
|
||||
}
|
||||
let tmpDatabase = try DatabaseQueue(path: tmpURL.path, configuration: tmpConfig)
|
||||
return try tmpDatabase.writeWithoutTransaction { db in
|
||||
try runMigrations(db, upTo: lastAppliedIdentifier)
|
||||
return try db.schema(.main)
|
||||
}
|
||||
}()
|
||||
|
||||
if try db.schema(.main) != tmpSchema {
|
||||
needsErase = true
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
|
||||
return .commit
|
||||
}
|
||||
|
||||
if needsErase {
|
||||
try db.erase()
|
||||
}
|
||||
}
|
||||
|
||||
// Migrate to target schema
|
||||
try runMigrations(db, upTo: targetIdentifier)
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Combine)
|
||||
extension DatabaseMigrator {
|
||||
// MARK: - Publishing Migrations
|
||||
|
||||
/// Returns a Publisher that asynchronously migrates a database.
|
||||
///
|
||||
/// let migrator: DatabaseMigrator = ...
|
||||
/// let dbQueue: DatabaseQueue = ...
|
||||
/// let publisher = migrator.migratePublisher(dbQueue)
|
||||
///
|
||||
/// It completes on the main dispatch queue.
|
||||
///
|
||||
/// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool)
|
||||
/// where migrations should apply.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func migratePublisher(_ writer: DatabaseWriter) -> DatabasePublishers.Migrate {
|
||||
migratePublisher(writer, receiveOn: DispatchQueue.main)
|
||||
}
|
||||
|
||||
/// Returns a Publisher that asynchronously migrates a database.
|
||||
///
|
||||
/// let migrator: DatabaseMigrator = ...
|
||||
/// let dbQueue: DatabaseQueue = ...
|
||||
/// let publisher = migrator.migratePublisher(dbQueue, receiveOn: DispatchQueue.global())
|
||||
///
|
||||
/// It completes on `scheduler`.
|
||||
///
|
||||
/// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool)
|
||||
/// where migrations should apply.
|
||||
/// - parameter scheduler: A Combine Scheduler.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func migratePublisher<S>(_ writer: DatabaseWriter, receiveOn scheduler: S)
|
||||
-> DatabasePublishers.Migrate
|
||||
where S: Scheduler
|
||||
{
|
||||
DatabasePublishers.Migrate(
|
||||
upstream: OnDemandFuture { promise in
|
||||
self.asyncMigrate(writer) { _, error in
|
||||
if let error = error {
|
||||
promise(.failure(error))
|
||||
} else {
|
||||
promise(.success(()))
|
||||
}
|
||||
}
|
||||
}
|
||||
.eraseToAnyPublisher()
|
||||
.receiveValues(on: scheduler)
|
||||
.eraseToAnyPublisher()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
extension DatabasePublishers {
|
||||
/// A publisher that migrates a database. It publishes exactly
|
||||
/// one element, or an error.
|
||||
///
|
||||
/// See `DatabaseMigrator.migratePublisher(_:receiveOn:)`.
|
||||
public struct Migrate: Publisher {
|
||||
public typealias Output = Void
|
||||
public typealias Failure = Error
|
||||
|
||||
fileprivate let upstream: AnyPublisher<Void, Error>
|
||||
|
||||
public func receive<S>(subscriber: S) where S: Subscriber, Self.Failure == S.Failure, Self.Output == S.Input {
|
||||
upstream.receive(subscriber: subscriber)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -72,13 +72,12 @@ extension Association {
|
||||
}
|
||||
|
||||
extension Association {
|
||||
private func mapDestinationRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self {
|
||||
fileprivate func mapDestinationRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self {
|
||||
.init(sqlAssociation: _sqlAssociation.map(\.destination.relation, transform))
|
||||
}
|
||||
}
|
||||
|
||||
extension Association {
|
||||
|
||||
/// The association key defines how rows fetched from this association
|
||||
/// should be consumed.
|
||||
///
|
||||
@@ -105,131 +104,6 @@ extension Association {
|
||||
/// }
|
||||
var key: SQLAssociationKey { _sqlAssociation.destination.key }
|
||||
|
||||
/// Creates an association which selects *selection*.
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*, team.color
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// let association = Player.team.select { db in [Column("color")]
|
||||
/// var request = Player.including(required: association)
|
||||
///
|
||||
/// Any previous selection is replaced:
|
||||
///
|
||||
/// // SELECT player.*, team.color
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// let association = Player.team
|
||||
/// .select { db in [Column("id")] }
|
||||
/// .select { db in [Column("color") }
|
||||
/// var request = Player.including(required: association)
|
||||
public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
|
||||
mapDestinationRelation { $0.select(selection) }
|
||||
}
|
||||
|
||||
/// Creates an association which appends *selection*.
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*, team.color, team.name
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// let association = Player.team
|
||||
/// .select([Column("color")])
|
||||
/// .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) }
|
||||
}
|
||||
|
||||
/// Creates an association with the provided *predicate promise* added to
|
||||
/// the eventual set of already applied predicates.
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId AND 1
|
||||
/// 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) }
|
||||
}
|
||||
|
||||
/// Creates an association with the provided *orderings promise*.
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// // ORDER BY team.name
|
||||
/// let association = Player.team.order { _ in [Column("name")] }
|
||||
/// var request = Player.including(required: association)
|
||||
///
|
||||
/// Any previous ordering is replaced:
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// // ORDER BY team.name
|
||||
/// let association = Player.team
|
||||
/// .order{ _ in [Column("color")] }
|
||||
/// .reversed()
|
||||
/// .order{ _ in [Column("name")] }
|
||||
/// var request = Player.including(required: association)
|
||||
public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self {
|
||||
mapDestinationRelation { $0.order(orderings) }
|
||||
}
|
||||
|
||||
/// Creates an association that reverses applied orderings.
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// // ORDER BY team.name DESC
|
||||
/// let association = Player.team.order(Column("name")).reversed()
|
||||
/// var request = Player.including(required: association)
|
||||
///
|
||||
/// If no ordering was applied, the returned association is identical.
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// let association = Player.team.reversed()
|
||||
/// var request = Player.including(required: association)
|
||||
public func reversed() -> Self {
|
||||
mapDestinationRelation { $0.reversed() }
|
||||
}
|
||||
|
||||
/// Creates an association without any ordering.
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// let association = Player.team.order(Column("name")).unordered()
|
||||
/// var request = Player.including(required: association)
|
||||
public func unordered() -> Self {
|
||||
mapDestinationRelation { $0.unordered() }
|
||||
}
|
||||
|
||||
/// Creates an association with the given key.
|
||||
///
|
||||
/// This new key helps Decodable records decode rows fetched from the
|
||||
@@ -285,18 +159,187 @@ 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) }
|
||||
}
|
||||
}
|
||||
|
||||
// TableRequest
|
||||
extension Association {
|
||||
/// :nodoc:
|
||||
extension Association where Self: SelectionRequest {
|
||||
|
||||
/// Creates an association which selects *selection*.
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*, team.color
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// let association = Player.team.select { db in [Column("color")]
|
||||
/// var request = Player.including(required: association)
|
||||
///
|
||||
/// Any previous selection is replaced:
|
||||
///
|
||||
/// // SELECT player.*, team.color
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// let association = Player.team
|
||||
/// .select { db in [Column("id")] }
|
||||
/// .select { db in [Column("color") }
|
||||
/// var request = Player.including(required: association)
|
||||
public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
|
||||
mapDestinationRelation { $0.select { try selection($0).map(\.sqlSelection) } }
|
||||
}
|
||||
|
||||
/// Creates an association which appends *selection*.
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*, team.color, team.name
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// let association = Player.team
|
||||
/// .select([Column("color")])
|
||||
/// .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 { try selection($0).map(\.sqlSelection) } }
|
||||
}
|
||||
}
|
||||
|
||||
extension Association where Self: FilteredRequest {
|
||||
/// Creates an association with the provided *predicate promise* added to
|
||||
/// the eventual set of already applied predicates.
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId AND 1
|
||||
/// 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 { try predicate($0).sqlExpression } }
|
||||
}
|
||||
}
|
||||
|
||||
extension Association where Self: OrderedRequest {
|
||||
/// Creates an association with the provided *orderings promise*.
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// // ORDER BY team.name
|
||||
/// let association = Player.team.order { _ in [Column("name")] }
|
||||
/// var request = Player.including(required: association)
|
||||
///
|
||||
/// Any previous ordering is replaced:
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// // ORDER BY team.name
|
||||
/// let association = Player.team
|
||||
/// .order{ _ in [Column("color")] }
|
||||
/// .reversed()
|
||||
/// .order{ _ in [Column("name")] }
|
||||
/// var request = Player.including(required: association)
|
||||
public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self {
|
||||
mapDestinationRelation { $0.order { try orderings($0).map(\.sqlOrdering) } }
|
||||
}
|
||||
|
||||
/// Creates an association that reverses applied orderings.
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// // ORDER BY team.name DESC
|
||||
/// let association = Player.team.order(Column("name")).reversed()
|
||||
/// var request = Player.including(required: association)
|
||||
///
|
||||
/// If no ordering was applied, the returned association is identical.
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// let association = Player.team.reversed()
|
||||
/// var request = Player.including(required: association)
|
||||
public func reversed() -> Self {
|
||||
mapDestinationRelation { $0.reversed() }
|
||||
}
|
||||
|
||||
/// Creates an association without any ordering.
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// let association = Player.team.order(Column("name")).unordered()
|
||||
/// var request = Player.including(required: association)
|
||||
public func unordered() -> Self {
|
||||
mapDestinationRelation { $0.unordered() }
|
||||
}
|
||||
}
|
||||
|
||||
extension Association where Self: TableRequest {
|
||||
public var databaseTableName: String {
|
||||
_sqlAssociation.destination.relation.source.tableName
|
||||
}
|
||||
}
|
||||
|
||||
extension Association where Self: AggregatingRequest {
|
||||
/// Creates an association grouped according to *expressions promise*.
|
||||
public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self {
|
||||
mapDestinationRelation { $0.group { try expressions($0).map(\.sqlExpression) } }
|
||||
}
|
||||
|
||||
/// Creates an association with the provided *predicate promise* added to
|
||||
/// the eventual set of already applied predicates.
|
||||
public func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self {
|
||||
mapDestinationRelation { $0.having { try predicate($0).sqlExpression } }
|
||||
}
|
||||
}
|
||||
|
||||
extension Association where Self: DerivableRequest {
|
||||
/// Creates an association for returns distinct rows.
|
||||
public func distinct() -> Self {
|
||||
mapDestinationRelation { $0.with(\.isDistinct, true) }
|
||||
}
|
||||
|
||||
/// Creates an association that fetches *limit* rows, starting at *offset*.
|
||||
///
|
||||
/// Any previous limit is replaced.
|
||||
///
|
||||
/// - warning: Avoid this method: it is unlikely it does what you expect it
|
||||
/// to do. It will be removed in a future GRDB version.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func limit(_ limit: Int, offset: Int? = nil) -> Self {
|
||||
mapDestinationRelation { $0.with(\.limit, SQLLimit(limit: limit, offset: offset)) }
|
||||
}
|
||||
|
||||
/// Returns an association that embeds the common table expression.
|
||||
///
|
||||
/// See `QueryInterfaceRequest.with(_:)` for more information.
|
||||
public func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> Self {
|
||||
mapDestinationRelation { $0.with(\.ctes[cte.tableName], cte.cte) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - AssociationToOne
|
||||
|
||||
/// The base protocol for all associations that define a one-to-one connection.
|
||||
|
||||
@@ -1,25 +1,8 @@
|
||||
import Foundation
|
||||
|
||||
typealias AssociationAggregatePreparation<RowDecoder> =
|
||||
(inout QueryInterfaceRequest<RowDecoder>)
|
||||
-> DatabasePromise<SQLExpression>
|
||||
|
||||
extension AssociationToMany {
|
||||
private func makeAggregate(_ expressionPromise: DatabasePromise<SQLExpression>)
|
||||
-> AssociationAggregate<OriginRowDecoder>
|
||||
{
|
||||
AssociationAggregate { request in
|
||||
let tableAlias = TableAlias()
|
||||
request = request
|
||||
.joining(optional: self.aliased(tableAlias))
|
||||
.groupByPrimaryKey()
|
||||
return expressionPromise.map { tableAlias[$0] }
|
||||
}
|
||||
}
|
||||
|
||||
// Convenience
|
||||
private func makeAggregate(_ expression: SQLExpression) -> AssociationAggregate<OriginRowDecoder> {
|
||||
makeAggregate(DatabasePromise(value: expression))
|
||||
AssociationAggregate(preparation: BasePreparation(association: self, expression: expression))
|
||||
}
|
||||
|
||||
/// The number of associated records.
|
||||
@@ -38,8 +21,8 @@ extension AssociationToMany {
|
||||
///
|
||||
/// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db)
|
||||
public var count: AssociationAggregate<OriginRowDecoder> {
|
||||
let expression = SQLExpressionCountDistinct(SQLExpressionFastPrimaryKey())
|
||||
return makeAggregate(expression).forKey("\(key.singularizedName)Count")
|
||||
makeAggregate(.countDistinct(.fastPrimaryKey))
|
||||
.forKey("\(key.singularizedName)Count")
|
||||
}
|
||||
|
||||
/// Creates an aggregate that is true if there exists no associated records.
|
||||
@@ -58,8 +41,8 @@ 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()))
|
||||
return makeAggregate(expression).forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)")
|
||||
makeAggregate(.isEmpty(.countDistinct(.fastPrimaryKey)))
|
||||
.forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)")
|
||||
}
|
||||
|
||||
/// Creates an aggregate which evaluate to the average value of the given
|
||||
@@ -80,7 +63,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(.aggregate("AVG", [expression.sqlExpression]))
|
||||
if let column = expression as? ColumnExpression {
|
||||
let name = key.singularizedName
|
||||
return aggregate.forKey("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
|
||||
@@ -107,7 +90,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(.aggregate("MAX", [expression.sqlExpression]))
|
||||
if let column = expression as? ColumnExpression {
|
||||
let name = key.singularizedName
|
||||
return aggregate.forKey("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
|
||||
@@ -134,7 +117,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(.aggregate("MIN", [expression.sqlExpression]))
|
||||
if let column = expression as? ColumnExpression {
|
||||
let name = key.singularizedName
|
||||
return aggregate.forKey("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
|
||||
@@ -161,7 +144,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(.aggregate("SUM", [expression.sqlExpression]))
|
||||
if let column = expression as? ColumnExpression {
|
||||
let name = key.singularizedName
|
||||
return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum")
|
||||
@@ -194,9 +177,13 @@ extension AssociationToMany {
|
||||
/// // Won't compile because Fruit is not Author.
|
||||
/// let request = Fruit.annotated(with: bookCount)
|
||||
public struct AssociationAggregate<RowDecoder> {
|
||||
/// Extend the request with the associated records used to compute the
|
||||
/// aggregate, and return an expression promise which resolves to the
|
||||
/// aggregated value.
|
||||
fileprivate let preparation: AssociationAggregatePreparation<RowDecoder>
|
||||
|
||||
/// The SQL name for the value of this aggregate. See forKey(_:).
|
||||
var key: String? = nil
|
||||
|
||||
/// Extends the request with the associated records used to compute the
|
||||
/// aggregate, and returns the aggregated expression.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -208,7 +195,7 @@ public struct AssociationAggregate<RowDecoder> {
|
||||
/// var request = Author.all()
|
||||
///
|
||||
/// let aggregate = Author.books.count
|
||||
/// let expressionPromise = aggregate.prepare(&request)
|
||||
/// let expression = aggregate.prepare(&request)
|
||||
///
|
||||
/// // The request has been extended with associated records:
|
||||
/// //
|
||||
@@ -220,17 +207,18 @@ public struct AssociationAggregate<RowDecoder> {
|
||||
/// // The aggregated value:
|
||||
/// //
|
||||
/// // COUNT(DISTINCT book.id)
|
||||
/// try expressionPromise.resolve(db)
|
||||
/// expression
|
||||
///
|
||||
/// The aggregated value is not right away embedded in the extended request:
|
||||
/// The aggregated expression is not embedded in the extended request:
|
||||
///
|
||||
/// - We don't know yet if the aggregated value will be used in the
|
||||
/// - We don't know yet if the aggregated expression will be used in the
|
||||
/// SQL selection, or in the HAVING clause.
|
||||
/// - It helps implementing aggregate operators such as `&&`, `+`, etc.
|
||||
let prepare: AssociationAggregatePreparation<RowDecoder>
|
||||
|
||||
/// The SQL name for the value of this aggregate. See forKey(_:).
|
||||
var key: String? = nil
|
||||
func prepare<Request>(_ request: inout Request) -> SQLExpression
|
||||
where Request: DerivableRequest, Request.RowDecoder == RowDecoder
|
||||
{
|
||||
preparation.prepare(&request)
|
||||
}
|
||||
}
|
||||
|
||||
extension AssociationAggregate: Refinable {
|
||||
@@ -265,12 +253,109 @@ extension AssociationAggregate: Refinable {
|
||||
public func forKey(_ key: CodingKey) -> Self {
|
||||
forKey(key.stringValue)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - AssociationAggregatePreparation
|
||||
|
||||
/// An abstract class that only exists as support for
|
||||
/// `AssociationAggregate.prepare(_:)`, which needs to prepare both query
|
||||
/// interface requests and associations through their conformance
|
||||
/// to `DerivableRequest`:
|
||||
///
|
||||
/// aggregate.prepare(&request)
|
||||
/// aggregate.prepare(&association)
|
||||
///
|
||||
/// We could have used a generic closure instead of this class... if only Swift
|
||||
/// would support generic closures.
|
||||
private class AssociationAggregatePreparation<RowDecoder> {
|
||||
func prepare<Request>(_ request: inout Request) -> SQLExpression
|
||||
where Request: DerivableRequest, Request.RowDecoder == RowDecoder
|
||||
{
|
||||
fatalError("subclass must override")
|
||||
}
|
||||
}
|
||||
|
||||
/// Prepares a request so that it can use association aggregates.
|
||||
private class BasePreparation<Association: AssociationToMany>:
|
||||
AssociationAggregatePreparation<Association.OriginRowDecoder> // swiftlint:disable:previous colon
|
||||
{
|
||||
private let association: Association
|
||||
private let expression: SQLExpression
|
||||
|
||||
init(association: Association, expression: SQLExpression) {
|
||||
self.association = association
|
||||
self.expression = expression
|
||||
}
|
||||
|
||||
override func prepare<Request>(_ request: inout Request) -> SQLExpression
|
||||
where Request: DerivableRequest, Request.RowDecoder == Association.OriginRowDecoder
|
||||
{
|
||||
// The fundamental request that supports association aggregate:
|
||||
//
|
||||
// SELECT parent.*
|
||||
// LEFT JOIN child ON child.parentID = parent.id
|
||||
// GROUP BY parent.id
|
||||
let tableAlias = TableAlias()
|
||||
request = request
|
||||
.joining(optional: association.aliased(tableAlias))
|
||||
.groupByPrimaryKey()
|
||||
|
||||
// The fundamental request can now be annotated, or filtered in the
|
||||
// having clause, with the association aggregate expression:
|
||||
// MIN(child.score), COUNT(DISTINCT child.id), etc.
|
||||
return expression.qualified(with: tableAlias)
|
||||
}
|
||||
}
|
||||
|
||||
/// Transforms the expression of an aggregate.
|
||||
private class MapPreparation<RowDecoder>: AssociationAggregatePreparation<RowDecoder> {
|
||||
private let base: AssociationAggregatePreparation<RowDecoder>
|
||||
private let transform: (SQLExpression) -> SQLExpression
|
||||
|
||||
init(
|
||||
base: AssociationAggregatePreparation<RowDecoder>,
|
||||
transform: @escaping (SQLExpression) -> SQLExpression)
|
||||
{
|
||||
self.base = base
|
||||
self.transform = transform
|
||||
}
|
||||
|
||||
override func prepare<Request>(_ request: inout Request) -> SQLExpression
|
||||
where Request: DerivableRequest, Request.RowDecoder == RowDecoder
|
||||
{
|
||||
transform(base.prepare(&request))
|
||||
}
|
||||
}
|
||||
|
||||
extension AssociationAggregate {
|
||||
/// Transforms the expression, and does not preserve key.
|
||||
fileprivate func map(_ transform: @escaping (SQLExpression) throws -> SQLExpression) -> Self {
|
||||
AssociationAggregate { request in
|
||||
self.prepare(&request).map(transform)
|
||||
}
|
||||
fileprivate func map(_ transform: @escaping (SQLExpression) -> SQLExpression) -> Self {
|
||||
AssociationAggregate(preparation: MapPreparation(base: preparation, transform: transform))
|
||||
}
|
||||
}
|
||||
|
||||
/// Combines the expressions of two aggregates.
|
||||
private class CombinePreparation<RowDecoder>: AssociationAggregatePreparation<RowDecoder> {
|
||||
private let lhs: AssociationAggregatePreparation<RowDecoder>
|
||||
private let rhs: AssociationAggregatePreparation<RowDecoder>
|
||||
private let combine: (_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression
|
||||
|
||||
init(
|
||||
_ lhs: AssociationAggregatePreparation<RowDecoder>,
|
||||
_ rhs: AssociationAggregatePreparation<RowDecoder>,
|
||||
combine: @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression)
|
||||
{
|
||||
self.lhs = lhs
|
||||
self.rhs = rhs
|
||||
self.combine = combine
|
||||
}
|
||||
|
||||
override func prepare<Request>(_ request: inout Request) -> SQLExpression
|
||||
where Request: DerivableRequest, Request.RowDecoder == RowDecoder
|
||||
{
|
||||
let lhsExpression = lhs.prepare(&request)
|
||||
let rhsExpression = rhs.prepare(&request)
|
||||
return combine(lhsExpression, rhsExpression)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -278,18 +363,10 @@ extension AssociationAggregate: Refinable {
|
||||
private func combine<RowDecoder>(
|
||||
_ lhs: AssociationAggregate<RowDecoder>,
|
||||
_ rhs: AssociationAggregate<RowDecoder>,
|
||||
with combineExpressions : @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) throws -> SQLExpression)
|
||||
with combine: @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
AssociationAggregate { request in
|
||||
let lhsPromise = lhs.prepare(&request)
|
||||
let rhsPromise = rhs.prepare(&request)
|
||||
return DatabasePromise { db in
|
||||
try combineExpressions(
|
||||
lhsPromise.resolve(db),
|
||||
rhsPromise.resolve(db))
|
||||
}
|
||||
}
|
||||
AssociationAggregate(preparation: CombinePreparation(lhs.preparation, rhs.preparation, combine: combine))
|
||||
}
|
||||
|
||||
// MARK: - Logical Operators (AND, OR, NOT)
|
||||
|
||||
@@ -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,41 +113,145 @@ 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`.
|
||||
/// Creates a common table expression from an SQL *literal*.
|
||||
///
|
||||
/// For example:
|
||||
/// Literals allow you to safely embed raw values in your SQL, without any
|
||||
/// risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// // WITH p AS (SELECT * FROM player WHERE name = 'O''Brien') ...
|
||||
/// let name = "O'Brien"
|
||||
/// let p = CommonTableExpression<Void>(
|
||||
/// named: "p",
|
||||
/// literal: "SELECT * FROM player WHERE name = \("O'Brien")")
|
||||
/// literal: "SELECT * FROM player WHERE name = \(name)")
|
||||
///
|
||||
/// - 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.
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
public init(
|
||||
recursive: Bool = false,
|
||||
named tableName: String,
|
||||
columns: [String]? = nil,
|
||||
literal sqlLiteral: SQLLiteral)
|
||||
literal sqlLiteral: SQL)
|
||||
{
|
||||
self.init(
|
||||
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 SQL *literal*.
|
||||
///
|
||||
/// Literals allow you to safely embed raw values in your SQL, without any
|
||||
/// risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// // WITH p AS (SELECT * FROM player WHERE name = 'O''Brien') ...
|
||||
/// let name = "O'Brien"
|
||||
/// let p = CommonTableExpression(
|
||||
/// named: "p",
|
||||
/// literal: "SELECT * FROM player WHERE name = \(name)")
|
||||
///
|
||||
/// - 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 `SQL` literal.
|
||||
public init(
|
||||
recursive: Bool = false,
|
||||
named tableName: String,
|
||||
columns: [String]? = nil,
|
||||
literal sqlLiteral: SQL)
|
||||
{
|
||||
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)] })
|
||||
.all(fromTable: tableName)
|
||||
}
|
||||
|
||||
/// Creates a request for all rows of the common table expression.
|
||||
@@ -136,7 +274,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 +288,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,88 +312,27 @@ 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.
|
||||
var isRecursive: Bool
|
||||
|
||||
/// The number of columns in the common table expression.
|
||||
func columnsCount(_ db: Database) throws -> Int {
|
||||
func columnCount(_ db: Database) throws -> Int {
|
||||
if let columns = columns {
|
||||
// No need to hit the database
|
||||
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.columnCount(db)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,7 +353,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 +389,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
|
||||
@@ -328,83 +409,3 @@ extension CommonTableExpression {
|
||||
JoinAssociation(to: Destination.relationForAll, condition: .none)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - QueryInterfaceRequest
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
/// Returns a request which embeds the common table expression.
|
||||
///
|
||||
/// If a common table expression with the same table name had already been
|
||||
/// embedded, it is replaced by the new one.
|
||||
///
|
||||
/// 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.all()
|
||||
/// .with(latestMessageCTE)
|
||||
/// .including(optional: latestMessage)
|
||||
///
|
||||
/// - parameter cte: A common table expression.
|
||||
/// - returns: A request.
|
||||
public func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> Self {
|
||||
with(\.query.ctes[cte.tableName], cte.cte)
|
||||
}
|
||||
}
|
||||
|
||||
extension TableRecord {
|
||||
/// Returns a request which embeds the common table expression.
|
||||
///
|
||||
/// If a common table expression with the same table name had already been
|
||||
/// embedded, it is replaced by the new one.
|
||||
///
|
||||
/// For example, you can build a request that fetches all chats with their
|
||||
/// latest post:
|
||||
///
|
||||
/// 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.
|
||||
/// - returns: A request.
|
||||
public static func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> QueryInterfaceRequest<Self> {
|
||||
all().with(cte)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -29,20 +29,18 @@
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift#the-query-interface
|
||||
public struct QueryInterfaceRequest<RowDecoder> {
|
||||
var query: SQLQuery
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
init(relation: SQLRelation) {
|
||||
self.init(query: SQLQuery(relation: relation))
|
||||
}
|
||||
var relation: SQLRelation
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest: Refinable { }
|
||||
|
||||
extension QueryInterfaceRequest: FetchRequest {
|
||||
public var sqlSubquery: SQLSubquery {
|
||||
.relation(relation)
|
||||
}
|
||||
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
try query.fetchCount(db)
|
||||
try relation.fetchCount(db)
|
||||
}
|
||||
|
||||
public func makePreparedRequest(
|
||||
@@ -50,27 +48,17 @@ extension QueryInterfaceRequest: FetchRequest {
|
||||
forSingleResult singleResult: Bool = false)
|
||||
throws -> PreparedRequest
|
||||
{
|
||||
let generator = SQLQueryGenerator(query: query, forSingleResult: singleResult)
|
||||
let generator = SQLQueryGenerator(relation: relation, forSingleResult: singleResult)
|
||||
var preparedRequest = try generator.makePreparedRequest(db)
|
||||
let associations = query.relation.prefetchedAssociations
|
||||
let associations = 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.supplementaryFetch = { [relation] db, rows in
|
||||
try prefetch(db, associations: associations, from: relation, 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 +77,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(\.relation) { $0.select { try selection($0).map(\.sqlSelection) } }
|
||||
}
|
||||
|
||||
/// Creates a request which selects *selection*, and fetches values of
|
||||
@@ -103,7 +91,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
|
||||
@@ -134,42 +122,27 @@ extension QueryInterfaceRequest: SelectionRequest {
|
||||
as type: RowDecoder.Type = RowDecoder.self)
|
||||
-> QueryInterfaceRequest<RowDecoder>
|
||||
{
|
||||
select(literal: SQLLiteral(sql: sql, arguments: arguments), as: type)
|
||||
select(SQL(sql: sql, arguments: arguments), as: type)
|
||||
}
|
||||
|
||||
/// Creates a request which selects an SQL *literal*, and fetches values of
|
||||
/// type *type*.
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// // SELECT IFNULL(name, 'Anonymous') FROM player WHERE id = 42
|
||||
/// let request = Player.
|
||||
/// .filter(primaryKey: 42)
|
||||
/// .select(
|
||||
/// SQLLiteral(
|
||||
/// sql: "IFNULL(name, ?)",
|
||||
/// arguments: ["Anonymous"]),
|
||||
/// as: String.self)
|
||||
/// let name: String? = try request.fetchOne(db)
|
||||
/// }
|
||||
/// Literals allow you to safely embed raw values in your SQL, without any
|
||||
/// risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// With Swift 5, you can safely embed raw values in your SQL queries,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// // SELECT IFNULL(name, 'Anonymous') FROM player WHERE id = 42
|
||||
/// let request = Player.
|
||||
/// .filter(primaryKey: 42)
|
||||
/// .select(
|
||||
/// literal: "IFNULL(name, \("Anonymous"))",
|
||||
/// as: String.self)
|
||||
/// let name: String? = try request.fetchOne(db)
|
||||
/// }
|
||||
/// // SELECT IFNULL(name, 'Anonymous') FROM player
|
||||
/// let defaultName = "Anonymous"
|
||||
/// let request = Player.all().select(
|
||||
/// literal: "IFNULL(name, \(defaultName))",
|
||||
/// as: String.self)
|
||||
/// let name: String? = try request.fetchOne(db)
|
||||
public func select<RowDecoder>(
|
||||
literal sqlLiteral: SQLLiteral,
|
||||
literal sqlLiteral: SQL,
|
||||
as type: RowDecoder.Type = RowDecoder.self)
|
||||
-> QueryInterfaceRequest<RowDecoder>
|
||||
{
|
||||
select(sqlLiteral.sqlSelectable, as: type)
|
||||
select(sqlLiteral, as: type)
|
||||
}
|
||||
|
||||
/// Creates a request which appends *selection promise*.
|
||||
@@ -180,7 +153,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(\.relation) { $0.annotated { try selection($0).map(\.sqlSelection) } }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -192,7 +165,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(\.relation) { $0.filter { try predicate($0).sqlExpression } }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -211,7 +184,7 @@ extension QueryInterfaceRequest: OrderedRequest {
|
||||
/// .reversed()
|
||||
/// .order{ _ in [Column("name")] }
|
||||
public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceRequest {
|
||||
map(\.query) { $0.order(orderings) }
|
||||
map(\.relation) { $0.order { try orderings($0).map(\.sqlOrdering) } }
|
||||
}
|
||||
|
||||
/// Creates a request that reverses applied orderings.
|
||||
@@ -226,7 +199,7 @@ extension QueryInterfaceRequest: OrderedRequest {
|
||||
/// var request = Player.all()
|
||||
/// request = request.reversed()
|
||||
public func reversed() -> QueryInterfaceRequest {
|
||||
map(\.query) { $0.reversed() }
|
||||
map(\.relation) { $0.reversed() }
|
||||
}
|
||||
|
||||
/// Creates a request without any ordering.
|
||||
@@ -235,20 +208,20 @@ extension QueryInterfaceRequest: OrderedRequest {
|
||||
/// var request = Player.all().order(Column("name"))
|
||||
/// request = request.unordered()
|
||||
public func unordered() -> QueryInterfaceRequest {
|
||||
map(\.query) { $0.unordered() }
|
||||
map(\.relation) { $0.unordered() }
|
||||
}
|
||||
}
|
||||
|
||||
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(\.relation) { $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(\.relation) { $0.having { try predicate($0).sqlExpression } }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -256,27 +229,27 @@ extension QueryInterfaceRequest: AggregatingRequest {
|
||||
extension QueryInterfaceRequest: _JoinableRequest {
|
||||
/// :nodoc:
|
||||
public func _including(all association: _SQLAssociation) -> QueryInterfaceRequest {
|
||||
map(\.query) { $0._including(all: association) }
|
||||
map(\.relation) { $0._including(all: association) }
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _including(optional association: _SQLAssociation) -> QueryInterfaceRequest {
|
||||
map(\.query) { $0._including(optional: association) }
|
||||
map(\.relation) { $0._including(optional: association) }
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _including(required association: _SQLAssociation) -> QueryInterfaceRequest {
|
||||
map(\.query) { $0._including(required: association) }
|
||||
map(\.relation) { $0._including(required: association) }
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _joining(optional association: _SQLAssociation) -> QueryInterfaceRequest {
|
||||
map(\.query) { $0._joining(optional: association) }
|
||||
map(\.relation) { $0._joining(optional: association) }
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _joining(required association: _SQLAssociation) -> QueryInterfaceRequest {
|
||||
map(\.query) { $0._joining(required: association) }
|
||||
map(\.relation) { $0._joining(required: association) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -285,7 +258,7 @@ extension QueryInterfaceRequest: JoinableRequest { }
|
||||
extension QueryInterfaceRequest: TableRequest {
|
||||
/// :nodoc:
|
||||
public var databaseTableName: String {
|
||||
query.relation.source.tableName
|
||||
relation.source.tableName
|
||||
}
|
||||
|
||||
/// Creates a request that allows you to define expressions that target
|
||||
@@ -306,37 +279,32 @@ 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(\.relation) { $0.aliased(alias) }
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest: DerivableRequest where RowDecoder: TableRecord { }
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
/// Creates a request which returns distinct rows.
|
||||
///
|
||||
/// // SELECT DISTINCT * FROM player
|
||||
/// var request = Player.all()
|
||||
/// request = request.distinct()
|
||||
///
|
||||
/// // SELECT DISTINCT name FROM player
|
||||
/// var request = Player.select(Column("name"))
|
||||
/// request = request.distinct()
|
||||
extension QueryInterfaceRequest: DerivableRequest {
|
||||
public func distinct() -> QueryInterfaceRequest {
|
||||
map(\.query) { $0.distinct() }
|
||||
with(\.relation.isDistinct, true)
|
||||
}
|
||||
|
||||
/// Creates a request which fetches *limit* rows, starting at *offset*.
|
||||
///
|
||||
/// // SELECT * FROM player LIMIT 1
|
||||
/// // SELECT * FROM player LIMIT 10 OFFSET 20
|
||||
/// var request = Player.all()
|
||||
/// request = request.limit(1)
|
||||
/// request = request.limit(10, offset: 20)
|
||||
///
|
||||
/// Any previous limit is replaced.
|
||||
public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest {
|
||||
map(\.query) { $0.limit(limit, offset: offset) }
|
||||
public func limit(_ limit: Int, offset: Int?) -> QueryInterfaceRequest {
|
||||
with(\.relation.limit, SQLLimit(limit: limit, offset: offset))
|
||||
}
|
||||
|
||||
public func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> Self {
|
||||
with(\.relation.ctes[cte.tableName], cte.cte)
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
/// Creates a request bound to type RowDecoder.
|
||||
///
|
||||
/// The returned request can fetch if the type RowDecoder is fetchable (Row,
|
||||
@@ -351,7 +319,7 @@ extension QueryInterfaceRequest {
|
||||
/// - parameter type: The fetched type RowDecoder
|
||||
/// - returns: A request bound to type RowDecoder.
|
||||
public func asRequest<RowDecoder>(of type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
|
||||
QueryInterfaceRequest<RowDecoder>(query: query)
|
||||
QueryInterfaceRequest<RowDecoder>(relation: relation)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -365,7 +333,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
@discardableResult
|
||||
public func deleteAll(_ db: Database) throws -> Int {
|
||||
try SQLQueryGenerator(query: query).makeDeleteStatement(db).execute()
|
||||
try SQLQueryGenerator(relation: relation).makeDeleteStatement(db).execute()
|
||||
return db.changesCount
|
||||
}
|
||||
}
|
||||
@@ -395,7 +363,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
|
||||
_ assignments: [ColumnAssignment]) throws -> Int
|
||||
{
|
||||
let conflictResolution = conflictResolution ?? RowDecoder.persistenceConflictPolicy.conflictResolutionForUpdate
|
||||
guard let updateStatement = try SQLQueryGenerator(query: query).makeUpdateStatement(
|
||||
guard let updateStatement = try SQLQueryGenerator(relation: relation).makeUpdateStatement(
|
||||
db,
|
||||
conflictResolution: conflictResolution,
|
||||
assignments: assignments) else
|
||||
@@ -449,12 +417,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 +437,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 +496,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 originRelation: SQLRelation,
|
||||
into originRows: [Row]) throws
|
||||
{
|
||||
guard let firstBaseRow = baseRows.first else {
|
||||
guard let firstOriginRow = originRows.first else {
|
||||
// No rows -> no prefetch
|
||||
return
|
||||
}
|
||||
@@ -554,10 +520,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 = originRelation.source.tableName
|
||||
let pivotMapping = try pivotForeignKey.joinMapping(db, from: originTable)
|
||||
let pivotColumns = pivotMapping.map(\.right)
|
||||
let leftColumns = pivotMapping.map(\.left)
|
||||
|
||||
@@ -587,7 +552,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 +570,24 @@ 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
|
||||
// Ordering and including(all:) children are
|
||||
// useless, and we only need pivoting columns:
|
||||
baseRelation
|
||||
.unordered()
|
||||
.removingChildrenForPrefetchedAssociations()
|
||||
.selectOnly(leftColumns.map(Column.init))
|
||||
}
|
||||
let baseCTE = CommonTableExpression<Void>(
|
||||
//
|
||||
// In the CTE, ordering and including(all:) children are
|
||||
// useless, and we only need to select pivot columns:
|
||||
let originRelation = originRelation
|
||||
.unordered()
|
||||
.removingChildrenForPrefetchedAssociations()
|
||||
.selectOnly(leftColumns.map { SQLExpression.column($0).sqlSelection })
|
||||
let originCTE = CommonTableExpression(
|
||||
named: "grdb_base",
|
||||
request: baseRequest)
|
||||
let pivotFilter = baseCTE.contains(SQLRowValue(pivotColumns.map(Column.init)))
|
||||
request: SQLSubquery.relation(originRelation))
|
||||
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 +601,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 +611,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 +659,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 +668,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 +681,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)
|
||||
}
|
||||
@@ -739,9 +707,7 @@ throws -> DatabaseRegion
|
||||
.map(\.pivot.relation) { $0.filter(pivotFilter) }
|
||||
.destinationRelation()
|
||||
|
||||
let prefetchQuery = SQLQuery(relation: prefetchRelation)
|
||||
|
||||
return try SQLQueryGenerator(query: prefetchQuery)
|
||||
return try SQLQueryGenerator(relation: prefetchRelation)
|
||||
.makeSelectStatement(db)
|
||||
.databaseRegion // contains region of nested associations
|
||||
}
|
||||
|
||||
Loaded 100 of 213 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user