Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4c2290f84b | ||
|
|
efc8e4bbf9 | ||
|
|
5c986b142b | ||
|
|
4ec77f8d02 | ||
|
|
d7dfb4c2ed | ||
|
|
f4a32edbb9 | ||
|
|
8bb9ef0849 | ||
|
|
0210144ea9 | ||
|
|
2842bc92ca | ||
|
|
2ca857d895 | ||
|
|
95ec107134 | ||
|
|
18c65eecb6 | ||
|
|
3c1ab47843 | ||
|
|
6b706bbc85 | ||
|
|
e6435ade96 | ||
|
|
c854b5a88a | ||
|
|
f2d51d2feb | ||
|
|
95cd6f3c4f | ||
|
|
4a0d8602e2 | ||
|
|
a83f76be10 | ||
|
|
10420e6426 | ||
|
|
5ab90c1b6c | ||
|
|
5c70477a04 | ||
|
|
cb4a0f349e | ||
|
|
9a0db52c9b | ||
|
|
7cf7300129 | ||
|
|
6fbeed1a2a | ||
|
|
1defe3aaf1 | ||
|
|
074af18152 | ||
|
|
43c9aa3474 | ||
|
|
d95a76a47a | ||
|
|
ae8c1f11a9 | ||
|
|
4decdd7dea | ||
|
|
1d41807e25 | ||
|
|
571a70e073 | ||
|
|
2822c959f8 | ||
|
|
d8c5d85fcb | ||
|
|
3f493fa7a8 | ||
|
|
cecc3cffdc | ||
|
|
5ea0cf6cdd | ||
|
|
3ebbddb9f3 | ||
|
|
238f01725b | ||
|
|
51b975e872 | ||
|
|
4b9643daf2 | ||
|
|
6daf078fc3 | ||
|
|
7aced9b925 | ||
|
|
16fc88ba09 | ||
|
|
4ac7e3d15c | ||
|
|
48b8c1ee14 | ||
|
|
1af981255d | ||
|
|
6a07361614 | ||
|
|
f32f5e2d7b | ||
|
|
322959f1c4 | ||
|
|
eaca12aed1 | ||
|
|
96a8b46214 | ||
|
|
7f2f4fdfcc | ||
|
|
ceccbb38fb | ||
|
|
af21c82dd6 | ||
|
|
b2573a12bc | ||
|
|
d00de45e4f | ||
|
|
6512e7bf61 | ||
|
|
1cd88114ec | ||
|
|
86cf024a78 | ||
|
|
afdde192cd | ||
|
|
0b321dfedf | ||
|
|
7617bb258d | ||
|
|
104466170b | ||
|
|
4b5a1340aa | ||
|
|
6ea56060a2 | ||
|
|
3733648598 | ||
|
|
40341d4e98 | ||
|
|
5393d97033 | ||
|
|
8bf9e5e30f | ||
|
|
bc5ba1fda5 | ||
|
|
034cf065c1 | ||
|
|
d7743d0a56 | ||
|
|
5ed0a4a6ed | ||
|
|
dd2e8bb063 | ||
|
|
790b678c74 | ||
|
|
abb50a0786 | ||
|
|
2862edcea8 | ||
|
|
91c17aca41 | ||
|
|
fc546e25e2 | ||
|
|
a5b6a0a51f | ||
|
|
befeb07234 | ||
|
|
8fe3d41d18 | ||
|
|
9628eaffb9 | ||
|
|
7be7e1cade | ||
|
|
db54c567de | ||
|
|
db6ea3b85e | ||
|
|
33f3e868da | ||
|
|
d4e380c35b | ||
|
|
0dd78f1580 | ||
|
|
267bfb29fe | ||
|
|
4e551c8c6e | ||
|
|
554a84cf28 | ||
|
|
2cfd51401a | ||
|
|
948f9d3f22 | ||
|
|
728efd3d67 | ||
|
|
1b0dd4ae25 | ||
|
|
e1b91e0642 | ||
|
|
74b71b024b | ||
|
|
c86d2d654f | ||
|
|
ff6bdc38ef | ||
|
|
ef5b284f11 | ||
|
|
836efb120f | ||
|
|
3a76b84eae | ||
|
|
ae17e9f893 | ||
|
|
6ea1e6aeaf | ||
|
|
ed32e44bc2 | ||
|
|
60a9494434 | ||
|
|
51991213ef | ||
|
|
dc16fae72e | ||
|
|
b485d4d3dc | ||
|
|
7634d3f950 | ||
|
|
6abbf82a89 | ||
|
|
2de9b2d9ed | ||
|
|
cc0611847d | ||
|
|
c844438dd6 | ||
|
|
0d6f68646c | ||
|
|
af55215356 | ||
|
|
f4f44c51d9 | ||
|
|
77a1becba1 | ||
|
|
5546961c8c | ||
|
|
d09571c0ad | ||
|
|
9b15011f17 | ||
|
|
e72007c1dd | ||
|
|
ab502baa20 | ||
|
|
eb0e0d4cdd | ||
|
|
c8818c1d44 | ||
|
|
1ff825c861 | ||
|
|
13946f1d8d | ||
|
|
6a68e31903 | ||
|
|
618be9b5e4 | ||
|
|
4a6a2c5495 | ||
|
|
6082fc4e54 | ||
|
|
4e8d129162 | ||
|
|
472b5bc604 | ||
|
|
cad788e59e | ||
|
|
2cb4cf51c3 | ||
|
|
5eff2448bb | ||
|
|
aabf6e6247 | ||
|
|
23c93eebdf | ||
|
|
732ec36b67 | ||
|
|
f1196bf924 | ||
|
|
fcd6a453f0 | ||
|
|
85af2deced | ||
|
|
b70f85d94b | ||
|
|
b715206502 | ||
|
|
18885d4ca1 | ||
|
|
555ed025bc | ||
|
|
d0e4d536d9 | ||
|
|
8c225105c2 | ||
|
|
c36539adb3 | ||
|
|
b636c391df | ||
|
|
659af2cd2a | ||
|
|
f70e2b4e37 | ||
|
|
b16e12cb6e | ||
|
|
df5c62d2d9 | ||
|
|
b89d11f8ec | ||
|
|
992f2a2d83 | ||
|
|
f94cecb329 | ||
|
|
89c117425e | ||
|
|
26c7441b49 | ||
|
|
a6d80ce208 | ||
|
|
c287449258 | ||
|
|
f9c98b4a1f | ||
|
|
86cfee4e23 | ||
|
|
a3351513ce | ||
|
|
95be9b7bb6 | ||
|
|
1c2dd8617b | ||
|
|
7f71174159 | ||
|
|
098ddf27ec | ||
|
|
bbce741688 | ||
|
|
c56382f04a | ||
|
|
71841f0a07 | ||
|
|
e43fae2a63 | ||
|
|
022a06b4bc | ||
|
|
7df77aa2d0 | ||
|
|
f18bcb67e4 | ||
|
|
cc68ef5872 | ||
|
|
5b3eee53c2 | ||
|
|
63255cabf8 | ||
|
|
9d1bcec132 | ||
|
|
b60f39e7cc | ||
|
|
5464d64180 | ||
|
|
1e2d07a16f | ||
|
|
66b23d423f | ||
|
|
3094c274df | ||
|
|
378279ee1a | ||
|
|
e509d7af65 | ||
|
|
9da4bc09c3 | ||
|
|
462461c1c9 | ||
|
|
7ded56dfc4 | ||
|
|
836a0a5e37 | ||
|
|
91dd13e2be | ||
|
|
a1f0f2c9b7 | ||
|
|
6f409f2140 | ||
|
|
64776682fe | ||
|
|
a21e6575d8 | ||
|
|
4ee6f3293a | ||
|
|
17b884b3dc | ||
|
|
0f6d36bfc2 | ||
|
|
0dc9215df6 | ||
|
|
333ffc1ebe | ||
|
|
181c930e39 | ||
|
|
65337e74d9 | ||
|
|
69c116507b | ||
|
|
2b82de42d8 | ||
|
|
10dfa3fba9 | ||
|
|
339062f01f | ||
|
|
eb2346dfce | ||
|
|
1d0adaacf6 | ||
|
|
5e8f95ca09 | ||
|
|
b085a29c8c | ||
|
|
992e8f3423 | ||
|
|
49e6923156 | ||
|
|
a7a4858364 | ||
|
|
3a38cbe87f | ||
|
|
2c42d0129c | ||
|
|
da5ef961d6 | ||
|
|
d35373dcdf | ||
|
|
adc6ba1226 | ||
|
|
b1d162c14e | ||
|
|
2b6c3fb868 | ||
|
|
a70b42cbf5 | ||
|
|
06000abbfd | ||
|
|
67bc47c3b5 | ||
|
|
5c34ab19e2 | ||
|
|
6d14f792e6 | ||
|
|
1238843a44 | ||
|
|
8000332ec4 | ||
|
|
9896607dff | ||
|
|
1be0a6cd5c | ||
|
|
0191676063 | ||
|
|
c16da693df | ||
|
|
f31dd0033c | ||
|
|
b7b89c5fa9 | ||
|
|
c776ee8d47 | ||
|
|
c36fc2813b | ||
|
|
ec2640a459 | ||
|
|
755782759a | ||
|
|
9275d4ddf8 | ||
|
|
96951b3d4e | ||
|
|
36a8cd1352 | ||
|
|
2bb9f5ce0d | ||
|
|
e1d3c1d7dc | ||
|
|
00a7eb53e8 | ||
|
|
e7dcf25063 | ||
|
|
d2b7b4240a | ||
|
|
b6ef89c116 | ||
|
|
2a917823ed | ||
|
|
2135f8e768 | ||
|
|
2c45ecf56c | ||
|
|
52f831936e | ||
|
|
28f6b64f67 | ||
|
|
cc0365d794 | ||
|
|
59ad47d640 | ||
|
|
27662f99b0 | ||
|
|
4c5c2dfb6c | ||
|
|
517a7b2984 | ||
|
|
10bb596b7c | ||
|
|
6913f1e39b | ||
|
|
fe8e32586b | ||
|
|
e0c91ed2ee | ||
|
|
428433672c | ||
|
|
f71a2f7cd8 | ||
|
|
102b037c7d | ||
|
|
46c3839ea0 | ||
|
|
2c51c04708 | ||
|
|
d0a7a49c19 | ||
|
|
0024a4e654 | ||
|
|
d66a3f4ab3 | ||
|
|
645aa1d67b | ||
|
|
06db4af649 | ||
|
|
baf1ef32d1 | ||
|
|
d5638f8e53 | ||
|
|
c65b5b28b9 | ||
|
|
1301e16f6e | ||
|
|
caa382f41b | ||
|
|
24fd69a9be | ||
|
|
2389ec691b | ||
|
|
b8dd2ce2f4 | ||
|
|
5114cc4d6d | ||
|
|
57036c4470 | ||
|
|
81166432a8 | ||
|
|
5dc8502c8b | ||
|
|
67e10926db | ||
|
|
e971e210a3 | ||
|
|
f7e6169c23 | ||
|
|
6fc4e31dfb | ||
|
|
dfc22bdf00 | ||
|
|
54b5f47ffa | ||
|
|
62a4251f90 | ||
|
|
a41c12252a | ||
|
|
e7cf816062 | ||
|
|
ff28cadd57 | ||
|
|
9039b18b84 | ||
|
|
480381deb5 | ||
|
|
84dbace4af | ||
|
|
44f80f4c7c | ||
|
|
1cb9e52123 | ||
|
|
4d7ddb9c26 | ||
|
|
1b29d7eca3 | ||
|
|
5c779b11db | ||
|
|
dc344c07de | ||
|
|
b7b3c3ab32 | ||
|
|
6fa20284ec | ||
|
|
978b570826 | ||
|
|
688e393ed1 | ||
|
|
8ede868068 | ||
|
|
667d42eeb4 | ||
|
|
1f87d5a375 | ||
|
|
4f0a6cf9e1 | ||
|
|
3318858b80 | ||
|
|
9c6f19f55f | ||
|
|
48ee93c244 | ||
|
|
ee4197bcc0 | ||
|
|
079c476148 | ||
|
|
aa909b7635 | ||
|
|
9167ebda98 | ||
|
|
38682c69da | ||
|
|
2a7f41c494 | ||
|
|
071bbc7905 | ||
|
|
ca18f509e7 | ||
|
|
5e2bb1d57a | ||
|
|
dd2950e4ca | ||
|
|
34f3097616 |
No files matched your search
@@ -2,6 +2,7 @@ included:
|
||||
- GRDB
|
||||
|
||||
disabled_rules:
|
||||
- comment_spacing
|
||||
- cyclomatic_complexity
|
||||
- duplicate_enum_cases
|
||||
- file_length
|
||||
|
||||
@@ -28,122 +28,123 @@ jobs:
|
||||
include:
|
||||
|
||||
###########################################
|
||||
## Test GRDB Xcode 12
|
||||
## Test GRDB Xcode 12.2
|
||||
|
||||
- name: "Test GRDB Xcode 12 - GRDBOSX - Swift 5.3"
|
||||
- name: "Test GRDB Xcode 12.2 - GRDBOSX - Swift 5.3"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12
|
||||
osx_image: xcode12.2
|
||||
script: make test_framework_GRDBOSX_maxSwift
|
||||
|
||||
- name: "Test GRDB Xcode 12 - GRDBOSX - Swift 5.2"
|
||||
- name: "Test GRDB Xcode 12.2 - GRDBOSX - Swift 5.2"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12
|
||||
osx_image: xcode12.2
|
||||
script: make test_framework_GRDBOSX_minSwift
|
||||
|
||||
- name: "Test GRDB Xcode 12 - GRDBWatchOS"
|
||||
- name: "Test GRDB Xcode 12.2 - GRDBWatchOS"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12
|
||||
osx_image: xcode12.2
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
- name: "Test GRDB Xcode 12 - GRDBiOS iOS maxTarget"
|
||||
- name: "Test GRDB Xcode 12.2 - GRDBiOS iOS maxTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12
|
||||
osx_image: xcode12.2
|
||||
script: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
|
||||
- name: "Test GRDB Xcode 12 - GRDBiOS iOS minTarget"
|
||||
- name: "Test GRDB Xcode 12.2 - GRDBiOS iOS minTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12
|
||||
osx_image: xcode12.2
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
- name: "Test GRDB Xcode 12 - GRDBtvOS maxTarget"
|
||||
- name: "Test GRDB Xcode 12.2 - GRDBtvOS maxTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12
|
||||
osx_image: xcode12.2
|
||||
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
|
||||
|
||||
- name: "Test GRDB Xcode 12 - GRDBtvOS minTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12
|
||||
osx_image: xcode12.2
|
||||
script: make test_framework_GRDBtvOS_minTarget
|
||||
|
||||
- name: "Test GRDB Xcode 12 - SPM"
|
||||
- name: "Test GRDB Xcode 12.2 - SPM"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12
|
||||
osx_image: xcode12.2
|
||||
script: make test_SPM
|
||||
|
||||
###########################################
|
||||
## Test GRDBCustom Xcode 12
|
||||
## Test GRDBCustom Xcode 12.2
|
||||
|
||||
- name: "Test GRDBCustom Xcode 12 - GRDBOSX"
|
||||
- name: "Test GRDBCustom Xcode 12.2 - GRDBOSX"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12
|
||||
osx_image: xcode12.2
|
||||
script: make test_framework_GRDBCustomSQLiteOSX
|
||||
|
||||
- name: "Test GRDBCustom Xcode 12 - GRDBiOS maxTarget"
|
||||
- name: "Test GRDBCustom Xcode 12.2 - GRDBiOS maxTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12
|
||||
osx_image: xcode12.2
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
|
||||
|
||||
- name: "Test GRDBCustom Xcode 12 - GRDBiOS minTarget"
|
||||
- name: "Test GRDBCustom Xcode 12.2 - GRDBiOS minTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12
|
||||
osx_image: xcode12.2
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
|
||||
|
||||
###########################################
|
||||
## Test SQLCipher Xcode 12
|
||||
## Test SQLCipher Xcode 12.2
|
||||
|
||||
- name: "Test SQLCipher Xcode 12 - SQLCipher 3"
|
||||
- name: "Test SQLCipher Xcode 12.2 - SQLCipher 3"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12
|
||||
osx_image: xcode12.2
|
||||
script: make test_framework_SQLCipher3
|
||||
|
||||
- name: "Test SQLCipher Xcode 12 - SQLCipher 4"
|
||||
- name: "Test SQLCipher Xcode 12.2 - SQLCipher 4"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12
|
||||
osx_image: xcode12.2
|
||||
script: make test_framework_SQLCipher4
|
||||
|
||||
###########################################
|
||||
## Test Installation Xcode 12
|
||||
## Test Installation Xcode 12.2
|
||||
|
||||
# Manual Install
|
||||
- name: "Test Installation Xcode 12 - Manual Install"
|
||||
- name: "Test Installation Xcode 12.2 - Manual Install"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12
|
||||
osx_image: xcode12.2
|
||||
script: make test_install_manual
|
||||
|
||||
# CocoaPods Lint
|
||||
- name: "Test Installation Xcode 12 - CocoaPods Lint"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12
|
||||
script: make test_CocoaPodsLint_GRDB
|
||||
# Travis is much too slow, and always fail this job
|
||||
# # CocoaPods Lint
|
||||
# - name: "Test Installation Xcode 12.2 - CocoaPods Lint"
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode12.2
|
||||
# script: make test_CocoaPodsLint_GRDB
|
||||
|
||||
# CocoaPods Install GRDB
|
||||
- name: "Test Installation Xcode 12 - CocoaPods Framework"
|
||||
- name: "Test Installation Xcode 12.2 - CocoaPods Framework"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12
|
||||
osx_image: xcode12.2
|
||||
script: make test_install_GRDB_CocoaPods_framework
|
||||
|
||||
# CocoaPods Install GRDB
|
||||
- name: "Test Installation Xcode 12 - CocoaPods Static"
|
||||
- name: "Test Installation Xcode 12.2 - CocoaPods Static"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12
|
||||
osx_image: xcode12.2
|
||||
script: make test_install_GRDB_CocoaPods_static
|
||||
|
||||
# SPM Install
|
||||
- name: "Test Installation Xcode 12 - SPM Package"
|
||||
- name: "Test Installation Xcode 12.2 - SPM Package"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12
|
||||
osx_image: xcode12.2
|
||||
script: make test_install_SPM_Package
|
||||
|
||||
# SPM Install
|
||||
- name: "Test Installation Xcode 12 - SPM Package in Xcode Project"
|
||||
- name: "Test Installation Xcode 12.2 - SPM Package in Xcode Project"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12
|
||||
osx_image: xcode12.2
|
||||
script: make test_install_SPM_Project
|
||||
|
||||
# Custom SQLite Install
|
||||
- name: "Test Installation Xcode 12 - Custom SQLite"
|
||||
- name: "Test Installation Xcode 12.2 - Custom SQLite"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12
|
||||
osx_image: xcode12.2
|
||||
script: make test_install_customSQLite
|
||||
|
||||
###########################################
|
||||
|
||||
@@ -4,6 +4,12 @@ Here is a list of people who were happy to meet GRDB :-)
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/peres/status/1352219836508729346
|
||||
|
||||
> Just the occasional reminder that GRDB and its documentation is the gold standard. That's it.
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/steipete/status/1275305583718129664
|
||||
|
||||
> This is the future of Core Data
|
||||
|
||||
@@ -7,12 +7,12 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 5.x Releases
|
||||
|
||||
<!-- - [Next Release](#next-release) -->
|
||||
|
||||
- `5.0.x` Releases - [5.0.0](#500) | [5.0.1](#501) | [5.0.2](#502)
|
||||
- `5.3.x` Releases - [5.3.0](#530)
|
||||
- `5.2.x` Releases - [5.2.0](#520)
|
||||
- `5.1.x` Releases - [5.1.0](#510)
|
||||
- `5.0.x` Releases - [5.0.0](#500) | [5.0.1](#501) | [5.0.2](#502) | [5.0.3](#503)
|
||||
- `5.0.0` Betas - [5.0.0-beta](#500-beta) | [5.0.0-beta.2](#500-beta2) | [5.0.0-beta.3](#500-beta3) | [5.0.0-beta.4](#500-beta4) | [5.0.0-beta.5](#500-beta5) | [5.0.0-beta.6](#500-beta6) | [5.0.0-beta.7](#500-beta7) | [5.0.0-beta.8](#500-beta8) | [5.0.0-beta.9](#500-beta9) | [5.0.0-beta.10](#500-beta10) | [5.0.0-beta.11](#500-beta11)
|
||||
|
||||
|
||||
#### 4.x Releases
|
||||
|
||||
- `4.14.x` Releases - [4.14.0](#4140)
|
||||
@@ -69,6 +69,50 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
- [0.110.0](#01100), ...
|
||||
|
||||
|
||||
## 5.3.0
|
||||
|
||||
Released January 9, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.2.0...v5.3.0)
|
||||
|
||||
- **New**: [#880](https://github.com/groue/GRDB.swift/pull/880): Common Table Expressions
|
||||
- **New**: [#892](https://github.com/groue/GRDB.swift/pull/892) by [@eburns-vmware](https://github.com/eburns-vmware): Provide SQLCipher passphrase as Data
|
||||
- **Fixed**: [#881](https://github.com/groue/GRDB.swift/pull/881) by [@felixscheinost](https://github.com/felixscheinost) and [#883](https://github.com/groue/GRDB.swift/pull/883) by [@professordeng](https://github.com/professordeng): Documentation improvements
|
||||
- **Fixed**: [#885](https://github.com/groue/GRDB.swift/pull/885): Robustness of eager loading of to-many associations based on compound foreign keys
|
||||
- **Fixed**: [#901](https://github.com/groue/GRDB.swift/pull/901) by [@wuyuehyang](https://github.com/wuyuehyang): Fix creation of FTS5 tokenizer with arguments
|
||||
- **Fixed**: [#903](https://github.com/groue/GRDB.swift/pull/903) by [@chrisballinger](https://github.com/chrisballinger): Fix SPM installation instructions
|
||||
- **Documentation update**: A new guide: [Common Table Expressions](https://github.com/groue/GRDB.swift/blob/master/Documentation/CommonTableExpressions.md)
|
||||
- **Documentation update**: The [Foreign Keys](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md#foreign-keys) chapter of the Associations Guide clarifies the behavior of SQLite and GRDB regarding the presence of NULL if compound foreign keys.
|
||||
|
||||
|
||||
## 5.2.0
|
||||
|
||||
Released November 29, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v5.1.0...v5.2.0)
|
||||
|
||||
- **New**: [#868](https://github.com/groue/GRDB.swift/pull/868): ValueObservation optimization is opt-in.
|
||||
- **New**: [#872](https://github.com/groue/GRDB.swift/pull/872): Parse time zones
|
||||
- **Documentation update**: The [ValueObservation Performance](https://github.com/groue/GRDB.swift/blob/master/README.md#valueobservation-performance) chapter was extended with a tip for observations that track a constant database region.
|
||||
- **Documentation update**: The [Date and DateComponents](https://github.com/groue/GRDB.swift/blob/master/README.md#date-and-datecomponents) chapter describes the support for time zones.
|
||||
- **Documentation update**: A caveat ([#871](https://github.com/groue/GRDB.swift/issues/871)) with the `including(all:)` method, which may fail with a database error of code [`SQLITE_ERROR`](https://www.sqlite.org/rescode.html#error) (1) "Expression tree is too large" when you use a compound foreign key and there are a lot of parent records, is detailed in the [Joining And Prefetching Associated Records](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md#joining-and-prefetching-associated-records) chapter.
|
||||
|
||||
|
||||
## 5.1.0
|
||||
|
||||
Released November 1, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v5.0.3...v5.1.0)
|
||||
|
||||
- **New**: Clarifications on [ValueObservation that track a varying database region](https://github.com/groue/GRDB.swift/blob/master/README.md#observing-a-varying-database-region).
|
||||
- **New**: FAQ [Why is ValueObservation not publishing value changes?](https://github.com/groue/GRDB.swift/blob/master/README.md#why-is-valueobservation-not-publishing-value-changes)
|
||||
- **New**: [#855](https://github.com/groue/GRDB.swift/pull/855) by [@mallman](https://github.com/mallman): Support for generated columns with custom SQLite build, and upgrade custom SQLite builds to version 3.33.0
|
||||
- **New**: [#864](https://github.com/groue/GRDB.swift/pull/864): Prevent filter misuse with a deprecation warning
|
||||
|
||||
|
||||
## 5.0.3
|
||||
|
||||
Released October 25, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v5.0.2...v5.0.3)
|
||||
|
||||
- **Fixed**: [#859](https://github.com/groue/GRDB.swift/pull/859): Database.close() is idempotent
|
||||
- **Fixed**: [#850](https://github.com/groue/GRDB.swift/pull/850) by [@mtancock](https://github.com/mtancock): Add buildActiveScheme to playground settings so they'll build under Xcode 12
|
||||
- **Fixed**: [#849](https://github.com/groue/GRDB.swift/pull/849) by [@MarshalGeazipp](https://github.com/MarshalGeazipp): Fix grammar mistake AssociationsBasics.md
|
||||
|
||||
|
||||
## 5.0.2
|
||||
|
||||
Released October 6, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v5.0.1...v5.0.2)
|
||||
|
||||
@@ -11,6 +11,7 @@ GRDB Associations
|
||||
- [HasOneThrough]
|
||||
- [Choosing Between BelongsTo and HasOne]
|
||||
- [Self Joins]
|
||||
- [Associations to Common Table Expressions]
|
||||
- [Associations and the Database Schema]
|
||||
- [Convention for Database Table Names]
|
||||
- [Convention for the BelongsTo Association]
|
||||
@@ -116,7 +117,7 @@ Loading all books from an existing author is now easier:
|
||||
let books = try author.books.fetchAll(db)
|
||||
```
|
||||
|
||||
As for loading all pairs of books and authors, it is not only easier, but also *far much efficient*:
|
||||
As for loading all pairs of books and authors, it is not only easier, but also *much more efficient*:
|
||||
|
||||
```swift
|
||||
struct BookInfo: FetchableRecord, Decodable {
|
||||
@@ -191,18 +192,21 @@ Generally speaking, associations use the [TableRecord], [FetchableRecord], and [
|
||||
The Types of Associations
|
||||
=========================
|
||||
|
||||
GRDB handles five types of associations:
|
||||
GRDB handles several types of associations:
|
||||
|
||||
- **BelongsTo**
|
||||
- **HasMany**
|
||||
- **HasOne**
|
||||
- **HasManyThrough**
|
||||
- **HasOneThrough**
|
||||
- **Associations to common table expressions**
|
||||
|
||||
An association declares a link from a record type to another, as in "one book **belongs to** its author". It instructs GRDB to use the foreign keys declared in the database as support for Swift methods.
|
||||
An association generally declares a link from a record type to another, as in "one book **belongs to** its author". It instructs GRDB to use the foreign keys declared in the database as support for Swift methods.
|
||||
|
||||
Each one of these associations is appropriate for a particular database situation.
|
||||
|
||||
Associations to [common table expressions] are specific enough and are documented in [Associations to Common Table Expressions].
|
||||
|
||||
- [BelongsTo]
|
||||
- [HasMany]
|
||||
- [HasOne]
|
||||
@@ -693,7 +697,7 @@ See [Foreign Keys] for more information.
|
||||
|
||||
**Associations can automatically infer the foreign keys that define how two database tables are linked together.**
|
||||
|
||||
In the example below, the `book.authorId` column is automatically used to link a book to its author:
|
||||
In the example below, the `book.authorId` column is automatically used to link a book to its author, because the database schema defines a foreign key between the book and author database tables (see [Convention for the BelongsTo Association]).
|
||||
|
||||

|
||||
|
||||
@@ -707,7 +711,9 @@ struct Author: TableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
But this requires the database schema to define a foreign key between the book and author database tables (see [Convention for the BelongsTo Association]).
|
||||
> :point_up: **Note**: Generally speaking, all foreign keys are supported, including composite keys that span several columns.
|
||||
>
|
||||
> :warning: **Warning**: SQLite voids foreign key constraints when one or more of a foreign key column is NULL (see [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html)). GRDB does not match foreign keys that involve a NULL value either.
|
||||
|
||||
Sometimes the database schema does not define any foreign key. And sometimes, there are *several* foreign keys from a table to another.
|
||||
|
||||
@@ -2373,7 +2379,7 @@ See [Good Practices for Designing Record Types] for more information.
|
||||
.including(all: Country.passports
|
||||
.including(required: Passport.citizen))
|
||||
```
|
||||
|
||||
|
||||
Come [discuss](http://twitter.com/groue) for more information, or if you wish to help turning those missing features into reality.
|
||||
|
||||
---
|
||||
@@ -2476,3 +2482,5 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
[database observation tools]: ../README.md#database-changes-observation
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[FAQ]: ../README.md#faq-associations
|
||||
[common table expressions]: CommonTableExpressions.md
|
||||
[Associations to Common Table Expressions]: CommonTableExpressions.md#associations-to-common-table-expressions
|
||||
@@ -0,0 +1,423 @@
|
||||
Common Table Expressions
|
||||
========================
|
||||
|
||||
[**:fire: EXPERIMENTAL**](../README.md#what-are-experimental-features)
|
||||
|
||||
---
|
||||
|
||||
**Common table expressions** (CTEs) can generally be seen as *SQL views that you define on the fly*.
|
||||
|
||||
A certain level of familiarity with SQL databases is helpful before you dive into this guide. The starting point is obviously the [SQLite documentation](https://sqlite.org/lang_with.html). Many CTE tutorials exist online as well, including [this good one](https://blog.expensify.com/2015/09/25/the-simplest-sqlite-common-table-expression-tutorial/).
|
||||
|
||||
In this guide, you will learn how to:
|
||||
|
||||
- [Define Common Table Expressions]
|
||||
- [Embed Common Table Expressions in Requests]
|
||||
- [Fetch Values From Common Table Expressions]
|
||||
- Join CTEs with [Associations to Common Table Expressions]
|
||||
|
||||
> :point_up: **Note**: most code examples will be trivial, and not very "useful". This is because the goal of this guide is to stay focused on the GRDB support for CTEs. Rich setup would just be distracting. So bring your own good ideas with you!
|
||||
|
||||
|
||||
## Define Common Table Expressions
|
||||
|
||||
You will create a `CommonTableExpression` definition first. Choose a **name**, and a **request** that provides the content of the common table expression.
|
||||
|
||||
The CTE name is like a regular table name: pick one that does not conflict with the names of existing tables.
|
||||
|
||||
The CTE request can be provided as a [query interface request]:
|
||||
|
||||
```swift
|
||||
// WITH playerName AS (SELECT name FROM player) ...
|
||||
let playerNameCTE = CommonTableExpression<Void>(
|
||||
named: "playerName",
|
||||
request: Player.select(Column("name")))
|
||||
```
|
||||
|
||||
You can feed a CTE with raw SQL as well (second and third examples use [SQL Interpolation]):
|
||||
|
||||
```swift
|
||||
let name = "O'Brien"
|
||||
|
||||
// WITH playerName AS (SELECT 'O''Brien') ...
|
||||
let playerNameCTE = CommonTableExpression<Void>(
|
||||
named: "playerName",
|
||||
sql: "SELECT ?", arguments: [name])
|
||||
|
||||
// WITH playerName AS (SELECT 'O''Brien') ...
|
||||
let playerNameCTE = CommonTableExpression<Void>(
|
||||
named: "playerName",
|
||||
literal: "SELECT \(name)")
|
||||
|
||||
// WITH playerName AS (SELECT 'O''Brien') ...
|
||||
let request: SQLRequest<String> = "SELECT \(name)"
|
||||
let playerNameCTE = CommonTableExpression<Void>(
|
||||
named: "playerName",
|
||||
request: requests)
|
||||
```
|
||||
|
||||
All CTEs can be provided with explicit column names:
|
||||
|
||||
```swift
|
||||
// WITH pair(a, b) AS (SELECT 1, 2) ...
|
||||
let pairCTE = CommonTableExpression<Void>(
|
||||
named: "pair",
|
||||
columns: ["a", "b"],
|
||||
sql: "SELECT 1, 2")
|
||||
```
|
||||
|
||||
Recursive CTEs need the `recursive` flag. The example below selects all integers between 1 and 1000:
|
||||
|
||||
```swift
|
||||
// WITH RECURSIVE counter(x) AS
|
||||
// (VALUES(1) UNION ALL SELECT x+1 FROM counter WHERE x<1000)
|
||||
let counterCTE = CommonTableExpression<Int>(
|
||||
recursive: true,
|
||||
named: "counter",
|
||||
columns: ["x"],
|
||||
sql: """
|
||||
VALUES(1)
|
||||
UNION ALL
|
||||
SELECT x+1 FROM counter WHERE x<1000
|
||||
""")
|
||||
```
|
||||
|
||||
> :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
|
||||
|
||||
A typical SQLite query that uses a common table expression first *defines* the CTE and then *uses* the CTE by mentioning its table name. We'll see below Swift apis that match those two steps.
|
||||
|
||||
We will use the (simple) query below as a target. It is the query we'll want to generate in this chapter. It defines a CTE, and uses it in a subquery:
|
||||
|
||||
```sql
|
||||
WITH playerName AS (SELECT 'O''Brien')
|
||||
SELECT * FROM player
|
||||
WHERE name = (SELECT * FROM playerName)
|
||||
```
|
||||
|
||||
We first build a `CommonTableExpression`:
|
||||
|
||||
```swift
|
||||
let name = "O'Brien"
|
||||
let playerNameCTE = CommonTableExpression<Void>(
|
||||
named: "playerName",
|
||||
literal: "SELECT \(name)")
|
||||
```
|
||||
|
||||
We can then embed the definition of the CTE in a [query interface request] by calling the `with(_:)` method:
|
||||
|
||||
```swift
|
||||
// WITH playerName AS (SELECT 'O''Brien')
|
||||
// SELECT * FROM player ...
|
||||
let request = Player
|
||||
.with(playerNameCTE)...
|
||||
```
|
||||
|
||||
And we can then filter the `player` table with a subquery:
|
||||
|
||||
```swift
|
||||
// WITH playerName AS (SELECT 'O''Brien')
|
||||
// SELECT * FROM player
|
||||
// WHERE name = (SELECT * FROM playerName)
|
||||
let request = Player
|
||||
.with(playerNameCTE)
|
||||
.filter(Column("name") == playerNameCTE.all())
|
||||
```
|
||||
|
||||
> :point_up: **Note**: the `with(_:)` method can be called as many times as a there are common table expressions in your request.
|
||||
>
|
||||
> :point_up: **Note**: the `with(_:)` method can be called at any time, as all request methods: `Player.with(...).filter(...).with(...)`.
|
||||
>
|
||||
> :point_up: **Note**: the `with(_:)` method replaces any previously embedded CTE that has the same table name. This allows you to embed the same CTE several times if you feel like it.
|
||||
>
|
||||
> :point_up: **Note**: the `CommonTableExpression.all()` method builds a regular [query interface request] for the content of the CTE (like `SELECT * FROM <cte name>`, not to be mismatched with the request that was used to define the CTE). You can filter this request, sort it, etc, like all query interface requests:
|
||||
>
|
||||
> ```swift
|
||||
> cte.all().select(...).filter(...).group(...).order(...)
|
||||
> ```
|
||||
|
||||
Common table expressions can also be embedded in [SQLRequest] with [SQL Interpolation]:
|
||||
|
||||
```swift
|
||||
// WITH playerName AS (SELECT 'O''Brien')
|
||||
// SELECT * FROM player
|
||||
// WHERE name = (SELECT * FROM playerName)
|
||||
let request: SQLRequest<Player> = """
|
||||
WITH \(definitionFor: playerNameCTE)
|
||||
SELECT * FROM player
|
||||
WHERE name = (SELECT * FROM \(playerNameCTE))
|
||||
"""
|
||||
|
||||
// WITH playerName AS (SELECT 'O''Brien')
|
||||
// SELECT * FROM player
|
||||
// WHERE name = (SELECT * FROM playerName)
|
||||
let request: SQLRequest<Player> = """
|
||||
WITH \(definitionFor: playerNameCTE)
|
||||
SELECT * FROM player
|
||||
WHERE name = (\(playerNameCTE.all()))
|
||||
"""
|
||||
```
|
||||
|
||||
Common table expressions can also be used as subqueries, when you update or delete rows in the database:
|
||||
|
||||
```swift
|
||||
// WITH playerName AS (SELECT 'O''Brien')
|
||||
// UPDATE player SET name = (SELECT * FROM playerName)
|
||||
try Player
|
||||
.with(playerNameCTE)
|
||||
.updateAll(db, Column("name").set(to: playerNameCTE.all()))
|
||||
|
||||
// WITH playerName AS (SELECT 'O''Brien')
|
||||
// DELETE FROM player WHERE name = (SELECT * FROM playerName)
|
||||
try Player
|
||||
.with(playerNameCTE)
|
||||
.filter(Column("name") == playerNameCTE.all())
|
||||
.deleteAll(db)
|
||||
```
|
||||
|
||||
|
||||
## Fetch Values From Common Table Expressions
|
||||
|
||||
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.
|
||||
|
||||
This will generally give requests of the form `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:
|
||||
|
||||
```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]"
|
||||
```
|
||||
|
||||
When you have to fetch from a `CommonTableExpression` which does not have the desired generic type, you can still use the `asRequest(of:)` method:
|
||||
|
||||
```swift
|
||||
let cte: CommonTableExpression<Void> = ...
|
||||
let rows: [Row] = try dbQueue.read { db in
|
||||
try cte.all().with(cte)
|
||||
.asRequest(of: Row.self)
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Associations to Common Table Expressions
|
||||
|
||||
GRDB [associations] define "to-one" and "to-many" relationships between two database tables. Here we will define associations between regular tables and common table expressions.
|
||||
|
||||
We recommend familiarity with the "joining methods", described in [Joining And Prefetching Associated Records]:
|
||||
|
||||
```swift
|
||||
// SELECT parent.* FROM parent LEFT JOIN child ON ...
|
||||
Parent.joining(optional: childAssociation)
|
||||
|
||||
// SELECT parent.* FROM parent JOIN child ON ...
|
||||
Parent.joining(required: childAssociation)
|
||||
|
||||
// SELECT parent.*, child.* FROM parent LEFT JOIN child ON ...
|
||||
Parent.including(optional: childAssociation)
|
||||
|
||||
// SELECT parent.*, child.* FROM parent JOIN child ON ...
|
||||
Parent.including(required: childAssociation)
|
||||
```
|
||||
|
||||
> :point_up: **Note**: common table expressions currently only define "to-one" associations, so the `including(all:)` joining method is unavailable.
|
||||
|
||||
CTE associations are generally built with the `association(to:on:)` method, which needs:
|
||||
|
||||
- The two sides of the association: a `CommonTableExpression` instance, and another CTE or a type that conforms to the [TableRecord] protocol.
|
||||
- A function that returns the condition that joins the two sides of the association.
|
||||
|
||||
The condition function plays the same role as the **foreign key** that defines regular table [associations] such as **BelongsTo** or **HasMany**. It accepts two [TableAlias], from which you can build a joining expression:
|
||||
|
||||
For example:
|
||||
|
||||
```swift
|
||||
// An association from LeftRecord to rightCTE
|
||||
let rightCTE = ...
|
||||
let association = LeftRecord.association(
|
||||
to: rightCTE,
|
||||
on: { left, right in
|
||||
left[Column("x")] = right[Column("y")]
|
||||
})
|
||||
```
|
||||
|
||||
Now this association can be used with a joining method:
|
||||
|
||||
```swift
|
||||
// WITH rightCTE AS (...)
|
||||
// SELECT leftRecord.*, rightCTE.*
|
||||
// FROM leftRecord
|
||||
// JOIN rightCTE ON leftRecord.x = rightCTE.y
|
||||
LeftRecord
|
||||
.with(rightCTE)
|
||||
.including(required: association)
|
||||
```
|
||||
|
||||
|
||||
### CTE Association Example: a Chat App
|
||||
|
||||
As an example, let's build the classical main screen of a chat application: a list of all latest messages from all conversations.
|
||||
|
||||
The database schema of the chat app contains a `chat` and a `message` table. The application defines the following records:
|
||||
|
||||
```swift
|
||||
struct Chat: Codable, FetchableRecord, PersistableRecord {
|
||||
var id: Int64
|
||||
...
|
||||
}
|
||||
|
||||
struct Message: Codable, FetchableRecord, PersistableRecord {
|
||||
var chatID: Int64
|
||||
var date: Date
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
To feed the main app screen, we want to fetch a list of `ChatInfo` records:
|
||||
|
||||
```swift
|
||||
struct ChatInfo: Decodable, FetchableRecord {
|
||||
/// The chat
|
||||
var chat: Chat
|
||||
|
||||
/// The latest chat message, if any
|
||||
var latestMessage: Message?
|
||||
}
|
||||
```
|
||||
|
||||
The SQL request that we want to run is below. It uses an SQLite-specific [special processing](https://sqlite.org/lang_select.html) of `MAX()` that helps the selection of latest messages from all chats:
|
||||
|
||||
```sql
|
||||
WITH latestMessage AS
|
||||
(SELECT *, MAX(date) FROM message GROUP BY chatID)
|
||||
SELECT chat.*, latestMessage.*
|
||||
FROM chat
|
||||
LEFT JOIN latestMessage ON chat.id = latestMessage.chatID
|
||||
ORDER BY latestMessage.date DESC
|
||||
```
|
||||
|
||||
We start by defining the CTE request, which loads the latest messages of all chats:
|
||||
|
||||
```swift
|
||||
// SELECT *, MAX(date) FROM message GROUP BY chatID
|
||||
let latestMessageRequest = Message
|
||||
.annotated(with: max(Column("date")))
|
||||
.group(Column("chatID"))
|
||||
```
|
||||
|
||||
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>(
|
||||
named: "latestMessage",
|
||||
request: latestMessageRequest)
|
||||
```
|
||||
|
||||
The association from a chat to its latest message follows:
|
||||
|
||||
```swift
|
||||
|
||||
// ... JOIN latestMessage ON chat.id = latestMessage.chatID
|
||||
let latestMessage = Chat.association(
|
||||
to: latestMessageCTE,
|
||||
on: { chat, latestMessage in
|
||||
chat[Column("id")] == latestMessage[Column("chatID")]
|
||||
})
|
||||
.order(Column("date").desc)
|
||||
```
|
||||
|
||||
The final request can now be defined:
|
||||
|
||||
```swift
|
||||
|
||||
// WITH latestMessage AS
|
||||
// (SELECT *, MAX(date) FROM message GROUP BY chatID)
|
||||
// SELECT chat.*, latestMessage.*
|
||||
// FROM chat
|
||||
// LEFT JOIN latestMessage ON chat.id = latestMessage.chatID
|
||||
// ORDER BY latestMessage.date DESC
|
||||
let request = Chat
|
||||
.with(latestMessageCTE)
|
||||
.including(optional: latestMessage)
|
||||
.asRequest(of: ChatInfo.self)
|
||||
```
|
||||
|
||||
And we can fetch the data that feeds our application screen:
|
||||
|
||||
```swift
|
||||
|
||||
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`.
|
||||
>
|
||||
> You can use an existing record type, or an ad-hoc enum. For example:
|
||||
>
|
||||
> ```swift
|
||||
> enum CTE1 { }
|
||||
> let cte1 = CommonTableExpression<CTE1>(...)
|
||||
>
|
||||
> 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: ...)
|
||||
>
|
||||
> // WITH ...
|
||||
> // SELECT base.* FROM base
|
||||
> // JOIN cte1 ON ...
|
||||
> // JOIN cte2 ON ...
|
||||
> // JOIN far ON ...
|
||||
> let request = BaseRecord
|
||||
> .with(cte1).with(cte2)
|
||||
> .joining(required: assoc1
|
||||
> .joining(required: assoc2
|
||||
> .joining(required: assoc3)))
|
||||
>
|
||||
> // Compiler error
|
||||
> let request = BaseRecord.joining(required: assoc2)
|
||||
> ```
|
||||
|
||||
[query interface request]: ../README.md#requests
|
||||
[query interface requests]: ../README.md#requests
|
||||
[SQLRequest]: ../README.md#custom-requests
|
||||
[SQLiteral]: SQLInterpolation.md
|
||||
[SQL Interpolation]: SQLInterpolation.md
|
||||
[associations]: AssociationsBasics.md
|
||||
[Joining And Prefetching Associated Records]: AssociationsBasics.md#joining-and-prefetching-associated-records
|
||||
[Define Common Table Expressions]: #define-common-table-expressions
|
||||
[Embed Common Table Expressions in Requests]: #embed-common-table-expressions-in-requests
|
||||
[Fetch Values From Common Table Expressions]: #fetch-values-from-common-table-expressions
|
||||
[Associations to Common Table Expressions]: #associations-to-common-table-expressions
|
||||
[TableRecord]: ../README.md#tablerecord-protocol
|
||||
[TableAlias]: AssociationsBasics.md#table-aliases
|
||||
@@ -3,7 +3,7 @@ Custom SQLite Builds
|
||||
|
||||
By default, GRDB uses the version of SQLite that ships with the target operating system.
|
||||
|
||||
**You can build GRDB with a custom build of [SQLite 3.28.0](https://www.sqlite.org/changes.html).**
|
||||
**You can build GRDB with a custom build of [SQLite 3.33.0](https://www.sqlite.org/changes.html).**
|
||||
|
||||
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](../../../#support-for-sqlite-pre-update-hooks).
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
objects = {
|
||||
|
||||
/* 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 */; };
|
||||
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 */; };
|
||||
@@ -26,6 +28,13 @@
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
56026C9D25B8A7D000D1DF3F /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 567C3E0E2520B6DE0011F6E9 /* Project object */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 567C3E152520B6DE0011F6E9;
|
||||
remoteInfo = GRDBCombineDemo;
|
||||
};
|
||||
567C3E342520B7000011F6E9 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */;
|
||||
@@ -106,6 +115,10 @@
|
||||
/* End PBXCopyFilesBuildPhase section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
56026C9825B8A7D000D1DF3F /* GRDBCombineDemoTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCombineDemoTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
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>"; };
|
||||
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>"; };
|
||||
@@ -126,6 +139,13 @@
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
56026C9525B8A7D000D1DF3F /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
567C3E132520B6DE0011F6E9 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
@@ -137,11 +157,40 @@
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
56026C9925B8A7D000D1DF3F /* GRDBCombineDemoTests */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56026C9C25B8A7D000D1DF3F /* Info.plist */,
|
||||
56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */,
|
||||
56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */,
|
||||
);
|
||||
path = GRDBCombineDemoTests;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56185BC125B8047D00B9C30F /* Resources */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */,
|
||||
567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */,
|
||||
567C3E752520BB650011F6E9 /* Localizable.stringsdict */,
|
||||
);
|
||||
path = Resources;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56185BC225B8048B00B9C30F /* Support */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567C3E222520B6DF0011F6E9 /* Info.plist */,
|
||||
);
|
||||
name = Support;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
567C3E0D2520B6DE0011F6E9 = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567C3E292520B7000011F6E9 /* GRDB.xcodeproj */,
|
||||
567C3E182520B6DE0011F6E9 /* GRDBCombineDemo */,
|
||||
56026C9925B8A7D000D1DF3F /* GRDBCombineDemoTests */,
|
||||
567C3E172520B6DE0011F6E9 /* Products */,
|
||||
567C3E4D2520B70E0011F6E9 /* Frameworks */,
|
||||
);
|
||||
@@ -151,6 +200,7 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */,
|
||||
56026C9825B8A7D000D1DF3F /* GRDBCombineDemoTests.xctest */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
@@ -158,17 +208,15 @@
|
||||
567C3E182520B6DE0011F6E9 /* GRDBCombineDemo */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */,
|
||||
567C3E652520B7880011F6E9 /* AppDatabase.swift */,
|
||||
567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */,
|
||||
567C3E542520B75C0011F6E9 /* Persistence.swift */,
|
||||
567C3E532520B75C0011F6E9 /* Player.swift */,
|
||||
567C3E1F2520B6DF0011F6E9 /* Preview Content */,
|
||||
56185BC125B8047D00B9C30F /* Resources */,
|
||||
56185BC225B8048B00B9C30F /* Support */,
|
||||
567C3E552520B75C0011F6E9 /* ViewModels */,
|
||||
567C3E582520B75C0011F6E9 /* Views */,
|
||||
567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */,
|
||||
567C3E752520BB650011F6E9 /* Localizable.stringsdict */,
|
||||
567C3E222520B6DF0011F6E9 /* Info.plist */,
|
||||
567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */,
|
||||
567C3E1F2520B6DF0011F6E9 /* Preview Content */,
|
||||
);
|
||||
path = GRDBCombineDemo;
|
||||
sourceTree = "<group>";
|
||||
@@ -226,6 +274,24 @@
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
56026C9725B8A7D000D1DF3F /* GRDBCombineDemoTests */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 56026CA825B8A7D000D1DF3F /* Build configuration list for PBXNativeTarget "GRDBCombineDemoTests" */;
|
||||
buildPhases = (
|
||||
56026C9425B8A7D000D1DF3F /* Sources */,
|
||||
56026C9525B8A7D000D1DF3F /* Frameworks */,
|
||||
56026C9625B8A7D000D1DF3F /* Resources */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
56026C9E25B8A7D000D1DF3F /* PBXTargetDependency */,
|
||||
);
|
||||
name = GRDBCombineDemoTests;
|
||||
productName = GRDBCombineDemoTests;
|
||||
productReference = 56026C9825B8A7D000D1DF3F /* GRDBCombineDemoTests.xctest */;
|
||||
productType = "com.apple.product-type.bundle.unit-test";
|
||||
};
|
||||
567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 567C3E252520B6DF0011F6E9 /* Build configuration list for PBXNativeTarget "GRDBCombineDemo" */;
|
||||
@@ -251,9 +317,13 @@
|
||||
567C3E0E2520B6DE0011F6E9 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastSwiftUpdateCheck = 1200;
|
||||
LastSwiftUpdateCheck = 1230;
|
||||
LastUpgradeCheck = 1200;
|
||||
TargetAttributes = {
|
||||
56026C9725B8A7D000D1DF3F = {
|
||||
CreatedOnToolsVersion = 12.3;
|
||||
TestTargetID = 567C3E152520B6DE0011F6E9;
|
||||
};
|
||||
567C3E152520B6DE0011F6E9 = {
|
||||
CreatedOnToolsVersion = 12.0;
|
||||
};
|
||||
@@ -279,6 +349,7 @@
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */,
|
||||
56026C9725B8A7D000D1DF3F /* GRDBCombineDemoTests */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
@@ -343,6 +414,13 @@
|
||||
/* End PBXReferenceProxy section */
|
||||
|
||||
/* Begin PBXResourcesBuildPhase section */
|
||||
56026C9625B8A7D000D1DF3F /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
567C3E142520B6DE0011F6E9 /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
@@ -357,6 +435,15 @@
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
56026C9425B8A7D000D1DF3F /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
56026CAC25B8A7EF00D1DF3F /* PlayerTests.swift in Sources */,
|
||||
56026CAD25B8A7EF00D1DF3F /* AppDatabaseTests.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
567C3E122520B6DE0011F6E9 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
@@ -377,6 +464,11 @@
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXTargetDependency section */
|
||||
56026C9E25B8A7D000D1DF3F /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
target = 567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */;
|
||||
targetProxy = 56026C9D25B8A7D000D1DF3F /* PBXContainerItemProxy */;
|
||||
};
|
||||
567C3E522520B71C0011F6E9 /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = GRDBiOS;
|
||||
@@ -404,6 +496,46 @@
|
||||
/* End PBXVariantGroup section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
56026C9F25B8A7D000D1DF3F /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
INFOPLIST_FILE = GRDBCombineDemoTests/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 14.3;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCombineDemoTests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBCombineDemo.app/GRDBCombineDemo";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
56026CA025B8A7D000D1DF3F /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
INFOPLIST_FILE = GRDBCombineDemoTests/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 14.3;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCombineDemoTests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBCombineDemo.app/GRDBCombineDemo";
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
567C3E232520B6DF0011F6E9 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
@@ -567,6 +699,15 @@
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
56026CA825B8A7D000D1DF3F /* Build configuration list for PBXNativeTarget "GRDBCombineDemoTests" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
56026C9F25B8A7D000D1DF3F /* Debug */,
|
||||
56026CA025B8A7D000D1DF3F /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBCombineDemo" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1230"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "567C3E152520B6DE0011F6E9"
|
||||
BuildableName = "GRDBCombineDemo.app"
|
||||
BlueprintName = "GRDBCombineDemo"
|
||||
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56026C9725B8A7D000D1DF3F"
|
||||
BuildableName = "GRDBCombineDemoTests.xctest"
|
||||
BlueprintName = "GRDBCombineDemoTests"
|
||||
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "567C3E152520B6DE0011F6E9"
|
||||
BuildableName = "GRDBCombineDemo.app"
|
||||
BlueprintName = "GRDBCombineDemo"
|
||||
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "567C3E152520B6DE0011F6E9"
|
||||
BuildableName = "GRDBCombineDemo.app"
|
||||
BlueprintName = "GRDBCombineDemo"
|
||||
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -6,14 +6,20 @@ import GRDB
|
||||
/// It applies the pratices recommended at
|
||||
/// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
|
||||
struct AppDatabase {
|
||||
private let dbWriter: DatabaseWriter
|
||||
|
||||
/// Creates an AppDatabase and make sure the database schema is ready.
|
||||
/// Creates an `AppDatabase`, and make sure the database schema is ready.
|
||||
init(_ dbWriter: DatabaseWriter) throws {
|
||||
self.dbWriter = dbWriter
|
||||
try migrator.migrate(dbWriter)
|
||||
}
|
||||
|
||||
/// Provides access to the database.
|
||||
///
|
||||
/// Application can use a `DatabasePool`, while SwiftUI previews and tests
|
||||
/// can use a fast in-memory `DatabaseQueue`.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
private let dbWriter: DatabaseWriter
|
||||
|
||||
/// The DatabaseMigrator that defines the database schema.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md
|
||||
@@ -32,9 +38,6 @@ struct AppDatabase {
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
// Sort player names in a localized case insensitive fashion by default
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#unicode
|
||||
.collate(.localizedCaseInsensitiveCompare)
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
}
|
||||
@@ -48,14 +51,11 @@ struct AppDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Database Access
|
||||
//
|
||||
// This extension defines methods that fulfill application needs, both in terms
|
||||
// of writes and reads.
|
||||
// MARK: - Database Access: Writes
|
||||
|
||||
extension AppDatabase {
|
||||
// MARK: Writes
|
||||
|
||||
/// Save (insert or update) a player.
|
||||
/// 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)
|
||||
@@ -80,7 +80,7 @@ extension AppDatabase {
|
||||
func refreshPlayers() throws {
|
||||
try dbWriter.write { db in
|
||||
if try Player.fetchCount(db) == 0 {
|
||||
// Insert new random players
|
||||
// When database is empty, insert new random players
|
||||
try createRandomPlayers(db)
|
||||
} else {
|
||||
// Insert a player
|
||||
@@ -88,10 +88,12 @@ extension AppDatabase {
|
||||
var player = Player.newRandom()
|
||||
try player.insert(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) {
|
||||
@@ -118,14 +120,16 @@ extension AppDatabase {
|
||||
try player.insert(db)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Reads
|
||||
|
||||
}
|
||||
|
||||
// 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)
|
||||
.publisher(in: dbWriter, scheduling: .immediate)
|
||||
.eraseToAnyPublisher()
|
||||
}
|
||||
|
||||
@@ -133,7 +137,7 @@ extension AppDatabase {
|
||||
func playersOrderedByScorePublisher() -> AnyPublisher<[Player], Error> {
|
||||
ValueObservation
|
||||
.tracking(Player.all().orderedByScore().fetchAll)
|
||||
.publisher(in: dbWriter)
|
||||
.publisher(in: dbWriter, scheduling: .immediate)
|
||||
.eraseToAnyPublisher()
|
||||
}
|
||||
}
|
||||
@@ -6,12 +6,21 @@ extension AppDatabase {
|
||||
|
||||
private static func makeShared() -> AppDatabase {
|
||||
do {
|
||||
// Create a folder for storing the SQLite database, as well as
|
||||
// the various temporary files created during normal database
|
||||
// operations (https://sqlite.org/tempfiles.html).
|
||||
let fileManager = FileManager()
|
||||
let folderURL = try fileManager
|
||||
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
.appendingPathComponent("database", isDirectory: true)
|
||||
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
|
||||
|
||||
// Connect to a database on disk
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
let url: URL = try FileManager.default
|
||||
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
.appendingPathComponent("db.sqlite")
|
||||
let dbPool = try DatabasePool(path: url.path)
|
||||
let dbURL = folderURL.appendingPathComponent("db.sqlite")
|
||||
let dbPool = try DatabasePool(path: dbURL.path)
|
||||
|
||||
// Create the AppDatabase
|
||||
let appDatabase = try AppDatabase(dbPool)
|
||||
|
||||
// Populate the database if it is empty, for better demo purpose.
|
||||
|
||||
@@ -2,8 +2,9 @@ import GRDB
|
||||
|
||||
/// The Player struct.
|
||||
///
|
||||
/// Identifiable conformance supports SwiftUI list animations
|
||||
struct Player: Identifiable {
|
||||
/// Identifiable conformance supports SwiftUI list animations.
|
||||
/// Equatable conformance supports tests.
|
||||
struct Player: Identifiable, Equatable {
|
||||
/// The player id.
|
||||
///
|
||||
/// Int64 is the recommended type for auto-incremented database ids.
|
||||
@@ -70,25 +71,35 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
|
||||
extension DerivableRequest where RowDecoder == Player {
|
||||
/// A request of players ordered by name
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let players = try dbQueue.read { db in
|
||||
/// let players: [Player] = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByName().fetchAll(db)
|
||||
/// }
|
||||
func orderedByName() -> Self {
|
||||
order(Player.Columns.name)
|
||||
// Sort by name in a localized case insensitive fashion
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
|
||||
order(Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
|
||||
/// A request of players ordered by score
|
||||
/// A request of players ordered by score.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let players = try dbQueue.read { db in
|
||||
/// let players: [Player] = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByScore().fetchAll(db)
|
||||
/// }
|
||||
/// let bestPlayer: Player? = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByScore().fetchOne(db)
|
||||
/// }
|
||||
func orderedByScore() -> Self {
|
||||
order(Player.Columns.score.desc, Player.Columns.name)
|
||||
// Sort by descending score, and then by name, in a
|
||||
// localized case insensitive fashion
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
|
||||
order(
|
||||
Player.Columns.score.desc,
|
||||
Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 329 KiB After Width: | Height: | Size: 329 KiB |
|
Before Width: | Height: | Size: 1.2 KiB After Width: | Height: | Size: 1.2 KiB |
|
Before Width: | Height: | Size: 2.6 KiB After Width: | Height: | Size: 2.6 KiB |
|
Before Width: | Height: | Size: 2.6 KiB After Width: | Height: | Size: 2.6 KiB |
|
Before Width: | Height: | Size: 4.7 KiB After Width: | Height: | Size: 4.7 KiB |
|
Before Width: | Height: | Size: 1.8 KiB After Width: | Height: | Size: 1.8 KiB |
|
Before Width: | Height: | Size: 4.5 KiB After Width: | Height: | Size: 4.5 KiB |
|
Before Width: | Height: | Size: 4.5 KiB After Width: | Height: | Size: 4.5 KiB |
|
Before Width: | Height: | Size: 7.8 KiB After Width: | Height: | Size: 7.8 KiB |
|
Before Width: | Height: | Size: 2.6 KiB After Width: | Height: | Size: 2.6 KiB |
|
Before Width: | Height: | Size: 6.9 KiB After Width: | Height: | Size: 6.9 KiB |
|
Before Width: | Height: | Size: 6.9 KiB After Width: | Height: | Size: 6.9 KiB |
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 23 KiB After Width: | Height: | Size: 23 KiB |
|
Before Width: | Height: | Size: 6.5 KiB After Width: | Height: | Size: 6.5 KiB |
|
Before Width: | Height: | Size: 18 KiB After Width: | Height: | Size: 18 KiB |
|
Before Width: | Height: | Size: 20 KiB After Width: | Height: | Size: 20 KiB |
@@ -0,0 +1,254 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
@testable import GRDBCombineDemo
|
||||
|
||||
class AppDatabaseTests: XCTestCase {
|
||||
func test_database_schema() throws {
|
||||
// Given an empty database
|
||||
let dbQueue = DatabaseQueue()
|
||||
|
||||
// When we instantiate an AppDatabase
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// Then the player table exists, with id, name & score columns
|
||||
try dbQueue.read { db in
|
||||
try XCTAssert(db.tableExists("player"))
|
||||
let columns = try db.columns(in: "player")
|
||||
let columnNames = Set(columns.map { $0.name })
|
||||
XCTAssertEqual(columnNames, ["id", "name", "score"])
|
||||
}
|
||||
}
|
||||
|
||||
func test_savePlayer_inserts() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we save a new player
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try appDatabase.savePlayer(&player)
|
||||
|
||||
// Then the player exists in the database
|
||||
try XCTAssertTrue(dbQueue.read(player.exists))
|
||||
}
|
||||
|
||||
func test_savePlayer_updates() throws {
|
||||
// Given a players database that contains a 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 modify and save the player
|
||||
player.name = "Barbara"
|
||||
player.score = 1000
|
||||
try appDatabase.savePlayer(&player)
|
||||
|
||||
// Then the player has been updated in the database
|
||||
let fetchedPlayer = try dbQueue.read { db in
|
||||
try XCTUnwrap(Player.fetchOne(db, key: player.id))
|
||||
}
|
||||
XCTAssertEqual(fetchedPlayer, player)
|
||||
}
|
||||
|
||||
func test_deletePlayers() throws {
|
||||
// Given a players database that contains four 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: 200)
|
||||
var player3 = Player(id: nil, name: "Craig", score: 150)
|
||||
var player4 = Player(id: nil, name: "David", score: 120)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
try player3.insert(db)
|
||||
try player4.insert(db)
|
||||
}
|
||||
|
||||
// When we delete two players
|
||||
try appDatabase.deletePlayers(ids: [player1.id!, player3.id!])
|
||||
|
||||
// Then the deleted players no longer exist
|
||||
try dbQueue.read { db in
|
||||
try XCTAssertFalse(player1.exists(db))
|
||||
try XCTAssertFalse(player3.exists(db))
|
||||
}
|
||||
|
||||
// Then the database still contains two players
|
||||
try XCTAssertEqual(dbQueue.read(Player.fetchCount), 2)
|
||||
}
|
||||
|
||||
func test_deleteAllPlayers() throws {
|
||||
// Given a players database that contains 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: 200)
|
||||
var player3 = Player(id: nil, name: "Craig", score: 150)
|
||||
var player4 = Player(id: nil, name: "David", score: 120)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
try player3.insert(db)
|
||||
try player4.insert(db)
|
||||
}
|
||||
|
||||
// When we delete all players
|
||||
try appDatabase.deleteAllPlayers()
|
||||
|
||||
// Then the database does not contain any player
|
||||
try XCTAssertEqual(dbQueue.read(Player.fetchCount), 0)
|
||||
}
|
||||
|
||||
func test_refreshPlayers_populates_an_empty_database() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we refresh players
|
||||
try appDatabase.refreshPlayers()
|
||||
|
||||
// Then the database is not empty
|
||||
try XCTAssert(dbQueue.read(Player.fetchCount) > 0)
|
||||
}
|
||||
|
||||
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we create random players
|
||||
try appDatabase.createRandomPlayersIfEmpty()
|
||||
|
||||
// Then the database is not empty
|
||||
try XCTAssert(dbQueue.read(Player.fetchCount) > 0)
|
||||
}
|
||||
|
||||
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() 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 create random players
|
||||
try appDatabase.createRandomPlayersIfEmpty()
|
||||
|
||||
// Then the database still only contains the original player
|
||||
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,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>
|
||||
@@ -0,0 +1,108 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
@testable import GRDBCombineDemo
|
||||
|
||||
class PlayerTests: XCTestCase {
|
||||
// MARK: - CRUD
|
||||
// Test that our Player type properly talks to GRDB.
|
||||
|
||||
func testInsert() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try dbQueue.write { db in
|
||||
try player.insert(db)
|
||||
}
|
||||
|
||||
// Then the player gets a non-nil id
|
||||
XCTAssertNotNil(player.id)
|
||||
}
|
||||
|
||||
func testRoundtrip() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player and fetch the player with the same id
|
||||
var insertedPlayer = Player(id: nil, name: "Arthur", score: 100)
|
||||
let fetchedPlayer: Player? = try dbQueue.write { db in
|
||||
try insertedPlayer.insert(db)
|
||||
return try Player.fetchOne(db, key: insertedPlayer.id)
|
||||
}
|
||||
|
||||
// Then the fetched player is equal to the inserted player
|
||||
XCTAssertEqual(insertedPlayer, fetchedPlayer)
|
||||
}
|
||||
|
||||
// MARK: - Requests
|
||||
// Test that requests defined on the Player type behave as expected.
|
||||
|
||||
func testOrderedByScore() throws {
|
||||
// Given a players database that contains players with distinct scores
|
||||
let dbQueue = DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
var player3 = Player(id: 3, name: "Craig", score: 150)
|
||||
var player4 = Player(id: 4, name: "David", score: 120)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
try player3.insert(db)
|
||||
try player4.insert(db)
|
||||
}
|
||||
|
||||
// When we fetch players ordered by score
|
||||
let players = try dbQueue.read(Player.all().orderedByScore().fetchAll)
|
||||
|
||||
// Then fetched players are ordered by score descending
|
||||
XCTAssertEqual(players, [player2, player3, player4, player1])
|
||||
}
|
||||
|
||||
func testOrderedByScoreSortsIdenticalScoresByName() throws {
|
||||
// Given a players database that contains players with common scores
|
||||
let dbQueue = DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
var player3 = Player(id: 3, name: "Craig", score: 200)
|
||||
var player4 = Player(id: 4, name: "David", score: 200)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
try player3.insert(db)
|
||||
try player4.insert(db)
|
||||
}
|
||||
|
||||
// When we fetch players ordered by score
|
||||
let players = try dbQueue.read(Player.all().orderedByScore().fetchAll)
|
||||
|
||||
// Then fetched players are ordered by score descending and by name
|
||||
XCTAssertEqual(players, [player2, player3, player4, player1])
|
||||
}
|
||||
|
||||
func testOrderedByName() throws {
|
||||
// Given a players database that contains players with distinct names
|
||||
let dbQueue = DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
var player3 = Player(id: 3, name: "Craig", score: 150)
|
||||
var player4 = Player(id: 4, name: "David", score: 120)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
try player3.insert(db)
|
||||
try player4.insert(db)
|
||||
}
|
||||
|
||||
// When we fetch players ordered by name
|
||||
let players = try dbQueue.read(Player.all().orderedByName().fetchAll)
|
||||
|
||||
// Then fetched players are ordered by name
|
||||
XCTAssertEqual(players, [player1, player2, player3, player4])
|
||||
}
|
||||
}
|
||||
@@ -40,3 +40,9 @@ The topics covered in this demo are:
|
||||
- [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).
|
||||
|
||||
`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`.
|
||||
|
||||
- [GRDBCombineDemoTests](GRDBCombineDemoTests)
|
||||
|
||||
- Test the database schema
|
||||
- Test the `Player` record and its requests
|
||||
- Test the `AppDatabase` methods that let the app access the database.
|
||||
@@ -25,7 +25,7 @@
|
||||
<key>NSExtensionAttributes</key>
|
||||
<dict>
|
||||
<key>WKAppBundleIdentifier</key>
|
||||
<string>com.github.groue.GRDBDemoiOS2.watchkitapp</string>
|
||||
<string>com.github.groue.GRDBDemoiOS.watchkitapp</string>
|
||||
</dict>
|
||||
<key>NSExtensionPointIdentifier</key>
|
||||
<string>com.apple.watchkit</string>
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
<string>UIInterfaceOrientationPortraitUpsideDown</string>
|
||||
</array>
|
||||
<key>WKCompanionAppBundleIdentifier</key>
|
||||
<string>com.github.groue.GRDBDemoiOS2</string>
|
||||
<string>com.github.groue.GRDBDemoiOS</string>
|
||||
<key>WKWatchKitApp</key>
|
||||
<true/>
|
||||
</dict>
|
||||
|
||||
@@ -7,6 +7,9 @@
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
56185BBF25B8036100B9C30F /* Persistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56185BBE25B8036100B9C30F /* Persistence.swift */; };
|
||||
56185BF325B80B8900B9C30F /* AppDatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56185BF225B80B8900B9C30F /* AppDatabaseTests.swift */; };
|
||||
56185C0725B80CEC00B9C30F /* PlayerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56185C0625B80CEC00B9C30F /* PlayerTests.swift */; };
|
||||
56606D202355938A00185962 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D142355931F00185962 /* GRDB.framework */; };
|
||||
56606D212355938A00185962 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D142355931F00185962 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
|
||||
56606D24235593AB00185962 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D182355931F00185962 /* GRDB.framework */; };
|
||||
@@ -30,6 +33,13 @@
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
56185BF525B80B8900B9C30F /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B035FB1E8D9EBE003B6DA4 /* Project object */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 56B036021E8D9EBE003B6DA4;
|
||||
remoteInfo = GRDBDemoiOS;
|
||||
};
|
||||
56606D092355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
@@ -164,6 +174,11 @@
|
||||
/* End PBXCopyFilesBuildPhase section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
56185BBE25B8036100B9C30F /* Persistence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Persistence.swift; sourceTree = "<group>"; };
|
||||
56185BF025B80B8900B9C30F /* GRDBDemoiOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBDemoiOSTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
56185BF225B80B8900B9C30F /* AppDatabaseTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDatabaseTests.swift; sourceTree = "<group>"; };
|
||||
56185BF425B80B8900B9C30F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
56185C0625B80CEC00B9C30F /* PlayerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerTests.swift; sourceTree = "<group>"; };
|
||||
568E5FBF1E926430002582E0 /* GRDBDemoWatchOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBDemoWatchOS.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
568E5FC21E926430002582E0 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Interface.storyboard; sourceTree = "<group>"; };
|
||||
568E5FC41E926430002582E0 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
|
||||
@@ -188,6 +203,13 @@
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
56185BED25B80B8900B9C30F /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
568E5FC81E926430002582E0 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
@@ -207,6 +229,16 @@
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
56185BF125B80B8900B9C30F /* GRDBDemoiOSTests */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56185BF425B80B8900B9C30F /* Info.plist */,
|
||||
56185BF225B80B8900B9C30F /* AppDatabaseTests.swift */,
|
||||
56185C0625B80CEC00B9C30F /* PlayerTests.swift */,
|
||||
);
|
||||
path = GRDBDemoiOSTests;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56606CFD2355931F00185962 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -257,6 +289,7 @@
|
||||
56B036051E8D9EBE003B6DA4 /* GRDBDemoiOS */,
|
||||
568E5FC01E926430002582E0 /* GRDBDemoWatchOS */,
|
||||
568E5FCF1E926430002582E0 /* GRDBDemoWatchOS Extension */,
|
||||
56185BF125B80B8900B9C30F /* GRDBDemoiOSTests */,
|
||||
56B036041E8D9EBE003B6DA4 /* Products */,
|
||||
56606D1F2355938A00185962 /* Frameworks */,
|
||||
);
|
||||
@@ -268,6 +301,7 @@
|
||||
56B036031E8D9EBE003B6DA4 /* GRDBDemoiOS.app */,
|
||||
568E5FBF1E926430002582E0 /* GRDBDemoWatchOS.app */,
|
||||
568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */,
|
||||
56185BF025B80B8900B9C30F /* GRDBDemoiOSTests.xctest */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
@@ -275,13 +309,14 @@
|
||||
56B036051E8D9EBE003B6DA4 /* GRDBDemoiOS */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */,
|
||||
56FE6F2524A90CE400711EDF /* SceneDelegate.swift */,
|
||||
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */,
|
||||
56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */,
|
||||
56185BBE25B8036100B9C30F /* Persistence.swift */,
|
||||
56B0361A1E8D9F38003B6DA4 /* Player.swift */,
|
||||
56FE6F4F24A9114200711EDF /* ViewControllers */,
|
||||
56FE6F2524A90CE400711EDF /* SceneDelegate.swift */,
|
||||
56FE6F4E24A9112900711EDF /* Resources */,
|
||||
56FE6F5124A9118000711EDF /* Support */,
|
||||
56FE6F4F24A9114200711EDF /* ViewControllers */,
|
||||
);
|
||||
path = GRDBDemoiOS;
|
||||
sourceTree = "<group>";
|
||||
@@ -316,6 +351,24 @@
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
56185BEF25B80B8900B9C30F /* GRDBDemoiOSTests */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 56185BFF25B80B8900B9C30F /* Build configuration list for PBXNativeTarget "GRDBDemoiOSTests" */;
|
||||
buildPhases = (
|
||||
56185BEC25B80B8900B9C30F /* Sources */,
|
||||
56185BED25B80B8900B9C30F /* Frameworks */,
|
||||
56185BEE25B80B8900B9C30F /* Resources */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
56185BF625B80B8900B9C30F /* PBXTargetDependency */,
|
||||
);
|
||||
name = GRDBDemoiOSTests;
|
||||
productName = GRDBDemoiOSTests;
|
||||
productReference = 56185BF025B80B8900B9C30F /* GRDBDemoiOSTests.xctest */;
|
||||
productType = "com.apple.product-type.bundle.unit-test";
|
||||
};
|
||||
568E5FBE1E926430002582E0 /* GRDBDemoWatchOS */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 568E5FDE1E926430002582E0 /* Build configuration list for PBXNativeTarget "GRDBDemoWatchOS" */;
|
||||
@@ -379,10 +432,16 @@
|
||||
56B035FB1E8D9EBE003B6DA4 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastSwiftUpdateCheck = 0830;
|
||||
LastSwiftUpdateCheck = 1230;
|
||||
LastUpgradeCheck = 1200;
|
||||
ORGANIZATIONNAME = "Gwendal Roué";
|
||||
TargetAttributes = {
|
||||
56185BEF25B80B8900B9C30F = {
|
||||
CreatedOnToolsVersion = 12.3;
|
||||
DevelopmentTeam = AMD8W895CT;
|
||||
ProvisioningStyle = Automatic;
|
||||
TestTargetID = 56B036021E8D9EBE003B6DA4;
|
||||
};
|
||||
568E5FBE1E926430002582E0 = {
|
||||
CreatedOnToolsVersion = 8.3;
|
||||
DevelopmentTeam = AMD8W895CT;
|
||||
@@ -424,6 +483,7 @@
|
||||
56B036021E8D9EBE003B6DA4 /* GRDBDemoiOS */,
|
||||
568E5FBE1E926430002582E0 /* GRDBDemoWatchOS */,
|
||||
568E5FCA1E926430002582E0 /* GRDBDemoWatchOS Extension */,
|
||||
56185BEF25B80B8900B9C30F /* GRDBDemoiOSTests */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
@@ -488,6 +548,13 @@
|
||||
/* End PBXReferenceProxy section */
|
||||
|
||||
/* Begin PBXResourcesBuildPhase section */
|
||||
56185BEE25B80B8900B9C30F /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
568E5FBD1E926430002582E0 /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
@@ -518,6 +585,15 @@
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
56185BEC25B80B8900B9C30F /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
56185C0725B80CEC00B9C30F /* PlayerTests.swift in Sources */,
|
||||
56185BF325B80B8900B9C30F /* AppDatabaseTests.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
568E5FC71E926430002582E0 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
@@ -534,6 +610,7 @@
|
||||
56FE6F2624A90CE400711EDF /* SceneDelegate.swift in Sources */,
|
||||
56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */,
|
||||
56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */,
|
||||
56185BBF25B8036100B9C30F /* Persistence.swift in Sources */,
|
||||
56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */,
|
||||
56B036241E8D9F4C003B6DA4 /* PlayerListViewController.swift in Sources */,
|
||||
56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */,
|
||||
@@ -543,6 +620,11 @@
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXTargetDependency section */
|
||||
56185BF625B80B8900B9C30F /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
target = 56B036021E8D9EBE003B6DA4 /* GRDBDemoiOS */;
|
||||
targetProxy = 56185BF525B80B8900B9C30F /* PBXContainerItemProxy */;
|
||||
};
|
||||
56606D1E2355937900185962 /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = GRDBiOS;
|
||||
@@ -593,6 +675,51 @@
|
||||
/* End PBXVariantGroup section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
56185BF725B80B8900B9C30F /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu11;
|
||||
INFOPLIST_FILE = GRDBDemoiOSTests/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 14.3;
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
|
||||
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
|
||||
MTL_FAST_MATH = YES;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOSTests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBDemoiOS.app/GRDBDemoiOS";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
56185BF825B80B8900B9C30F /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu11;
|
||||
INFOPLIST_FILE = GRDBDemoiOSTests/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 14.3;
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
|
||||
MTL_FAST_MATH = YES;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOSTests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBDemoiOS.app/GRDBDemoiOS";
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
568E5FDB1E926430002582E0 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
@@ -601,7 +728,7 @@
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
INFOPLIST_FILE = "GRDBDemoWatchOS Extension/Info.plist";
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension;
|
||||
PRODUCT_NAME = "${TARGET_NAME}";
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
@@ -617,7 +744,7 @@
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
INFOPLIST_FILE = "GRDBDemoWatchOS Extension/Info.plist";
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension;
|
||||
PRODUCT_NAME = "${TARGET_NAME}";
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
@@ -634,7 +761,7 @@
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
IBSC_MODULE = GRDBDemoWatchOS_Extension;
|
||||
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
@@ -651,7 +778,7 @@
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
IBSC_MODULE = GRDBDemoWatchOS_Extension;
|
||||
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
@@ -785,7 +912,7 @@
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
};
|
||||
name = Debug;
|
||||
@@ -799,7 +926,7 @@
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
};
|
||||
name = Release;
|
||||
@@ -807,6 +934,15 @@
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
56185BFF25B80B8900B9C30F /* Build configuration list for PBXNativeTarget "GRDBDemoiOSTests" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
56185BF725B80B8900B9C30F /* Debug */,
|
||||
56185BF825B80B8900B9C30F /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
568E5FDA1E926430002582E0 /* Build configuration list for PBXNativeTarget "GRDBDemoWatchOS Extension" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
|
||||
@@ -56,6 +56,16 @@
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56185BEF25B80B8900B9C30F"
|
||||
BuildableName = "GRDBDemoiOSTests.xctest"
|
||||
BlueprintName = "GRDBDemoiOSTests"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
@@ -68,10 +78,8 @@
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<RemoteRunnable
|
||||
runnableDebuggingMode = "2"
|
||||
BundleIdentifier = "com.apple.Carousel"
|
||||
RemotePath = "/GRDBDemoiOS">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
@@ -79,7 +87,7 @@
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</RemoteRunnable>
|
||||
</BuildableProductRunnable>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
@@ -87,10 +95,8 @@
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<RemoteRunnable
|
||||
runnableDebuggingMode = "2"
|
||||
BundleIdentifier = "com.apple.Carousel"
|
||||
RemotePath = "/GRDBDemoiOS">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
@@ -98,16 +104,7 @@
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</RemoteRunnable>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
BuildableName = "GRDBDemoWatchOS.app"
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1200"
|
||||
LastUpgradeVersion = "1230"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -28,6 +28,16 @@
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56185BEF25B80B8900B9C30F"
|
||||
BuildableName = "GRDBDemoiOSTests.xctest"
|
||||
BlueprintName = "GRDBDemoiOSTests"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
|
||||
@@ -5,17 +5,20 @@ import GRDB
|
||||
/// It applies the pratices recommended at
|
||||
/// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
|
||||
final class AppDatabase {
|
||||
/// The shared AppDatabase
|
||||
static var shared: AppDatabase!
|
||||
|
||||
private let dbQueue: DatabaseQueue
|
||||
|
||||
/// Creates an AppDatabase and make sure the database schema is ready.
|
||||
init(_ dbQueue: DatabaseQueue) throws {
|
||||
self.dbQueue = dbQueue
|
||||
try migrator.migrate(dbQueue)
|
||||
/// Creates an `AppDatabase`, and make sure the database schema is ready.
|
||||
init(_ dbWriter: DatabaseWriter) throws {
|
||||
self.dbWriter = dbWriter
|
||||
try migrator.migrate(dbWriter)
|
||||
}
|
||||
|
||||
/// Provides access to the database.
|
||||
///
|
||||
/// Application can use a `DatabasePool`, and tests can use a fast
|
||||
/// in-memory `DatabaseQueue`.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
private let dbWriter: DatabaseWriter
|
||||
|
||||
/// The DatabaseMigrator that defines the database schema.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md
|
||||
@@ -34,9 +37,6 @@ final class AppDatabase {
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
// Sort player names in a localized case insensitive fashion by default
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#unicode
|
||||
.collate(.localizedCaseInsensitiveCompare)
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
}
|
||||
@@ -50,39 +50,36 @@ final class AppDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Database Access
|
||||
//
|
||||
// This extension defines methods that fulfill application needs, both in terms
|
||||
// of writes and reads.
|
||||
// MARK: - Database Access: Writes
|
||||
|
||||
extension AppDatabase {
|
||||
// MARK: Writes
|
||||
|
||||
/// Save (insert or update) a player.
|
||||
/// 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 dbQueue.write { db in
|
||||
try dbWriter.write { db in
|
||||
try player.save(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete the specified players
|
||||
func deletePlayers(ids: [Int64]) throws {
|
||||
try dbQueue.write { db in
|
||||
try dbWriter.write { db in
|
||||
_ = try Player.deleteAll(db, keys: ids)
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete all players
|
||||
func deleteAllPlayers() throws {
|
||||
try dbQueue.write { db in
|
||||
try dbWriter.write { db in
|
||||
_ = try Player.deleteAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Refresh all players (by performing some random changes, for demo purpose).
|
||||
func refreshPlayers() throws {
|
||||
try dbQueue.write { db in
|
||||
try dbWriter.write { db in
|
||||
if try Player.fetchCount(db) == 0 {
|
||||
// Insert new random players
|
||||
// When database is empty, insert new random players
|
||||
try createRandomPlayers(db)
|
||||
} else {
|
||||
// Insert a player
|
||||
@@ -90,10 +87,12 @@ extension AppDatabase {
|
||||
var player = Player.newRandom()
|
||||
try player.insert(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) {
|
||||
@@ -106,7 +105,7 @@ extension AppDatabase {
|
||||
|
||||
/// Create random players if the database is empty.
|
||||
func createRandomPlayersIfEmpty() throws {
|
||||
try dbQueue.write { db in
|
||||
try dbWriter.write { db in
|
||||
if try Player.fetchCount(db) == 0 {
|
||||
try createRandomPlayers(db)
|
||||
}
|
||||
@@ -120,23 +119,11 @@ extension AppDatabase {
|
||||
try player.insert(db)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Reads
|
||||
|
||||
/// Tracks changes in the number of players
|
||||
func observePlayerCount(
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Int) -> Void)
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
ValueObservation
|
||||
.tracking(Player.fetchCount)
|
||||
.start(
|
||||
in: dbQueue,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Database Access: Reads
|
||||
|
||||
extension AppDatabase {
|
||||
/// Tracks changes in players ordered by name
|
||||
func observePlayersOrderedByName(
|
||||
onError: @escaping (Error) -> Void,
|
||||
@@ -146,7 +133,7 @@ extension AppDatabase {
|
||||
ValueObservation
|
||||
.tracking(Player.all().orderedByName().fetchAll)
|
||||
.start(
|
||||
in: dbQueue,
|
||||
in: dbWriter,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
}
|
||||
@@ -160,19 +147,8 @@ extension AppDatabase {
|
||||
ValueObservation
|
||||
.tracking(Player.all().orderedByScore().fetchAll)
|
||||
.start(
|
||||
in: dbQueue,
|
||||
in: dbWriter,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Support for Tests
|
||||
|
||||
#if DEBUG
|
||||
extension AppDatabase {
|
||||
/// Returns an empty, in-memory database, suitable for testing.
|
||||
static func empty() throws -> AppDatabase {
|
||||
try AppDatabase(DatabaseQueue())
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,11 +1,8 @@
|
||||
import UIKit
|
||||
import GRDB
|
||||
|
||||
@UIApplicationMain
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
|
||||
// Setup database. Error handling left as an exercise for the reader.
|
||||
try! setupDatabase()
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -22,24 +19,4 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
|
||||
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
|
||||
}
|
||||
|
||||
// MARK: - Database Setup
|
||||
|
||||
private func setupDatabase() throws {
|
||||
// AppDelegate chooses the location of the database file.
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
let databaseURL = try FileManager.default
|
||||
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
.appendingPathComponent("db.sqlite")
|
||||
let dbQueue = try DatabaseQueue(path: databaseURL.path)
|
||||
|
||||
// Create the shared application database
|
||||
let database = try AppDatabase(dbQueue)
|
||||
|
||||
// Populate the database if it is empty, for better demo purpose.
|
||||
try database.createRandomPlayersIfEmpty()
|
||||
|
||||
// Expose it to the rest of the application
|
||||
AppDatabase.shared = database
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
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, as well as
|
||||
// the various temporary files created during normal database
|
||||
// operations (https://sqlite.org/tempfiles.html).
|
||||
let fileManager = FileManager()
|
||||
let folderURL = try fileManager
|
||||
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
.appendingPathComponent("database", isDirectory: true)
|
||||
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
|
||||
|
||||
// Connect to a database on disk
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
let 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 {
|
||||
// Replace this implementation with code to handle the error appropriately.
|
||||
// fatalError() causes the application to generate a crash log and terminate.
|
||||
//
|
||||
// Typical reasons for an error here include:
|
||||
// * The parent directory cannot be created, or disallows writing.
|
||||
// * The database is not accessible, due to permissions or data protection when the device is locked.
|
||||
// * The device is out of space.
|
||||
// * The database could not be migrated to its latest schema version.
|
||||
// Check the error message to determine what the actual problem was.
|
||||
fatalError("Unresolved error \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -70,25 +70,35 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
|
||||
extension DerivableRequest where RowDecoder == Player {
|
||||
/// A request of players ordered by name
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let players = try dbQueue.read { db in
|
||||
/// let players: [Player] = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByName().fetchAll(db)
|
||||
/// }
|
||||
func orderedByName() -> Self {
|
||||
order(Player.Columns.name)
|
||||
// Sort by name in a localized case insensitive fashion
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
|
||||
order(Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
|
||||
/// A request of players ordered by score
|
||||
/// A request of players ordered by score.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let players = try dbQueue.read { db in
|
||||
/// let players: [Player] = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByScore().fetchAll(db)
|
||||
/// }
|
||||
/// let bestPlayer: Player? = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByScore().fetchOne(db)
|
||||
/// }
|
||||
func orderedByScore() -> Self {
|
||||
order(Player.Columns.score.desc, Player.Columns.name)
|
||||
// Sort by descending score, and then by name, in a
|
||||
// localized case insensitive fashion
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
|
||||
order(
|
||||
Player.Columns.score.desc,
|
||||
Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
}
|
||||
@@ -12,11 +12,10 @@ class PlayerListViewController: UITableViewController {
|
||||
private var dataSource: PlayerDataSource!
|
||||
private var animatesPlayersChange = false // Don't animate first update
|
||||
private var playersCancellable: DatabaseCancellable?
|
||||
private var playerCountCancellable: DatabaseCancellable?
|
||||
private var playerOrdering: PlayerOrdering = .byScore {
|
||||
didSet {
|
||||
configureOrderingBarButtonItem()
|
||||
configureDataSourceContent()
|
||||
observePlayers()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +24,7 @@ class PlayerListViewController: UITableViewController {
|
||||
configureToolbar()
|
||||
configureNavigationItem()
|
||||
configureDataSource()
|
||||
configureDataSourceContent()
|
||||
observePlayers()
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
@@ -49,7 +48,6 @@ class PlayerListViewController: UITableViewController {
|
||||
target: nil, action: nil)
|
||||
navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem]
|
||||
configureOrderingBarButtonItem()
|
||||
configureTitle()
|
||||
}
|
||||
|
||||
private func configureOrderingBarButtonItem() {
|
||||
@@ -67,19 +65,6 @@ class PlayerListViewController: UITableViewController {
|
||||
}
|
||||
}
|
||||
|
||||
private func configureTitle() {
|
||||
playerCountCancellable = AppDatabase.shared.observePlayerCount(
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] count in
|
||||
guard let self = self else { return }
|
||||
switch count {
|
||||
case 0: self.navigationItem.title = "No Player"
|
||||
case 1: self.navigationItem.title = "1 Player"
|
||||
default: self.navigationItem.title = "\(count) Players"
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private func configureDataSource() {
|
||||
dataSource = PlayerDataSource(tableView: tableView) { (tableView, indexPath, player) in
|
||||
let cell = tableView.dequeueReusableCell(withIdentifier: "Player", for: indexPath)
|
||||
@@ -95,26 +80,18 @@ class PlayerListViewController: UITableViewController {
|
||||
tableView.dataSource = dataSource
|
||||
}
|
||||
|
||||
private func configureDataSourceContent() {
|
||||
switch playerOrdering {
|
||||
case .byName:
|
||||
playersCancellable = AppDatabase.shared.observePlayersOrderedByName(
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
self.updateDataSourceContent(with: players)
|
||||
})
|
||||
case .byScore:
|
||||
playersCancellable = AppDatabase.shared.observePlayersOrderedByScore(
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
self.updateDataSourceContent(with: players)
|
||||
})
|
||||
private func configureTitle(from players: [Player]) {
|
||||
switch players.count {
|
||||
case 0:
|
||||
navigationItem.title = "No Player"
|
||||
case 1:
|
||||
navigationItem.title = "1 Player"
|
||||
case let count:
|
||||
navigationItem.title = "\(count) Players"
|
||||
}
|
||||
}
|
||||
|
||||
private func updateDataSourceContent(with players: [Player]) {
|
||||
private func configureDataSource(from players: [Player]) {
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Int, Player>()
|
||||
snapshot.appendSections([0])
|
||||
snapshot.appendItems(players, toSection: 0)
|
||||
@@ -127,6 +104,27 @@ class PlayerListViewController: UITableViewController {
|
||||
dataSource.apply(snapshot, animatingDifferences: false, completion: nil)
|
||||
}
|
||||
}
|
||||
|
||||
private func observePlayers() {
|
||||
switch playerOrdering {
|
||||
case .byName:
|
||||
playersCancellable = AppDatabase.shared.observePlayersOrderedByName(
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
self.configureTitle(from: players)
|
||||
self.configureDataSource(from: players)
|
||||
})
|
||||
case .byScore:
|
||||
playersCancellable = AppDatabase.shared.observePlayersOrderedByScore(
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
self.configureTitle(from: players)
|
||||
self.configureDataSource(from: players)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
@testable import GRDBDemoiOS
|
||||
|
||||
class AppDatabaseTests: XCTestCase {
|
||||
func test_database_schema() throws {
|
||||
// Given an empty database
|
||||
let dbQueue = DatabaseQueue()
|
||||
|
||||
// When we instantiate an AppDatabase
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// Then the player table exists, with id, name & score columns
|
||||
try dbQueue.read { db in
|
||||
try XCTAssert(db.tableExists("player"))
|
||||
let columns = try db.columns(in: "player")
|
||||
let columnNames = Set(columns.map { $0.name })
|
||||
XCTAssertEqual(columnNames, ["id", "name", "score"])
|
||||
}
|
||||
}
|
||||
|
||||
func test_savePlayer_inserts() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we save a new player
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try appDatabase.savePlayer(&player)
|
||||
|
||||
// Then the player exists in the database
|
||||
try XCTAssertTrue(dbQueue.read(player.exists))
|
||||
}
|
||||
|
||||
func test_savePlayer_updates() throws {
|
||||
// Given a players database that contains a 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 modify and save the player
|
||||
player.name = "Barbara"
|
||||
player.score = 1000
|
||||
try appDatabase.savePlayer(&player)
|
||||
|
||||
// Then the player has been updated in the database
|
||||
let fetchedPlayer = try dbQueue.read { db in
|
||||
try XCTUnwrap(Player.fetchOne(db, key: player.id))
|
||||
}
|
||||
XCTAssertEqual(fetchedPlayer, player)
|
||||
}
|
||||
|
||||
func test_deletePlayers() throws {
|
||||
// Given a players database that contains four 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: 200)
|
||||
var player3 = Player(id: nil, name: "Craig", score: 150)
|
||||
var player4 = Player(id: nil, name: "David", score: 120)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
try player3.insert(db)
|
||||
try player4.insert(db)
|
||||
}
|
||||
|
||||
// When we delete two players
|
||||
try appDatabase.deletePlayers(ids: [player1.id!, player3.id!])
|
||||
|
||||
// Then the deleted players no longer exist
|
||||
try dbQueue.read { db in
|
||||
try XCTAssertFalse(player1.exists(db))
|
||||
try XCTAssertFalse(player3.exists(db))
|
||||
}
|
||||
|
||||
// Then the database still contains two players
|
||||
try XCTAssertEqual(dbQueue.read(Player.fetchCount), 2)
|
||||
}
|
||||
|
||||
func test_deleteAllPlayers() throws {
|
||||
// Given a players database that contains 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: 200)
|
||||
var player3 = Player(id: nil, name: "Craig", score: 150)
|
||||
var player4 = Player(id: nil, name: "David", score: 120)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
try player3.insert(db)
|
||||
try player4.insert(db)
|
||||
}
|
||||
|
||||
// When we delete all players
|
||||
try appDatabase.deleteAllPlayers()
|
||||
|
||||
// Then the database does not contain any player
|
||||
try XCTAssertEqual(dbQueue.read(Player.fetchCount), 0)
|
||||
}
|
||||
|
||||
func test_refreshPlayers_populates_an_empty_database() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we refresh players
|
||||
try appDatabase.refreshPlayers()
|
||||
|
||||
// Then the database is not empty
|
||||
try XCTAssert(dbQueue.read(Player.fetchCount) > 0)
|
||||
}
|
||||
|
||||
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we create random players
|
||||
try appDatabase.createRandomPlayersIfEmpty()
|
||||
|
||||
// Then the database is not empty
|
||||
try XCTAssert(dbQueue.read(Player.fetchCount) > 0)
|
||||
}
|
||||
|
||||
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() 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 create random players
|
||||
try appDatabase.createRandomPlayersIfEmpty()
|
||||
|
||||
// Then the database still only contains the original player
|
||||
let players = try dbQueue.read(Player.fetchAll)
|
||||
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()
|
||||
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.observePlayersOrderedByName(
|
||||
onError: { error in
|
||||
XCTFail("Unexpected error \(error)")
|
||||
},
|
||||
onChange: {
|
||||
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_observePlayersOrderedByScore() 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.observePlayersOrderedByScore(
|
||||
onError: { error in
|
||||
XCTFail("Unexpected error \(error)")
|
||||
},
|
||||
onChange: {
|
||||
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])
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
@@ -0,0 +1,108 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
@testable import GRDBDemoiOS
|
||||
|
||||
class PlayerTests: XCTestCase {
|
||||
// MARK: - CRUD
|
||||
// Test that our Player type properly talks to GRDB.
|
||||
|
||||
func testInsert() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try dbQueue.write { db in
|
||||
try player.insert(db)
|
||||
}
|
||||
|
||||
// Then the player gets a non-nil id
|
||||
XCTAssertNotNil(player.id)
|
||||
}
|
||||
|
||||
func testRoundtrip() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player and fetch the player with the same id
|
||||
var insertedPlayer = Player(id: nil, name: "Arthur", score: 100)
|
||||
let fetchedPlayer: Player? = try dbQueue.write { db in
|
||||
try insertedPlayer.insert(db)
|
||||
return try Player.fetchOne(db, key: insertedPlayer.id)
|
||||
}
|
||||
|
||||
// Then the fetched player is equal to the inserted player
|
||||
XCTAssertEqual(insertedPlayer, fetchedPlayer)
|
||||
}
|
||||
|
||||
// MARK: - Requests
|
||||
// Test that requests defined on the Player type behave as expected.
|
||||
|
||||
func testOrderedByScore() throws {
|
||||
// Given a players database that contains players with distinct scores
|
||||
let dbQueue = DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
var player3 = Player(id: 3, name: "Craig", score: 150)
|
||||
var player4 = Player(id: 4, name: "David", score: 120)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
try player3.insert(db)
|
||||
try player4.insert(db)
|
||||
}
|
||||
|
||||
// When we fetch players ordered by score
|
||||
let players = try dbQueue.read(Player.all().orderedByScore().fetchAll)
|
||||
|
||||
// Then fetched players are ordered by score descending
|
||||
XCTAssertEqual(players, [player2, player3, player4, player1])
|
||||
}
|
||||
|
||||
func testOrderedByScoreSortsIdenticalScoresByName() throws {
|
||||
// Given a players database that contains players with common scores
|
||||
let dbQueue = DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
var player3 = Player(id: 3, name: "Craig", score: 200)
|
||||
var player4 = Player(id: 4, name: "David", score: 200)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
try player3.insert(db)
|
||||
try player4.insert(db)
|
||||
}
|
||||
|
||||
// When we fetch players ordered by score
|
||||
let players = try dbQueue.read(Player.all().orderedByScore().fetchAll)
|
||||
|
||||
// Then fetched players are ordered by score descending and by name
|
||||
XCTAssertEqual(players, [player2, player3, player4, player1])
|
||||
}
|
||||
|
||||
func testOrderedByName() throws {
|
||||
// Given a players database that contains players with distinct names
|
||||
let dbQueue = DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
var player3 = Player(id: 3, name: "Craig", score: 150)
|
||||
var player4 = Player(id: 4, name: "David", score: 120)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
try player3.insert(db)
|
||||
try player4.insert(db)
|
||||
}
|
||||
|
||||
// When we fetch players ordered by name
|
||||
let players = try dbQueue.read(Player.all().orderedByName().fetchAll)
|
||||
|
||||
// Then fetched players are ordered by name
|
||||
XCTAssertEqual(players, [player1, player2, player3, player4])
|
||||
}
|
||||
}
|
||||
@@ -16,13 +16,13 @@ The topics covered in this demo are:
|
||||
|
||||
**Files of interest:**
|
||||
|
||||
- [AppDelegate.swift](GRDBDemoiOS/AppDelegate.swift)
|
||||
|
||||
`AppDelegate` creates, on application startup, a unique instance of [DatabaseQueue](../../../README.md#database-queues) available for the whole application.
|
||||
|
||||
- [AppDatabase.swift](GRDBDemoiOS/AppDatabase.swift)
|
||||
|
||||
`AppDatabase` grants database access for the whole application. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema, and [ValueObservation](../../../README.md#valueobservation) in order to let the application observe database changes.
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema, and [ValueObservation](../../../README.md#valueobservation) in order to let the application observe database changes.
|
||||
|
||||
- [Persistence.swift](GRDBDemoiOS/Persistence.swift)
|
||||
|
||||
This file defines the `AppDatabase` instance used by the application.
|
||||
|
||||
- [Player.swift](GRDBDemoiOS/Player.swift)
|
||||
|
||||
@@ -35,3 +35,9 @@ The topics covered in this demo are:
|
||||
- [PlayerEditionViewController.swift](GRDBDemoiOS/ViewControllers/PlayerEditionViewController.swift)
|
||||
|
||||
`PlayerEditionViewController` can create or edit a player, and save it in the database.
|
||||
|
||||
- [GRDBDemoiOSTests](GRDBDemoiOSTests)
|
||||
|
||||
- Test the database schema
|
||||
- Test the `Player` record and its requests
|
||||
- Test the `AppDatabase` methods that let the app access the database.
|
||||
@@ -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.0/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.3/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -529,7 +529,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.0/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.3/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
|
||||
@@ -93,19 +93,6 @@ let observation = ValueObservation.tracking { db in
|
||||
let observation = ValueObservation.tracking(Player.fetchAll)
|
||||
```
|
||||
|
||||
If the tracked value is computed from several database requests that are not always the same, make sure you use the `trackingVaryingRegion` method, as below. See [Observing a Varying Database Region] for more information.
|
||||
|
||||
```swift
|
||||
// An observation which does not always execute the same requests:
|
||||
let observation = ValueObservation.trackingVaryingRegion { db -> Int in
|
||||
let preference = try Preference.fetchOne(db) ?? .default
|
||||
switch preference.selection {
|
||||
case .food: return try Food.fetchCount(db)
|
||||
case .beverage: return try Beverage.fetchCount(db)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Several methods that build observations were removed:
|
||||
|
||||
```swift
|
||||
@@ -515,7 +502,6 @@ let publisher = observation
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
|
||||
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
|
||||
[Observing a Varying Database Region]: ../README.md#observing-a-varying-database-region
|
||||
[removeDuplicates]: ../README.md#valueobservationremoveduplicates
|
||||
[Custom SQL functions]: ../README.md#custom-sql-functions
|
||||
[Batch updates]: ../README.md#update-requests
|
||||
|
||||
@@ -68,7 +68,7 @@ try dbQueue.read { db in
|
||||
}
|
||||
```
|
||||
|
||||
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.0/Structs/DatabaseMigrator.html) for more migrator methods.
|
||||
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.3/Structs/DatabaseMigrator.html) for more migrator methods.
|
||||
|
||||
|
||||
## The `eraseDatabaseOnSchemaChange` Option
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<playground version='5.0' target-platform='macos'>
|
||||
<playground version='5.0' target-platform='macos' buildActiveScheme='true'>
|
||||
<timeline fileName='timeline.xctimeline'/>
|
||||
</playground>
|
||||
@@ -1,4 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<playground version='5.0' target-platform='macos' display-mode='rendered'>
|
||||
<playground version='5.0' target-platform='macos' display-mode='rendered' buildActiveScheme='true'>
|
||||
<timeline fileName='timeline.xctimeline'/>
|
||||
</playground>
|
||||
@@ -1,4 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<playground version='5.0' target-platform='macos'>
|
||||
<playground version='5.0' target-platform='macos' buildActiveScheme='true'>
|
||||
<timeline fileName='timeline.xctimeline'/>
|
||||
</playground>
|
||||
@@ -1,4 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<playground version='5.0' target-platform='osx' display-mode='raw'>
|
||||
<playground version='5.0' target-platform='osx' display-mode='raw' buildActiveScheme='true'>
|
||||
<timeline fileName='timeline.xctimeline'/>
|
||||
</playground>
|
||||
@@ -1,4 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<playground version='5.0' target-platform='osx' display-mode='rendered'>
|
||||
<playground version='5.0' target-platform='osx' display-mode='rendered' buildActiveScheme='true'>
|
||||
<timeline fileName='timeline.xctimeline'/>
|
||||
</playground>
|
||||
@@ -11,7 +11,7 @@ To release a new GRDB version:
|
||||
- Archive GRDBDemoiOS
|
||||
- Check for performance regression with GRDBOSXPerformanceTests
|
||||
- On https://github.com/groue/sqlcipher.git upgrade, update SQLCipher version in README.md
|
||||
- On https://github.com/swiftlyfalling/SQLiteLib upgrade, update SQLite version in README.md and Documentation/CustomSQLiteBuilds.md
|
||||
- On https://github.com/swiftlyfalling/SQLiteLib upgrade, update SQLite version in Documentation/CustomSQLiteBuilds.md
|
||||
- Update GRDB version number and release date in:
|
||||
- Makefile
|
||||
- CHANGELOG.md
|
||||
|
||||
@@ -417,9 +417,16 @@ This chapter lists all kinds of supported interpolations.
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player ORDER BY name DESC
|
||||
"SELECT * FROM player WHERE id IN \(Column("name").desc)"
|
||||
"SELECT * FROM player ORDER BY \(Column("name").desc)"
|
||||
```
|
||||
|
||||
- Database Collations:
|
||||
|
||||
```swift
|
||||
"SELECT * FROM player ORDER BY email COLLATING \(.nocase)"
|
||||
"SELECT * FROM player ORDER BY email COLLATING \(.localizedCompare)"
|
||||
```
|
||||
|
||||
- Subqueries:
|
||||
|
||||
```swift
|
||||
@@ -432,6 +439,16 @@ This chapter lists all kinds of supported interpolations.
|
||||
"SELECT * FROM player WHERE score = (\(subquery))"
|
||||
```
|
||||
|
||||
- Definition and table name of [common table Expressions]:
|
||||
|
||||
```swift
|
||||
// WITH name AS (SELECT 'O''Brien') SELECT * FROM name
|
||||
let cte = CommonTableExpression<Void>(
|
||||
named: "name",
|
||||
literal: "SELECT \("O'Brien")")
|
||||
"WITH \(definitionFor: cte) SELECT * FROM \(cte)"
|
||||
```
|
||||
|
||||
- SQLLiteral:
|
||||
|
||||
```swift
|
||||
@@ -472,3 +489,4 @@ This chapter lists all kinds of supported interpolations.
|
||||
[query interface requests]: ../README.md#requests
|
||||
[SE-0228 Fix ExpressibleByStringInterpolation]: https://github.com/apple/swift-evolution/blob/master/proposals/0228-fix-expressiblebystringinterpolation.md
|
||||
[columns selected by the record]: ../README.md#columns-selected-by-a-request
|
||||
[common table Expressions]: CommonTableExpressions.md
|
||||
@@ -188,7 +188,7 @@ See https://developer.apple.com/library/archive/technotes/tn2151/_index.html for
|
||||
|
||||
This will avoid https://github.com/sqlcipher/sqlcipher/issues/255.
|
||||
|
||||
2. [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features) In each process that wants to write in the database:
|
||||
2. [**:fire: EXPERIMENTAL**](../README.md#what-are-experimental-features) In each process that wants to write in the database:
|
||||
|
||||
Set the `observesSuspensionNotifications` configuration flag:
|
||||
|
||||
|
||||
@@ -0,0 +1,956 @@
|
||||
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
|
||||
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '5.0.2'
|
||||
s.version = '5.3.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -7,6 +7,13 @@
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
56012B552573EED000B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */; };
|
||||
56012B562573EED100B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */; };
|
||||
56012B572573EED100B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */; };
|
||||
56012B9F257404DF00B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B742574048B00B4925B /* CommonTableExpression.swift */; };
|
||||
56012BA8257404E000B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B742574048B00B4925B /* CommonTableExpression.swift */; };
|
||||
56012BB1257404E100B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B742574048B00B4925B /* CommonTableExpression.swift */; };
|
||||
56012BB2257404E200B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B742574048B00B4925B /* CommonTableExpression.swift */; };
|
||||
560432A0228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */; };
|
||||
560432A1228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */; };
|
||||
560432A3228F1668009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */; };
|
||||
@@ -52,6 +59,10 @@
|
||||
560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; };
|
||||
560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; };
|
||||
560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; };
|
||||
5611620825757583007AAF99 /* JoinAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5611620725757583007AAF99 /* JoinAssociation.swift */; };
|
||||
5611620925757583007AAF99 /* JoinAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5611620725757583007AAF99 /* JoinAssociation.swift */; };
|
||||
5611620A25757583007AAF99 /* JoinAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5611620725757583007AAF99 /* JoinAssociation.swift */; };
|
||||
5611620B25757583007AAF99 /* JoinAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5611620725757583007AAF99 /* JoinAssociation.swift */; };
|
||||
5613ED3521A95A5C00DC7A68 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3421A95A5C00DC7A68 /* Map.swift */; };
|
||||
5613ED3621A95A5C00DC7A68 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3421A95A5C00DC7A68 /* Map.swift */; };
|
||||
5613ED3721A95A5C00DC7A68 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3421A95A5C00DC7A68 /* Map.swift */; };
|
||||
@@ -810,6 +821,10 @@
|
||||
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 */; };
|
||||
@@ -856,66 +871,18 @@
|
||||
56EB0AB31BCD787300A3DC55 /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; };
|
||||
56F0B9921B6001C600A2F135 /* FoundationNSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */; };
|
||||
56F26C1C1CEE3F32007969C4 /* RowAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */; };
|
||||
56F34F9924AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34F9824AE78DE007513FC /* SQLExpressionVisitor.swift */; };
|
||||
56F34F9A24AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34F9824AE78DE007513FC /* SQLExpressionVisitor.swift */; };
|
||||
56F34F9B24AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34F9824AE78DE007513FC /* SQLExpressionVisitor.swift */; };
|
||||
56F34F9C24AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34F9824AE78DE007513FC /* SQLExpressionVisitor.swift */; };
|
||||
56F34FA424B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FA324B06A3B007513FC /* SQLExpressionGenerator.swift */; };
|
||||
56F34FA524B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FA324B06A3B007513FC /* SQLExpressionGenerator.swift */; };
|
||||
56F34FA624B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FA324B06A3B007513FC /* SQLExpressionGenerator.swift */; };
|
||||
56F34FA724B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FA324B06A3B007513FC /* SQLExpressionGenerator.swift */; };
|
||||
56F34FBA24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */; };
|
||||
56F34FBB24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */; };
|
||||
56F34FBC24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */; };
|
||||
56F34FC224B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */; };
|
||||
56F34FC324B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */; };
|
||||
56F34FC424B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */; };
|
||||
56F34FC924B0DD6A007513FC /* SQLSelectableVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC824B0DD6A007513FC /* SQLSelectableVisitor.swift */; };
|
||||
56F34FCA24B0DD6A007513FC /* SQLSelectableVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC824B0DD6A007513FC /* SQLSelectableVisitor.swift */; };
|
||||
56F34FCB24B0DD6B007513FC /* SQLSelectableVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC824B0DD6A007513FC /* SQLSelectableVisitor.swift */; };
|
||||
56F34FCC24B0DD6B007513FC /* SQLSelectableVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC824B0DD6A007513FC /* SQLSelectableVisitor.swift */; };
|
||||
56F34FD124B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD024B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift */; };
|
||||
56F34FD224B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD024B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift */; };
|
||||
56F34FD324B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD024B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift */; };
|
||||
56F34FD424B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD024B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift */; };
|
||||
56F34FD624B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD524B0E532007513FC /* SQLSelectableCountGenerator.swift */; };
|
||||
56F34FD724B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD524B0E532007513FC /* SQLSelectableCountGenerator.swift */; };
|
||||
56F34FD824B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD524B0E532007513FC /* SQLSelectableCountGenerator.swift */; };
|
||||
56F34FD924B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD524B0E532007513FC /* SQLSelectableCountGenerator.swift */; };
|
||||
56F34FE124B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE024B0E915007513FC /* SQLOrderingTermVisitor.swift */; };
|
||||
56F34FE224B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE024B0E915007513FC /* SQLOrderingTermVisitor.swift */; };
|
||||
56F34FE324B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE024B0E915007513FC /* SQLOrderingTermVisitor.swift */; };
|
||||
56F34FE424B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE024B0E915007513FC /* SQLOrderingTermVisitor.swift */; };
|
||||
56F34FE924B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE824B0EE9C007513FC /* SQLOrderingGenerator.swift */; };
|
||||
56F34FEA24B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE824B0EE9C007513FC /* SQLOrderingGenerator.swift */; };
|
||||
56F34FEB24B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE824B0EE9C007513FC /* SQLOrderingGenerator.swift */; };
|
||||
56F34FEC24B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE824B0EE9C007513FC /* SQLOrderingGenerator.swift */; };
|
||||
56F34FF424B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FF324B0F83D007513FC /* SQLCollectionVisitor.swift */; };
|
||||
56F34FF524B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FF324B0F83D007513FC /* SQLCollectionVisitor.swift */; };
|
||||
56F34FF624B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FF324B0F83D007513FC /* SQLCollectionVisitor.swift */; };
|
||||
56F34FF724B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FF324B0F83D007513FC /* SQLCollectionVisitor.swift */; };
|
||||
56F34FFF24B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FFE24B0FB69007513FC /* SQLCollectionGenerator.swift */; };
|
||||
56F3500024B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FFE24B0FB69007513FC /* SQLCollectionGenerator.swift */; };
|
||||
56F3500124B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FFE24B0FB69007513FC /* SQLCollectionGenerator.swift */; };
|
||||
56F3500224B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FFE24B0FB69007513FC /* SQLCollectionGenerator.swift */; };
|
||||
56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
|
||||
56F3E74D1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
|
||||
56F5ABD91D814330001F60CB /* Data.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C33F1D23E82A00E59934 /* Data.swift */; };
|
||||
56F5ABDA1D814330001F60CB /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; };
|
||||
56F5ABDC1D814330001F60CB /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; };
|
||||
56F5ABDD1D814330001F60CB /* UUID.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C22F1D1914540096E9D4 /* UUID.swift */; };
|
||||
56F896AA24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896A924B9DEA7005FB062 /* FetchRequestVisitor.swift */; };
|
||||
56F896AB24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896A924B9DEA7005FB062 /* FetchRequestVisitor.swift */; };
|
||||
56F896AC24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896A924B9DEA7005FB062 /* FetchRequestVisitor.swift */; };
|
||||
56F896AD24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896A924B9DEA7005FB062 /* FetchRequestVisitor.swift */; };
|
||||
56F896B624B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896B524B9E68D005FB062 /* SQLRequestGenerator.swift */; };
|
||||
56F896B724B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896B524B9E68D005FB062 /* SQLRequestGenerator.swift */; };
|
||||
56F896B824B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896B524B9E68D005FB062 /* SQLRequestGenerator.swift */; };
|
||||
56F896B924B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896B524B9E68D005FB062 /* SQLRequestGenerator.swift */; };
|
||||
56F896BB24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896BA24B9E730005FB062 /* SQLPreparedRequestGenerator.swift */; };
|
||||
56F896BC24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896BA24B9E730005FB062 /* SQLPreparedRequestGenerator.swift */; };
|
||||
56F896BD24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896BA24B9E730005FB062 /* SQLPreparedRequestGenerator.swift */; };
|
||||
56F896BE24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896BA24B9E730005FB062 /* SQLPreparedRequestGenerator.swift */; };
|
||||
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 */; };
|
||||
@@ -1279,6 +1246,8 @@
|
||||
/* End PBXContainerItemProxy section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
56012B542573EED000B4925B /* CommonTableExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpressionTests.swift; sourceTree = "<group>"; };
|
||||
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>"; };
|
||||
56057C4E2291B16900A7CB10 /* AssociationHasManyRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyRowScopeTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1304,6 +1273,7 @@
|
||||
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = "<group>"; };
|
||||
560D92441C672C4B00F4F92B /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = "<group>"; };
|
||||
560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = "<group>"; };
|
||||
5611620725757583007AAF99 /* JoinAssociation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JoinAssociation.swift; sourceTree = "<group>"; };
|
||||
5613ED3421A95A5C00DC7A68 /* Map.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Map.swift; sourceTree = "<group>"; };
|
||||
5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueReducer.swift; sourceTree = "<group>"; };
|
||||
5615B25A222AE1B400061C1C /* AssociationHasOneThroughSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLDerivationTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1607,6 +1577,7 @@
|
||||
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>"; };
|
||||
@@ -1629,21 +1600,9 @@
|
||||
56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataMemoryTests.swift; sourceTree = "<group>"; };
|
||||
56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizerTests.swift; sourceTree = "<group>"; };
|
||||
56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = "<group>"; };
|
||||
56F34F9824AE78DE007513FC /* SQLExpressionVisitor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpressionVisitor.swift; sourceTree = "<group>"; };
|
||||
56F34FA324B06A3B007513FC /* SQLExpressionGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpressionGenerator.swift; sourceTree = "<group>"; };
|
||||
56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLExpressionIsConstantTests.swift; sourceTree = "<group>"; };
|
||||
56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLIdentifyingColumnsTests.swift; sourceTree = "<group>"; };
|
||||
56F34FC824B0DD6A007513FC /* SQLSelectableVisitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelectableVisitor.swift; sourceTree = "<group>"; };
|
||||
56F34FD024B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelectableResultColumnGenerator.swift; sourceTree = "<group>"; };
|
||||
56F34FD524B0E532007513FC /* SQLSelectableCountGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectableCountGenerator.swift; sourceTree = "<group>"; };
|
||||
56F34FE024B0E915007513FC /* SQLOrderingTermVisitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLOrderingTermVisitor.swift; sourceTree = "<group>"; };
|
||||
56F34FE824B0EE9C007513FC /* SQLOrderingGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOrderingGenerator.swift; sourceTree = "<group>"; };
|
||||
56F34FF324B0F83D007513FC /* SQLCollectionVisitor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollectionVisitor.swift; sourceTree = "<group>"; };
|
||||
56F34FFE24B0FB69007513FC /* SQLCollectionGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollectionGenerator.swift; sourceTree = "<group>"; };
|
||||
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = "<group>"; };
|
||||
56F896A924B9DEA7005FB062 /* FetchRequestVisitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchRequestVisitor.swift; sourceTree = "<group>"; };
|
||||
56F896B524B9E68D005FB062 /* SQLRequestGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestGenerator.swift; sourceTree = "<group>"; };
|
||||
56F896BA24B9E730005FB062 /* SQLPreparedRequestGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLPreparedRequestGenerator.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>"; };
|
||||
@@ -1902,6 +1861,7 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */,
|
||||
56012B542573EED000B4925B /* CommonTableExpressionTests.swift */,
|
||||
56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */,
|
||||
56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */,
|
||||
56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */,
|
||||
@@ -2060,6 +2020,7 @@
|
||||
56959628222C462D002CB7C9 /* HasManyThroughAssociation.swift */,
|
||||
5653EB0220944C7C00F46237 /* HasOneAssociation.swift */,
|
||||
56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */,
|
||||
5611620725757583007AAF99 /* JoinAssociation.swift */,
|
||||
);
|
||||
path = Association;
|
||||
sourceTree = "<group>";
|
||||
@@ -2076,15 +2037,8 @@
|
||||
5656A8162295AFD6001FF3FF /* SQLGeneration */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56F34FFE24B0FB69007513FC /* SQLCollectionGenerator.swift */,
|
||||
56F34FA324B06A3B007513FC /* SQLExpressionGenerator.swift */,
|
||||
5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */,
|
||||
56F34FE824B0EE9C007513FC /* SQLOrderingGenerator.swift */,
|
||||
56F896BA24B9E730005FB062 /* SQLPreparedRequestGenerator.swift */,
|
||||
568D13182207213E00674B58 /* SQLQueryGenerator.swift */,
|
||||
56F896B524B9E68D005FB062 /* SQLRequestGenerator.swift */,
|
||||
56F34FD524B0E532007513FC /* SQLSelectableCountGenerator.swift */,
|
||||
56F34FD024B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift */,
|
||||
);
|
||||
path = SQLGeneration;
|
||||
sourceTree = "<group>";
|
||||
@@ -2097,21 +2051,18 @@
|
||||
5656A81D2295B12F001FF3FF /* SQLAssociation.swift */,
|
||||
5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */,
|
||||
566475991D97D8A000FF74B8 /* SQLCollection.swift */,
|
||||
56F34FF324B0F83D007513FC /* SQLCollectionVisitor.swift */,
|
||||
56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */,
|
||||
56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */,
|
||||
56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */,
|
||||
56F34F9824AE78DE007513FC /* SQLExpressionVisitor.swift */,
|
||||
5653EAF920944C7B00F46237 /* SQLForeignKeyRequest.swift */,
|
||||
566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */,
|
||||
566475CB1D981D5E00FF74B8 /* SQLOperators.swift */,
|
||||
56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */,
|
||||
56F34FE024B0E915007513FC /* SQLOrderingTermVisitor.swift */,
|
||||
56D91AAF2205F8AC00770D8D /* SQLQuery.swift */,
|
||||
56D91AA12205E03700770D8D /* SQLRelation.swift */,
|
||||
56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */,
|
||||
56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */,
|
||||
566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */,
|
||||
56F34FC824B0DD6A007513FC /* SQLSelectableVisitor.swift */,
|
||||
566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */,
|
||||
);
|
||||
path = SQL;
|
||||
@@ -2121,6 +2072,7 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5653EAF720944BC900F46237 /* Association */,
|
||||
56012B742574048B00B4925B /* CommonTableExpression.swift */,
|
||||
56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */,
|
||||
5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */,
|
||||
5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */,
|
||||
@@ -2352,7 +2304,6 @@
|
||||
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
|
||||
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
|
||||
5636E9BB1D22574100B9B05F /* FetchRequest.swift */,
|
||||
56F896A924B9DEA7005FB062 /* FetchRequestVisitor.swift */,
|
||||
56A238761B9C75030082EB20 /* Row.swift */,
|
||||
567404871CEF84C8003ED5CC /* RowAdapter.swift */,
|
||||
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
|
||||
@@ -2919,12 +2870,10 @@
|
||||
files = (
|
||||
5616AAF3207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
|
||||
56B964BF1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
|
||||
56F34FCB24B0DD6B007513FC /* SQLSelectableVisitor.swift in Sources */,
|
||||
56D51D061EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
|
||||
565490CE1D5AE252005622CB /* NSNull.swift in Sources */,
|
||||
5656A8202295B12F001FF3FF /* SQLAssociation.swift in Sources */,
|
||||
565490E41D5AE252005622CB /* TableRecord.swift in Sources */,
|
||||
56F3500124B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */,
|
||||
564CE5AE21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
|
||||
565490CF1D5AE252005622CB /* NSNumber.swift in Sources */,
|
||||
566475C01D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */,
|
||||
@@ -2947,7 +2896,6 @@
|
||||
56172950223533F40006E219 /* EncodableRecord.swift in Sources */,
|
||||
56AE64142229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */,
|
||||
5613ED3721A95A5C00DC7A68 /* Map.swift in Sources */,
|
||||
56F34FD324B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */,
|
||||
5659F48E1EA8D94E004A4992 /* Utils.swift in Sources */,
|
||||
564CE43321AA901800652B19 /* ValueObserver.swift in Sources */,
|
||||
56CEB5671EAA359A00BFAF62 /* SQLSelectable.swift in Sources */,
|
||||
@@ -2964,8 +2912,8 @@
|
||||
565490D91D5AE252005622CB /* Migration.swift in Sources */,
|
||||
56CEB5001EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
|
||||
5698AD271DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
|
||||
56F896BD24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */,
|
||||
C96C0F2D2084A45A006B2981 /* SQLiteDateParser.swift in Sources */,
|
||||
56012BB1257404E100B4925B /* CommonTableExpression.swift in Sources */,
|
||||
566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */,
|
||||
565490D51D5AE252005622CB /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
|
||||
565490C51D5AE236005622CB /* SerializedDatabase.swift in Sources */,
|
||||
@@ -2973,6 +2921,7 @@
|
||||
5698AC3D1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
|
||||
563EF45D2163309F007DAACD /* Inflections.swift in Sources */,
|
||||
569D6DE0220EF9E100A058A9 /* SQLInterpolation.swift in Sources */,
|
||||
5611620A25757583007AAF99 /* JoinAssociation.swift in Sources */,
|
||||
567ECE512222E431009245CA /* GRDB-5.0.swift in Sources */,
|
||||
565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */,
|
||||
566B91191FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
|
||||
@@ -2993,14 +2942,12 @@
|
||||
565490DA1D5AE252005622CB /* QueryInterfaceRequest.swift in Sources */,
|
||||
563B8FAE24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */,
|
||||
565490CA1D5AE252005622CB /* DatabaseDateComponents.swift in Sources */,
|
||||
56F896AC24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */,
|
||||
565490D01D5AE252005622CB /* NSString.swift in Sources */,
|
||||
565490DF1D5AE252005622CB /* TableDefinition.swift in Sources */,
|
||||
565490B71D5AE236005622CB /* Database.swift in Sources */,
|
||||
5674A6E81F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
|
||||
56E9FACD221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */,
|
||||
5653EB2320944C7C00F46237 /* HasOneAssociation.swift in Sources */,
|
||||
56F34F9B24AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */,
|
||||
565490C01D5AE236005622CB /* DatabaseWriter.swift in Sources */,
|
||||
565490C41D5AE236005622CB /* SchedulingWatchdog.swift in Sources */,
|
||||
566B91311FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */,
|
||||
@@ -3020,12 +2967,10 @@
|
||||
56FBFEDB2210731A00945324 /* SQLRequest.swift in Sources */,
|
||||
56F5ABD91D814330001F60CB /* Data.swift in Sources */,
|
||||
565490D41D5AE252005622CB /* (null) in Sources */,
|
||||
56F34FA624B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */,
|
||||
566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
|
||||
565490B61D5AE236005622CB /* Configuration.swift in Sources */,
|
||||
565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */,
|
||||
56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */,
|
||||
56F896B824B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */,
|
||||
569BBA50229170FA00478429 /* Inflections+English.swift in Sources */,
|
||||
563B8FB724A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
|
||||
566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
@@ -3044,18 +2989,15 @@
|
||||
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 */,
|
||||
56F34FEB24B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */,
|
||||
56781B0D243F86E600650A83 /* Refinable.swift in Sources */,
|
||||
565490CD1D5AE252005622CB /* Date.swift in Sources */,
|
||||
56F34FD824B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */,
|
||||
56F34FE324B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */,
|
||||
56F34FF624B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */,
|
||||
5653EB0820944C7C00F46237 /* SQLForeignKeyRequest.swift in Sources */,
|
||||
565490BE1D5AE236005622CB /* DatabaseValue.swift in Sources */,
|
||||
);
|
||||
@@ -3085,8 +3027,6 @@
|
||||
5636E9BF1D22574100B9B05F /* FetchRequest.swift in Sources */,
|
||||
563EF42E2161180D007DAACD /* AssociationAggregate.swift in Sources */,
|
||||
56BB6EAC1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
|
||||
56F34FEA24B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */,
|
||||
56F34FD724B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */,
|
||||
563B8FC624A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
56300B791C53F592005A543B /* QueryInterfaceRequest.swift in Sources */,
|
||||
5656A8B12295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
|
||||
@@ -3095,13 +3035,13 @@
|
||||
5605F18E1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */,
|
||||
566475D61D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
|
||||
5698AD381DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
|
||||
56012BA8257404E000B4925B /* CommonTableExpression.swift in Sources */,
|
||||
5653EB0A20944C7C00F46237 /* Association.swift in Sources */,
|
||||
56A2387E1B9C75030082EB20 /* Database.swift in Sources */,
|
||||
56CEB4FD1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
|
||||
5605F15A1C672E4000235C62 /* CGFloat.swift in Sources */,
|
||||
56CEB5481EAA359A00BFAF62 /* Column.swift in Sources */,
|
||||
5653EB262094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */,
|
||||
56F896AB24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */,
|
||||
5605F1641C672E4000235C62 /* Date.swift in Sources */,
|
||||
566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
564CE43221AA901800652B19 /* ValueObserver.swift in Sources */,
|
||||
@@ -3117,7 +3057,6 @@
|
||||
5664759D1D97D8A000FF74B8 /* SQLCollection.swift in Sources */,
|
||||
568D13202207213E00674B58 /* SQLQueryGenerator.swift in Sources */,
|
||||
5674048A1CEF84C8003ED5CC /* RowAdapter.swift in Sources */,
|
||||
56F34FE224B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */,
|
||||
563EF416215F87EB007DAACD /* OrderedDictionary.swift in Sources */,
|
||||
563363C51C942C37000BE133 /* DatabaseWriter.swift in Sources */,
|
||||
5698AD1B1DAAD17D0056AF8C /* FTS5Tokenizer.swift in Sources */,
|
||||
@@ -3125,7 +3064,6 @@
|
||||
56B964B41DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
|
||||
563B8FB624A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
|
||||
560A37A81C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
|
||||
56F34FD224B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */,
|
||||
566A841B2041146100E50BFD /* DatabaseSnapshot.swift in Sources */,
|
||||
56CEB54F1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
|
||||
56A238941B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
|
||||
@@ -3134,7 +3072,6 @@
|
||||
56A8C2331D1914540096E9D4 /* UUID.swift in Sources */,
|
||||
560D92411C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */,
|
||||
566475BD1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */,
|
||||
56F3500024B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */,
|
||||
56A238A51B9C753B0082EB20 /* Record.swift in Sources */,
|
||||
5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
|
||||
56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
|
||||
@@ -3149,7 +3086,6 @@
|
||||
5657AB121D10899D006283EF /* URL.swift in Sources */,
|
||||
5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
|
||||
5659F48B1EA8D94E004A4992 /* Utils.swift in Sources */,
|
||||
56F34FA524B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */,
|
||||
56A2387C1B9C75030082EB20 /* Configuration.swift in Sources */,
|
||||
56DAA2DE1DE9C827006E10C8 /* Cursor.swift in Sources */,
|
||||
560A37A51C8F625000949E71 /* DatabasePool.swift in Sources */,
|
||||
@@ -3158,14 +3094,10 @@
|
||||
56A2388C1B9C75030082EB20 /* Statement.swift in Sources */,
|
||||
5659F4931EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
|
||||
56D91AB12205F8AC00770D8D /* SQLQuery.swift in Sources */,
|
||||
56F896BC24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */,
|
||||
56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */,
|
||||
56F896B724B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */,
|
||||
5690C3431D23E82A00E59934 /* Data.swift in Sources */,
|
||||
5674A7001F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
|
||||
5674A6E91F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
|
||||
56F34FF524B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */,
|
||||
56F34F9A24AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */,
|
||||
566B91161FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
|
||||
56FC987B1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */,
|
||||
56A238881B9C75030082EB20 /* Row.swift in Sources */,
|
||||
@@ -3181,6 +3113,7 @@
|
||||
569EF0E3200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */,
|
||||
56A238841B9C75030082EB20 /* DatabaseQueue.swift in Sources */,
|
||||
563B06AC217EF0CC00B38F35 /* ValueObservation.swift in Sources */,
|
||||
5611620925757583007AAF99 /* JoinAssociation.swift in Sources */,
|
||||
56D91AAA2205F2F100770D8D /* DatabasePromise.swift in Sources */,
|
||||
566BE71F2342542F00A8254B /* LockedBox.swift in Sources */,
|
||||
5698AC7B1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */,
|
||||
@@ -3189,6 +3122,7 @@
|
||||
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 */,
|
||||
56FBFED92210731A00945324 /* SQLRequest.swift in Sources */,
|
||||
5644DE6E20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */,
|
||||
@@ -3216,7 +3150,6 @@
|
||||
56D91AA32205E03700770D8D /* SQLRelation.swift in Sources */,
|
||||
564F9C311F07611600877A00 /* DatabaseFunction.swift in Sources */,
|
||||
564CE59E21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */,
|
||||
56F34FCA24B0DD6A007513FC /* SQLSelectableVisitor.swift in Sources */,
|
||||
56B964A01DA51B4C0002DA19 /* FTS5.swift in Sources */,
|
||||
5674A6F01F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */,
|
||||
);
|
||||
@@ -3286,6 +3219,7 @@
|
||||
5698AC4D1DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */,
|
||||
56419C6E24A519A3004967E1 /* DatabaseWriterWritePublisherTests.swift in Sources */,
|
||||
56057C632291C7C600A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */,
|
||||
56012B562573EED100B4925B /* CommonTableExpressionTests.swift in Sources */,
|
||||
56A238681B9C74A90082EB20 /* RecordInitializersTests.swift in Sources */,
|
||||
5656A80022946B34001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */,
|
||||
5615B261222AE1B400061C1C /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */,
|
||||
@@ -3511,6 +3445,7 @@
|
||||
56D496881D81316E008276D7 /* DatabaseValueConversionTests.swift in Sources */,
|
||||
56419C6924A519A2004967E1 /* DatabaseWriterWritePublisherTests.swift in Sources */,
|
||||
56057C622291C7C600A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */,
|
||||
56012B552573EED000B4925B /* CommonTableExpressionTests.swift in Sources */,
|
||||
56D496BA1D813482008276D7 /* DatabaseQueueSchemaCacheTests.swift in Sources */,
|
||||
56D496781D81309E008276D7 /* RecordSubClassTests.swift in Sources */,
|
||||
5656A7FF22946B34001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */,
|
||||
@@ -3679,8 +3614,6 @@
|
||||
AAA4DC77230F1E0600C74B15 /* FetchRequest.swift in Sources */,
|
||||
AAA4DC78230F1E0600C74B15 /* AssociationAggregate.swift in Sources */,
|
||||
AAA4DC79230F1E0600C74B15 /* SchedulingWatchdog.swift in Sources */,
|
||||
56F34FEC24B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */,
|
||||
56F34FD924B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */,
|
||||
563B8FC824A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
AAA4DC7A230F1E0600C74B15 /* QueryInterfaceRequest.swift in Sources */,
|
||||
AAA4DC7B230F1E0600C74B15 /* TableRecord+QueryInterfaceRequest.swift in Sources */,
|
||||
@@ -3689,13 +3622,13 @@
|
||||
AAA4DC7E230F1E0600C74B15 /* SQLCollatedExpression.swift in Sources */,
|
||||
AAA4DC7F230F1E0600C74B15 /* SQLOperators.swift in Sources */,
|
||||
AAA4DC80230F1E0600C74B15 /* FTS5CustomTokenizer.swift in Sources */,
|
||||
56012BB2257404E200B4925B /* CommonTableExpression.swift in Sources */,
|
||||
AAA4DC81230F1E0600C74B15 /* Association.swift in Sources */,
|
||||
AAA4DC82230F1E0600C74B15 /* Database.swift in Sources */,
|
||||
AAA4DC83230F1E0600C74B15 /* FTS3.swift in Sources */,
|
||||
AAA4DC84230F1E0600C74B15 /* CGFloat.swift in Sources */,
|
||||
AAA4DC85230F1E0600C74B15 /* Column.swift in Sources */,
|
||||
AAA4DC86230F1E0600C74B15 /* QueryInterfaceRequest+Association.swift in Sources */,
|
||||
56F896AD24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */,
|
||||
AAA4DC87230F1E0600C74B15 /* Date.swift in Sources */,
|
||||
AAA4DC89230F1E0600C74B15 /* TransactionObserver.swift in Sources */,
|
||||
AAA4DC8A230F1E0600C74B15 /* ValueObserver.swift in Sources */,
|
||||
@@ -3711,7 +3644,6 @@
|
||||
AAA4DC93230F1E0600C74B15 /* SQLCollection.swift in Sources */,
|
||||
AAA4DC94230F1E0600C74B15 /* SQLQueryGenerator.swift in Sources */,
|
||||
AAA4DC95230F1E0600C74B15 /* RowAdapter.swift in Sources */,
|
||||
56F34FE424B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */,
|
||||
AAA4DC96230F1E0600C74B15 /* OrderedDictionary.swift in Sources */,
|
||||
AAA4DC97230F1E0600C74B15 /* DatabaseWriter.swift in Sources */,
|
||||
AAA4DC98230F1E0600C74B15 /* FTS5Tokenizer.swift in Sources */,
|
||||
@@ -3719,7 +3651,6 @@
|
||||
AAA4DC9A230F1E0600C74B15 /* FTS5TokenizerDescriptor.swift in Sources */,
|
||||
563B8FB824A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
|
||||
AAA4DC9B230F1E0600C74B15 /* SerializedDatabase.swift in Sources */,
|
||||
56F34FD424B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */,
|
||||
AAA4DC9C230F1E0600C74B15 /* DatabaseSnapshot.swift in Sources */,
|
||||
AAA4DC9D230F1E0600C74B15 /* SQLExpressible.swift in Sources */,
|
||||
AAA4DC9E230F1E0600C74B15 /* DatabaseMigrator.swift in Sources */,
|
||||
@@ -3728,7 +3659,6 @@
|
||||
AAA4DCA1230F1E0600C74B15 /* UUID.swift in Sources */,
|
||||
AAA4DCA2230F1E0600C74B15 /* DatabaseValueConvertible.swift in Sources */,
|
||||
AAA4DCA3230F1E0600C74B15 /* SQLSpecificExpressible+QueryInterface.swift in Sources */,
|
||||
56F3500224B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */,
|
||||
AAA4DCA4230F1E0600C74B15 /* Record.swift in Sources */,
|
||||
AAA4DCA5230F1E0600C74B15 /* FTS3TokenizerDescriptor.swift in Sources */,
|
||||
AAA4DCA6230F1E0600C74B15 /* FetchableRecord+TableRecord.swift in Sources */,
|
||||
@@ -3743,7 +3673,6 @@
|
||||
AAA4DCAD230F1E0600C74B15 /* URL.swift in Sources */,
|
||||
AAA4DCAE230F1E0600C74B15 /* RequestProtocols.swift in Sources */,
|
||||
AAA4DCAF230F1E0600C74B15 /* Utils.swift in Sources */,
|
||||
56F34FA724B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */,
|
||||
AAA4DCB0230F1E0600C74B15 /* Configuration.swift in Sources */,
|
||||
AAA4DCB1230F1E0600C74B15 /* Cursor.swift in Sources */,
|
||||
AAA4DCB2230F1E0600C74B15 /* DatabasePool.swift in Sources */,
|
||||
@@ -3752,14 +3681,10 @@
|
||||
AAA4DCB5230F1E0600C74B15 /* Statement.swift in Sources */,
|
||||
AAA4DCB6230F1E0600C74B15 /* ReadWriteBox.swift in Sources */,
|
||||
AAA4DCB7230F1E0600C74B15 /* SQLQuery.swift in Sources */,
|
||||
56F896BE24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */,
|
||||
AAA4DCB8230F1E0600C74B15 /* Migration.swift in Sources */,
|
||||
56F896B924B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */,
|
||||
AAA4DCB9230F1E0600C74B15 /* Data.swift in Sources */,
|
||||
AAA4DCBA230F1E0600C74B15 /* FetchableRecord+Decodable.swift in Sources */,
|
||||
AAA4DCBB230F1E0600C74B15 /* DatabaseValueConvertible+Decodable.swift in Sources */,
|
||||
56F34FF724B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */,
|
||||
56F34F9C24AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */,
|
||||
AAA4DCBC230F1E0600C74B15 /* DatabaseCollation.swift in Sources */,
|
||||
AAA4DCBD230F1E0600C74B15 /* SQLExpression+QueryInterface.swift in Sources */,
|
||||
AAA4DCBE230F1E0600C74B15 /* Row.swift in Sources */,
|
||||
@@ -3775,6 +3700,7 @@
|
||||
AAA4DCCB230F1E0600C74B15 /* DatabaseRegion.swift in Sources */,
|
||||
AAA4DCCC230F1E0600C74B15 /* DatabaseQueue.swift in Sources */,
|
||||
AAA4DCCD230F1E0600C74B15 /* ValueObservation.swift in Sources */,
|
||||
5611620B25757583007AAF99 /* JoinAssociation.swift in Sources */,
|
||||
AAA4DCCE230F1E0600C74B15 /* DatabasePromise.swift in Sources */,
|
||||
566BE7212342542F00A8254B /* LockedBox.swift in Sources */,
|
||||
AAA4DCCF230F1E0600C74B15 /* VirtualTableModule.swift in Sources */,
|
||||
@@ -3783,6 +3709,7 @@
|
||||
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 */,
|
||||
AAA4DCD6230F1E0600C74B15 /* SQLRequest.swift in Sources */,
|
||||
AAA4DCD7230F1E0600C74B15 /* DatabaseValueConversion.swift in Sources */,
|
||||
@@ -3810,7 +3737,6 @@
|
||||
AAA4DCEF230F1E0600C74B15 /* SQLRelation.swift in Sources */,
|
||||
AAA4DCF0230F1E0600C74B15 /* DatabaseFunction.swift in Sources */,
|
||||
AAA4DCF1230F1E0600C74B15 /* RemoveDuplicates.swift in Sources */,
|
||||
56F34FCC24B0DD6B007513FC /* SQLSelectableVisitor.swift in Sources */,
|
||||
AAA4DCF2230F1E0600C74B15 /* FTS5.swift in Sources */,
|
||||
AAA4DCF3230F1E0600C74B15 /* DatabaseValueConvertible+Encodable.swift in Sources */,
|
||||
);
|
||||
@@ -3880,6 +3806,7 @@
|
||||
AAA4DD3E230F262000C74B15 /* FTS3RecordTests.swift in Sources */,
|
||||
56419C7324A519A4004967E1 /* DatabaseWriterWritePublisherTests.swift in Sources */,
|
||||
AAA4DD3F230F262000C74B15 /* AssociationHasManyThroughRowScopeTests.swift in Sources */,
|
||||
56012B572573EED100B4925B /* CommonTableExpressionTests.swift in Sources */,
|
||||
AAA4DD41230F262000C74B15 /* RecordInitializersTests.swift in Sources */,
|
||||
AAA4DD42230F262000C74B15 /* ValueObservationQueryInterfaceRequestTests.swift in Sources */,
|
||||
AAA4DD43230F262000C74B15 /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */,
|
||||
@@ -4048,8 +3975,6 @@
|
||||
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */,
|
||||
56D91AB02205F8AC00770D8D /* SQLQuery.swift in Sources */,
|
||||
5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
|
||||
56F34FE924B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */,
|
||||
56F34FD624B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */,
|
||||
563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
5656A8B02295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
|
||||
5613ED4421A95B2C00DC7A68 /* ValueReducer.swift in Sources */,
|
||||
@@ -4058,13 +3983,13 @@
|
||||
563EF44A2161F179007DAACD /* Inflections.swift in Sources */,
|
||||
566B91091FA4C3970012D5B0 /* Database+Statements.swift in Sources */,
|
||||
566B91231FA4CF810012D5B0 /* Database+Schema.swift in Sources */,
|
||||
56012B9F257404DF00B4925B /* CommonTableExpression.swift in Sources */,
|
||||
563B06AB217EF0CC00B38F35 /* ValueObservation.swift in Sources */,
|
||||
56CEB5111EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */,
|
||||
5659F4901EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
|
||||
566A841A2041146100E50BFD /* DatabaseSnapshot.swift in Sources */,
|
||||
569EF0E2200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */,
|
||||
56CEB4F11EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */,
|
||||
56F896AA24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */,
|
||||
56D91AA22205E03700770D8D /* SQLRelation.swift in Sources */,
|
||||
56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */,
|
||||
56AACAA822ACED7100A40F2A /* Fetch.swift in Sources */,
|
||||
@@ -4080,7 +4005,6 @@
|
||||
5605F1591C672E4000235C62 /* CGFloat.swift in Sources */,
|
||||
5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
|
||||
5605F1631C672E4000235C62 /* Date.swift in Sources */,
|
||||
56F34FE124B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */,
|
||||
5605F1711C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
|
||||
56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */,
|
||||
566475CC1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
|
||||
@@ -4088,7 +4012,6 @@
|
||||
563EF415215F87EB007DAACD /* OrderedDictionary.swift in Sources */,
|
||||
563B8FB524A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
|
||||
564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */,
|
||||
56F34FD124B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */,
|
||||
564CE5AC21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
|
||||
5659F4981EA8D989004A4992 /* Pool.swift in Sources */,
|
||||
56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */,
|
||||
@@ -4097,7 +4020,6 @@
|
||||
5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */,
|
||||
567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */,
|
||||
5653EB0320944C7C00F46237 /* BelongsToAssociation.swift in Sources */,
|
||||
56F34FFF24B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */,
|
||||
563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */,
|
||||
569BBA4E229170F800478429 /* Inflections+English.swift in Sources */,
|
||||
5656A81E2295B12F001FF3FF /* SQLAssociation.swift in Sources */,
|
||||
@@ -4112,7 +4034,6 @@
|
||||
560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */,
|
||||
56A8C2301D1914540096E9D4 /* UUID.swift in Sources */,
|
||||
56CEB5011EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
|
||||
56F34FA424B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */,
|
||||
56AE64122229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */,
|
||||
56CEB55A1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */,
|
||||
56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */,
|
||||
@@ -4121,14 +4042,10 @@
|
||||
5653EB0920944C7C00F46237 /* Association.swift in Sources */,
|
||||
56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */,
|
||||
5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
|
||||
56F896BB24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */,
|
||||
56A238A41B9C753B0082EB20 /* Record.swift in Sources */,
|
||||
56F896B624B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */,
|
||||
56CEB5451EAA359A00BFAF62 /* Column.swift in Sources */,
|
||||
5657AB0F1D10899D006283EF /* URL.swift in Sources */,
|
||||
560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */,
|
||||
56F34FF424B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */,
|
||||
56F34F9924AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */,
|
||||
56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */,
|
||||
5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */,
|
||||
56D91AA92205F2F100770D8D /* DatabasePromise.swift in Sources */,
|
||||
@@ -4144,6 +4061,7 @@
|
||||
56FC98781D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */,
|
||||
566BE71E2342542F00A8254B /* LockedBox.swift in Sources */,
|
||||
56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
|
||||
5611620825757583007AAF99 /* JoinAssociation.swift in Sources */,
|
||||
5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */,
|
||||
569D6DDE220EF9E100A058A9 /* SQLInterpolation.swift in Sources */,
|
||||
568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */,
|
||||
@@ -4152,6 +4070,7 @@
|
||||
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 */,
|
||||
@@ -4179,7 +4098,6 @@
|
||||
5644DE6D20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */,
|
||||
5657AAB91D107001006283EF /* NSData.swift in Sources */,
|
||||
560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */,
|
||||
56F34FC924B0DD6A007513FC /* SQLSelectableVisitor.swift in Sources */,
|
||||
56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */,
|
||||
56B9649D1DA51B4C0002DA19 /* FTS5.swift in Sources */,
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1200"
|
||||
LastUpgradeVersion = "1230"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1200"
|
||||
LastUpgradeVersion = "1230"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1200"
|
||||
LastUpgradeVersion = "1230"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1200"
|
||||
LastUpgradeVersion = "1230"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -45,7 +45,7 @@ extension Sequence {
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult: Cursor>(
|
||||
_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult)
|
||||
-> FlattenCursor<MapCursor<AnyCursor<Iterator.Element>, SegmentOfResult>>
|
||||
-> FlattenCursor<MapCursor<AnyCursor<Iterator.Element>, SegmentOfResult>>
|
||||
{
|
||||
AnyCursor(self).flatMap(transform)
|
||||
}
|
||||
@@ -159,7 +159,7 @@ extension Cursor {
|
||||
/// Returns a cursor over the concatenated non-nil results of mapping
|
||||
/// transform over this cursor.
|
||||
public func compactMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?)
|
||||
-> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult>
|
||||
-> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult>
|
||||
{
|
||||
map(transform).filter { $0 != nil }.map { $0! }
|
||||
}
|
||||
@@ -263,8 +263,8 @@ extension Cursor {
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult>(_ transform: @escaping (Element) throws -> SegmentOfResult)
|
||||
-> FlattenCursor<MapCursor<Self, AnyCursor<SegmentOfResult.Element>>>
|
||||
where SegmentOfResult: Sequence
|
||||
-> FlattenCursor<MapCursor<Self, AnyCursor<SegmentOfResult.Element>>>
|
||||
where SegmentOfResult: Sequence
|
||||
{
|
||||
flatMap { try AnyCursor(transform($0)) }
|
||||
}
|
||||
@@ -272,8 +272,8 @@ extension Cursor {
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult>(_ transform: @escaping (Element) throws -> SegmentOfResult)
|
||||
-> FlattenCursor<MapCursor<Self, SegmentOfResult>>
|
||||
where SegmentOfResult: Cursor
|
||||
-> FlattenCursor<MapCursor<Self, SegmentOfResult>>
|
||||
where SegmentOfResult: Cursor
|
||||
{
|
||||
map(transform).joined()
|
||||
}
|
||||
@@ -367,7 +367,7 @@ extension Cursor {
|
||||
public func reduce<Result>(
|
||||
_ initialResult: Result,
|
||||
_ nextPartialResult: (Result, Element) throws -> Result)
|
||||
throws -> Result
|
||||
throws -> Result
|
||||
{
|
||||
var accumulator = initialResult
|
||||
while let element = try next() {
|
||||
@@ -381,7 +381,7 @@ extension Cursor {
|
||||
public func reduce<Result>(
|
||||
into initialResult: Result,
|
||||
_ updateAccumulatingResult: (inout Result, Element) throws -> Void)
|
||||
throws -> Result
|
||||
throws -> Result
|
||||
{
|
||||
var accumulator = initialResult
|
||||
while let element = try next() {
|
||||
|
||||
@@ -35,26 +35,44 @@ extension Database {
|
||||
|
||||
/// Returns whether a table is an internal SQLite table.
|
||||
///
|
||||
/// Those are tables whose name begins with "sqlite_".
|
||||
/// Those are tables whose name begins with `sqlite_` and `pragma_`.
|
||||
///
|
||||
/// For more information, see https://www.sqlite.org/fileformat2.html
|
||||
public func isSQLiteInternalTable(_ tableName: String) -> Bool {
|
||||
public static func isSQLiteInternalTable(_ tableName: String) -> Bool {
|
||||
// https://www.sqlite.org/fileformat2.html#internal_schema_objects
|
||||
// > The names of internal schema objects always begin with "sqlite_"
|
||||
// > and any table, index, view, or trigger whose name begins with
|
||||
// > "sqlite_" is an internal schema object. SQLite prohibits
|
||||
// > applications from creating objects whose names begin with
|
||||
// > "sqlite_".
|
||||
return tableName.starts(with: "sqlite_")
|
||||
tableName.starts(with: "sqlite_") || tableName.starts(with: "pragma_")
|
||||
}
|
||||
|
||||
/// Returns whether a table is an internal SQLite table.
|
||||
///
|
||||
/// Those are tables whose name begins with `sqlite_` and `pragma_`.
|
||||
///
|
||||
/// For more information, see https://www.sqlite.org/fileformat2.html
|
||||
@available(*, deprecated, message: "Use Database.isSQLiteInternalTable(_:) static method instead.")
|
||||
public func isSQLiteInternalTable(_ tableName: String) -> Bool {
|
||||
Self.isSQLiteInternalTable(tableName)
|
||||
}
|
||||
|
||||
/// Returns whether a table is an internal GRDB table.
|
||||
///
|
||||
/// Those are tables whose name begins with "grdb_".
|
||||
public func isGRDBInternalTable(_ tableName: String) -> Bool {
|
||||
public static func isGRDBInternalTable(_ tableName: String) -> Bool {
|
||||
tableName.starts(with: "grdb_")
|
||||
}
|
||||
|
||||
/// Returns whether a table is an internal GRDB table.
|
||||
///
|
||||
/// Those are tables whose name begins with "grdb_".
|
||||
@available(*, deprecated, message: "Use Database.isGRDBInternalTable(_:) static method instead.")
|
||||
public func isGRDBInternalTable(_ tableName: String) -> Bool {
|
||||
Self.isGRDBInternalTable(tableName)
|
||||
}
|
||||
|
||||
/// Returns whether a view exists.
|
||||
public func viewExists(_ name: String) throws -> Bool {
|
||||
try exists(type: .view, name: name)
|
||||
@@ -220,7 +238,7 @@ extension Database {
|
||||
columns.append(column)
|
||||
}
|
||||
return IndexInfo(name: indexName, columns: columns, unique: unique)
|
||||
}
|
||||
}
|
||||
|
||||
if indexes.isEmpty {
|
||||
// PRAGMA index_list doesn't throw any error when table does
|
||||
@@ -239,8 +257,8 @@ extension Database {
|
||||
public func table<T: Sequence>(
|
||||
_ tableName: String,
|
||||
hasUniqueKey columns: T)
|
||||
throws -> Bool
|
||||
where T.Iterator.Element == String
|
||||
throws -> Bool
|
||||
where T.Iterator.Element == String
|
||||
{
|
||||
try columnsForUniqueKey(Array(columns), in: tableName) != nil
|
||||
}
|
||||
@@ -268,9 +286,8 @@ extension Database {
|
||||
.mapping
|
||||
.append((origin: origin, destination: destination, seq: seq))
|
||||
} else {
|
||||
rawForeignKeys.append((
|
||||
destinationTable: table,
|
||||
mapping: [(origin: origin, destination: destination, seq: seq)]))
|
||||
let mapping = [(origin: origin, destination: destination, seq: seq)]
|
||||
rawForeignKeys.append((destinationTable: table, mapping: mapping))
|
||||
previousId = id
|
||||
}
|
||||
}
|
||||
@@ -346,27 +363,54 @@ extension Database {
|
||||
// > column in the primary key for columns that are part of the primary
|
||||
// > key.
|
||||
//
|
||||
// CREATE TABLE players (
|
||||
// sqlite> CREATE TABLE players (
|
||||
// id INTEGER PRIMARY KEY,
|
||||
// firstName TEXT,
|
||||
// lastName TEXT)
|
||||
//
|
||||
// PRAGMA table_info("players")
|
||||
// lastName TEXT);
|
||||
//
|
||||
// sqlite> PRAGMA table_info("players");
|
||||
// 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 |
|
||||
|
||||
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)")
|
||||
//
|
||||
//
|
||||
// PRAGMA table_info does not expose hidden and generated columns. For
|
||||
// that, we need PRAGMA table_xinfo, introduced in SQLite 3.26.0:
|
||||
// https://sqlite.org/releaselog/3_26_0.html
|
||||
//
|
||||
// > PRAGMA schema.table_xinfo(table-name);
|
||||
//
|
||||
// > This pragma returns one row for each column in the named table,
|
||||
// > including hidden columns in virtual tables. The output is the same
|
||||
// > as for PRAGMA table_info except that hidden columns are shown
|
||||
// > rather than being omitted.
|
||||
//
|
||||
// sqlite> PRAGMA table_xinfo("players");
|
||||
// cid | name | type | notnull | dflt_value | pk | hidden
|
||||
// 0 | id | INTEGER | 0 | NULL | 1 | 0
|
||||
// 1 | firstName | TEXT | 0 | NULL | 0 | 0
|
||||
// 2 | lastName | TEXT | 0 | NULL | 0 | 0
|
||||
let columnInfoQuery: String
|
||||
if sqlite3_libversion_number() < 3026000 {
|
||||
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)")
|
||||
}
|
||||
}
|
||||
columnInfoQuery = "PRAGMA table_info(\(tableName.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)"
|
||||
}
|
||||
let columns = try ColumnInfo
|
||||
.fetchAll(self, sql: "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
|
||||
.fetchAll(self, sql: columnInfoQuery)
|
||||
.sorted(by: { $0.cid < $1.cid })
|
||||
if columns.isEmpty {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
@@ -382,8 +426,8 @@ extension Database {
|
||||
func columnsForUniqueKey<T: Sequence>(
|
||||
_ columns: T,
|
||||
in tableName: String)
|
||||
throws -> [String]?
|
||||
where T.Iterator.Element == String
|
||||
throws -> [String]?
|
||||
where T.Iterator.Element == String
|
||||
{
|
||||
let lowercasedColumns = Set(columns.map { $0.lowercased() })
|
||||
if lowercasedColumns.isEmpty {
|
||||
|
||||
@@ -268,7 +268,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
|
||||
let callback = db.busyCallback!
|
||||
return callback(Int(numberOfTries)) ? 1 : 0
|
||||
},
|
||||
},
|
||||
dbPointer)
|
||||
}
|
||||
}
|
||||
@@ -311,7 +311,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
return SQLITE_OK
|
||||
}
|
||||
return authorizer.authorize(actionCode, cString1, cString2, cString3, cString4)
|
||||
},
|
||||
},
|
||||
dbPointer)
|
||||
}
|
||||
|
||||
@@ -355,7 +355,10 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// This method must be called before database deallocation
|
||||
func close() {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
assert(!isClosed)
|
||||
|
||||
if isClosed {
|
||||
return
|
||||
}
|
||||
|
||||
configuration.SQLiteConnectionWillClose?(sqliteConnection)
|
||||
internalStatementCache.clear()
|
||||
@@ -399,7 +402,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
public var maximumStatementArgumentCount: Int {
|
||||
Int(sqlite3_limit(sqliteConnection, SQLITE_LIMIT_VARIABLE_NUMBER, -1))
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
@@ -443,7 +446,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
{ (collationPointer, length1, buffer1, length2, buffer2) -> Int32 in
|
||||
let collation = Unmanaged<DatabaseCollation>.fromOpaque(collationPointer!).takeUnretainedValue()
|
||||
return Int32(collation.function(length1, buffer1, length2, buffer2).rawValue)
|
||||
}, nil)
|
||||
}, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError(DatabaseError(resultCode: code, message: lastErrorMessage).description)
|
||||
@@ -490,7 +493,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT
|
||||
/// Returns a snapshot that must be freed with `sqlite3_snapshot_free`.
|
||||
///
|
||||
///
|
||||
/// See https://www.sqlite.org/c3ref/snapshot.html
|
||||
func takeVersionSnapshot() throws -> UnsafeMutablePointer<sqlite3_snapshot> {
|
||||
var snapshot: UnsafeMutablePointer<sqlite3_snapshot>?
|
||||
@@ -645,18 +648,20 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
switch mask {
|
||||
case SQLITE_TRACE_STMT:
|
||||
if let sqliteStatement = p, let unexpandedSQL = x {
|
||||
let statement = TraceEvent.Statement(impl: .trace_v2(
|
||||
sqliteStatement: OpaquePointer(sqliteStatement),
|
||||
unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)),
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql))
|
||||
let statement = TraceEvent.Statement(
|
||||
impl: .trace_v2(
|
||||
sqliteStatement: OpaquePointer(sqliteStatement),
|
||||
unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)),
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql))
|
||||
trace(TraceEvent.statement(statement))
|
||||
}
|
||||
case SQLITE_TRACE_PROFILE:
|
||||
if let sqliteStatement = p, let durationP = x?.assumingMemoryBound(to: Int64.self) {
|
||||
let statement = TraceEvent.Statement(impl: .trace_v2(
|
||||
sqliteStatement: OpaquePointer(sqliteStatement),
|
||||
unexpandedSQL: nil,
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql))
|
||||
let statement = TraceEvent.Statement(
|
||||
impl: .trace_v2(
|
||||
sqliteStatement: OpaquePointer(sqliteStatement),
|
||||
unexpandedSQL: nil,
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql))
|
||||
let duration = TimeInterval(durationP.pointee) / 1.0e9
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
|
||||
@@ -689,7 +694,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// in the log file
|
||||
@discardableResult
|
||||
public func checkpoint(_ kind: Database.CheckpointMode = .passive, on dbName: String? = "main") throws
|
||||
-> (walFrameCount: Int, checkpointedFrameCount: Int)
|
||||
-> (walFrameCount: Int, checkpointedFrameCount: Int)
|
||||
{
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
var walFrameCount: CInt = -1
|
||||
@@ -811,9 +816,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
return
|
||||
}
|
||||
|
||||
if
|
||||
let updateStatement = statement as? UpdateStatement,
|
||||
updateStatement.releasesDatabaseLock
|
||||
if let updateStatement = statement as? UpdateStatement,
|
||||
updateStatement.releasesDatabaseLock
|
||||
{
|
||||
// Accept statements that release locks:
|
||||
// - COMMIT
|
||||
@@ -860,7 +864,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
func checkForAbortedTransaction(
|
||||
sql: @autoclosure () -> String? = nil,
|
||||
arguments: @autoclosure () -> StatementArguments? = nil)
|
||||
throws
|
||||
throws
|
||||
{
|
||||
if isInsideTransactionBlock && !isInsideTransaction {
|
||||
throw DatabaseError(
|
||||
@@ -1161,13 +1165,13 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
return .commit
|
||||
}
|
||||
},
|
||||
},
|
||||
finally: {
|
||||
// Restore foreign keys if needed
|
||||
if foreignKeysEnabled {
|
||||
try execute(sql: "PRAGMA foreign_keys = ON")
|
||||
}
|
||||
})
|
||||
})
|
||||
#else
|
||||
try DatabaseQueue().backup(to: self)
|
||||
#endif
|
||||
@@ -1179,7 +1183,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
to dbDest: Database,
|
||||
afterBackupInit: (() -> Void)? = nil,
|
||||
afterBackupStep: (() -> Void)? = nil)
|
||||
throws
|
||||
throws
|
||||
{
|
||||
guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", sqliteConnection, "main") else {
|
||||
throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage)
|
||||
@@ -1234,8 +1238,26 @@ extension Database {
|
||||
/// try db.usePassphrase("secret")
|
||||
/// }
|
||||
public func usePassphrase(_ passphrase: String) throws {
|
||||
let data = passphrase.data(using: .utf8)!
|
||||
let code = data.withUnsafeBytes {
|
||||
guard var data = passphrase.data(using: .utf8) else {
|
||||
throw DatabaseError(message: "invalid passphrase")
|
||||
}
|
||||
defer {
|
||||
data.resetBytes(in: 0..<data.count)
|
||||
}
|
||||
try usePassphrase(data)
|
||||
}
|
||||
|
||||
/// Sets the passphrase used to crypt and decrypt an SQLCipher database.
|
||||
///
|
||||
/// Call this method from `Configuration.prepareDatabase`,
|
||||
/// as in the example below:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// try db.usePassphrase(passphraseData)
|
||||
/// }
|
||||
public func usePassphrase(_ passphrase: Data) throws {
|
||||
let code = passphrase.withUnsafeBytes {
|
||||
sqlite3_key(sqliteConnection, $0.baseAddress, Int32($0.count))
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
@@ -1245,6 +1267,17 @@ extension Database {
|
||||
|
||||
/// Changes the passphrase used by an SQLCipher encrypted database.
|
||||
public func changePassphrase(_ passphrase: String) throws {
|
||||
guard var data = passphrase.data(using: .utf8) else {
|
||||
throw DatabaseError(message: "invalid passphrase")
|
||||
}
|
||||
defer {
|
||||
data.resetBytes(in: 0..<data.count)
|
||||
}
|
||||
try changePassphrase(data)
|
||||
}
|
||||
|
||||
/// Changes the passphrase used by an SQLCipher encrypted database.
|
||||
public func changePassphrase(_ passphrase: Data) throws {
|
||||
// FIXME: sqlite3_rekey is discouraged.
|
||||
//
|
||||
// https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320
|
||||
@@ -1255,8 +1288,7 @@ extension Database {
|
||||
// > schema of the original db into the new one:
|
||||
// > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/
|
||||
// swiftlint:disable:previous line_length
|
||||
let data = passphrase.data(using: .utf8)!
|
||||
let code = data.withUnsafeBytes {
|
||||
let code = passphrase.withUnsafeBytes {
|
||||
sqlite3_rekey(sqliteConnection, $0.baseAddress, Int32($0.count))
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
@@ -1478,9 +1510,9 @@ extension Database {
|
||||
enum Impl {
|
||||
case trace_v1(String)
|
||||
case trace_v2(
|
||||
sqliteStatement: SQLiteStatement,
|
||||
unexpandedSQL: UnsafePointer<CChar>?,
|
||||
sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
|
||||
sqliteStatement: SQLiteStatement,
|
||||
unexpandedSQL: UnsafePointer<CChar>?,
|
||||
sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
|
||||
}
|
||||
let impl: Impl
|
||||
|
||||
|
||||
@@ -126,7 +126,7 @@ public final class DatabaseFunction: Hashable {
|
||||
{ definitionP in
|
||||
// Release the function definition
|
||||
Unmanaged<AnyObject>.fromOpaque(definitionP!).release()
|
||||
})
|
||||
})
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
|
||||
@@ -369,7 +369,7 @@ extension DatabasePool: DatabaseReader {
|
||||
} catch {
|
||||
block(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
@@ -414,7 +414,7 @@ extension DatabasePool: DatabaseReader {
|
||||
} catch {
|
||||
block(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a read-only block in a protected dispatch queue,
|
||||
@@ -748,7 +748,7 @@ extension DatabasePool: DatabaseReader {
|
||||
public func writeInTransaction(
|
||||
_ kind: Database.TransactionKind? = nil,
|
||||
_ updates: (Database) throws -> Database.TransactionCompletion)
|
||||
throws
|
||||
throws
|
||||
{
|
||||
try writer.sync { db in
|
||||
try db.inTransaction(kind) {
|
||||
@@ -793,7 +793,7 @@ extension DatabasePool: DatabaseReader {
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
return _addReadOnly(
|
||||
@@ -823,7 +823,7 @@ extension DatabasePool: DatabaseReader {
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> ValueObserver<Reducer> // For testability
|
||||
-> ValueObserver<Reducer> // For testability
|
||||
{
|
||||
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
|
||||
assert(!observation.requiresWriteAccess, "Use _addWriteOnly(observation:) instead")
|
||||
@@ -903,7 +903,7 @@ extension DatabasePool: DatabaseReader {
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#else
|
||||
if scheduler.immediateInitialValue() {
|
||||
|
||||
@@ -349,7 +349,7 @@ extension DatabaseQueue {
|
||||
public func inTransaction(
|
||||
_ kind: Database.TransactionKind? = nil,
|
||||
_ updates: (Database) throws -> Database.TransactionCompletion)
|
||||
throws
|
||||
throws
|
||||
{
|
||||
try writer.sync { db in
|
||||
try db.inTransaction(kind) {
|
||||
@@ -434,7 +434,7 @@ extension DatabaseQueue {
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
return _addReadOnly(
|
||||
|
||||
@@ -223,7 +223,7 @@ public protocol DatabaseReader: AnyObject {
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
-> DatabaseCancellable
|
||||
}
|
||||
|
||||
extension DatabaseReader {
|
||||
@@ -248,7 +248,7 @@ extension DatabaseReader {
|
||||
to dbDest: Database,
|
||||
afterBackupInit: (() -> Void)? = nil,
|
||||
afterBackupStep: (() -> Void)? = nil)
|
||||
throws
|
||||
throws
|
||||
{
|
||||
try read { dbFrom in
|
||||
try dbFrom.backup(
|
||||
@@ -276,7 +276,7 @@ extension DatabaseReader {
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func readPublisher<Output>(
|
||||
value: @escaping (Database) throws -> Output)
|
||||
-> DatabasePublishers.Read<Output>
|
||||
-> DatabasePublishers.Read<Output>
|
||||
{
|
||||
readPublisher(receiveOn: DispatchQueue.main, value: value)
|
||||
}
|
||||
@@ -296,8 +296,8 @@ extension DatabaseReader {
|
||||
public func readPublisher<S, Output>(
|
||||
receiveOn scheduler: S,
|
||||
value: @escaping (Database) throws -> Output)
|
||||
-> DatabasePublishers.Read<Output>
|
||||
where S: Scheduler
|
||||
-> DatabasePublishers.Read<Output>
|
||||
where S: Scheduler
|
||||
{
|
||||
Deferred {
|
||||
Future { fulfill in
|
||||
@@ -349,7 +349,7 @@ extension DatabaseReader {
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
@@ -362,10 +362,9 @@ extension DatabaseReader {
|
||||
} else {
|
||||
var isCancelled = false
|
||||
_weakAsyncRead { dbResult in
|
||||
guard
|
||||
!isCancelled,
|
||||
let dbResult = dbResult
|
||||
else { return }
|
||||
guard !isCancelled,
|
||||
let dbResult = dbResult
|
||||
else { return }
|
||||
|
||||
let result = dbResult.flatMap { db in
|
||||
Result { try observation.fetchValue(db) }
|
||||
@@ -437,7 +436,7 @@ public final class AnyDatabaseReader: DatabaseReader {
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
base._add(
|
||||
observation: observation,
|
||||
|
||||
@@ -89,8 +89,8 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
var tableRegionsIntersection: [String: TableRegion] = [:]
|
||||
for (table, tableRegion) in tableRegions {
|
||||
guard let otherTableRegion = otherTableRegions
|
||||
.first(where: { (otherTable, _) in otherTable == table })?
|
||||
.value else { continue }
|
||||
.first(where: { (otherTable, _) in otherTable == table })?
|
||||
.value else { continue }
|
||||
let tableRegionIntersection = tableRegion.intersection(otherTableRegion)
|
||||
guard !tableRegionIntersection.isEmpty else { continue }
|
||||
tableRegionsIntersection[table] = tableRegionIntersection
|
||||
@@ -164,7 +164,9 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
/// Returns a region which doesn't contain any SQLite internal table.
|
||||
func ignoringInternalSQLiteTables() -> DatabaseRegion {
|
||||
guard let tableRegions = tableRegions else { return .fullDatabase }
|
||||
let filteredRegions = tableRegions.filter { !$0.key.starts(with: "sqlite_") }
|
||||
let filteredRegions = tableRegions.filter {
|
||||
!Database.isSQLiteInternalTable($0.key)
|
||||
}
|
||||
return DatabaseRegion(tableRegions: filteredRegions)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,7 +86,7 @@ extension DatabaseRegionObservation {
|
||||
public func start(
|
||||
in dbWriter: DatabaseWriter,
|
||||
onChange: @escaping (Database) -> Void)
|
||||
throws -> TransactionObserver
|
||||
throws -> TransactionObserver
|
||||
{
|
||||
// Use unsafeReentrantWrite so that observation can start from any
|
||||
// dispatch queue.
|
||||
@@ -103,7 +103,7 @@ extension DatabaseRegionObservation {
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
extension DatabaseRegionObservation {
|
||||
// MARK: - Publishing Impactful Transactions
|
||||
|
||||
|
||||
/// Returns a publisher that tracks changes in a database region.
|
||||
///
|
||||
/// It emits database connections on a protected dispatch queue.
|
||||
@@ -179,7 +179,7 @@ extension DatabasePublishers {
|
||||
}
|
||||
|
||||
private class DatabaseRegionSubscription<Downstream: Subscriber>: Subscription
|
||||
where Downstream.Failure == Error, Downstream.Input == Database
|
||||
where Downstream.Failure == Error, Downstream.Input == Database
|
||||
{
|
||||
private struct WaitingForDemand {
|
||||
let downstream: Downstream
|
||||
@@ -216,9 +216,9 @@ extension DatabasePublishers {
|
||||
downstream: Downstream)
|
||||
{
|
||||
state = .waitingForDemand(WaitingForDemand(
|
||||
downstream: downstream,
|
||||
writer: writer,
|
||||
observation: observation))
|
||||
downstream: downstream,
|
||||
writer: writer,
|
||||
observation: observation))
|
||||
}
|
||||
|
||||
func request(_ demand: Subscribers.Demand) {
|
||||
@@ -230,9 +230,9 @@ extension DatabasePublishers {
|
||||
}
|
||||
do {
|
||||
state = .observing(Observing(
|
||||
downstream: info.downstream,
|
||||
writer: info.writer,
|
||||
remainingDemand: demand))
|
||||
downstream: info.downstream,
|
||||
writer: info.writer,
|
||||
remainingDemand: demand))
|
||||
observer = try info.observation.start(
|
||||
in: info.writer,
|
||||
onChange: { [weak self] in self?.receive($0) })
|
||||
@@ -261,7 +261,7 @@ extension DatabasePublishers {
|
||||
private func receive(_ value: Database) {
|
||||
lock.synchronized {
|
||||
if case let .observing(info) = state,
|
||||
info.remainingDemand > .none
|
||||
info.remainingDemand > .none
|
||||
{
|
||||
let additionalDemand = info.downstream.receive(value)
|
||||
if case var .observing(info) = state {
|
||||
|
||||
@@ -126,7 +126,7 @@ extension DatabaseSnapshot {
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
_addReadOnly(
|
||||
observation: observation,
|
||||
|
||||
@@ -137,6 +137,69 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
|
||||
fatalError("Unexpected SQLite column type: \(type)")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: SQLExpression
|
||||
|
||||
/// :nodoc:
|
||||
public func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
if isNull {
|
||||
// fast path for NULL
|
||||
return "NULL"
|
||||
} else if context.append(arguments: [self]) {
|
||||
// Use statement arguments
|
||||
return "?"
|
||||
} else {
|
||||
// Quoting needed: just use SQLite, which knows better.
|
||||
return try String.fetchOne(context.db, sql: "SELECT QUOTE(?)", arguments: [self])!
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set<Int64>? {
|
||||
if isNull || self == false.databaseValue {
|
||||
// Those requests select no row:
|
||||
// - WHERE NULL
|
||||
// - WHERE 0
|
||||
return []
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Specific boolean checks for null, true, and false
|
||||
/// :nodoc:
|
||||
public func _is(_ test: _SQLBooleanTest) -> SQLExpression {
|
||||
switch storage {
|
||||
case .null:
|
||||
return DatabaseValue.null
|
||||
|
||||
case .int64(let int64) where int64 == 0 || int64 == 1:
|
||||
switch test {
|
||||
case .true:
|
||||
return (int64 == 1).sqlExpression
|
||||
case .false, .falsey:
|
||||
return (int64 == 0).sqlExpression
|
||||
}
|
||||
|
||||
default:
|
||||
switch test {
|
||||
case .true:
|
||||
return SQLExpressionEqual(.equal, self, true.sqlExpression)
|
||||
case .false:
|
||||
return SQLExpressionEqual(.equal, self, false.sqlExpression)
|
||||
case .falsey:
|
||||
return SQLExpressionNot(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public var _isConstantInRequest: Bool { true }
|
||||
|
||||
/// :nodoc:
|
||||
public var _isTrue: Bool { self == true.databaseValue }
|
||||
|
||||
/// :nodoc:
|
||||
public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { self }
|
||||
}
|
||||
|
||||
// MARK: - Hashable & Equatable
|
||||
@@ -219,46 +282,6 @@ extension DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
// SQLExpression
|
||||
extension DatabaseValue {
|
||||
// Specific boolean checks for null, true, and false
|
||||
/// :nodoc:
|
||||
public func _is(_ test: _SQLBooleanTest) -> SQLExpression {
|
||||
switch storage {
|
||||
case .null:
|
||||
return DatabaseValue.null
|
||||
|
||||
case .int64(let int64) where int64 == 0 || int64 == 1:
|
||||
switch test {
|
||||
case .true:
|
||||
return (int64 == 1).sqlExpression
|
||||
case .false, .falsey:
|
||||
return (int64 == 0).sqlExpression
|
||||
}
|
||||
|
||||
default:
|
||||
switch test {
|
||||
case .true:
|
||||
return _SQLExpressionEqual(.equal, self, true.sqlExpression)
|
||||
case .false:
|
||||
return _SQLExpressionEqual(.equal, self, false.sqlExpression)
|
||||
case .falsey:
|
||||
return _SQLExpressionNot(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
self
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _accept<Visitor: _SQLExpressionVisitor>(_ visitor: inout Visitor) throws {
|
||||
try visitor.visit(self)
|
||||
}
|
||||
}
|
||||
|
||||
// CustomStringConvertible
|
||||
extension DatabaseValue {
|
||||
/// :nodoc:
|
||||
|
||||
@@ -82,7 +82,7 @@ func conversionErrorMessage<T>(
|
||||
to: T.Type,
|
||||
from dbValue: DatabaseValue?,
|
||||
conversionContext: ValueConversionContext?)
|
||||
-> String
|
||||
-> String
|
||||
{
|
||||
var message: String
|
||||
var extras: [String] = []
|
||||
@@ -128,7 +128,7 @@ func fatalConversionError<T>(
|
||||
conversionContext: ValueConversionContext?,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
-> Never
|
||||
-> Never
|
||||
{
|
||||
fatalError(
|
||||
conversionErrorMessage(
|
||||
@@ -147,7 +147,7 @@ func fatalConversionError<T>(
|
||||
atColumn columnName: String,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
-> Never
|
||||
-> Never
|
||||
{
|
||||
fatalConversionError(
|
||||
to: T.self,
|
||||
@@ -162,7 +162,7 @@ func fatalConversionError<T>(
|
||||
index: Int32,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
-> Never
|
||||
-> Never
|
||||
{
|
||||
let row = Row(sqliteStatement: sqliteStatement)
|
||||
fatalConversionError(
|
||||
@@ -179,7 +179,7 @@ func fatalConversionError<T>(
|
||||
index: Int32,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
-> Never
|
||||
-> Never
|
||||
{
|
||||
let row = Row(sqliteStatement: sqliteStatement)
|
||||
fatalConversionError(
|
||||
@@ -205,7 +205,7 @@ extension DatabaseValueConvertible {
|
||||
static func decode(
|
||||
from dbValue: DatabaseValue,
|
||||
conversionContext: @autoclosure () -> ValueConversionContext?)
|
||||
-> Self
|
||||
-> Self
|
||||
{
|
||||
if let value = fromDatabaseValue(dbValue) {
|
||||
return value
|
||||
@@ -236,7 +236,7 @@ extension DatabaseValueConvertible {
|
||||
static func decodeIfPresent(
|
||||
from dbValue: DatabaseValue,
|
||||
conversionContext: @autoclosure () -> ValueConversionContext?)
|
||||
-> Self?
|
||||
-> Self?
|
||||
{
|
||||
// Use fromDatabaseValue before checking for null: this allows DatabaseValue to convert NULL to .null.
|
||||
if let value = fromDatabaseValue(dbValue) {
|
||||
@@ -299,7 +299,7 @@ extension Row {
|
||||
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int)
|
||||
-> Value
|
||||
-> Value
|
||||
{
|
||||
impl.fastDecode(type, atUncheckedIndex: index)
|
||||
}
|
||||
@@ -308,7 +308,7 @@ extension Row {
|
||||
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int)
|
||||
-> Value?
|
||||
-> Value?
|
||||
{
|
||||
impl.fastDecodeIfPresent(type, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
@@ -179,7 +179,7 @@ extension DatabaseValueConvertible {
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> DatabaseValueCursor<Self>
|
||||
throws -> DatabaseValueCursor<Self>
|
||||
{
|
||||
try DatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
@@ -199,7 +199,7 @@ extension DatabaseValueConvertible {
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Self]
|
||||
throws -> [Self]
|
||||
{
|
||||
try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -222,7 +222,7 @@ extension DatabaseValueConvertible {
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Self?
|
||||
throws -> Self?
|
||||
{
|
||||
// fetchOne returns nil if there is no row, or if there is a row with a null value
|
||||
let cursor = try NullableDatabaseValueCursor<Self>(statement: statement, arguments: arguments, adapter: adapter)
|
||||
@@ -246,7 +246,7 @@ extension DatabaseValueConvertible where Self: Hashable {
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Self>
|
||||
throws -> Set<Self>
|
||||
{
|
||||
try Set(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -280,7 +280,7 @@ extension DatabaseValueConvertible {
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> DatabaseValueCursor<Self>
|
||||
throws -> DatabaseValueCursor<Self>
|
||||
{
|
||||
try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -301,7 +301,7 @@ extension DatabaseValueConvertible {
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Self]
|
||||
throws -> [Self]
|
||||
{
|
||||
try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -325,7 +325,7 @@ extension DatabaseValueConvertible {
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Self?
|
||||
throws -> Self?
|
||||
{
|
||||
try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -348,7 +348,7 @@ extension DatabaseValueConvertible where Self: Hashable {
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Self>
|
||||
throws -> Set<Self>
|
||||
{
|
||||
try fetchSet(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -536,7 +536,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
{
|
||||
try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
@@ -556,7 +556,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Wrapped?]
|
||||
throws -> [Wrapped?]
|
||||
{
|
||||
try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -578,7 +578,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & Hashable {
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Wrapped?>
|
||||
throws -> Set<Wrapped?>
|
||||
{
|
||||
try Set(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -612,7 +612,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
{
|
||||
try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -633,7 +633,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Wrapped?]
|
||||
throws -> [Wrapped?]
|
||||
{
|
||||
try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -656,7 +656,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & Hashable {
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Wrapped?>
|
||||
throws -> Set<Wrapped?>
|
||||
{
|
||||
try fetchSet(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -685,7 +685,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R)
|
||||
throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
{
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchCursor(request.statement, adapter: request.adapter)
|
||||
|
||||
@@ -317,7 +317,7 @@ extension DatabaseWriter {
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> ValueObserver<Reducer> // For testability
|
||||
-> ValueObserver<Reducer> // For testability
|
||||
{
|
||||
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
|
||||
|
||||
@@ -379,7 +379,7 @@ extension DatabaseWriter {
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func writePublisher<Output>(
|
||||
updates: @escaping (Database) throws -> Output)
|
||||
-> DatabasePublishers.Write<Output>
|
||||
-> DatabasePublishers.Write<Output>
|
||||
{
|
||||
writePublisher(receiveOn: DispatchQueue.main, updates: updates)
|
||||
}
|
||||
@@ -402,18 +402,18 @@ extension DatabaseWriter {
|
||||
public func writePublisher<S, Output>(
|
||||
receiveOn scheduler: S,
|
||||
updates: @escaping (Database) throws -> Output)
|
||||
-> DatabasePublishers.Write<Output>
|
||||
where S: Scheduler
|
||||
-> DatabasePublishers.Write<Output>
|
||||
where S: Scheduler
|
||||
{
|
||||
OnDemandFuture({ fulfill in
|
||||
self.asyncWrite(updates, completion: { _, result in
|
||||
fulfill(result)
|
||||
})
|
||||
})
|
||||
// We don't want users to process emitted values on a
|
||||
// database dispatch queue.
|
||||
.receiveValues(on: scheduler)
|
||||
.eraseToWritePublisher()
|
||||
// We don't want users to process emitted values on a
|
||||
// database dispatch queue.
|
||||
.receiveValues(on: scheduler)
|
||||
.eraseToWritePublisher()
|
||||
}
|
||||
|
||||
/// Returns a Publisher that asynchronously writes into the database.
|
||||
@@ -431,7 +431,7 @@ extension DatabaseWriter {
|
||||
public func writePublisher<T, Output>(
|
||||
updates: @escaping (Database) throws -> T,
|
||||
thenRead value: @escaping (Database, T) throws -> Output)
|
||||
-> DatabasePublishers.Write<Output>
|
||||
-> DatabasePublishers.Write<Output>
|
||||
{
|
||||
writePublisher(receiveOn: DispatchQueue.main, updates: updates, thenRead: value)
|
||||
}
|
||||
@@ -455,8 +455,8 @@ extension DatabaseWriter {
|
||||
receiveOn scheduler: S,
|
||||
updates: @escaping (Database) throws -> T,
|
||||
thenRead value: @escaping (Database, T) throws -> Output)
|
||||
-> DatabasePublishers.Write<Output>
|
||||
where S: Scheduler
|
||||
-> DatabasePublishers.Write<Output>
|
||||
where S: Scheduler
|
||||
{
|
||||
OnDemandFuture({ fulfill in
|
||||
self.asyncWriteWithoutTransaction { db in
|
||||
@@ -475,10 +475,10 @@ extension DatabaseWriter {
|
||||
}
|
||||
}
|
||||
})
|
||||
// We don't want users to process emitted values on a
|
||||
// database dispatch queue.
|
||||
.receiveValues(on: scheduler)
|
||||
.eraseToWritePublisher()
|
||||
// We don't want users to process emitted values on a
|
||||
// database dispatch queue.
|
||||
.receiveValues(on: scheduler)
|
||||
.eraseToWritePublisher()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -647,7 +647,7 @@ public final class AnyDatabaseWriter: DatabaseWriter {
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
base._add(
|
||||
observation: observation,
|
||||
|
||||
@@ -4,8 +4,48 @@
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol _FetchRequest {
|
||||
/// Accepts a visitor
|
||||
func _accept<Visitor: _FetchRequestVisitor>(_ visitor: inout Visitor) throws
|
||||
/// 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
|
||||
@@ -21,25 +61,96 @@ public protocol _FetchRequest {
|
||||
public protocol FetchRequest: _FetchRequest, DatabaseRegionConvertible, SQLExpression, SQLCollection {
|
||||
/// The type that tells how fetched database rows should be interpreted.
|
||||
associatedtype RowDecoder
|
||||
|
||||
/// Returns a PreparedRequest that is ready to be executed.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter singleResult: A hint that a single result row will be
|
||||
/// consumed. Implementations can optionally use it to optimize the
|
||||
/// prepared statement, for example by adding a `LIMIT 1` SQL clause.
|
||||
///
|
||||
/// // Calls makePreparedRequest(db, forSingleResult: true)
|
||||
/// try request.fetchOne(db)
|
||||
///
|
||||
/// // Calls makePreparedRequest(db, forSingleResult: false)
|
||||
/// try request.fetchAll(db)
|
||||
/// - returns: A prepared request.
|
||||
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
|
||||
|
||||
/// Returns the number of rows fetched by the request.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
func fetchCount(_ db: Database) throws -> Int
|
||||
}
|
||||
|
||||
extension FetchRequest {
|
||||
/// :nodoc:
|
||||
public func _qualifiedCollection(with alias: TableAlias) -> SQLCollection {
|
||||
self
|
||||
// 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 func _qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
self
|
||||
public var _collectionExpressions: [SQLExpression]? { nil }
|
||||
|
||||
/// :nodoc:
|
||||
public func _collectionSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
try "("
|
||||
+ _requestSQL(context, forSingleResult: false)
|
||||
+ ")"
|
||||
}
|
||||
|
||||
/// Returns an expression which applies the `IN` SQL operator.
|
||||
public func contains(_ value: SQLExpressible) -> SQLExpression {
|
||||
_SQLExpressionContains(value, self)
|
||||
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
|
||||
|
||||
/// A PreparedRequest is a request that is ready to be executed.
|
||||
public struct PreparedRequest {
|
||||
/// A prepared statement
|
||||
public var statement: SelectStatement
|
||||
|
||||
/// An eventual adapter for rows fetched by the select statement
|
||||
public var adapter: RowAdapter?
|
||||
|
||||
/// Support for eager loading of hasMany associations.
|
||||
var supplementaryFetch: ((Database, [Row]) throws -> Void)?
|
||||
|
||||
init(
|
||||
statement: SelectStatement,
|
||||
adapter: RowAdapter?,
|
||||
supplementaryFetch: ((Database, [Row]) throws -> Void)? = nil)
|
||||
{
|
||||
self.statement = statement
|
||||
self.adapter = adapter
|
||||
self.supplementaryFetch = supplementaryFetch
|
||||
}
|
||||
}
|
||||
|
||||
extension PreparedRequest: Refinable { }
|
||||
|
||||
// MARK: - AdaptedFetchRequest
|
||||
|
||||
extension FetchRequest {
|
||||
@@ -63,9 +174,34 @@ public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
|
||||
self.adapter = adapter
|
||||
}
|
||||
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
try base.fetchCount(db)
|
||||
}
|
||||
|
||||
public func makePreparedRequest(
|
||||
_ db: Database,
|
||||
forSingleResult singleResult: Bool = false)
|
||||
throws -> PreparedRequest
|
||||
{
|
||||
var preparedRequest = try base.makePreparedRequest(db, forSingleResult: singleResult)
|
||||
|
||||
if let baseAdapter = preparedRequest.adapter {
|
||||
preparedRequest.adapter = try ChainedAdapter(first: baseAdapter, second: adapter(db))
|
||||
} else {
|
||||
preparedRequest.adapter = try adapter(db)
|
||||
}
|
||||
|
||||
return preparedRequest
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _accept<Visitor: _FetchRequestVisitor>(_ visitor: inout Visitor) throws {
|
||||
try visitor.visit(self)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,27 +223,55 @@ public struct AnyFetchRequest<RowDecoder>: FetchRequest {
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _accept<Visitor: _FetchRequestVisitor>(_ visitor: inout Visitor) throws {
|
||||
try request._accept(&visitor)
|
||||
public func _selectedColumnCount(_ db: Database) throws -> Int {
|
||||
try request._selectedColumnCount(db)
|
||||
}
|
||||
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
try request.fetchCount(db)
|
||||
}
|
||||
|
||||
public func makePreparedRequest(
|
||||
_ db: Database,
|
||||
forSingleResult singleResult: Bool = false)
|
||||
throws -> PreparedRequest
|
||||
{
|
||||
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 {
|
||||
/// Creates a request that wraps and forwards operations to `request`.
|
||||
public init<Request: FetchRequest>(_ request: Request)
|
||||
where Request.RowDecoder == RowDecoder
|
||||
where Request.RowDecoder == RowDecoder
|
||||
{
|
||||
self.init(request: ConcreteFetchRequestEraser(request: request))
|
||||
}
|
||||
}
|
||||
|
||||
// Class-based type erasure, so that we preserve full type information in
|
||||
// the generic `_accept<Visitor: _FetchRequestVisitor>(_:)`
|
||||
// Class-based type erasure, so that we preserve full type information.
|
||||
private class FetchRequestEraser: FetchRequest {
|
||||
typealias RowDecoder = Void
|
||||
|
||||
func _accept<Visitor: _FetchRequestVisitor>(_ visitor: inout Visitor) throws {
|
||||
fatalError("Abstract Method")
|
||||
func _selectedColumnCount(_ db: Database) throws -> Int {
|
||||
fatalError("subclass must override")
|
||||
}
|
||||
|
||||
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
|
||||
fatalError("subclass must override")
|
||||
}
|
||||
|
||||
func fetchCount(_ db: Database) throws -> Int {
|
||||
fatalError("subclass must override")
|
||||
}
|
||||
|
||||
func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
|
||||
fatalError("subclass must override")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,7 +282,19 @@ private final class ConcreteFetchRequestEraser<Request: FetchRequest>: FetchRequ
|
||||
self.request = request
|
||||
}
|
||||
|
||||
override func _accept<Visitor: _FetchRequestVisitor>(_ visitor: inout Visitor) throws {
|
||||
try request._accept(&visitor)
|
||||
override func _selectedColumnCount(_ db: Database) throws -> Int {
|
||||
try request._selectedColumnCount(db)
|
||||
}
|
||||
|
||||
override func fetchCount(_ db: Database) throws -> Int {
|
||||
try request.fetchCount(db)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
/// :nodoc:
|
||||
public protocol _FetchRequestVisitor {
|
||||
mutating func visit<Base: FetchRequest>(_ request: AdaptedFetchRequest<Base>) throws
|
||||
mutating func visit<RowDecoder>(_ request: QueryInterfaceRequest<RowDecoder>) throws
|
||||
mutating func visit<RowDecoder>(_ request: SQLRequest<RowDecoder>) throws
|
||||
}
|
||||
@@ -2,8 +2,8 @@ import Foundation
|
||||
|
||||
/// A database row.
|
||||
public final class Row: Equatable, Hashable, RandomAccessCollection,
|
||||
ExpressibleByDictionaryLiteral, CustomStringConvertible,
|
||||
CustomDebugStringConvertible
|
||||
ExpressibleByDictionaryLiteral, CustomStringConvertible,
|
||||
CustomDebugStringConvertible
|
||||
{
|
||||
// It is not a violation of the Demeter law when another type uses this
|
||||
// property, which is exposed for optimizations.
|
||||
@@ -123,8 +123,8 @@ public final class Row: Equatable, Hashable, RandomAccessCollection,
|
||||
statement: SelectStatement)
|
||||
{
|
||||
self.init(impl: StatementCopyRowImpl(
|
||||
sqliteStatement: sqliteStatement,
|
||||
columnNames: statement.columnNames))
|
||||
sqliteStatement: sqliteStatement,
|
||||
columnNames: statement.columnNames))
|
||||
}
|
||||
|
||||
init(impl: RowImpl) {
|
||||
@@ -414,8 +414,8 @@ extension Row {
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
@inlinable
|
||||
public subscript<Value, Column>(_ column: Column)
|
||||
-> Value?
|
||||
where
|
||||
-> Value?
|
||||
where
|
||||
Value: DatabaseValueConvertible & StatementColumnConvertible,
|
||||
Column: ColumnExpression
|
||||
{
|
||||
@@ -451,8 +451,8 @@ extension Row {
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
@inlinable
|
||||
public subscript<Value, Column>(_ column: Column)
|
||||
-> Value
|
||||
where
|
||||
-> Value
|
||||
where
|
||||
Value: DatabaseValueConvertible & StatementColumnConvertible,
|
||||
Column: ColumnExpression
|
||||
{
|
||||
@@ -625,8 +625,8 @@ extension Row {
|
||||
/// print(books[0].title)
|
||||
/// // Prints "Moby-Dick"
|
||||
public subscript<Collection>(_ key: String)
|
||||
-> Collection
|
||||
where
|
||||
-> Collection
|
||||
where
|
||||
Collection: RangeReplaceableCollection,
|
||||
Collection.Element: FetchableRecord
|
||||
{
|
||||
@@ -847,7 +847,7 @@ extension Row {
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> RowCursor
|
||||
throws -> RowCursor
|
||||
{
|
||||
try RowCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
@@ -867,7 +867,7 @@ extension Row {
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Row]
|
||||
throws -> [Row]
|
||||
{
|
||||
// The cursor reuses a single mutable row. Return immutable copies.
|
||||
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter).map { $0.copy() })
|
||||
@@ -888,7 +888,7 @@ extension Row {
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Row>
|
||||
throws -> Set<Row>
|
||||
{
|
||||
// The cursor reuses a single mutable row. Return immutable copies.
|
||||
return try Set(fetchCursor(statement, arguments: arguments, adapter: adapter).map { $0.copy() })
|
||||
@@ -909,7 +909,7 @@ extension Row {
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Row?
|
||||
throws -> Row?
|
||||
{
|
||||
let cursor = try fetchCursor(statement, arguments: arguments, adapter: adapter)
|
||||
// Keep cursor alive until we can copy the fetched row
|
||||
@@ -956,7 +956,7 @@ extension Row {
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> RowCursor
|
||||
throws -> RowCursor
|
||||
{
|
||||
try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -981,7 +981,7 @@ extension Row {
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Row]
|
||||
throws -> [Row]
|
||||
{
|
||||
try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -1006,7 +1006,7 @@ extension Row {
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Row>
|
||||
throws -> Set<Row>
|
||||
{
|
||||
try fetchSet(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -1031,7 +1031,7 @@ extension Row {
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Row?
|
||||
throws -> Row?
|
||||
{
|
||||
try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -1650,11 +1650,11 @@ protocol RowImpl {
|
||||
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int)
|
||||
-> Value
|
||||
-> Value
|
||||
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int)
|
||||
-> Value?
|
||||
-> Value?
|
||||
func dataNoCopy(atUncheckedIndex index: Int) -> Data?
|
||||
|
||||
/// Returns the index of the leftmost column that matches *name* (case-insensitive)
|
||||
|
||||
@@ -13,8 +13,10 @@ 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())
|
||||
case subquery(_FetchRequest)
|
||||
// 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)
|
||||
@@ -38,14 +40,14 @@ public struct SQLLiteral {
|
||||
fatalError("Not implemented: turning an SQL parameter into an SQL literal value")
|
||||
}
|
||||
return sql
|
||||
case let .subquery(request):
|
||||
return try request.requestSQL(context, forSingleResult: false)
|
||||
case let .subquery(requestPromise):
|
||||
return try requestPromise.resolve(context.db)._requestSQL(context, forSingleResult: false)
|
||||
case let .expression(expression):
|
||||
return try expression.expressionSQL(context, wrappedInParenthesis: false)
|
||||
return try expression._expressionSQL(context, wrappedInParenthesis: false)
|
||||
case let .selectable(selectable):
|
||||
return try selectable.resultColumnSQL(context)
|
||||
return try selectable._resultColumnSQL(context)
|
||||
case let .orderingTerm(orderingTerm):
|
||||
return try orderingTerm.orderingTermSQL(context)
|
||||
return try orderingTerm._orderingTermSQL(context)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,7 +119,7 @@ public struct SQLLiteral {
|
||||
try elements.map { try $0.sql(context) }.joined()
|
||||
}
|
||||
|
||||
fileprivate func qualified(with alias: TableAlias) -> SQLLiteral {
|
||||
func qualified(with alias: TableAlias) -> SQLLiteral {
|
||||
SQLLiteral(elements: elements.map { $0.qualified(with: alias) })
|
||||
}
|
||||
}
|
||||
@@ -170,15 +172,15 @@ extension SQLLiteral {
|
||||
/// SQLLiteral(sql: "? + ?", arguments: [1, 2]).sqlExpression
|
||||
/// SQLLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]).sqlExpression
|
||||
public var sqlExpression: SQLExpression {
|
||||
_SQLExpressionLiteral(sqlLiteral: self)
|
||||
SQLExpressionLiteral(sqlLiteral: self)
|
||||
}
|
||||
|
||||
var sqlSelectable: SQLSelectable {
|
||||
_SQLSelectionLiteral(sqlLiteral: self)
|
||||
SQLSelectionLiteral(sqlLiteral: self)
|
||||
}
|
||||
|
||||
var sqlOrderingTerm: SQLOrderingTerm {
|
||||
_SQLOrderingLiteral(sqlLiteral: self)
|
||||
SQLOrderingLiteral(sqlLiteral: self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -244,19 +246,40 @@ extension SQLLiteral: ExpressibleByStringInterpolation {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - _SQLExpressionLiteral
|
||||
// MARK: - SQLExpressionLiteral
|
||||
|
||||
/// SQLExpressionLiteral is an expression built from a raw SQL snippet.
|
||||
// TODO: remove public qualifier when GRDB5 fixits are removed.
|
||||
/// `SQLExpressionLiteral` is an expression built from a raw SQL snippet.
|
||||
///
|
||||
/// SQLExpressionLiteral(sql: "1 + 2")
|
||||
/// To build one, use the `SQLiteral.sqlExpression` property:
|
||||
///
|
||||
/// The SQL literal may contain `?` and colon-prefixed arguments:
|
||||
/// let name = "O'Brien"
|
||||
/// let column = Column("name")
|
||||
/// let literal: SQLLiteral = "\(column) = \(name)"
|
||||
/// let expression = literal.sqlExpression
|
||||
///
|
||||
/// SQLExpressionLiteral(sql: "? + ?", arguments: [1, 2])
|
||||
/// SQLExpressionLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2])
|
||||
/// 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 {
|
||||
public struct SQLExpressionLiteral: SQLExpression {
|
||||
let sqlLiteral: SQLLiteral
|
||||
|
||||
// Prefer SQLLiteral.sqlExpression
|
||||
@@ -265,20 +288,25 @@ public struct _SQLExpressionLiteral: SQLExpression {
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
sqlLiteral.qualified(with: alias).sqlExpression
|
||||
public func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
var resultSQL = try sqlLiteral.sql(context)
|
||||
|
||||
if wrappedInParenthesis {
|
||||
resultSQL = "(\(resultSQL))"
|
||||
}
|
||||
|
||||
return resultSQL
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _accept<Visitor: _SQLExpressionVisitor>(_ visitor: inout Visitor) throws {
|
||||
try visitor.visit(self)
|
||||
public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
sqlLiteral.qualified(with: alias).sqlExpression
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - _SQLSelectionLiteral
|
||||
// MARK: - SQLSelectionLiteral
|
||||
|
||||
/// :nodoc:
|
||||
public struct _SQLSelectionLiteral: SQLSelectable {
|
||||
struct SQLSelectionLiteral: SQLSelectable {
|
||||
let sqlLiteral: SQLLiteral
|
||||
|
||||
// Prefer SQLLiteral.sqlSelectable
|
||||
@@ -286,11 +314,7 @@ public struct _SQLSelectionLiteral: SQLSelectable {
|
||||
self.sqlLiteral = sqlLiteral
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _count(distinct: Bool) -> _SQLCount? { nil }
|
||||
|
||||
/// :nodoc:
|
||||
public func _columnCount(_ db: Database) throws -> Int {
|
||||
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. \
|
||||
@@ -298,21 +322,28 @@ public struct _SQLSelectionLiteral: SQLSelectable {
|
||||
""")
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable {
|
||||
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
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _accept<Visitor: _SQLSelectableVisitor>(_ visitor: inout Visitor) throws {
|
||||
try visitor.visit(self)
|
||||
func _resultColumnSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
try sqlLiteral.sql(context)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - _SQLOrderingLiteral
|
||||
// MARK: - SQLOrderingLiteral
|
||||
|
||||
/// :nodoc:
|
||||
public struct _SQLOrderingLiteral: SQLOrderingTerm {
|
||||
struct SQLOrderingLiteral: SQLOrderingTerm {
|
||||
let sqlLiteral: SQLLiteral
|
||||
|
||||
// Prefer SQLLiteral.sqlOrderingTerm
|
||||
@@ -320,21 +351,18 @@ public struct _SQLOrderingLiteral: SQLOrderingTerm {
|
||||
self.sqlLiteral = sqlLiteral
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public var _reversed: SQLOrderingTerm {
|
||||
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.
|
||||
""")
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm {
|
||||
sqlLiteral.qualified(with: alias).sqlOrderingTerm
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _accept<Visitor: _SQLOrderingTermVisitor>(_ visitor: inout Visitor) throws {
|
||||
try visitor.visit(self)
|
||||
}
|
||||
}
|
||||
@@ -102,9 +102,43 @@ public struct SQLRequest<RowDecoder> {
|
||||
}
|
||||
|
||||
extension SQLRequest: FetchRequest {
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
try SQLRequest<Int>("SELECT COUNT(*) FROM (\(self))").fetchOne(db)!
|
||||
}
|
||||
|
||||
public func makePreparedRequest(
|
||||
_ db: Database,
|
||||
forSingleResult singleResult: Bool = false)
|
||||
throws -> PreparedRequest
|
||||
{
|
||||
let context = SQLGenerationContext(db)
|
||||
let sql = try sqlLiteral.sql(context)
|
||||
let statement: SelectStatement
|
||||
switch cache {
|
||||
case .none:
|
||||
statement = try db.makeSelectStatement(sql: sql)
|
||||
case .public?:
|
||||
statement = try db.cachedSelectStatement(sql: sql)
|
||||
case .internal?:
|
||||
statement = try db.internalCachedSelectStatement(sql: sql)
|
||||
}
|
||||
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 _accept<Visitor: _FetchRequestVisitor>(_ visitor: inout Visitor) throws {
|
||||
try visitor.visit(self)
|
||||
public func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
|
||||
try sqlLiteral.sql(context)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ final class SerializedDatabase {
|
||||
schemaCache: DatabaseSchemaCache,
|
||||
defaultLabel: String,
|
||||
purpose: String? = nil)
|
||||
throws
|
||||
throws
|
||||
{
|
||||
// According to https://www.sqlite.org/threadsafe.html
|
||||
//
|
||||
@@ -55,6 +55,12 @@ final class SerializedDatabase {
|
||||
do {
|
||||
try db.setUp()
|
||||
} catch {
|
||||
// Recent versions of the Swift compiler will call the
|
||||
// deinitializer. Older ones won't.
|
||||
// See https://bugs.swift.org/browse/SR-13746 for details.
|
||||
//
|
||||
// So let's close the database now. The deinitializer
|
||||
// will only close the database if needed.
|
||||
db.close()
|
||||
throw error
|
||||
}
|
||||
|
||||
@@ -282,11 +282,11 @@ extension Statement {
|
||||
let statementStart = buffer.baseAddress!
|
||||
var statementEnd: UnsafePointer<Int8>? = nil
|
||||
guard let statement = try self.init(
|
||||
database: db,
|
||||
statementStart: statementStart,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: prepFlags,
|
||||
authorizer: authorizer) else
|
||||
database: db,
|
||||
statementStart: statementStart,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: prepFlags,
|
||||
authorizer: authorizer) else
|
||||
{
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_ERROR,
|
||||
@@ -634,7 +634,7 @@ public final class UpdateStatement: Statement {
|
||||
/// .filter(sql: "score > ?", arguments: [1000])
|
||||
/// .fetchAll(db)
|
||||
public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral
|
||||
ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral
|
||||
{
|
||||
private(set) var values: [DatabaseValue] = []
|
||||
private(set) var namedValues: [String: DatabaseValue] = [:]
|
||||
@@ -714,7 +714,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
/// - parameter sequence: A sequence of (key, value) pairs
|
||||
/// - returns: A StatementArguments.
|
||||
public init<Sequence>(_ sequence: Sequence)
|
||||
where Sequence: Swift.Sequence, Sequence.Element == (String, DatabaseValueConvertible?)
|
||||
where Sequence: Swift.Sequence, Sequence.Element == (String, DatabaseValueConvertible?)
|
||||
{
|
||||
namedValues = Dictionary(uniqueKeysWithValues: sequence.map { ($0.0, $0.1?.databaseValue ?? .null) })
|
||||
}
|
||||
@@ -902,7 +902,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
mutating func extractBindings(
|
||||
forStatement statement: Statement,
|
||||
allowingRemainingValues: Bool)
|
||||
throws -> [DatabaseValue]
|
||||
throws -> [DatabaseValue]
|
||||
{
|
||||
let initialValuesCount = values.count
|
||||
let bindings = try statement.sqliteArgumentNames.map { argumentName -> DatabaseValue in
|
||||
|
||||
@@ -10,7 +10,7 @@ protocol StatementAuthorizer: AnyObject {
|
||||
_ cString2: UnsafePointer<Int8>?,
|
||||
_ cString3: UnsafePointer<Int8>?,
|
||||
_ cString4: UnsafePointer<Int8>?)
|
||||
-> Int32
|
||||
-> Int32
|
||||
}
|
||||
|
||||
/// A class that gathers information about one statement during its compilation.
|
||||
@@ -38,13 +38,13 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
_ cString2: UnsafePointer<Int8>?,
|
||||
_ cString3: UnsafePointer<Int8>?,
|
||||
_ cString4: UnsafePointer<Int8>?)
|
||||
-> Int32
|
||||
-> Int32
|
||||
{
|
||||
// print("""
|
||||
// StatementCompilationAuthorizer: \
|
||||
// \(AuthorizerActionCode(rawValue: actionCode)) \
|
||||
// \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) })
|
||||
// """)
|
||||
// print("""
|
||||
// StatementCompilationAuthorizer: \
|
||||
// \(AuthorizerActionCode(rawValue: actionCode)) \
|
||||
// \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) })
|
||||
// """)
|
||||
|
||||
switch actionCode {
|
||||
case SQLITE_DROP_TABLE, SQLITE_DROP_VTABLE, SQLITE_DROP_TEMP_TABLE,
|
||||
@@ -173,13 +173,13 @@ final class TruncateOptimizationBlocker: StatementAuthorizer {
|
||||
_ cString2: UnsafePointer<Int8>?,
|
||||
_ cString3: UnsafePointer<Int8>?,
|
||||
_ cString4: UnsafePointer<Int8>?)
|
||||
-> Int32
|
||||
-> Int32
|
||||
{
|
||||
// print("""
|
||||
// TruncateOptimizationBlocker: \
|
||||
// \(AuthorizerActionCode(rawValue: actionCode)) \
|
||||
// \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) })
|
||||
// """)
|
||||
// print("""
|
||||
// TruncateOptimizationBlocker: \
|
||||
// \(AuthorizerActionCode(rawValue: actionCode)) \
|
||||
// \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) })
|
||||
// """)
|
||||
return (actionCode == SQLITE_DELETE) ? SQLITE_IGNORE : SQLITE_OK
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,7 +110,7 @@ public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & Sta
|
||||
/// }
|
||||
/// }
|
||||
public final class FastNullableDatabaseValueCursor<Value>: Cursor
|
||||
where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
{
|
||||
@usableFromInline let _statement: SelectStatement
|
||||
@usableFromInline let _columnIndex: Int32
|
||||
@@ -190,7 +190,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> FastDatabaseValueCursor<Self>
|
||||
throws -> FastDatabaseValueCursor<Self>
|
||||
{
|
||||
try FastDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
@@ -210,7 +210,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Self]
|
||||
throws -> [Self]
|
||||
{
|
||||
try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -230,7 +230,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Self?
|
||||
throws -> Self?
|
||||
{
|
||||
// fetchOne returns nil if there is no row, or if there is a row with a null value
|
||||
let cursor = try FastNullableDatabaseValueCursor<Self>(
|
||||
@@ -257,7 +257,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Self>
|
||||
throws -> Set<Self>
|
||||
{
|
||||
try Set(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -291,7 +291,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> FastDatabaseValueCursor<Self>
|
||||
throws -> FastDatabaseValueCursor<Self>
|
||||
{
|
||||
try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -312,7 +312,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Self]
|
||||
throws -> [Self]
|
||||
{
|
||||
try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -333,7 +333,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Self?
|
||||
throws -> Self?
|
||||
{
|
||||
try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -356,7 +356,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Self>
|
||||
throws -> Set<Self>
|
||||
{
|
||||
try fetchSet(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -385,7 +385,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R)
|
||||
throws -> FastDatabaseValueCursor<Self>
|
||||
throws -> FastDatabaseValueCursor<Self>
|
||||
{
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchCursor(request.statement, adapter: request.adapter)
|
||||
@@ -543,7 +543,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> FastNullableDatabaseValueCursor<Wrapped>
|
||||
throws -> FastNullableDatabaseValueCursor<Wrapped>
|
||||
{
|
||||
try FastNullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
@@ -563,7 +563,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Wrapped?]
|
||||
throws -> [Wrapped?]
|
||||
{
|
||||
try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -585,7 +585,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Wrapped?>
|
||||
throws -> Set<Wrapped?>
|
||||
{
|
||||
try Set(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -619,7 +619,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> FastNullableDatabaseValueCursor<Wrapped>
|
||||
throws -> FastNullableDatabaseValueCursor<Wrapped>
|
||||
{
|
||||
try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -640,7 +640,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Wrapped?]
|
||||
throws -> [Wrapped?]
|
||||
{
|
||||
try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -663,7 +663,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Wrapped?>
|
||||
throws -> Set<Wrapped?>
|
||||
{
|
||||
try fetchSet(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
@@ -692,7 +692,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R)
|
||||
throws -> FastNullableDatabaseValueCursor<Wrapped>
|
||||
throws -> FastNullableDatabaseValueCursor<Wrapped>
|
||||
{
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchCursor(request.statement, adapter: request.adapter)
|
||||
@@ -732,7 +732,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
}
|
||||
|
||||
extension FetchRequest
|
||||
where
|
||||
where
|
||||
RowDecoder: _OptionalProtocol,
|
||||
RowDecoder.Wrapped: DatabaseValueConvertible & StatementColumnConvertible
|
||||
{
|
||||
@@ -788,7 +788,7 @@ extension FetchRequest
|
||||
}
|
||||
|
||||
extension FetchRequest
|
||||
where
|
||||
where
|
||||
RowDecoder: _OptionalProtocol,
|
||||
RowDecoder.Wrapped: DatabaseValueConvertible & StatementColumnConvertible & Hashable
|
||||
{
|
||||
|
||||
@@ -77,7 +77,7 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC
|
||||
let optionalComponents = cString.withMemoryRebound(
|
||||
to: Int8.self,
|
||||
capacity: length + 1 /* trailing \0 */) { cString in
|
||||
SQLiteDateParser().components(cString: cString, length: length)
|
||||
SQLiteDateParser().components(cString: cString, length: length)
|
||||
}
|
||||
guard let components = optionalComponents else {
|
||||
fatalConversionError(to: DatabaseDateComponents.self, sqliteStatement: sqliteStatement, index: index)
|
||||
@@ -152,10 +152,10 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC
|
||||
|
||||
return SQLiteDateParser().components(from: string)
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Codable adoption
|
||||
|
||||
|
||||
|
||||
|
||||
/// Creates a new instance by decoding from the given decoder.
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -169,7 +169,7 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC
|
||||
}
|
||||
self = decodedValue
|
||||
}
|
||||
|
||||
|
||||
/// Encodes this value into the given encoder.
|
||||
///
|
||||
/// - parameters:
|
||||
|
||||
@@ -27,7 +27,7 @@ extension DatabaseValueConvertible where Self: ReferenceConvertible, Self.Refere
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible
|
||||
where
|
||||
where
|
||||
Self: Decodable & ReferenceConvertible,
|
||||
Self.ReferenceType: DatabaseValueConvertible
|
||||
{
|
||||
@@ -38,7 +38,7 @@ extension DatabaseValueConvertible
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible
|
||||
where
|
||||
where
|
||||
Self: Encodable & ReferenceConvertible,
|
||||
Self.ReferenceType: DatabaseValueConvertible
|
||||
{
|
||||
|
||||
@@ -16,9 +16,9 @@ extension NSNumber: DatabaseValueConvertible {
|
||||
public var databaseValue: DatabaseValue {
|
||||
// Don't lose precision: store integers that fits in Int64 as Int64
|
||||
if let decimal = self as? NSDecimalNumber,
|
||||
decimal == decimal.rounding(accordingToBehavior: integerRoundingBehavior), // integer
|
||||
decimal.compare(NSDecimalNumber(value: Int64.max)) != .orderedDescending, // decimal <= Int64.max
|
||||
decimal.compare(NSDecimalNumber(value: Int64.min)) != .orderedAscending // decimal >= Int64.min
|
||||
decimal == decimal.rounding(accordingToBehavior: integerRoundingBehavior), // integer
|
||||
decimal.compare(NSDecimalNumber(value: Int64.max)) != .orderedDescending, // decimal <= Int64.max
|
||||
decimal.compare(NSDecimalNumber(value: Int64.min)) != .orderedAscending // decimal >= Int64.min
|
||||
{
|
||||
return int64Value.databaseValue
|
||||
}
|
||||
|
||||
@@ -2,18 +2,7 @@ import Foundation
|
||||
|
||||
// inspired by: http://jordansmith.io/performant-date-parsing/
|
||||
|
||||
class SQLiteDateParser {
|
||||
|
||||
private struct ParserComponents {
|
||||
var year: Int32 = 0
|
||||
var month: Int32 = 0
|
||||
var day: Int32 = 0
|
||||
var hour: Int32 = 0
|
||||
var minute: Int32 = 0
|
||||
var second: Int32 = 0
|
||||
var nanosecond = ContiguousArray<CChar>(repeating: 0, count: 10) // 9 digits, and trailing \0
|
||||
}
|
||||
|
||||
final class SQLiteDateParser {
|
||||
func components(from dateString: String) -> DatabaseDateComponents? {
|
||||
dateString.withCString { cString in
|
||||
components(cString: cString, length: strlen(cString))
|
||||
@@ -29,17 +18,25 @@ class SQLiteDateParser {
|
||||
// "YYYY-..." -> datetime
|
||||
if cString[4] == UInt8(ascii: "-") {
|
||||
var components = DateComponents()
|
||||
return parseDatetimeFormat(cString: cString, length: length, into: &components)
|
||||
.map { DatabaseDateComponents(components, format: $0)
|
||||
var parser = Parser(cString: cString, length: length)
|
||||
guard let format = parseDatetimeFormat(parser: &parser, into: &components),
|
||||
parser.length == 0
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
return DatabaseDateComponents(components, format: format)
|
||||
}
|
||||
|
||||
// "HH-:..." -> time
|
||||
if cString[2] == UInt8(ascii: ":") {
|
||||
var components = DateComponents()
|
||||
return parseTimeFormat(cString: cString, length: length, into: &components)
|
||||
.map { DatabaseDateComponents(components, format: $0)
|
||||
var parser = Parser(cString: cString, length: length)
|
||||
guard let format = parseTimeFormat(parser: &parser, into: &components),
|
||||
parser.length == 0
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
return DatabaseDateComponents(components, format: format)
|
||||
}
|
||||
|
||||
// Invalid
|
||||
@@ -54,35 +51,28 @@ class SQLiteDateParser {
|
||||
// - YYYY-MM-DDTHH:MM:SS
|
||||
// - YYYY-MM-DDTHH:MM:SS.SSS
|
||||
private func parseDatetimeFormat(
|
||||
cString: UnsafePointer<CChar>,
|
||||
length: Int,
|
||||
parser: inout Parser,
|
||||
into components: inout DateComponents)
|
||||
-> DatabaseDateComponents.Format?
|
||||
-> DatabaseDateComponents.Format?
|
||||
{
|
||||
var cString = cString
|
||||
var remainingLength = length
|
||||
|
||||
if remainingLength < 10 { return nil }
|
||||
remainingLength -= 10
|
||||
guard
|
||||
let year = parseNNNN(cString: &cString),
|
||||
parse("-", cString: &cString),
|
||||
let month = parseNN(cString: &cString),
|
||||
parse("-", cString: &cString),
|
||||
let day = parseNN(cString: &cString)
|
||||
else { return nil }
|
||||
guard let year = parser.parseNNNN(),
|
||||
parser.parse("-"),
|
||||
let month = parser.parseNN(),
|
||||
parser.parse("-"),
|
||||
let day = parser.parseNN()
|
||||
else { return nil }
|
||||
|
||||
components.year = year
|
||||
components.month = month
|
||||
components.day = day
|
||||
if remainingLength == 0 { return .YMD }
|
||||
if parser.length == 0 { return .YMD }
|
||||
|
||||
remainingLength -= 1
|
||||
guard parse(" ", cString: &cString) || parse("T", cString: &cString) else {
|
||||
guard parser.parse(" ") || parser.parse("T")
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch parseTimeFormat(cString: cString, length: remainingLength, into: &components) {
|
||||
switch parseTimeFormat(parser: &parser, into: &components) {
|
||||
case .HM: return .YMD_HM
|
||||
case .HMS: return .YMD_HMS
|
||||
case .HMSS: return .YMD_HMSS
|
||||
@@ -94,94 +84,145 @@ class SQLiteDateParser {
|
||||
// - HH:MM:SS
|
||||
// - HH:MM:SS.SSS
|
||||
private func parseTimeFormat(
|
||||
cString: UnsafePointer<CChar>,
|
||||
length: Int,
|
||||
parser: inout Parser,
|
||||
into components: inout DateComponents)
|
||||
-> DatabaseDateComponents.Format?
|
||||
-> DatabaseDateComponents.Format?
|
||||
{
|
||||
var cString = cString
|
||||
var remainingLength = length
|
||||
|
||||
if remainingLength < 5 { return nil }
|
||||
remainingLength -= 5
|
||||
guard
|
||||
let hour = parseNN(cString: &cString),
|
||||
parse(":", cString: &cString),
|
||||
let minute = parseNN(cString: &cString)
|
||||
else { return nil }
|
||||
guard let hour = parser.parseNN(),
|
||||
parser.parse(":"),
|
||||
let minute = parser.parseNN()
|
||||
else { return nil }
|
||||
|
||||
components.hour = hour
|
||||
components.minute = minute
|
||||
if remainingLength == 0 { return .HM }
|
||||
if parser.length == 0 || parseTimeZone(parser: &parser, into: &components) { return .HM }
|
||||
|
||||
if remainingLength < 3 { return nil }
|
||||
remainingLength -= 3
|
||||
guard
|
||||
parse(":", cString: &cString),
|
||||
let second = parseNN(cString: &cString)
|
||||
else { return nil }
|
||||
guard parser.parse(":"),
|
||||
let second = parser.parseNN()
|
||||
else { return nil }
|
||||
|
||||
components.second = second
|
||||
if remainingLength == 0 { return .HMS }
|
||||
if parser.length == 0 || parseTimeZone(parser: &parser, into: &components) { return .HMS }
|
||||
|
||||
if remainingLength < 1 { return nil }
|
||||
remainingLength -= 1
|
||||
guard parse(".", cString: &cString) else { return nil }
|
||||
guard parser.parse(".") else { return nil }
|
||||
|
||||
// Parse three digits
|
||||
// Parse one to three digits
|
||||
// Rationale: https://github.com/groue/GRDB.swift/pull/362
|
||||
remainingLength = min(remainingLength, 3)
|
||||
var nanosecond = 0
|
||||
for _ in 0..<remainingLength {
|
||||
guard parseDigit(cString: &cString, into: &nanosecond) else { return nil }
|
||||
guard parser.parseDigit(into: &nanosecond) else { return nil }
|
||||
if parser.length == 0 || parseTimeZone(parser: &parser, into: &components) {
|
||||
components.nanosecond = nanosecond * 100_000_000
|
||||
return .HMSS
|
||||
}
|
||||
nanosecond *= [1_000_000_000, 100_000_000, 10_000_000, 1_000_000][remainingLength]
|
||||
components.nanosecond = nanosecond
|
||||
guard parser.parseDigit(into: &nanosecond) else { return nil }
|
||||
if parser.length == 0 || parseTimeZone(parser: &parser, into: &components) {
|
||||
components.nanosecond = nanosecond * 10_000_000
|
||||
return .HMSS
|
||||
}
|
||||
guard parser.parseDigit(into: &nanosecond) else { return nil }
|
||||
components.nanosecond = nanosecond * 1_000_000
|
||||
while parser.parseDigit() != nil { }
|
||||
_ = parseTimeZone(parser: &parser, into: &components)
|
||||
return .HMSS
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
private func parseNNNN(cString: inout UnsafePointer<CChar>) -> Int? {
|
||||
var number = 0
|
||||
guard parseDigit(cString: &cString, into: &number)
|
||||
&& parseDigit(cString: &cString, into: &number)
|
||||
&& parseDigit(cString: &cString, into: &number)
|
||||
&& parseDigit(cString: &cString, into: &number)
|
||||
else {
|
||||
return nil
|
||||
private func parseTimeZone(
|
||||
parser: inout Parser,
|
||||
into components: inout DateComponents)
|
||||
-> Bool
|
||||
{
|
||||
if parser.parse("Z") {
|
||||
components.timeZone = TimeZone(secondsFromGMT: 0)
|
||||
return true
|
||||
}
|
||||
return number
|
||||
|
||||
if parser.parse("+"),
|
||||
let hour = parser.parseNN(),
|
||||
parser.parse(":"),
|
||||
let minute = parser.parseNN()
|
||||
{
|
||||
components.timeZone = TimeZone(secondsFromGMT: hour * 3600 + minute * 60)
|
||||
return true
|
||||
}
|
||||
|
||||
if parser.parse("-"),
|
||||
let hour = parser.parseNN(),
|
||||
parser.parse(":"),
|
||||
let minute = parser.parseNN()
|
||||
{
|
||||
components.timeZone = TimeZone(secondsFromGMT: -(hour * 3600 + minute * 60))
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
private func parseNN(cString: inout UnsafePointer<CChar>) -> Int? {
|
||||
var number = 0
|
||||
guard parseDigit(cString: &cString, into: &number)
|
||||
&& parseDigit(cString: &cString, into: &number)
|
||||
else {
|
||||
return nil
|
||||
private struct Parser {
|
||||
var cString: UnsafePointer<CChar>
|
||||
var length: Int
|
||||
|
||||
@inline(__always)
|
||||
private mutating func shift() {
|
||||
cString += 1
|
||||
length -= 1
|
||||
}
|
||||
return number
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
private func parse(_ scalar: Unicode.Scalar, cString: inout UnsafePointer<CChar>) -> Bool {
|
||||
guard cString[0] == UInt8(ascii: scalar) else {
|
||||
return false
|
||||
|
||||
@inline(__always)
|
||||
mutating func parse(_ scalar: Unicode.Scalar) -> Bool {
|
||||
guard length > 0, cString[0] == UInt8(ascii: scalar) else {
|
||||
return false
|
||||
}
|
||||
shift()
|
||||
return true
|
||||
}
|
||||
cString += 1
|
||||
return true
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
private func parseDigit(cString: inout UnsafePointer<CChar>, into number: inout Int) -> Bool {
|
||||
let char = cString[0]
|
||||
let digit = char - CChar(bitPattern: UInt8(ascii: "0"))
|
||||
guard digit >= 0 && digit <= 9 else {
|
||||
return false
|
||||
|
||||
@inline(__always)
|
||||
mutating func parseDigit() -> Int? {
|
||||
guard length > 0 else {
|
||||
return nil
|
||||
}
|
||||
let char = cString[0]
|
||||
let digit = char - CChar(bitPattern: UInt8(ascii: "0"))
|
||||
guard digit >= 0 && digit <= 9 else {
|
||||
return nil
|
||||
}
|
||||
shift()
|
||||
return Int(digit)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
mutating func parseDigit(into number: inout Int) -> Bool {
|
||||
guard let digit = parseDigit() else {
|
||||
return false
|
||||
}
|
||||
number = number * 10 + digit
|
||||
return true
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
mutating func parseNNNN() -> Int? {
|
||||
var number = 0
|
||||
guard parseDigit(into: &number)
|
||||
&& parseDigit(into: &number)
|
||||
&& parseDigit(into: &number)
|
||||
&& parseDigit(into: &number)
|
||||
else {
|
||||
// Don't restore self to initial state because we don't need it
|
||||
return nil
|
||||
}
|
||||
return number
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
mutating func parseNN() -> Int? {
|
||||
var number = 0
|
||||
guard parseDigit(into: &number)
|
||||
&& parseDigit(into: &number)
|
||||
else {
|
||||
// Don't restore self to initial state because we don't need it
|
||||
return nil
|
||||
}
|
||||
return number
|
||||
}
|
||||
cString += 1
|
||||
number = number * 10 + Int(digit)
|
||||
return true
|
||||
}
|
||||
}
|
||||