mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-01 04:38:44 +00:00
Compare commits
499
Commits
dev/tutorial
...
v5.11.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1acf8e4b1e | ||
|
|
042fbe958d | ||
|
|
e4bc3da4d7 | ||
|
|
cc23263897 | ||
|
|
c7e05caf86 | ||
|
|
dabdb0d590 | ||
|
|
14ca47f84d | ||
|
|
d63429ea23 | ||
|
|
87e9a0d0e0 | ||
|
|
d2e7485b02 | ||
|
|
c23d977759 | ||
|
|
0842e11281 | ||
|
|
e6e2536f6b | ||
|
|
86e4adf860 | ||
|
|
c36aa2bfda | ||
|
|
427a00582f | ||
|
|
6f024373b3 | ||
|
|
76f8b5547f | ||
|
|
e60a31f401 | ||
|
|
8846ea3c25 | ||
|
|
d567630966 | ||
|
|
5a04183baf | ||
|
|
8aa640f84b | ||
|
|
42045ad8fb | ||
|
|
0914b56c41 | ||
|
|
33e2c379db | ||
|
|
06763e47d2 | ||
|
|
5f23d97903 | ||
|
|
03a8e03a92 | ||
|
|
987b8a48e5 | ||
|
|
cbc24751d1 | ||
|
|
e0b397fd4e | ||
|
|
c26df67e78 | ||
|
|
ae60de399e | ||
|
|
b06dc5dc77 | ||
|
|
c0c8eec75d | ||
|
|
151a457251 | ||
|
|
fc4b55dd97 | ||
|
|
ba41c22304 | ||
|
|
04c18e3fd6 | ||
|
|
28f2aa1423 | ||
|
|
5ecc069bb4 | ||
|
|
47934cc858 | ||
|
|
0511fec001 | ||
|
|
14b5eea277 | ||
|
|
c7294af809 | ||
|
|
8eff518850 | ||
|
|
48ef691897 | ||
|
|
836432c4ce | ||
|
|
2f3311cd1e | ||
|
|
8f7a2b6a8e | ||
|
|
7ae35068c4 | ||
|
|
6639e9c598 | ||
|
|
e6cdbb156d | ||
|
|
e2c9734df1 | ||
|
|
18e9b1b9aa | ||
|
|
59c4d42076 | ||
|
|
665770c50c | ||
|
|
f36f4aaf74 | ||
|
|
2858b803d0 | ||
|
|
faf100dbba | ||
|
|
8af2b4bf1b | ||
|
|
253c878367 | ||
|
|
f5b1219549 | ||
|
|
eda960de58 | ||
|
|
f0443a63eb | ||
|
|
24b978c3bb | ||
|
|
3d180183a4 | ||
|
|
98930d7f1d | ||
|
|
adc16ea7dc | ||
|
|
79abf62a47 | ||
|
|
4ab7f1cf3e | ||
|
|
cdc7805471 | ||
|
|
7791e300d2 | ||
|
|
8350dced55 | ||
|
|
97221c7bd6 | ||
|
|
eb6895207e | ||
|
|
d93b2f16e4 | ||
|
|
f09a5e105d | ||
|
|
e6f6a11277 | ||
|
|
fe95d07062 | ||
|
|
dc3fac95db | ||
|
|
be0a2c01e1 | ||
|
|
f232dfde27 | ||
|
|
e1dd96603b | ||
|
|
f2296c065a | ||
|
|
096eeffecf | ||
|
|
6bbec1495d | ||
|
|
a60fe170de | ||
|
|
5cd34da6ca | ||
|
|
a4acbf4854 | ||
|
|
c9eb67dae8 | ||
|
|
bf601e6810 | ||
|
|
c45f681813 | ||
|
|
6a2645e0be | ||
|
|
96108a5b9b | ||
|
|
a6e0d47d61 | ||
|
|
8b060e6b09 | ||
|
|
f0a99a9100 | ||
|
|
6cc45202a0 | ||
|
|
368594b051 | ||
|
|
8d4416d02e | ||
|
|
6db245efe5 | ||
|
|
c115b6a92d | ||
|
|
dc40da1ef2 | ||
|
|
374595d89e | ||
|
|
2d05dd488c | ||
|
|
7d0c8c6657 | ||
|
|
ed9fb39982 | ||
|
|
b28f75c5a2 | ||
|
|
1ac364defb | ||
|
|
e19de4e42e | ||
|
|
57cf9b45b6 | ||
|
|
d772e8da3a | ||
|
|
ad48aa6eec | ||
|
|
620eb6f21c | ||
|
|
653837bb02 | ||
|
|
3de6f51427 | ||
|
|
9456fe809d | ||
|
|
e907bc2686 | ||
|
|
e386553c18 | ||
|
|
3b435d018f | ||
|
|
b5de7a907a | ||
|
|
e5bb488b00 | ||
|
|
76852c1f9c | ||
|
|
2f36fc06f5 | ||
|
|
ff576d945c | ||
|
|
0098369e29 | ||
|
|
fb5a3ba388 | ||
|
|
98f398cd75 | ||
|
|
f2dbbee428 | ||
|
|
f54467af3c | ||
|
|
8c361acd7f | ||
|
|
bdfd5ce277 | ||
|
|
120c973e29 | ||
|
|
17ee1debdc | ||
|
|
b154998ae6 | ||
|
|
eedd3af59b | ||
|
|
c5b6325cf6 | ||
|
|
629840f6f2 | ||
|
|
e7ef3e1867 | ||
|
|
32bbee9c8a | ||
|
|
9def48f4f6 | ||
|
|
92d10e2713 | ||
|
|
3d855a6a90 | ||
|
|
d7971d76e7 | ||
|
|
220d221ea6 | ||
|
|
2ce588ad76 | ||
|
|
7050e3cc48 | ||
|
|
fed0b6b136 | ||
|
|
e3674ccdf2 | ||
|
|
046564dab6 | ||
|
|
d6069888b8 | ||
|
|
a9ea79dba9 | ||
|
|
18083165a1 | ||
|
|
1aeb10439f | ||
|
|
1a2de126ce | ||
|
|
d8cb3066a1 | ||
|
|
c3b3d2eeb8 | ||
|
|
52b1727bb3 | ||
|
|
a328349514 | ||
|
|
5666ffb4a7 | ||
|
|
e6ef8740eb | ||
|
|
df6c2e2b05 | ||
|
|
ae7f83dc40 | ||
|
|
1693a706e0 | ||
|
|
af13c91744 | ||
|
|
b5dea2164f | ||
|
|
148897ad73 | ||
|
|
095bfde072 | ||
|
|
fabdb73785 | ||
|
|
f30f970cf2 | ||
|
|
1c2499528c | ||
|
|
766e731bf9 | ||
|
|
b9496a01e1 | ||
|
|
1554c80fdb | ||
|
|
61ee7cc3f7 | ||
|
|
0f481e7867 | ||
|
|
ed3397176a | ||
|
|
5f4c64ceda | ||
|
|
e5a810105a | ||
|
|
a46b2ad127 | ||
|
|
3ccac4098a | ||
|
|
a4e8bbe2da | ||
|
|
52bc7eb7c6 | ||
|
|
e8802fb010 | ||
|
|
885f43dbad | ||
|
|
5dfab017e5 | ||
|
|
35d6ac0041 | ||
|
|
eae64b587a | ||
|
|
fb6ae07722 | ||
|
|
491e17f62e | ||
|
|
f521002e74 | ||
|
|
bbaee79618 | ||
|
|
64951c84d7 | ||
|
|
5996b64469 | ||
|
|
65b2fecdfc | ||
|
|
232086e50e | ||
|
|
8f7feda27c | ||
|
|
6aa6c4d4b5 | ||
|
|
afc360cf78 | ||
|
|
5673d73738 | ||
|
|
4a894f2b43 | ||
|
|
83cd6d1469 | ||
|
|
0b2e5d836f | ||
|
|
b9576aedbe | ||
|
|
2f549d21bf | ||
|
|
4d6958b52a | ||
|
|
588b2677e7 | ||
|
|
66e52eea40 | ||
|
|
975cbaa7e8 | ||
|
|
9e265f7ebc | ||
|
|
37522f3766 | ||
|
|
4980beda69 | ||
|
|
69b9c7331f | ||
|
|
28375f5c1a | ||
|
|
e019617a50 | ||
|
|
8ff0c456dc | ||
|
|
744b0c5661 | ||
|
|
c6003143c4 | ||
|
|
b0545bcfb0 | ||
|
|
3976feb6ab | ||
|
|
002399ff1a | ||
|
|
cdc21531fc | ||
|
|
7afe011b69 | ||
|
|
12809f5891 | ||
|
|
7fd51f440a | ||
|
|
4f0d3b31e1 | ||
|
|
36039fb6a3 | ||
|
|
e66e59cd21 | ||
|
|
a3279c9f63 | ||
|
|
5ed64ea8f8 | ||
|
|
62763ece52 | ||
|
|
c50f698eae | ||
|
|
31e2b01c10 | ||
|
|
7fd786955c | ||
|
|
af13283aa7 | ||
|
|
6a5d196c2d | ||
|
|
6959ac80b5 | ||
|
|
0c4e483e9e | ||
|
|
f9c162b657 | ||
|
|
c0f537c5e6 | ||
|
|
8895d590a0 | ||
|
|
a44c518e31 | ||
|
|
0571d9b3b8 | ||
|
|
c0a3e61253 | ||
|
|
c02901b335 | ||
|
|
ee2d6d8074 | ||
|
|
b51dc81c3a | ||
|
|
47199ed72b | ||
|
|
28bddb04fa | ||
|
|
c34615ced3 | ||
|
|
a5ffc52dbe | ||
|
|
fd61a5f1ea | ||
|
|
0f70e9d9c9 | ||
|
|
d4f1102976 | ||
|
|
1591948c10 | ||
|
|
43de1c24a7 | ||
|
|
481f6e93e5 | ||
|
|
6887441264 | ||
|
|
e017eddf4f | ||
|
|
53d75c37aa | ||
|
|
331990ce33 | ||
|
|
63a52acb34 | ||
|
|
6958a10a08 | ||
|
|
5d14b3d6db | ||
|
|
de0709163c | ||
|
|
8c872fccfc | ||
|
|
46867877fd | ||
|
|
622ecda283 | ||
|
|
5f9911ff0d | ||
|
|
eaf830c05c | ||
|
|
064dec5095 | ||
|
|
89521a7288 | ||
|
|
76d4e38cd1 | ||
|
|
c56a56a2f3 | ||
|
|
02d3518194 | ||
|
|
67892d7cdb | ||
|
|
0e091124a2 | ||
|
|
2402185235 | ||
|
|
f406062b81 | ||
|
|
7bf25925c7 | ||
|
|
8dd8a57de3 | ||
|
|
fa8a8f0b87 | ||
|
|
fa2c489ee4 | ||
|
|
2cb0baf88e | ||
|
|
1ab23dfa52 | ||
|
|
bd29585461 | ||
|
|
f1cd6dbae8 | ||
|
|
a91d9b23e0 | ||
|
|
7eb348cb2a | ||
|
|
ab4ae144ac | ||
|
|
09899e9bcf | ||
|
|
2625653532 | ||
|
|
ea26dea687 | ||
|
|
4a17281bd7 | ||
|
|
e9ba3e6ccc | ||
|
|
9692410e7d | ||
|
|
b69dfb1709 | ||
|
|
4307eedbc0 | ||
|
|
521f9e498a | ||
|
|
e7ce5f13e7 | ||
|
|
55c0abef8b | ||
|
|
9489174b98 | ||
|
|
b086b99821 | ||
|
|
984dea156c | ||
|
|
1297a781fd | ||
|
|
c4f9ddd688 | ||
|
|
fcff9b34ba | ||
|
|
914ad1b882 | ||
|
|
b13922b76e | ||
|
|
f6f4839e07 | ||
|
|
c5aeec3385 | ||
|
|
21b22ab3fb | ||
|
|
39eb57fe64 | ||
|
|
bbacfd5ec1 | ||
|
|
7bbec01dec | ||
|
|
969f28945c | ||
|
|
869f6cb3b3 | ||
|
|
607e53b04e | ||
|
|
051fdb37b6 | ||
|
|
db963cbbb2 | ||
|
|
13120063e0 | ||
|
|
be02e920d2 | ||
|
|
901b9c6fe6 | ||
|
|
64f5e6bdca | ||
|
|
178727fd5b | ||
|
|
791a8ed41b | ||
|
|
d9083a7bf5 | ||
|
|
e355af3584 | ||
|
|
5b39494125 | ||
|
|
4f709e8e4f | ||
|
|
63448fb0bc | ||
|
|
989a0e82eb | ||
|
|
8ba05a011d | ||
|
|
659e6a53bb | ||
|
|
8a7ab17349 | ||
|
|
3113e20f69 | ||
|
|
e44dc8486a | ||
|
|
21a2206443 | ||
|
|
f38c2ff754 | ||
|
|
8ad880e20d | ||
|
|
50cec3fce7 | ||
|
|
c9c652dddc | ||
|
|
edde38837e | ||
|
|
c4443eead8 | ||
|
|
7c023d5c1f | ||
|
|
99a06f1c05 | ||
|
|
0c2b5318bf | ||
|
|
c47316a846 | ||
|
|
529b042b8a | ||
|
|
5aa1184e68 | ||
|
|
a912c5cbe5 | ||
|
|
3753bd8d6d | ||
|
|
a6f7d9ba86 | ||
|
|
fdc47d7158 | ||
|
|
8aa4807f9b | ||
|
|
339fbdf1ce | ||
|
|
ada972d78d | ||
|
|
085c8f5953 | ||
|
|
1f4db99a37 | ||
|
|
076813826f | ||
|
|
fcb6049381 | ||
|
|
4c88d792f0 | ||
|
|
9d64a32814 | ||
|
|
77db650464 | ||
|
|
0e8a42aedc | ||
|
|
8ad096ae35 | ||
|
|
ac436a2770 | ||
|
|
0133ff9056 | ||
|
|
178fb8688a | ||
|
|
0b5f7e960b | ||
|
|
ae3c491661 | ||
|
|
8548d7a727 | ||
|
|
daab7aef2c | ||
|
|
ba9b4db197 | ||
|
|
cab795a4a9 | ||
|
|
b331a715ef | ||
|
|
48e214b4b3 | ||
|
|
65beb24d41 | ||
|
|
e1c7150714 | ||
|
|
cc93f43ee4 | ||
|
|
33174fce8e | ||
|
|
cb8611587c | ||
|
|
6e7555514a | ||
|
|
8b1efb2c80 | ||
|
|
8388486289 | ||
|
|
c3dcd7636e | ||
|
|
464b77bdcd | ||
|
|
fe437fb7e3 | ||
|
|
1a2a6898eb | ||
|
|
de2a37fb89 | ||
|
|
1d5604815d | ||
|
|
4de5059373 | ||
|
|
850040c51e | ||
|
|
eb0983facd | ||
|
|
9e974a4c96 | ||
|
|
609fcf6a6d | ||
|
|
5e61d38272 | ||
|
|
cdbca5d215 | ||
|
|
9bda5fc41b | ||
|
|
04d35381a6 | ||
|
|
1f27e724c9 | ||
|
|
b22afd7f17 | ||
|
|
ed3d1e1ac4 | ||
|
|
4521e6b37d | ||
|
|
42718db49d | ||
|
|
e08df854dd | ||
|
|
f4b7d99aab | ||
|
|
4dd8042894 | ||
|
|
4583bbfa90 | ||
|
|
a655974eb0 | ||
|
|
d4fc1d9566 | ||
|
|
f9b554d00a | ||
|
|
6b733cfc0a | ||
|
|
f0aec27095 | ||
|
|
092b0d0e44 | ||
|
|
d2a22ddd97 | ||
|
|
9c6ff6a1c0 | ||
|
|
a4dca3390a | ||
|
|
ea6a052b73 | ||
|
|
f49fab0cff | ||
|
|
37faf0a1fd | ||
|
|
4b5a6b503a | ||
|
|
2a85b1230b | ||
|
|
3eb17fdbb7 | ||
|
|
5400217bb6 | ||
|
|
71083a5586 | ||
|
|
37279dfad2 | ||
|
|
8be0976bd1 | ||
|
|
7623a96034 | ||
|
|
424df6dee3 | ||
|
|
48b6faa45e | ||
|
|
bac7b6b0e5 | ||
|
|
174766925a | ||
|
|
9d5cb15380 | ||
|
|
284ebbd3ef | ||
|
|
3b6cf4c12b | ||
|
|
2329a5c7b4 | ||
|
|
8f50d70703 | ||
|
|
d2d515658e | ||
|
|
72123494ca | ||
|
|
7b81fd1bff | ||
|
|
5ea7296e7a | ||
|
|
279b00f890 | ||
|
|
01d71d6f35 | ||
|
|
96df69b3fb | ||
|
|
b17fce357d | ||
|
|
37dfd95ae1 | ||
|
|
b834b9876d | ||
|
|
7f48e66fdc | ||
|
|
b7c57dc7f2 | ||
|
|
cb2405a8b9 | ||
|
|
4398777f07 | ||
|
|
6e8285e4ec | ||
|
|
aceaaf24d2 | ||
|
|
64bb63e304 | ||
|
|
a681ccf2b9 | ||
|
|
8c8a25a73b | ||
|
|
d419d23368 | ||
|
|
081500b5ce | ||
|
|
7dd36ecc0f | ||
|
|
10a16ac6f0 | ||
|
|
d7f61fa0f5 | ||
|
|
3665a533cf | ||
|
|
c9332a8c9e | ||
|
|
e40534942c | ||
|
|
de52856cf3 | ||
|
|
0dd345eb91 | ||
|
|
c4620aa587 | ||
|
|
bda63c70bf | ||
|
|
3407715599 | ||
|
|
7eaf579c18 | ||
|
|
488849535e | ||
|
|
15b892af6e | ||
|
|
cceb24a1e5 | ||
|
|
bea454a0b9 | ||
|
|
276fb2d698 | ||
|
|
8e3046b00f | ||
|
|
8a5790ed8b | ||
|
|
fd6f5ec525 | ||
|
|
987d549ff0 | ||
|
|
f57e724ef6 | ||
|
|
920417beb3 | ||
|
|
2a016ac4f5 | ||
|
|
ba3a3f7c38 | ||
|
|
ae6f5dd0f5 | ||
|
|
7914805524 | ||
|
|
5c2f113631 | ||
|
|
d3df3ed5ec | ||
|
|
40389ee102 | ||
|
|
edc8c2aeea | ||
|
|
f9ad87e54f | ||
|
|
a6a10270a0 | ||
|
|
9a1ff5e9a0 | ||
|
|
7151648279 | ||
|
|
921c629a5e | ||
|
|
25b2a0392d | ||
|
|
cb7aa3c14f |
No files matched your search
@@ -0,0 +1,19 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master, development ]
|
||||
pull_request:
|
||||
branches: [ master, development ]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
runs-on: macos-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Build
|
||||
run: swift build -v
|
||||
- name: Run tests
|
||||
run: swift test -v
|
||||
@@ -62,3 +62,5 @@ opt_in_rules:
|
||||
vertical_whitespace:
|
||||
max_empty_lines: 2
|
||||
|
||||
line_length:
|
||||
ignores_urls: true
|
||||
+120
-120
@@ -26,126 +26,6 @@ git:
|
||||
|
||||
jobs:
|
||||
include:
|
||||
|
||||
###########################################
|
||||
## Test GRDB Xcode 12.2
|
||||
|
||||
- name: "Test GRDB Xcode 12.2 - GRDBOSX - Swift 5.3"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
script: make test_framework_GRDBOSX_maxSwift
|
||||
|
||||
- name: "Test GRDB Xcode 12.2 - GRDBOSX - Swift 5.2"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
script: make test_framework_GRDBOSX_minSwift
|
||||
|
||||
- name: "Test GRDB Xcode 12.2 - GRDBWatchOS"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
- name: "Test GRDB Xcode 12.2 - GRDBiOS iOS maxTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
script: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
|
||||
- name: "Test GRDB Xcode 12.2 - GRDBiOS iOS minTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
- name: "Test GRDB Xcode 12.2 - GRDBtvOS maxTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
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.2
|
||||
script: make test_framework_GRDBtvOS_minTarget
|
||||
|
||||
- name: "Test GRDB Xcode 12.2 - SPM"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
script: make test_SPM
|
||||
|
||||
###########################################
|
||||
## Test GRDBCustom Xcode 12.2
|
||||
|
||||
- name: "Test GRDBCustom Xcode 12.2 - GRDBOSX"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
script: make test_framework_GRDBCustomSQLiteOSX
|
||||
|
||||
- name: "Test GRDBCustom Xcode 12.2 - GRDBiOS maxTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
|
||||
|
||||
- name: "Test GRDBCustom Xcode 12.2 - GRDBiOS minTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
|
||||
|
||||
###########################################
|
||||
## Test SQLCipher Xcode 12.2
|
||||
|
||||
- name: "Test SQLCipher Xcode 12.2 - SQLCipher 3"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
script: make test_framework_SQLCipher3
|
||||
|
||||
- name: "Test SQLCipher Xcode 12.2 - SQLCipher 4"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
script: make test_framework_SQLCipher4
|
||||
|
||||
###########################################
|
||||
## Test Installation Xcode 12.2
|
||||
|
||||
# Manual Install
|
||||
- name: "Test Installation Xcode 12.2 - Manual Install"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
script: make test_install_manual
|
||||
|
||||
# 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.2 - CocoaPods Framework"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
script: make test_install_GRDB_CocoaPods_framework
|
||||
|
||||
# CocoaPods Install GRDB
|
||||
- name: "Test Installation Xcode 12.2 - CocoaPods Static"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
script: make test_install_GRDB_CocoaPods_static
|
||||
|
||||
# SPM Install
|
||||
- name: "Test Installation Xcode 12.2 - SPM Package"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
script: make test_install_SPM_Package
|
||||
|
||||
# SPM Install
|
||||
- name: "Test Installation Xcode 12.2 - SPM Package in Xcode Project"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
script: make test_install_SPM_Project
|
||||
|
||||
# Custom SQLite Install
|
||||
- name: "Test Installation Xcode 12.2 - Custom SQLite"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
script: make test_install_customSQLite
|
||||
|
||||
###########################################
|
||||
## Test GRDB Xcode 11.4
|
||||
@@ -159,3 +39,123 @@ jobs:
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
###########################################
|
||||
## Test GRDB Xcode 12.5
|
||||
|
||||
- name: "Test GRDB Xcode 12.5 - GRDBOSX - Swift 5.3"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_GRDBOSX_maxSwift
|
||||
|
||||
- name: "Test GRDB Xcode 12.5 - GRDBOSX - Swift 5.2"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_GRDBOSX_minSwift
|
||||
|
||||
- name: "Test GRDB Xcode 12.5 - GRDBWatchOS"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
- name: "Test GRDB Xcode 12.5 - GRDBiOS iOS maxTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
|
||||
- name: "Test GRDB Xcode 12.5 - GRDBiOS iOS minTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
- name: "Test GRDB Xcode 12.5 - GRDBtvOS maxTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
|
||||
|
||||
- name: "Test GRDB Xcode 12.5 - GRDBtvOS minTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_GRDBtvOS_minTarget
|
||||
|
||||
- name: "Test GRDB Xcode 12.5 - SPM"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.5
|
||||
script: make test_SPM
|
||||
|
||||
###########################################
|
||||
## Test GRDBCustom Xcode 12.5
|
||||
|
||||
- name: "Test GRDBCustom Xcode 12.5 - GRDBOSX"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_GRDBCustomSQLiteOSX
|
||||
|
||||
- name: "Test GRDBCustom Xcode 12.5 - GRDBiOS maxTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
|
||||
|
||||
- name: "Test GRDBCustom Xcode 12.5 - GRDBiOS minTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
|
||||
|
||||
###########################################
|
||||
## Test SQLCipher Xcode 12.5
|
||||
|
||||
- name: "Test SQLCipher Xcode 12.5 - SQLCipher 3"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_SQLCipher3
|
||||
|
||||
- name: "Test SQLCipher Xcode 12.5 - SQLCipher 4"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_SQLCipher4
|
||||
|
||||
###########################################
|
||||
## Test Installation Xcode 12.5
|
||||
|
||||
# Manual Install
|
||||
- name: "Test Installation Xcode 12.5 - Manual Install"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.5
|
||||
script: make test_install_manual
|
||||
|
||||
# Travis is much too slow, and always fail this job
|
||||
# # CocoaPods Lint
|
||||
# - name: "Test Installation Xcode 12.5 - CocoaPods Lint"
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode12.5
|
||||
# script: make test_CocoaPodsLint_GRDB
|
||||
|
||||
# CocoaPods Install GRDB
|
||||
- name: "Test Installation Xcode 12.5 - CocoaPods Framework"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.5
|
||||
script: make test_install_GRDB_CocoaPods_framework
|
||||
|
||||
# CocoaPods Install GRDB
|
||||
- name: "Test Installation Xcode 12.5 - CocoaPods Static"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.5
|
||||
script: make test_install_GRDB_CocoaPods_static
|
||||
|
||||
# SPM Install
|
||||
- name: "Test Installation Xcode 12.5 - SPM Package"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.5
|
||||
script: make test_install_SPM_Package
|
||||
|
||||
# SPM Install
|
||||
- name: "Test Installation Xcode 12.5 - SPM Package in Xcode Project"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.5
|
||||
script: make test_install_SPM_Project
|
||||
|
||||
# Custom SQLite Install
|
||||
- name: "Test Installation Xcode 12.5 - Custom SQLite"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.5
|
||||
script: make test_install_customSQLite
|
||||
@@ -4,6 +4,12 @@ Here is a list of people who were happy to meet GRDB :-)
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/swiftkarim/status/1354753451377483781
|
||||
|
||||
> I cannot recommend GRDB enough. It works well with Swift and eliminates whole classes of potential programming errors that can be made with Core Data. Also being able to use raw SQL queries if needed can be extremely useful!
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/peres/status/1352219836508729346
|
||||
|
||||
> Just the occasional reminder that GRDB and its documentation is the gold standard. That's it.
|
||||
|
||||
+223
@@ -7,6 +7,14 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 5.x Releases
|
||||
|
||||
- `5.11.x` Releases - [5.11.0](#5110)
|
||||
- `5.10.x` Releases - [5.10.0](#5100)
|
||||
- `5.9.x` Releases - [5.9.0](#590)
|
||||
- `5.8.x` Releases - [5.8.0](#580)
|
||||
- `5.7.x` Releases - [5.7.0](#570) | [5.7.1](#571) | [5.7.2](#572) | [5.7.3](#573) | [5.7.4](#574)
|
||||
- `5.6.x` Releases - [5.6.0](#560)
|
||||
- `5.5.x` Releases - [5.5.0](#550)
|
||||
- `5.4.x` Releases - [5.4.0](#540)
|
||||
- `5.3.x` Releases - [5.3.0](#530)
|
||||
- `5.2.x` Releases - [5.2.0](#520)
|
||||
- `5.1.x` Releases - [5.1.0](#510)
|
||||
@@ -68,6 +76,221 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
- [0.110.0](#01100), ...
|
||||
|
||||
---
|
||||
|
||||
## 5.11.0
|
||||
|
||||
Released September 3, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.10.0...v5.11.0)
|
||||
|
||||
- **Fixed**: Version 5.10.0, when embedded as an Xcode project, would enable the FTS5 full-text engine on system versions that do not provide it.
|
||||
- **New**: [#1046](https://github.com/groue/GRDB.swift/pull/1046) by [@groue](https://github.com/groue): Improve performance of by-index row decoding
|
||||
- **New**: [#1029](https://github.com/groue/GRDB.swift/pull/1029) by [@sberrevoets](https://github.com/sberrevoets), [@groue](https://github.com/groue): Column coding strategies for Codable records
|
||||
|
||||
|
||||
## 5.10.0
|
||||
|
||||
Released August 22, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.9.0...v5.10.0)
|
||||
|
||||
- **New**: [#1036](https://github.com/groue/GRDB.swift/pull/1036) by [@groue](https://github.com/groue): Restore minimal CI tests
|
||||
- **New**: [#1037](https://github.com/groue/GRDB.swift/pull/1037) by [@groue](https://github.com/groue): Support BUILD_LIBRARY_FOR_DISTRIBUTION
|
||||
- **New**: [#1038](https://github.com/groue/GRDB.swift/pull/1038) by [@GetToSet](https://github.com/GetToSet): Add match operator in ColumnExpression for FTS5
|
||||
- **New**: With Swift 5.5+, enhance access to `Column.rowID`. Row and PersistenceContainer subscripts now accept `row[.rowID]` and `container[.rowID]` ([SE-0299](https://github.com/apple/swift-evolution/blob/main/proposals/0299-extend-generic-static-member-lookup.md))
|
||||
- **Documentation Update**: A new [Combine and Data Consistency](Documentation/Combine.md#combine-and-data-consistency) chapter explains how to make sure database publishers do not break important database invariants.
|
||||
|
||||
|
||||
## 5.9.0
|
||||
|
||||
Released August 15, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.8.0...v5.9.0)
|
||||
|
||||
- **Fixed**: [#980](https://github.com/groue/GRDB.swift/pull/980) by [@jroselightricks](https://github.com/jroselightricks): Fix spelling
|
||||
- **Fixed**: [#989](https://github.com/groue/GRDB.swift/pull/989) by [@pp5x](https://github.com/pp5x): FTS: add support of ifNotExists in synchronize()
|
||||
- **Fixed**: [#999](https://github.com/groue/GRDB.swift/issues/999): `request(for: association)` no longer crashes when the foreign key contains a NULL value.
|
||||
- **Fixed**: [#1025](https://github.com/groue/GRDB.swift/issues/1025) by [@mattgallagher](https://github.com/mattgallagher): Fix ValueObservation crash
|
||||
- **Fixed**: Fix thread unsafety in `ValueObservation.print()`
|
||||
- **New**: The `selectID()` method is now available for [Identifiable Records](README.md#identifiable-records)
|
||||
- **New**: Cached prepared statements can profit from [SQL Interpolation](Documentation/SQLInterpolation.md):
|
||||
|
||||
```swift
|
||||
let updateStatement = try db.cachedStatement(literal: "INSERT ...")
|
||||
// ~~~~~~~
|
||||
```
|
||||
|
||||
- **New**: [#993](https://github.com/groue/GRDB.swift/pull/993) by [@groue](https://github.com/groue): QueryInterfaceRequest builder with dynamic table/view name
|
||||
- **New**: Types that adopt both `DatabaseValueConvertible` and `Codable` now profit from automatic JSON encoding and decoding.
|
||||
- **New**: [#1010](https://github.com/groue/GRDB.swift/pull/1010) by [@tternes](https://github.com/tternes): Add VACUUM INTO Support
|
||||
- **New**: [#1012](https://github.com/groue/GRDB.swift/pull/1012) by [@ZevEisenberg](https://github.com/ZevEisenberg): Add brackets to urls in doc comments to make them clickable
|
||||
- **New**: [#1019](https://github.com/groue/GRDB.swift/pull/1019) by [@groue](https://github.com/groue): Merge prepared statement types, and introduce statement cursor
|
||||
- **Documentation Update**: The [Requests](README.md#requests) chapter was updated for the new `Table` type that can build requests without any record type.
|
||||
- **Documentation Update**: The [Custom Value Types](README.md#custom-value-types) chapter was extended about the new support for codable value types encoded as JSON arrays or objects.
|
||||
- **Documentation Update**: The [Fetching Methods](README.md#fetching-methods) and [Prepared Statements](README.md#prepared-statements) chapters have been updated for the unique `Statement` class, and the new `Database.allStatements()` method.
|
||||
|
||||
|
||||
## 5.8.0
|
||||
|
||||
Released May 16, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.7.4...v5.8.0)
|
||||
|
||||
- **New**: Support for the `ESCAPE` clause with the `LIKE` operator.
|
||||
- **New**: You can now define an `SQLRequest` without any generic qualifier (which defaults to `Row`):
|
||||
|
||||
```swift
|
||||
let request = SQLRequest("SELECT ...")
|
||||
```
|
||||
- **New**: [#967](https://github.com/groue/GRDB.swift/pull/967) by [@steipete](https://github.com/steipete): Make SelectStatement conform to CustomStringConvertible
|
||||
- **Fixed**: The `DerivableRequest.limit(_:offset:)` method was ill-designed, and removed from the documentation. It is unfortunately impossible to deprecate it without triggering warnings on the legit use cases (on `QueryInterfaceRequest`).
|
||||
- **Fixed**: [#973](https://github.com/groue/GRDB.swift/pull/973): Restore access to attached databases from record types
|
||||
- **Fixed**: [#974](https://github.com/groue/GRDB.swift/pull/974): Provide access to included associations when root table is not selected
|
||||
- **Documentation Update**: A new [Query Interface Organization](Documentation/QueryInterfaceOrganization.md) document reveals the relationship between the various components of the GRDB query builder.
|
||||
|
||||
## 5.7.4
|
||||
|
||||
Released April 11, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.7.3...v5.7.4)
|
||||
|
||||
- **New**: [#953](https://github.com/groue/GRDB.swift/pull/953): Refactor the SwiftUI demo app
|
||||
- **Fixed**: [#955](https://github.com/groue/GRDB.swift/pull/955) by [@steipete](https://github.com/steipete): Robustness of @Query in the SwiftUI demo app
|
||||
- **Fixed**: [#956](https://github.com/groue/GRDB.swift/pull/956): Fix case-sensitivity of region-based database observation
|
||||
- **New**: [#958](https://github.com/groue/GRDB.swift/pull/958) by [@chrisballinger](https://github.com/chrisballinger): Always add userInfo to databaseJSONDecoder and databaseJSONEncoder
|
||||
- **New**: [#960](https://github.com/groue/GRDB.swift/pull/960) by [@MartinP7r](https://github.com/MartinP7r): Add tests for userInfo being applied to database encoder/decoder
|
||||
|
||||
|
||||
## 5.7.3
|
||||
|
||||
Released April 5, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.7.2...v5.7.3)
|
||||
|
||||
- **Fixed**: [#950](https://github.com/groue/GRDB.swift/pull/950) by [@MartinP7r](https://github.com/MartinP7r): Fix memory consumption when encoding JSON columns
|
||||
- **Fixed**: [#951](https://github.com/groue/GRDB.swift/pull/951) by [@alexwlchan](https://github.com/alexwlchan): Fix documentation typo
|
||||
- **Fixed**: [#952](https://github.com/groue/GRDB.swift/pull/952) by [@holsety](https://github.com/holsety): Fix documentation typo
|
||||
- **Documentation Update**: [#953](https://github.com/groue/GRDB.swift/pull/953): Refactor the SwiftUI demo app
|
||||
|
||||
#### 5.7.2
|
||||
|
||||
- **Fixed**: Really fix breaking change and restore `SQLLiteral` as a deprecated alias for `SQL`.
|
||||
|
||||
#### 5.7.1
|
||||
|
||||
- **Fixed**: Fix breaking change and restore `SQLLiteral` as a deprecated alias for `SQL`.
|
||||
|
||||
## 5.7.0
|
||||
|
||||
Released March 28, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.6.0...v5.7.0)
|
||||
|
||||
- **New**: [#947](https://github.com/groue/GRDB.swift/pull/947) by [@chrisballinger](https://github.com/chrisballinger): Allow access to Encoder from KeyedEncodingContainer
|
||||
|
||||
- **New**: Record types that adopt the standard [Identifiable](https://developer.apple.com/documentation/swift/identifiable) protocol have gained type-safe methods that deal with the primary key. For example:
|
||||
|
||||
```swift
|
||||
let player = try Player.fetchOne(db, id: 42)
|
||||
try Player.deleteAll(db, ids: [1, 2, 3])
|
||||
```
|
||||
|
||||
See the new [Identifiable Records](README.md#identifiable-records) documentation chapter for more information.
|
||||
|
||||
- **New**: `SQLLiteral` has more use cases than initialy expected, and is renamed `SQL`.
|
||||
|
||||
- **New**: [`SQL` literal](Documentation/SQLInterpolation.md#sql-literal) can now be directly used as an expression, an ordering term, or a selection item.:
|
||||
|
||||
```swift
|
||||
let name = "O'Brien"
|
||||
let request = Player
|
||||
.select(SQL("id, score"), ...)
|
||||
.filter(SQL("name = \(name)") && ...)
|
||||
.order(SQL("score DESC"), ...)
|
||||
```
|
||||
|
||||
- **New**: Table creation DSL now supports columns and constraints defined with raw SQL String or [SQL literal](Documentation/SQLInterpolation.md#sql-literal):
|
||||
|
||||
```swift
|
||||
try db.create(table: "player") do { t in
|
||||
t.column(sql: "id INTEGER PRIMARY KEY AUTOINCREMENT")
|
||||
t.column(literal: "name TEXT DEFAULT \("Anonymous")")
|
||||
t.constraint(sql: "CHECK (LENGTH(name) > 0)")
|
||||
t.constraint(literal: "CHECK (LENGTH(name) <= \(100))")
|
||||
}
|
||||
```
|
||||
|
||||
- **New**: Prepared statements can profit from [SQL Interpolation](Documentation/SQLInterpolation.md):
|
||||
|
||||
```swift
|
||||
let updateStatement = try db.makeUpdateStatement(literal: "INSERT ...")
|
||||
let selectStatement = try db.makeSelectStatement(literal: "SELECT ...")
|
||||
// ~~~~~~~
|
||||
```
|
||||
|
||||
- **New**: [DatabaseMigrator](Documentation/Migrations.md#asynchronous-migrations) can now asynchronously migrate a database. A Combine publisher is also available.
|
||||
|
||||
- **New**: Added support for the `EXISTS` and `NOT EXISTS` subquery operators. See the updated [SQL Operators](README.md#sql-operators) documentation.
|
||||
|
||||
- **New**: `Foundation.Decimal` can now be stored in the database, and all Foundation number types can be decoded from decimal numbers stored as strings. See the [NSNumber, NSDecimalNumber, and Decimal](README.md#nsnumber-nsdecimalnumber-and-decimal) chapter for details.
|
||||
|
||||
## 5.6.0
|
||||
|
||||
Released March 12, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.5.0...v5.6.0)
|
||||
|
||||
- **Fixed**: [#933](https://github.com/groue/GRDB.swift/pull/933): Fix DatabaseMigrator.eraseDatabaseOnSchemaChange in the context of shared databases
|
||||
|
||||
- **Fixed**: [#934](https://github.com/groue/GRDB.swift/pull/934): Fix a crash in the ValueObservation publisher
|
||||
|
||||
- **New**: [#936](https://github.com/groue/GRDB.swift/pull/936): Complete Associations and the DerivableRequest Protocol
|
||||
|
||||
- **New**: Database cursors can feed more standard Swift collections: `Array(cursor, minimumCapacity: ...)`, `Dictionary(uniqueKeysWithValues: cursor)`, etc (see [Cursors](README.md#cursors)).
|
||||
|
||||
- **Documentation update**: The [Associations Guide](Documentation/AssociationsBasics.md) has gained a new [Further Refinements to Associations](Documentation/AssociationsBasics.md#further-refinements-to-associations) chapter which shows the new association methods brought by [#936](https://github.com/groue/GRDB.swift/pull/936).
|
||||
|
||||
- **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has an updated [Define Record Requests](Documentation/GoodPracticesForDesigningRecordTypes.md#define-record-requests) chapter, now that the `DerivableRequest` protocol has access to `limit`, `distinct`, `group`, `having`, association aggregates, and common table expressions.
|
||||
|
||||
- **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has a new chapter of good practices: [Record Types Hide Intimate Database Details](Documentation/GoodPracticesForDesigningRecordTypes.md#record-types-hide-intimate-database-details).
|
||||
|
||||
- **Documentation update**: A new [Single-Row Tables](Documentation/SingleRowTables.md) guide provides guidance for designing tables that store configuration values, user preferences, and generally some global application state.
|
||||
|
||||
## 5.5.0
|
||||
|
||||
Released March 3, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.4.0...v5.5.0)
|
||||
|
||||
- **New**: You can now define common table expressions without any generic qualifier (which defaults to `Row`):
|
||||
|
||||
```swift
|
||||
let cte = CommonTableExpression(...)
|
||||
```
|
||||
|
||||
The [Common Table Expressions Guide](Documentation/CommonTableExpressions.md) was updated accordingly.
|
||||
|
||||
- **New**: `DatabaseQueue` reading methods are now wrapped in a deferred transaction. This guarantees snapshot isolation in case of concurrent writes performed by external connections, and makes `DatabaseQueue` a type suitable for shared databases.
|
||||
|
||||
- **Fixed**: `DatabaseQueue.read` is now declared `throws` instead of `rethrows`.
|
||||
|
||||
- **Fixed**: [#930](https://github.com/groue/GRDB.swift/pull/930): Fix SQL generation for `COLLATE`, `IN`, `NOT IN`
|
||||
|
||||
## 5.4.0
|
||||
|
||||
Released February 15, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.3.0...v5.4.0)
|
||||
|
||||
- **Breaking Change**: The query interface was refactored and some types such as `SQLExpression` are no longer a protocol.
|
||||
|
||||
This may break some applications that rely on Swift type inference, such as in the following example:
|
||||
|
||||
```swift
|
||||
// No longer compiles
|
||||
let values = [Column("score"), Column("score") + Column("bonus")]
|
||||
```
|
||||
|
||||
The fix is to add an explicit declaration of the desired type:
|
||||
|
||||
```swift
|
||||
// A possible fix
|
||||
let values: [SQLExpressible] = [Column("score"), Column("score") + Column("bonus")]
|
||||
```
|
||||
|
||||
Occurrences of such code breakage should be very rare.
|
||||
|
||||
- **New**: [SQL Interpolation](Documentation/SQLInterpolation.md) supports embedding collations into SQL literals:
|
||||
|
||||
```swift
|
||||
let request: SQLRequest<Player> = "SELECT * FROM player ORDER BY email COLLATION \(.nocase)"
|
||||
let request: SQLRequest<Player> = "SELECT * FROM player ORDER BY name COLLATION \(.localizedCompare)"
|
||||
```
|
||||
|
||||
- **Documentation update**: [Adding support for missing SQL functions or operators](README.md#adding-support-for-missing-sql-functions-or-operators) explains how to extend the query interface when needed.
|
||||
|
||||
- **Documentation update**: The [Demo Applications](Documentation/DemoApps/) now provide tests for the database access layer.
|
||||
|
||||
## 5.3.0
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ GRDB Associations
|
||||
- [Sorting Associations]
|
||||
- [Ordered Associations]
|
||||
- [Columns Selected by an Association]
|
||||
- [Further Refinements to Associations]
|
||||
- [Table Aliases]
|
||||
- [Refining Association Requests]
|
||||
- [Fetching Values from Associations]
|
||||
@@ -88,7 +89,7 @@ struct BookInfo {
|
||||
|
||||
let books = try Book.fetchAll(db)
|
||||
let bookInfos = books.map { book -> BookInfo in
|
||||
let author = try Author.fetchOne(db, key: book.authorId)
|
||||
let author = try Author.fetchOne(db, id: book.authorId)
|
||||
return BookInfo(book: book, author: author)
|
||||
}
|
||||
```
|
||||
@@ -781,6 +782,7 @@ Fetch requests do not visit the database until you fetch values from them. This
|
||||
- [Sorting Associations]
|
||||
- [Ordered Associations]
|
||||
- [Columns Selected by an Association]
|
||||
- [Further Refinements to Associations]
|
||||
- [Table Aliases]
|
||||
- [Refining Association Requests]
|
||||
|
||||
@@ -855,14 +857,18 @@ Before we describe them in detail, let's see a few requests they can build:
|
||||
let request = Author
|
||||
.including(all: Author.books)
|
||||
|
||||
/// All authors with their awarded books
|
||||
let request = Author
|
||||
.including(all: Author.books.having(Book.awards.isEmpty == false))
|
||||
|
||||
/// All books with their respective author
|
||||
let request = Book
|
||||
.including(required: Book.author)
|
||||
|
||||
/// All books with their respective author, sorted by title
|
||||
let request = Book
|
||||
.order(Column("title"))
|
||||
.including(required: Book.author)
|
||||
.order(Column("title"))
|
||||
|
||||
/// All books written by a French author
|
||||
let request = Book
|
||||
@@ -941,7 +947,21 @@ The pattern is always the same: you start from a base request, that you extend w
|
||||
|
||||
Another way to describe the difference is that `required` filters the fetched results in order to discard missing associated records, when `optional` does not filter anything, and lets missing values pass through.
|
||||
|
||||
Finally, readers who speak SQL may compare `optional` with left joins, and `required` with inner joins.
|
||||
Finally, readers who speak SQL may compare `optional` with left joins, and `required` with inner joins:
|
||||
|
||||
```swift
|
||||
// SELECT book.* FROM book LEFT JOIN author ON author.id = book.authorID
|
||||
Book.joining(optional: Book.author)
|
||||
|
||||
// SELECT book.* FROM book JOIN author ON author.id = book.authorID
|
||||
Book.joining(required: Book.author)
|
||||
|
||||
// SELECT book.*, author.* FROM book LEFT JOIN author ON author.id = book.authorID
|
||||
Book.including(optional: Book.author)
|
||||
|
||||
// SELECT book.*, author.* FROM book JOIN author ON author.id = book.authorID
|
||||
Book.including(required: Book.author)
|
||||
```
|
||||
|
||||
|
||||
## Combining Associations
|
||||
@@ -1044,7 +1064,7 @@ let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
|
||||
|
||||
**You can filter associated records.**
|
||||
|
||||
The `filter(_:)`, `filter(key:)` and `filter(keys:)` methods, that you already know for [filtering simple requests](../README.md#requests), can filter associated records as well:
|
||||
The `filter(_:)`, `filter(id:)`, `filter(ids:)`, `filter(key:)` and `filter(keys:)` methods, that you already know for [filtering simple requests](../README.md#requests), can filter associated records as well:
|
||||
|
||||
```swift
|
||||
// SELECT book.*
|
||||
@@ -1221,7 +1241,6 @@ let teamInfos = try Team
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
|
||||
## Columns Selected by an Association
|
||||
|
||||
By default, associated records include all their columns:
|
||||
@@ -1248,6 +1267,104 @@ let request = Book.including(required: restrictedAuthor)
|
||||
To specify the default selection for all inclusions of a given type, see [Columns Selected by a Request](../README.md#columns-selected-by-a-request).
|
||||
|
||||
|
||||
## Further Refinements to Associations
|
||||
|
||||
Associations support more refinements:
|
||||
|
||||
- `distinct`
|
||||
|
||||
Fetch all authors with the kinds of books they write (novels, poems, plays, etc):
|
||||
|
||||
```swift
|
||||
struct AuthorInfo: Decodable, FetchableRecord {
|
||||
var author: Author
|
||||
var bookKinds: Set<Book.Kind>
|
||||
}
|
||||
|
||||
let distinctBookKinds = Author.books
|
||||
.select(Column("kind"))
|
||||
.distinct()
|
||||
.forKey("bookKinds")
|
||||
|
||||
let authorInfos: [AuthorInfo] = try Author
|
||||
.including(all: distinctBookKinds)
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
- `group`, `having`
|
||||
|
||||
Fetch all authors with the year of their latest book for each kind (novels, poems, plays, etc):
|
||||
|
||||
```swift
|
||||
struct BookKindInfo: Decodable {
|
||||
var kind: Book.Kind
|
||||
var maxYear: Int
|
||||
}
|
||||
|
||||
struct AuthorInfo: Decodable, FetchableRecord {
|
||||
var author: Author
|
||||
var bookKindInfos: [BookKindInfo]
|
||||
}
|
||||
|
||||
let bookKindInfos = Author.books
|
||||
.select(
|
||||
Column("kind"),
|
||||
max(Column("year")).forKey("maxYear"))
|
||||
.group(Column("kind"))
|
||||
.forKey("bookKindInfos")
|
||||
|
||||
let authorInfos: [AuthorInfo] = try Author
|
||||
.including(all: bookKindInfos)
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
- [Association Aggregates]
|
||||
|
||||
Fetch all authors with their awarded books:
|
||||
|
||||
```swift
|
||||
struct AuthorInfo: FetchableRecord, Decodable {
|
||||
var author: Author
|
||||
var awardedBooks: [Book]
|
||||
}
|
||||
|
||||
let awardedBooks = Author.books
|
||||
.having(Book.awards.isEmpty == false)
|
||||
.forKey("awardedBooks")
|
||||
|
||||
let authorInfos: [AuthorInfo] = try Author
|
||||
.including(all: awardedBooks)
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
- [Common Table Expressions]
|
||||
|
||||
Association can use their own CTEs:
|
||||
|
||||
```swift
|
||||
struct AuthorInfo: FetchableRecord, Decodable {
|
||||
var author: Author
|
||||
var specialBooks: [Book]
|
||||
}
|
||||
|
||||
let specialCTE = CommonTableExpression(...)
|
||||
let specialBooks = Author.books
|
||||
.with(specialCTE)
|
||||
... // use the CTE in the book association
|
||||
.forKey("specialBooks")
|
||||
|
||||
let authorInfos = try Author
|
||||
.including(all: specialBooks)
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
> :warning: **Warning**: associations refined with `limit`, `distinct`, `group`, `having`, or association aggregates can only be used with `including(all:)`. You will get a fatal error if you use them with other joining methods: `including(required:)`, etc.
|
||||
|
||||
|
||||
## Table Aliases
|
||||
|
||||
In all examples we have seen so far, all associated records are joined, included, filtered, and sorted independently. We could not filter them on conditions that involve several records, for example.
|
||||
@@ -2433,6 +2550,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
[Choosing Between BelongsTo and HasOne]: #choosing-between-belongsto-and-hasone
|
||||
[Self Joins]: #self-joins
|
||||
[Ordered Associations]: #ordered-associations
|
||||
[Further Refinements to Associations]: #further-refinements-to-associations
|
||||
[The Types of Associations]: #the-types-of-associations
|
||||
[FetchableRecord]: ../README.md#fetchablerecord-protocols
|
||||
[migration]: Migrations.md
|
||||
@@ -2483,4 +2601,5 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[FAQ]: ../README.md#faq-associations
|
||||
[common table expressions]: CommonTableExpressions.md
|
||||
[Common Table Expressions]: CommonTableExpressions.md
|
||||
[Associations to Common Table Expressions]: CommonTableExpressions.md#associations-to-common-table-expressions
|
||||
+92
-33
@@ -7,6 +7,7 @@ GRDB ❤️ Combine
|
||||
- [Demo Application]
|
||||
- [Asynchronous Database Access]
|
||||
- [Database Observation]
|
||||
- [Combine and Data Consistency]: take care when you combine database publishers together
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -46,6 +47,19 @@ let newPlayerCount = dbQueue.writePublisher { db -> Int in
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>Asynchronously migrate the database</strong></summary>
|
||||
|
||||
This publisher migrates a database:
|
||||
|
||||
```swift
|
||||
// DatabasePublishers.Migrate
|
||||
let migrator: DatabaseMigrator = ...
|
||||
let publisher = migrator.migratePublisher(dbQueue)
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>Observe changes in database values</strong></summary>
|
||||
|
||||
@@ -99,11 +113,12 @@ let cancellable = publisher.sink(
|
||||
|
||||
# Asynchronous Database Access
|
||||
|
||||
GRDB provide publishers that perform asynchronous database accesses.
|
||||
GRDB provide publishers that perform asynchronous database accesses:
|
||||
|
||||
- [`readPublisher(receiveOn:value:)`]
|
||||
- [`writePublisher(receiveOn:updates:)`]
|
||||
- [`writePublisher(receiveOn:updates:thenRead:)`]
|
||||
- [`migratePublisher(_:receiveOn:)`]
|
||||
|
||||
|
||||
#### `DatabaseReader.readPublisher(receiveOn:value:)`
|
||||
@@ -125,7 +140,7 @@ When you use a [database pool], reads are generally non-blocking, unless the max
|
||||
|
||||
This publisher can be subscribed from any thread. A new database access starts on every subscription.
|
||||
|
||||
The fetched value is published on the main queue, unless you provide a specific scheduler to the `receiveOn` argument.
|
||||
The fetched value is published on the main queue, unless you provide a specific [scheduler] to the `receiveOn` argument.
|
||||
|
||||
|
||||
#### `DatabaseWriter.writePublisher(receiveOn:updates:)`
|
||||
@@ -234,37 +249,6 @@ This publisher has the same behavior as ValueObservation:
|
||||
|
||||
See [ValueObservation Scheduling](../README.md#valueobservation-scheduling) for more information.
|
||||
|
||||
:warning: **ValueObservation and Data Consistency**
|
||||
|
||||
When you compose ValueObservation publishers together with the [combineLatest](https://developer.apple.com/documentation/combine/publisher/3333677-combinelatest) operator, you lose all guarantees of [data consistency](https://en.wikipedia.org/wiki/Consistency_(database_systems)).
|
||||
|
||||
Instead, compose requests together into **one single** ValueObservation, as below:
|
||||
|
||||
```swift
|
||||
struct HallOfFame {
|
||||
var totalPlayerCount: Int
|
||||
var bestPlayers: [Player]
|
||||
}
|
||||
|
||||
// DATA CONSISTENCY GUARANTEED
|
||||
let hallOfFamePublisher = ValueObservation
|
||||
.tracking { db -> HallOfFame in
|
||||
let totalPlayerCount = try Player.fetchCount(db)
|
||||
|
||||
let bestPlayers = try Player
|
||||
.order(Column("score").desc)
|
||||
.limit(10)
|
||||
.fetchAll(db)
|
||||
|
||||
return HallOfFame(
|
||||
totalPlayerCount: totalPlayerCount,
|
||||
bestPlayers: bestPlayers)
|
||||
}
|
||||
.publisher(in: dbQueue)
|
||||
```
|
||||
|
||||
See [ValueObservation] for more information.
|
||||
|
||||
|
||||
#### `DatabaseRegionObservation.publisher(in:)`
|
||||
|
||||
@@ -306,12 +290,86 @@ try dbQueue.write { db in
|
||||
See [DatabaseRegionObservation] for more information.
|
||||
|
||||
|
||||
## Combine and Data Consistency
|
||||
|
||||
When you compose database publishers together with Combine operators such as `combineLatest` or `zip`, you lose all guarantees of [data consistency](https://en.wikipedia.org/wiki/Consistency_(database_systems)).
|
||||
|
||||
This is because each database publisher is isolated from others: each one of them sees its own state of the database. Whenever some database change is interleaved between publisher operations, publishers will process or publish values that may not fit well together.
|
||||
|
||||
In other words, whenever you need to perform some database access or observation that depends on some database invariant, make sure you define one and only one database publisher instead of combining several publishers. This is how you will prevent eventual concurrent database writes from messing with your app, and introduce bugs.
|
||||
|
||||
To this end, remember that *all database publishers can perform several requests*.
|
||||
|
||||
In the example below, we are totally sure that the published `HallOfFame` values will never contain inconsistent values, because it is produced by one and ony one publisher:
|
||||
|
||||
```swift
|
||||
struct HallOfFame {
|
||||
// Invariant: bestPlayers.count <= totalPlayerCount
|
||||
var totalPlayerCount: Int
|
||||
var bestPlayers: [Player]
|
||||
}
|
||||
|
||||
// CORRECT: DATA CONSISTENCY GUARANTEED
|
||||
let hallOfFamePublisher = ValueObservation
|
||||
.tracking { db -> HallOfFame in
|
||||
// 1st request
|
||||
let totalPlayerCount = try Player.fetchCount(db)
|
||||
|
||||
// 2nd request
|
||||
let bestPlayers = try Player
|
||||
.order(Column("score").desc)
|
||||
.limit(10)
|
||||
.fetchAll(db)
|
||||
|
||||
// 100% guaranteed
|
||||
assert(bestPlayers.count <= totalPlayerCount)
|
||||
|
||||
// Merge results together
|
||||
return HallOfFame(
|
||||
totalPlayerCount: totalPlayerCount,
|
||||
bestPlayers: bestPlayers)
|
||||
}
|
||||
.publisher(in: dbQueue)
|
||||
```
|
||||
|
||||
Compare with the incorrect version that combines two database publishers together:
|
||||
|
||||
```swift
|
||||
// OK
|
||||
let totalPlayerCountPublisher = ValueObservation
|
||||
.tracking(Player.fetchCount)
|
||||
.publisher(in: dbQueue)
|
||||
|
||||
// OK
|
||||
let bestPlayerPublisher = ValueObservation
|
||||
.tracking(Player
|
||||
.order(Column("score").desc)
|
||||
.limit(10)
|
||||
.fetchAll)
|
||||
.publisher(in: dbQueue)
|
||||
|
||||
// NOT OK: DATA CONSISTENCY NOT GUARANTEED
|
||||
let hallOfFamePublisher = totalPlayerCountPublisher
|
||||
.combineLatest(bestPlayerPublisher)
|
||||
.map(HallOfFame.init(totalPlayerCount:bestPlayers))
|
||||
|
||||
let cancellable = hallOfFamePublisher.sink(
|
||||
receiveCompletion: { completion in ... },
|
||||
receiveValue: { hallOfFame in
|
||||
// ASSERTION MAY FAIL if some players are deleted
|
||||
// at the wrong time
|
||||
assert(hallOfFame.bestPlayers.count <= hallOfFame.totalPlayerCount)
|
||||
})
|
||||
```
|
||||
|
||||
|
||||
[Database Connections]: ../README.md#database-connections
|
||||
[Usage]: #usage
|
||||
[Asynchronous Database Access]: #asynchronous-database-access
|
||||
[Combine]: https://developer.apple.com/documentation/combine
|
||||
[Database Changes Observation]: ../README.md#database-changes-observation
|
||||
[Database Observation]: #database-observation
|
||||
[Combine and Data Consistency]: #combine-and-data-consistency
|
||||
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
|
||||
[Demo Application]: DemoApps/GRDBCombineDemo/README.md
|
||||
[SQLite]: http://sqlite.org
|
||||
@@ -321,6 +379,7 @@ See [DatabaseRegionObservation] for more information.
|
||||
[`readPublisher(receiveOn:value:)`]: #databasereaderreadpublisherreceiveonvalue
|
||||
[`writePublisher(receiveOn:updates:)`]: #databasewriterwritepublisherreceiveonupdates
|
||||
[`writePublisher(receiveOn:updates:thenRead:)`]: #databasewriterwritepublisherreceiveonupdatesthenread
|
||||
[`migratePublisher(_:receiveOn:)`]: Migrations.md#asynchronous-migrations
|
||||
[configured]: ../README.md#databasepool-configuration
|
||||
[database pool]: ../README.md#database-pools
|
||||
[database queue]: ../README.md#database-queues
|
||||
|
||||
@@ -29,7 +29,7 @@ The CTE request can be provided as a [query interface request]:
|
||||
|
||||
```swift
|
||||
// WITH playerName AS (SELECT name FROM player) ...
|
||||
let playerNameCTE = CommonTableExpression<Void>(
|
||||
let playerNameCTE = CommonTableExpression(
|
||||
named: "playerName",
|
||||
request: Player.select(Column("name")))
|
||||
```
|
||||
@@ -40,27 +40,27 @@ You can feed a CTE with raw SQL as well (second and third examples use [SQL Inte
|
||||
let name = "O'Brien"
|
||||
|
||||
// WITH playerName AS (SELECT 'O''Brien') ...
|
||||
let playerNameCTE = CommonTableExpression<Void>(
|
||||
let playerNameCTE = CommonTableExpression(
|
||||
named: "playerName",
|
||||
sql: "SELECT ?", arguments: [name])
|
||||
|
||||
// WITH playerName AS (SELECT 'O''Brien') ...
|
||||
let playerNameCTE = CommonTableExpression<Void>(
|
||||
let playerNameCTE = CommonTableExpression(
|
||||
named: "playerName",
|
||||
literal: "SELECT \(name)")
|
||||
|
||||
// WITH playerName AS (SELECT 'O''Brien') ...
|
||||
let request: SQLRequest<String> = "SELECT \(name)"
|
||||
let playerNameCTE = CommonTableExpression<Void>(
|
||||
let request = SQLRequest("SELECT \(name)")
|
||||
let playerNameCTE = CommonTableExpression(
|
||||
named: "playerName",
|
||||
request: requests)
|
||||
request: request)
|
||||
```
|
||||
|
||||
All CTEs can be provided with explicit column names:
|
||||
|
||||
```swift
|
||||
// WITH pair(a, b) AS (SELECT 1, 2) ...
|
||||
let pairCTE = CommonTableExpression<Void>(
|
||||
let pairCTE = CommonTableExpression(
|
||||
named: "pair",
|
||||
columns: ["a", "b"],
|
||||
sql: "SELECT 1, 2")
|
||||
@@ -71,7 +71,7 @@ Recursive CTEs need the `recursive` flag. The example below selects all integers
|
||||
```swift
|
||||
// WITH RECURSIVE counter(x) AS
|
||||
// (VALUES(1) UNION ALL SELECT x+1 FROM counter WHERE x<1000)
|
||||
let counterCTE = CommonTableExpression<Int>(
|
||||
let counterCTE = CommonTableExpression(
|
||||
recursive: true,
|
||||
named: "counter",
|
||||
columns: ["x"],
|
||||
@@ -84,8 +84,6 @@ let counterCTE = CommonTableExpression<Int>(
|
||||
|
||||
> :point_up: **Note**: many recursive CTEs use the `UNION ALL` SQL operator. The query interface does not provide any Swift support for it, so you'll generally have to write SQL in your definitions of recursive CTEs.
|
||||
|
||||
As you can see in all above examples, `CommonTableExpression` is a generic type: `CommonTableExpression<Void>`, `CommonTableExpression<Int>`. The generic argument (`Void`, `Int`) turns useful when you [join common table expressions](#associations-to-common-table-expressions), or when you [fetch values directly from a common table expression](#fetch-values-from-common-table-expressions). Otherwise, you can just use `Void`.
|
||||
|
||||
|
||||
## Embed Common Table Expressions in Requests
|
||||
|
||||
@@ -103,7 +101,7 @@ We first build a `CommonTableExpression`:
|
||||
|
||||
```swift
|
||||
let name = "O'Brien"
|
||||
let playerNameCTE = CommonTableExpression<Void>(
|
||||
let playerNameCTE = CommonTableExpression(
|
||||
named: "playerName",
|
||||
literal: "SELECT \(name)")
|
||||
```
|
||||
@@ -184,48 +182,37 @@ try Player
|
||||
|
||||
In the previous chapter, a common table expression was embedded as a subquery, with the `CommonTableExpression.all()` method.
|
||||
|
||||
`all()` builds a regular [query interface request] that you can filter, sort, etc, like all query interface requests. You can also fetch from it, but only as long as it is provided with the definition of the CTE.
|
||||
`cte.all()` builds a regular [query interface request] that you can filter, sort, etc, like all query interface requests.
|
||||
|
||||
This will generally give requests of the form `cte.all().with(cte)`. In SQL, this would give: `WITH cte AS (...) SELECT * FROM cte`.
|
||||
You can also fetch from `cte.all()`, as long as the request is given the definition of the CTE: `cte.all().with(cte)`. In SQL, this would give: `WITH cte AS (...) SELECT * FROM cte`:
|
||||
|
||||
The generic type of `CommonTableExpression<...>` now turns out useful, so that you can fetch the desired outcome (database [rows](../README.md#row-queries), simple [values](../README.md#value-queries), or custom [records](../README.md#records)).
|
||||
|
||||
For example, let's fetch a range of integer:
|
||||
This request, of type `QueryInterfaceRequest<Row>`, can fetch raw database [rows](../README.md#row-queries):
|
||||
|
||||
```swift
|
||||
func counterRequest(range: ClosedRange<Int>) -> QueryInterfaceRequest<Int> {
|
||||
// WITH RECURSIVE counter(x) AS
|
||||
// (VALUES(...) UNION ALL SELECT x+1 FROM counter WHERE x<...)
|
||||
// SELECT * FROM counter
|
||||
let counter = CommonTableExpression<Int>(
|
||||
recursive: true,
|
||||
named: "counter",
|
||||
columns: ["x"],
|
||||
literal: """
|
||||
VALUES(\(range.lowerBound)) \
|
||||
UNION ALL \
|
||||
SELECT x+1 FROM counter WHERE x < \(range.upperBound)
|
||||
""")
|
||||
return counter.all().with(counter)
|
||||
}
|
||||
|
||||
let values = try dbQueue.read { db in
|
||||
try counterRequest(range: 3...7).fetchAll(db)
|
||||
}
|
||||
print(values) // prints "[3, 4, 5, 6, 7]"
|
||||
let cte = CommonTableExpression(...)
|
||||
let request = cte.all().with(cte)
|
||||
let rows = try request.fetchAll(db) // [Row]
|
||||
```
|
||||
|
||||
When you have to fetch from a `CommonTableExpression` which does not have the desired generic type, you can still use the `asRequest(of:)` method:
|
||||
In order to fetch something else, such as simple [values](../README.md#value-queries), or custom [records](../README.md#records), you have two possible options:
|
||||
|
||||
```swift
|
||||
let cte: CommonTableExpression<Void> = ...
|
||||
let rows: [Row] = try dbQueue.read { db in
|
||||
try cte.all().with(cte)
|
||||
.asRequest(of: Row.self)
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
1. Use the `asRequest(of:)` method:
|
||||
|
||||
```swift
|
||||
let cte = CommonTableExpression(...)
|
||||
let request = cte.all().with(cte).asRequest(of: Player.self)
|
||||
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
let players = try request.fetchAll(db) // [Player]
|
||||
```
|
||||
|
||||
2. Provide the fetched type to the cte itself:
|
||||
|
||||
```swift
|
||||
let cte = CommonTableExpression<Player>(...)
|
||||
// ~~~~~~~~
|
||||
let request = cte.all().with(cte)
|
||||
let players = try request.fetchAll(db) // [Player]
|
||||
```
|
||||
|
||||
## Associations to Common Table Expressions
|
||||
|
||||
@@ -337,7 +324,7 @@ We can now define the CTE for the latest messages:
|
||||
```swift
|
||||
// WITH latestMessage AS
|
||||
// (SELECT *, MAX(date) FROM message GROUP BY chatID)
|
||||
let latestMessageCTE = CommonTableExpression<Void>(
|
||||
let latestMessageCTE = CommonTableExpression(
|
||||
named: "latestMessage",
|
||||
request: latestMessageRequest)
|
||||
```
|
||||
@@ -378,9 +365,9 @@ And we can fetch the data that feeds our application screen:
|
||||
let chatInfos: [ChatInfos] = try dbQueue.read(request.fetchAll)
|
||||
```
|
||||
|
||||
> :bulb: **Tip**: the joining methods are generally type-safe: they won't allow you to join apples to oranges. This works when associations have a *precise* type. In this context, our go-to `CommonTableExpression<Void>` CTEs can work against type safety. So when you want to define associations between several CTEs, and make sure the compiler will notice wrong uses of those associations, tag your `CommonTableExpression` with a type instead of `Void`.
|
||||
> :bulb: **Tip**: the joining methods are generally type-safe: they won't allow you to join apples to oranges. This works when associations have a *precise* type. In this context, anonymous `CommonTableExpression` CTEs can work against type safety. When you want to define associations between several CTEs, and make sure the compiler will notice wrong uses of those associations, tag your common table expressions with an explicit type: `CommonTableExpression<SomeType>`.
|
||||
>
|
||||
> You can use an existing record type, or an ad-hoc enum. For example:
|
||||
> To do so, you can use an existing record type, or an ad-hoc enum. For example:
|
||||
>
|
||||
> ```swift
|
||||
> enum CTE1 { }
|
||||
@@ -389,9 +376,9 @@ let chatInfos: [ChatInfos] = try dbQueue.read(request.fetchAll)
|
||||
> enum CTE2 { }
|
||||
> let cte2 = CommonTableExpression<CTE2>(...)
|
||||
>
|
||||
> let assoc1 = BaseRecord.association(to: cte1, on: ...)
|
||||
> let assoc2 = cte1.association(to: cte2, on: ...)
|
||||
> let assoc3 = cte2.association(to: FarRecord.self, on: ...)
|
||||
> let assoc1 = BaseRecord.association(to: cte1, on: ...) // from BaseRecord to CTE1
|
||||
> let assoc2 = cte1.association(to: cte2, on: ...) // from CTE1 to CTE2
|
||||
> let assoc3 = cte2.association(to: FarRecord.self, on: ...) // from CTE2 to FarRecord
|
||||
>
|
||||
> // WITH ...
|
||||
> // SELECT base.* FROM base
|
||||
@@ -400,12 +387,14 @@ let chatInfos: [ChatInfos] = try dbQueue.read(request.fetchAll)
|
||||
> // JOIN far ON ...
|
||||
> let request = BaseRecord
|
||||
> .with(cte1).with(cte2)
|
||||
> .joining(required: assoc1
|
||||
> .joining(required: assoc2
|
||||
> .joining(required: assoc3)))
|
||||
> .joining(required: assoc1. // OK
|
||||
> .joining(required: assoc2. // OK
|
||||
> .joining(required: assoc3))) // OK
|
||||
>
|
||||
> // Compiler error
|
||||
> let request = BaseRecord.joining(required: assoc2)
|
||||
> let request = BaseRecord
|
||||
> .joining(required: assoc2) // Not OK
|
||||
> .joining(required: assoc3) // Not OK
|
||||
> ```
|
||||
|
||||
[query interface request]: ../README.md#requests
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
/* Begin PBXBuildFile section */
|
||||
56026CAC25B8A7EF00D1DF3F /* PlayerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */; };
|
||||
56026CAD25B8A7EF00D1DF3F /* AppDatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */; };
|
||||
5671722A261A185300423B6F /* Query.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717229261A185300423B6F /* Query.swift */; };
|
||||
5671723A261B23C800423B6F /* PlayerList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717239261B23C800423B6F /* PlayerList.swift */; };
|
||||
56717252261B334D00423B6F /* PlayerRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717251261B334D00423B6F /* PlayerRequestTests.swift */; };
|
||||
567C3E1A2520B6DE0011F6E9 /* GRDBCombineDemoApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */; };
|
||||
567C3E1E2520B6DF0011F6E9 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */; };
|
||||
567C3E212520B6DF0011F6E9 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */; };
|
||||
@@ -16,15 +19,15 @@
|
||||
567C3E4F2520B70E0011F6E9 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 567C3E3B2520B7000011F6E9 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
|
||||
567C3E5D2520B75C0011F6E9 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E532520B75C0011F6E9 /* Player.swift */; };
|
||||
567C3E5E2520B75C0011F6E9 /* Persistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E542520B75C0011F6E9 /* Persistence.swift */; };
|
||||
567C3E5F2520B75C0011F6E9 /* PlayerListViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E562520B75C0011F6E9 /* PlayerListViewModel.swift */; };
|
||||
567C3E602520B75C0011F6E9 /* PlayerFormViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E572520B75C0011F6E9 /* PlayerFormViewModel.swift */; };
|
||||
567C3E612520B75D0011F6E9 /* PlayerForm.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E592520B75C0011F6E9 /* PlayerForm.swift */; };
|
||||
567C3E622520B75D0011F6E9 /* PlayerList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5A2520B75C0011F6E9 /* PlayerList.swift */; };
|
||||
567C3E632520B75D0011F6E9 /* PlayerCreationSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5B2520B75C0011F6E9 /* PlayerCreationSheet.swift */; };
|
||||
567C3E612520B75D0011F6E9 /* PlayerFormView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E592520B75C0011F6E9 /* PlayerFormView.swift */; };
|
||||
567C3E622520B75D0011F6E9 /* AppView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5A2520B75C0011F6E9 /* AppView.swift */; };
|
||||
567C3E632520B75D0011F6E9 /* PlayerCreationView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */; };
|
||||
567C3E642520B75D0011F6E9 /* PlayerEditionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */; };
|
||||
567C3E662520B7880011F6E9 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E652520B7880011F6E9 /* AppDatabase.swift */; };
|
||||
567C3E792520BB650011F6E9 /* Localizable.stringsdict in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E752520BB650011F6E9 /* Localizable.stringsdict */; };
|
||||
567C3E7A2520BB650011F6E9 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */; };
|
||||
56B6D1092619EC1B003CC455 /* PlayerRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D1082619EC1B003CC455 /* PlayerRequest.swift */; };
|
||||
78E2F9E6261EEC22005D1F7F /* GRDBCombineDemoUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78E2F9E5261EEC22005D1F7F /* GRDBCombineDemoUITests.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
@@ -98,6 +101,13 @@
|
||||
remoteGlobalIDString = 56E5D7C91B4D3FED00430942;
|
||||
remoteInfo = GRDBiOS;
|
||||
};
|
||||
78E2F9E8261EEC22005D1F7F /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 567C3E0E2520B6DE0011F6E9 /* Project object */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 567C3E152520B6DE0011F6E9;
|
||||
remoteInfo = GRDBCombineDemo;
|
||||
};
|
||||
/* End PBXContainerItemProxy section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
@@ -119,6 +129,9 @@
|
||||
56026C9C25B8A7D000D1DF3F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerTests.swift; sourceTree = "<group>"; };
|
||||
56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabaseTests.swift; sourceTree = "<group>"; };
|
||||
56717229261A185300423B6F /* Query.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Query.swift; sourceTree = "<group>"; };
|
||||
56717239261B23C800423B6F /* PlayerList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerList.swift; sourceTree = "<group>"; };
|
||||
56717251261B334D00423B6F /* PlayerRequestTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequestTests.swift; sourceTree = "<group>"; };
|
||||
567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBCombineDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GRDBCombineDemoApp.swift; sourceTree = "<group>"; };
|
||||
567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
|
||||
@@ -127,15 +140,17 @@
|
||||
567C3E292520B7000011F6E9 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = "<group>"; };
|
||||
567C3E532520B75C0011F6E9 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = "<group>"; };
|
||||
567C3E542520B75C0011F6E9 /* Persistence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistence.swift; sourceTree = "<group>"; };
|
||||
567C3E562520B75C0011F6E9 /* PlayerListViewModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerListViewModel.swift; sourceTree = "<group>"; };
|
||||
567C3E572520B75C0011F6E9 /* PlayerFormViewModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerFormViewModel.swift; sourceTree = "<group>"; };
|
||||
567C3E592520B75C0011F6E9 /* PlayerForm.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerForm.swift; sourceTree = "<group>"; };
|
||||
567C3E5A2520B75C0011F6E9 /* PlayerList.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerList.swift; sourceTree = "<group>"; };
|
||||
567C3E5B2520B75C0011F6E9 /* PlayerCreationSheet.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerCreationSheet.swift; sourceTree = "<group>"; };
|
||||
567C3E592520B75C0011F6E9 /* PlayerFormView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerFormView.swift; sourceTree = "<group>"; };
|
||||
567C3E5A2520B75C0011F6E9 /* AppView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppView.swift; sourceTree = "<group>"; };
|
||||
567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerCreationView.swift; sourceTree = "<group>"; };
|
||||
567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionView.swift; sourceTree = "<group>"; };
|
||||
567C3E652520B7880011F6E9 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
|
||||
567C3E762520BB650011F6E9 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.stringsdict; name = en; path = en.lproj/Localizable.stringsdict; sourceTree = "<group>"; };
|
||||
567C3E782520BB650011F6E9 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
|
||||
56B6D1082619EC1B003CC455 /* PlayerRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequest.swift; sourceTree = "<group>"; };
|
||||
78E2F9E3261EEC22005D1F7F /* GRDBCombineDemoUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCombineDemoUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
78E2F9E5261EEC22005D1F7F /* GRDBCombineDemoUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GRDBCombineDemoUITests.swift; sourceTree = "<group>"; };
|
||||
78E2F9E7261EEC22005D1F7F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
@@ -154,6 +169,13 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
78E2F9E0261EEC22005D1F7F /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
@@ -162,6 +184,7 @@
|
||||
children = (
|
||||
56026C9C25B8A7D000D1DF3F /* Info.plist */,
|
||||
56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */,
|
||||
56717251261B334D00423B6F /* PlayerRequestTests.swift */,
|
||||
56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */,
|
||||
);
|
||||
path = GRDBCombineDemoTests;
|
||||
@@ -191,6 +214,7 @@
|
||||
567C3E292520B7000011F6E9 /* GRDB.xcodeproj */,
|
||||
567C3E182520B6DE0011F6E9 /* GRDBCombineDemo */,
|
||||
56026C9925B8A7D000D1DF3F /* GRDBCombineDemoTests */,
|
||||
78E2F9E4261EEC22005D1F7F /* GRDBCombineDemoUITests */,
|
||||
567C3E172520B6DE0011F6E9 /* Products */,
|
||||
567C3E4D2520B70E0011F6E9 /* Frameworks */,
|
||||
);
|
||||
@@ -201,6 +225,7 @@
|
||||
children = (
|
||||
567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */,
|
||||
56026C9825B8A7D000D1DF3F /* GRDBCombineDemoTests.xctest */,
|
||||
78E2F9E3261EEC22005D1F7F /* GRDBCombineDemoUITests.xctest */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
@@ -212,10 +237,11 @@
|
||||
567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */,
|
||||
567C3E542520B75C0011F6E9 /* Persistence.swift */,
|
||||
567C3E532520B75C0011F6E9 /* Player.swift */,
|
||||
56B6D1082619EC1B003CC455 /* PlayerRequest.swift */,
|
||||
56717229261A185300423B6F /* Query.swift */,
|
||||
567C3E1F2520B6DF0011F6E9 /* Preview Content */,
|
||||
56185BC125B8047D00B9C30F /* Resources */,
|
||||
56185BC225B8048B00B9C30F /* Support */,
|
||||
567C3E552520B75C0011F6E9 /* ViewModels */,
|
||||
567C3E582520B75C0011F6E9 /* Views */,
|
||||
);
|
||||
path = GRDBCombineDemo;
|
||||
@@ -251,26 +277,27 @@
|
||||
name = Frameworks;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
567C3E552520B75C0011F6E9 /* ViewModels */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567C3E562520B75C0011F6E9 /* PlayerListViewModel.swift */,
|
||||
567C3E572520B75C0011F6E9 /* PlayerFormViewModel.swift */,
|
||||
);
|
||||
path = ViewModels;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
567C3E582520B75C0011F6E9 /* Views */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567C3E592520B75C0011F6E9 /* PlayerForm.swift */,
|
||||
567C3E5A2520B75C0011F6E9 /* PlayerList.swift */,
|
||||
567C3E5B2520B75C0011F6E9 /* PlayerCreationSheet.swift */,
|
||||
567C3E5A2520B75C0011F6E9 /* AppView.swift */,
|
||||
567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */,
|
||||
567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */,
|
||||
567C3E592520B75C0011F6E9 /* PlayerFormView.swift */,
|
||||
56717239261B23C800423B6F /* PlayerList.swift */,
|
||||
);
|
||||
path = Views;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
78E2F9E4261EEC22005D1F7F /* GRDBCombineDemoUITests */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
78E2F9E5261EEC22005D1F7F /* GRDBCombineDemoUITests.swift */,
|
||||
78E2F9E7261EEC22005D1F7F /* Info.plist */,
|
||||
);
|
||||
path = GRDBCombineDemoUITests;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
@@ -311,13 +338,31 @@
|
||||
productReference = 567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */;
|
||||
productType = "com.apple.product-type.application";
|
||||
};
|
||||
78E2F9E2261EEC22005D1F7F /* GRDBCombineDemoUITests */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 78E2F9F3261EEC22005D1F7F /* Build configuration list for PBXNativeTarget "GRDBCombineDemoUITests" */;
|
||||
buildPhases = (
|
||||
78E2F9DF261EEC22005D1F7F /* Sources */,
|
||||
78E2F9E0261EEC22005D1F7F /* Frameworks */,
|
||||
78E2F9E1261EEC22005D1F7F /* Resources */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
78E2F9E9261EEC22005D1F7F /* PBXTargetDependency */,
|
||||
);
|
||||
name = GRDBCombineDemoUITests;
|
||||
productName = GRDBCombineDemoUITests;
|
||||
productReference = 78E2F9E3261EEC22005D1F7F /* GRDBCombineDemoUITests.xctest */;
|
||||
productType = "com.apple.product-type.bundle.ui-testing";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
567C3E0E2520B6DE0011F6E9 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastSwiftUpdateCheck = 1230;
|
||||
LastSwiftUpdateCheck = 1250;
|
||||
LastUpgradeCheck = 1200;
|
||||
TargetAttributes = {
|
||||
56026C9725B8A7D000D1DF3F = {
|
||||
@@ -327,6 +372,10 @@
|
||||
567C3E152520B6DE0011F6E9 = {
|
||||
CreatedOnToolsVersion = 12.0;
|
||||
};
|
||||
78E2F9E2261EEC22005D1F7F = {
|
||||
CreatedOnToolsVersion = 12.5;
|
||||
TestTargetID = 567C3E152520B6DE0011F6E9;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = 567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBCombineDemo" */;
|
||||
@@ -350,6 +399,7 @@
|
||||
targets = (
|
||||
567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */,
|
||||
56026C9725B8A7D000D1DF3F /* GRDBCombineDemoTests */,
|
||||
78E2F9E2261EEC22005D1F7F /* GRDBCombineDemoUITests */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
@@ -432,6 +482,13 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
78E2F9E1261EEC22005D1F7F /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
@@ -441,6 +498,7 @@
|
||||
files = (
|
||||
56026CAC25B8A7EF00D1DF3F /* PlayerTests.swift in Sources */,
|
||||
56026CAD25B8A7EF00D1DF3F /* AppDatabaseTests.swift in Sources */,
|
||||
56717252261B334D00423B6F /* PlayerRequestTests.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -448,16 +506,25 @@
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
5671722A261A185300423B6F /* Query.swift in Sources */,
|
||||
567C3E5E2520B75C0011F6E9 /* Persistence.swift in Sources */,
|
||||
567C3E5D2520B75C0011F6E9 /* Player.swift in Sources */,
|
||||
567C3E612520B75D0011F6E9 /* PlayerForm.swift in Sources */,
|
||||
567C3E632520B75D0011F6E9 /* PlayerCreationSheet.swift in Sources */,
|
||||
56B6D1092619EC1B003CC455 /* PlayerRequest.swift in Sources */,
|
||||
5671723A261B23C800423B6F /* PlayerList.swift in Sources */,
|
||||
567C3E612520B75D0011F6E9 /* PlayerFormView.swift in Sources */,
|
||||
567C3E632520B75D0011F6E9 /* PlayerCreationView.swift in Sources */,
|
||||
567C3E662520B7880011F6E9 /* AppDatabase.swift in Sources */,
|
||||
567C3E622520B75D0011F6E9 /* PlayerList.swift in Sources */,
|
||||
567C3E622520B75D0011F6E9 /* AppView.swift in Sources */,
|
||||
567C3E642520B75D0011F6E9 /* PlayerEditionView.swift in Sources */,
|
||||
567C3E1A2520B6DE0011F6E9 /* GRDBCombineDemoApp.swift in Sources */,
|
||||
567C3E5F2520B75C0011F6E9 /* PlayerListViewModel.swift in Sources */,
|
||||
567C3E602520B75C0011F6E9 /* PlayerFormViewModel.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
78E2F9DF261EEC22005D1F7F /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
78E2F9E6261EEC22005D1F7F /* GRDBCombineDemoUITests.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -474,6 +541,11 @@
|
||||
name = GRDBiOS;
|
||||
targetProxy = 567C3E512520B71C0011F6E9 /* PBXContainerItemProxy */;
|
||||
};
|
||||
78E2F9E9261EEC22005D1F7F /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
target = 567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */;
|
||||
targetProxy = 78E2F9E8261EEC22005D1F7F /* PBXContainerItemProxy */;
|
||||
};
|
||||
/* End PBXTargetDependency section */
|
||||
|
||||
/* Begin PBXVariantGroup section */
|
||||
@@ -659,7 +731,7 @@
|
||||
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_ASSET_PATHS = "\"GRDBCombineDemo/Preview Content\"";
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
DEVELOPMENT_TEAM = "";
|
||||
ENABLE_PREVIEWS = YES;
|
||||
INFOPLIST_FILE = GRDBCombineDemo/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
|
||||
@@ -681,7 +753,7 @@
|
||||
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_ASSET_PATHS = "\"GRDBCombineDemo/Preview Content\"";
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
DEVELOPMENT_TEAM = "";
|
||||
ENABLE_PREVIEWS = YES;
|
||||
INFOPLIST_FILE = GRDBCombineDemo/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
|
||||
@@ -696,6 +768,44 @@
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
78E2F9EA261EEC22005D1F7F /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_TEAM = "";
|
||||
INFOPLIST_FILE = GRDBCombineDemoUITests/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.groue.GRDBCombineDemoUITests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_TARGET_NAME = GRDBCombineDemo;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
78E2F9EB261EEC22005D1F7F /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_TEAM = "";
|
||||
INFOPLIST_FILE = GRDBCombineDemoUITests/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.groue.GRDBCombineDemoUITests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_TARGET_NAME = GRDBCombineDemo;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
@@ -726,6 +836,15 @@
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
78E2F9F3261EEC22005D1F7F /* Build configuration list for PBXNativeTarget "GRDBCombineDemoUITests" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
78E2F9EA261EEC22005D1F7F /* Debug */,
|
||||
78E2F9EB261EEC22005D1F7F /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
};
|
||||
rootObject = 567C3E0E2520B6DE0011F6E9 /* Project object */;
|
||||
|
||||
+10
@@ -38,6 +38,16 @@
|
||||
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "78E2F9E2261EEC22005D1F7F"
|
||||
BuildableName = "GRDBCombineDemoUITests.xctest"
|
||||
BlueprintName = "GRDBCombineDemoUITests"
|
||||
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
|
||||
@@ -4,7 +4,7 @@ import GRDB
|
||||
/// AppDatabase lets the application access the database.
|
||||
///
|
||||
/// It applies the pratices recommended at
|
||||
/// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
|
||||
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
struct AppDatabase {
|
||||
/// Creates an `AppDatabase`, and make sure the database schema is ready.
|
||||
init(_ dbWriter: DatabaseWriter) throws {
|
||||
@@ -17,12 +17,12 @@ struct AppDatabase {
|
||||
/// 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
|
||||
/// 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
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md>
|
||||
private var migrator: DatabaseMigrator {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
@@ -38,9 +38,6 @@ struct AppDatabase {
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
// Sort player names in a localized case insensitive fashion by default
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#unicode
|
||||
.collate(.localizedCaseInsensitiveCompare)
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
}
|
||||
@@ -57,9 +54,25 @@ struct AppDatabase {
|
||||
// MARK: - Database Access: Writes
|
||||
|
||||
extension AppDatabase {
|
||||
/// A validation error that prevents some players from being saved into
|
||||
/// the database.
|
||||
enum ValidationError: LocalizedError {
|
||||
case missingName
|
||||
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .missingName:
|
||||
return "Please provide a name"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Saves (inserts or updates) a player. When the method returns, the
|
||||
/// player id is not nil.
|
||||
/// player is present in the database, and its id is not nil.
|
||||
func savePlayer(_ player: inout Player) throws {
|
||||
if player.name.isEmpty {
|
||||
throw ValidationError.missingName
|
||||
}
|
||||
try dbWriter.write { db in
|
||||
try player.save(db)
|
||||
}
|
||||
@@ -68,7 +81,7 @@ extension AppDatabase {
|
||||
/// Delete the specified players
|
||||
func deletePlayers(ids: [Int64]) throws {
|
||||
try dbWriter.write { db in
|
||||
_ = try Player.deleteAll(db, keys: ids)
|
||||
_ = try Player.deleteAll(db, ids: ids)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,7 +96,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
|
||||
@@ -115,6 +128,25 @@ extension AppDatabase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static let uiTestPlayers = [
|
||||
Player(id: nil, name: "Arthur", score: 5),
|
||||
Player(id: nil, name: "Barbara", score: 6),
|
||||
Player(id: nil, name: "Craig", score: 8),
|
||||
Player(id: nil, name: "David", score: 4),
|
||||
Player(id: nil, name: "Elena", score: 1),
|
||||
Player(id: nil, name: "Frederik", score: 2),
|
||||
Player(id: nil, name: "Gilbert", score: 7),
|
||||
Player(id: nil, name: "Henriette", score: 3)]
|
||||
|
||||
func createPlayersForUITests() throws {
|
||||
try dbWriter.write { db in
|
||||
try AppDatabase.uiTestPlayers.forEach { player in
|
||||
var mutablePlayer = player
|
||||
try mutablePlayer.save(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Support for `createRandomPlayersIfEmpty()` and `refreshPlayers()`.
|
||||
private func createRandomPlayers(_ db: Database) throws {
|
||||
@@ -128,19 +160,8 @@ extension AppDatabase {
|
||||
// MARK: - Database Access: Reads
|
||||
|
||||
extension AppDatabase {
|
||||
/// Returns a publisher that tracks changes in players ordered by name
|
||||
func playersOrderedByNamePublisher() -> AnyPublisher<[Player], Error> {
|
||||
ValueObservation
|
||||
.tracking(Player.all().orderedByName().fetchAll)
|
||||
.publisher(in: dbWriter, scheduling: .immediate)
|
||||
.eraseToAnyPublisher()
|
||||
}
|
||||
|
||||
/// Returns a publisher that tracks changes in players ordered by score
|
||||
func playersOrderedByScorePublisher() -> AnyPublisher<[Player], Error> {
|
||||
ValueObservation
|
||||
.tracking(Player.all().orderedByScore().fetchAll)
|
||||
.publisher(in: dbWriter, scheduling: .immediate)
|
||||
.eraseToAnyPublisher()
|
||||
/// Provides a read-only access to the database
|
||||
var databaseReader: DatabaseReader {
|
||||
dbWriter
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,23 @@
|
||||
import GRDB
|
||||
import SwiftUI
|
||||
|
||||
@main
|
||||
struct GRDBCombineDemoApp: App {
|
||||
let appDatabase = AppDatabase.shared
|
||||
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
PlayerList(viewModel: PlayerListViewModel(database: appDatabase))
|
||||
AppView().environment(\.appDatabase, AppDatabase.shared)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Let SwiftUI views access the database through the SwiftUI environment
|
||||
private struct AppDatabaseKey: EnvironmentKey {
|
||||
static let defaultValue: AppDatabase? = nil
|
||||
}
|
||||
|
||||
extension EnvironmentValues {
|
||||
var appDatabase: AppDatabase? {
|
||||
get { self[AppDatabaseKey.self] }
|
||||
set { self[AppDatabaseKey.self] = newValue }
|
||||
}
|
||||
}
|
||||
@@ -6,16 +6,38 @@ extension AppDatabase {
|
||||
|
||||
private static func makeShared() -> AppDatabase {
|
||||
do {
|
||||
// Pick a folder for storing the SQLite database, as well as
|
||||
// the various temporary files created during normal database
|
||||
// operations (https://sqlite.org/tempfiles.html).
|
||||
let fileManager = FileManager()
|
||||
let folderURL = try fileManager
|
||||
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
.appendingPathComponent("database", isDirectory: true)
|
||||
|
||||
// Support for tests: delete the database if requested
|
||||
if CommandLine.arguments.contains("-reset") {
|
||||
try? fileManager.removeItem(at: folderURL)
|
||||
}
|
||||
|
||||
// Create the database folder if needed
|
||||
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
|
||||
|
||||
// Connect to a database on disk
|
||||
// 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.
|
||||
try appDatabase.createRandomPlayersIfEmpty()
|
||||
// Prepare the database with test fixtures if requested
|
||||
if CommandLine.arguments.contains("-fixedTestData") {
|
||||
try appDatabase.createPlayersForUITests()
|
||||
} else {
|
||||
// Otherwise, populate the database if it is empty, for better
|
||||
// demo purpose.
|
||||
try appDatabase.createRandomPlayersIfEmpty()
|
||||
}
|
||||
|
||||
return appDatabase
|
||||
} catch {
|
||||
|
||||
@@ -2,7 +2,8 @@ import GRDB
|
||||
|
||||
/// The Player struct.
|
||||
///
|
||||
/// Identifiable conformance supports SwiftUI list animations.
|
||||
/// Identifiable conformance supports SwiftUI list animations, and type-safe
|
||||
/// GRDB primary key methods.
|
||||
/// Equatable conformance supports tests.
|
||||
struct Player: Identifiable, Equatable {
|
||||
/// The player id.
|
||||
@@ -50,7 +51,7 @@ extension Player {
|
||||
|
||||
/// Make Player a Codable Record.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#records
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#records>
|
||||
extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
// Define database columns from CodingKeys
|
||||
fileprivate enum Columns {
|
||||
@@ -68,28 +69,38 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
|
||||
/// Define some player requests used by the application.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
|
||||
/// 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))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import GRDB
|
||||
|
||||
/// A player request defines how to feed the player list
|
||||
struct PlayerRequest {
|
||||
enum Ordering {
|
||||
case byScore
|
||||
case byName
|
||||
}
|
||||
|
||||
var ordering: Ordering
|
||||
}
|
||||
|
||||
/// Make `PlayerRequest` able to be used with the `@Query` property wrapper.
|
||||
extension PlayerRequest: Queryable {
|
||||
static var defaultValue: [Player] { [] }
|
||||
|
||||
func fetchValue(_ db: Database) throws -> [Player] {
|
||||
switch ordering {
|
||||
case .byScore: return try Player.all().orderedByScore().fetchAll(db)
|
||||
case .byName: return try Player.all().orderedByName().fetchAll(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
//
|
||||
// Query.swift
|
||||
//
|
||||
// A property wrapper inspired from
|
||||
// https://davedelong.com/blog/2021/04/03/core-data-and-swiftui/
|
||||
//
|
||||
|
||||
import Combine
|
||||
import GRDB
|
||||
import SwiftUI
|
||||
|
||||
/// The protocol that feeds the `@Query` property wrapper.
|
||||
protocol Queryable: Equatable {
|
||||
/// The type of the fetched value
|
||||
associatedtype Value
|
||||
|
||||
/// The default value, used whenever the database is not available
|
||||
static var defaultValue: Value { get }
|
||||
|
||||
/// Fetches the database value
|
||||
func fetchValue(_ db: Database) throws -> Value
|
||||
}
|
||||
|
||||
/// The property wrapper that observes a database query
|
||||
@propertyWrapper
|
||||
struct Query<Query: Queryable>: DynamicProperty {
|
||||
/// The database reader that makes it possible to observe the database
|
||||
@Environment(\.appDatabase?.databaseReader) private var databaseReader: DatabaseReader?
|
||||
@StateObject private var core = Core()
|
||||
private var baseQuery: Query
|
||||
|
||||
/// The fetched value
|
||||
var wrappedValue: Query.Value {
|
||||
core.value ?? Query.defaultValue
|
||||
}
|
||||
|
||||
/// A binding to the query, that lets your views modify it.
|
||||
///
|
||||
/// This is how the demo app changes the player ordering.
|
||||
var projectedValue: Binding<Query> {
|
||||
Binding(
|
||||
get: { core.query ?? baseQuery },
|
||||
set: {
|
||||
core.usesBaseQuery = false
|
||||
core.query = $0
|
||||
})
|
||||
}
|
||||
|
||||
init(_ query: Query) {
|
||||
baseQuery = query
|
||||
}
|
||||
|
||||
func update() {
|
||||
guard let databaseReader = databaseReader else {
|
||||
fatalError("Attempting to use @Query without any database in the environment")
|
||||
}
|
||||
// Feed core with necessary information, and make sure tracking has started
|
||||
if core.usesBaseQuery { core.query = baseQuery }
|
||||
core.startTrackingIfNecessary(in: databaseReader)
|
||||
}
|
||||
|
||||
private class Core: ObservableObject {
|
||||
private(set) var value: Query.Value?
|
||||
var databaseReader: DatabaseReader?
|
||||
var usesBaseQuery = true
|
||||
var query: Query? {
|
||||
willSet {
|
||||
if query != newValue {
|
||||
// Stop tracking, and tell SwiftUI about the update
|
||||
objectWillChange.send()
|
||||
cancellable = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
private var cancellable: AnyCancellable?
|
||||
|
||||
init() { }
|
||||
|
||||
func startTrackingIfNecessary(in databaseReader: DatabaseReader) {
|
||||
if databaseReader !== self.databaseReader {
|
||||
// Database has changed. Stop tracking.
|
||||
self.databaseReader = databaseReader
|
||||
cancellable = nil
|
||||
}
|
||||
|
||||
guard let query = query else {
|
||||
// No query set
|
||||
return
|
||||
}
|
||||
|
||||
guard cancellable == nil else {
|
||||
// Already tracking
|
||||
return
|
||||
}
|
||||
|
||||
cancellable = ValueObservation
|
||||
.tracking(query.fetchValue)
|
||||
.publisher(
|
||||
in: databaseReader,
|
||||
scheduling: .immediate)
|
||||
.sink(
|
||||
receiveCompletion: { _ in
|
||||
// Ignore errors
|
||||
},
|
||||
receiveValue: { [weak self] value in
|
||||
guard let self = self else { return }
|
||||
// Tell SwiftUI about the new value
|
||||
self.objectWillChange.send()
|
||||
self.value = value
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
-67
@@ -1,67 +0,0 @@
|
||||
import Combine
|
||||
import Foundation
|
||||
|
||||
/// The view model that validates and saves an edited player into the database.
|
||||
///
|
||||
/// It feeds `PlayerForm`, `PlayerCreationSheet` and `PlayerEditionView`.
|
||||
final class PlayerFormViewModel: ObservableObject {
|
||||
/// A validation error that prevents the player from being saved into
|
||||
/// the database.
|
||||
enum ValidationError: LocalizedError {
|
||||
case missingName
|
||||
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .missingName:
|
||||
return "Please give a name to this player."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Published var name: String = ""
|
||||
@Published var score: String = ""
|
||||
|
||||
private let database: AppDatabase
|
||||
private var player: Player
|
||||
|
||||
init(database: AppDatabase, player: Player) {
|
||||
self.database = database
|
||||
self.player = player
|
||||
updateViewFromPlayer()
|
||||
}
|
||||
|
||||
// MARK: - Manage the Player Form
|
||||
|
||||
/// Validates and saves the player into the database.
|
||||
func savePlayer() throws {
|
||||
if name.isEmpty {
|
||||
throw ValidationError.missingName
|
||||
}
|
||||
player.name = name
|
||||
player.score = Int(score) ?? 0
|
||||
try database.savePlayer(&player)
|
||||
}
|
||||
|
||||
/// Resets form values to the original player values.
|
||||
func reset() {
|
||||
updateViewFromPlayer()
|
||||
}
|
||||
|
||||
/// Edits a new player
|
||||
func editNewPlayer() {
|
||||
player = .new()
|
||||
updateViewFromPlayer()
|
||||
}
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
private func updateViewFromPlayer() {
|
||||
self.name = player.name
|
||||
if player.score == 0 && player.id == nil {
|
||||
// Avoid displaying "0" for a new player: it does not look good.
|
||||
self.score = ""
|
||||
} else {
|
||||
self.score = "\(player.score)"
|
||||
}
|
||||
}
|
||||
}
|
||||
-118
@@ -1,118 +0,0 @@
|
||||
import Combine
|
||||
import Foundation
|
||||
|
||||
/// The view model that feeds `PlayerList`, and performs list modifications
|
||||
/// in the database.
|
||||
final class PlayerListViewModel: ObservableObject {
|
||||
enum Ordering {
|
||||
case byScore
|
||||
case byName
|
||||
}
|
||||
|
||||
struct PlayerList {
|
||||
var players: [Player]
|
||||
var animatedChanges: Bool
|
||||
}
|
||||
|
||||
/// The list ordering
|
||||
@Published var ordering: Ordering = .byScore
|
||||
|
||||
/// The players in the list
|
||||
@Published var playerList = PlayerList(players: [], animatedChanges: false)
|
||||
|
||||
/// The view model that edits a new player
|
||||
let newPlayerViewModel: PlayerFormViewModel
|
||||
|
||||
private let database: AppDatabase
|
||||
private var playersCancellable: AnyCancellable?
|
||||
|
||||
init(database: AppDatabase) {
|
||||
self.database = database
|
||||
newPlayerViewModel = PlayerFormViewModel(database: database, player: .new())
|
||||
playersCancellable = playersPublisher(in: database)
|
||||
.scan(nil) { (previousList: PlayerList?, players: [Player]) in
|
||||
if previousList == nil {
|
||||
// Do not animate first view update
|
||||
return PlayerList(players: players, animatedChanges: false)
|
||||
} else {
|
||||
return PlayerList(players: players, animatedChanges: true)
|
||||
}
|
||||
}
|
||||
.compactMap { $0 }
|
||||
.sink { [weak self] playerList in
|
||||
self?.playerList = playerList
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Players List Management
|
||||
|
||||
/// Deletes all players
|
||||
func deleteAllPlayers() {
|
||||
// Eventual error presentation is left as an exercise for the reader.
|
||||
try! database.deleteAllPlayers()
|
||||
}
|
||||
|
||||
func deletePlayers(atOffsets offsets: IndexSet) {
|
||||
// Eventual error presentation is left as an exercise for the reader.
|
||||
let playerIDs = offsets.compactMap { playerList.players[$0].id }
|
||||
try! database.deletePlayers(ids: playerIDs)
|
||||
}
|
||||
|
||||
/// Refreshes the list of players
|
||||
func refreshPlayers() {
|
||||
// Eventual error presentation is left as an exercise for the reader.
|
||||
try! database.refreshPlayers()
|
||||
}
|
||||
|
||||
/// Spawns many concurrent database updates, for demo purpose
|
||||
func stressTest() {
|
||||
for _ in 0..<50 {
|
||||
DispatchQueue.global().async {
|
||||
self.refreshPlayers()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Change Player Ordering
|
||||
|
||||
/// Toggles between the available orderings
|
||||
func toggleOrdering() {
|
||||
switch ordering {
|
||||
case .byName:
|
||||
ordering = .byScore
|
||||
case .byScore:
|
||||
ordering = .byName
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Player Edition
|
||||
|
||||
/// Returns a view model suitable for editing a player.
|
||||
func formViewModel(for player: Player) -> PlayerFormViewModel {
|
||||
PlayerFormViewModel(database: database, player: player)
|
||||
}
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
/// Returns a publisher of the players in the list
|
||||
private func playersPublisher(in database: AppDatabase) -> AnyPublisher<[Player], Never> {
|
||||
// Players depend on the current ordering
|
||||
$ordering.map { ordering -> AnyPublisher<[Player], Error> in
|
||||
switch ordering {
|
||||
case .byScore:
|
||||
return database.playersOrderedByScorePublisher()
|
||||
case .byName:
|
||||
return database.playersOrderedByNamePublisher()
|
||||
}
|
||||
}
|
||||
.map { playersPublisher in
|
||||
// Turn database errors into an empty players list.
|
||||
// Eventual error presentation is left as an exercise for the reader.
|
||||
playersPublisher.catch { error in
|
||||
Just<[Player]>([])
|
||||
}
|
||||
}
|
||||
.switchToLatest()
|
||||
.eraseToAnyPublisher()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import SwiftUI
|
||||
|
||||
/// The main application view
|
||||
struct AppView: View {
|
||||
/// Database access
|
||||
@Environment(\.appDatabase) private var appDatabase
|
||||
|
||||
/// The `players` property is kept up-to-date with the list of players.
|
||||
@Query(PlayerRequest(ordering: .byScore)) private var players: [Player]
|
||||
|
||||
/// Tracks the presentation of the player creation sheet.
|
||||
@State private var newPlayerIsPresented = false
|
||||
|
||||
// If you want to define the query on initialization, you will prefer:
|
||||
//
|
||||
// @Query<PlayerRequest> private var players: [Player]
|
||||
//
|
||||
// init(initialOrdering: PlayerRequest.Ordering) {
|
||||
// _players = Query(PlayerRequest(ordering: initialOrdering))
|
||||
// }
|
||||
|
||||
var body: some View {
|
||||
NavigationView {
|
||||
PlayerList(players: players)
|
||||
.navigationBarTitle(Text("\(players.count) Players"))
|
||||
.navigationBarItems(
|
||||
leading: HStack {
|
||||
EditButton()
|
||||
newPlayerButton
|
||||
},
|
||||
trailing: ToggleOrderingButton(ordering: $players.ordering))
|
||||
.toolbar { toolbarContent }
|
||||
}
|
||||
}
|
||||
|
||||
private var toolbarContent: some ToolbarContent {
|
||||
ToolbarItemGroup(placement: .bottomBar) {
|
||||
Button(
|
||||
action: { try? appDatabase?.deleteAllPlayers() },
|
||||
label: { Image(systemName: "trash").imageScale(.large) })
|
||||
Spacer()
|
||||
Button(
|
||||
action: { try? appDatabase?.refreshPlayers() },
|
||||
label: { Image(systemName: "arrow.clockwise").imageScale(.large) })
|
||||
}
|
||||
}
|
||||
|
||||
/// The button that presents the player creation sheet.
|
||||
private var newPlayerButton: some View {
|
||||
Button(
|
||||
action: { newPlayerIsPresented = true },
|
||||
label: { Image(systemName: "plus") })
|
||||
.accessibility(label: Text("New Player"))
|
||||
.sheet(
|
||||
isPresented: $newPlayerIsPresented,
|
||||
content: {
|
||||
PlayerCreationView(dismissAction: {
|
||||
newPlayerIsPresented = false
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private struct ToggleOrderingButton: View {
|
||||
@Binding var ordering: PlayerRequest.Ordering
|
||||
|
||||
var body: some View {
|
||||
switch ordering {
|
||||
case .byName:
|
||||
Button(
|
||||
action: { ordering = .byScore },
|
||||
label: {
|
||||
HStack {
|
||||
Text("Name")
|
||||
Image(systemName: "arrowtriangle.up.fill")
|
||||
}
|
||||
})
|
||||
case .byScore:
|
||||
Button(
|
||||
action: { ordering = .byName },
|
||||
label: {
|
||||
HStack {
|
||||
Text("Score")
|
||||
Image(systemName: "arrowtriangle.down.fill")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct AppView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
Group {
|
||||
// Preview a database of random players
|
||||
AppView().environment(\.appDatabase, .random())
|
||||
|
||||
// Preview an empty database
|
||||
AppView().environment(\.appDatabase, .empty())
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
-16
@@ -1,36 +1,37 @@
|
||||
import SwiftUI
|
||||
|
||||
/// The Player creation sheet
|
||||
struct PlayerCreationSheet: View {
|
||||
/// Manages the player form
|
||||
let viewModel: PlayerFormViewModel
|
||||
|
||||
/// The view that creates a new player.
|
||||
struct PlayerCreationView: View {
|
||||
/// Executed when user cancels or saves the new user.
|
||||
let dismissAction: () -> Void
|
||||
|
||||
@Environment(\.appDatabase) private var appDatabase
|
||||
@State private var name = ""
|
||||
@State private var score = ""
|
||||
@State private var errorAlertIsPresented = false
|
||||
@State private var errorAlertTitle = ""
|
||||
|
||||
var body: some View {
|
||||
NavigationView {
|
||||
PlayerForm(viewModel: viewModel)
|
||||
PlayerFormView(name: $name, score: $score)
|
||||
.alert(
|
||||
isPresented: $errorAlertIsPresented,
|
||||
content: { Alert(title: Text(errorAlertTitle)) })
|
||||
.navigationBarTitle("New Player")
|
||||
.navigationBarItems(
|
||||
leading: Button(
|
||||
action: self.dismissAction,
|
||||
action: dismissAction,
|
||||
label: { Text("Cancel") }),
|
||||
trailing: Button(
|
||||
action: self.save,
|
||||
action: save,
|
||||
label: { Text("Save") }))
|
||||
}
|
||||
}
|
||||
|
||||
private func save() {
|
||||
do {
|
||||
try viewModel.savePlayer()
|
||||
var player = Player(id: nil, name: name, score: Int(score) ?? 0)
|
||||
try appDatabase?.savePlayer(&player)
|
||||
dismissAction()
|
||||
} catch {
|
||||
errorAlertTitle = (error as? LocalizedError)?.errorDescription ?? "An error occurred"
|
||||
@@ -41,12 +42,7 @@ struct PlayerCreationSheet: View {
|
||||
|
||||
struct PlayerCreationSheet_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
let viewModel = PlayerFormViewModel(
|
||||
database: .empty(),
|
||||
player: .new())
|
||||
|
||||
return PlayerCreationSheet(
|
||||
viewModel: viewModel,
|
||||
dismissAction: { })
|
||||
PlayerCreationView(dismissAction: { })
|
||||
.environment(\.appDatabase, .empty())
|
||||
}
|
||||
}
|
||||
+14
-15
@@ -1,28 +1,27 @@
|
||||
import SwiftUI
|
||||
|
||||
/// The Player edition view, designed to be the destination of
|
||||
/// a NavigationLink.
|
||||
/// The view that edits an existing player.
|
||||
struct PlayerEditionView: View {
|
||||
/// Manages the player form
|
||||
let viewModel: PlayerFormViewModel
|
||||
@Environment(\.appDatabase) private var appDatabase
|
||||
@State var player: Player
|
||||
|
||||
var body: some View {
|
||||
PlayerForm(viewModel: viewModel)
|
||||
.onDisappear(perform: {
|
||||
// Ignore validation errors
|
||||
try? self.viewModel.savePlayer()
|
||||
})
|
||||
PlayerFormView(
|
||||
name: $player.name,
|
||||
score: Binding(
|
||||
get: { "\(player.score)" },
|
||||
set: { player.score = Int($0) ?? 0 }))
|
||||
.onDisappear {
|
||||
// save and ignore error
|
||||
try? appDatabase?.savePlayer(&player)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerEditionView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
let viewModel = PlayerFormViewModel(
|
||||
database: .empty(),
|
||||
player: .newRandom())
|
||||
|
||||
return NavigationView {
|
||||
PlayerEditionView(viewModel: viewModel)
|
||||
NavigationView {
|
||||
PlayerEditionView(player: Player.newRandom())
|
||||
.navigationBarTitle("Player Edition")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
import SwiftUI
|
||||
|
||||
/// The Player editing form, embedded in both
|
||||
/// `PlayerCreationSheet` and `PlayerEditionView`.
|
||||
struct PlayerForm: View {
|
||||
/// Manages the player form
|
||||
@ObservedObject var viewModel: PlayerFormViewModel
|
||||
|
||||
var body: some View {
|
||||
List {
|
||||
TextField("Name", text: $viewModel.name)
|
||||
TextField("Score", text: $viewModel.score)
|
||||
.keyboardType(.numberPad)
|
||||
}
|
||||
.listStyle(GroupedListStyle())
|
||||
// Make sure the form is reset, in case a previous edition ended
|
||||
// with a validation error.
|
||||
//
|
||||
// The bug we want to prevent is the following:
|
||||
//
|
||||
// 1. Launch the app
|
||||
// 2. Tap a player
|
||||
// 3. Erase the name so that validation fails
|
||||
// 4. Hit the back button
|
||||
// 5. Tap the same player
|
||||
// 6. Bug: the form displays an empty name.
|
||||
.onAppear(perform: viewModel.reset)
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerFormView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
let viewModel = PlayerFormViewModel(
|
||||
database: .empty(),
|
||||
player: .newRandom())
|
||||
|
||||
return PlayerForm(viewModel: viewModel)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import SwiftUI
|
||||
|
||||
/// The Player editing form, embedded in both
|
||||
/// `PlayerCreationView` and `PlayerEditionView`.
|
||||
struct PlayerFormView: View {
|
||||
@Binding var name: String
|
||||
@Binding var score: String
|
||||
|
||||
var body: some View {
|
||||
List {
|
||||
TextField("Name", text: $name)
|
||||
.accessibility(label: Text("Player Name"))
|
||||
TextField("Score", text: $score).keyboardType(.numberPad)
|
||||
.accessibility(label: Text("Player Score"))
|
||||
}
|
||||
.listStyle(InsetGroupedListStyle())
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerFormView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
Group {
|
||||
PlayerFormView(
|
||||
name: .constant(""),
|
||||
score: .constant(""))
|
||||
PlayerFormView(
|
||||
name: .constant(Player.randomName()),
|
||||
score: .constant("\(Player.randomScore())"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,117 +1,35 @@
|
||||
import SwiftUI
|
||||
|
||||
/// The list of players
|
||||
struct PlayerList: View {
|
||||
/// Manages the list of players
|
||||
@ObservedObject var viewModel: PlayerListViewModel
|
||||
/// Database access
|
||||
@Environment(\.appDatabase) private var appDatabase
|
||||
|
||||
/// Controls the presentation of the player creation sheet.
|
||||
@State private var newPlayerIsPresented = false
|
||||
/// The players in the list
|
||||
var players: [Player]
|
||||
|
||||
var body: some View {
|
||||
NavigationView {
|
||||
VStack {
|
||||
playerList
|
||||
toolbar
|
||||
}
|
||||
.navigationBarTitle(Text("\(viewModel.playerList.players.count) Players"))
|
||||
.navigationBarItems(
|
||||
leading: HStack {
|
||||
EditButton()
|
||||
newPlayerButton
|
||||
},
|
||||
trailing: toggleOrderingButton)
|
||||
}
|
||||
}
|
||||
|
||||
private var playerList: some View {
|
||||
List {
|
||||
ForEach(viewModel.playerList.players) { player in
|
||||
NavigationLink(destination: self.editionView(for: player)) {
|
||||
PlayerRow(player: player)
|
||||
.animation(nil)
|
||||
ForEach(players) { player in
|
||||
NavigationLink(destination: editionView(for: player)) {
|
||||
PlayerRow(player: player).animation(nil)
|
||||
}
|
||||
}
|
||||
.onDelete(perform: { offsets in
|
||||
self.viewModel.deletePlayers(atOffsets: offsets)
|
||||
let playerIds = offsets.compactMap { players[$0].id }
|
||||
try? appDatabase?.deletePlayers(ids: playerIds)
|
||||
})
|
||||
}
|
||||
.animation(.default)
|
||||
.listStyle(PlainListStyle())
|
||||
.animation(viewModel.playerList.animatedChanges ? .default : nil)
|
||||
}
|
||||
|
||||
private var toolbar: some View {
|
||||
HStack {
|
||||
Button(
|
||||
action: viewModel.deleteAllPlayers,
|
||||
label: { Image(systemName: "trash").imageScale(.large) })
|
||||
Spacer()
|
||||
Button(
|
||||
action: viewModel.refreshPlayers,
|
||||
label: { Image(systemName: "arrow.clockwise").imageScale(.large) })
|
||||
Spacer()
|
||||
Button(
|
||||
action: viewModel.stressTest,
|
||||
label: { Image(systemName: "tornado").imageScale(.large) })
|
||||
}
|
||||
|
||||
.padding()
|
||||
}
|
||||
|
||||
/// The button that toggles between name/score ordering.
|
||||
private var toggleOrderingButton: some View {
|
||||
switch viewModel.ordering {
|
||||
case .byName:
|
||||
return Button(action: viewModel.toggleOrdering, label: {
|
||||
HStack {
|
||||
Text("Name")
|
||||
Image(systemName: "arrowtriangle.up.fill")
|
||||
.imageScale(.small)
|
||||
}
|
||||
})
|
||||
case .byScore:
|
||||
return Button(action: viewModel.toggleOrdering, label: {
|
||||
HStack {
|
||||
Text("Score")
|
||||
Image(systemName: "arrowtriangle.down.fill")
|
||||
.imageScale(.small)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The view that edits a player in the list.
|
||||
private func editionView(for player: Player) -> some View {
|
||||
PlayerEditionView(
|
||||
viewModel: viewModel.formViewModel(for: player))
|
||||
.navigationBarTitle(player.name)
|
||||
}
|
||||
|
||||
/// The button that presents the player creation sheet.
|
||||
private var newPlayerButton: some View {
|
||||
Button(
|
||||
action: {
|
||||
// Make sure we do not edit a previously created player.
|
||||
self.viewModel.newPlayerViewModel.editNewPlayer()
|
||||
self.newPlayerIsPresented = true
|
||||
},
|
||||
label: { Image(systemName: "plus").imageScale(.large) })
|
||||
.sheet(
|
||||
isPresented: $newPlayerIsPresented,
|
||||
content: { self.newPlayerCreationSheet })
|
||||
}
|
||||
|
||||
/// The player creation sheet.
|
||||
private var newPlayerCreationSheet: some View {
|
||||
PlayerCreationSheet(
|
||||
viewModel: self.viewModel.newPlayerViewModel,
|
||||
dismissAction: {
|
||||
self.newPlayerIsPresented = false
|
||||
})
|
||||
PlayerEditionView(player: player).navigationBarTitle(player.name)
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerRow: View {
|
||||
private struct PlayerRow: View {
|
||||
var player: Player
|
||||
|
||||
var body: some View {
|
||||
@@ -123,9 +41,14 @@ struct PlayerRow: View {
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerListView_Previews: PreviewProvider {
|
||||
struct PlayerList_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
let viewModel = PlayerListViewModel(database: .random())
|
||||
return PlayerList(viewModel: viewModel)
|
||||
NavigationView {
|
||||
PlayerList(players: [
|
||||
Player(id: 1, name: "Arthur", score: 100),
|
||||
Player(id: 2, name: "Barbara", score: 1000),
|
||||
])
|
||||
.navigationTitle("Preview")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -143,112 +143,4 @@ class AppDatabaseTests: XCTestCase {
|
||||
let players = try dbQueue.read(Player.fetchAll)
|
||||
XCTAssertEqual(players, [player])
|
||||
}
|
||||
|
||||
func test_playersOrderedByNamePublisher_publishes_well_ordered_players() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
}
|
||||
|
||||
// When we observe players and wait for the first value
|
||||
let exp = expectation(description: "Players")
|
||||
var players: [Player]?
|
||||
let cancellable = appDatabase.playersOrderedByNamePublisher().sink { completion in
|
||||
if case let .failure(error) = completion {
|
||||
XCTFail("Unexpected error \(error)")
|
||||
}
|
||||
} receiveValue: {
|
||||
players = $0
|
||||
exp.fulfill()
|
||||
}
|
||||
withExtendedLifetime(cancellable) {
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
}
|
||||
|
||||
// Then the players are the two players ordered by name
|
||||
XCTAssertEqual(players, [player1, player2])
|
||||
}
|
||||
|
||||
func test_playersOrderedByNamePublisher_publishes_right_on_subscripion() throws {
|
||||
// Our SwiftUI views have no "waiting" state, and must be fed with
|
||||
// players without any delay in order to avoid any rendering glitch.
|
||||
// This test makes sure `playersOrderedByNamePublisher` publishes right
|
||||
// on subscription.
|
||||
|
||||
// Given a players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we observe players
|
||||
var players: [Player]?
|
||||
_ = appDatabase.playersOrderedByNamePublisher().sink { completion in
|
||||
if case let .failure(error) = completion {
|
||||
XCTFail("Unexpected error \(error)")
|
||||
}
|
||||
} receiveValue: {
|
||||
players = $0
|
||||
}
|
||||
|
||||
// Then the players are published right on subscription
|
||||
XCTAssertNotNil(players)
|
||||
}
|
||||
|
||||
func test_playersOrderedByScorePublisher_publishes_well_ordered_players() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
}
|
||||
|
||||
// When we observe players and wait for the first value
|
||||
let exp = expectation(description: "Players")
|
||||
var players: [Player]?
|
||||
let cancellable = appDatabase.playersOrderedByScorePublisher().sink { completion in
|
||||
if case let .failure(error) = completion {
|
||||
XCTFail("Unexpected error \(error)")
|
||||
}
|
||||
} receiveValue: {
|
||||
players = $0
|
||||
exp.fulfill()
|
||||
}
|
||||
withExtendedLifetime(cancellable) {
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
}
|
||||
|
||||
// Then the players are the two players ordered by score descending
|
||||
XCTAssertEqual(players, [player2, player1])
|
||||
}
|
||||
|
||||
func test_playersOrderedByScorePublisher_publishes_right_on_subscripion() throws {
|
||||
// Our SwiftUI views have no "waiting" state, and must be fed with
|
||||
// players without any delay in order to avoid any rendering glitch.
|
||||
// This test makes sure `playersOrderedByScorePublisher` publishes right
|
||||
// on subscription.
|
||||
|
||||
// Given a players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we observe players
|
||||
var players: [Player]?
|
||||
_ = appDatabase.playersOrderedByScorePublisher().sink { completion in
|
||||
if case let .failure(error) = completion {
|
||||
XCTFail("Unexpected error \(error)")
|
||||
}
|
||||
} receiveValue: {
|
||||
players = $0
|
||||
}
|
||||
|
||||
// Then the players are published right on subscription
|
||||
XCTAssertNotNil(players)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
@testable import GRDBCombineDemo
|
||||
|
||||
class PlayerRequestTests: XCTestCase {
|
||||
func test_PlayerRequest_byName_fetches_well_ordered_players() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
}
|
||||
|
||||
// When we fetch players ordered by name
|
||||
let playerRequest = PlayerRequest(ordering: .byName)
|
||||
let players = try dbQueue.read(playerRequest.fetchValue)
|
||||
|
||||
// Then the players are the two players ordered by name
|
||||
XCTAssertEqual(players, [player1, player2])
|
||||
}
|
||||
|
||||
func test_PlayerRequest_byScore_fetches_well_ordered_players() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
}
|
||||
|
||||
// When we fetch players ordered by score
|
||||
let playerRequest = PlayerRequest(ordering: .byScore)
|
||||
let players = try dbQueue.read(playerRequest.fetchValue)
|
||||
|
||||
// Then the players are the two players ordered by score descending
|
||||
XCTAssertEqual(players, [player2, player1])
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
//
|
||||
// GRDBCombineDemoUITests.swift
|
||||
// GRDBCombineDemoUITests
|
||||
//
|
||||
// Created by Peter Steinberger on 08.04.21.
|
||||
//
|
||||
|
||||
import XCTest
|
||||
|
||||
class GRDBCombineDemoUITests: XCTestCase {
|
||||
|
||||
override func setUpWithError() throws {
|
||||
// In UI tests it is usually best to stop immediately when a failure occurs.
|
||||
continueAfterFailure = false
|
||||
}
|
||||
|
||||
override func tearDownWithError() throws {
|
||||
}
|
||||
|
||||
func runApp() -> XCUIApplication {
|
||||
// UI tests must launch the application that they test.
|
||||
let app = XCUIApplication()
|
||||
// We enforce a fresh database to ensure 8 random players.
|
||||
app.launchArguments = ["-reset", "-fixedTestData"]
|
||||
app.launch()
|
||||
return app
|
||||
}
|
||||
|
||||
// This test, introduced in 481f6e93, tests the @Query fix added in
|
||||
// 68874412. The fix expresses itself when a view defines an @Query
|
||||
// property that is replaced in the view initializer, as in 481f6e93.
|
||||
//
|
||||
// It happens that I did not find that this particular view setup was suited
|
||||
// for a demo app. The demo has to find a delicate balance, not too trivial,
|
||||
// but without gratuitous complexity.
|
||||
//
|
||||
// I simplified the demo app in a5ffc52d, and we no longer have any view
|
||||
// that defines an @Query property which is replaced in the view
|
||||
// initializer. This means that this test no longer checks against
|
||||
// 68874412 regressions!
|
||||
//
|
||||
// Whenever the @Query property wrapper ships with GRDB itself, make sure
|
||||
// we test for those regressions!
|
||||
func testInitialSortingIsByScore() throws {
|
||||
let app = runApp()
|
||||
|
||||
let getFirstCell = { () -> XCUIElement in
|
||||
app.tables.element(boundBy: 0).cells.element(boundBy: 0)
|
||||
}
|
||||
|
||||
// Given default sorting, Henriette must be on top
|
||||
XCTAssertEqual(getFirstCell().label, "Craig, 8 points")
|
||||
|
||||
// Reverse sorting will bring Arthur on top (sort by name)
|
||||
app.buttons["Score"].tap()
|
||||
XCTAssertEqual(getFirstCell().label, "Arthur, 5 points")
|
||||
}
|
||||
|
||||
func testListAndAddPlayer() throws {
|
||||
let app = runApp()
|
||||
|
||||
// Ensure we have 8 players visible
|
||||
XCTAssert(app.tables.cells.count == 8)
|
||||
|
||||
// add a player
|
||||
app.buttons["New Player"].tap()
|
||||
|
||||
let playerNameField = app.textFields["Player Name"]
|
||||
playerNameField.tap()
|
||||
playerNameField.typeText("Tim Apple")
|
||||
|
||||
app.buttons["Save"].tap()
|
||||
|
||||
// This is suboptimal, but we need to wait for the animation to finish
|
||||
// A better way could be to disable animations globally,
|
||||
// and/or a hook to detect when the async fetch completes.
|
||||
sleep(2)
|
||||
|
||||
XCTAssert(app.tables.cells.count == 9)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -3,7 +3,7 @@ Combine + SwiftUI Demo Application
|
||||
|
||||
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBCombineDemo/Screenshot.png" width="50%">
|
||||
|
||||
**This demo application is a Combine + SwiftUI application, based on the MVVM design pattern.** For a demo application that uses UIKit, see [GRDBDemoiOS](../GRDBDemoiOS/README.md).
|
||||
**This demo application is a Combine + SwiftUI application.** For a demo application that uses UIKit, see [GRDBDemoiOS](../GRDBDemoiOS/README.md).
|
||||
|
||||
> :point_up: **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration.
|
||||
|
||||
@@ -19,7 +19,7 @@ The topics covered in this demo are:
|
||||
|
||||
- [GRDBCombineDemoApp.swift](GRDBCombineDemo/GRDBCombineDemoApp.swift)
|
||||
|
||||
`GRDBCombineDemoApp` feeds the app views with a database.
|
||||
`GRDBCombineDemoApp` feeds the app views with a database, through the SwiftUI environment.
|
||||
|
||||
- [AppDatabase.swift](GRDBCombineDemo/AppDatabase.swift)
|
||||
|
||||
@@ -31,18 +31,19 @@ The topics covered in this demo are:
|
||||
|
||||
- [Player.swift](GRDBCombineDemo/Player.swift)
|
||||
|
||||
`Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records). It defines the database requests used by the application.
|
||||
`Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records).
|
||||
|
||||
- [PlayerList.swift](GRDBCombineDemo/Views/PlayerList.swift) and [PlayerListViewModel.swift](GRDBCombineDemo/ViewModels/PlayerListViewModel.swift)
|
||||
- [PlayerRequest.swift](GRDBCombineDemo/PlayerRequest.swift), [Query.swift](GRDBCombineDemo/Query.swift), [AppView.swift](GRDBCombineDemo/Views/AppView.swift)
|
||||
|
||||
`PlayerList` is the SwiftUI view that displays the list of players, fed by `PlayerListViewModel`.
|
||||
|
||||
- [PlayerForm.swift](GRDBCombineDemo/Views/PlayerForm.swift), [PlayerEditionView.swift](GRDBCombineDemo/Views/PlayerEditionView.swift), [PlayerCreationSheet.swift](GRDBCombineDemo/Views/PlayerCreationSheet.swift) and [PlayerFormViewModel.swift](GRDBCombineDemo/ViewModels/PlayerFormViewModel.swift).
|
||||
`PlayerRequest` defines the player requests used by the app (sorted by score, or by name).
|
||||
|
||||
`PlayerForm` is the SwiftUI view that displays a Player editing form. It is embedded in `PlayerEditionView` and `PlayerCreationSheet`, two SwiftUI views that edit or create a player. All those views are fed by `PlayerFormViewModel`.
|
||||
`PlayerRequest` feeds the `@Query` property wrapper. `@Query`, inspired by [this article](https://davedelong.com/blog/2021/04/03/core-data-and-swiftui/), allows SwiftUI views to display up-to-date database content thanks to GRDB's [ValueObservation](../../../README.md#valueobservation).
|
||||
|
||||
`AppView` is the SwiftUI view that uses `@Query` in order to feed its player list.
|
||||
|
||||
- [GRDBCombineDemoTests](GRDBCombineDemoTests)
|
||||
|
||||
- Test the database schema
|
||||
- Test the `Player` record and its requests
|
||||
- Test the `PlayerRequest` methods that feed the list of players.
|
||||
- Test the `AppDatabase` methods that let the app access the database.
|
||||
+19
-6
@@ -78,8 +78,10 @@
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<RemoteRunnable
|
||||
runnableDebuggingMode = "2"
|
||||
BundleIdentifier = "com.apple.Carousel"
|
||||
RemotePath = "/GRDBDemoiOS">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
@@ -87,7 +89,7 @@
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</RemoteRunnable>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
@@ -95,8 +97,10 @@
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<RemoteRunnable
|
||||
runnableDebuggingMode = "2"
|
||||
BundleIdentifier = "com.apple.Carousel"
|
||||
RemotePath = "/GRDBDemoiOS">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
@@ -104,7 +108,16 @@
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</RemoteRunnable>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
BuildableName = "GRDBDemoWatchOS.app"
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
|
||||
@@ -3,7 +3,7 @@ import GRDB
|
||||
/// AppDatabase lets the application access the database.
|
||||
///
|
||||
/// It applies the pratices recommended at
|
||||
/// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
|
||||
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
final class AppDatabase {
|
||||
/// Creates an `AppDatabase`, and make sure the database schema is ready.
|
||||
init(_ dbWriter: DatabaseWriter) throws {
|
||||
@@ -16,12 +16,12 @@ final class AppDatabase {
|
||||
/// 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
|
||||
/// 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
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md>
|
||||
private var migrator: DatabaseMigrator {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
@@ -37,9 +37,6 @@ final class AppDatabase {
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
// Sort player names in a localized case insensitive fashion by default
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#unicode
|
||||
.collate(.localizedCaseInsensitiveCompare)
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
}
|
||||
@@ -57,7 +54,7 @@ final class AppDatabase {
|
||||
|
||||
extension AppDatabase {
|
||||
/// Saves (inserts or updates) a player. When the method returns, the
|
||||
/// player id is not nil.
|
||||
/// player is present in the database, and its id is not nil.
|
||||
func savePlayer(_ player: inout Player) throws {
|
||||
try dbWriter.write { db in
|
||||
try player.save(db)
|
||||
@@ -67,7 +64,7 @@ extension AppDatabase {
|
||||
/// Delete the specified players
|
||||
func deletePlayers(ids: [Int64]) throws {
|
||||
try dbWriter.write { db in
|
||||
_ = try Player.deleteAll(db, keys: ids)
|
||||
_ = try Player.deleteAll(db, ids: ids)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,7 +79,7 @@ extension AppDatabase {
|
||||
func refreshPlayers() throws {
|
||||
try dbWriter.write { db in
|
||||
if try Player.fetchCount(db) == 0 {
|
||||
// Insert new random players
|
||||
// When database is empty, insert new random players
|
||||
try createRandomPlayers(db)
|
||||
} else {
|
||||
// Insert a player
|
||||
@@ -127,20 +124,6 @@ extension AppDatabase {
|
||||
// MARK: - Database Access: Reads
|
||||
|
||||
extension AppDatabase {
|
||||
/// Tracks changes in the number of players
|
||||
func observePlayerCount(
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Int) -> Void)
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
ValueObservation
|
||||
.tracking(Player.fetchCount)
|
||||
.start(
|
||||
in: dbWriter,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
}
|
||||
|
||||
/// Tracks changes in players ordered by name
|
||||
func observePlayersOrderedByName(
|
||||
onError: @escaping (Error) -> Void,
|
||||
|
||||
@@ -1,17 +1,26 @@
|
||||
import GRDB
|
||||
|
||||
extension AppDatabase {
|
||||
/// The shared `PlayerDatabase`
|
||||
/// The database for the application
|
||||
static let shared = makeShared()
|
||||
|
||||
private static func makeShared() -> AppDatabase {
|
||||
do {
|
||||
// Create a folder for storing the SQLite database, as well as
|
||||
// the various temporary files created during normal database
|
||||
// operations (https://sqlite.org/tempfiles.html).
|
||||
let fileManager = FileManager()
|
||||
let folderURL = try fileManager
|
||||
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
.appendingPathComponent("database", isDirectory: true)
|
||||
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
|
||||
|
||||
// Connect to a database on disk
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
let url: URL = try FileManager.default
|
||||
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
.appendingPathComponent("db.sqlite")
|
||||
let dbPool = try DatabasePool(path: url.path)
|
||||
let dbURL = folderURL.appendingPathComponent("db.sqlite")
|
||||
let dbPool = try DatabasePool(path: dbURL.path)
|
||||
|
||||
// Create the AppDatabase
|
||||
let appDatabase = try AppDatabase(dbPool)
|
||||
|
||||
// Populate the database if it is empty, for better demo purpose.
|
||||
|
||||
@@ -2,8 +2,9 @@ import GRDB
|
||||
|
||||
/// The Player struct.
|
||||
///
|
||||
/// Identifiable conformance supports type-safe GRDB primary key methods.
|
||||
/// Hashable conformance supports table view updates
|
||||
struct Player: Hashable {
|
||||
struct Player: Identifiable, Hashable {
|
||||
/// The player id.
|
||||
///
|
||||
/// Int64 is the recommended type for auto-incremented database ids.
|
||||
@@ -49,7 +50,7 @@ extension Player {
|
||||
|
||||
/// Make Player a Codable Record.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#records
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#records>
|
||||
extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
// Define database columns from CodingKeys
|
||||
fileprivate enum Columns {
|
||||
@@ -67,28 +68,38 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
|
||||
/// Define some player requests used by the application.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
extension DerivableRequest where RowDecoder == Player {
|
||||
/// A request of players ordered by name
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let players = try dbQueue.read { db in
|
||||
/// let players: [Player] = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByName().fetchAll(db)
|
||||
/// }
|
||||
func orderedByName() -> Self {
|
||||
order(Player.Columns.name)
|
||||
// Sort by name in a localized case insensitive fashion
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
|
||||
order(Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
|
||||
/// A request of players ordered by score
|
||||
/// A request of players ordered by score.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let players = try dbQueue.read { db in
|
||||
/// let players: [Player] = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByScore().fetchAll(db)
|
||||
/// }
|
||||
/// let bestPlayer: Player? = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByScore().fetchOne(db)
|
||||
/// }
|
||||
func orderedByScore() -> Self {
|
||||
order(Player.Columns.score.desc, Player.Columns.name)
|
||||
// Sort by descending score, and then by name, in a
|
||||
// localized case insensitive fashion
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
|
||||
order(
|
||||
Player.Columns.score.desc,
|
||||
Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
}
|
||||
+32
-34
@@ -12,11 +12,10 @@ class PlayerListViewController: UITableViewController {
|
||||
private var dataSource: PlayerDataSource!
|
||||
private var animatesPlayersChange = false // Don't animate first update
|
||||
private var playersCancellable: DatabaseCancellable?
|
||||
private var playerCountCancellable: DatabaseCancellable?
|
||||
private var playerOrdering: PlayerOrdering = .byScore {
|
||||
didSet {
|
||||
configureOrderingBarButtonItem()
|
||||
configureDataSourceContent()
|
||||
observePlayers()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +24,7 @@ class PlayerListViewController: UITableViewController {
|
||||
configureToolbar()
|
||||
configureNavigationItem()
|
||||
configureDataSource()
|
||||
configureDataSourceContent()
|
||||
observePlayers()
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
@@ -49,7 +48,6 @@ class PlayerListViewController: UITableViewController {
|
||||
target: nil, action: nil)
|
||||
navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem]
|
||||
configureOrderingBarButtonItem()
|
||||
configureTitle()
|
||||
}
|
||||
|
||||
private func configureOrderingBarButtonItem() {
|
||||
@@ -67,19 +65,6 @@ class PlayerListViewController: UITableViewController {
|
||||
}
|
||||
}
|
||||
|
||||
private func configureTitle() {
|
||||
playerCountCancellable = AppDatabase.shared.observePlayerCount(
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] count in
|
||||
guard let self = self else { return }
|
||||
switch count {
|
||||
case 0: self.navigationItem.title = "No Player"
|
||||
case 1: self.navigationItem.title = "1 Player"
|
||||
default: self.navigationItem.title = "\(count) Players"
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private func configureDataSource() {
|
||||
dataSource = PlayerDataSource(tableView: tableView) { (tableView, indexPath, player) in
|
||||
let cell = tableView.dequeueReusableCell(withIdentifier: "Player", for: indexPath)
|
||||
@@ -95,26 +80,18 @@ class PlayerListViewController: UITableViewController {
|
||||
tableView.dataSource = dataSource
|
||||
}
|
||||
|
||||
private func configureDataSourceContent() {
|
||||
switch playerOrdering {
|
||||
case .byName:
|
||||
playersCancellable = AppDatabase.shared.observePlayersOrderedByName(
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
self.updateDataSourceContent(with: players)
|
||||
})
|
||||
case .byScore:
|
||||
playersCancellable = AppDatabase.shared.observePlayersOrderedByScore(
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
self.updateDataSourceContent(with: players)
|
||||
})
|
||||
private func configureTitle(from players: [Player]) {
|
||||
switch players.count {
|
||||
case 0:
|
||||
navigationItem.title = "No Player"
|
||||
case 1:
|
||||
navigationItem.title = "1 Player"
|
||||
case let count:
|
||||
navigationItem.title = "\(count) Players"
|
||||
}
|
||||
}
|
||||
|
||||
private func updateDataSourceContent(with players: [Player]) {
|
||||
private func configureDataSource(from players: [Player]) {
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Int, Player>()
|
||||
snapshot.appendSections([0])
|
||||
snapshot.appendItems(players, toSection: 0)
|
||||
@@ -127,6 +104,27 @@ class PlayerListViewController: UITableViewController {
|
||||
dataSource.apply(snapshot, animatingDifferences: false, completion: nil)
|
||||
}
|
||||
}
|
||||
|
||||
private func observePlayers() {
|
||||
switch playerOrdering {
|
||||
case .byName:
|
||||
playersCancellable = AppDatabase.shared.observePlayersOrderedByName(
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
self.configureTitle(from: players)
|
||||
self.configureDataSource(from: players)
|
||||
})
|
||||
case .byScore:
|
||||
playersCancellable = AppDatabase.shared.observePlayersOrderedByScore(
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
self.configureTitle(from: players)
|
||||
self.configureDataSource(from: players)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -144,34 +144,6 @@ class AppDatabaseTests: XCTestCase {
|
||||
XCTAssertEqual(players, [player])
|
||||
}
|
||||
|
||||
func test_observePlayerCount() throws {
|
||||
// Given a players database that contains one player
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try dbQueue.write { db in
|
||||
try player.insert(db)
|
||||
}
|
||||
|
||||
// When we observe the player count and wait for the first value
|
||||
let exp = expectation(description: "Player count")
|
||||
var count: Int?
|
||||
let cancellable = appDatabase.observePlayerCount(
|
||||
onError: { error in
|
||||
XCTFail("Unexpected error \(error)")
|
||||
},
|
||||
onChange: {
|
||||
count = $0
|
||||
exp.fulfill()
|
||||
})
|
||||
withExtendedLifetime(cancellable) {
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
}
|
||||
|
||||
// Then that first value is one
|
||||
XCTAssertEqual(count, 1)
|
||||
}
|
||||
|
||||
func test_observePlayersOrderedByName() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = DatabaseQueue()
|
||||
|
||||
@@ -3,7 +3,7 @@ UIKit Demo Application
|
||||
|
||||
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBDemoiOS/Screenshot.png" width="50%">
|
||||
|
||||
**This demo application is a storyboard-based UIKit application, based on the MVC design pattern.** For a demo application that uses Combine and SwiftUI, see [GRDBCombineDemo](../GRDBCombineDemo/README.md).
|
||||
**This demo application is a storyboard-based UIKit application.** For a demo application that uses Combine and SwiftUI, see [GRDBCombineDemo](../GRDBCombineDemo/README.md).
|
||||
|
||||
> :point_up: **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration.
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
Demo Applications
|
||||
=================
|
||||
|
||||
- [UIKit Demo Application](GRDBDemoiOS/README.md): a storyboard-based UIKit application, based on the MVC design pattern.
|
||||
- [Combine + SwiftUI Demo Application](GRDBCombineDemo/README.md): a Combine + SwiftUI application, based on the MVVM design pattern.
|
||||
|
||||
- [UIKit Demo Application](GRDBDemoiOS/README.md): a storyboard-based UIKit application.
|
||||
- [Combine + SwiftUI Demo Application](GRDBCombineDemo/README.md): a Combine + SwiftUI application.
|
||||
@@ -280,7 +280,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.3/Structs/StatementArguments.html):
|
||||
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.11/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -529,7 +529,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.3/Structs/StatementArguments.html):
|
||||
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.11/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -540,7 +540,11 @@ let documents = try Document.fetchAll(db,
|
||||
Use them in the [query interface](../README.md#the-query-interface):
|
||||
|
||||
```swift
|
||||
// Search in all columns
|
||||
let documents = try Document.matching(pattern).fetchAll(db)
|
||||
|
||||
// Search in a specific column:
|
||||
let documents = try Document.filter(Column("content").match(pattern)).fetchAll(db)
|
||||
```
|
||||
|
||||
|
||||
|
||||
@@ -387,16 +387,16 @@ let publisher = observation
|
||||
|
||||
> :question: This change makes it possible to concatenate subqueries with the UNION operator.
|
||||
|
||||
4. In order to extract raw SQL string from an [SQLLiteral], you now need a database connection:
|
||||
4. In order to extract raw SQL string from an [SQL literal], you now need a database connection:
|
||||
|
||||
```swift
|
||||
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
|
||||
// BEFORE: GRDB 4
|
||||
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
print(query.sql) // prints "UPDATE player SET name = ? WHERE id = ?"
|
||||
print(query.arguments) // prints ["O'Brien", 42]
|
||||
|
||||
// NEW: GRDB 5
|
||||
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
let (sql, arguments) = try dbQueue.read(query.build)
|
||||
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
|
||||
print(arguments) // prints ["O'Brien", 42]
|
||||
@@ -506,7 +506,7 @@ let publisher = observation
|
||||
[Custom SQL functions]: ../README.md#custom-sql-functions
|
||||
[Batch updates]: ../README.md#update-requests
|
||||
[SQL Interpolation]: SQLInterpolation.md
|
||||
[SQLLiteral]: SQLInterpolation.md#sqlliteral
|
||||
[SQL literal]: SQLInterpolation.md#sql-literal
|
||||
[SQLRequest]: ../README.md#custom-requests
|
||||
[QueryInterfaceRequest]: ../README.md#requests
|
||||
[Combine publishers]: Combine.md
|
||||
|
||||
@@ -9,6 +9,8 @@ To support this guide, we'll design a simple library application that lets the u
|
||||
|
||||
- [Trust SQLite More Than Yourself]
|
||||
- [Persistable Record Types are Responsible for Their Tables]
|
||||
- [Record Types Hide Intimate Database Details]
|
||||
- [Singleton Records]
|
||||
- [Define Record Requests]
|
||||
- [Compose Records]
|
||||
- [How to Design Database Managers]
|
||||
@@ -96,13 +98,13 @@ Define one record type per database table, and make it adopt a [PersistableRecor
|
||||
In this sample code, we'll use Codable structs, but there are [other ways](../README.md#examples-of-record-definitions) to define records.
|
||||
|
||||
```swift
|
||||
struct Author: Codable {
|
||||
struct Author: Codable, Identifiable {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
var country: String?
|
||||
}
|
||||
|
||||
struct Book: Codable {
|
||||
struct Book: Codable, Identifiable {
|
||||
var id: Int64?
|
||||
var authorId: Int64
|
||||
var title: String
|
||||
@@ -138,12 +140,108 @@ That's it. The `Author` type can read and write in the `author` database table.
|
||||
> print(author.id!) // Guaranteed non-nil id
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> :bulb: **Tip**: When the database table has a single-column primary key, have your record type adopt the standard [Identifiable] protocol. This allows GRDB to define type-safe id-related methods:
|
||||
>
|
||||
> ```swift
|
||||
> let authorID: Int64 = ...
|
||||
> let author: Author? = try dbQueue.read { db in
|
||||
> try Author.fetchOne(db, id: authorID)
|
||||
> }
|
||||
> ```
|
||||
|
||||
Since `Author` and `Book` can insert, update, and delete rows in the `author` and `book` database tables, they are *responsible for modifying those database tables*.
|
||||
Now that `Author` and `Book` can read and write in their own database tables, they are responsible for it. Make sure each record type deals with one database table, and only one database table!
|
||||
|
||||
Applying the **[Single Responsibility Principle]** has a consequence: don't even try to have an author responsible for its books. Don't add a `books: [Book]` property in Author. Don't let Author write in the `book` table. When a new fellow coworker joins your team and asks you "who is saving books in the database?", you don't want to answer "it depends." You want to confidently answer: "the Book type".
|
||||
|
||||
> :bulb: **Tip**: Make sure each record type deals with one database table, and only one database table.
|
||||
## Record Types Hide Intimate Database Details
|
||||
|
||||
The application uses `Book` and `Author` as regular structs, using their properties. Each of those properties matches a column in the database (`Book.title`, `Author.id`), and is defined with a Swift type that is natively supported by SQLite (`String`, `Int`, etc.)
|
||||
|
||||
Sometimes, it happens that raw database column names and types are not a very good fit for the application.
|
||||
|
||||
Let's look at three examples:
|
||||
|
||||
1. Authors write books, and more specifically novels, poems, essays, or theatre plays. Let's add a `kind` column in the database. For easy debugging of the database contents, a book kind is represented as a string ("novel", "essay", etc.):
|
||||
|
||||
```swift
|
||||
try db.create(table: "book") { t in
|
||||
...
|
||||
t.column("kind", .text).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
In Swift, it is not a good practice to use `String` for the type of the `kind` property. We want an enum instead:
|
||||
|
||||
```swift
|
||||
struct Book: Codable {
|
||||
enum Kind: String, Codable {
|
||||
case novel, poems, essay, play
|
||||
}
|
||||
var id: Int64?
|
||||
var authorId: Int64
|
||||
var title: String
|
||||
var kind: Kind
|
||||
}
|
||||
```
|
||||
|
||||
In order to make it possible to use `Book.Kind` in book requests (see [Define Record Requests] below), we add this conformance:
|
||||
|
||||
```swift
|
||||
extension Book.Kind: DatabaseValueConvertible { }
|
||||
```
|
||||
|
||||
> :bulb: Records can pick the best suited [Value] type for their column properties (Bool, Int, String, Date, etc.) Thanks to its enum property, the `Book` record prevents unknown book kinds from entering the database.
|
||||
|
||||
2. GPS coordinates are usually stored in two distinct `latitude` and `longitude` columns. But the standard way to deal with such coordinate is a single `CLLocationCoordinate2D` struct.
|
||||
|
||||
When this happens, keep column properties private, and provide sensible accessors instead:
|
||||
|
||||
```swift
|
||||
struct Place: Codable {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
private var latitude: CLLocationDegrees
|
||||
private var longitude: CLLocationDegrees
|
||||
|
||||
var coordinate: CLLocationCoordinate2D {
|
||||
get {
|
||||
CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
|
||||
}
|
||||
set {
|
||||
latitude = newValue.latitude
|
||||
longitude = newValue.longitude
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: Private properties make it possible to hide raw columns from the rest of the application.
|
||||
|
||||
3. The record below exposes a `price: Decimal` property ($12.00), backed by an integer column that stores a quantity of cents (1200). An integer column is preferred because it allows SQLite to compute exact sums of prices.
|
||||
|
||||
```swift
|
||||
struct Product: Codable {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
private var priceCents: Int
|
||||
|
||||
var price: Decimal {
|
||||
get { Decimal(priceCents) / 100 }
|
||||
set { priceCents = NSDecimalNumber(decimal: newValue * 100).intValue }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: Private properties allow records to choose both their best database representation, and at the same time, their best Swift interface.
|
||||
|
||||
**Generally speaking**, record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. When needed, you can even [validate values](../README.md#customizing-the-persistence-methods) before they enter the database.
|
||||
|
||||
|
||||
## Singleton Records
|
||||
|
||||
**Singleton Records** are records that store configuration values, user preferences, and generally some global application state. They are backed by a database table that contains a single row.
|
||||
|
||||
The recommended setup for such records is described in the [Single-Row Tables](SingleRowTables.md) guide. Go check it, and come back when you're done!
|
||||
|
||||
|
||||
## Define Record Requests
|
||||
@@ -166,7 +264,7 @@ extension Author {
|
||||
}
|
||||
```
|
||||
|
||||
Otherwise, declare a plain String enum that conforms to the ColumnExpression protocol:
|
||||
Otherwise, declare a plain `String` enum that conforms to the `ColumnExpression` protocol:
|
||||
|
||||
```swift
|
||||
// For a non-codable record
|
||||
@@ -178,31 +276,50 @@ extension Author {
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: **Tip**: Define commonly used requests in a constrained extension of the `DerivableRequest` protocol.
|
||||
|
||||
The `DerivableRequest` protocol generally lets you filter, sort, and join or include associations (we'll talk about associations in the [Compose Records] chapter below).
|
||||
|
||||
Here is how you define those requests:
|
||||
Those columns let you define requests:
|
||||
|
||||
```swift
|
||||
// Some requests of Author --------------------v
|
||||
try dbQueue.read { db in
|
||||
// Order authors by name, in a localized case-insensitive fashion
|
||||
let sortedAuthors: [Author] = try Author.all()
|
||||
.order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
.fetchAll(db)
|
||||
|
||||
// French authors
|
||||
let frenchAuthors: [Author] = try Author.all()
|
||||
.filter(Author.Columns.country == "France")
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: **Tip**: Define commonly used requests in a constrained extension of the `DerivableRequest` protocol.
|
||||
|
||||
When you find yourself build similar requests over and over in your application, you may want to define a reusable and composable request vocabulary. This will avoid repetition in your app, ease refactoring, and enable [testability](DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift).
|
||||
|
||||
To do so, extend the `DerivableRequest` protocol. It generally lets you filter, sort, leverage associations (we'll talk about associations in the [Compose Records] chapter below), etc:
|
||||
|
||||
```swift
|
||||
// Author requests ~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
extension DerivableRequest where RowDecoder == Author {
|
||||
|
||||
/// Returns a request for all authors ordered by name, in a localized
|
||||
/// case-insensitive fashion
|
||||
/// Order authors by name, in a localized case-insensitive fashion
|
||||
func orderByName() -> Self {
|
||||
let name = Author.Columns.name
|
||||
return order(name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
|
||||
/// Returns a request for all authors from a country
|
||||
/// Filters authors from a country
|
||||
func filter(country: String) -> Self {
|
||||
filter(Author.Columns.country == country)
|
||||
}
|
||||
|
||||
/// Filters authors with at least one book
|
||||
func havingBooks() -> Self {
|
||||
having(Author.books.isEmpty == false)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Those methods defined on the `DerivableRequest` protocol hide intimate database details. They allow you to compose database requests in a fluent style:
|
||||
Those methods encapsulate intimate database details, and allow you to compose database requests in a fluent and legible style:
|
||||
|
||||
```swift
|
||||
try dbQueue.read { db in
|
||||
@@ -214,72 +331,55 @@ try dbQueue.read { db in
|
||||
.filter(country: "France")
|
||||
.fetchAll(db)
|
||||
|
||||
let sortedSpanishAuthors: [Author] = try Author.all()
|
||||
let sortedSpanishAuthorsHavingBooks: [Author] = try Author.all()
|
||||
.filter(country: "Spain")
|
||||
.havingBooks()
|
||||
.orderByName()
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
Those customized request methods are also available on record associations, because associations conform to the `DerivableRequest` protocol:
|
||||
Because they are defined in an extension of the `DerivableRequest` protocol, our customized methods can decorate both requests and associations. See how the implementation of `filter(authorCountry:)` for books, below, uses the `filter(country:)` for authors:
|
||||
|
||||
```swift
|
||||
// Some requests of Book
|
||||
// Book requests ~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
extension DerivableRequest where RowDecoder == Book {
|
||||
/// Returns a request for all books from a country
|
||||
/// Filters books by kind
|
||||
func filter(kind: Book.Kind) -> Self {
|
||||
filter(Book.Columns.kind == kind)
|
||||
}
|
||||
|
||||
/// Filters books from a country
|
||||
func filter(authorCountry: String) -> Self {
|
||||
// A book is from a country if it can be
|
||||
// joined with an author from that country:
|
||||
// ---------------------------v
|
||||
// Books do not have any country column. But their author has one.
|
||||
// A book is from a country if it can be joined to an author from this country:
|
||||
joining(required: Book.author.filter(country: authorCountry))
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.read { db in
|
||||
let italianBooks = try Book.all()
|
||||
let italianNovels: [Book] = try Book.all()
|
||||
.filter(kind: .novel)
|
||||
.filter(authorCountry: "Italy")
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
Not *every requests* can be expressed on `DerivableRequest`. For example, [Association Aggregates] are out of scope. When this happens, define your requests in a constrained extension to `QueryInterfaceRequest`:
|
||||
Extensions to the `DerivableRequest` protocol can not change the type of requests. This has to be expressed in an extension to `QueryInterfaceRequest`. For example:
|
||||
|
||||
```swift
|
||||
// More requests of Author -------------------------v
|
||||
// Author requests ~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
extension QueryInterfaceRequest where RowDecoder == Author {
|
||||
/// Returns a request for all authors with at least one book
|
||||
func havingBooks() -> QueryInterfaceRequest<Author> {
|
||||
having(Author.books.isEmpty == false)
|
||||
// Selects author ids
|
||||
func id() -> QueryInterfaceRequest<Int64> {
|
||||
select(Author.Columns.id)
|
||||
}
|
||||
}
|
||||
|
||||
// IDs of French authors
|
||||
let ids: [Int64] = try Author.all().filter(country: "France").id().fetchAll(db)
|
||||
```
|
||||
|
||||
Those requests defined on `QueryInterfaceRequest` still compose fluently:
|
||||
|
||||
```swift
|
||||
try dbQueue.read { db in
|
||||
let sortedFrenchAuthorsHavingBooks = try Author.all()
|
||||
.filter(country: "France")
|
||||
.havingBooks() // <-
|
||||
.orderByName()
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
Finally, when it happens that a request only makes sense when defined on the Record type itself, just go ahead and define a static method or property of your Record type:
|
||||
|
||||
```swift
|
||||
extension MySingletonRecord {
|
||||
/// The one any only record stored in the database
|
||||
static let shared = all().limit(1)
|
||||
}
|
||||
|
||||
let singleton = try dbQueue.read { db
|
||||
try MySingletonRecord.shared.fetchOne(db)
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Compose Records
|
||||
|
||||
We'd like to navigate from books to authors and vice-versa: we may want to know an author's books, or a book's author.
|
||||
@@ -358,7 +458,7 @@ Granted with primitive and derived record types, your application will load the
|
||||
let authorId = 123
|
||||
let authorInfo: AuthorInfo? = try dbQueue.read { db in
|
||||
let request = Author
|
||||
.filter(key: authorId)
|
||||
.filter(id: authorId)
|
||||
.including(all: Author.books)
|
||||
return try AuthorInfo.fetchOne(db, request)
|
||||
}
|
||||
@@ -374,7 +474,7 @@ Granted with primitive and derived record types, your application will load the
|
||||
let bookId = 123
|
||||
let bookInfo: BookInfo? = try dbQueue.read { db in
|
||||
let request = Book
|
||||
.filter(key: bookId)
|
||||
.filter(id: bookId)
|
||||
.including(required: Book.author)
|
||||
return try BookInfo.fetchOne(db, request)
|
||||
}
|
||||
@@ -411,7 +511,7 @@ Those properties provide an alternative way to feed our application:
|
||||
}
|
||||
let authorId = 123
|
||||
let authorInfo: AuthorInfo? = try dbQueue.read { db in
|
||||
guard let author = try Author.fetchOne(db, key: authorId) else {
|
||||
guard let author = try Author.fetchOne(db, id: authorId) else {
|
||||
return nil
|
||||
}
|
||||
let books = try author.books.fetchAll(db)
|
||||
@@ -430,7 +530,7 @@ Those properties provide an alternative way to feed our application:
|
||||
}
|
||||
let bookId = 123
|
||||
let bookInfo: BookInfo? = try dbQueue.read { db in
|
||||
guard let book = try Book.fetchOne(db, key: bookId) else {
|
||||
guard let book = try Book.fetchOne(db, id: bookId) else {
|
||||
return nil
|
||||
}
|
||||
guard let author = try book.author.fetchOne(db) else {
|
||||
@@ -472,7 +572,7 @@ class NaiveLibraryManager {
|
||||
func author(id: Int64) -> Author? {
|
||||
do {
|
||||
return try dbQueue.read { db in
|
||||
try Author.fetchOne(db, key: id)
|
||||
try Author.fetchOne(db, id: id)
|
||||
}
|
||||
} catch {
|
||||
return nil
|
||||
@@ -482,7 +582,7 @@ class NaiveLibraryManager {
|
||||
func book(id: Int64) -> Book? {
|
||||
do {
|
||||
return try dbQueue.read { db in
|
||||
try Book.fetchOne(db, key: id)
|
||||
try Book.fetchOne(db, id: id)
|
||||
}
|
||||
} catch {
|
||||
return nil
|
||||
@@ -531,13 +631,13 @@ class ImprovedLibraryManager {
|
||||
|
||||
func author(id: Int64) throws -> Author? {
|
||||
try dbQueue.read { db in
|
||||
try Author.fetchOne(db, key: id)
|
||||
try Author.fetchOne(db, id: id)
|
||||
}
|
||||
}
|
||||
|
||||
func book(id: Int64) throws -> Book? {
|
||||
try dbQueue.read { db in
|
||||
try Book.fetchOne(db, key: id)
|
||||
try Book.fetchOne(db, id: id)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -611,7 +711,7 @@ extension LibraryManager {
|
||||
|
||||
func bookInfo(bookId: Int64) throws -> BookInfo? {
|
||||
try dbQueue.read { db in
|
||||
guard let book = try Book.fetchOne(db, key: bookId) else {
|
||||
guard let book = try Book.fetchOne(db, id: bookId) else {
|
||||
return nil
|
||||
}
|
||||
guard let author = try book.author.fetchOne(db) else {
|
||||
@@ -631,7 +731,7 @@ extension LibraryManager {
|
||||
|
||||
func authorInfo(authorId: Int64) throws -> AuthorInfo? {
|
||||
try dbQueue.read { db in
|
||||
guard let author = try Author.fetchOne(db, key: authorId) else {
|
||||
guard let author = try Author.fetchOne(db, id: authorId) else {
|
||||
return nil
|
||||
}
|
||||
let books = try author.books.fetchAll(db)
|
||||
@@ -696,7 +796,6 @@ Instead, have a look at [Database Observation]:
|
||||
[Django]: https://docs.djangoproject.com/en/2.0/topics/db/
|
||||
[record protocols]: ../README.md#record-protocols-overview
|
||||
[Separation of Concerns]: https://en.wikipedia.org/wiki/Separation_of_concerns
|
||||
[Single Responsibility Principle]: https://en.wikipedia.org/wiki/Single_responsibility_principle
|
||||
[Single Source of Truth]: https://en.wikipedia.org/wiki/Single_source_of_truth
|
||||
[Divide and Conquer]: https://en.wikipedia.org/wiki/Divide_and_rule
|
||||
[Why Adopt GRDB?]: WhyAdoptGRDB.md
|
||||
@@ -713,6 +812,8 @@ Instead, have a look at [Database Observation]:
|
||||
[TransactionObserver]: ../README.md#transactionobserver-protocol
|
||||
[Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself
|
||||
[Persistable Record Types are Responsible for Their Tables]: #persistable-record-types-are-responsible-for-their-tables
|
||||
[Record Types Hide Intimate Database Details]: #record-types-hide-intimate-database-details
|
||||
[Singleton Records]: #singleton-records
|
||||
[Define Record Requests]: #define-record-requests
|
||||
[Compose Records]: #compose-records
|
||||
[How to Design Database Managers]: #how-to-design-database-managers
|
||||
@@ -727,3 +828,5 @@ Instead, have a look at [Database Observation]:
|
||||
[Codable Record]: ../README.md#codable-records
|
||||
[CodingKeys]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
|
||||
[Combine Support]: Combine.md
|
||||
[Value]: ../README.md#values
|
||||
[Identifiable]: https://developer.apple.com/documentation/swift/identifiable
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 498 KiB |
@@ -68,7 +68,7 @@ try dbQueue.read { db in
|
||||
}
|
||||
```
|
||||
|
||||
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.3/Structs/DatabaseMigrator.html) for more migrator methods.
|
||||
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.11/Structs/DatabaseMigrator.html) for more migrator methods.
|
||||
|
||||
|
||||
## The `eraseDatabaseOnSchemaChange` Option
|
||||
@@ -119,4 +119,26 @@ migrator.registerMigration("AddNotNullCheckOnName") { db in
|
||||
}
|
||||
```
|
||||
|
||||
## Asynchronous Migrations
|
||||
|
||||
`DatabaseMigrator` provides two ways to migrate a database in an asynchronous way.
|
||||
|
||||
The `asyncMigrate(_:completion:)` method:
|
||||
|
||||
```swift
|
||||
// Completes in a protected dispatch queue that can write in the database
|
||||
migrator.asyncMigrate(dbQueue, completion: { db, error in
|
||||
if let error = error {
|
||||
// Some error occurred during migrations
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
The `migratePublisher(_:receiveOn:)` [Combine](https://developer.apple.com/documentation/combine) publisher:
|
||||
|
||||
```swift
|
||||
// DatabasePublishers.Migrate
|
||||
let publisher = migrator.migratePublisher(dbQueue)
|
||||
```
|
||||
|
||||
This publisher completes on the main queue, unless you provide a specific [scheduler](https://developer.apple.com/documentation/combine/scheduler) to the `receiveOn` argument.
|
||||
+12
-12
@@ -212,30 +212,30 @@ extension Base: MyDatabaseDecoder {
|
||||
//: **prepared statement**:
|
||||
//:
|
||||
//: try dbQueue.read { db in
|
||||
//: let statement = try db.makeSelectStatement(sql: "SELECT ...")
|
||||
//: let statement = try db.makeStatement(sql: "SELECT ...")
|
||||
//: try Base.fetchCursor(statement) // Cursor of Base
|
||||
//: try Base.fetchAll(statement) // [Base]
|
||||
//: try Base.fetchOne(statement) // Base?
|
||||
//: }
|
||||
|
||||
extension MyDatabaseDecoder {
|
||||
// MARK: - Fetch from SelectStatement
|
||||
// MARK: - Fetch from Prepared Statement
|
||||
|
||||
// SelectStatement, StatementArguments, and RowAdapter are the fundamental
|
||||
// Statement, StatementArguments, and RowAdapter are the fundamental
|
||||
// fetching parameters of GRDB. Make sure to accept them all:
|
||||
static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
|
||||
static func fetchCursor(_ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
|
||||
// Turn the cursor of raw rows into a cursor of decoded rows
|
||||
return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map {
|
||||
self.decode(row: $0)
|
||||
}
|
||||
}
|
||||
|
||||
static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [DecodedType] {
|
||||
static func fetchAll(_ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [DecodedType] {
|
||||
// Turn the cursor into an Array
|
||||
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DecodedType? {
|
||||
static func fetchOne(_ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DecodedType? {
|
||||
// Consume the first value of the cursor
|
||||
return try fetchCursor(statement, arguments: arguments, adapter: adapter).next()
|
||||
}
|
||||
@@ -243,7 +243,7 @@ extension MyDatabaseDecoder {
|
||||
|
||||
try dbQueue.read { db in
|
||||
print("> Fetch from prepared statement")
|
||||
let statement = try db.makeSelectStatement(sql: "SELECT * FROM base")
|
||||
let statement = try db.makeStatement(sql: "SELECT * FROM base")
|
||||
let bases = try Base.fetchAll(statement)
|
||||
for base in bases {
|
||||
print(base.description)
|
||||
@@ -368,15 +368,15 @@ extension MyDatabaseDecoder {
|
||||
// MARK: - Fetch from SQL
|
||||
|
||||
static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
|
||||
try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [DecodedType] {
|
||||
try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DecodedType? {
|
||||
try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -422,7 +422,7 @@ protocol ContextFetchableRecord {
|
||||
|
||||
extension ContextFetchableRecord {
|
||||
static func fetchCursor(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil,
|
||||
context: Context)
|
||||
@@ -454,7 +454,7 @@ protocol FailableFetchableRecord {
|
||||
|
||||
extension FailableFetchableRecord {
|
||||
static func fetchCursor(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> MapCursor<RowCursor, Self>
|
||||
|
||||
@@ -8,16 +8,39 @@ configuration.prepareDatabase { db in
|
||||
}
|
||||
let dbQueue = DatabaseQueue(configuration: configuration)
|
||||
|
||||
try! dbQueue.inDatabase { db in
|
||||
struct Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
var score: Int
|
||||
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
|
||||
try db.execute(sql: "INSERT INTO player (name, score) VALUES (?, ?)", arguments: ["Arthur", 1000])
|
||||
try db.execute(sql: "INSERT INTO player (name, score) VALUES (?, ?)", arguments: ["Barbara", 1000])
|
||||
do {
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try player.insert(db)
|
||||
player = Player(id: nil, name: "Barbara", score: 100)
|
||||
try player.insert(db)
|
||||
}
|
||||
|
||||
let names = try String.fetchAll(db, sql: "SELECT name FROM player")
|
||||
print(names)
|
||||
do {
|
||||
let players = try Player.fetchAll(db)
|
||||
for player in players {
|
||||
print(player)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let count = try Player.fetchCount(db)
|
||||
print(count)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,632 @@
|
||||
Query Interface Organization
|
||||
============================
|
||||
|
||||
**The [query interface] is a Swift API that approximates the [SQLite SELECT query grammar](https://sqlite.org/lang_select.html) through a hierarchy of values and protocols.**
|
||||
|
||||
This document exposes its inner organization, so that you can leverage the most of those types and protocols when you want it.
|
||||
|
||||
In the diagram below, protocols are pale blue and have rounded corners, and standard types are grey rectangles. Solid arrows read "inherits from", and dashed arrows read "produces". Generic types are marked as such, as well as "PATs" (protocols with associated types).
|
||||
|
||||
<img src="https://github.com/groue/GRDB.swift/raw/development/Documentation/Images/QueryInterfaceOrganization2.png" width="100%">
|
||||
|
||||
Diagram items are described below:
|
||||
|
||||
- [Association]
|
||||
- [Column]
|
||||
- [ColumnExpression]
|
||||
- [DatabaseRegionConvertible]
|
||||
- [DatabaseValue]
|
||||
- [DatabaseValueConvertible]
|
||||
- [DerivableRequest]
|
||||
- [FetchRequest]
|
||||
- [Int, String, Date…]
|
||||
- [QueryInterfaceRequest]
|
||||
- [SQL]
|
||||
- [SQLExpression]
|
||||
- [SQLExpressible]
|
||||
- [SQLOrderingTerm]
|
||||
- [SQLOrdering]
|
||||
- [SQLRequest]
|
||||
- [SQLSelectable]
|
||||
- [SQLSelection]
|
||||
- [SQLSpecificExpressible]
|
||||
- [SQLSubquery]
|
||||
- [SQLSubqueryable]
|
||||
|
||||
---
|
||||
|
||||
### Association
|
||||
|
||||
`Association` is the protocol for all [associations]. It is adopted by `BelongsToAssociation`, `HasManyAssociation`, etc. It conforms to [DerivableRequest].
|
||||
|
||||
```swift
|
||||
protocol Association: DerivableRequest {
|
||||
associatedtype OriginRowDecoder
|
||||
func forKey(_ key: String) -> Self
|
||||
}
|
||||
```
|
||||
|
||||
Association has two sub-protocols:
|
||||
|
||||
```swift
|
||||
protocol AssociationToOne: Association { }
|
||||
protocol AssociationToMany: Association { }
|
||||
```
|
||||
|
||||
`AssociationToMany`, adopted by `HasManyAssociation` and `HasManyThroughAssociation`, leverages [association aggregates].
|
||||
|
||||
### Column
|
||||
|
||||
`Column` is the type for database columns. It conforms to [ColumnExpression].
|
||||
|
||||
```swift
|
||||
Column("name")
|
||||
Column("id")
|
||||
Column.rowID
|
||||
```
|
||||
|
||||
|
||||
### ColumnExpression
|
||||
|
||||
`ColumnExpression` is the protocol for database columns. It is adopted by [Column]. It conforms to [SQLSpecificExpressible].
|
||||
|
||||
```swift
|
||||
protocol ColumnExpression: SQLSpecificExpressible {
|
||||
/// The name of a database column.
|
||||
var name: String { get }
|
||||
}
|
||||
```
|
||||
|
||||
Columns can be used, for example, to query database rows:
|
||||
|
||||
```swift
|
||||
let row = try Row.fetchOne(db, sql: "SELECT 'Arthur' AS name")!
|
||||
let name: String = row[Column("name")] // "Arthur"
|
||||
```
|
||||
|
||||
Columns are special expressions that allow some optimizations and niceties:
|
||||
|
||||
- Database observation: When a request is limited to a known list of rowids in a database table, changes applied to other rows do not trigger the observation. GRDB needs column expressions in order to apply this optimization:
|
||||
|
||||
```swift
|
||||
// Optimized Observations
|
||||
ValueObservation.tracking { db in
|
||||
try Player.fetchOne(db, id: 1)
|
||||
// or
|
||||
try Player.filter(Column("id") == 1).fetchOne(db)
|
||||
}
|
||||
|
||||
// Non-optimized observations
|
||||
ValueObservation.tracking { db in
|
||||
try SQLRequest<Player>("SELECT * FROM player WHERE id = 1").fetchOne(db)
|
||||
// or
|
||||
try Player.filter(sql: "id = 1").fetchOne(db)
|
||||
}
|
||||
```
|
||||
|
||||
- SQL generation: when it generates SQL queries, GRDB appends `LIMIT 1` or not, depending on the primary key and unique indexes used on the queried table. GRDB needs column expressions in order to improve its SQL generation:
|
||||
|
||||
```swift
|
||||
// Nicer SQL
|
||||
// SELECT * FROM player WHERE id = 1
|
||||
try Player.fetchOne(db, id: 1)
|
||||
try Player.filter(Column("id") == 1).fetchOne(db)
|
||||
|
||||
// Less nice SQL
|
||||
// SELECT * FROM player WHERE id = 1 LIMIT 1
|
||||
try Player.filter(sql: "id = 1").fetchOne(db)
|
||||
```
|
||||
|
||||
### DatabaseRegionConvertible
|
||||
|
||||
`DatabaseRegionConvertible` is the protocol for observable requests. It is adopted by [FetchRequest].
|
||||
|
||||
```swift
|
||||
protocol DatabaseRegionConvertible {
|
||||
func databaseRegion(_ db: Database) throws -> DatabaseRegion
|
||||
}
|
||||
```
|
||||
|
||||
DatabaseRegionConvertible feeds [DatabaseRegionObservation], which tracks database transactions that impact a particular database region:
|
||||
|
||||
```swift
|
||||
let request = Player.all()
|
||||
let observation = DatabaseRegionObservation(tracking: request)
|
||||
let observer = try observation.start(in: dbQueue) { (db: Database) in
|
||||
print("Players were changed")
|
||||
}
|
||||
```
|
||||
|
||||
### DatabaseValue
|
||||
|
||||
`DatabaseValue` is the type for SQL values (integers, doubles, strings, blobs, and NULL). It conforms to [SQLSpecificExpressible].
|
||||
|
||||
You generally build a DatabaseValue from a [DatabaseValueConvertible] type:
|
||||
|
||||
```swift
|
||||
1.databaseValue
|
||||
"Hello".databaseValue
|
||||
DatabaseValue.null
|
||||
```
|
||||
|
||||
The query interface will sometimes not accept raw [SQLExpressible] values such as [Int, String, Date], etc. In this case, turn those values into DatabaseValue so that you leverage APIs that need [SQLSpecificExpressible]. For example:
|
||||
|
||||
```swift
|
||||
// SQL: firstName || ' ' || lastName
|
||||
let fullname = [
|
||||
Column("firstName"),
|
||||
" ".databaseValue,
|
||||
Column("lastName"),
|
||||
].joined(operator: .concat)
|
||||
```
|
||||
|
||||
### DatabaseValueConvertible
|
||||
|
||||
`DatabaseValueConvertible` is the protocol for types that can provide [DatabaseValue]: SQL integers, doubles, strings, blobs, and NULL. It is adopted by [Int, String, Date], etc. It conforms to [SQLExpressible] because all SQL values are SQL expressions.
|
||||
|
||||
```swift
|
||||
protocol DatabaseValueConvertible: SQLExpressible {
|
||||
/// Returns a value that can be stored in the database.
|
||||
var databaseValue: DatabaseValue { get }
|
||||
|
||||
/// Returns a value initialized from `dbValue`, if possible.
|
||||
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self?
|
||||
}
|
||||
```
|
||||
|
||||
### DerivableRequest
|
||||
|
||||
`DerivableRequest` is the protocol for query interface requests and associations that can be refined. It is adopted by [QueryInterfaceRequest] and [Association].
|
||||
|
||||
```swift
|
||||
protocol DerivableRequest: AggregatingRequest, FilteredRequest,
|
||||
JoinableRequest, OrderedRequest,
|
||||
SelectionRequest, TableRequest
|
||||
{
|
||||
func distinct() -> Self
|
||||
func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> Self
|
||||
}
|
||||
```
|
||||
|
||||
- `AggregatingRequest` provides grouping methods such as `groupByPrimaryKey()`
|
||||
- `FilteredRequest` provides filtering methods such as `filter(expression)` or `filter(id: value)`
|
||||
- `JoinableRequest` provides association methods such as `joining(required: association)` or `including(all: association)`
|
||||
- `OrderedRequest` provides ordering methods such as `order(ordering)` or `reversed()`
|
||||
- `SelectionRequest` provides selection methods such as `select(selection)` or `annotated(with: selection)`
|
||||
- `TableRequest` provides table targeting methods such as `aliased(tableAlias)`
|
||||
|
||||
DerivableRequest makes it possible to build reusable code snippets that apply to both requests and associations. You'll read more about it in the [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md) and [Associations](AssociationsBasics.md).
|
||||
|
||||
### FetchRequest
|
||||
|
||||
`FetchRequest` is the protocol for requests that can fetch. It is adopted by [QueryInterfaceRequest] and [SQLRequest]. It conforms to [SQLSubqueryable] and [DatabaseRegionConvertible].
|
||||
|
||||
```swift
|
||||
protocol FetchRequest: SQLSubqueryable, DatabaseRegionConvertible {
|
||||
/// The type that tells how fetched database rows should be interpreted.
|
||||
associatedtype RowDecoder
|
||||
|
||||
/// Returns a PreparedRequest that is ready to be executed.
|
||||
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
|
||||
|
||||
/// Returns the number of rows fetched by the request.
|
||||
func fetchCount(_ db: Database) throws -> Int
|
||||
}
|
||||
```
|
||||
|
||||
FetchRequest can fetch values from the database as long as its `RowDecoder` associated type is `Row`, a [DatabaseValueConvertible] type, or a [FetchableRecord] type.
|
||||
|
||||
```swift
|
||||
let row: Row? = try SQLRequest<Row>("SELECT * FROM player").fetchOne(db)
|
||||
let players: [Player] = try Player.all().fetchAll(db)
|
||||
```
|
||||
|
||||
FetchRequest usually executes a single SQL query:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player
|
||||
let request = Player.all()
|
||||
try request.fetchAll(db)
|
||||
```
|
||||
|
||||
This single SQL query is exposed through `makePreparedRequest(_:forSingleResult:)`:
|
||||
|
||||
```swift
|
||||
let request = Player.all()
|
||||
let preparedRequest = try request.makePreparedRequest(db)
|
||||
print(preparedRequest.statement.sql) // SELECT * FROM player
|
||||
```
|
||||
|
||||
But not all fetch requests execute a single SQL query. A [QueryInterfaceRequest] that involves [associations] can execute several:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player
|
||||
// SELECT * FROM award WHERE playerId IN (...)
|
||||
struct PlayerInfo: Decodable, FetchableRecord {
|
||||
var player: Player
|
||||
var awards: [Award]
|
||||
}
|
||||
let playerInfos = try Player
|
||||
.including(all: Player.awards)
|
||||
.asRequest(of: PlayerInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
Those supplementary SQL queries are an implementation detail of `PreparedRequest`, and are not currently exposed.
|
||||
|
||||
### Int, String, Date…
|
||||
|
||||
The basic value types conform to [DatabaseValueConvertible] so that they can feed database queries with [DatabaseValue]:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player WHERE name = 'O''Brien'
|
||||
// ~~~~~~~~~~
|
||||
Player.filter(Column("name") == "O'Brien")
|
||||
```
|
||||
|
||||
### QueryInterfaceRequest
|
||||
|
||||
`QueryInterfaceRequest` is the type of fetch requests built by the GRDB query builder. It conforms to [FetchRequest] and [DerivableRequest].
|
||||
|
||||
It is generic on the type of fetched values:
|
||||
|
||||
```swift
|
||||
struct PlayerInfo: Decodable, FetchableRecord {
|
||||
var player: Player
|
||||
var awards: [Award]
|
||||
}
|
||||
|
||||
// QueryInterfaceRequest<Player>
|
||||
let playerRequest = Player.all()
|
||||
|
||||
// QueryInterfaceRequest<String>
|
||||
let nameRequest = Player.select(Column("name"), as: String.self)
|
||||
|
||||
// QueryInterfaceRequest<PlayerInfo>
|
||||
let playerInfoRequest = Player
|
||||
.including(all: Player.awards)
|
||||
.asRequest(of: PlayerInfo.self)
|
||||
|
||||
try playerRequest.fetchAll(db) // [Player]
|
||||
try nameRequest.fetchAll(db) // [String]
|
||||
try playerInfoRequest.fetchAll(db) // [PlayerInfo]
|
||||
```
|
||||
|
||||
For more information on QueryInterfaceRequest, see [Requests](../README.md#requests) and [Associations](AssociationsBasics.md).
|
||||
|
||||
### SQL
|
||||
|
||||
`SQL` is the type for SQL literals that support [SQL Interpolation]. It can feed all GRDB APIs that have a `literal` argument:
|
||||
|
||||
```swift
|
||||
let literal: SQL = "SELECT * FROM player"
|
||||
let request = SQLRequest<Player>(literal: literal)
|
||||
let players: [Player] = try request.fetchAll(db)
|
||||
```
|
||||
|
||||
`SQL` conforms to [SQLSpecificExpressible], and thus behaves as an [SQLite expression](https://sqlite.org/syntax/expr.html) by default:
|
||||
|
||||
```swift
|
||||
let literal: SQL = "name = \("O'Brien")"
|
||||
let request = Player.filter(literal)
|
||||
let players: [Player] = try request.fetchAll(db)
|
||||
```
|
||||
|
||||
:warning: **Warning**: Not all SQL snippets are expressions. It is not recommended to pass `SQL` literals around, or you may end up forgetting their content, and eventually generate invalid SQL. When possible, prefer building an explicit [SQLExpression], [SQLOrdering], [SQLSelection], [SQLRequest], or [SQLSubquery], depending on what you want to express:
|
||||
|
||||
```swift
|
||||
// SQLExpression
|
||||
SQL("name = \("O'Brien")").sqlExpression
|
||||
|
||||
// SQLOrdering
|
||||
SQL("name DESC)").sqlOrdering
|
||||
|
||||
// SQLSelection
|
||||
SQL("score + bonus AS total)").sqlSelection
|
||||
SQL("*").sqlSelection
|
||||
|
||||
// SQLRequest
|
||||
SQLRequest<Player>(literal: "SELECT * FROM player")
|
||||
|
||||
// SQLSubquery
|
||||
SQLRequest(literal: "SELECT * FROM player").sqlSubquery
|
||||
```
|
||||
|
||||
### SQLExpression
|
||||
|
||||
`SQLExpression` is the opaque type for all [SQLite expressions](https://sqlite.org/syntax/expr.html). It adopts [SQLSpecificExpressible], and is built from [SQLExpressible].
|
||||
|
||||
```swift
|
||||
struct SQLExpression: SQLSpecificExpressible {
|
||||
// opaque implementation
|
||||
}
|
||||
```
|
||||
|
||||
Functions and methods that build an SQL expression should return an SQLExpression value:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player WHERE LENGTH(name) > 0
|
||||
let expression = length(Column("name")) > 0 // SQLExpression
|
||||
Player.filter(expression)
|
||||
```
|
||||
|
||||
When it looks like GRDB APIs are unable to build a particular expression, use [SQL]:
|
||||
|
||||
```swift
|
||||
func date(_ value: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQL("DATE(\(value))").sqlExpression
|
||||
}
|
||||
|
||||
// SELECT * FROM player WHERE DATE(createdAt) = '2020-01-23'
|
||||
let request = Player.filter(date(Column("createdAt")) == "2020-01-23")
|
||||
```
|
||||
|
||||
This technique, based on [SQL Interpolation], is composable and works well even when several tables are involved. See how the `createdAt` column below is correctly attributed to the `player` table:
|
||||
|
||||
```swift
|
||||
// SELECT player.*, team.* FROM player
|
||||
// JOIN team ON team.id = player.teamId
|
||||
// WHERE DATE(player.createdAt) = '2020-01-23'
|
||||
let request = Player
|
||||
.filter(date(Column("createdAt")) == "2020-01-23")
|
||||
.including(required: Player.team)
|
||||
```
|
||||
|
||||
### SQLExpressible
|
||||
|
||||
`SQLExpressible` is the protocol for all [SQLite expressions](https://sqlite.org/syntax/expr.html). It is adopted by [Column], [SQL], [SQLExpression], and also [Int, String, Date], etc. It has an `sqlExpression` property which returns an [SQLExpression].
|
||||
|
||||
```swift
|
||||
protocol SQLExpressible {
|
||||
var sqlExpression: SQLExpression { get }
|
||||
}
|
||||
```
|
||||
|
||||
SQLExpressible-conforming types include types which are not directly related to SQL, such as [Int, String, Date], etc. Because of this, SQLExpressible has limited powers that prevent misuses and API pollution. For full-fledged SQL expressions, see [SQLSpecificExpressible]. For example, compare:
|
||||
|
||||
```swift
|
||||
Player.filter(1) // Compiler warning (will become an error in the next major release)
|
||||
Player.select(1) // Compiler error
|
||||
Player.order("name") // Compiler error
|
||||
length("name") // Compiler error
|
||||
"name".desc // Compiler error
|
||||
```
|
||||
|
||||
```swift
|
||||
Player.filter(id: 1) // OK
|
||||
Player.filter(1.databaseValue) // Odd, but OK
|
||||
Player.select(1.databaseValue) // Odd, but OK
|
||||
Player.order(Column("name")) // OK
|
||||
length(Column("name")) // OK
|
||||
Column("name").desc // OK
|
||||
```
|
||||
|
||||
### SQLOrderingTerm
|
||||
|
||||
`SQLOrderingTerm` is the protocol for all [SQLite ordering terms](https://sqlite.org/syntax/ordering-term.html). It is adopted by [SQLSpecificExpressible]. It has an `sqlOrdering` property which returns an [SQLOrdering].
|
||||
|
||||
```swift
|
||||
protocol SQLOrderingTerm {
|
||||
var sqlOrdering: SQLOrdering { get }
|
||||
}
|
||||
```
|
||||
|
||||
SQLOrderingTerm feeds the `order()` method of the query interface:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player
|
||||
// ORDER BY score DESC, name COLLATE ...
|
||||
Player.order(
|
||||
Column("score").desc,
|
||||
Column("name").collating(.localizedCaseInsensitiveCompare))
|
||||
```
|
||||
|
||||
All [SQLSpecificExpressible] values are ordering terms. [SQLExpressible] values are not: `Player.order("name")` does not compile. Instead, use:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player ORDER BY name -- Order according to a column
|
||||
Player.order(Column("name"))
|
||||
|
||||
// SELECT * FROM player ORDER BY 'name' -- Order according to a constant string (why not)
|
||||
Player.order("name".databaseValue)
|
||||
```
|
||||
|
||||
### SQLOrdering
|
||||
|
||||
`SQLOrdering` is the opaque type for all [SQLite ordering terms](https://sqlite.org/syntax/ordering-term.html). An SQLOrdering adopts and is built from [SQLOrderingTerm].
|
||||
|
||||
```swift
|
||||
struct SQLOrdering: SQLOrderingTerm {
|
||||
// opaque implementation
|
||||
}
|
||||
```
|
||||
|
||||
Functions and methods that build ordering terms should return an SQLOrdering value:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player ORDER BY score DESC
|
||||
let ordering = Column("score").desc // SQLOrdering
|
||||
Player.order(ordering)
|
||||
```
|
||||
|
||||
To build an SQLOrdering without applying any `DESC` or `ASC` qualifier, use `sqlOrdering` (from [SQLOrderingTerm], inherited by [SQLSpecificExpressible], [ColumnExpression]...):
|
||||
|
||||
```swift
|
||||
let ordering = Column("score").sqlOrdering // SQLOrdering
|
||||
```
|
||||
|
||||
### SQLRequest
|
||||
|
||||
`SQLRequest` is the type of fetch requests expressed with raw SQL. It conforms to [FetchRequest].
|
||||
|
||||
It is generic on the type of fetched values (which defaults to `Row`):
|
||||
|
||||
```swift
|
||||
let rowRequest = SQLRequest(sql: "SELECT * FROM player") // SQLRequest<Row>
|
||||
let playerRequest = SQLRequest<Player>(sql: "SELECT * FROM player") // SQLRequest<Player>
|
||||
let nameRequest = SQLRequest<String>(sql: "SELECT name FROM player") // SQLRequest<String>
|
||||
|
||||
try rowRequest.fetchAll(db) // [Row]
|
||||
try playerRequest.fetchAll(db) // [Player]
|
||||
try nameRequest.fetchAll(db) // [String]
|
||||
|
||||
try rowRequest.fetchOne(db) // Row?
|
||||
try playerRequest.fetchOne(db) // Player?
|
||||
try nameRequest.fetchOne(db) // String?
|
||||
```
|
||||
|
||||
SQLRequest supports [SQL Interpolation]:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player WHERE name = 'O''Brien'
|
||||
let playerRequest: SQLRequest<Player> = """
|
||||
SELECT * FROM player WHERE name = \("O'Brien")
|
||||
"""
|
||||
```
|
||||
|
||||
### SQLSelectable
|
||||
|
||||
`SQLSelectable` is the protocol for all [SQLite result columns](https://sqlite.org/syntax/result-column.html). It is adopted by [SQLSpecificExpressible]. It has an `sqlSelection` property which returns an [SQLSelection].
|
||||
|
||||
```swift
|
||||
protocol SQLSelectable {
|
||||
var sqlSelection: SQLSelection { get }
|
||||
}
|
||||
```
|
||||
|
||||
SQLSelectable feeds the `select()` method of the query interface:
|
||||
|
||||
```swift
|
||||
Player.select(AllColumns())
|
||||
Player.select(Column("name"), Column("score"))
|
||||
```
|
||||
|
||||
All [SQLSpecificExpressible] values are selectable. Other selectable values are:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player
|
||||
Player.select(AllColumns())
|
||||
|
||||
// SELECT MAX(score) AS maxScore FROM player
|
||||
Player.select(max(Column("score")).forKey("maxScore"))
|
||||
```
|
||||
|
||||
[SQLExpressible] values are not selectable: `Player.select("name")` does not compile. Instead, use:
|
||||
|
||||
```swift
|
||||
// SELECT name FROM player -- Selects a column
|
||||
Player.select(Column("name"))
|
||||
|
||||
// SELECT 'name' FROM player -- Selects a constant string (why not)
|
||||
Player.select("name".databaseValue)
|
||||
```
|
||||
|
||||
### SQLSelection
|
||||
|
||||
`SQLSelection` is the opaque type for all [SQLite result columns](https://sqlite.org/syntax/result-column.html). An SQLSelection adopts and is built from [SQLSelectable].
|
||||
|
||||
```swift
|
||||
struct SQLSelection: SQLSelectable {
|
||||
// opaque implementation
|
||||
}
|
||||
```
|
||||
|
||||
Functions and methods that build result columns should return an SQLSelection value:
|
||||
|
||||
```swift
|
||||
// SELECT (score + bonus) AS total
|
||||
let selection = (Column("score") + Column("bonus")).forKey("total") // SQLSelection
|
||||
Player.select(selection)
|
||||
```
|
||||
|
||||
### SQLSpecificExpressible
|
||||
|
||||
`SQLSpecificExpressible` is the protocol for all SQL expressions, except values such as [Int, String, Date], etc. It conforms to [SQLExpressible], [SQLSelectable], and [SQLOrderingTerm]. It is adopted by [Column], [SQL], and [SQLExpression]. It is also adopted through [SQLSubqueryable] by [QueryInterfaceRequest] and [SQLRequest].
|
||||
|
||||
```swift
|
||||
protocol SQLSpecificExpressible: SQLExpressible, SQLSelectable, SQLOrderingTerm { }
|
||||
```
|
||||
|
||||
Use SQLSpecificExpressible when you want to operate on expressions, except [Int, String, Date] and other types which are not directly related to SQL. For example, the built-in `length(_:)` GRDB function accepts SQLSpecificExpressible:
|
||||
|
||||
```swift
|
||||
/// The LENGTH SQL function
|
||||
func length(_ value: SQLSpecificExpressible) -> SQLExpression { ... }
|
||||
|
||||
length(Column("name")) // OK
|
||||
length("name") // Compiler error
|
||||
```
|
||||
|
||||
### SQLSubquery
|
||||
|
||||
`SQLSubquery` is the opaque type for all [SQLite SELECT queries](https://sqlite.org/syntax/select-stmt.html). An SQLSubquery adopts and is built from [SQLSubqueryable].
|
||||
|
||||
```swift
|
||||
struct SQLSubquery: SQLSubqueryable {
|
||||
// opaque implementation
|
||||
}
|
||||
```
|
||||
|
||||
### SQLSubqueryable
|
||||
|
||||
`SQLSubqueryable` is the protocol for all [SQLite SELECT queries](https://sqlite.org/syntax/select-stmt.html). It conforms to [SQLSpecificExpressible], and is adopted by [FetchRequest], [QueryInterfaceRequest], [SQLRequest]. It has an `sqlSubquery` property which returns an [SQLSubquery].
|
||||
|
||||
```swift
|
||||
protocol SQLSubqueryable: SQLSpecificExpressible {
|
||||
var sqlSubquery: SQLSubquery { get }
|
||||
}
|
||||
```
|
||||
|
||||
SQLSubqueryable provides the GRDB support for subqueries. Its [SQLSpecificExpressible] facet lets you use any request as an expression:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player
|
||||
// WHERE score >= (SELECT AVG(score) FROM player)
|
||||
let averageScore = Player.select(average(Column("score")))
|
||||
Player.filter(Column("score") >= averageScore)
|
||||
```
|
||||
|
||||
SQLSubqueryable has the `contains(_:)` and `exists()` methods that support the `value IN (subquery)` and `EXISTS (subquery)` expressions.
|
||||
|
||||
Use SQLSubqueryable in order to define a function that requires a subquery argument:
|
||||
|
||||
```swift
|
||||
func myRequest(_ nameSubquery: SQLSubqueryable) -> SQLRequest<Player> {
|
||||
"""
|
||||
SELECT * FROM player
|
||||
WHERE name IN (\(nameSubquery) UNION ...)
|
||||
"""
|
||||
}
|
||||
|
||||
myRequest(SQLRequest("SELECT ..."))
|
||||
myRequest(Player.select(...).filter(...))
|
||||
```
|
||||
|
||||
[Association]: #association
|
||||
[associations]: AssociationsBasics.md
|
||||
[association aggregates]: AssociationsBasics.md#association-aggregates
|
||||
[Column]: #column
|
||||
[ColumnExpression]: #columnexpression
|
||||
[DatabaseRegionConvertible]: #databaseregionconvertible
|
||||
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
|
||||
[DatabaseValue]: #databasevalue
|
||||
[DatabaseValueConvertible]: #databasevalueconvertible
|
||||
[DerivableRequest]: #derivablerequest
|
||||
[FetchableRecord]: ../README.md#fetchablerecord-protocol
|
||||
[FetchRequest]: #fetchrequest
|
||||
[Int, String, Date…]: #int-string-date
|
||||
[Int, String, Date]: #int-string-date
|
||||
[query interface]: ../README.md#the-query-interface
|
||||
[QueryInterfaceRequest]: #queryinterfacerequest
|
||||
[SQL]: #sql
|
||||
[SQL Interpolation]: SQLInterpolation.md
|
||||
[SQLExpression]: #sqlexpression
|
||||
[SQLExpressible]: #sqlexpressible
|
||||
[SQLOrderingTerm]: #sqlorderingterm
|
||||
[SQLOrdering]: #sqlordering
|
||||
[SQLRequest]: #sqlrequest
|
||||
[SQLSelectable]: #sqlselectable
|
||||
[SQLSelection]: #sqlselection
|
||||
[SQLSpecificExpressible]: #sqlspecificexpressible
|
||||
[SQLSubquery]: #sqlsubquery
|
||||
[SQLSubqueryable]: #sqlsubqueryable
|
||||
@@ -22,7 +22,7 @@ try dbQueue.write { db in
|
||||
SQL Interpolation is an answer to these troubles. It is available in Swift 5.
|
||||
|
||||
- [Introduction]
|
||||
- [SQLLiteral]
|
||||
- [SQL Literal]
|
||||
- [SQL Interpolation and the Query Interface]
|
||||
- [SQL Interpolation and Record Protocols]
|
||||
- [SQL Interpolation Reference]
|
||||
@@ -73,38 +73,38 @@ Plain SQL strings are indeed still available, and SQL interpolation only kicks i
|
||||
```
|
||||
|
||||
|
||||
## SQLLiteral
|
||||
## SQL Literal
|
||||
|
||||
**SQLLiteral** is the type that looks like a plain String, but profits from SQL interpolation:
|
||||
**`SQL`** is the type that looks like a plain String, but profits from SQL interpolation:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
try db.execute(literal: query)
|
||||
}
|
||||
```
|
||||
|
||||
**SQLLiteral is not a Swift String.** You can not use the `execute(literal:)` method with a String argument:
|
||||
**`SQL` is not a Swift String.** You can not use the `execute(literal:)` method with a String argument:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
let query = "UPDATE player SET name = \(name) WHERE id = \(id)" // a regular String
|
||||
// Compiler error:
|
||||
// Cannot convert value of type 'String' to expected argument type 'SQLLiteral'
|
||||
// Cannot convert value of type 'String' to expected argument type 'SQL'
|
||||
try db.execute(literal: query)
|
||||
}
|
||||
```
|
||||
|
||||
SQLLiteral can build your queries step by step, with regular operators and methods:
|
||||
`SQL` can build your queries step by step, with regular operators and methods:
|
||||
|
||||
```swift
|
||||
// +, +=, append
|
||||
var query: SQLLiteral = "UPDATE player "
|
||||
var query: SQL = "UPDATE player "
|
||||
query += "SET name = \(name) "
|
||||
query.append(literal: "WHERE id = \(id)")
|
||||
|
||||
// joined(), joined(separator:)
|
||||
let components: [SQLLiteral] = [
|
||||
let components: [SQL] = [
|
||||
"UPDATE player",
|
||||
"SET name = \(name)",
|
||||
"WHERE id = \(id)"
|
||||
@@ -115,7 +115,7 @@ let query = components.joined(separator: " ")
|
||||
Extract the plain SQL string from a literal:
|
||||
|
||||
```swift
|
||||
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
let (sql, arguments) = try dbQueue.read(query.build)
|
||||
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
|
||||
print(arguments) // prints ["O'Brien", 42]
|
||||
@@ -124,17 +124,17 @@ print(arguments) // prints ["O'Brien", 42]
|
||||
Build a literal from a plain SQL string:
|
||||
|
||||
```swift
|
||||
let query = SQLLiteral(
|
||||
let query = SQL(
|
||||
sql: "UPDATE player SET name = ? WHERE id = ?",
|
||||
arguments: [name, id])
|
||||
```
|
||||
|
||||
SQLLiteral can embed any [value], as we have seen above, but not only. Please keep on reading the next chapter, or jump directly to the [SQL Interpolation Reference].
|
||||
`SQL` can embed any [value], as we have seen above, but not only. Please keep on reading the next chapter, or jump directly to the [SQL Interpolation Reference].
|
||||
|
||||
|
||||
## SQL Interpolation and the Query Interface
|
||||
|
||||
SQL Interpolation and SQLLiteral let you embed raw SQL snippets in [query interface requests].
|
||||
SQL Interpolation and `SQL` let you embed raw SQL snippets in [query interface requests].
|
||||
|
||||
For example:
|
||||
|
||||
@@ -143,25 +143,37 @@ For example:
|
||||
let request = Player.filter(literal: "name = \("O'Brien")")
|
||||
```
|
||||
|
||||
You can also build literal expressions from other expressions. For example, let's call the `DATE` SQLite function on a query interface column:
|
||||
You can also build literals from other expressions. For example, let's call the `DATE` SQLite function on a query interface column:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23'
|
||||
// SELECT * FROM player WHERE DATE(createdAt) = '2020-01-23'
|
||||
let createdAt = Column("createdAt")
|
||||
let creationDay = SQLLiteral("DATE(\(createdAt))").sqlExpression
|
||||
let creationDay = SQL("DATE(\(createdAt))")
|
||||
let request = Player.filter(creationDay == "2020-01-23")
|
||||
```
|
||||
|
||||
Such literal expressions can be returned by Swift functions:
|
||||
Such literals play well with the query interface, even when several tables are involved with [associations](AssociationsBasics.md):
|
||||
|
||||
```swift
|
||||
func date(_ value: SQLExpressible) -> SQLExpression {
|
||||
SQLLiteral("DATE(\(value))").sqlExpression
|
||||
// SELECT player.*, team.*
|
||||
// FROM player
|
||||
// JOIN team ON team.id = player.teamID
|
||||
// WHERE DATE(player.createdAt) = '2020-01-23'
|
||||
// ~~~~~~~~~~~~~~~~~~~~~~
|
||||
// automatic table disambiguation
|
||||
let request = Player
|
||||
.filter(creationDay == "2020-01-23")
|
||||
.including(required: Player.team)
|
||||
```
|
||||
|
||||
This allows you to define Swift functions that you can use in all circumstances:
|
||||
|
||||
```swift
|
||||
func date(_ expression: SQLExpressible) -> SQLExpression {
|
||||
SQL("DATE(\(expression))").sqlExpression
|
||||
}
|
||||
|
||||
// SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23'
|
||||
let createdAt = Column("createdAt")
|
||||
let request = Player.filter(date(createdAt) == "2020-01-23")
|
||||
let request = Player.filter(date(Column("createdAt")) == "2020-01-23")
|
||||
```
|
||||
|
||||
|
||||
@@ -334,7 +346,7 @@ Let's extend Player with database methods.
|
||||
extension Player: Decodable, FetchableRecord, TableRecord {
|
||||
/// A complex request
|
||||
static func complexRequest() -> SQLRequest<Player> {
|
||||
let query: SQLLiteral = "SELECT \(columnsOf: self) "
|
||||
let query: SQL = "SELECT \(columnsOf: self) "
|
||||
query += "FROM \(self) "
|
||||
query += "JOIN \(Team.self) ON ..."
|
||||
query += "GROUP BY ..."
|
||||
@@ -343,7 +355,7 @@ Let's extend Player with database methods.
|
||||
}
|
||||
```
|
||||
|
||||
This last request shows how to build an SQLRequest from an [SQLLiteral]. You will need SQLLiteral when the request can not be written in a single stroke.
|
||||
This last request shows how to build an SQLRequest from an [SQL Literal]. You will need `SQL` when the request can not be written in a single stroke.
|
||||
|
||||
|
||||
|
||||
@@ -417,14 +429,21 @@ 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
|
||||
// SELECT * FROM player WHERE score = (SELECT MAX(score) FROM player)
|
||||
let subquery: SQLRequest<Int> = "SELECT MAX(score) FROM player"
|
||||
let subquery = SQLRequest("SELECT MAX(score) FROM player")
|
||||
"SELECT * FROM player WHERE score = (\(subquery))"
|
||||
|
||||
// SELECT * FROM player WHERE score = (SELECT MAX(score) FROM player)
|
||||
@@ -442,11 +461,11 @@ This chapter lists all kinds of supported interpolations.
|
||||
"WITH \(definitionFor: cte) SELECT * FROM \(cte)"
|
||||
```
|
||||
|
||||
- SQLLiteral:
|
||||
- `SQL` literal:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player WHERE name = 'O''Brien'
|
||||
let condition: SQLLiteral = "name = \("O'Brien")"
|
||||
let condition: SQL = "name = \("O'Brien")"
|
||||
"SELECT * FROM player WHERE \(literal: condition)"
|
||||
```
|
||||
|
||||
@@ -461,7 +480,7 @@ This chapter lists all kinds of supported interpolations.
|
||||
```
|
||||
|
||||
[Introduction]: #introduction
|
||||
[SQLLiteral]: #sqlliteral
|
||||
[SQL Literal]: #sql-literal
|
||||
[SQL Interpolation and the Query Interface]: #sql-interpolation-and-the-query-interface
|
||||
[SQL Interpolation and Record Protocols]: #sql-interpolation-and-record-protocols
|
||||
[SQL Interpolation Reference]: #sql-interpolation-reference
|
||||
|
||||
@@ -66,7 +66,7 @@ Since several processes may open the database at the same time, protect the crea
|
||||
}
|
||||
}
|
||||
}
|
||||
let dbPool = try DatabasePool(path: databaseURL.path)
|
||||
let dbPool = try DatabasePool(path: databaseURL.path, configuration: configuration)
|
||||
|
||||
// Perform here other database setups, such as defining
|
||||
// the database schema with a DatabaseMigrator, and
|
||||
@@ -173,9 +173,9 @@ do {
|
||||
|
||||
> The exception code 0xDEAD10CC indicates that an application has been terminated by the OS because it held on to a file lock or sqlite database lock during suspension.
|
||||
|
||||
See https://developer.apple.com/library/archive/technotes/tn2151/_index.html for more information about this exception.
|
||||
See https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report for more information about this exception.
|
||||
|
||||
1. If you use SQLCipher, use SQLCipher 4+, and call the `cipher_plaintext_header_size` pragma from your database preparation function:
|
||||
1. If you use SQLCipher, use SQLCipher 4+, and call the [`cipher_plaintext_header_size` pragma](https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_plaintext_header_size) from your database preparation function:
|
||||
|
||||
```swift
|
||||
var configuration = Configuration()
|
||||
@@ -186,7 +186,13 @@ See https://developer.apple.com/library/archive/technotes/tn2151/_index.html for
|
||||
let dbPool = try DatabasePool(path: ..., configuration: configuration)
|
||||
```
|
||||
|
||||
This will avoid https://github.com/sqlcipher/sqlcipher/issues/255.
|
||||
This will avoid this issue: https://github.com/sqlcipher/sqlcipher/issues/255.
|
||||
|
||||
This will also disable a SQLCipher security feature: the salt. As described by https://www.zetetic.net/sqlcipher/design/:
|
||||
|
||||
> The salt is used for key derivation and it ensures that even if two databases are created using the same password, they will not have the same encryption key.
|
||||
|
||||
Applications are responsible for managing the salt themselves and providing it to SQLCipher. See https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_plaintext_header_size for instructions.
|
||||
|
||||
2. [**:fire: EXPERIMENTAL**](../README.md#what-are-experimental-features) In each process that wants to write in the database:
|
||||
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
Single-Row Tables
|
||||
=================
|
||||
|
||||
Let's talk about database tables that should contain a single row.
|
||||
|
||||
Such tables can store configuration values, user preferences, and generally some global application state. They are a suitable alternative to `UserDefaults` in some applications, especially when configuration refers to values found in other database tables, and database integrity is a concern.
|
||||
|
||||
An alternative way to store such configuration is a table of key-value pairs: two columns, and one row for each configuration value. This technique works, but it has a few drawbacks: you will have to deal with the various types of configuration values (strings, integers, dates, etc), and you won't be able to define foreign keys. This is why we won't explore key-value tables.
|
||||
|
||||
This guide helps you implementing a single-row table with GRDB, with recommendations on the database schema, migrations, and the design of a matching [record] type.
|
||||
|
||||
- [The Single-Row Table]
|
||||
- [The Single-Row Record]
|
||||
- [Wrap-Up]
|
||||
|
||||
|
||||
## The Single-Row Table
|
||||
|
||||
As always with GRDB, everything starts at the level of the database schema. Putting the robust SQLite on our side is always a good idea, because we have to write less code, and this helps shipping less bugs.
|
||||
|
||||
We want to instruct SQLite that our table must never contain more than one row. We will never have to wonder what to do if we were unlucky enough to find two rows with conflicting values in this table.
|
||||
|
||||
SQLite is not able to guarantee that the table is never empty, so we have to deal with two cases: either the table is empty, or it contains one row.
|
||||
|
||||
Those two cases can create a nagging question for the application. By default, inserts fail when the row already exists, and updates fail when the table is empty. In order to avoid those errors, we will have the app perform an insert in case of a failed update (in the [The Single-Row Record] chapter). And we instruct SQLite to just replace the eventual existing row in case of conflicting inserts:
|
||||
|
||||
```swift
|
||||
// CREATE TABLE appConfiguration (
|
||||
// id INTEGER PRIMARY KEY ON CONFLICT REPLACE CHECK (id = 1),
|
||||
// flag BOOLEAN NOT NULL,
|
||||
// ...)
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// Single row guarantee
|
||||
t.column("id", .integer)
|
||||
// Have inserts replace the existing row
|
||||
.primaryKey(onConflict: .replace)
|
||||
// Make sure the id column is always 1
|
||||
.check { $0 == 1 }
|
||||
|
||||
// The configuration colums
|
||||
t.column("flag", .boolean).notNull()
|
||||
// ... other columns
|
||||
}
|
||||
```
|
||||
|
||||
When you use [migrations], you may wonder if it is a good idea or not to perform an initial insert just after the table is created. Well, this is not recommended:
|
||||
|
||||
```swift
|
||||
// NOT RECOMMENDED
|
||||
migrator.registerMigration("appConfiguration") { db in
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// Single row guarantee
|
||||
t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 }
|
||||
|
||||
// Define sensible defaults for each column
|
||||
t.column("flag", .boolean).notNull()
|
||||
.defaults(to: false)
|
||||
// ... other columns
|
||||
}
|
||||
|
||||
// Populate the table
|
||||
try db.execute(sql: "INSERT INTO appConfiguration DEFAULT VALUES")
|
||||
}
|
||||
```
|
||||
|
||||
It is not a good idea to populate the table in a migration, for two reasons:
|
||||
|
||||
1. This is not a hard guarantee that the table will never be empty. As a consequence, this won't prevent your Swift code from dealing with the possibility of a missing row. On top of that, the Swift code that deals with the missing row may not use the same default values as the SQLite schema (a [DRY] violation), with unclear consequences.
|
||||
|
||||
2. Migrations that are shipped in the wild should *never* change, because you want to control the state of the databases installed on your users' devices, regardless of the application version they install first, regardless of how many application versions are skipped when they download an upgrade, etc. By inserting an initial row in a migration, you make it difficult for your application to adjust the sensible default values in the future, while keeping a clear idea of the various installation and upgrade scenarios.
|
||||
|
||||
The recommended migration creates the table, nothing more:
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
migrator.registerMigration("appConfiguration") { db in
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// Single row guarantee
|
||||
t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 }
|
||||
|
||||
// The configuration colums
|
||||
t.column("flag", .boolean).notNull()
|
||||
// ... other columns
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## The Single-Row Record
|
||||
|
||||
Now that the database schema has been defined, we can define the [record] type that will help the application access the single row:
|
||||
|
||||
```swift
|
||||
struct AppConfiguration: Codable {
|
||||
// Support for the single row guarantee
|
||||
private var id = 1
|
||||
|
||||
// The configuration properties
|
||||
var flag: Bool
|
||||
// ... other properties
|
||||
}
|
||||
```
|
||||
|
||||
In case the database table would be empty, we need a default configuration:
|
||||
|
||||
```swift
|
||||
extension AppConfiguration {
|
||||
/// The default configuration
|
||||
static let `default` = AppConfiguration(flag: false, ...)
|
||||
}
|
||||
```
|
||||
|
||||
We make our record able to access the database:
|
||||
|
||||
```swift
|
||||
extension AppConfiguration: FetchableRecord, PersistableRecord {
|
||||
```
|
||||
|
||||
We have seen in the [The Single-Row Table] chapter that by default, updates throw an error if the database table is empty. To avoid this error, we instruct GRDB to perform an insert in case of a failed update (see [Persistence Methods] for more information):
|
||||
|
||||
```swift
|
||||
// Customize the default PersistableRecord behavior
|
||||
func update(_ db: Database, columns: Set<String>) throws {
|
||||
do {
|
||||
try performUpdate(db, columns: columns)
|
||||
} catch PersistenceError.recordNotFound {
|
||||
// No row was updated: perform an insert
|
||||
try performInsert(db)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The standard GRDB method `fetchOne` returns an optional which is nil when the database table is empty. As a convenience, let's define a method that returns a non-optional (replacing the missing row with `default`):
|
||||
|
||||
```swift
|
||||
/// Returns the persisted configuration, or the default one if the
|
||||
/// database table is empty.
|
||||
static func fetch(_ db: Database) throws -> AppConfiguration {
|
||||
try fetchOne(db) ?? .default
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And that's it! Now we can use our singleton record:
|
||||
|
||||
```swift
|
||||
// READ
|
||||
let config = try dbQueue.read { db in
|
||||
try AppConfiguration.fetch(db)
|
||||
}
|
||||
if config.flag {
|
||||
// ...
|
||||
}
|
||||
|
||||
// WRITE
|
||||
try dbQueue.write { db in
|
||||
var config = try AppConfiguration.fetch(db)
|
||||
|
||||
// Update some config values
|
||||
try config.updateChanges(db) {
|
||||
$0.flag = true
|
||||
}
|
||||
|
||||
// Other possible ways to write config:
|
||||
try config.update(db)
|
||||
try config.save(db)
|
||||
try config.insert(db)
|
||||
}
|
||||
```
|
||||
|
||||
The three `update`, `save` and `insert` methods can be used interchangeably: all three make sure the configuration is stored in the database.
|
||||
|
||||
The `updateChanges` method only updates the values changed by its closure argument (and performs an insert if the database table is empty).
|
||||
|
||||
See [Persistence Methods] for more information.
|
||||
|
||||
|
||||
## Wrap-Up
|
||||
|
||||
We all love to copy and paste, don't we? Just customize the template code below:
|
||||
|
||||
```swift
|
||||
// Table creation
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// Single row guarantee
|
||||
t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 }
|
||||
|
||||
// The configuration columns
|
||||
t.column("flag", .boolean).notNull()
|
||||
// ... other columns
|
||||
}
|
||||
```
|
||||
|
||||
```swift
|
||||
//
|
||||
// AppConfiguration.swift
|
||||
//
|
||||
|
||||
import GRDB
|
||||
|
||||
struct AppConfiguration: Codable {
|
||||
// Support for the single row guarantee
|
||||
private var id = 1
|
||||
|
||||
// The configuration properties
|
||||
var flag: Bool
|
||||
// ... other properties
|
||||
}
|
||||
|
||||
extension AppConfiguration {
|
||||
/// The default configuration
|
||||
static let `default` = AppConfiguration(flag: false, ...)
|
||||
}
|
||||
|
||||
// Database Access
|
||||
extension AppConfiguration: FetchableRecord, PersistableRecord {
|
||||
// Customize the default PersistableRecord behavior
|
||||
func update(_ db: Database, columns: Set<String>) throws {
|
||||
do {
|
||||
try performUpdate(db, columns: columns)
|
||||
} catch PersistenceError.recordNotFound {
|
||||
// No row was updated: perform an insert
|
||||
try performInsert(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the persisted configuration, or the default one if the
|
||||
/// database table is empty.
|
||||
static func fetch(_ db: Database) throws -> AppConfiguration {
|
||||
try fetchOne(db) ?? .default
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
[migrations]: Migrations.md
|
||||
[record]: ../README.md#records
|
||||
[The Single-Row Table]: #the-single-row-table
|
||||
[The Single-Row Record]: #the-single-row-record
|
||||
[Wrap-Up]: #wrap-up
|
||||
[DRY]: https://en.wikipedia.org/wiki/Don%27t_repeat_yourself
|
||||
[Persistence Methods]: ../README.md#persistence-methods
|
||||
@@ -283,8 +283,6 @@ while let row = try rows.next() {
|
||||
|
||||
If this little tour of GRDB has convinced you, the real trip starts here: [GRDB].
|
||||
|
||||
And if you happen to maintain an Objective-C application that uses FMDB, checkout [GRDBObjc]. It provides FMDB-compatible bindings to GRDB, so that you can inject sweet drops of Swift into your app, at your own pace, and at minimal cost.
|
||||
|
||||
Happy GRDB! :gift:
|
||||
|
||||
[Concurrency Guide]: ../README.md#concurrency
|
||||
@@ -296,7 +294,6 @@ Happy GRDB! :gift:
|
||||
[Fluent]: https://github.com/vapor/fluent
|
||||
[FMDB]: http://github.com/ccgus/fmdb
|
||||
[GRDB]: http://github.com/groue/GRDB.swift
|
||||
[GRDBObjc]: http://github.com/groue/GRDBObjc
|
||||
[PersistableRecord]: ../README.md#records
|
||||
[Realm]: http://realm.io
|
||||
[FetchableRecord]: ../README.md#records
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '5.3.0'
|
||||
s.version = '5.11.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
+168
-138
File diff suppressed because it is too large.
Load diff
@@ -9,12 +9,12 @@ public struct Configuration {
|
||||
/// If true, foreign key constraints are checked.
|
||||
///
|
||||
/// Default: true
|
||||
public var foreignKeysEnabled: Bool = true
|
||||
public var foreignKeysEnabled = true
|
||||
|
||||
/// If true, database modifications are disallowed.
|
||||
///
|
||||
/// Default: false
|
||||
public var readonly: Bool = false
|
||||
public var readonly = false
|
||||
|
||||
/// The configuration label.
|
||||
///
|
||||
@@ -91,7 +91,7 @@ public struct Configuration {
|
||||
/// When true, the `Database.suspendNotification` and
|
||||
/// `Database.resumeNotification` suspend and resume the database. Database
|
||||
/// suspension helps avoiding the [`0xdead10cc`
|
||||
/// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html).
|
||||
/// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report).
|
||||
///
|
||||
/// During suspension, all database accesses but reads in WAL mode may throw
|
||||
/// a DatabaseError of code `SQLITE_INTERRUPT`, or `SQLITE_ABORT`. You can
|
||||
@@ -108,6 +108,9 @@ public struct Configuration {
|
||||
/// The function argument is run when an SQLite connection is opened,
|
||||
/// before the connection is made available for database access methods.
|
||||
///
|
||||
/// This method can be called several times. The preparation functions are
|
||||
/// run in the same order.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
@@ -115,8 +118,21 @@ public struct Configuration {
|
||||
/// try db.execute(sql: "PRAGMA kdf_iter = 10000")
|
||||
/// }
|
||||
///
|
||||
/// This method can be called several times. The setup functions are run in
|
||||
/// the same order.
|
||||
/// When you use a `DatabasePool`, preparation functions are called for
|
||||
/// the writer connection and all reader connections. You can distinguish
|
||||
/// them by querying `db.configuration.readonly`:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// if db.configuration.readonly {
|
||||
/// // reader connection
|
||||
/// } else {
|
||||
/// // writer connection
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// On newly created databases, `DatabasePool` the WAL mode is activated
|
||||
/// after the preparation functions have run.
|
||||
public mutating func prepareDatabase(_ setup: @escaping (Database) throws -> Void) {
|
||||
setups.append(setup)
|
||||
}
|
||||
@@ -159,11 +175,11 @@ public struct Configuration {
|
||||
/// never allow leaving a transaction opened at the end of a read access.
|
||||
///
|
||||
/// Default: false
|
||||
public var allowsUnsafeTransactions: Bool = false
|
||||
public var allowsUnsafeTransactions = false
|
||||
|
||||
// MARK: - Concurrency
|
||||
|
||||
/// The behavior in case of SQLITE_BUSY error. See https://www.sqlite.org/rescode.html#busy
|
||||
/// The behavior in case of SQLITE_BUSY error. See <https://www.sqlite.org/rescode.html#busy>
|
||||
///
|
||||
/// Default: immediateError
|
||||
public var busyMode: Database.BusyMode = .immediateError
|
||||
|
||||
+147
-22
@@ -9,38 +9,176 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// MARK: - Array, Sequence, Dictionary, Set extensions
|
||||
// MARK: - RangeReplaceableCollection, Sequence, Dictionary, Set extensions
|
||||
|
||||
extension Array {
|
||||
/// Creates an array containing the elements of a cursor.
|
||||
extension RangeReplaceableCollection {
|
||||
/// Creates a collection containing the elements of a cursor.
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
|
||||
/// let strings = try Array(cursor) // ["foo", "bar"]
|
||||
@inlinable
|
||||
/// // [String]
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Array(cursor)
|
||||
///
|
||||
/// - parameter cursor: The cursor whose elements feed the collection.
|
||||
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
|
||||
self.init()
|
||||
while let element = try cursor.next() {
|
||||
append(element)
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a collection containing the elements of a cursor.
|
||||
///
|
||||
/// // [String]
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Array(cursor, minimumCapacity: 100)
|
||||
///
|
||||
/// - parameter cursor: The cursor whose elements feed the collection.
|
||||
/// - parameter minimumCapacity: Prepares the returned collection to store
|
||||
/// the specified number of elements.
|
||||
public init<C: Cursor>(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element {
|
||||
self.init()
|
||||
reserveCapacity(minimumCapacity)
|
||||
while let element = try cursor.next() {
|
||||
append(element)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Dictionary {
|
||||
/// Creates a new dictionary whose keys are the groupings returned by the
|
||||
/// given closure and whose values are arrays of the elements that returned
|
||||
/// each key.
|
||||
public init<C: Cursor>(grouping values: C, by keyForValue: (C.Element) throws -> Key)
|
||||
///
|
||||
/// // [Int64: [Player]]
|
||||
/// let cursor = try Player.fetchCursor(db)
|
||||
/// let dictionary = try Dictionary(grouping: cursor, by: { $0.teamID })
|
||||
///
|
||||
/// - parameter cursor: A cursor of values to group into a dictionary.
|
||||
/// - parameter keyForValue: A closure that returns a key for each element
|
||||
/// in the cursor.
|
||||
public init<C: Cursor>(grouping cursor: C, by keyForValue: (C.Element) throws -> Key)
|
||||
throws where Value == [C.Element]
|
||||
{
|
||||
self.init()
|
||||
while let value = try values.next() {
|
||||
while let value = try cursor.next() {
|
||||
try self[keyForValue(value), default: []].append(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new dictionary whose keys are the groupings returned by the
|
||||
/// given closure and whose values are arrays of the elements that returned
|
||||
/// each key.
|
||||
///
|
||||
/// // [Int64: [Player]]
|
||||
/// let cursor = try Player.fetchCursor(db)
|
||||
/// let dictionary = try Dictionary(
|
||||
/// minimumCapacity: 100,
|
||||
/// grouping: cursor,
|
||||
/// by: { $0.teamID })
|
||||
///
|
||||
/// - parameter minimumCapacity: The minimum number of key-value pairs that
|
||||
/// the newly created dictionary should be able to store without
|
||||
/// reallocating its storage buffer.
|
||||
/// - parameter cursor: A cursor of values to group into a dictionary.
|
||||
/// - parameter keyForValue: A closure that returns a key for each element
|
||||
/// in the cursor.
|
||||
public init<C: Cursor>(minimumCapacity: Int, grouping cursor: C, by keyForValue: (C.Element) throws -> Key)
|
||||
throws where Value == [C.Element]
|
||||
{
|
||||
self.init(minimumCapacity: minimumCapacity)
|
||||
while let value = try cursor.next() {
|
||||
try self[keyForValue(value), default: []].append(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new dictionary from the key-value pairs in the given cursor.
|
||||
///
|
||||
/// You use this initializer to create a dictionary when you have a cursor
|
||||
/// of key-value tuples with unique keys. Passing a cursor with duplicate
|
||||
/// keys to this initializer results in a fatal error.
|
||||
///
|
||||
/// // [Int64: Player]
|
||||
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
|
||||
/// let playerByID = try Dictionary(uniqueKeysWithValues: cursor)
|
||||
///
|
||||
/// - parameter keysAndValues: A cursor of key-value pairs to use for the
|
||||
/// new dictionary. Every key in `keysAndValues` must be unique.
|
||||
/// - precondition: The cursor must not have duplicate keys.
|
||||
public init<C: Cursor>(uniqueKeysWithValues keysAndValues: C)
|
||||
throws where C.Element == (Key, Value)
|
||||
{
|
||||
self.init()
|
||||
while let (key, value) = try keysAndValues.next() {
|
||||
if updateValue(value, forKey: key) != nil {
|
||||
fatalError("Duplicate values for key: '\(String(describing: key))'")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new dictionary from the key-value pairs in the given cursor.
|
||||
///
|
||||
/// You use this initializer to create a dictionary when you have a cursor
|
||||
/// of key-value tuples with unique keys. Passing a cursor with duplicate
|
||||
/// keys to this initializer results in a fatal error.
|
||||
///
|
||||
/// // [Int64: Player]
|
||||
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
|
||||
/// let playerByID = try Dictionary(
|
||||
/// minimumCapacity: 100,
|
||||
/// uniqueKeysWithValues: cursor)
|
||||
///
|
||||
/// - parameter minimumCapacity: The minimum number of key-value pairs that
|
||||
/// the newly created dictionary should be able to store without
|
||||
/// reallocating its storage buffer.
|
||||
/// - parameter keysAndValues: A cursor of key-value pairs to use for the
|
||||
/// new dictionary. Every key in `keysAndValues` must be unique.
|
||||
/// - precondition: The cursor must not have duplicate keys.
|
||||
public init<C: Cursor>(minimumCapacity: Int, uniqueKeysWithValues keysAndValues: C)
|
||||
throws where C.Element == (Key, Value)
|
||||
{
|
||||
self.init(minimumCapacity: minimumCapacity)
|
||||
while let (key, value) = try keysAndValues.next() {
|
||||
if updateValue(value, forKey: key) != nil {
|
||||
fatalError("Duplicate values for key: '\(String(describing: key))'")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Set {
|
||||
/// Creates a set containing the elements of a cursor.
|
||||
///
|
||||
/// // Set<String>
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Set(cursor)
|
||||
///
|
||||
/// - parameter cursor: A cursor of values to gather into a set.
|
||||
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
|
||||
self.init()
|
||||
while let element = try cursor.next() {
|
||||
insert(element)
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a set containing the elements of a cursor.
|
||||
///
|
||||
/// // Set<String>
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Set(cursor, minimumCapacity: 100)
|
||||
///
|
||||
/// - parameter cursor: A cursor of values to gather into a set.
|
||||
/// - parameter minimumCapacity: The minimum number of elements that the
|
||||
/// newly created set should be able to store without reallocating its
|
||||
/// storage buffer.
|
||||
public init<C: Cursor>(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element {
|
||||
self.init(minimumCapacity: minimumCapacity)
|
||||
while let element = try cursor.next() {
|
||||
insert(element)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult: Cursor>(
|
||||
@@ -51,19 +189,6 @@ extension Sequence {
|
||||
}
|
||||
}
|
||||
|
||||
extension Set {
|
||||
/// Creates a set containing the elements of a cursor.
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'foo'")
|
||||
/// let strings = try Set(cursor) // ["foo"]
|
||||
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
|
||||
self.init()
|
||||
while let element = try cursor.next() {
|
||||
insert(element)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Cursor
|
||||
|
||||
/// A type that supplies the values of some external resource, one at a time.
|
||||
|
||||
+267
-80
@@ -1,4 +1,51 @@
|
||||
extension Database {
|
||||
/// A SQLite schema. See <https://sqlite.org/lang_naming.html>
|
||||
enum SchemaIdentifier: Hashable {
|
||||
/// The main database
|
||||
case main
|
||||
|
||||
/// The temp database
|
||||
case temp
|
||||
|
||||
/// An attached database: <https://sqlite.org/lang_attach.html>
|
||||
case attached(String)
|
||||
|
||||
/// The name of the schema in SQL queries
|
||||
var sql: String {
|
||||
switch self {
|
||||
case .main: return "main"
|
||||
case .temp: return "temp"
|
||||
case let .attached(name): return name
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of the master sqlite table
|
||||
var masterTableName: String { // swiftlint:disable:this inclusive_language
|
||||
switch self {
|
||||
case .main: return "sqlite_master"
|
||||
case .temp: return "sqlite_temp_master"
|
||||
case let .attached(name): return "\(name).sqlite_master"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A table identifier
|
||||
struct TableIdentifier {
|
||||
/// The SQLite schema
|
||||
var schemaID: SchemaIdentifier
|
||||
|
||||
/// The table name
|
||||
var name: String
|
||||
|
||||
/// Returns the receiver, quoted for safe insertion as an identifier in
|
||||
/// an SQL query.
|
||||
///
|
||||
/// // SELECT * FROM temp.player
|
||||
/// db.execute(sql: "SELECT * FROM \(table.quotedDatabaseIdentifier)")
|
||||
var quotedDatabaseIdentifier: String {
|
||||
"\(schemaID.sql).\(name.quotedDatabaseIdentifier)"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Database Schema
|
||||
|
||||
@@ -10,8 +57,8 @@ extension Database {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
schemaCache.clear()
|
||||
|
||||
// We also clear updateStatementCache and selectStatementCache despite
|
||||
// the automatic statement recompilation (see https://www.sqlite.org/c3ref/prepare.html)
|
||||
// We also clear statement cache despite the automatic statement
|
||||
// recompilation (see https://www.sqlite.org/c3ref/prepare.html)
|
||||
// because the automatic statement recompilation only happens a
|
||||
// limited number of times.
|
||||
internalStatementCache.clear()
|
||||
@@ -21,23 +68,55 @@ extension Database {
|
||||
/// Clears the database schema cache if the database schema has changed
|
||||
/// since this method was last called.
|
||||
func clearSchemaCacheIfNeeded() throws {
|
||||
let schemaVersion = try Int32.fetchOne(internalCachedSelectStatement(sql: "PRAGMA schema_version"))
|
||||
let schemaVersion = try Int32.fetchOne(internalCachedStatement(sql: "PRAGMA schema_version"))
|
||||
if _lastSchemaVersion != schemaVersion {
|
||||
_lastSchemaVersion = schemaVersion
|
||||
clearSchemaCache()
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether a table exists.
|
||||
/// The list of database schemas, in the order of SQLite resolution:
|
||||
/// temp, main, then attached databases.
|
||||
func schemaIdentifiers() throws -> [SchemaIdentifier] {
|
||||
if let schemaIdentifiers = schemaCache.schemaIdentifiers {
|
||||
return schemaIdentifiers
|
||||
}
|
||||
|
||||
var schemaIdentifiers = try Row
|
||||
.fetchAll(self, sql: "PRAGMA database_list")
|
||||
.map { row -> SchemaIdentifier in
|
||||
switch row[1] as String {
|
||||
case "main": return .main
|
||||
case "temp": return .temp
|
||||
case let other: return .attached(other)
|
||||
}
|
||||
}
|
||||
|
||||
// Temp schema shadows other schema: put it first
|
||||
if let tempIdx = schemaIdentifiers.firstIndex(of: .temp) {
|
||||
schemaIdentifiers.swapAt(tempIdx, 0)
|
||||
}
|
||||
|
||||
schemaCache.schemaIdentifiers = schemaIdentifiers
|
||||
return schemaIdentifiers
|
||||
}
|
||||
|
||||
/// Returns whether a table exists in the main or temp schema.
|
||||
public func tableExists(_ name: String) throws -> Bool {
|
||||
try exists(type: .table, name: name)
|
||||
try schemaIdentifiers().contains {
|
||||
try exists(type: .table, name: name, in: $0)
|
||||
}
|
||||
}
|
||||
|
||||
private func tableExists(_ table: TableIdentifier) throws -> Bool {
|
||||
try exists(type: .table, name: table.name, in: table.schemaID)
|
||||
}
|
||||
|
||||
/// Returns whether a table is an internal SQLite table.
|
||||
///
|
||||
/// Those are tables whose name begins with `sqlite_` and `pragma_`.
|
||||
///
|
||||
/// For more information, see https://www.sqlite.org/fileformat2.html
|
||||
/// For more information, see <https://www.sqlite.org/fileformat2.html>
|
||||
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_"
|
||||
@@ -52,7 +131,7 @@ extension Database {
|
||||
///
|
||||
/// Those are tables whose name begins with `sqlite_` and `pragma_`.
|
||||
///
|
||||
/// For more information, see https://www.sqlite.org/fileformat2.html
|
||||
/// 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)
|
||||
@@ -73,26 +152,30 @@ extension Database {
|
||||
Self.isGRDBInternalTable(tableName)
|
||||
}
|
||||
|
||||
/// Returns whether a view exists.
|
||||
/// Returns whether a view exists in the main or temp schema.
|
||||
public func viewExists(_ name: String) throws -> Bool {
|
||||
try exists(type: .view, name: name)
|
||||
try schemaIdentifiers().contains {
|
||||
try exists(type: .view, name: name, in: $0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether a trigger exists.
|
||||
/// Returns whether a trigger exists in the main or temp schema.
|
||||
public func triggerExists(_ name: String) throws -> Bool {
|
||||
try exists(type: .trigger, name: name)
|
||||
try schemaIdentifiers().contains {
|
||||
try exists(type: .trigger, name: name, in: $0)
|
||||
}
|
||||
}
|
||||
|
||||
private func exists(type: SchemaObjectType, name: String) throws -> Bool {
|
||||
private func exists(type: SchemaObjectType, name: String, in schemaID: SchemaIdentifier) throws -> Bool {
|
||||
// SQlite identifiers are case-insensitive, case-preserving:
|
||||
// http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html
|
||||
let name = name.lowercased()
|
||||
return try schema()
|
||||
return try schema(schemaID)
|
||||
.names(ofType: type)
|
||||
.contains { $0.lowercased() == name }
|
||||
}
|
||||
|
||||
/// The primary key for table named `tableName`.
|
||||
/// The primary key for table named `tableName`, in the main or temp schema.
|
||||
///
|
||||
/// All tables have a primary key, even when it is not explicit. When a
|
||||
/// table has no explicit primary key, the result is the hidden
|
||||
@@ -100,10 +183,20 @@ extension Database {
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
public func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo {
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try primaryKey(TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
return result
|
||||
}
|
||||
}
|
||||
throw DatabaseError.noSuchTable(tableName)
|
||||
}
|
||||
|
||||
/// Returns nil if table does not exist
|
||||
private func primaryKey(_ table: TableIdentifier) throws -> PrimaryKeyInfo? {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
|
||||
if let primaryKey = schemaCache.primaryKey(tableName) {
|
||||
return primaryKey
|
||||
if let primaryKey = schemaCache[table.schemaID].primaryKey(table.name) {
|
||||
return primaryKey.value
|
||||
}
|
||||
|
||||
// https://www.sqlite.org/pragma.html
|
||||
@@ -130,7 +223,11 @@ extension Database {
|
||||
// 1 | name | TEXT | 0 | NULL | 0 |
|
||||
// 2 | score | INTEGER | 0 | NULL | 0 |
|
||||
|
||||
let columns = try self.columns(in: tableName)
|
||||
guard let columns = try self.columns(in: table) else {
|
||||
// table does not exist
|
||||
schemaCache[table.schemaID].set(primaryKey: .missing, forTable: table.name)
|
||||
return nil
|
||||
}
|
||||
|
||||
let primaryKey: PrimaryKeyInfo
|
||||
let pkColumns = columns
|
||||
@@ -168,14 +265,14 @@ extension Database {
|
||||
if pkColumn.type.uppercased() == "INTEGER" {
|
||||
primaryKey = .rowID(pkColumn.name)
|
||||
} else {
|
||||
primaryKey = try .regular([pkColumn.name], tableHasRowID: tableHasRowID(tableName))
|
||||
primaryKey = try .regular([pkColumn.name], tableHasRowID: tableHasRowID(table))
|
||||
}
|
||||
default:
|
||||
// Multi-columns primary key
|
||||
primaryKey = try .regular(pkColumns.map(\.name), tableHasRowID: tableHasRowID(tableName))
|
||||
primaryKey = try .regular(pkColumns.map(\.name), tableHasRowID: tableHasRowID(table))
|
||||
}
|
||||
|
||||
schemaCache.set(primaryKey: primaryKey, forTable: tableName)
|
||||
schemaCache[table.schemaID].set(primaryKey: .value(primaryKey), forTable: table.name)
|
||||
return primaryKey
|
||||
}
|
||||
|
||||
@@ -186,18 +283,28 @@ extension Database {
|
||||
}
|
||||
|
||||
/// Returns whether the table has a rowid column.
|
||||
private func tableHasRowID(_ tableName: String) throws -> Bool {
|
||||
///
|
||||
/// - precondition: table exists.
|
||||
private func tableHasRowID(_ table: TableIdentifier) throws -> Bool {
|
||||
// Not need to cache the result, because this information feeds
|
||||
// `PrimaryKeyInfo`, which is cached.
|
||||
do {
|
||||
_ = try makeSelectStatement(sql: "SELECT rowid FROM \(tableName.quotedDatabaseIdentifier)")
|
||||
// Use a distinctive alias so that we better understand in the
|
||||
// future why this query appears in the error log.
|
||||
// https://github.com/groue/GRDB.swift/issues/945#issuecomment-804896196
|
||||
//
|
||||
// TODO: find a way to know if a table is WITHOUT ROWID without
|
||||
// generating an error.
|
||||
_ = try makeStatement(sql: """
|
||||
SELECT rowid AS checkWithoutRowidOptimization FROM \(table.quotedDatabaseIdentifier)
|
||||
""")
|
||||
return true
|
||||
} catch DatabaseError.SQLITE_ERROR {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// The indexes on table named `tableName`.
|
||||
/// The indexes on table named `tableName`, in the main or temp schema.
|
||||
///
|
||||
/// Only indexes on columns are returned. Indexes on expressions are
|
||||
/// not returned.
|
||||
@@ -207,21 +314,35 @@ extension Database {
|
||||
///
|
||||
/// If you want to know if a set of columns uniquely identify a row, prefer
|
||||
/// `table(_:hasUniqueKey:)` instead.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
public func indexes(on tableName: String) throws -> [IndexInfo] {
|
||||
if let indexes = schemaCache.indexes(on: tableName) {
|
||||
return indexes
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try indexes(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
return result
|
||||
}
|
||||
}
|
||||
throw DatabaseError.noSuchTable(tableName)
|
||||
}
|
||||
|
||||
/// Returns nil if table does not exist
|
||||
private func indexes(on table: TableIdentifier) throws -> [IndexInfo]? {
|
||||
if let indexes = schemaCache[table.schemaID].indexes(on: table.name) {
|
||||
return indexes.value
|
||||
}
|
||||
|
||||
let indexes = try Row
|
||||
// [seq:0 name:"index" unique:0 origin:"c" partial:0]
|
||||
.fetchAll(self, sql: "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))")
|
||||
.fetchAll(self, sql: "PRAGMA \(table.schemaID.sql).index_list(\(table.name.quotedDatabaseIdentifier))")
|
||||
.compactMap { row -> IndexInfo? in
|
||||
let indexName: String = row[1]
|
||||
let unique: Bool = row[2]
|
||||
|
||||
let indexInfoRows = try Row
|
||||
// [seqno:0 cid:2 name:"column"]
|
||||
.fetchAll(self, sql: "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))")
|
||||
.fetchAll(self, sql: """
|
||||
PRAGMA \(table.schemaID.sql).index_info(\(indexName.quotedDatabaseIdentifier))
|
||||
""")
|
||||
// Sort by rank
|
||||
.sorted(by: { ($0[0] as Int) < ($1[0] as Int) })
|
||||
var columns: [String] = []
|
||||
@@ -243,12 +364,13 @@ extension Database {
|
||||
if indexes.isEmpty {
|
||||
// PRAGMA index_list doesn't throw any error when table does
|
||||
// not exist. So let's check if table exists:
|
||||
if try tableExists(tableName) == false {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
if try tableExists(table) == false {
|
||||
schemaCache[table.schemaID].set(indexes: .missing, forTable: table.name)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
schemaCache.set(indexes: indexes, forTable: tableName)
|
||||
schemaCache[table.schemaID].set(indexes: .value(indexes), forTable: table.name)
|
||||
return indexes
|
||||
}
|
||||
|
||||
@@ -263,17 +385,32 @@ extension Database {
|
||||
try columnsForUniqueKey(Array(columns), in: tableName) != nil
|
||||
}
|
||||
|
||||
/// The foreign keys defined on table named `tableName`.
|
||||
/// The foreign keys defined on table named `tableName`, in the main or temp schema.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo] {
|
||||
if let foreignKeys = schemaCache.foreignKeys(on: tableName) {
|
||||
return foreignKeys
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try foreignKeys(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
return result
|
||||
}
|
||||
}
|
||||
throw DatabaseError.noSuchTable(tableName)
|
||||
}
|
||||
|
||||
/// Returns nil if table does not exist
|
||||
private func foreignKeys(on table: TableIdentifier) throws -> [ForeignKeyInfo]? {
|
||||
if let foreignKeys = schemaCache[table.schemaID].foreignKeys(on: table.name) {
|
||||
return foreignKeys.value
|
||||
}
|
||||
|
||||
var rawForeignKeys: [(
|
||||
destinationTable: String,
|
||||
mapping: [(origin: String, destination: String?, seq: Int)])] = []
|
||||
var previousId: Int? = nil
|
||||
for row in try Row.fetchAll(self, sql: "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") {
|
||||
for row in try Row.fetchAll(self, sql: """
|
||||
PRAGMA \(table.schemaID.sql).foreign_key_list(\(table.name.quotedDatabaseIdentifier))
|
||||
""")
|
||||
{
|
||||
// row = [id:0 seq:0 table:"parents" from:"parentId" to:"id" on_update:"..." on_delete:"..." match:"..."]
|
||||
let id: Int = row[0]
|
||||
let seq: Int = row[1]
|
||||
@@ -295,8 +432,9 @@ extension Database {
|
||||
if rawForeignKeys.isEmpty {
|
||||
// PRAGMA foreign_key_list doesn't throw any error when table does
|
||||
// not exist. So let's check if table exists:
|
||||
if try tableExists(tableName) == false {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
if try tableExists(table) == false {
|
||||
schemaCache[table.schemaID].set(foreignKeys: .missing, forTable: table.name)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -319,36 +457,51 @@ extension Database {
|
||||
return ForeignKeyInfo(destinationTable: destinationTable, mapping: completeMapping)
|
||||
}
|
||||
|
||||
schemaCache.set(foreignKeys: foreignKeys, forTable: tableName)
|
||||
schemaCache[table.schemaID].set(foreignKeys: .value(foreignKeys), forTable: table.name)
|
||||
return foreignKeys
|
||||
}
|
||||
|
||||
/// Returns the actual name of the database table
|
||||
func canonicalTableName(_ tableName: String) throws -> String {
|
||||
guard let name = try schema().canonicalName(tableName, ofType: .table) else {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
/// Returns the actual name of the database table, in the main or temp
|
||||
/// schema, or nil if the table does not exist.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
func canonicalTableName(_ tableName: String) throws -> String? {
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try schema(schemaIdentifier).canonicalName(tableName, ofType: .table) {
|
||||
return result
|
||||
}
|
||||
}
|
||||
return name
|
||||
return nil
|
||||
}
|
||||
|
||||
func schema() throws -> SchemaInfo {
|
||||
if let schemaInfo = schemaCache.schemaInfo {
|
||||
func schema(_ schemaID: SchemaIdentifier) throws -> SchemaInfo {
|
||||
if let schemaInfo = schemaCache[schemaID].schemaInfo {
|
||||
return schemaInfo
|
||||
}
|
||||
let schemaInfo = try SchemaInfo(self)
|
||||
schemaCache.schemaInfo = schemaInfo
|
||||
let schemaInfo = try SchemaInfo(self, masterTableName: schemaID.masterTableName)
|
||||
schemaCache[schemaID].schemaInfo = schemaInfo
|
||||
return schemaInfo
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
/// The columns in the table named `tableName`
|
||||
/// The columns in the table named `tableName`, in the main or temp schema.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
public func columns(in tableName: String) throws -> [ColumnInfo] {
|
||||
if let columns = schemaCache.columns(in: tableName) {
|
||||
return columns
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try columns(in: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
return result
|
||||
}
|
||||
}
|
||||
throw DatabaseError.noSuchTable(tableName)
|
||||
}
|
||||
|
||||
/// Returns nil if table does not exist
|
||||
private func columns(in table: TableIdentifier) throws -> [ColumnInfo]? {
|
||||
if let columns = schemaCache[table.schemaID].columns(in: table.name) {
|
||||
return columns.value
|
||||
}
|
||||
|
||||
// https://www.sqlite.org/pragma.html
|
||||
@@ -396,27 +549,35 @@ extension Database {
|
||||
if sqlite3_libversion_number() < 3008005 {
|
||||
// Work around a bug in SQLite where PRAGMA table_info would
|
||||
// return a result even after the table was deleted.
|
||||
if try !tableExists(tableName) {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
if try !tableExists(table) {
|
||||
schemaCache[table.schemaID].set(columns: .missing, forTable: table.name)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
columnInfoQuery = "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))"
|
||||
columnInfoQuery = "PRAGMA \(table.schemaID.sql).table_info(\(table.name.quotedDatabaseIdentifier))"
|
||||
} else {
|
||||
// For our purposes, we look for generated columns, not hidden
|
||||
// columns. The "hidden" column magic numbers come from the SQLite
|
||||
// source code. The values 2 and 3 refer to virtual and stored
|
||||
// generated columns, respectively. Search for COLFLAG_VIRTUAL in
|
||||
// https://www.sqlite.org/cgi/src/file?name=src/pragma.c&ci=fca8dc8b578f215a
|
||||
columnInfoQuery = "SELECT * FROM pragma_table_xinfo('\(tableName)') WHERE hidden IN (0,2,3)"
|
||||
// Use PRAGMA table_xinfo so that we can load generated columns
|
||||
columnInfoQuery = "PRAGMA \(table.schemaID.sql).table_xinfo(\(table.name.quotedDatabaseIdentifier))"
|
||||
}
|
||||
let columns = try ColumnInfo
|
||||
.fetchAll(self, sql: columnInfoQuery)
|
||||
.filter {
|
||||
// Purpose: keep generated columns, but discard hidden ones.
|
||||
// The "hidden" column magic numbers come from the SQLite
|
||||
// source code. The values 2 and 3 refer to virtual and stored
|
||||
// generated columns, respectively, and 1 refer to hidden one.
|
||||
// Search for COLFLAG_HIDDEN in
|
||||
// https://www.sqlite.org/cgi/src/file?name=src/pragma.c&ci=fca8dc8b578f215a
|
||||
$0.hidden != 1
|
||||
}
|
||||
.sorted(by: { $0.cid < $1.cid })
|
||||
if columns.isEmpty {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
// Table does not exist
|
||||
schemaCache[table.schemaID].set(columns: .missing, forTable: table.name)
|
||||
return nil
|
||||
}
|
||||
|
||||
schemaCache.set(columns: columns, forTable: tableName)
|
||||
schemaCache[table.schemaID].set(columns: .value(columns), forTable: table.name)
|
||||
return columns
|
||||
}
|
||||
|
||||
@@ -461,22 +622,29 @@ extension Database {
|
||||
/// A column of a database table.
|
||||
///
|
||||
/// This type closely matches the information returned by the
|
||||
/// `table_info` pragma.
|
||||
/// `table_info` and `table_xinfo` pragmas.
|
||||
///
|
||||
/// > CREATE TABLE player (
|
||||
/// id INTEGER PRIMARY KEY,
|
||||
/// firstName TEXT,
|
||||
/// lastName TEXT)
|
||||
/// > PRAGMA table_info("player")
|
||||
/// cid name type notnull dflt_value pk
|
||||
/// ---- ----- ------- -------- ---------- ---
|
||||
/// 0 id INTEGER 0 NULL 1
|
||||
/// 1 name TEXT 0 NULL 0
|
||||
/// 2 score INTEGER 0 NULL 0
|
||||
/// sqlite> CREATE TABLE player (
|
||||
/// ...> id INTEGER PRIMARY KEY,
|
||||
/// ...> firstName TEXT,
|
||||
/// ...> lastName TEXT);
|
||||
/// sqlite> PRAGMA table_info(player);
|
||||
/// cid name type notnull dflt_value pk
|
||||
/// ------ ---------- ---------- ---------- ---------- -----
|
||||
/// 0 id INTEGER 0 1
|
||||
/// 1 firstName TEXT 0 0
|
||||
/// 2 lastName TEXT 0 0
|
||||
/// sqlite> PRAGMA table_xinfo(player);
|
||||
/// cid name type notnull dflt_value pk hidden
|
||||
/// ------ ---------- ---------- ---------- ---------- ----- ----------
|
||||
/// 0 id INTEGER 0 1 0
|
||||
/// 1 firstName TEXT 0 0 0
|
||||
/// 2 lastName TEXT 0 0 0
|
||||
///
|
||||
/// See `Database.columns(in:)` and https://www.sqlite.org/pragma.html#pragma_table_info
|
||||
/// See `Database.columns(in:)` and <https://www.sqlite.org/pragma.html#pragma_table_info>
|
||||
public struct ColumnInfo: FetchableRecord {
|
||||
let cid: Int
|
||||
let hidden: Int?
|
||||
|
||||
/// The column name
|
||||
public let name: String
|
||||
@@ -521,8 +689,8 @@ public struct ColumnInfo: FetchableRecord {
|
||||
/// the primary key for columns that are part of the primary key.
|
||||
///
|
||||
/// References:
|
||||
/// - https://sqlite.org/releaselog/3_7_16.html
|
||||
/// - http://mailinglists.sqlite.org/cgi-bin/mailman/private/sqlite-users/2013-April/046034.html
|
||||
/// - <https://sqlite.org/releaselog/3_7_16.html>
|
||||
/// - <http://mailinglists.sqlite.org/cgi-bin/mailman/private/sqlite-users/2013-April/046034.html>
|
||||
public let primaryKeyIndex: Int
|
||||
|
||||
/// :nodoc:
|
||||
@@ -533,6 +701,7 @@ public struct ColumnInfo: FetchableRecord {
|
||||
isNotNull = row["notnull"]
|
||||
defaultValueSQL = row["dflt_value"]
|
||||
primaryKeyIndex = row["pk"]
|
||||
hidden = row["hidden"]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -669,6 +838,24 @@ public struct PrimaryKeyInfo {
|
||||
return tableHasRowID
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of the fastest primary key column
|
||||
///
|
||||
/// Returns nil for WITHOUT ROWID tables with a multi-columns primary key
|
||||
var fastPrimaryKeyColumn: String? {
|
||||
if let rowIDColumn = rowIDColumn {
|
||||
// Prefer the user-provided name of the rowid
|
||||
return rowIDColumn
|
||||
} else if tableHasRowID {
|
||||
// Prefer the rowid
|
||||
return Column.rowID.name
|
||||
} else if columns.count == 1 {
|
||||
// WITHOUT ROWID table: use primary key column
|
||||
return columns[0]
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// You get foreign keys from table names, with the
|
||||
@@ -701,11 +888,10 @@ enum SchemaObjectType: String {
|
||||
struct SchemaInfo: Equatable {
|
||||
private var objects: Set<SchemaObject>
|
||||
|
||||
init(_ db: Database) throws {
|
||||
/// - parameter masterTable: "sqlite_master" or "sqlite_temp_master"
|
||||
init(_ db: Database, masterTableName: String) throws { // swiftlint:disable:this inclusive_language
|
||||
objects = try Set(SchemaObject.fetchCursor(db, sql: """
|
||||
SELECT type, name, tbl_name, sql, 0 AS isTemporary FROM sqlite_master \
|
||||
UNION \
|
||||
SELECT type, name, tbl_name, sql, 1 FROM sqlite_temp_master
|
||||
SELECT type, name, tbl_name, sql FROM \(masterTableName)
|
||||
"""))
|
||||
}
|
||||
|
||||
@@ -724,7 +910,9 @@ struct SchemaInfo: Equatable {
|
||||
/// try db.schema().canonicalName("foobar", ofType: .table) // "FooBar"
|
||||
func canonicalName(_ name: String, ofType type: SchemaObjectType) -> String? {
|
||||
let name = name.lowercased()
|
||||
return objects.first { $0.name.lowercased() == name }?.name
|
||||
return objects
|
||||
.first { $0.type == type.rawValue && $0.name.lowercased() == name }?
|
||||
.name
|
||||
}
|
||||
|
||||
private struct SchemaObject: Codable, Hashable, FetchableRecord {
|
||||
@@ -732,6 +920,5 @@ struct SchemaInfo: Equatable {
|
||||
var name: String
|
||||
var tbl_name: String?
|
||||
var sql: String?
|
||||
var isTemporary: Bool
|
||||
}
|
||||
}
|
||||
+475
-189
@@ -4,6 +4,62 @@ extension Database {
|
||||
|
||||
// MARK: - Statements
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func makeStatement(sql: String) throws -> Statement {
|
||||
try makeStatement(sql: sql, prepFlags: 0)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeStatement(literal: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// let statement = try db.makeStatement(literal: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
public func makeStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
let (sql, arguments) = try sqlLiteral.build(self)
|
||||
let statement = try makeStatement(sql: sql)
|
||||
if arguments.isEmpty == false {
|
||||
// Throws if arguments do not match
|
||||
try statement.setArguments(arguments)
|
||||
}
|
||||
return statement
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT * FROM player WHERE id = ?")
|
||||
@@ -11,25 +67,139 @@ extension Database {
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: A SelectStatement.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func makeSelectStatement(sql: String) throws -> SelectStatement {
|
||||
try makeSelectStatement(sql: sql, prepFlags: 0)
|
||||
@available(*, deprecated, renamed: "makeStatement(sql:)")
|
||||
public func makeSelectStatement(sql: String) throws -> Statement {
|
||||
try makeStatement(sql: sql)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0)
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try makeSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try makeSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try makeSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
@available(*, deprecated, renamed: "makeStatement(literal:)")
|
||||
public func makeSelectStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
try makeStatement(literal: sqlLiteral)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0)
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
/// - returns: A SelectStatement.
|
||||
/// SQLite 3.20.0, see <http://www.sqlite.org/c3ref/prepare.html>)
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
func makeSelectStatement(sql: String, prepFlags: Int32) throws -> SelectStatement {
|
||||
try SelectStatement.prepare(self, sql: sql, prepFlags: prepFlags)
|
||||
func makeStatement(sql: String, prepFlags: Int32) throws -> Statement {
|
||||
let statements = SQLStatementCursor(database: self, sql: sql, arguments: nil, prepFlags: prepFlags)
|
||||
guard let statement = try statements.next() else {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_ERROR,
|
||||
message: "empty statement",
|
||||
sql: sql)
|
||||
}
|
||||
do {
|
||||
guard try statements.next() == nil else {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: """
|
||||
Multiple statements found. To execute multiple statements, use \
|
||||
Database.execute(sql:) or Database.allStatements(sql:) instead.
|
||||
""",
|
||||
sql: sql)
|
||||
}
|
||||
} catch {
|
||||
// Something while would not compile was found after the first statement.
|
||||
// Complain about multiple statements anyway.
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: """
|
||||
Multiple statements found. To execute multiple statements, use \
|
||||
Database.execute(sql:) or Database.allStatements(sql:) instead.
|
||||
""",
|
||||
sql: sql)
|
||||
}
|
||||
return statement
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedStatement(sql: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// let statement = try db.cachedStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// The returned statement may have already been used: it may or may not
|
||||
/// contain values for its eventual arguments.
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func cachedStatement(sql: String) throws -> Statement {
|
||||
try publicStatementCache.statement(sql)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedStatement(literal: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// let statement = try db.cachedStatement(literal: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
public func cachedStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
let (sql, arguments) = try sqlLiteral.build(self)
|
||||
let statement = try cachedStatement(sql: sql)
|
||||
if arguments.isEmpty == false {
|
||||
// Throws if arguments do not match
|
||||
try statement.setArguments(arguments)
|
||||
}
|
||||
return statement
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
@@ -42,15 +212,45 @@ extension Database {
|
||||
/// contain values for its eventual arguments.
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func cachedSelectStatement(sql: String) throws -> SelectStatement {
|
||||
try publicStatementCache.selectStatement(sql)
|
||||
@available(*, deprecated, renamed: "cachedStatement(sql:)")
|
||||
public func cachedSelectStatement(sql: String) throws -> Statement {
|
||||
try cachedStatement(sql: sql)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedSelectStatement(literal: "SELECT COUNT(*) FROM player WHERE score > \(20)")
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement)!
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try cachedSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try cachedSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try cachedSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
@available(*, deprecated, renamed: "cachedStatement(literal:)")
|
||||
public func cachedSelectStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
try cachedStatement(literal: sqlLiteral)
|
||||
}
|
||||
|
||||
/// Returns a cached statement that does not conflict with user's cached statements.
|
||||
func internalCachedSelectStatement(sql: String) throws -> SelectStatement {
|
||||
try internalStatementCache.selectStatement(sql)
|
||||
func internalCachedStatement(sql: String) throws -> Statement {
|
||||
try internalStatementCache.statement(sql)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
@@ -62,23 +262,34 @@ extension Database {
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func makeUpdateStatement(sql: String) throws -> UpdateStatement {
|
||||
try makeUpdateStatement(sql: sql, prepFlags: 0)
|
||||
@available(*, deprecated, renamed: "makeStatement(sql:)")
|
||||
public func makeUpdateStatement(sql: String) throws -> Statement {
|
||||
try makeStatement(sql: sql)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)", prepFlags: 0)
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
func makeUpdateStatement(sql: String, prepFlags: Int32) throws -> UpdateStatement {
|
||||
try UpdateStatement.prepare(self, sql: sql, prepFlags: prepFlags)
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try makeUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = ?
|
||||
/// """)
|
||||
/// try makeUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = \("O'Brien")
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try makeUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = ?, score = \(10)
|
||||
/// """)
|
||||
@available(*, deprecated, renamed: "makeStatement(literal:)")
|
||||
public func makeUpdateStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
try makeStatement(literal: sqlLiteral)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
@@ -91,15 +302,120 @@ extension Database {
|
||||
/// contain values for its eventual arguments.
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func cachedUpdateStatement(sql: String) throws -> UpdateStatement {
|
||||
try publicStatementCache.updateStatement(sql)
|
||||
@available(*, deprecated, renamed: "cachedStatement(sql:)")
|
||||
public func cachedUpdateStatement(sql: String) throws -> Statement {
|
||||
try cachedStatement(sql: sql)
|
||||
}
|
||||
|
||||
/// Returns a cached statement that does not conflict with user's cached statements.
|
||||
func internalCachedUpdateStatement(sql: String) throws -> UpdateStatement {
|
||||
try internalStatementCache.updateStatement(sql)
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try cachedUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = ?
|
||||
/// """)
|
||||
/// try cachedUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = \("O'Brien")
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try cachedUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = ?, score = \(10)
|
||||
/// """)
|
||||
@available(*, deprecated, renamed: "cachedStatement(sql:)")
|
||||
public func cachedUpdateStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
try cachedStatement(literal: sqlLiteral)
|
||||
}
|
||||
|
||||
/// Returns a cursor of all SQL statements separated by semi-colons.
|
||||
///
|
||||
/// let statements = try db.allStatements(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// """, arguments: ["Arthur", "Barbara", "O'Brien"])
|
||||
/// while let statement = try statements.next() {
|
||||
/// try statement.execute()
|
||||
/// }
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - returns: A cursor of `Statement`
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
/// - precondition: Arguments must be nil, or all arguments must be set.
|
||||
/// The returned cursor will throw an error otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """, arguments: [1000, 1000])
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """, arguments: [1000])
|
||||
public func allStatements(sql: String, arguments: StatementArguments? = nil)
|
||||
throws -> SQLStatementCursor
|
||||
{
|
||||
SQLStatementCursor(database: self, sql: sql, arguments: arguments)
|
||||
}
|
||||
|
||||
/// Returns a cursor of all SQL statements separated by semi-colons.
|
||||
///
|
||||
/// Literals allow you to safely embed raw values in your SQL, without any
|
||||
/// risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// let statements = try db.allStatements(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"));
|
||||
/// INSERT INTO player (name) VALUES (\("Barbara"));
|
||||
/// INSERT INTO player (name) VALUES (\("O'Brien"));
|
||||
/// """)
|
||||
/// while let statement = try statements.next() {
|
||||
/// try statement.execute()
|
||||
/// }
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A cursor of `Statement`
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// The returned cursor will throw an error otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < \(1000);
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000);
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < \(1000);
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
public func allStatements(literal sqlLiteral: SQL) throws -> SQLStatementCursor {
|
||||
let context = SQLGenerationContext(self)
|
||||
let sql = try sqlLiteral.sql(context)
|
||||
let arguments = context.arguments.isEmpty
|
||||
? nil // builds statements without arguments
|
||||
: context.arguments // force arguments to match
|
||||
return SQLStatementCursor(database: self, sql: sql, arguments: arguments)
|
||||
}
|
||||
|
||||
/// Executes one or several SQL statements, separated by semi-colons.
|
||||
@@ -121,23 +437,17 @@ extension Database {
|
||||
/// - arguments: Statement arguments.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func execute(sql: String, arguments: StatementArguments = StatementArguments()) throws {
|
||||
try execute(literal: SQLLiteral(sql: sql, arguments: arguments))
|
||||
try execute(literal: SQL(sql: sql, arguments: arguments))
|
||||
}
|
||||
|
||||
/// Executes one or several SQL statements, separated by semi-colons.
|
||||
///
|
||||
/// try db.execute(literal: SQLLiteral(
|
||||
/// sql: "INSERT INTO player (name) VALUES (:name)",
|
||||
/// arguments: ["name": "Arthur"]))
|
||||
/// Literals allow you to safely embed raw values in your SQL, without any
|
||||
/// risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// try db.execute(literal: SQLLiteral(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// """, arguments: ["Arthur", "Barbara", "O'Brien"]))
|
||||
///
|
||||
/// With Swift 5, you can safely embed raw values in your SQL queries,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
/// try db.execute(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"))
|
||||
/// """)
|
||||
///
|
||||
/// try db.execute(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"));
|
||||
@@ -147,86 +457,95 @@ extension Database {
|
||||
///
|
||||
/// This method may throw a DatabaseError.
|
||||
///
|
||||
/// - parameter sqlLiteral: An SQLLiteral.
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func execute(literal sqlLiteral: SQLLiteral) throws {
|
||||
// This method is like sqlite3_exec (https://www.sqlite.org/c3ref/exec.html)
|
||||
// It adds support for arguments, and the tricky part is to consume
|
||||
// arguments as statements are executed.
|
||||
//
|
||||
// This job is performed by StatementArguments.extractBindings(forStatement:allowingRemainingValues:)
|
||||
//
|
||||
// And before we return, we'll check that all arguments were consumed.
|
||||
|
||||
let context = SQLGenerationContext(self)
|
||||
let sql = try sqlLiteral.sql(context)
|
||||
var arguments = context.arguments
|
||||
let initialValuesCount = arguments.values.count
|
||||
|
||||
// Build a C string (SQLite wants that), and execute SQL statements one
|
||||
// after the other.
|
||||
try sql.utf8CString.withUnsafeBufferPointer { buffer in
|
||||
guard let sqlStart = buffer.baseAddress else { return }
|
||||
let sqlEnd = sqlStart + buffer.count // past \0
|
||||
var statementStart = sqlStart
|
||||
while statementStart < sqlEnd {
|
||||
var statementEnd: UnsafePointer<Int8>? = nil
|
||||
let nextStatement: UpdateStatement?
|
||||
|
||||
// Compile
|
||||
do {
|
||||
let authorizer = StatementCompilationAuthorizer()
|
||||
nextStatement = try withAuthorizer(authorizer) {
|
||||
try UpdateStatement(
|
||||
database: self,
|
||||
statementStart: statementStart,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: 0,
|
||||
authorizer: authorizer)
|
||||
}
|
||||
}
|
||||
|
||||
guard let statement = nextStatement else {
|
||||
// End of SQL string
|
||||
break
|
||||
}
|
||||
|
||||
// Extract statement arguments
|
||||
let bindings = try arguments.extractBindings(forStatement: statement, allowingRemainingValues: true)
|
||||
// unsafe is OK because we just extracted the correct number of arguments
|
||||
statement.setUncheckedArguments(StatementArguments(bindings))
|
||||
|
||||
// Execute
|
||||
try statement.execute()
|
||||
|
||||
// Next
|
||||
statementStart = statementEnd!
|
||||
}
|
||||
public func execute(literal sqlLiteral: SQL) throws {
|
||||
let statements = try allStatements(literal: sqlLiteral)
|
||||
while let statement = try statements.next() {
|
||||
try statement.execute()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class SQLStatementCursor: Cursor {
|
||||
private let database: Database
|
||||
private let cString: ContiguousArray<CChar>
|
||||
private let prepFlags: CInt
|
||||
private let initialArgumentCount: Int?
|
||||
|
||||
// Mutated by iteration
|
||||
private var offset: Int // offset in the C string
|
||||
private var arguments: StatementArguments? // Nil when arguments are set later
|
||||
|
||||
init(database: Database, sql: String, arguments: StatementArguments?, prepFlags: CInt = 0) {
|
||||
self.database = database
|
||||
self.cString = sql.utf8CString
|
||||
self.prepFlags = prepFlags
|
||||
self.initialArgumentCount = arguments?.values.count
|
||||
self.offset = 0
|
||||
self.arguments = arguments
|
||||
}
|
||||
|
||||
public func next() throws -> Statement? {
|
||||
guard offset < cString.count - 1 /* trailing \0 */ else {
|
||||
try checkArgumentsAreEmpty()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Check that all arguments were consumed: it is a programmer error to
|
||||
// provide arguments that do not match the statement.
|
||||
if arguments.values.isEmpty == false {
|
||||
return try cString.withUnsafeBufferPointer { buffer in
|
||||
guard let baseAddress = buffer.baseAddress else {
|
||||
// Should never happen since buffer contains at least
|
||||
// the trailing \0
|
||||
return nil
|
||||
}
|
||||
|
||||
var statementEnd: UnsafePointer<Int8>? = nil
|
||||
let compiledStatement = try Statement(
|
||||
database: database,
|
||||
statementStart: baseAddress + offset,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: prepFlags)
|
||||
|
||||
offset = statementEnd! - baseAddress
|
||||
|
||||
guard let statement = compiledStatement else {
|
||||
try checkArgumentsAreEmpty()
|
||||
return nil
|
||||
}
|
||||
|
||||
if arguments != nil {
|
||||
// Extract statement arguments
|
||||
let bindings = try arguments!.extractBindings(
|
||||
forStatement: statement,
|
||||
allowingRemainingValues: true)
|
||||
// unchecked is OK because we just extracted the correct
|
||||
// number of arguments
|
||||
statement.setUncheckedArguments(StatementArguments(bindings))
|
||||
}
|
||||
|
||||
return statement
|
||||
}
|
||||
}
|
||||
|
||||
/// Check that all arguments were consumed: it is a programmer error to
|
||||
/// provide arguments that do not match the statements.
|
||||
private func checkArgumentsAreEmpty() throws {
|
||||
if let arguments = arguments,
|
||||
let initialArgumentCount = initialArgumentCount,
|
||||
arguments.values.isEmpty == false
|
||||
{
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: "wrong number of statement arguments: \(initialValuesCount)")
|
||||
message: "wrong number of statement arguments: \(initialArgumentCount)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
func executeUpdateStatement(_ statement: UpdateStatement) throws {
|
||||
// Two things must prevent the statement from executing: aborted
|
||||
// transactions, and database suspension.
|
||||
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
|
||||
try checkForSuspensionViolation(from: statement)
|
||||
|
||||
if _isRecordingSelectedRegion {
|
||||
_selectedRegion.formUnion(statement.databaseRegion)
|
||||
}
|
||||
|
||||
let authorizer = observationBroker.updateStatementWillExecute(statement)
|
||||
func executeStatement(_ statement: Statement) throws {
|
||||
let authorizer = try statementWillExecute(statement)
|
||||
let sqliteStatement = statement.sqliteStatement
|
||||
|
||||
var code: Int32 = SQLITE_OK
|
||||
withAuthorizer(authorizer) {
|
||||
while true {
|
||||
@@ -259,40 +578,18 @@ extension Database {
|
||||
// We can now move on further tasks.
|
||||
|
||||
if code == SQLITE_DONE {
|
||||
try updateStatementDidExecute(statement)
|
||||
try statementDidExecute(statement)
|
||||
} else {
|
||||
assert(code != SQLITE_ROW)
|
||||
try updateStatementDidFail(statement)
|
||||
throw DatabaseError(
|
||||
resultCode: code,
|
||||
message: lastErrorMessage,
|
||||
sql: statement.sql,
|
||||
arguments: statement.arguments)
|
||||
try statementDidFail(statement, withResultCode: code)
|
||||
}
|
||||
}
|
||||
|
||||
private func updateStatementDidExecute(_ statement: UpdateStatement) throws {
|
||||
if statement.invalidatesDatabaseSchemaCache {
|
||||
clearSchemaCache()
|
||||
}
|
||||
|
||||
try observationBroker.updateStatementDidExecute(statement)
|
||||
}
|
||||
|
||||
private func updateStatementDidFail(_ statement: UpdateStatement) throws {
|
||||
// Failed statements can not be reused, because sqlite3_reset won't
|
||||
// be able to restore the statement to its initial state:
|
||||
// https://www.sqlite.org/c3ref/reset.html
|
||||
//
|
||||
// So make sure we clear this statement from the cache.
|
||||
internalStatementCache.remove(statement)
|
||||
publicStatementCache.remove(statement)
|
||||
|
||||
try observationBroker.updateStatementDidFail(statement)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
func selectStatementWillExecute(_ statement: SelectStatement) throws {
|
||||
/// Returns the authorizer that should be used during statement execution
|
||||
/// (this allows preventing the truncate optimization when there exists a
|
||||
/// transaction observer for row deletion).
|
||||
@usableFromInline
|
||||
func statementWillExecute(_ statement: Statement) throws -> StatementAuthorizer? {
|
||||
// Two things must prevent the statement from executing: aborted
|
||||
// transactions, and database suspension.
|
||||
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
|
||||
@@ -301,9 +598,24 @@ extension Database {
|
||||
if _isRecordingSelectedRegion {
|
||||
_selectedRegion.formUnion(statement.databaseRegion)
|
||||
}
|
||||
|
||||
return observationBroker.statementWillExecute(statement)
|
||||
}
|
||||
|
||||
func selectStatementDidFail(_ statement: SelectStatement) {
|
||||
/// May throw a cancelled commit error, if a transaction observer cancels
|
||||
/// an empty transaction.
|
||||
@usableFromInline
|
||||
func statementDidExecute(_ statement: Statement) throws {
|
||||
if statement.invalidatesDatabaseSchemaCache {
|
||||
clearSchemaCache()
|
||||
}
|
||||
|
||||
try observationBroker.statementDidExecute(statement)
|
||||
}
|
||||
|
||||
/// Always throws an error
|
||||
@usableFromInline
|
||||
func statementDidFail(_ statement: Statement, withResultCode resultCode: Int32) throws -> Never {
|
||||
// Failed statements can not be reused, because sqlite3_reset won't
|
||||
// be able to restore the statement to its initial state:
|
||||
// https://www.sqlite.org/c3ref/reset.html
|
||||
@@ -311,21 +623,30 @@ extension Database {
|
||||
// So make sure we clear this statement from the cache.
|
||||
internalStatementCache.remove(statement)
|
||||
publicStatementCache.remove(statement)
|
||||
|
||||
/// Exposes the user-provided cancelled commit error, if a transaction
|
||||
/// observer has cancelled a transaction.
|
||||
try observationBroker.statementDidFail(statement)
|
||||
|
||||
throw DatabaseError(
|
||||
resultCode: resultCode,
|
||||
message: lastErrorMessage,
|
||||
sql: statement.sql,
|
||||
arguments: statement.arguments)
|
||||
}
|
||||
}
|
||||
|
||||
/// A thread-unsafe statement cache
|
||||
struct StatementCache {
|
||||
unowned let db: Database
|
||||
private var selectStatements: [String: SelectStatement] = [:]
|
||||
private var updateStatements: [String: UpdateStatement] = [:]
|
||||
private var statements: [String: Statement] = [:]
|
||||
|
||||
init(database: Database) {
|
||||
self.db = database
|
||||
}
|
||||
|
||||
mutating func selectStatement(_ sql: String) throws -> SelectStatement {
|
||||
if let statement = selectStatements[sql] {
|
||||
mutating func statement(_ sql: String) throws -> Statement {
|
||||
if let statement = statements[sql] {
|
||||
return statement
|
||||
}
|
||||
|
||||
@@ -339,61 +660,26 @@ struct StatementCache {
|
||||
// However SQLITE_PREPARE_PERSISTENT was only introduced in
|
||||
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
let statement = try db.makeSelectStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
|
||||
let statement = try db.makeStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
|
||||
#else
|
||||
let statement: SelectStatement
|
||||
let statement: Statement
|
||||
if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) {
|
||||
// SQLite 3.24.0 or more
|
||||
statement = try db.makeSelectStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
|
||||
statement = try db.makeStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
|
||||
} else {
|
||||
// SQLite 3.19.3 or less
|
||||
statement = try db.makeSelectStatement(sql: sql)
|
||||
statement = try db.makeStatement(sql: sql)
|
||||
}
|
||||
#endif
|
||||
selectStatements[sql] = statement
|
||||
return statement
|
||||
}
|
||||
|
||||
mutating func updateStatement(_ sql: String) throws -> UpdateStatement {
|
||||
if let statement = updateStatements[sql] {
|
||||
return statement
|
||||
}
|
||||
|
||||
// http://www.sqlite.org/c3ref/c_prepare_persistent.html#sqlitepreparepersistent
|
||||
// > The SQLITE_PREPARE_PERSISTENT flag is a hint to the query
|
||||
// > planner that the prepared statement will be retained for a long
|
||||
// > time and probably reused many times.
|
||||
//
|
||||
// This looks like a perfect match for cached statements.
|
||||
//
|
||||
// However SQLITE_PREPARE_PERSISTENT was only introduced in
|
||||
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
let statement = try db.makeUpdateStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
|
||||
#else
|
||||
let statement: UpdateStatement
|
||||
if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) {
|
||||
// SQLite 3.24.0 or more
|
||||
statement = try db.makeUpdateStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
|
||||
} else {
|
||||
// SQLite 3.19.3 or less
|
||||
statement = try db.makeUpdateStatement(sql: sql)
|
||||
}
|
||||
#endif
|
||||
updateStatements[sql] = statement
|
||||
statements[sql] = statement
|
||||
return statement
|
||||
}
|
||||
|
||||
mutating func clear() {
|
||||
updateStatements = [:]
|
||||
selectStatements = [:]
|
||||
statements = [:]
|
||||
}
|
||||
|
||||
mutating func remove(_ statement: SelectStatement) {
|
||||
selectStatements.removeFirst { $0.value === statement }
|
||||
}
|
||||
|
||||
mutating func remove(_ statement: UpdateStatement) {
|
||||
updateStatements.removeFirst { $0.value === statement }
|
||||
mutating func remove(_ statement: Statement) {
|
||||
statements.removeFirst { $0.value === statement }
|
||||
}
|
||||
}
|
||||
+73
-75
@@ -32,7 +32,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// The error logging function.
|
||||
///
|
||||
/// Quoting https://www.sqlite.org/errlog.html:
|
||||
/// Quoting <https://www.sqlite.org/errlog.html>:
|
||||
///
|
||||
/// > SQLite can be configured to invoke a callback function containing an
|
||||
/// > error code and a terse error message whenever anomalies occur. This
|
||||
@@ -71,7 +71,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// If no row has ever been inserted using this database connection,
|
||||
/// returns zero.
|
||||
///
|
||||
/// For more detailed information, see https://www.sqlite.org/c3ref/last_insert_rowid.html
|
||||
/// For more detailed information, see <https://www.sqlite.org/c3ref/last_insert_rowid.html>
|
||||
public var lastInsertedRowID: Int64 {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
return sqlite3_last_insert_rowid(sqliteConnection)
|
||||
@@ -80,7 +80,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// The number of rows modified, inserted or deleted by the most recent
|
||||
/// successful INSERT, UPDATE or DELETE statement.
|
||||
///
|
||||
/// For more detailed information, see https://www.sqlite.org/c3ref/changes.html
|
||||
/// For more detailed information, see <https://www.sqlite.org/c3ref/changes.html>
|
||||
public var changesCount: Int {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
return Int(sqlite3_changes(sqliteConnection))
|
||||
@@ -90,7 +90,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// INSERT, UPDATE or DELETE statements since the database connection was
|
||||
/// opened.
|
||||
///
|
||||
/// For more detailed information, see https://www.sqlite.org/c3ref/total_changes.html
|
||||
/// For more detailed information, see <https://www.sqlite.org/c3ref/total_changes.html>
|
||||
public var totalChangesCount: Int {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
return Int(sqlite3_total_changes(sqliteConnection))
|
||||
@@ -125,8 +125,27 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// MARK: - Internal properties
|
||||
|
||||
// Caches
|
||||
struct SchemaCache {
|
||||
var schemaIdentifiers: [SchemaIdentifier]?
|
||||
fileprivate var schemas: [SchemaIdentifier: DatabaseSchemaCache] = [:]
|
||||
|
||||
subscript(schemaID: SchemaIdentifier) -> DatabaseSchemaCache { // internal so that it can be tested
|
||||
get {
|
||||
schemas[schemaID] ?? DatabaseSchemaCache()
|
||||
}
|
||||
set {
|
||||
schemas[schemaID] = newValue
|
||||
}
|
||||
}
|
||||
|
||||
mutating func clear() {
|
||||
schemaIdentifiers = nil
|
||||
schemas.removeAll()
|
||||
}
|
||||
}
|
||||
|
||||
var _lastSchemaVersion: Int32? // Support for clearSchemaCacheIfNeeded()
|
||||
var schemaCache: DatabaseSchemaCache // internal so that it can be tested
|
||||
var schemaCache = SchemaCache()
|
||||
lazy var internalStatementCache = StatementCache(database: self)
|
||||
lazy var publicStatementCache = StatementCache(database: self)
|
||||
|
||||
@@ -142,8 +161,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
|
||||
/// If true, select statement execution is recorded.
|
||||
/// Use recordingSelectedRegion(_:), see `selectStatementWillExecute(_:)`
|
||||
var _isRecordingSelectedRegion: Bool = false
|
||||
/// Use recordingSelectedRegion(_:), see `statementWillExecute(_:)`
|
||||
var _isRecordingSelectedRegion = false
|
||||
var _selectedRegion = DatabaseRegion()
|
||||
|
||||
/// Support for checkForAbortedTransaction()
|
||||
@@ -163,20 +182,18 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
private var functions = Set<DatabaseFunction>()
|
||||
private var collations = Set<DatabaseCollation>()
|
||||
private var _readOnlyDepth = 0 // Modify with beginReadOnly/endReadOnly
|
||||
private var isClosed: Bool = false
|
||||
private var isClosed = false
|
||||
|
||||
// MARK: - Initializer
|
||||
|
||||
init(
|
||||
path: String,
|
||||
description: String,
|
||||
configuration: Configuration,
|
||||
schemaCache: DatabaseSchemaCache) throws
|
||||
configuration: Configuration) throws
|
||||
{
|
||||
self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
|
||||
self.description = description
|
||||
self.configuration = configuration
|
||||
self.schemaCache = schemaCache
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -186,7 +203,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// MARK: - Database Opening
|
||||
|
||||
private static func openConnection(path: String, flags: Int32) throws -> SQLiteConnection {
|
||||
// See https://www.sqlite.org/c3ref/open.html
|
||||
// See <https://www.sqlite.org/c3ref/open.html>
|
||||
var sqliteConnection: SQLiteConnection? = nil
|
||||
let code = sqlite3_open_v2(path, &sqliteConnection, flags, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
@@ -301,7 +318,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
//
|
||||
// - DatabaseCursorTests.testIssue583()
|
||||
// - http://sqlite.1065341.n5.nabble.com/Issue-report-sqlite3-set-authorizer-triggers-error-4-516-SQLITE-ABORT-ROLLBACK-during-statement-itern-td107972.html
|
||||
// swiftlint:disable:previous line_length
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
sqlite3_set_authorizer(
|
||||
sqliteConnection,
|
||||
@@ -347,7 +363,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
//
|
||||
// So let's fail early if file is not a database, or encrypted with
|
||||
// another passphrase.
|
||||
try makeSelectStatement(sql: "SELECT * FROM sqlite_master LIMIT 1").makeCursor().next()
|
||||
try makeStatement(sql: "SELECT * FROM sqlite_master LIMIT 1").makeCursor().next()
|
||||
}
|
||||
|
||||
// MARK: - Database Closing
|
||||
@@ -397,7 +413,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// try Player.deleteAll(db, keys: ids)
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/limits.html
|
||||
/// See <https://www.sqlite.org/limits.html>
|
||||
/// and `SQLITE_LIMIT_VARIABLE_NUMBER`.
|
||||
public var maximumStatementArgumentCount: Int {
|
||||
Int(sqlite3_limit(sqliteConnection, SQLITE_LIMIT_VARIABLE_NUMBER, -1))
|
||||
@@ -449,7 +465,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError(DatabaseError(resultCode: code, message: lastErrorMessage).description)
|
||||
fatalError(DatabaseError(resultCode: code, message: lastErrorMessage))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -468,7 +484,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
func beginReadOnly() throws {
|
||||
if configuration.readonly { return }
|
||||
if _readOnlyDepth == 0 {
|
||||
try internalCachedUpdateStatement(sql: "PRAGMA query_only = 1").execute()
|
||||
try internalCachedStatement(sql: "PRAGMA query_only = 1").execute()
|
||||
}
|
||||
_readOnlyDepth += 1
|
||||
}
|
||||
@@ -477,7 +493,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
if configuration.readonly { return }
|
||||
_readOnlyDepth -= 1
|
||||
if _readOnlyDepth == 0 {
|
||||
try internalCachedUpdateStatement(sql: "PRAGMA query_only = 0").execute()
|
||||
try internalCachedStatement(sql: "PRAGMA query_only = 0").execute()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -494,7 +510,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
|
||||
/// See <https://www.sqlite.org/c3ref/snapshot.html>
|
||||
func takeVersionSnapshot() throws -> UnsafeMutablePointer<sqlite3_snapshot> {
|
||||
var snapshot: UnsafeMutablePointer<sqlite3_snapshot>?
|
||||
let code = withUnsafeMutablePointer(to: &snapshot) {
|
||||
@@ -574,7 +590,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// // Stop tracing
|
||||
/// db.trace(options: [])
|
||||
///
|
||||
/// See https://www.sqlite.org/c3ref/trace_v2.html for more information.
|
||||
/// See <https://www.sqlite.org/c3ref/trace_v2.html> for more information.
|
||||
///
|
||||
/// - parameter options: The set of desired event kinds. Defaults to
|
||||
/// `.statement`, which notifies all executed database statements.
|
||||
@@ -682,8 +698,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// Runs a WAL checkpoint.
|
||||
///
|
||||
/// See https://www.sqlite.org/wal.html and
|
||||
/// https://www.sqlite.org/c3ref/wal_checkpoint_v2.html for
|
||||
/// See <https://www.sqlite.org/wal.html> and
|
||||
/// <https://www.sqlite.org/c3ref/wal_checkpoint_v2.html> for
|
||||
/// more information.
|
||||
///
|
||||
/// - parameter kind: The checkpoint mode (default passive)
|
||||
@@ -713,7 +729,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// MARK: - Interrupt
|
||||
|
||||
// See https://www.sqlite.org/c3ref/interrupt.html
|
||||
// See <https://www.sqlite.org/c3ref/interrupt.html>
|
||||
func interrupt() {
|
||||
sqlite3_interrupt(sqliteConnection)
|
||||
}
|
||||
@@ -734,7 +750,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// Suspends the database. A suspended database prevents database locks in
|
||||
/// order to avoid the [`0xdead10cc`
|
||||
/// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html).
|
||||
/// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report).
|
||||
///
|
||||
/// This method can be called from any thread.
|
||||
///
|
||||
@@ -755,7 +771,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// Interrupt the database because this may trigger an
|
||||
// SQLITE_INTERRUPT error which may itself abort a transaction and
|
||||
// release a lock. See https://www.sqlite.org/c3ref/interrupt.html
|
||||
// release a lock. See <https://www.sqlite.org/c3ref/interrupt.html>
|
||||
interrupt()
|
||||
|
||||
// Now what about the eventual remaining lock? We'll issue a
|
||||
@@ -766,7 +782,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// Resumes the database. A resumed database stops preventing database locks
|
||||
/// in order to avoid the [`0xdead10cc`
|
||||
/// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html).
|
||||
/// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report).
|
||||
///
|
||||
/// This method can be called from any thread.
|
||||
///
|
||||
@@ -798,7 +814,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// Throws SQLITE_ABORT for suspended databases, if statement would lock
|
||||
/// the database, in order to avoid the [`0xdead10cc`
|
||||
/// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html).
|
||||
/// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report).
|
||||
func checkForSuspensionViolation(from statement: Statement) throws {
|
||||
try $isSuspended.read { isSuspended in
|
||||
guard isSuspended else {
|
||||
@@ -816,9 +832,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
return
|
||||
}
|
||||
|
||||
if let updateStatement = statement as? UpdateStatement,
|
||||
updateStatement.releasesDatabaseLock
|
||||
{
|
||||
if statement.releasesDatabaseLock {
|
||||
// Accept statements that release locks:
|
||||
// - COMMIT
|
||||
// - ROLLBACK
|
||||
@@ -866,7 +880,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
arguments: @autoclosure () -> StatementArguments? = nil)
|
||||
throws
|
||||
{
|
||||
if isInsideTransactionBlock && !isInsideTransaction {
|
||||
if isInsideTransactionBlock && sqlite3_get_autocommit(sqliteConnection) != 0 {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_ABORT,
|
||||
message: "Transaction was aborted",
|
||||
@@ -892,7 +906,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
|
||||
/// defaults to .deferred. See <https://www.sqlite.org/lang_transaction.html>
|
||||
/// for more information.
|
||||
/// - block: A block that executes SQL statements and return either
|
||||
/// .commit or .rollback.
|
||||
@@ -993,11 +1007,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
return
|
||||
}
|
||||
|
||||
// If the savepoint is top-level, we'll use ROLLBACK TRANSACTION in
|
||||
// order to perform the special error handling of rollbacks (see
|
||||
// the rollback method).
|
||||
let topLevelSavepoint = !isInsideTransaction
|
||||
|
||||
// Begin savepoint
|
||||
//
|
||||
// We use a single name for savepoints because there is no need
|
||||
@@ -1031,7 +1040,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
isInsideTransactionBlock = wasInsideTransactionBlock
|
||||
|
||||
try execute(sql: "RELEASE SAVEPOINT grdb")
|
||||
assert(!topLevelSavepoint || !isInsideTransaction)
|
||||
assert(sqlite3_get_autocommit(sqliteConnection) == 0)
|
||||
needsRollback = false
|
||||
case .rollback:
|
||||
needsRollback = true
|
||||
@@ -1043,15 +1052,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
if needsRollback {
|
||||
do {
|
||||
if topLevelSavepoint {
|
||||
try rollback()
|
||||
} else {
|
||||
// Rollback, and release the savepoint.
|
||||
// Rollback alone is not enough to clear the savepoint from
|
||||
// the SQLite savepoint stack.
|
||||
try execute(sql: "ROLLBACK TRANSACTION TO SAVEPOINT grdb")
|
||||
try execute(sql: "RELEASE SAVEPOINT grdb")
|
||||
}
|
||||
// Rollback, and release the savepoint.
|
||||
// Rollback alone is not enough to clear the savepoint from
|
||||
// the SQLite savepoint stack.
|
||||
try execute(sql: "ROLLBACK TRANSACTION TO SAVEPOINT grdb")
|
||||
try execute(sql: "RELEASE SAVEPOINT grdb")
|
||||
} catch {
|
||||
if firstError == nil {
|
||||
firstError = error
|
||||
@@ -1068,13 +1073,13 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
///
|
||||
/// - parameter kind: The transaction type (default nil). If nil, the
|
||||
/// transaction type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
|
||||
/// defaults to .deferred. See <https://www.sqlite.org/lang_transaction.html>
|
||||
/// for more information.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func beginTransaction(_ kind: TransactionKind? = nil) throws {
|
||||
let kind = kind ?? configuration.defaultTransactionKind
|
||||
try execute(sql: "BEGIN \(kind.rawValue) TRANSACTION")
|
||||
assert(isInsideTransaction)
|
||||
assert(sqlite3_get_autocommit(sqliteConnection) == 0)
|
||||
}
|
||||
|
||||
/// Rollbacks a database transaction.
|
||||
@@ -1121,13 +1126,13 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
if isInsideTransaction {
|
||||
try execute(sql: "ROLLBACK TRANSACTION")
|
||||
}
|
||||
assert(!isInsideTransaction)
|
||||
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
|
||||
}
|
||||
|
||||
/// Commits a database transaction.
|
||||
public func commit() throws {
|
||||
try execute(sql: "COMMIT TRANSACTION")
|
||||
assert(!isInsideTransaction)
|
||||
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
|
||||
}
|
||||
|
||||
// MARK: - Memory Management
|
||||
@@ -1246,7 +1251,7 @@ extension Database {
|
||||
}
|
||||
try usePassphrase(data)
|
||||
}
|
||||
|
||||
|
||||
/// Sets the passphrase used to crypt and decrypt an SQLCipher database.
|
||||
///
|
||||
/// Call this method from `Configuration.prepareDatabase`,
|
||||
@@ -1275,7 +1280,7 @@ extension Database {
|
||||
}
|
||||
try changePassphrase(data)
|
||||
}
|
||||
|
||||
|
||||
/// Changes the passphrase used by an SQLCipher encrypted database.
|
||||
public func changePassphrase(_ passphrase: Data) throws {
|
||||
// FIXME: sqlite3_rekey is discouraged.
|
||||
@@ -1287,7 +1292,6 @@ extension Database {
|
||||
// > options and using sqlcipher_export() to migrate the contents and
|
||||
// > 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 code = passphrase.withUnsafeBytes {
|
||||
sqlite3_rekey(sqliteConnection, $0.baseAddress, Int32($0.count))
|
||||
}
|
||||
@@ -1302,7 +1306,7 @@ extension Database {
|
||||
|
||||
// MARK: - Database-Related Types
|
||||
|
||||
/// See BusyMode and https://www.sqlite.org/c3ref/busy_handler.html
|
||||
/// See BusyMode and <https://www.sqlite.org/c3ref/busy_handler.html>
|
||||
public typealias BusyCallback = (_ numberOfTries: Int) -> Bool
|
||||
|
||||
/// When there are several connections to a database, a connection may try
|
||||
@@ -1327,10 +1331,10 @@ extension Database {
|
||||
///
|
||||
/// Relevant SQLite documentation:
|
||||
///
|
||||
/// - https://www.sqlite.org/c3ref/busy_timeout.html
|
||||
/// - https://www.sqlite.org/c3ref/busy_handler.html
|
||||
/// - https://www.sqlite.org/lang_transaction.html
|
||||
/// - https://www.sqlite.org/wal.html
|
||||
/// - <https://www.sqlite.org/c3ref/busy_timeout.html>
|
||||
/// - <https://www.sqlite.org/c3ref/busy_handler.html>
|
||||
/// - <https://www.sqlite.org/lang_transaction.html>
|
||||
/// - <https://www.sqlite.org/wal.html>
|
||||
public enum BusyMode {
|
||||
/// The SQLITE_BUSY error is immediately returned to the connection that
|
||||
/// tries to access the locked database.
|
||||
@@ -1341,7 +1345,7 @@ extension Database {
|
||||
case timeout(TimeInterval)
|
||||
|
||||
/// A custom callback that is called when a database is locked.
|
||||
/// See https://www.sqlite.org/c3ref/busy_handler.html
|
||||
/// See <https://www.sqlite.org/c3ref/busy_handler.html>
|
||||
case callback(BusyCallback)
|
||||
}
|
||||
|
||||
@@ -1362,7 +1366,7 @@ extension Database {
|
||||
|
||||
/// A built-in SQLite collation.
|
||||
///
|
||||
/// See https://www.sqlite.org/datatype3.html#collation
|
||||
/// See <https://www.sqlite.org/datatype3.html#collation>
|
||||
public struct CollationName: RawRepresentable, Hashable {
|
||||
/// :nodoc:
|
||||
public let rawValue: String
|
||||
@@ -1389,7 +1393,7 @@ extension Database {
|
||||
/// t.column("title", .text)
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/datatype3.html
|
||||
/// See <https://www.sqlite.org/datatype3.html>
|
||||
public struct ColumnType: RawRepresentable, Hashable {
|
||||
/// :nodoc:
|
||||
public let rawValue: String
|
||||
@@ -1426,7 +1430,7 @@ extension Database {
|
||||
|
||||
/// An SQLite conflict resolution.
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_conflict.html.
|
||||
/// See <https://www.sqlite.org/lang_conflict.html>
|
||||
public enum ConflictResolution: String {
|
||||
/// The `ROLLBACK` conflict resolution
|
||||
case rollback = "ROLLBACK"
|
||||
@@ -1446,7 +1450,7 @@ extension Database {
|
||||
|
||||
/// A foreign key action.
|
||||
///
|
||||
/// See https://www.sqlite.org/foreignkeys.html
|
||||
/// See <https://www.sqlite.org/foreignkeys.html>
|
||||
public enum ForeignKeyAction: String {
|
||||
/// The `CASCADE` foreign key action
|
||||
case cascade = "CASCADE"
|
||||
@@ -1468,13 +1472,13 @@ extension Database {
|
||||
public struct TracingOptions: OptionSet {
|
||||
/// The raw "Trace Event Code".
|
||||
///
|
||||
/// See https://www.sqlite.org/c3ref/c_trace.html
|
||||
/// See <https://www.sqlite.org/c3ref/c_trace.html>
|
||||
public let rawValue: CInt
|
||||
|
||||
/// Creates a `TracingOptions` from a raw "Trace Event Code".
|
||||
///
|
||||
/// See:
|
||||
/// - https://www.sqlite.org/c3ref/c_trace.html
|
||||
/// - <https://www.sqlite.org/c3ref/c_trace.html>
|
||||
/// - `Database.trace(options:_:)`
|
||||
public init(rawValue: CInt) {
|
||||
self.rawValue = rawValue
|
||||
@@ -1575,15 +1579,8 @@ extension Database {
|
||||
/// An event reported by `TracingOptions.statement`.
|
||||
case statement(Statement)
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
|
||||
/// An event reported by `TracingOptions.profile`.
|
||||
case profile(statement: Statement, duration: TimeInterval)
|
||||
#elseif os(Linux)
|
||||
#else
|
||||
/// An event reported by `TracingOptions.profile`.
|
||||
@available(OSX 10.12, tvOS 10.0, watchOS 3.0, *)
|
||||
case profile(statement: Statement, duration: TimeInterval)
|
||||
#endif
|
||||
|
||||
public var description: String {
|
||||
switch self {
|
||||
@@ -1597,6 +1594,7 @@ extension Database {
|
||||
}
|
||||
|
||||
/// Confirms or cancels the changes performed by a transaction or savepoint.
|
||||
@frozen
|
||||
public enum TransactionCompletion {
|
||||
/// Confirms changes
|
||||
case commit
|
||||
@@ -1605,7 +1603,7 @@ extension Database {
|
||||
case rollback
|
||||
}
|
||||
|
||||
/// An SQLite transaction kind. See https://www.sqlite.org/lang_transaction.html
|
||||
/// An SQLite transaction kind. See <https://www.sqlite.org/lang_transaction.html>
|
||||
public enum TransactionKind: String {
|
||||
/// The `DEFERRED` transaction kind
|
||||
case deferred = "DEFERRED"
|
||||
@@ -1617,7 +1615,7 @@ extension Database {
|
||||
case exclusive = "EXCLUSIVE"
|
||||
}
|
||||
|
||||
/// An SQLite threading mode. See https://www.sqlite.org/threadsafe.html.
|
||||
/// An SQLite threading mode. See <https://www.sqlite.org/threadsafe.html>.
|
||||
enum ThreadingMode {
|
||||
case `default`
|
||||
case multiThread
|
||||
|
||||
@@ -51,7 +51,7 @@ extension DatabaseCollation: Hashable {
|
||||
/// Two collations are equal if they share the same name (case insensitive)
|
||||
/// :nodoc:
|
||||
public static func == (lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool {
|
||||
// See https://www.sqlite.org/c3ref/create_collation.html
|
||||
// See <https://www.sqlite.org/c3ref/create_collation.html>
|
||||
return sqlite3_stricmp(lhs.name, rhs.name) == 0
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import Foundation
|
||||
|
||||
/// An SQLite result code.
|
||||
///
|
||||
/// See https://www.sqlite.org/rescode.html
|
||||
/// See <https://www.sqlite.org/rescode.html>
|
||||
public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
|
||||
/// The raw SQLite result code
|
||||
public let rawValue: CInt
|
||||
@@ -13,7 +13,7 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
|
||||
}
|
||||
|
||||
/// A result code limited to the least significant 8 bits of the receiver.
|
||||
/// See https://www.sqlite.org/rescode.html for more information.
|
||||
/// See <https://www.sqlite.org/rescode.html> for more information.
|
||||
///
|
||||
/// let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY
|
||||
/// resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true
|
||||
@@ -193,7 +193,7 @@ extension ResultCode {
|
||||
public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
|
||||
/// The SQLite error code (see
|
||||
/// https://www.sqlite.org/rescode.html#primary_result_code_list).
|
||||
/// <https://www.sqlite.org/rescode.html#primary_result_code_list>).
|
||||
///
|
||||
/// do {
|
||||
/// ...
|
||||
@@ -203,7 +203,7 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
///
|
||||
/// This property returns a "primary result code", that is to say the least
|
||||
/// significant 8 bits of any SQLite result code. See
|
||||
/// https://www.sqlite.org/rescode.html for more information.
|
||||
/// <https://www.sqlite.org/rescode.html> for more information.
|
||||
///
|
||||
/// See also `extendedResultCode`.
|
||||
public var resultCode: ResultCode {
|
||||
@@ -211,7 +211,7 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
}
|
||||
|
||||
/// The SQLite extended error code (see
|
||||
/// https://www.sqlite.org/rescode.html#extended_result_code_list).
|
||||
/// <https://www.sqlite.org/rescode.html#extended_result_code_list>).
|
||||
///
|
||||
/// do {
|
||||
/// ...
|
||||
@@ -248,9 +248,14 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
///
|
||||
/// This initializer is not public because library user is not supposed to
|
||||
/// be exposed to raw result codes.
|
||||
@usableFromInline
|
||||
init(resultCode: CInt, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
|
||||
self.init(resultCode: ResultCode(rawValue: resultCode), message: message, sql: sql, arguments: arguments)
|
||||
}
|
||||
|
||||
static func noSuchTable(_ tableName: String) -> Self {
|
||||
DatabaseError(message: "no such table: \(tableName)")
|
||||
}
|
||||
}
|
||||
|
||||
// Support for `catch DatabaseError.SQLITE_XXX`
|
||||
|
||||
@@ -107,8 +107,20 @@ public final class DatabaseFunction: Hashable {
|
||||
self.kind = .aggregate { Aggregate() }
|
||||
}
|
||||
|
||||
/// Returns an SQL expression that applies the function.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/#sql-functions>
|
||||
public func callAsFunction(_ arguments: SQLExpressible...) -> SQLExpression {
|
||||
switch kind {
|
||||
case .aggregate:
|
||||
return .function(name, arguments.map(\.sqlExpression))
|
||||
case .function:
|
||||
return .aggregate(name, arguments.map(\.sqlExpression))
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls sqlite3_create_function_v2
|
||||
/// See https://sqlite.org/c3ref/create_function.html
|
||||
/// See <https://sqlite.org/c3ref/create_function.html>
|
||||
func install(in db: Database) {
|
||||
// Retain the function definition
|
||||
let definition = kind.definition
|
||||
@@ -130,12 +142,12 @@ public final class DatabaseFunction: Hashable {
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage).description)
|
||||
fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage))
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls sqlite3_create_function_v2
|
||||
/// See https://sqlite.org/c3ref/create_function.html
|
||||
/// See <https://sqlite.org/c3ref/create_function.html>
|
||||
func uninstall(in db: Database) {
|
||||
let code = sqlite3_create_function_v2(
|
||||
db.sqliteConnection,
|
||||
@@ -146,13 +158,13 @@ public final class DatabaseFunction: Hashable {
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage).description)
|
||||
fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage))
|
||||
}
|
||||
}
|
||||
|
||||
/// The way to compute the result of a function.
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
private class FunctionDefinition {
|
||||
let compute: (Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?
|
||||
init(compute: @escaping (Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?) {
|
||||
@@ -162,7 +174,7 @@ public final class DatabaseFunction: Hashable {
|
||||
|
||||
/// The way to start an aggregate.
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
private class AggregateDefinition {
|
||||
let makeAggregate: () -> DatabaseAggregate
|
||||
init(makeAggregate: @escaping () -> DatabaseAggregate) {
|
||||
@@ -180,7 +192,7 @@ public final class DatabaseFunction: Hashable {
|
||||
}
|
||||
|
||||
/// A function kind: an "SQL function" or an "aggregate".
|
||||
/// See http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
/// See <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
private enum Kind {
|
||||
/// A regular function: SELECT f(1)
|
||||
case function((Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?)
|
||||
@@ -189,7 +201,7 @@ public final class DatabaseFunction: Hashable {
|
||||
case aggregate(() -> DatabaseAggregate)
|
||||
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
var definition: AnyObject {
|
||||
switch self {
|
||||
case .function(let compute):
|
||||
@@ -200,7 +212,7 @@ public final class DatabaseFunction: Hashable {
|
||||
}
|
||||
|
||||
/// Feeds the `xFunc` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
var xFunc: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
|
||||
guard case .function = self else { return nil }
|
||||
return { (sqliteContext, argc, argv) in
|
||||
@@ -218,7 +230,7 @@ public final class DatabaseFunction: Hashable {
|
||||
}
|
||||
|
||||
/// Feeds the `xStep` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
var xStep: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
|
||||
guard case .aggregate = self else { return nil }
|
||||
return { (sqliteContext, argc, argv) in
|
||||
@@ -238,7 +250,7 @@ public final class DatabaseFunction: Hashable {
|
||||
}
|
||||
|
||||
/// Feeds the `xFinal` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
var xFinal: (@convention(c) (OpaquePointer?) -> Void)? {
|
||||
guard case .aggregate = self else { return nil }
|
||||
return { (sqliteContext) in
|
||||
@@ -266,8 +278,8 @@ public final class DatabaseFunction: Hashable {
|
||||
///
|
||||
/// The result must be released when the aggregate concludes.
|
||||
///
|
||||
/// See https://sqlite.org/c3ref/context.html
|
||||
/// See https://sqlite.org/c3ref/aggregate_context.html
|
||||
/// See <https://sqlite.org/c3ref/context.html>
|
||||
/// See <https://sqlite.org/c3ref/aggregate_context.html>
|
||||
private static func unmanagedAggregateContext(_ sqliteContext: OpaquePointer?) -> Unmanaged<AggregateContext> {
|
||||
// > The first time the sqlite3_aggregate_context(C,N) routine is called
|
||||
// > for a particular aggregate function, SQLite allocates N of memory,
|
||||
|
||||
@@ -42,7 +42,6 @@ public final class DatabasePool: DatabaseWriter {
|
||||
writer = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
schemaCache: DatabaseSchemaCache(),
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "writer")
|
||||
|
||||
@@ -60,7 +59,6 @@ public final class DatabasePool: DatabaseWriter {
|
||||
return try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: readerConfiguration,
|
||||
schemaCache: DatabaseSchemaCache(),
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "reader.\(readerCount)")
|
||||
})
|
||||
@@ -717,6 +715,22 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, and returns the result.
|
||||
///
|
||||
/// Updates are guaranteed an exclusive access to the database. They wait
|
||||
/// until all pending writes and reads are completed. They postpone all
|
||||
/// other writes and reads until they are completed.
|
||||
///
|
||||
/// - important: Reads executed by concurrent *database snapshots* are not
|
||||
/// considered: they can run concurrently with the barrier updates.
|
||||
/// - parameter updates: The updates to the database.
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
readerPool.asyncBarrier {
|
||||
self.writer.sync(updates)
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// wrapped inside a transaction, and returns the result.
|
||||
///
|
||||
@@ -740,7 +754,7 @@ extension DatabasePool: DatabaseReader {
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
|
||||
/// defaults to .deferred. See <https://www.sqlite.org/lang_transaction.html>
|
||||
/// for more information.
|
||||
/// - updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates, or by the
|
||||
@@ -1058,7 +1072,7 @@ extension DatabasePool {
|
||||
/// You can create as many snapshots as you need, regardless of the maximum
|
||||
/// number of reader connections in the pool.
|
||||
///
|
||||
/// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html
|
||||
/// For more information, read about "snapshot isolation" at <https://sqlite.org/isolation.html>
|
||||
public func makeSnapshot() throws -> DatabaseSnapshot {
|
||||
// Sanity check
|
||||
if writer.onValidQueue {
|
||||
|
||||
@@ -36,7 +36,6 @@ public final class DatabaseQueue: DatabaseWriter {
|
||||
writer = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
schemaCache: DatabaseSchemaCache(),
|
||||
defaultLabel: "GRDB.DatabaseQueue")
|
||||
|
||||
setupSuspension()
|
||||
@@ -60,7 +59,6 @@ public final class DatabaseQueue: DatabaseWriter {
|
||||
writer = try! SerializedDatabase(
|
||||
path: ":memory:",
|
||||
configuration: configuration,
|
||||
schemaCache: DatabaseSchemaCache(),
|
||||
defaultLabel: "GRDB.DatabaseQueue")
|
||||
}
|
||||
|
||||
@@ -190,9 +188,16 @@ extension DatabaseQueue {
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
public func read<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
try writer.sync { db in
|
||||
try db.readOnly { try block(db) }
|
||||
// The transaction guarantees snapshot isolation against eventual
|
||||
// external connection.
|
||||
var result: T?
|
||||
try db.inTransaction(.deferred) {
|
||||
result = try db.readOnly { try block(db) }
|
||||
return .commit
|
||||
}
|
||||
return result!
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,6 +219,9 @@ extension DatabaseQueue {
|
||||
public func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void) {
|
||||
writer.async { db in
|
||||
do {
|
||||
// The transaction guarantees snapshot isolation against eventual
|
||||
// external connection.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.beginReadOnly()
|
||||
} catch {
|
||||
block(.failure(error))
|
||||
@@ -224,6 +232,7 @@ extension DatabaseQueue {
|
||||
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.endReadOnly()
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -236,6 +245,9 @@ extension DatabaseQueue {
|
||||
}
|
||||
|
||||
do {
|
||||
// The transaction guarantees snapshot isolation against eventual
|
||||
// external connection.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.beginReadOnly()
|
||||
} catch {
|
||||
block(.failure(error))
|
||||
@@ -246,6 +258,7 @@ extension DatabaseQueue {
|
||||
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.endReadOnly()
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -289,9 +302,14 @@ extension DatabaseQueue {
|
||||
try writer.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
|
||||
return try db.readOnly {
|
||||
try block(db)
|
||||
// The transaction guarantees snapshot isolation against eventual
|
||||
// external connection.
|
||||
var result: T?
|
||||
try db.inTransaction(.deferred) {
|
||||
result = try db.readOnly { try block(db) }
|
||||
return .commit
|
||||
}
|
||||
return result!
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -306,6 +324,7 @@ extension DatabaseQueue {
|
||||
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
|
||||
|
||||
do {
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.beginReadOnly()
|
||||
} catch {
|
||||
block(.failure(error))
|
||||
@@ -316,6 +335,7 @@ extension DatabaseQueue {
|
||||
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.endReadOnly()
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -341,7 +361,7 @@ extension DatabaseQueue {
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
|
||||
/// defaults to .deferred. See <https://www.sqlite.org/lang_transaction.html>
|
||||
/// for more information.
|
||||
/// - updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates, or by the
|
||||
@@ -386,6 +406,17 @@ extension DatabaseQueue {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, and returns the result.
|
||||
///
|
||||
/// Eventual concurrent database accesses are postponed until the updates
|
||||
/// are completed.
|
||||
///
|
||||
/// - parameter updates: The updates to the database.
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
writer.async(updates)
|
||||
}
|
||||
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, and returns the result.
|
||||
///
|
||||
|
||||
@@ -120,7 +120,7 @@ public protocol DatabaseReader: AnyObject {
|
||||
/// database updates are not visible inside the block:
|
||||
///
|
||||
/// try reader.asyncRead { dbResult in
|
||||
/// do (
|
||||
/// do {
|
||||
/// let db = try dbResult.get()
|
||||
/// // Those two values are guaranteed to be equal, even if the
|
||||
/// // `player` table is modified between the two requests:
|
||||
|
||||
@@ -20,9 +20,9 @@
|
||||
///
|
||||
/// - `DatabaseRegion(table:)`: the region that covers one database table.
|
||||
///
|
||||
/// - `SelectStatement.databaseRegion`:
|
||||
/// - `Statement.databaseRegion`:
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name, score FROM player")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name, score FROM player")
|
||||
/// let region = statement.databaseRegion
|
||||
///
|
||||
/// - `FetchRequest.databaseRegion(_:)`
|
||||
@@ -30,9 +30,9 @@
|
||||
/// let request = Player.filter(key: 1)
|
||||
/// let region = try request.databaseRegion(db)
|
||||
public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
private let tableRegions: [String: TableRegion]?
|
||||
private let tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
|
||||
|
||||
private init(tableRegions: [String: TableRegion]?) {
|
||||
private init(tableRegions: [CaseInsensitiveIdentifier: TableRegion]?) {
|
||||
self.tableRegions = tableRegions
|
||||
}
|
||||
|
||||
@@ -64,16 +64,20 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
///
|
||||
/// - parameter table: A table name.
|
||||
public init(table: String) {
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: nil)])
|
||||
}
|
||||
|
||||
/// Full columns in a table: (some columns in a table) × (all rows)
|
||||
init(table: String, columns: Set<String>) {
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
let columns = Set(columns.map(CaseInsensitiveIdentifier.init))
|
||||
self.init(tableRegions: [table: TableRegion(columns: columns, rowIds: nil)])
|
||||
}
|
||||
|
||||
/// Full rows in a table: (all columns in a table) × (some rows)
|
||||
init(table: String, rowIds: Set<Int64>) {
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: rowIds)])
|
||||
}
|
||||
|
||||
@@ -86,7 +90,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
guard let tableRegions = tableRegions else { return other }
|
||||
guard let otherTableRegions = other.tableRegions else { return self }
|
||||
|
||||
var tableRegionsIntersection: [String: TableRegion] = [:]
|
||||
var tableRegionsIntersection: [CaseInsensitiveIdentifier: TableRegion] = [:]
|
||||
for (table, tableRegion) in tableRegions {
|
||||
guard let otherTableRegion = otherTableRegions
|
||||
.first(where: { (otherTable, _) in otherTable == table })?
|
||||
@@ -105,6 +109,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
return DatabaseRegion(table: table, rowIds: rowIds)
|
||||
}
|
||||
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
guard let tableRegion = tableRegions[table] else {
|
||||
return self
|
||||
}
|
||||
@@ -123,7 +128,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
guard let tableRegions = tableRegions else { return .fullDatabase }
|
||||
guard let otherTableRegions = other.tableRegions else { return .fullDatabase }
|
||||
|
||||
var tableRegionsUnion: [String: TableRegion] = [:]
|
||||
var tableRegionsUnion: [CaseInsensitiveIdentifier: TableRegion] = [:]
|
||||
let tableNames = Set(tableRegions.keys).union(Set(otherTableRegions.keys))
|
||||
for table in tableNames {
|
||||
let tableRegion = tableRegions[table]
|
||||
@@ -148,24 +153,39 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
self = union(other)
|
||||
}
|
||||
|
||||
/// Returns a region suitable for database observation by removing views.
|
||||
/// Returns a region suitable for database observation
|
||||
func observableRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
// SQLite does not expose schema changes to the
|
||||
// TransactionObserver protocol. By removing internal SQLite tables from
|
||||
// the observed region, we optimize database observation.
|
||||
//
|
||||
// And by canonicalizing table names, we remove views, and help the
|
||||
// `isModified` methods.
|
||||
try ignoringInternalSQLiteTables().canonicalTables(db)
|
||||
}
|
||||
|
||||
/// Returns a region only made of actual tables with their canonical names.
|
||||
/// Canonical names help the `isModified` methods.
|
||||
///
|
||||
/// We can do it because modifications only happen in actual tables. And we
|
||||
/// want to do it because we have a fast path for regions that span a
|
||||
/// single table.
|
||||
func ignoringViews(_ db: Database) throws -> DatabaseRegion {
|
||||
/// This method removes views (assuming no table exists with the same name
|
||||
/// as a view).
|
||||
private func canonicalTables(_ db: Database) throws -> DatabaseRegion {
|
||||
guard let tableRegions = tableRegions else { return .fullDatabase }
|
||||
let viewNames = try db.schema().names(ofType: .view)
|
||||
guard viewNames.isEmpty == false else { return self }
|
||||
let filteredRegions = tableRegions.filter { viewNames.contains($0.key) == false }
|
||||
return DatabaseRegion(tableRegions: filteredRegions)
|
||||
var region = DatabaseRegion()
|
||||
for (table, tableRegion) in tableRegions {
|
||||
if let canonicalTableName = try db.canonicalTableName(table.rawValue) {
|
||||
let table = CaseInsensitiveIdentifier(rawValue: canonicalTableName)
|
||||
region.formUnion(DatabaseRegion(tableRegions: [table: tableRegion]))
|
||||
}
|
||||
}
|
||||
return region
|
||||
}
|
||||
|
||||
/// Returns a region which doesn't contain any SQLite internal table.
|
||||
func ignoringInternalSQLiteTables() -> DatabaseRegion {
|
||||
private func ignoringInternalSQLiteTables() -> DatabaseRegion {
|
||||
guard let tableRegions = tableRegions else { return .fullDatabase }
|
||||
let filteredRegions = tableRegions.filter {
|
||||
!Database.isSQLiteInternalTable($0.key)
|
||||
!Database.isSQLiteInternalTable($0.key.rawValue)
|
||||
}
|
||||
return DatabaseRegion(tableRegions: filteredRegions)
|
||||
}
|
||||
@@ -192,7 +212,7 @@ extension DatabaseRegion {
|
||||
return true
|
||||
}
|
||||
|
||||
guard let tableRegion = tableRegions[event.tableName] else {
|
||||
guard let tableRegion = tableRegions[CaseInsensitiveIdentifier(rawValue: event.tableName)] else {
|
||||
// FTS4 (and maybe other virtual tables) perform unadvertised
|
||||
// changes. For example, an "INSERT INTO document ..." statement
|
||||
// advertises an insertion in the `document` table, but the
|
||||
@@ -240,11 +260,11 @@ extension DatabaseRegion {
|
||||
return "empty"
|
||||
}
|
||||
return tableRegions
|
||||
.sorted(by: { (l, r) in l.key < r.key })
|
||||
.sorted(by: { (l, r) in l.key.rawValue < r.key.rawValue })
|
||||
.map({ (table, tableRegion) in
|
||||
var desc = table
|
||||
var desc = table.rawValue
|
||||
if let columns = tableRegion.columns {
|
||||
desc += "(" + columns.sorted().joined(separator: ",") + ")"
|
||||
desc += "(" + columns.map(\.rawValue).sorted().joined(separator: ",") + ")"
|
||||
} else {
|
||||
desc += "(*)"
|
||||
}
|
||||
@@ -258,7 +278,7 @@ extension DatabaseRegion {
|
||||
}
|
||||
|
||||
private struct TableRegion: Equatable {
|
||||
var columns: Set<String>? // nil means "all columns"
|
||||
var columns: Set<CaseInsensitiveIdentifier>? // nil means "all columns"
|
||||
var rowIds: Set<Int64>? // nil means "all rowids"
|
||||
|
||||
var isEmpty: Bool {
|
||||
@@ -268,7 +288,7 @@ private struct TableRegion: Equatable {
|
||||
}
|
||||
|
||||
func intersection(_ other: TableRegion) -> TableRegion {
|
||||
let columnsIntersection: Set<String>?
|
||||
let columnsIntersection: Set<CaseInsensitiveIdentifier>?
|
||||
switch (self.columns, other.columns) {
|
||||
case let (nil, columns), let (columns, nil):
|
||||
columnsIntersection = columns
|
||||
@@ -288,7 +308,7 @@ private struct TableRegion: Equatable {
|
||||
}
|
||||
|
||||
func union(_ other: TableRegion) -> TableRegion {
|
||||
let columnsUnion: Set<String>?
|
||||
let columnsUnion: Set<CaseInsensitiveIdentifier>?
|
||||
switch (self.columns, other.columns) {
|
||||
case (nil, _), (_, nil):
|
||||
columnsUnion = nil
|
||||
|
||||
@@ -91,7 +91,7 @@ extension DatabaseRegionObservation {
|
||||
// Use unsafeReentrantWrite so that observation can start from any
|
||||
// dispatch queue.
|
||||
return try dbWriter.unsafeReentrantWrite { db -> TransactionObserver in
|
||||
let region = try observedRegion(db).ignoringViews(db)
|
||||
let region = try observedRegion(db).observableRegion(db)
|
||||
let observer = DatabaseRegionObserver(region: region, onChange: onChange)
|
||||
db.add(transactionObserver: observer, extent: extent)
|
||||
return observer
|
||||
|
||||
@@ -1,10 +1,30 @@
|
||||
/// A thread-unsafe database schema cache
|
||||
struct DatabaseSchemaCache {
|
||||
/// A cached value
|
||||
///
|
||||
/// We cache both hits and misses, because we often query both the temp
|
||||
/// schema and the main schema: not remembering misses would have us
|
||||
/// perform too many database queries.
|
||||
enum Presence<T> {
|
||||
/// Value does not exist in the schema.
|
||||
case missing
|
||||
|
||||
/// Value exists in the schema.
|
||||
case value(T)
|
||||
|
||||
var value: T? {
|
||||
switch self {
|
||||
case .missing: return nil
|
||||
case let .value(value): return value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var schemaInfo: SchemaInfo?
|
||||
private var primaryKeys: [String: PrimaryKeyInfo] = [:]
|
||||
private var columns: [String: [ColumnInfo]] = [:]
|
||||
private var indexes: [String: [IndexInfo]] = [:]
|
||||
private var foreignKeys: [String: [ForeignKeyInfo]] = [:]
|
||||
private var primaryKeys: [String: Presence<PrimaryKeyInfo>] = [:]
|
||||
private var columns: [String: Presence<[ColumnInfo]>] = [:]
|
||||
private var indexes: [String: Presence<[IndexInfo]>] = [:]
|
||||
private var foreignKeys: [String: Presence<[ForeignKeyInfo]>] = [:]
|
||||
|
||||
mutating func clear() {
|
||||
primaryKeys = [:]
|
||||
@@ -14,35 +34,35 @@ struct DatabaseSchemaCache {
|
||||
schemaInfo = nil
|
||||
}
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
|
||||
func primaryKey(_ table: String) -> Presence<PrimaryKeyInfo>? {
|
||||
primaryKeys[table]
|
||||
}
|
||||
|
||||
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
|
||||
mutating func set(primaryKey: Presence<PrimaryKeyInfo>, forTable table: String) {
|
||||
primaryKeys[table] = primaryKey
|
||||
}
|
||||
|
||||
func columns(in table: String) -> [ColumnInfo]? {
|
||||
func columns(in table: String) -> Presence<[ColumnInfo]>? {
|
||||
columns[table]
|
||||
}
|
||||
|
||||
mutating func set(columns: [ColumnInfo], forTable table: String) {
|
||||
mutating func set(columns: Presence<[ColumnInfo]>, forTable table: String) {
|
||||
self.columns[table] = columns
|
||||
}
|
||||
|
||||
func indexes(on table: String) -> [IndexInfo]? {
|
||||
func indexes(on table: String) -> Presence<[IndexInfo]>? {
|
||||
indexes[table]
|
||||
}
|
||||
|
||||
mutating func set(indexes: [IndexInfo], forTable table: String) {
|
||||
mutating func set(indexes: Presence<[IndexInfo]>, forTable table: String) {
|
||||
self.indexes[table] = indexes
|
||||
}
|
||||
|
||||
func foreignKeys(on table: String) -> [ForeignKeyInfo]? {
|
||||
func foreignKeys(on table: String) -> Presence<[ForeignKeyInfo]>? {
|
||||
foreignKeys[table]
|
||||
}
|
||||
|
||||
mutating func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
|
||||
mutating func set(foreignKeys: Presence<[ForeignKeyInfo]>, forTable table: String) {
|
||||
self.foreignKeys[table] = foreignKeys
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import Dispatch
|
||||
///
|
||||
/// See DatabasePool.makeSnapshot()
|
||||
///
|
||||
/// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html
|
||||
/// For more information, read about "snapshot isolation" at <https://sqlite.org/isolation.html>
|
||||
public class DatabaseSnapshot: DatabaseReader {
|
||||
private var serializedDatabase: SerializedDatabase
|
||||
|
||||
@@ -26,7 +26,6 @@ public class DatabaseSnapshot: DatabaseReader {
|
||||
serializedDatabase = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
schemaCache: DatabaseSchemaCache(),
|
||||
defaultLabel: defaultLabel,
|
||||
purpose: purpose)
|
||||
|
||||
@@ -41,7 +40,7 @@ public class DatabaseSnapshot: DatabaseReader {
|
||||
try db.beginTransaction(.deferred)
|
||||
|
||||
// Acquire snapshot isolation
|
||||
try db.internalCachedSelectStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next()
|
||||
try db.internalCachedStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next()
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT
|
||||
// We must expect an error: https://www.sqlite.org/c3ref/snapshot_get.html
|
||||
|
||||
@@ -4,8 +4,8 @@ import Foundation
|
||||
|
||||
/// DatabaseValue is the intermediate type between SQLite and your values.
|
||||
///
|
||||
/// See https://www.sqlite.org/datatype3.html
|
||||
public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLExpression {
|
||||
/// See <https://www.sqlite.org/datatype3.html>
|
||||
public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLSpecificExpressible {
|
||||
/// The SQLite storage
|
||||
public let storage: Storage
|
||||
|
||||
@@ -13,6 +13,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
|
||||
public static let null = DatabaseValue(storage: .null)
|
||||
|
||||
/// An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB).
|
||||
@frozen
|
||||
public enum Storage: Equatable {
|
||||
/// The NULL storage class.
|
||||
case null
|
||||
@@ -137,69 +138,23 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
|
||||
fatalError("Unexpected SQLite column type: \(type)")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: SQLExpression
|
||||
|
||||
/// :nodoc:
|
||||
public func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
if isNull {
|
||||
// fast path for NULL
|
||||
return "NULL"
|
||||
} else if context.append(arguments: [self]) {
|
||||
// Use statement arguments
|
||||
return "?"
|
||||
} else {
|
||||
// Quoting needed: just use SQLite, which knows better.
|
||||
return try String.fetchOne(context.db, sql: "SELECT QUOTE(?)", arguments: [self])!
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set<Int64>? {
|
||||
if isNull || self == false.databaseValue {
|
||||
// Those requests select no row:
|
||||
// - WHERE NULL
|
||||
// - WHERE 0
|
||||
return []
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Specific boolean checks for null, true, and false
|
||||
/// :nodoc:
|
||||
public func _is(_ test: _SQLBooleanTest) -> SQLExpression {
|
||||
}
|
||||
|
||||
extension DatabaseValue: StatementBinding {
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
switch storage {
|
||||
case .null:
|
||||
return DatabaseValue.null
|
||||
|
||||
case .int64(let int64) where int64 == 0 || int64 == 1:
|
||||
switch test {
|
||||
case .true:
|
||||
return (int64 == 1).sqlExpression
|
||||
case .false, .falsey:
|
||||
return (int64 == 0).sqlExpression
|
||||
}
|
||||
|
||||
default:
|
||||
switch test {
|
||||
case .true:
|
||||
return SQLExpressionEqual(.equal, self, true.sqlExpression)
|
||||
case .false:
|
||||
return SQLExpressionEqual(.equal, self, false.sqlExpression)
|
||||
case .falsey:
|
||||
return SQLExpressionNot(self)
|
||||
}
|
||||
return sqlite3_bind_null(sqliteStatement, index)
|
||||
case .int64(let int64):
|
||||
return int64.bind(to: sqliteStatement, at: index)
|
||||
case .double(let double):
|
||||
return double.bind(to: sqliteStatement, at: index)
|
||||
case .string(let string):
|
||||
return string.bind(to: sqliteStatement, at: index)
|
||||
case .blob(let data):
|
||||
return data.bind(to: sqliteStatement, at: index)
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public var _isConstantInRequest: Bool { true }
|
||||
|
||||
/// :nodoc:
|
||||
public var _isTrue: Bool { self == true.databaseValue }
|
||||
|
||||
/// :nodoc:
|
||||
public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { self }
|
||||
}
|
||||
|
||||
// MARK: - Hashable & Equatable
|
||||
@@ -276,9 +231,8 @@ extension DatabaseValue {
|
||||
|
||||
// SQLExpressible
|
||||
extension DatabaseValue {
|
||||
/// :nodoc:
|
||||
public var sqlExpression: SQLExpression {
|
||||
self
|
||||
.databaseValue(self)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,315 +0,0 @@
|
||||
// MARK: - Conversion Context and Errors
|
||||
|
||||
/// A type that helps the user understanding value conversion errors
|
||||
struct ValueConversionContext: Refinable {
|
||||
private enum Column {
|
||||
case columnIndex(Int)
|
||||
case columnName(String)
|
||||
}
|
||||
|
||||
var row: Row?
|
||||
var sql: String?
|
||||
var arguments: StatementArguments?
|
||||
private var column: Column?
|
||||
|
||||
func atColumn(_ columnIndex: Int) -> Self {
|
||||
with(\.column, .columnIndex(columnIndex))
|
||||
}
|
||||
|
||||
func atColumn(_ columnName: String) -> Self {
|
||||
with(\.column, .columnName(columnName))
|
||||
}
|
||||
|
||||
var columnIndex: Int? {
|
||||
guard let column = column else { return nil }
|
||||
switch column {
|
||||
case .columnIndex(let index):
|
||||
return index
|
||||
case .columnName(let name):
|
||||
return row?.index(forColumn: name)
|
||||
}
|
||||
}
|
||||
|
||||
var columnName: String? {
|
||||
guard let column = column else { return nil }
|
||||
switch column {
|
||||
case .columnIndex(let index):
|
||||
guard let row = row else { return nil }
|
||||
return Array(row.columnNames)[index]
|
||||
case .columnName(let name):
|
||||
return name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension ValueConversionContext {
|
||||
init(_ statement: SelectStatement) {
|
||||
self.init(
|
||||
row: Row(statement: statement).copy(),
|
||||
sql: statement.sql,
|
||||
arguments: statement.arguments,
|
||||
column: nil)
|
||||
}
|
||||
|
||||
init(_ row: Row) {
|
||||
if let statement = row.statement {
|
||||
self.init(
|
||||
row: row.copy(),
|
||||
sql: statement.sql,
|
||||
arguments: statement.arguments,
|
||||
column: nil)
|
||||
} else if let sqliteStatement = row.sqliteStatement {
|
||||
let sql = String(cString: sqlite3_sql(sqliteStatement)).trimmingCharacters(in: .sqlStatementSeparators)
|
||||
self.init(
|
||||
row: row.copy(),
|
||||
sql: sql,
|
||||
arguments: nil,
|
||||
column: nil)
|
||||
} else {
|
||||
self.init(
|
||||
row: row.copy(),
|
||||
sql: nil,
|
||||
arguments: nil,
|
||||
column: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The canonical conversion error message
|
||||
///
|
||||
/// - parameter dbValue: nil means "missing column"
|
||||
func conversionErrorMessage<T>(
|
||||
to: T.Type,
|
||||
from dbValue: DatabaseValue?,
|
||||
conversionContext: ValueConversionContext?)
|
||||
-> String
|
||||
{
|
||||
var message: String
|
||||
var extras: [String] = []
|
||||
|
||||
if let dbValue = dbValue {
|
||||
message = "could not convert database value \(dbValue) to \(T.self)"
|
||||
if let columnName = conversionContext?.columnName {
|
||||
extras.append("column: `\(columnName)`")
|
||||
}
|
||||
if let columnIndex = conversionContext?.columnIndex {
|
||||
extras.append("column index: \(columnIndex)")
|
||||
}
|
||||
} else {
|
||||
message = "could not read \(T.self) from missing column"
|
||||
if let columnName = conversionContext?.columnName {
|
||||
message += " `\(columnName)`"
|
||||
}
|
||||
}
|
||||
|
||||
if let row = conversionContext?.row {
|
||||
extras.append("row: \(row)")
|
||||
}
|
||||
|
||||
if let sql = conversionContext?.sql {
|
||||
extras.append("sql: `\(sql)`")
|
||||
if let arguments = conversionContext?.arguments, arguments.isEmpty == false {
|
||||
extras.append("arguments: \(arguments)")
|
||||
}
|
||||
}
|
||||
|
||||
if extras.isEmpty == false {
|
||||
message += " (" + extras.joined(separator: ", ") + ")"
|
||||
}
|
||||
return message
|
||||
}
|
||||
|
||||
/// The canonical conversion fatal error
|
||||
///
|
||||
/// - parameter dbValue: nil means "missing column", for consistency with (row["missing"] as DatabaseValue? == nil)
|
||||
func fatalConversionError<T>(
|
||||
to: T.Type,
|
||||
from dbValue: DatabaseValue?,
|
||||
conversionContext: ValueConversionContext?,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
-> Never
|
||||
{
|
||||
fatalError(
|
||||
conversionErrorMessage(
|
||||
to: T.self,
|
||||
from: dbValue,
|
||||
conversionContext: conversionContext),
|
||||
file: file,
|
||||
line: line)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func fatalConversionError<T>(
|
||||
to: T.Type,
|
||||
from dbValue: DatabaseValue?,
|
||||
in row: Row,
|
||||
atColumn columnName: String,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
-> Never
|
||||
{
|
||||
fatalConversionError(
|
||||
to: T.self,
|
||||
from: dbValue,
|
||||
conversionContext: ValueConversionContext(row).atColumn(columnName))
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func fatalConversionError<T>(
|
||||
to: T.Type,
|
||||
sqliteStatement: SQLiteStatement,
|
||||
index: Int32,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
-> Never
|
||||
{
|
||||
let row = Row(sqliteStatement: sqliteStatement)
|
||||
fatalConversionError(
|
||||
to: T.self,
|
||||
from: DatabaseValue(sqliteStatement: sqliteStatement, index: index),
|
||||
conversionContext: ValueConversionContext(row).atColumn(Int(index)))
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func fatalConversionError<T>(
|
||||
to: T.Type,
|
||||
from dbValue: DatabaseValue?,
|
||||
sqliteStatement: SQLiteStatement,
|
||||
index: Int32,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
-> Never
|
||||
{
|
||||
let row = Row(sqliteStatement: sqliteStatement)
|
||||
fatalConversionError(
|
||||
to: T.self,
|
||||
from: dbValue,
|
||||
conversionContext: ValueConversionContext(row).atColumn(Int(index)))
|
||||
}
|
||||
|
||||
// MARK: - DatabaseValueConvertible
|
||||
|
||||
/// Lossless conversions from database values and rows
|
||||
extension DatabaseValueConvertible {
|
||||
@usableFromInline
|
||||
static func decode(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self {
|
||||
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
|
||||
if let value = fromDatabaseValue(dbValue) {
|
||||
return value
|
||||
} else {
|
||||
fatalConversionError(to: Self.self, from: dbValue, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
}
|
||||
|
||||
static func decode(
|
||||
from dbValue: DatabaseValue,
|
||||
conversionContext: @autoclosure () -> ValueConversionContext?)
|
||||
-> Self
|
||||
{
|
||||
if let value = fromDatabaseValue(dbValue) {
|
||||
return value
|
||||
} else {
|
||||
fatalConversionError(to: Self.self, from: dbValue, conversionContext: conversionContext())
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
static func decode(from row: Row, atUncheckedIndex index: Int) -> Self {
|
||||
decode(
|
||||
from: row.impl.databaseValue(atUncheckedIndex: index),
|
||||
conversionContext: ValueConversionContext(row).atColumn(index))
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
static func decodeIfPresent(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self? {
|
||||
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
|
||||
if let value = fromDatabaseValue(dbValue) {
|
||||
return value
|
||||
} else if dbValue.isNull {
|
||||
return nil
|
||||
} else {
|
||||
fatalConversionError(to: Self.self, from: dbValue, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
}
|
||||
|
||||
static func decodeIfPresent(
|
||||
from dbValue: DatabaseValue,
|
||||
conversionContext: @autoclosure () -> ValueConversionContext?)
|
||||
-> Self?
|
||||
{
|
||||
// Use fromDatabaseValue before checking for null: this allows DatabaseValue to convert NULL to .null.
|
||||
if let value = fromDatabaseValue(dbValue) {
|
||||
return value
|
||||
} else if dbValue.isNull {
|
||||
return nil
|
||||
} else {
|
||||
fatalConversionError(to: Self.self, from: dbValue, conversionContext: conversionContext())
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
static func decodeIfPresent(from row: Row, atUncheckedIndex index: Int) -> Self? {
|
||||
decodeIfPresent(
|
||||
from: row.impl.databaseValue(atUncheckedIndex: index),
|
||||
conversionContext: ValueConversionContext(row).atColumn(index))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - DatabaseValueConvertible & StatementColumnConvertible
|
||||
|
||||
/// Lossless conversions from database values and rows
|
||||
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
@inlinable
|
||||
static func fastDecode(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self {
|
||||
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
|
||||
fatalConversionError(to: Self.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
return self.init(sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func fastDecode(from row: Row, atUncheckedIndex index: Int) -> Self {
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return fastDecode(from: sqliteStatement, atUncheckedIndex: Int32(index))
|
||||
}
|
||||
return row.fastDecode(Self.self, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func fastDecodeIfPresent(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self? {
|
||||
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
|
||||
return nil
|
||||
}
|
||||
return self.init(sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func fastDecodeIfPresent(from row: Row, atUncheckedIndex index: Int) -> Self? {
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return fastDecodeIfPresent(from: sqliteStatement, atUncheckedIndex: Int32(index))
|
||||
}
|
||||
return row.fastDecodeIfPresent(Self.self, atUncheckedIndex: index)
|
||||
}
|
||||
}
|
||||
|
||||
// Support for @inlinable decoding
|
||||
extension Row {
|
||||
@usableFromInline
|
||||
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int)
|
||||
-> Value
|
||||
{
|
||||
impl.fastDecode(type, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int)
|
||||
-> Value?
|
||||
{
|
||||
impl.fastDecodeIfPresent(type, atUncheckedIndex: index)
|
||||
}
|
||||
}
|
||||
@@ -8,27 +8,115 @@
|
||||
/// try String.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String]
|
||||
/// try String.fetchOne(db, sql: "SELECT name FROM ...", arguments:...) // String?
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// try String.fetchCursor(statement, arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(statement, arguments:...) // [String]
|
||||
/// try String.fetchOne(statement, arguments:...) // String?
|
||||
///
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
public protocol DatabaseValueConvertible: SQLExpressible {
|
||||
public protocol DatabaseValueConvertible: SQLExpressible, StatementBinding {
|
||||
/// Returns a value that can be stored in the database.
|
||||
var databaseValue: DatabaseValue { get }
|
||||
|
||||
/// Returns a value initialized from *dbValue*, if possible.
|
||||
/// Returns a value initialized from `dbValue`, if possible.
|
||||
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self?
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible {
|
||||
/// :nodoc:
|
||||
public var sqlExpression: SQLExpression {
|
||||
databaseValue
|
||||
.databaseValue(databaseValue)
|
||||
}
|
||||
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
databaseValue.bind(to: sqliteStatement, at: index)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Conversions
|
||||
|
||||
extension DatabaseValueConvertible {
|
||||
static func decode(
|
||||
fromDatabaseValue dbValue: DatabaseValue,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Self
|
||||
{
|
||||
if let value = fromDatabaseValue(dbValue) {
|
||||
return value
|
||||
} else {
|
||||
throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue)
|
||||
}
|
||||
}
|
||||
|
||||
static func decode(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: Int32,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Self
|
||||
{
|
||||
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
|
||||
return try decode(fromDatabaseValue: dbValue, context: context())
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
static func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Self {
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return try decode(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
return try decode(
|
||||
fromDatabaseValue: row.impl.databaseValue(atUncheckedIndex: index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
|
||||
static func decodeIfPresent(
|
||||
fromDatabaseValue dbValue: DatabaseValue,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Self?
|
||||
{
|
||||
// Use fromDatabaseValue before checking for null: this allows DatabaseValue to convert NULL to .null.
|
||||
if let value = fromDatabaseValue(dbValue) {
|
||||
return value
|
||||
} else if dbValue.isNull {
|
||||
return nil
|
||||
} else {
|
||||
throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue)
|
||||
}
|
||||
}
|
||||
|
||||
static func decodeIfPresent(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: Int32,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Self?
|
||||
{
|
||||
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
|
||||
if let value = fromDatabaseValue(dbValue) {
|
||||
return value
|
||||
} else if dbValue.isNull {
|
||||
return nil
|
||||
} else {
|
||||
throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue)
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
static func decodeIfPresent(fromRow row: Row, atUncheckedIndex index: Int) throws -> Self? {
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return try decodeIfPresent(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
return try decodeIfPresent(
|
||||
fromDatabaseValue: row.impl.databaseValue(atUncheckedIndex: index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Cursors
|
||||
|
||||
/// A cursor of database values extracted from a single column.
|
||||
/// For example:
|
||||
///
|
||||
@@ -39,12 +127,16 @@ extension DatabaseValueConvertible {
|
||||
/// }
|
||||
/// }
|
||||
public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor {
|
||||
@usableFromInline let _statement: SelectStatement
|
||||
@usableFromInline let _sqliteStatement: SQLiteStatement
|
||||
@usableFromInline let _columnIndex: Int32
|
||||
@usableFromInline var _done = false
|
||||
private enum _State {
|
||||
case idle, busy, done, failed
|
||||
}
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
private let _statement: Statement
|
||||
private let _sqliteStatement: SQLiteStatement
|
||||
private let _columnIndex: Int32
|
||||
private var _state = _State.idle
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
_statement = statement
|
||||
_sqliteStatement = statement.sqliteStatement
|
||||
if let adapter = adapter {
|
||||
@@ -53,33 +145,54 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor
|
||||
} else {
|
||||
_columnIndex = 0
|
||||
}
|
||||
_statement.reset(withArguments: arguments)
|
||||
|
||||
// Assume cursor is created for iteration
|
||||
try statement.database.selectStatementWillExecute(statement)
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
if _state == .busy {
|
||||
try? _statement.database.statementDidExecute(_statement)
|
||||
}
|
||||
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? _statement.reset()
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func next() throws -> Value? {
|
||||
if _done {
|
||||
switch _state {
|
||||
case .done:
|
||||
// make sure this instance never yields a value again, even if the
|
||||
// statement is reset by another cursor.
|
||||
return nil
|
||||
case .idle:
|
||||
guard try _statement.database.statementWillExecute(_statement) == nil else {
|
||||
throw DatabaseError(
|
||||
resultCode: SQLITE_MISUSE,
|
||||
message: "Can't run statement that requires a customized authorizer from a cursor",
|
||||
sql: _statement.sql,
|
||||
arguments: _statement.arguments)
|
||||
}
|
||||
_state = .busy
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
switch sqlite3_step(_sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
_done = true
|
||||
_state = .done
|
||||
try _statement.database.statementDidExecute(_statement)
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return Value.decode(from: _sqliteStatement, atUncheckedIndex: _columnIndex)
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
return try! Value.decode(
|
||||
fromStatement: _sqliteStatement,
|
||||
atUncheckedIndex: _columnIndex,
|
||||
context: RowDecodingContext(statement: _statement, index: Int(_columnIndex)))
|
||||
case let code:
|
||||
try _statement.didFail(withResultCode: code)
|
||||
_state = .failed
|
||||
try _statement.database.statementDidFail(_statement, withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -94,12 +207,16 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor
|
||||
/// }
|
||||
/// }
|
||||
public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor {
|
||||
@usableFromInline let _statement: SelectStatement
|
||||
@usableFromInline let _sqliteStatement: SQLiteStatement
|
||||
@usableFromInline let _columnIndex: Int32
|
||||
@usableFromInline var _done = false
|
||||
private enum _State {
|
||||
case idle, busy, done, failed
|
||||
}
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
private let _statement: Statement
|
||||
private let _sqliteStatement: SQLiteStatement
|
||||
private let _columnIndex: Int32
|
||||
private var _state = _State.idle
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
_statement = statement
|
||||
_sqliteStatement = statement.sqliteStatement
|
||||
if let adapter = adapter {
|
||||
@@ -108,33 +225,54 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>:
|
||||
} else {
|
||||
_columnIndex = 0
|
||||
}
|
||||
_statement.reset(withArguments: arguments)
|
||||
|
||||
// Assume cursor is created for iteration
|
||||
try statement.database.selectStatementWillExecute(statement)
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
if _state == .busy {
|
||||
try? _statement.database.statementDidExecute(_statement)
|
||||
}
|
||||
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? _statement.reset()
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func next() throws -> Value?? {
|
||||
if _done {
|
||||
switch _state {
|
||||
case .done:
|
||||
// make sure this instance never yields a value again, even if the
|
||||
// statement is reset by another cursor.
|
||||
return nil
|
||||
case .idle:
|
||||
guard try _statement.database.statementWillExecute(_statement) == nil else {
|
||||
throw DatabaseError(
|
||||
resultCode: SQLITE_MISUSE,
|
||||
message: "Can't run statement that requires a customized authorizer from a cursor",
|
||||
sql: _statement.sql,
|
||||
arguments: _statement.arguments)
|
||||
}
|
||||
_state = .busy
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
switch sqlite3_step(_sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
_done = true
|
||||
_state = .done
|
||||
try _statement.database.statementDidExecute(_statement)
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return Value.decodeIfPresent(from: _sqliteStatement, atUncheckedIndex: _columnIndex)
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
return try! Value.decodeIfPresent(
|
||||
fromStatement: _sqliteStatement,
|
||||
atUncheckedIndex: _columnIndex,
|
||||
context: RowDecodingContext(statement: _statement, index: Int(_columnIndex)))
|
||||
case let code:
|
||||
try _statement.didFail(withResultCode: code)
|
||||
_state = .failed
|
||||
try _statement.database.statementDidFail(_statement, withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -146,7 +284,7 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>:
|
||||
/// try String.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String]
|
||||
/// try String.fetchOne(db, sql: "SELECT name FROM ...", arguments:...) // String?
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// try String.fetchCursor(statement, arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(statement, arguments:...) // [String]
|
||||
/// try String.fetchOne(statement, arguments:...) // String
|
||||
@@ -154,11 +292,11 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>:
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
extension DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching From SelectStatement
|
||||
// MARK: Fetching From Prepared Statement
|
||||
|
||||
/// Returns a cursor over values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try String.fetchCursor(statement) // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
@@ -176,7 +314,7 @@ extension DatabaseValueConvertible {
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> DatabaseValueCursor<Self>
|
||||
@@ -186,7 +324,7 @@ extension DatabaseValueConvertible {
|
||||
|
||||
/// Returns an array of values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try String.fetchAll(statement) // [String]
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -196,7 +334,7 @@ extension DatabaseValueConvertible {
|
||||
/// - returns: An array.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Self]
|
||||
@@ -209,7 +347,7 @@ extension DatabaseValueConvertible {
|
||||
/// The result is nil if the query returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let name = try String.fetchOne(statement) // String?
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -219,7 +357,7 @@ extension DatabaseValueConvertible {
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Self?
|
||||
@@ -233,7 +371,7 @@ extension DatabaseValueConvertible {
|
||||
extension DatabaseValueConvertible where Self: Hashable {
|
||||
/// Returns a set of values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try String.fetchSet(statement) // Set<String>
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -243,7 +381,7 @@ extension DatabaseValueConvertible where Self: Hashable {
|
||||
/// - returns: A set.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Self>
|
||||
@@ -282,7 +420,7 @@ extension DatabaseValueConvertible {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> DatabaseValueCursor<Self>
|
||||
{
|
||||
try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from an SQL query.
|
||||
@@ -303,7 +441,7 @@ extension DatabaseValueConvertible {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Self]
|
||||
{
|
||||
try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from an SQL query.
|
||||
@@ -327,7 +465,7 @@ extension DatabaseValueConvertible {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Self?
|
||||
{
|
||||
try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -350,7 +488,7 @@ extension DatabaseValueConvertible where Self: Hashable {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Self>
|
||||
{
|
||||
try fetchSet(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -504,18 +642,18 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable {
|
||||
/// try Optional<String>.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String?]
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// try Optional<String>.fetchCursor(statement, arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(statement, arguments:...) // [String?]
|
||||
///
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching From SelectStatement
|
||||
// MARK: Fetching From Prepared Statement
|
||||
|
||||
/// Returns a cursor over optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchCursor(statement) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
@@ -533,7 +671,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(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
@@ -543,7 +681,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
|
||||
/// Returns an array of optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchAll(statement) // [String?]
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -553,7 +691,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
/// - returns: An array of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Wrapped?]
|
||||
@@ -565,7 +703,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & Hashable {
|
||||
/// Returns a set of optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchSet(statement) // Set<String?>
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -575,7 +713,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & Hashable {
|
||||
/// - returns: A set of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Wrapped?>
|
||||
@@ -614,7 +752,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
{
|
||||
try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from an SQL query.
|
||||
@@ -635,7 +773,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Wrapped?]
|
||||
{
|
||||
try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -658,7 +796,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & Hashable {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Wrapped?>
|
||||
{
|
||||
try fetchSet(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -70,6 +70,16 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// - throws: The error thrown by the updates.
|
||||
func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T
|
||||
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, and returns the result.
|
||||
///
|
||||
/// Updates are guaranteed an exclusive access to the database. They wait
|
||||
/// until all pending writes and reads are completed. They postpone all
|
||||
/// other writes and reads until they are completed.
|
||||
///
|
||||
/// - parameter updates: The updates to the database.
|
||||
func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
|
||||
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
/// wrapped inside a transaction.
|
||||
///
|
||||
@@ -305,11 +315,50 @@ extension DatabaseWriter {
|
||||
/// Rebuilds the database file, repacking it into a minimal amount of
|
||||
/// disk space.
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_vacuum.html for more information.
|
||||
/// See <https://www.sqlite.org/lang_vacuum.html> for more information.
|
||||
public func vacuum() throws {
|
||||
try writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
|
||||
}
|
||||
|
||||
// VACUUM INTO was introduced in SQLite 3.27.0:
|
||||
// https://www.sqlite.org/releaselog/3_27_0.html
|
||||
//
|
||||
// Old versions of SQLCipher won't have it, but I don't know how to perform
|
||||
// availability checks that depend on the version of the SQLCipher CocoaPod
|
||||
// chosen by the application. So let's just have the method fail at runtime.
|
||||
//
|
||||
// This method is declared on DatabaseWriter instead of DatabaseReader,
|
||||
// so that it is not available on DatabaseSnaphot. VACUUM INTO is not
|
||||
// available inside the transaction that is kept open by DatabaseSnaphot.
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// Creates a new database file at the specified path with a minimum
|
||||
/// amount of disk space.
|
||||
///
|
||||
/// Databases encrypted with SQLCipher are copied with the same password
|
||||
/// and configuration as the original database.
|
||||
///
|
||||
/// See <https://www.sqlite.org/lang_vacuum.html#vacuuminto> for more information.
|
||||
///
|
||||
/// - Parameter filePath: file path for new database
|
||||
public func vacuum(into filePath: String) throws {
|
||||
try writeWithoutTransaction {
|
||||
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
|
||||
}
|
||||
}
|
||||
#else
|
||||
/// Creates a new database file at the specified path with a minimum
|
||||
/// amount of disk space.
|
||||
/// See <https://www.sqlite.org/lang_vacuum.html#vacuuminto> for more information.
|
||||
///
|
||||
/// - Parameter filePath: file path for new database
|
||||
@available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *)
|
||||
public func vacuum(into filePath: String) throws {
|
||||
try writeWithoutTransaction {
|
||||
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// A write-only observation only uses the serialized writer
|
||||
@@ -620,6 +669,10 @@ public final class AnyDatabaseWriter: DatabaseWriter {
|
||||
try base.barrierWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
base.asyncBarrierWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
public func asyncWrite<T>(
|
||||
_ updates: @escaping (Database) throws -> T,
|
||||
completion: @escaping (Database, Result<T, Error>) -> Void)
|
||||
|
||||
+12
-113
@@ -1,53 +1,5 @@
|
||||
// MARK: - FetchRequest
|
||||
|
||||
/// Implementation details of `FetchRequest`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol _FetchRequest {
|
||||
/// The number of columns selected by the request.
|
||||
///
|
||||
/// This method makes it possible to find the columns of a CTE in a request
|
||||
/// that includes a CTE association:
|
||||
///
|
||||
/// // WITH cte AS (SELECT 1 AS a, 2 AS b)
|
||||
/// // SELECT player.*, cte.*
|
||||
/// // FROM player
|
||||
/// // JOIN cte
|
||||
/// let cte = CommonTableExpression<Void>(named: "cte", sql: "SELECT 1 AS a, 2 AS b")
|
||||
/// let request = Player
|
||||
/// .with(cte)
|
||||
/// .including(required: Player.association(to: cte))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// // We know that "SELECT 1 AS a, 2 AS b" selects two columns,
|
||||
/// // so we can find cte columns in the row:
|
||||
/// row.scopes["cte"] // [a:1, b:2]
|
||||
///
|
||||
/// :nodoc:
|
||||
func _selectedColumnCount(_ db: Database) throws -> Int
|
||||
|
||||
/// Returns the request SQL.
|
||||
///
|
||||
/// This method makes it possible to embed a request as a subquery:
|
||||
///
|
||||
/// // SELECT *
|
||||
/// // FROM "player"
|
||||
/// // WHERE "score" = (SELECT MAX("score") FROM "player")
|
||||
/// let maxScore = Player.select(max(Column("score")))
|
||||
/// let players = try Player
|
||||
/// .filter(Column("score") == maxScore)
|
||||
/// .fetchAll(db)
|
||||
///
|
||||
/// - parameter context: An SQL generation context.
|
||||
/// - parameter singleResult: A hint that a single result row will be
|
||||
/// consumed. Implementations can optionally use it to optimize the
|
||||
/// generated SQL, for example by adding a `LIMIT 1` SQL clause.
|
||||
/// - returns: An SQL string.
|
||||
///
|
||||
/// :nodoc:
|
||||
func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String
|
||||
}
|
||||
|
||||
/// The protocol for all requests that fetch database rows, and tell how those
|
||||
/// rows should be interpreted.
|
||||
///
|
||||
@@ -58,7 +10,7 @@ public protocol _FetchRequest {
|
||||
/// try request.fetchSet(db) // Set<Player>
|
||||
/// try request.fetchOne(db) // Player?
|
||||
/// try request.fetchCount(db) // Int
|
||||
public protocol FetchRequest: _FetchRequest, DatabaseRegionConvertible, SQLExpression, SQLCollection {
|
||||
public protocol FetchRequest: SQLSubqueryable, DatabaseRegionConvertible {
|
||||
/// The type that tells how fetched database rows should be interpreted.
|
||||
associatedtype RowDecoder
|
||||
|
||||
@@ -84,45 +36,12 @@ public protocol FetchRequest: _FetchRequest, DatabaseRegionConvertible, SQLExpre
|
||||
}
|
||||
|
||||
extension FetchRequest {
|
||||
// MARK: DatabaseRegionConvertible
|
||||
|
||||
/// Returns the database region that the request feeds from.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
try makePreparedRequest(db, forSingleResult: false).statement.databaseRegion
|
||||
}
|
||||
|
||||
// MARK: SQLCollection
|
||||
|
||||
/// :nodoc:
|
||||
public var _collectionExpressions: [SQLExpression]? { nil }
|
||||
|
||||
/// :nodoc:
|
||||
public func _collectionSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
try "("
|
||||
+ _requestSQL(context, forSingleResult: false)
|
||||
+ ")"
|
||||
}
|
||||
|
||||
public func contains(_ value: SQLExpressible) -> SQLExpression {
|
||||
SQLExpressionContains(value, self)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _qualifiedCollection(with alias: TableAlias) -> SQLCollection { self }
|
||||
|
||||
// MARK: SQLExpression
|
||||
|
||||
/// :nodoc:
|
||||
public func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
try "("
|
||||
+ _requestSQL(context, forSingleResult: false)
|
||||
+ ")"
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { self }
|
||||
}
|
||||
|
||||
// MARK: - PreparedRequest
|
||||
@@ -130,7 +49,7 @@ extension FetchRequest {
|
||||
/// A PreparedRequest is a request that is ready to be executed.
|
||||
public struct PreparedRequest {
|
||||
/// A prepared statement
|
||||
public var statement: SelectStatement
|
||||
public var statement: Statement
|
||||
|
||||
/// An eventual adapter for rows fetched by the select statement
|
||||
public var adapter: RowAdapter?
|
||||
@@ -139,7 +58,7 @@ public struct PreparedRequest {
|
||||
var supplementaryFetch: ((Database, [Row]) throws -> Void)?
|
||||
|
||||
init(
|
||||
statement: SelectStatement,
|
||||
statement: Statement,
|
||||
adapter: RowAdapter?,
|
||||
supplementaryFetch: ((Database, [Row]) throws -> Void)? = nil)
|
||||
{
|
||||
@@ -174,6 +93,10 @@ public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
|
||||
self.adapter = adapter
|
||||
}
|
||||
|
||||
public var sqlSubquery: SQLSubquery {
|
||||
base.sqlSubquery
|
||||
}
|
||||
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
try base.fetchCount(db)
|
||||
}
|
||||
@@ -193,16 +116,6 @@ public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
|
||||
|
||||
return preparedRequest
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _selectedColumnCount(_ db: Database) throws -> Int {
|
||||
try base._selectedColumnCount(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
|
||||
try base._requestSQL(context, forSingleResult: singleResult)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - AnyFetchRequest
|
||||
@@ -222,9 +135,8 @@ public struct AnyFetchRequest<RowDecoder>: FetchRequest {
|
||||
AnyFetchRequest<RowDecoder>(request: request)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _selectedColumnCount(_ db: Database) throws -> Int {
|
||||
try request._selectedColumnCount(db)
|
||||
public var sqlSubquery: SQLSubquery {
|
||||
request.sqlSubquery
|
||||
}
|
||||
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
@@ -238,11 +150,6 @@ public struct AnyFetchRequest<RowDecoder>: FetchRequest {
|
||||
{
|
||||
try request.makePreparedRequest(db, forSingleResult: singleResult)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
|
||||
try request._requestSQL(context, forSingleResult: singleResult)
|
||||
}
|
||||
}
|
||||
|
||||
extension AnyFetchRequest {
|
||||
@@ -258,7 +165,7 @@ extension AnyFetchRequest {
|
||||
private class FetchRequestEraser: FetchRequest {
|
||||
typealias RowDecoder = Void
|
||||
|
||||
func _selectedColumnCount(_ db: Database) throws -> Int {
|
||||
var sqlSubquery: SQLSubquery {
|
||||
fatalError("subclass must override")
|
||||
}
|
||||
|
||||
@@ -269,10 +176,6 @@ private class FetchRequestEraser: FetchRequest {
|
||||
func fetchCount(_ db: Database) throws -> Int {
|
||||
fatalError("subclass must override")
|
||||
}
|
||||
|
||||
func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
|
||||
fatalError("subclass must override")
|
||||
}
|
||||
}
|
||||
|
||||
private final class ConcreteFetchRequestEraser<Request: FetchRequest>: FetchRequestEraser {
|
||||
@@ -282,8 +185,8 @@ private final class ConcreteFetchRequestEraser<Request: FetchRequest>: FetchRequ
|
||||
self.request = request
|
||||
}
|
||||
|
||||
override func _selectedColumnCount(_ db: Database) throws -> Int {
|
||||
try request._selectedColumnCount(db)
|
||||
override var sqlSubquery: SQLSubquery {
|
||||
request.sqlSubquery
|
||||
}
|
||||
|
||||
override func fetchCount(_ db: Database) throws -> Int {
|
||||
@@ -293,8 +196,4 @@ private final class ConcreteFetchRequestEraser<Request: FetchRequest>: FetchRequ
|
||||
override func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
|
||||
try request.makePreparedRequest(db, forSingleResult: singleResult)
|
||||
}
|
||||
|
||||
override func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
|
||||
try request._requestSQL(context, forSingleResult: singleResult)
|
||||
}
|
||||
}
|
||||
+645
-171
File diff suppressed because it is too large.
Load diff
@@ -141,7 +141,7 @@ public protocol _RowLayout {
|
||||
func _layoutIndex(ofColumn name: String) -> Int?
|
||||
}
|
||||
|
||||
extension SelectStatement: _RowLayout {
|
||||
extension Statement: _RowLayout {
|
||||
/// :nodoc:
|
||||
public var _layoutColumns: [(Int, String)] {
|
||||
Array(columnNames.enumerated())
|
||||
@@ -494,23 +494,30 @@ struct AdaptedRowImpl: RowImpl {
|
||||
|
||||
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int) -> Value
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Value
|
||||
{
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return Value.fastDecode(from: base, atUncheckedIndex: mappedIndex)
|
||||
return try Value.fastDecode(fromRow: base, atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int) -> Value?
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Value?
|
||||
{
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return Value.fastDecodeIfPresent(from: base, atUncheckedIndex: mappedIndex)
|
||||
return try Value.fastDecodeIfPresent(fromRow: base, atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func dataNoCopy(atUncheckedIndex index: Int) -> Data? {
|
||||
func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data {
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return base.impl.dataNoCopy(atUncheckedIndex: mappedIndex)
|
||||
return try base.impl.fastDecodeDataNoCopy(atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? {
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return try base.impl.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func columnName(atUncheckedIndex index: Int) -> String {
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
/// A key that is used to decode a value in a row
|
||||
@usableFromInline
|
||||
enum RowKey: Hashable {
|
||||
/// A column name
|
||||
case columnName(String)
|
||||
|
||||
/// A column index
|
||||
case columnIndex(Int)
|
||||
|
||||
/// A scope
|
||||
case scope(String)
|
||||
|
||||
/// A key of prefetched rows
|
||||
case prefetchKey(String)
|
||||
}
|
||||
|
||||
/// A decoding error
|
||||
@usableFromInline
|
||||
enum RowDecodingError: Error {
|
||||
@usableFromInline
|
||||
struct Context: CustomDebugStringConvertible {
|
||||
/// A description of what went wrong, for debugging purposes.
|
||||
@usableFromInline
|
||||
let debugDescription: String
|
||||
|
||||
/// The row that could not be decoded
|
||||
let row: Row
|
||||
|
||||
/// Nil for RowDecodingError.keyNotFound, in order to avoid redundancy
|
||||
let key: RowKey?
|
||||
|
||||
/// The SQL query
|
||||
let sql: String?
|
||||
|
||||
/// The SQL query arguments
|
||||
let statementArguments: StatementArguments?
|
||||
|
||||
init(decodingContext: RowDecodingContext, debugDescription: String) {
|
||||
self.debugDescription = debugDescription
|
||||
self.row = decodingContext.row
|
||||
self.key = decodingContext.key
|
||||
self.sql = decodingContext.sql
|
||||
self.statementArguments = decodingContext.statementArguments
|
||||
}
|
||||
}
|
||||
|
||||
case keyNotFound(RowKey, Context)
|
||||
case valueMismatch(Any.Type, Context)
|
||||
|
||||
var context: Context {
|
||||
switch self {
|
||||
case .keyNotFound(_, let context),
|
||||
.valueMismatch(_, let context):
|
||||
return context
|
||||
}
|
||||
}
|
||||
|
||||
/// Convenience method that builds the
|
||||
/// `could not decode <Type> from database value <value>` error message.
|
||||
static func valueMismatch(
|
||||
_ type: Any.Type,
|
||||
context: RowDecodingContext,
|
||||
databaseValue: DatabaseValue)
|
||||
-> Self
|
||||
{
|
||||
valueMismatch(
|
||||
type,
|
||||
RowDecodingError.Context(decodingContext: context, debugDescription: """
|
||||
could not decode \(type) from database value \(databaseValue)
|
||||
"""))
|
||||
}
|
||||
|
||||
/// Convenience method that builds the
|
||||
/// `could not decode <Type> from database value <value>` error message.
|
||||
@usableFromInline
|
||||
static func valueMismatch(
|
||||
_ type: Any.Type,
|
||||
sqliteStatement: SQLiteStatement,
|
||||
index: Int32,
|
||||
context: RowDecodingContext)
|
||||
-> Self
|
||||
{
|
||||
valueMismatch(
|
||||
type,
|
||||
context: context,
|
||||
databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index))
|
||||
}
|
||||
|
||||
/// Convenience method that builds the
|
||||
/// `could not decode <Type> from database value <value>` error message.
|
||||
static func valueMismatch(
|
||||
_ type: Any.Type,
|
||||
statement: Statement,
|
||||
index: Int)
|
||||
-> Self
|
||||
{
|
||||
valueMismatch(
|
||||
type,
|
||||
context: RowDecodingContext(statement: statement, index: index),
|
||||
databaseValue: DatabaseValue(sqliteStatement: statement.sqliteStatement, index: Int32(index)))
|
||||
}
|
||||
|
||||
/// Convenience method that builds the `column not found: <column>`
|
||||
/// error message.
|
||||
@usableFromInline
|
||||
static func columnNotFound(_ columnName: String, context: RowDecodingContext) -> Self {
|
||||
keyNotFound(
|
||||
.columnName(columnName),
|
||||
RowDecodingError.Context(decodingContext: context, debugDescription: """
|
||||
column not found: \(String(reflecting: columnName))
|
||||
"""))
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
struct RowDecodingContext {
|
||||
/// The row that is decoded
|
||||
let row: Row
|
||||
|
||||
let key: RowKey?
|
||||
|
||||
/// The SQL query
|
||||
let sql: String?
|
||||
|
||||
/// The SQL query arguments
|
||||
let statementArguments: StatementArguments?
|
||||
|
||||
@usableFromInline
|
||||
init(row: Row, key: RowKey? = nil) {
|
||||
if let statement = row.statement {
|
||||
self.key = key
|
||||
self.row = row.copy()
|
||||
self.sql = statement.sql
|
||||
self.statementArguments = statement.arguments
|
||||
} else if let sqliteStatement = row.sqliteStatement {
|
||||
self.key = key
|
||||
self.row = row.copy()
|
||||
self.sql = String(cString: sqlite3_sql(sqliteStatement)).trimmingCharacters(in: .sqlStatementSeparators)
|
||||
self.statementArguments = nil // Can't rebuild them
|
||||
} else {
|
||||
self.key = key
|
||||
self.row = row.copy()
|
||||
self.sql = nil
|
||||
self.statementArguments = nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Convenience initializer
|
||||
@usableFromInline
|
||||
init(statement: Statement, index: Int) {
|
||||
self.key = .columnIndex(index)
|
||||
self.row = Row(copiedFromSQLiteStatement: statement.sqliteStatement, statement: statement)
|
||||
self.sql = statement.sql
|
||||
self.statementArguments = statement.arguments
|
||||
}
|
||||
}
|
||||
|
||||
extension RowDecodingError: CustomStringConvertible {
|
||||
@usableFromInline
|
||||
var description: String {
|
||||
let context = self.context
|
||||
let row = context.row
|
||||
var chunks: [String] = []
|
||||
|
||||
if let key = context.key {
|
||||
switch key {
|
||||
case let .columnIndex(columnIndex):
|
||||
let rowIndex = row.index(row.startIndex, offsetBy: columnIndex)
|
||||
let columnName = row.columnNames[rowIndex]
|
||||
chunks.append("column: \(String(reflecting: columnName))")
|
||||
chunks.append("column index: \(columnIndex)")
|
||||
|
||||
case let .columnName(columnName):
|
||||
if let columnIndex = row.index(forColumn: columnName) {
|
||||
chunks.append("column: \(String(reflecting: columnName))")
|
||||
chunks.append("column index: \(columnIndex)")
|
||||
} else {
|
||||
// column name is already mentionned in context.debugDescription
|
||||
}
|
||||
|
||||
case .prefetchKey:
|
||||
// key is already mentionned in context.debugDescription
|
||||
break
|
||||
|
||||
case .scope:
|
||||
// scope is already mentionned in context.debugDescription
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
chunks.append("row: \(row.description)")
|
||||
|
||||
if let sql = context.sql {
|
||||
chunks.append("sql: `\(sql)`")
|
||||
}
|
||||
|
||||
if let statementArguments = context.statementArguments {
|
||||
chunks.append("arguments: \(statementArguments)")
|
||||
}
|
||||
|
||||
return "\(context.debugDescription) - \(chunks.joined(separator: ", "))"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
/// `SQL` helps you build SQL literal with
|
||||
/// [SQL Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md).
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// let name: String = ...
|
||||
/// let id: Int64 = ...
|
||||
/// let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
/// try db.execute(literal: query)
|
||||
/// }
|
||||
public struct SQL {
|
||||
/// `SQL` is an array of elements which can be qualified with table
|
||||
/// aliases. This is how `SQL` can blend well in the query interface.
|
||||
enum Element {
|
||||
// Can't be qualified with a table alias
|
||||
case sql(String, StatementArguments = StatementArguments())
|
||||
// Does not need to be qualified with a table alias
|
||||
case subquery(SQLSubquery)
|
||||
// Cases below can be qualified with a table alias
|
||||
case expression(SQLExpression)
|
||||
case selection(SQLSelection)
|
||||
case ordering(SQLOrdering)
|
||||
|
||||
var isEmpty: Bool {
|
||||
switch self {
|
||||
case let .sql(sql, _):
|
||||
return sql.isEmpty
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func sql(_ context: SQLGenerationContext) throws -> String {
|
||||
switch self {
|
||||
case let .sql(sql, arguments):
|
||||
if context.append(arguments: arguments) == false {
|
||||
// We don't know how to look for `?` in sql and
|
||||
// replace them with literals.
|
||||
fatalError("Not implemented: turning an SQL parameter into an SQL literal value")
|
||||
}
|
||||
return sql
|
||||
case let .subquery(subquery):
|
||||
return try subquery.sql(context)
|
||||
case let .expression(expression):
|
||||
return try expression.sql(context)
|
||||
case let .selection(selection):
|
||||
return try selection.sql(context)
|
||||
case let .ordering(ordering):
|
||||
return try ordering.sql(context)
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func qualified(with alias: TableAlias) -> Element {
|
||||
switch self {
|
||||
case .sql:
|
||||
// Can't qualify raw SQL string
|
||||
return self
|
||||
case .subquery:
|
||||
// Subqueries don't need table alias
|
||||
return self
|
||||
case let .expression(expression):
|
||||
return .expression(expression.qualified(with: alias))
|
||||
case let .selection(selection):
|
||||
return .selection(selection.qualified(with: alias))
|
||||
case let .ordering(ordering):
|
||||
return .ordering(ordering.qualified(with: alias))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private(set) var elements: [Element]
|
||||
|
||||
init(elements: [Element]) {
|
||||
self.elements = elements
|
||||
}
|
||||
|
||||
/// Creates an `SQL` literal from a plain SQL string, and
|
||||
/// eventual arguments.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let query = SQL(
|
||||
/// sql: "UPDATE player SET name = ? WHERE id = ?",
|
||||
/// arguments: [name, id])
|
||||
public init(sql: String, arguments: StatementArguments = StatementArguments()) {
|
||||
self.init(elements: [.sql(sql, arguments)])
|
||||
}
|
||||
|
||||
/// Creates an `SQL` literal from an SQL expression.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let columnLiteral = SQL(Column("username"))
|
||||
/// let suffixLiteral = SQL("@example.com".databaseValue)
|
||||
/// let emailLiteral = [columnLiteral, suffixLiteral].joined(separator: " || ")
|
||||
/// let request = User.select(emailLiteral.sqlExpression)
|
||||
/// let emails = try String.fetchAll(db, request)
|
||||
public init(_ expression: SQLSpecificExpressible) {
|
||||
self.init(elements: [.expression(expression.sqlExpression)])
|
||||
}
|
||||
|
||||
/// Returns true if this literal generates an empty SQL string
|
||||
public var isEmpty: Bool {
|
||||
elements.allSatisfy(\.isEmpty)
|
||||
}
|
||||
|
||||
/// Turn a `SQL` literal into raw SQL and arguments.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A tuple made of a raw SQL string, and statement arguments.
|
||||
public func build(_ db: Database) throws -> (sql: String, arguments: StatementArguments) {
|
||||
let context = SQLGenerationContext(db)
|
||||
let sql = try self.sql(context)
|
||||
return (sql: sql, arguments: context.arguments)
|
||||
}
|
||||
|
||||
/// Returns the literal SQL string given an SQL generation context.
|
||||
func sql(_ context: SQLGenerationContext) throws -> String {
|
||||
try elements.map { try $0.sql(context) }.joined()
|
||||
}
|
||||
|
||||
func qualified(with alias: TableAlias) -> SQL {
|
||||
SQL(elements: elements.map { $0.qualified(with: alias) })
|
||||
}
|
||||
}
|
||||
|
||||
extension SQL {
|
||||
/// Returns the `SQL` literal produced by the concatenation of two literals.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// let selection: SQL = "SELECT * FROM player "
|
||||
/// let condition: SQL = "WHERE name = \(name)"
|
||||
/// let query = selection + condition
|
||||
public static func + (lhs: SQL, rhs: SQL) -> SQL {
|
||||
var result = lhs
|
||||
result += rhs
|
||||
return result
|
||||
}
|
||||
|
||||
/// Appends an `SQL` literal to the receiver.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQL = "SELECT * FROM player "
|
||||
/// query += "WHERE name = \(name)"
|
||||
public static func += (lhs: inout SQL, rhs: SQL) {
|
||||
lhs.elements += rhs.elements
|
||||
}
|
||||
|
||||
/// Appends an `SQL` literal to the receiver.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQL = "SELECT * FROM player "
|
||||
/// query.append(literal: "WHERE name = \(name)")
|
||||
public mutating func append(literal sqlLiteral: SQL) {
|
||||
self += sqlLiteral
|
||||
}
|
||||
|
||||
/// Appends a plain SQL string to the receiver, and eventual arguments.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQL = "SELECT * FROM player "
|
||||
/// query.append(sql: "WHERE name = ?", arguments: [name])
|
||||
public mutating func append(sql: String, arguments: StatementArguments = StatementArguments()) {
|
||||
self += SQL(sql: sql, arguments: arguments)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQL: SQLSpecificExpressible {
|
||||
/// Creates a literal SQL expression.
|
||||
///
|
||||
/// Use this property when you need an explicit `SQLExpression`.
|
||||
/// For example:
|
||||
///
|
||||
/// func date(_ value: SQLExpressible) -> SQLExpression {
|
||||
/// SQL("DATE(\(value))").sqlExpression
|
||||
/// }
|
||||
///
|
||||
/// // SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23'
|
||||
/// let createdAt = Column("createdAt")
|
||||
/// let request = Player.filter(date(createdAt) == "2020-01-23")
|
||||
public var sqlExpression: SQLExpression {
|
||||
.literal(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQL: SQLSelectable {
|
||||
public var sqlSelection: SQLSelection {
|
||||
.literal(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQL: SQLOrderingTerm {
|
||||
public var sqlOrdering: SQLOrdering {
|
||||
.literal(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence where Element == SQL {
|
||||
/// Returns the concatenated `SQL` literal of this sequence of literals,
|
||||
/// inserting the given separator between each element.
|
||||
///
|
||||
/// let components: [SQL] = [
|
||||
/// "UPDATE player",
|
||||
/// "SET name = \(name)",
|
||||
/// "WHERE id = \(id)"
|
||||
/// ]
|
||||
/// let query = components.joined(separator: " ")
|
||||
public func joined(separator: String = "") -> SQL {
|
||||
if separator.isEmpty {
|
||||
return SQL(elements: flatMap(\.elements))
|
||||
} else {
|
||||
return SQL(elements: Array(map(\.elements).joined(separator: CollectionOfOne(.sql(separator)))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Collection where Element == SQL {
|
||||
/// Returns the concatenated `SQL` literal of this collection of literals,
|
||||
/// inserting the given SQL separator between each element.
|
||||
///
|
||||
/// let components: [SQL] = [
|
||||
/// "UPDATE player",
|
||||
/// "SET name = \(name)",
|
||||
/// "WHERE id = \(id)"
|
||||
/// ]
|
||||
/// let query = components.joined(separator: " ")
|
||||
public func joined(separator: String = "") -> SQL {
|
||||
if separator.isEmpty {
|
||||
return SQL(elements: flatMap(\.elements))
|
||||
} else {
|
||||
return SQL(elements: Array(map(\.elements).joined(separator: CollectionOfOne(.sql(separator)))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ExpressibleByStringInterpolation
|
||||
|
||||
extension SQL: ExpressibleByStringInterpolation {
|
||||
/// :nodoc
|
||||
public init(unicodeScalarLiteral: String) {
|
||||
self.init(sql: unicodeScalarLiteral, arguments: [])
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(extendedGraphemeClusterLiteral: String) {
|
||||
self.init(sql: extendedGraphemeClusterLiteral, arguments: [])
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(stringLiteral: String) {
|
||||
self.init(sql: stringLiteral, arguments: [])
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(stringInterpolation sqlInterpolation: SQLInterpolation) {
|
||||
self.init(elements: sqlInterpolation.elements)
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,52 @@
|
||||
/// :nodoc:
|
||||
public struct SQLInterpolation: StringInterpolationProtocol {
|
||||
var elements: [SQLLiteral.Element]
|
||||
var elements: [SQL.Element]
|
||||
|
||||
public init(literalCapacity: Int, interpolationCount: Int) {
|
||||
elements = []
|
||||
elements.reserveCapacity(interpolationCount + 1)
|
||||
}
|
||||
|
||||
/// "SELECT * FROM player"
|
||||
public mutating func appendLiteral(_ sql: String) {
|
||||
if sql.isEmpty { return }
|
||||
elements.append(.sql(sql))
|
||||
}
|
||||
|
||||
/// "SELECT * FROM \(sql: "player")"
|
||||
/// Appends a raw SQL snippet, with eventual arguments.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// "SELECT * FROM \(sql: "player")"
|
||||
/// "SELECT * FROM player WHERE \(sql: "name = ?", arguments: ["O'Brien"])"
|
||||
public mutating func appendInterpolation(sql: String, arguments: StatementArguments = StatementArguments()) {
|
||||
elements.append(.sql(sql, arguments))
|
||||
}
|
||||
|
||||
/// "SELECT * FROM player WHERE \(literal: condition)"
|
||||
public mutating func appendInterpolation(literal sqlLiteral: SQLLiteral) {
|
||||
/// Appends a raw `SQL` literal.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// "SELECT * FROM \(SQL("player"))"
|
||||
/// "SELECT * FROM player WHERE \(SQL("name = \("O'Brien")"))"
|
||||
public mutating func appendInterpolation(_ sqlLiteral: SQL) {
|
||||
elements.append(contentsOf: sqlLiteral.elements)
|
||||
}
|
||||
|
||||
/// Appends a String expression.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// "SELECT * FROM player WHERE name = \("O'Brien")"
|
||||
public mutating func appendInterpolation<S: StringProtocol>(_ string: S) {
|
||||
elements.append(.expression(String(string).sqlExpression))
|
||||
}
|
||||
|
||||
/// Appends a raw `SQL` literal.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// "SELECT * FROM player WHERE \(literal: "name = \("O'Brien")")"
|
||||
public mutating func appendInterpolation(literal sqlLiteral: SQL) {
|
||||
elements.append(contentsOf: sqlLiteral.elements)
|
||||
}
|
||||
}
|
||||
@@ -1,368 +0,0 @@
|
||||
/// SQLLiteral is a type which support [SQL
|
||||
/// Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md).
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// let name: String = ...
|
||||
/// let id: Int64 = ...
|
||||
/// let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
/// try db.execute(literal: query)
|
||||
/// }
|
||||
public struct SQLLiteral {
|
||||
/// SQLLiteral is an array of elements which can be qualified with
|
||||
/// table aliases.
|
||||
enum Element {
|
||||
// Can't be qualified with a table alias
|
||||
case sql(String, StatementArguments = StatementArguments())
|
||||
// Does not need to be qualified with a table alias
|
||||
case subquery(DatabasePromise<_FetchRequest>)
|
||||
// Cases below can be qualified with a table alias
|
||||
case expression(SQLExpression)
|
||||
case selectable(SQLSelectable)
|
||||
case orderingTerm(SQLOrderingTerm)
|
||||
|
||||
var isEmpty: Bool {
|
||||
switch self {
|
||||
case let .sql(sql, _):
|
||||
return sql.isEmpty
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func sql(_ context: SQLGenerationContext) throws -> String {
|
||||
switch self {
|
||||
case let .sql(sql, arguments):
|
||||
if context.append(arguments: arguments) == false {
|
||||
// We don't know how to look for `?` in sql and
|
||||
// replace them with literals.
|
||||
fatalError("Not implemented: turning an SQL parameter into an SQL literal value")
|
||||
}
|
||||
return sql
|
||||
case let .subquery(requestPromise):
|
||||
return try requestPromise.resolve(context.db)._requestSQL(context, forSingleResult: false)
|
||||
case let .expression(expression):
|
||||
return try expression._expressionSQL(context, wrappedInParenthesis: false)
|
||||
case let .selectable(selectable):
|
||||
return try selectable._resultColumnSQL(context)
|
||||
case let .orderingTerm(orderingTerm):
|
||||
return try orderingTerm._orderingTermSQL(context)
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func qualified(with alias: TableAlias) -> Element {
|
||||
switch self {
|
||||
case .sql:
|
||||
// Can't qualify raw SQL string
|
||||
return self
|
||||
case .subquery:
|
||||
// Subqueries don't need table alias
|
||||
return self
|
||||
case let .expression(expression):
|
||||
return .expression(expression._qualifiedExpression(with: alias))
|
||||
case let .selectable(selectable):
|
||||
return .selectable(selectable._qualifiedSelectable(with: alias))
|
||||
case let .orderingTerm(orderingTerm):
|
||||
return .orderingTerm(orderingTerm._qualifiedOrdering(with: alias))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private(set) var elements: [Element]
|
||||
|
||||
init(elements: [Element]) {
|
||||
self.elements = elements
|
||||
}
|
||||
|
||||
/// Creates an SQLLiteral from a plain SQL string, and eventual arguments.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let query = SQLLiteral(
|
||||
/// sql: "UPDATE player SET name = ? WHERE id = ?",
|
||||
/// arguments: [name, id])
|
||||
public init(sql: String, arguments: StatementArguments = StatementArguments()) {
|
||||
self.init(elements: [.sql(sql, arguments)])
|
||||
}
|
||||
|
||||
/// Creates an SQLLiteral from an SQL expression.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let columnLiteral = SQLLiteral(Column("username"))
|
||||
/// let suffixLiteral = SQLLiteral("@example.com".databaseValue)
|
||||
/// let emailLiteral = [columnLiteral, suffixLiteral].joined(separator: " || ")
|
||||
/// let request = User.select(emailLiteral.sqlExpression)
|
||||
/// let emails = try String.fetchAll(db, request)
|
||||
public init(_ expression: SQLExpression) {
|
||||
self.init(elements: [.expression(expression)])
|
||||
}
|
||||
|
||||
/// Returns true if this literal generates an empty SQL string
|
||||
public var isEmpty: Bool {
|
||||
elements.allSatisfy(\.isEmpty)
|
||||
}
|
||||
|
||||
/// Turn a SQLLiteral into raw SQL and arguments.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A tuple made of a raw SQL string, and statement arguments.
|
||||
public func build(_ db: Database) throws -> (sql: String, arguments: StatementArguments) {
|
||||
let context = SQLGenerationContext(db)
|
||||
let sql = try self.sql(context)
|
||||
return (sql: sql, arguments: context.arguments)
|
||||
}
|
||||
|
||||
/// Returns the literal SQL string given an SQL generation context.
|
||||
func sql(_ context: SQLGenerationContext) throws -> String {
|
||||
try elements.map { try $0.sql(context) }.joined()
|
||||
}
|
||||
|
||||
func qualified(with alias: TableAlias) -> SQLLiteral {
|
||||
SQLLiteral(elements: elements.map { $0.qualified(with: alias) })
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLLiteral {
|
||||
/// Returns the SQLLiteral produced by the concatenation of two literals.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// let selection: SQLLiteral = "SELECT * FROM player "
|
||||
/// let condition: SQLLiteral = "WHERE name = \(name)"
|
||||
/// let query = selection + condition
|
||||
public static func + (lhs: SQLLiteral, rhs: SQLLiteral) -> SQLLiteral {
|
||||
var result = lhs
|
||||
result += rhs
|
||||
return result
|
||||
}
|
||||
|
||||
/// Appends an SQLLiteral to the receiver.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQLLiteral = "SELECT * FROM player "
|
||||
/// query += "WHERE name = \(name)"
|
||||
public static func += (lhs: inout SQLLiteral, rhs: SQLLiteral) {
|
||||
lhs.elements += rhs.elements
|
||||
}
|
||||
|
||||
/// Appends an SQLLiteral to the receiver.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQLLiteral = "SELECT * FROM player "
|
||||
/// query.append(literal: "WHERE name = \(name)")
|
||||
public mutating func append(literal sqlLiteral: SQLLiteral) {
|
||||
self += sqlLiteral
|
||||
}
|
||||
|
||||
/// Appends a plain SQL string to the receiver, and eventual arguments.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQLLiteral = "SELECT * FROM player "
|
||||
/// query.append(sql: "WHERE name = ?", arguments: [name])
|
||||
public mutating func append(sql: String, arguments: StatementArguments = StatementArguments()) {
|
||||
self += SQLLiteral(sql: sql, arguments: arguments)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLLiteral {
|
||||
/// Creates a literal SQL expression.
|
||||
///
|
||||
/// SQLLiteral(sql: "1 + 2").sqlExpression
|
||||
/// SQLLiteral(sql: "? + ?", arguments: [1, 2]).sqlExpression
|
||||
/// SQLLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]).sqlExpression
|
||||
public var sqlExpression: SQLExpression {
|
||||
SQLExpressionLiteral(sqlLiteral: self)
|
||||
}
|
||||
|
||||
var sqlSelectable: SQLSelectable {
|
||||
SQLSelectionLiteral(sqlLiteral: self)
|
||||
}
|
||||
|
||||
var sqlOrderingTerm: SQLOrderingTerm {
|
||||
SQLOrderingLiteral(sqlLiteral: self)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence where Element == SQLLiteral {
|
||||
/// Returns the concatenated SQLLiteral of this sequence of literals,
|
||||
/// inserting the given separator between each element.
|
||||
///
|
||||
/// let components: [SQLLiteral] = [
|
||||
/// "UPDATE player",
|
||||
/// "SET name = \(name)",
|
||||
/// "WHERE id = \(id)"
|
||||
/// ]
|
||||
/// let query = components.joined(separator: " ")
|
||||
public func joined(separator: String = "") -> SQLLiteral {
|
||||
if separator.isEmpty {
|
||||
return SQLLiteral(elements: flatMap(\.elements))
|
||||
} else {
|
||||
return SQLLiteral(elements: Array(map(\.elements).joined(separator: CollectionOfOne(.sql(separator)))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Collection where Element == SQLLiteral {
|
||||
/// Returns the concatenated SQLLiteral of this collection of literals,
|
||||
/// inserting the given SQL separator between each element.
|
||||
///
|
||||
/// let components: [SQLLiteral] = [
|
||||
/// "UPDATE player",
|
||||
/// "SET name = \(name)",
|
||||
/// "WHERE id = \(id)"
|
||||
/// ]
|
||||
/// let query = components.joined(separator: " ")
|
||||
public func joined(separator: String = "") -> SQLLiteral {
|
||||
if separator.isEmpty {
|
||||
return SQLLiteral(elements: flatMap(\.elements))
|
||||
} else {
|
||||
return SQLLiteral(elements: Array(map(\.elements).joined(separator: CollectionOfOne(.sql(separator)))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ExpressibleByStringInterpolation
|
||||
|
||||
extension SQLLiteral: ExpressibleByStringInterpolation {
|
||||
/// :nodoc
|
||||
public init(unicodeScalarLiteral: String) {
|
||||
self.init(sql: unicodeScalarLiteral, arguments: [])
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(extendedGraphemeClusterLiteral: String) {
|
||||
self.init(sql: extendedGraphemeClusterLiteral, arguments: [])
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(stringLiteral: String) {
|
||||
self.init(sql: stringLiteral, arguments: [])
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(stringInterpolation sqlInterpolation: SQLInterpolation) {
|
||||
self.init(elements: sqlInterpolation.elements)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionLiteral
|
||||
|
||||
// TODO: remove public qualifier when GRDB5 fixits are removed.
|
||||
/// `SQLExpressionLiteral` is an expression built from a raw SQL snippet.
|
||||
///
|
||||
/// To build one, use the `SQLiteral.sqlExpression` property:
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// let column = Column("name")
|
||||
/// let literal: SQLLiteral = "\(column) = \(name)"
|
||||
/// let expression = literal.sqlExpression
|
||||
///
|
||||
/// Such expressions can feed query interface requests:
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// // SELECT * FROM player WHERE name = 'O''Brien'
|
||||
/// let players = try Player
|
||||
/// .filter(expression)
|
||||
/// .fetchAll(db)
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // FROM player
|
||||
/// // JOIN team WHERE team.id = player.teamID
|
||||
/// // WHERE player.name = 'O''Brien'
|
||||
/// let players = try Player
|
||||
/// .including(required: Player.team)
|
||||
/// .filter(expression)
|
||||
/// .fetchAll(db)
|
||||
/// }
|
||||
///
|
||||
/// See SQLLiteral for more information.
|
||||
///
|
||||
/// :nodoc:
|
||||
public struct SQLExpressionLiteral: SQLExpression {
|
||||
let sqlLiteral: SQLLiteral
|
||||
|
||||
// Prefer SQLLiteral.sqlExpression
|
||||
fileprivate init(sqlLiteral: SQLLiteral) {
|
||||
self.sqlLiteral = sqlLiteral
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
var resultSQL = try sqlLiteral.sql(context)
|
||||
|
||||
if wrappedInParenthesis {
|
||||
resultSQL = "(\(resultSQL))"
|
||||
}
|
||||
|
||||
return resultSQL
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
sqlLiteral.qualified(with: alias).sqlExpression
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLSelectionLiteral
|
||||
|
||||
struct SQLSelectionLiteral: SQLSelectable {
|
||||
let sqlLiteral: SQLLiteral
|
||||
|
||||
// Prefer SQLLiteral.sqlSelectable
|
||||
fileprivate init(sqlLiteral: SQLLiteral) {
|
||||
self.sqlLiteral = sqlLiteral
|
||||
}
|
||||
|
||||
func _columnCount(_ db: Database) throws -> Int {
|
||||
fatalError("""
|
||||
Selection literals don't known how many columns they contain. \
|
||||
To resolve this error, select one or several literal expressions instead. \
|
||||
See SQLLiteral.sqlExpression.
|
||||
""")
|
||||
}
|
||||
|
||||
func _count(distinct: Bool) -> _SQLCount? { nil }
|
||||
|
||||
func _countedSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
fatalError("""
|
||||
Selection literals can't be counted. \
|
||||
To resolve this error, select one or several literal expressions instead. \
|
||||
See SQLLiteral.sqlExpression.
|
||||
""")
|
||||
}
|
||||
|
||||
func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable {
|
||||
sqlLiteral.qualified(with: alias).sqlSelectable
|
||||
}
|
||||
|
||||
func _resultColumnSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
try sqlLiteral.sql(context)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLOrderingLiteral
|
||||
|
||||
struct SQLOrderingLiteral: SQLOrderingTerm {
|
||||
let sqlLiteral: SQLLiteral
|
||||
|
||||
// Prefer SQLLiteral.sqlOrderingTerm
|
||||
fileprivate init(sqlLiteral: SQLLiteral) {
|
||||
self.sqlLiteral = sqlLiteral
|
||||
}
|
||||
|
||||
func _orderingTermSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
try sqlLiteral.sql(context)
|
||||
}
|
||||
|
||||
func _qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm {
|
||||
sqlLiteral.qualified(with: alias).sqlOrderingTerm
|
||||
}
|
||||
|
||||
var _reversed: SQLOrderingTerm {
|
||||
fatalError("""
|
||||
Ordering literals can't be reversed. \
|
||||
To resolve this error, order by expression literals instead.
|
||||
""")
|
||||
}
|
||||
}
|
||||
+82
-55
@@ -15,9 +15,22 @@ public struct SQLRequest<RowDecoder> {
|
||||
/// The request adapter
|
||||
public var adapter: RowAdapter?
|
||||
|
||||
private(set) var sqlLiteral: SQLLiteral
|
||||
private(set) var sqlLiteral: SQL
|
||||
let cache: Cache?
|
||||
|
||||
private init(
|
||||
literal sqlLiteral: SQL,
|
||||
adapter: RowAdapter?,
|
||||
fromCache cache: Cache?,
|
||||
type: RowDecoder.Type)
|
||||
{
|
||||
self.sqlLiteral = sqlLiteral
|
||||
self.adapter = adapter
|
||||
self.cache = cache
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLRequest {
|
||||
/// Creates a request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
///
|
||||
@@ -42,66 +55,95 @@ public struct SQLRequest<RowDecoder> {
|
||||
cached: Bool = false)
|
||||
{
|
||||
self.init(
|
||||
literal: SQLLiteral(sql: sql, arguments: arguments),
|
||||
literal: SQL(sql: sql, arguments: arguments),
|
||||
adapter: adapter,
|
||||
fromCache: cached ? .public : nil)
|
||||
fromCache: cached ? .public : nil,
|
||||
type: RowDecoder.self)
|
||||
}
|
||||
|
||||
/// Creates a request from an SQLLiteral, and optional row adapter.
|
||||
/// Creates a request from an `SQL` literal, and optional row adapter.
|
||||
///
|
||||
/// let request = SQLRequest<String>(literal: SQLLiteral(sql: """
|
||||
/// SELECT name FROM player
|
||||
/// """))
|
||||
/// let request = SQLRequest<Player>(literal: SQLLiteral(sql: """
|
||||
/// SELECT * FROM player WHERE name = ?
|
||||
/// """, arguments: ["O'Brien"]))
|
||||
///
|
||||
/// With Swift 5, you can safely embed raw values in your SQL queries,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
/// Literals allow you to safely embed raw values in your SQL, without any
|
||||
/// risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// let name = "O'brien"
|
||||
/// let request = SQLRequest<Player>(literal: """
|
||||
/// SELECT * FROM player WHERE name = \("O'brien")
|
||||
/// SELECT * FROM player WHERE name = \(name)
|
||||
/// """)
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqlLiteral: An SQLLiteral.
|
||||
/// - sqlLiteral: An `SQL` literal.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: A SQLRequest
|
||||
public init(literal sqlLiteral: SQLLiteral, adapter: RowAdapter? = nil, cached: Bool = false) {
|
||||
self.init(literal: sqlLiteral, adapter: adapter, fromCache: cached ? .public : nil)
|
||||
public init(literal sqlLiteral: SQL, adapter: RowAdapter? = nil, cached: Bool = false) {
|
||||
self.init(
|
||||
literal: sqlLiteral,
|
||||
adapter: adapter,
|
||||
fromCache: cached ? .public : nil,
|
||||
type: RowDecoder.self)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLRequest where RowDecoder == Row {
|
||||
/// Creates a request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
///
|
||||
/// let request = SQLRequest(sql: """
|
||||
/// SELECT * FROM player WHERE id = ?
|
||||
/// """, arguments: [1])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: A SQLRequest
|
||||
public init(
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil,
|
||||
cached: Bool = false)
|
||||
{
|
||||
self.init(
|
||||
literal: SQL(sql: sql, arguments: arguments),
|
||||
adapter: adapter,
|
||||
fromCache: cached ? .public : nil,
|
||||
type: Row.self)
|
||||
}
|
||||
|
||||
/// Creates a request from an SQLLiteral, and optional row adapter.
|
||||
/// Creates a request from an `SQL` literal, and optional row adapter.
|
||||
///
|
||||
/// let request = SQLRequest<String>(literal: SQLLiteral(sql: """
|
||||
/// SELECT name FROM player
|
||||
/// """))
|
||||
/// let request = SQLRequest<Player>(literal: SQLLiteral(sql: """
|
||||
/// SELECT * FROM player WHERE name = ?
|
||||
/// """, arguments: ["O'Brien"]))
|
||||
/// Literals allow you to safely embed raw values in your SQL, without any
|
||||
/// risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// With Swift 5, you can safely embed raw values in your SQL queries,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// let request = SQLRequest<Player>(literal: """
|
||||
/// SELECT * FROM player WHERE name = \("O'brien")
|
||||
/// let name = "O'brien"
|
||||
/// let request = SQLRequest(literal: """
|
||||
/// SELECT * FROM player WHERE name = \(name)
|
||||
/// """)
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqlLiteral: An SQLLiteral.
|
||||
/// - sqlLiteral: An `SQL` literal.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - cache: The eventual cache
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: A SQLRequest
|
||||
init(literal sqlLiteral: SQLLiteral, adapter: RowAdapter? = nil, fromCache cache: Cache?) {
|
||||
self.sqlLiteral = sqlLiteral
|
||||
self.adapter = adapter
|
||||
self.cache = cache
|
||||
public init(literal sqlLiteral: SQL, adapter: RowAdapter? = nil, cached: Bool = false) {
|
||||
self.init(
|
||||
literal: sqlLiteral,
|
||||
adapter: adapter,
|
||||
fromCache: cached ? .public : nil,
|
||||
type: Row.self)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLRequest: FetchRequest {
|
||||
public var sqlSubquery: SQLSubquery {
|
||||
.literal(sqlLiteral)
|
||||
}
|
||||
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
try SQLRequest<Int>("SELECT COUNT(*) FROM (\(self))").fetchOne(db)!
|
||||
}
|
||||
@@ -113,33 +155,18 @@ extension SQLRequest: FetchRequest {
|
||||
{
|
||||
let context = SQLGenerationContext(db)
|
||||
let sql = try sqlLiteral.sql(context)
|
||||
let statement: SelectStatement
|
||||
let statement: Statement
|
||||
switch cache {
|
||||
case .none:
|
||||
statement = try db.makeSelectStatement(sql: sql)
|
||||
statement = try db.makeStatement(sql: sql)
|
||||
case .public?:
|
||||
statement = try db.cachedSelectStatement(sql: sql)
|
||||
statement = try db.cachedStatement(sql: sql)
|
||||
case .internal?:
|
||||
statement = try db.internalCachedSelectStatement(sql: sql)
|
||||
statement = try db.internalCachedStatement(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 _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
|
||||
try sqlLiteral.sql(context)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLRequest: ExpressibleByStringInterpolation {
|
||||
@@ -160,6 +187,6 @@ extension SQLRequest: ExpressibleByStringInterpolation {
|
||||
|
||||
/// :nodoc:
|
||||
public init(stringInterpolation sqlInterpolation: SQLInterpolation) {
|
||||
self.init(literal: SQLLiteral(stringInterpolation: sqlInterpolation))
|
||||
self.init(literal: SQL(stringInterpolation: sqlInterpolation))
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import Dispatch
|
||||
///
|
||||
/// Generally speaking, each connection has its own dispatch queue. But it's not
|
||||
/// enough: users need to use two database connections at the same time:
|
||||
/// https://github.com/groue/GRDB.swift/issues/55. To support this use case, a
|
||||
/// <https://github.com/groue/GRDB.swift/issues/55>. To support this use case, a
|
||||
/// single dispatch queue can be temporarily shared by two or more connections.
|
||||
///
|
||||
/// - SchedulingWatchdog.makeSerializedQueue(allowingDatabase:) creates a
|
||||
|
||||
@@ -17,7 +17,6 @@ final class SerializedDatabase {
|
||||
init(
|
||||
path: String,
|
||||
configuration: Configuration = Configuration(),
|
||||
schemaCache: DatabaseSchemaCache,
|
||||
defaultLabel: String,
|
||||
purpose: String? = nil)
|
||||
throws
|
||||
@@ -47,8 +46,7 @@ final class SerializedDatabase {
|
||||
self.db = try Database(
|
||||
path: path,
|
||||
description: identifier,
|
||||
configuration: config,
|
||||
schemaCache: schemaCache)
|
||||
configuration: config)
|
||||
self.queue = configuration.makeDispatchQueue(label: identifier)
|
||||
SchedulingWatchdog.allowDatabase(db, onQueue: queue)
|
||||
try queue.sync {
|
||||
|
||||
+143
-238
@@ -9,34 +9,65 @@ extension CharacterSet {
|
||||
}
|
||||
|
||||
/// A statement represents an SQL query.
|
||||
///
|
||||
/// It is the base class of UpdateStatement that executes *update statements*,
|
||||
/// and SelectStatement that fetches rows.
|
||||
public class Statement {
|
||||
public final class Statement {
|
||||
enum TransactionEffect {
|
||||
case beginTransaction
|
||||
case commitTransaction
|
||||
case rollbackTransaction
|
||||
case beginSavepoint(String)
|
||||
case releaseSavepoint(String)
|
||||
case rollbackSavepoint(String)
|
||||
}
|
||||
|
||||
/// The raw SQLite statement, suitable for the SQLite C API.
|
||||
public let sqliteStatement: SQLiteStatement
|
||||
|
||||
/// The SQL query
|
||||
public var sql: String {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
|
||||
// trim white space and semicolumn for homogeneous output
|
||||
return String(cString: sqlite3_sql(sqliteStatement))
|
||||
.trimmingCharacters(in: .sqlStatementSeparators)
|
||||
}
|
||||
|
||||
/// The column names, ordered from left to right.
|
||||
public lazy var columnNames: [String] = {
|
||||
let sqliteStatement = self.sqliteStatement
|
||||
return (0..<Int32(self.columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
|
||||
}()
|
||||
|
||||
// Database region is computed during statement compilation, and maybe
|
||||
// extended for select statements compiled by QueryInterfaceRequest, in
|
||||
// order to perform focused database observation. See
|
||||
// SQLQueryGenerator.makeSelectStatement(_:)
|
||||
// SQLQueryGenerator.makeStatement(_:)
|
||||
/// The database region that the statement looks into.
|
||||
public internal(set) var databaseRegion = DatabaseRegion()
|
||||
|
||||
var isReadonly: Bool {
|
||||
/// If true, the database schema cache gets invalidated after this statement
|
||||
/// is executed.
|
||||
private(set) var invalidatesDatabaseSchemaCache = false
|
||||
private(set) var transactionEffect: TransactionEffect?
|
||||
private(set) var databaseEventKinds: [DatabaseEventKind] = []
|
||||
|
||||
/// Returns true if and only if the prepared statement makes no direct
|
||||
/// changes to the content of the database file.
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/stmt_readonly.html>.
|
||||
public var isReadonly: Bool {
|
||||
sqlite3_stmt_readonly(sqliteStatement) != 0
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
unowned let database: Database
|
||||
|
||||
/// Cache for index(ofColumn:). Keys are lowercase.
|
||||
private lazy var columnIndexes: [String: Int] = {
|
||||
Dictionary(
|
||||
self.columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
|
||||
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
|
||||
}()
|
||||
|
||||
/// Creates a prepared statement. Returns nil if the compiled string is
|
||||
/// blank or empty.
|
||||
///
|
||||
@@ -46,34 +77,34 @@ public class Statement {
|
||||
/// - parameter statementEnd: Upon success, the pointer to the next
|
||||
/// statement in the C string.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
/// - parameter authorizer: A StatementCompilationAuthorizer
|
||||
/// SQLite 3.20.0, see <http://www.sqlite.org/c3ref/prepare.html>)
|
||||
/// - throws: DatabaseError in case of compilation error.
|
||||
required init?(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
prepFlags: Int32,
|
||||
authorizer: StatementCompilationAuthorizer) throws
|
||||
prepFlags: Int32) throws
|
||||
{
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
|
||||
let authorizer = StatementCompilationAuthorizer()
|
||||
var sqliteStatement: SQLiteStatement? = nil
|
||||
// sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
let code = sqlite3_prepare_v3(
|
||||
database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags),
|
||||
&sqliteStatement, statementEnd)
|
||||
#else
|
||||
let code: Int32
|
||||
if #available(iOS 12.0, OSX 10.14, tvOS 12.0, watchOS 5.0, *) {
|
||||
code = sqlite3_prepare_v3(
|
||||
let code: Int32 = database.withAuthorizer(authorizer) {
|
||||
// sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
return sqlite3_prepare_v3(
|
||||
database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags),
|
||||
&sqliteStatement, statementEnd)
|
||||
} else {
|
||||
code = sqlite3_prepare_v2(database.sqliteConnection, statementStart, -1, &sqliteStatement, statementEnd)
|
||||
#else
|
||||
if #available(iOS 12.0, OSX 10.14, tvOS 12.0, watchOS 5.0, *) {
|
||||
return sqlite3_prepare_v3(
|
||||
database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags),
|
||||
&sqliteStatement, statementEnd)
|
||||
} else {
|
||||
return sqlite3_prepare_v2(database.sqliteConnection, statementStart, -1, &sqliteStatement, statementEnd)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(
|
||||
@@ -89,6 +120,9 @@ public class Statement {
|
||||
self.database = database
|
||||
self.sqliteStatement = statement
|
||||
self.databaseRegion = authorizer.selectedRegion
|
||||
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
|
||||
self.transactionEffect = authorizer.transactionEffect
|
||||
self.databaseEventKinds = authorizer.databaseEventKinds
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -106,8 +140,9 @@ public class Statement {
|
||||
|
||||
// MARK: Arguments
|
||||
|
||||
var argumentsNeedValidation = true
|
||||
var _arguments = StatementArguments()
|
||||
private var argumentsNeedValidation = true
|
||||
|
||||
private var _arguments = StatementArguments()
|
||||
|
||||
lazy var sqliteArgumentCount: Int = {
|
||||
Int(sqlite3_bind_parameter_count(self.sqliteStatement))
|
||||
@@ -188,8 +223,6 @@ public class Statement {
|
||||
bind(value, at: index)
|
||||
} else if let value = valuesIterator.next() {
|
||||
bind(value, at: index)
|
||||
} else {
|
||||
bind(.null, at: index)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -224,157 +257,59 @@ public class Statement {
|
||||
}
|
||||
|
||||
// 1-based index
|
||||
private func bind(_ dbValue: DatabaseValue, at index: Int32) {
|
||||
let code: Int32
|
||||
switch dbValue.storage {
|
||||
case .null:
|
||||
code = sqlite3_bind_null(sqliteStatement, index)
|
||||
case .int64(let int64):
|
||||
code = sqlite3_bind_int64(sqliteStatement, index, int64)
|
||||
case .double(let double):
|
||||
code = sqlite3_bind_double(sqliteStatement, index, double)
|
||||
case .string(let string):
|
||||
code = sqlite3_bind_text(sqliteStatement, index, string, -1, SQLITE_TRANSIENT)
|
||||
case .blob(let data):
|
||||
code = data.withUnsafeBytes {
|
||||
sqlite3_bind_blob(sqliteStatement, index, $0.baseAddress, Int32($0.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
func bind<T: StatementBinding>(_ value: T, at index: CInt) {
|
||||
let code = value.bind(to: sqliteStatement, at: index)
|
||||
|
||||
// It looks like sqlite3_bind_xxx() functions do not access the file system.
|
||||
// They should thus succeed, unless a GRDB bug: there is no point throwing any error.
|
||||
guard code == SQLITE_OK else {
|
||||
fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql).description)
|
||||
fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql))
|
||||
}
|
||||
}
|
||||
|
||||
// Don't make this one public unless we keep the arguments property in sync.
|
||||
private func clearBindings() {
|
||||
func clearBindings() {
|
||||
// It looks like sqlite3_clear_bindings() does not access the file system.
|
||||
// This function call should thus succeed, unless a GRDB bug: there is
|
||||
// no point throwing any error.
|
||||
let code = sqlite3_clear_bindings(sqliteStatement)
|
||||
guard code == SQLITE_OK else {
|
||||
fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql).description)
|
||||
fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql))
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func prepare(withArguments arguments: StatementArguments?) {
|
||||
func reset(withArguments arguments: StatementArguments?) {
|
||||
// Force arguments validity: it is a programmer error to provide
|
||||
// arguments that do not match the statement.
|
||||
if let arguments = arguments {
|
||||
try! setArguments(arguments)
|
||||
} else if argumentsNeedValidation {
|
||||
try! reset()
|
||||
try! validateArguments(self.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Statement Preparation
|
||||
@available(*, deprecated, renamed: "Statement")
|
||||
public typealias SelectStatement = Statement
|
||||
|
||||
extension Statement {
|
||||
// Static method instead of an initializer because initializer can't run
|
||||
// inside `sqlCodeUnits.withUnsafeBufferPointer`.
|
||||
static func prepare(_ db: Database, sql: String, prepFlags: Int32) throws -> Self {
|
||||
let authorizer = StatementCompilationAuthorizer()
|
||||
return try db.withAuthorizer(authorizer) {
|
||||
try sql.utf8CString.withUnsafeBufferPointer { buffer in
|
||||
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
|
||||
{
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_ERROR,
|
||||
message: "empty statement",
|
||||
sql: sql)
|
||||
}
|
||||
|
||||
let remainingSQL = String(cString: statementEnd!).trimmingCharacters(in: .sqlStatementSeparators)
|
||||
guard remainingSQL.isEmpty else {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: """
|
||||
Multiple statements found. To execute multiple statements, \
|
||||
use Database.execute(sql:) instead.
|
||||
""",
|
||||
sql: sql)
|
||||
}
|
||||
|
||||
return statement
|
||||
}
|
||||
}
|
||||
@available(*, deprecated, renamed: "Statement")
|
||||
public typealias UpdateStatement = Statement
|
||||
|
||||
extension Statement: CustomStringConvertible {
|
||||
public var description: String {
|
||||
"SQL: \(sql), Arguments: \(arguments)"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SelectStatement
|
||||
// MARK: - Select Statements
|
||||
|
||||
/// A subclass of Statement that fetches database rows.
|
||||
///
|
||||
/// You create SelectStatement with the Database.makeSelectStatement() method:
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?")
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
/// }
|
||||
public final class SelectStatement: Statement {
|
||||
/// Creates a prepared statement. Returns nil if the compiled string is
|
||||
/// blank or empty.
|
||||
///
|
||||
/// - parameter database: A database connection.
|
||||
/// - parameter statementStart: A pointer to a UTF-8 encoded C string
|
||||
/// containing SQL.
|
||||
/// - parameter statementEnd: Upon success, the pointer to the next
|
||||
/// statement in the C string.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
/// - parameter authorizer: A StatementCompilationAuthorizer
|
||||
/// - throws: DatabaseError in case of compilation error.
|
||||
required init?(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
prepFlags: Int32,
|
||||
authorizer: StatementCompilationAuthorizer) throws
|
||||
{
|
||||
try super.init(
|
||||
database: database,
|
||||
statementStart: statementStart,
|
||||
statementEnd: statementEnd,
|
||||
prepFlags: prepFlags,
|
||||
authorizer: authorizer)
|
||||
|
||||
GRDBPrecondition(
|
||||
authorizer.invalidatesDatabaseSchemaCache == false,
|
||||
"Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
|
||||
GRDBPrecondition(
|
||||
authorizer.transactionEffect == nil,
|
||||
"Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
|
||||
}
|
||||
|
||||
extension Statement {
|
||||
/// The number of columns in the resulting rows.
|
||||
public var columnCount: Int {
|
||||
Int(sqlite3_column_count(self.sqliteStatement))
|
||||
}
|
||||
|
||||
/// The column names, ordered from left to right.
|
||||
public lazy var columnNames: [String] = {
|
||||
let sqliteStatement = self.sqliteStatement
|
||||
return (0..<Int32(self.columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
|
||||
}()
|
||||
|
||||
/// Cache for index(ofColumn:). Keys are lowercase.
|
||||
private lazy var columnIndexes: [String: Int] = {
|
||||
Dictionary(
|
||||
self.columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
|
||||
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
|
||||
}()
|
||||
|
||||
/// Returns the index of the leftmost column named `name`, in a
|
||||
/// case-insensitive way.
|
||||
public func index(ofColumn name: String) -> Int? {
|
||||
@@ -387,23 +322,6 @@ public final class SelectStatement: Statement {
|
||||
func makeCursor(arguments: StatementArguments? = nil) throws -> StatementCursor {
|
||||
try StatementCursor(statement: self, arguments: arguments)
|
||||
}
|
||||
|
||||
/// Utility function for cursors
|
||||
func reset(withArguments arguments: StatementArguments? = nil) {
|
||||
prepare(withArguments: arguments)
|
||||
try! reset()
|
||||
}
|
||||
|
||||
/// Utility function for cursors
|
||||
@usableFromInline
|
||||
func didFail(withResultCode resultCode: Int32) throws -> Never {
|
||||
database.selectStatementDidFail(self)
|
||||
throw DatabaseError(
|
||||
resultCode: resultCode,
|
||||
message: database.lastErrorMessage,
|
||||
sql: sql,
|
||||
arguments: arguments)
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor that iterates a database statement without producing any value.
|
||||
@@ -412,81 +330,75 @@ public final class SelectStatement: Statement {
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let statement = db.makeSelectStatement(sql: "SELECT performSideEffect()")
|
||||
/// let statement = db.makeStatement(sql: "SELECT performSideEffect()")
|
||||
/// let cursor = statement.makeCursor()
|
||||
/// try cursor.next()
|
||||
/// }
|
||||
final class StatementCursor: Cursor {
|
||||
let _statement: SelectStatement
|
||||
let _sqliteStatement: SQLiteStatement
|
||||
var _done = false
|
||||
private enum _State {
|
||||
case idle, busy, done, failed
|
||||
}
|
||||
|
||||
// Use SelectStatement.makeCursor() instead
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil) throws {
|
||||
/* private, internal for testability */ let _statement: Statement
|
||||
private let _sqliteStatement: SQLiteStatement
|
||||
private var _state = _State.idle
|
||||
|
||||
// Use Statement.makeCursor() instead
|
||||
init(statement: Statement, arguments: StatementArguments? = nil) throws {
|
||||
_statement = statement
|
||||
_sqliteStatement = statement.sqliteStatement
|
||||
_statement.reset(withArguments: arguments)
|
||||
|
||||
// Assume cursor is created for iteration
|
||||
try statement.database.selectStatementWillExecute(statement)
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
if _state == .busy {
|
||||
try? _statement.database.statementDidExecute(_statement)
|
||||
}
|
||||
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? _statement.reset()
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
@inlinable
|
||||
func next() throws -> Void? {
|
||||
if _done {
|
||||
switch _state {
|
||||
case .done:
|
||||
// make sure this instance never yields a value again, even if the
|
||||
// statement is reset by another cursor.
|
||||
return nil
|
||||
case .idle:
|
||||
guard try _statement.database.statementWillExecute(_statement) == nil else {
|
||||
throw DatabaseError(
|
||||
resultCode: SQLITE_MISUSE,
|
||||
message: "Can't run statement that requires a customized authorizer from a cursor",
|
||||
sql: _statement.sql,
|
||||
arguments: _statement.arguments)
|
||||
}
|
||||
_state = .busy
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
switch sqlite3_step(_sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
_done = true
|
||||
_state = .done
|
||||
try _statement.database.statementDidExecute(_statement)
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return .some(())
|
||||
case let code:
|
||||
try _statement.didFail(withResultCode: code)
|
||||
_state = .failed
|
||||
try _statement.database.statementDidFail(_statement, withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Update Statements
|
||||
|
||||
// MARK: - UpdateStatement
|
||||
|
||||
/// A subclass of Statement that executes SQL queries.
|
||||
///
|
||||
/// You create UpdateStatement with the Database.makeUpdateStatement() method:
|
||||
///
|
||||
/// try dbQueue.inTransaction { db in
|
||||
/// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// return .commit
|
||||
/// }
|
||||
public final class UpdateStatement: Statement {
|
||||
enum TransactionEffect {
|
||||
case beginTransaction
|
||||
case commitTransaction
|
||||
case rollbackTransaction
|
||||
case beginSavepoint(String)
|
||||
case releaseSavepoint(String)
|
||||
case rollbackSavepoint(String)
|
||||
}
|
||||
|
||||
/// If true, the database schema cache gets invalidated after this statement
|
||||
/// is executed.
|
||||
private(set) var invalidatesDatabaseSchemaCache: Bool = false
|
||||
|
||||
private(set) var transactionEffect: TransactionEffect?
|
||||
private(set) var databaseEventKinds: [DatabaseEventKind] = []
|
||||
|
||||
extension Statement {
|
||||
var releasesDatabaseLock: Bool {
|
||||
guard let transactionEffect = transactionEffect else {
|
||||
return false
|
||||
@@ -506,58 +418,38 @@ public final class UpdateStatement: Statement {
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a prepared statement. Returns nil if the compiled string is
|
||||
/// blank or empty.
|
||||
///
|
||||
/// - parameter database: A database connection.
|
||||
/// - parameter statementStart: A pointer to a UTF-8 encoded C string
|
||||
/// containing SQL.
|
||||
/// - parameter statementEnd: Upon success, the pointer to the next
|
||||
/// statement in the C string.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
/// - parameter authorizer: A StatementCompilationAuthorizer
|
||||
/// - throws: DatabaseError in case of compilation error.
|
||||
required init?(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
prepFlags: Int32,
|
||||
authorizer: StatementCompilationAuthorizer) throws
|
||||
{
|
||||
try super.init(
|
||||
database: database,
|
||||
statementStart: statementStart,
|
||||
statementEnd: statementEnd,
|
||||
prepFlags: prepFlags,
|
||||
authorizer: authorizer)
|
||||
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
|
||||
self.transactionEffect = authorizer.transactionEffect
|
||||
self.databaseEventKinds = authorizer.databaseEventKinds
|
||||
}
|
||||
|
||||
/// Executes the SQL query.
|
||||
/// Executes the prepared statement.
|
||||
///
|
||||
/// - parameter arguments: Optional statement arguments.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func execute(arguments: StatementArguments? = nil) throws {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
prepare(withArguments: arguments)
|
||||
try reset()
|
||||
reset(withArguments: arguments)
|
||||
|
||||
// Statement does not know how to execute itself, because it does not
|
||||
// know how to handle its errors, or if truncate optimisation should be
|
||||
// prevented or not. Database knows.
|
||||
try database.executeUpdateStatement(self)
|
||||
try database.executeStatement(self)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - StatementBinding
|
||||
|
||||
public protocol StatementBinding {
|
||||
/// Binds a statement argument.
|
||||
///
|
||||
/// - parameter sqliteStatement: An SQLite statement.
|
||||
/// - parameter index: 1-based index to statement arguments
|
||||
/// - returns: the code returned by the `sqlite3_bind_xxx` function.
|
||||
func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt
|
||||
}
|
||||
|
||||
// MARK: - StatementArguments
|
||||
|
||||
/// StatementArguments provide values to argument placeholders in raw
|
||||
/// SQL queries.
|
||||
///
|
||||
/// Placeholders can take several forms (see https://www.sqlite.org/lang_expr.html#varparam
|
||||
/// Placeholders can take several forms (see <https://www.sqlite.org/lang_expr.html#varparam>
|
||||
/// for more information):
|
||||
///
|
||||
/// - `?NNN` (e.g. `?2`): the NNN-th argument (starts at 1)
|
||||
@@ -636,8 +528,8 @@ public final class UpdateStatement: Statement {
|
||||
public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral
|
||||
{
|
||||
private(set) var values: [DatabaseValue] = []
|
||||
private(set) var namedValues: [String: DatabaseValue] = [:]
|
||||
private(set) var values: [DatabaseValue]
|
||||
private(set) var namedValues: [String: DatabaseValue]
|
||||
|
||||
public var isEmpty: Bool {
|
||||
values.isEmpty && namedValues.isEmpty
|
||||
@@ -648,6 +540,8 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
|
||||
/// Creates empty StatementArguments.
|
||||
public init() {
|
||||
values = .init()
|
||||
namedValues = .init()
|
||||
}
|
||||
|
||||
// MARK: Positional Arguments
|
||||
@@ -661,6 +555,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
/// - returns: A StatementArguments.
|
||||
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Element == DatabaseValueConvertible? {
|
||||
values = sequence.map { $0?.databaseValue ?? .null }
|
||||
namedValues = .init()
|
||||
}
|
||||
|
||||
/// Creates statement arguments from a sequence of optional values.
|
||||
@@ -672,6 +567,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
/// - returns: A StatementArguments.
|
||||
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Element: DatabaseValueConvertible {
|
||||
values = sequence.map(\.databaseValue)
|
||||
namedValues = .init()
|
||||
}
|
||||
|
||||
/// Creates statement arguments from any array. The result is nil unless all
|
||||
@@ -690,6 +586,10 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
self.init(values)
|
||||
}
|
||||
|
||||
private mutating func set(databaseValues: [DatabaseValue]) {
|
||||
self.values = databaseValues
|
||||
namedValues.removeAll(keepingCapacity: true)
|
||||
}
|
||||
|
||||
// MARK: Named Arguments
|
||||
|
||||
@@ -703,6 +603,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
/// - returns: A StatementArguments.
|
||||
public init(_ dictionary: [String: DatabaseValueConvertible?]) {
|
||||
namedValues = dictionary.mapValues { $0?.databaseValue ?? .null }
|
||||
values = .init()
|
||||
}
|
||||
|
||||
/// Creates statement arguments from a sequence of (key, value) pairs, such
|
||||
@@ -716,7 +617,11 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
public init<Sequence>(_ sequence: Sequence)
|
||||
where Sequence: Swift.Sequence, Sequence.Element == (String, DatabaseValueConvertible?)
|
||||
{
|
||||
namedValues = Dictionary(uniqueKeysWithValues: sequence.map { ($0.0, $0.1?.databaseValue ?? .null) })
|
||||
namedValues = .init(minimumCapacity: sequence.underestimatedCount)
|
||||
for (key, value) in sequence {
|
||||
namedValues[key] = value?.databaseValue ?? .null
|
||||
}
|
||||
values = .init()
|
||||
}
|
||||
|
||||
/// Creates statement arguments from [AnyHashable: Any].
|
||||
|
||||
@@ -3,6 +3,7 @@ import Glibc
|
||||
#endif
|
||||
|
||||
/// A protocol around sqlite3_set_authorizer
|
||||
@usableFromInline
|
||||
protocol StatementAuthorizer: AnyObject {
|
||||
func authorize(
|
||||
_ actionCode: Int32,
|
||||
@@ -28,7 +29,7 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
|
||||
/// Not nil if a statement is a BEGIN/COMMIT/ROLLBACK/RELEASE transaction or
|
||||
/// savepoint statement.
|
||||
var transactionEffect: UpdateStatement.TransactionEffect?
|
||||
var transactionEffect: Statement.TransactionEffect?
|
||||
|
||||
private var isDropStatement = false
|
||||
|
||||
@@ -55,7 +56,7 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
invalidatesDatabaseSchemaCache = true
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_ALTER_TABLE, SQLITE_DETACH,
|
||||
case SQLITE_ATTACH, SQLITE_DETACH, SQLITE_ALTER_TABLE,
|
||||
SQLITE_CREATE_INDEX, SQLITE_CREATE_TABLE,
|
||||
SQLITE_CREATE_TEMP_INDEX, SQLITE_CREATE_TEMP_TABLE,
|
||||
SQLITE_CREATE_TEMP_TRIGGER, SQLITE_CREATE_TEMP_VIEW,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/// The `StatementColumnConvertible` protocol grants access to the low-level C
|
||||
/// interface that extracts values from query results:
|
||||
/// https://www.sqlite.org/c3ref/column_blob.html. It can bring performance
|
||||
/// <https://www.sqlite.org/c3ref/column_blob.html>. It can bring performance
|
||||
/// improvements.
|
||||
///
|
||||
/// To use it, have a value type adopt both `StatementColumnConvertible` and
|
||||
@@ -18,32 +18,117 @@
|
||||
/// score = row["score"] // there
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// `StatementColumnConvertible` is already adopted by all Swift integer types,
|
||||
/// `Float`, `Double`, `String`, and `Bool`.
|
||||
public protocol StatementColumnConvertible {
|
||||
|
||||
/// Initializes a value from a raw SQLite statement pointer.
|
||||
/// Initializes a value from a raw SQLite statement pointer, if possible.
|
||||
///
|
||||
/// For example, here is the how Int64 adopts StatementColumnConvertible:
|
||||
///
|
||||
/// extension Int64: StatementColumnConvertible {
|
||||
/// init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
/// init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
/// self = sqlite3_column_int64(sqliteStatement, index)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// This initializer is never called for NULL database values: don't perform
|
||||
/// any extra check.
|
||||
/// This initializer is never called for NULL database values. Just return
|
||||
/// `nil` for failed conversions: GRDB will interpret a nil result as a
|
||||
/// decoding failure.
|
||||
///
|
||||
/// See https://www.sqlite.org/c3ref/column_blob.html for more information.
|
||||
/// See <https://www.sqlite.org/c3ref/column_blob.html> for more information.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
init(sqliteStatement: SQLiteStatement, index: Int32)
|
||||
init?(sqliteStatement: SQLiteStatement, index: Int32)
|
||||
}
|
||||
|
||||
// MARK: - Conversions
|
||||
|
||||
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
@usableFromInline
|
||||
/* private */ static func _valueMismatch(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: Int32,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Never
|
||||
{
|
||||
throw RowDecodingError.valueMismatch(
|
||||
Self.self,
|
||||
sqliteStatement: sqliteStatement,
|
||||
index: index,
|
||||
context: context())
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
static func fastDecode(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: Int32,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Self
|
||||
{
|
||||
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL,
|
||||
let value = self.init(sqliteStatement: sqliteStatement, index: index)
|
||||
else {
|
||||
try _valueMismatch(fromStatement: sqliteStatement, atUncheckedIndex: index, context: context())
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
static func fastDecode(
|
||||
fromRow row: Row,
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Self
|
||||
{
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return try fastDecode(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
// Support for fast decoding from adapted rows
|
||||
return try row.fastDecode(Self.self, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
static func fastDecodeIfPresent(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: Int32,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Self?
|
||||
{
|
||||
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
|
||||
return nil
|
||||
}
|
||||
guard let value = self.init(sqliteStatement: sqliteStatement, index: index) else {
|
||||
try _valueMismatch(fromStatement: sqliteStatement, atUncheckedIndex: index, context: context())
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
static func fastDecodeIfPresent(
|
||||
fromRow row: Row,
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Self?
|
||||
{
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return try fastDecodeIfPresent(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
// Support for fast decoding from adapted rows
|
||||
return try row.fastDecodeIfPresent(Self.self, atUncheckedIndex: index)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Cursors
|
||||
|
||||
/// A cursor of database values extracted from a single column.
|
||||
/// For example:
|
||||
///
|
||||
@@ -54,12 +139,17 @@ public protocol StatementColumnConvertible {
|
||||
/// }
|
||||
/// }
|
||||
public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
|
||||
@usableFromInline let _statement: SelectStatement
|
||||
@usableFromInline
|
||||
enum _State {
|
||||
case idle, busy, done, failed
|
||||
}
|
||||
|
||||
@usableFromInline let _statement: Statement
|
||||
@usableFromInline let _columnIndex: Int32
|
||||
@usableFromInline let _sqliteStatement: SQLiteStatement
|
||||
@usableFromInline var _done = false
|
||||
@usableFromInline var _state = _State.idle
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
_statement = statement
|
||||
_sqliteStatement = statement.sqliteStatement
|
||||
if let adapter = adapter {
|
||||
@@ -68,13 +158,16 @@ public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & Sta
|
||||
} else {
|
||||
_columnIndex = 0
|
||||
}
|
||||
_statement.reset(withArguments: arguments)
|
||||
|
||||
// Assume cursor is created for iteration
|
||||
try statement.database.selectStatementWillExecute(statement)
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
if _state == .busy {
|
||||
try? _statement.database.statementDidExecute(_statement)
|
||||
}
|
||||
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? _statement.reset()
|
||||
@@ -82,19 +175,38 @@ public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & Sta
|
||||
|
||||
@inlinable
|
||||
public func next() throws -> Value? {
|
||||
if _done {
|
||||
switch _state {
|
||||
case .done:
|
||||
// make sure this instance never yields a value again, even if the
|
||||
// statement is reset by another cursor.
|
||||
return nil
|
||||
case .idle:
|
||||
guard try _statement.database.statementWillExecute(_statement) == nil else {
|
||||
throw DatabaseError(
|
||||
resultCode: SQLITE_MISUSE,
|
||||
message: "Can't run statement that requires a customized authorizer from a cursor",
|
||||
sql: _statement.sql,
|
||||
arguments: _statement.arguments)
|
||||
}
|
||||
_state = .busy
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
switch sqlite3_step(_sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
_done = true
|
||||
_state = .done
|
||||
try _statement.database.statementDidExecute(_statement)
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return Value.fastDecode(from: _sqliteStatement, atUncheckedIndex: _columnIndex)
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
return try! Value.fastDecode(
|
||||
fromStatement: _sqliteStatement,
|
||||
atUncheckedIndex: _columnIndex,
|
||||
context: RowDecodingContext(statement: _statement, index: Int(_columnIndex)))
|
||||
case let code:
|
||||
try _statement.didFail(withResultCode: code)
|
||||
_state = .failed
|
||||
try _statement.database.statementDidFail(_statement, withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -112,12 +224,17 @@ public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & Sta
|
||||
public final class FastNullableDatabaseValueCursor<Value>: Cursor
|
||||
where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
{
|
||||
@usableFromInline let _statement: SelectStatement
|
||||
@usableFromInline
|
||||
enum _State {
|
||||
case idle, busy, done, failed
|
||||
}
|
||||
|
||||
@usableFromInline let _statement: Statement
|
||||
@usableFromInline let _columnIndex: Int32
|
||||
@usableFromInline let _sqliteStatement: SQLiteStatement
|
||||
@usableFromInline var _done = false
|
||||
@usableFromInline var _state = _State.idle
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
_statement = statement
|
||||
_sqliteStatement = statement.sqliteStatement
|
||||
if let adapter = adapter {
|
||||
@@ -126,13 +243,16 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
} else {
|
||||
_columnIndex = 0
|
||||
}
|
||||
_statement.reset(withArguments: arguments)
|
||||
|
||||
// Assume cursor is created for iteration
|
||||
try statement.database.selectStatementWillExecute(statement)
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
if _state == .busy {
|
||||
try? _statement.database.statementDidExecute(_statement)
|
||||
}
|
||||
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? _statement.reset()
|
||||
@@ -140,19 +260,38 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
|
||||
@inlinable
|
||||
public func next() throws -> Value?? {
|
||||
if _done {
|
||||
switch _state {
|
||||
case .done:
|
||||
// make sure this instance never yields a value again, even if the
|
||||
// statement is reset by another cursor.
|
||||
return nil
|
||||
case .idle:
|
||||
guard try _statement.database.statementWillExecute(_statement) == nil else {
|
||||
throw DatabaseError(
|
||||
resultCode: SQLITE_MISUSE,
|
||||
message: "Can't run statement that requires a customized authorizer from a cursor",
|
||||
sql: _statement.sql,
|
||||
arguments: _statement.arguments)
|
||||
}
|
||||
_state = .busy
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
switch sqlite3_step(_sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
_done = true
|
||||
_state = .done
|
||||
try _statement.database.statementDidExecute(_statement)
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return Value.fastDecodeIfPresent(from: _sqliteStatement, atUncheckedIndex: _columnIndex)
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
return try! Value.fastDecodeIfPresent(
|
||||
fromStatement: _sqliteStatement,
|
||||
atUncheckedIndex: _columnIndex,
|
||||
context: RowDecodingContext(statement: _statement, index: Int(_columnIndex)))
|
||||
case let code:
|
||||
try _statement.didFail(withResultCode: code)
|
||||
_state = .failed
|
||||
try _statement.database.statementDidFail(_statement, withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -164,12 +303,11 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
/// See DatabaseValueConvertible for more information.
|
||||
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
|
||||
// MARK: Fetching From SelectStatement
|
||||
// MARK: Fetching From Prepared Statement
|
||||
|
||||
/// Returns a cursor over values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try String.fetchCursor(statement) // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
@@ -187,7 +325,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(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> FastDatabaseValueCursor<Self>
|
||||
@@ -197,7 +335,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
/// Returns an array of values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try String.fetchAll(statement) // [String]
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -207,7 +345,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Self]
|
||||
@@ -217,7 +355,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
/// Returns a single value fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let name = try String.fetchOne(statement) // String?
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -227,7 +365,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Self?
|
||||
@@ -244,7 +382,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hashable {
|
||||
/// Returns a set of values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try String.fetchSet(statement) // Set<String>
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -254,7 +392,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Self>
|
||||
@@ -293,7 +431,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> FastDatabaseValueCursor<Self>
|
||||
{
|
||||
try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from an SQL query.
|
||||
@@ -314,7 +452,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Self]
|
||||
{
|
||||
try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from an SQL query.
|
||||
@@ -335,7 +473,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Self?
|
||||
{
|
||||
try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -358,7 +496,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Self>
|
||||
{
|
||||
try fetchSet(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -511,18 +649,18 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// try Optional<String>.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String?]
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// try Optional<String>.fetchCursor(statement, arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(statement, arguments:...) // [String?]
|
||||
///
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching From SelectStatement
|
||||
// MARK: Fetching From Prepared Statement
|
||||
|
||||
/// Returns a cursor over optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchCursor(statement) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
@@ -540,7 +678,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(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> FastNullableDatabaseValueCursor<Wrapped>
|
||||
@@ -550,7 +688,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
|
||||
/// Returns an array of optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchAll(statement) // [String?]
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -560,7 +698,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
/// - returns: An array of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Wrapped?]
|
||||
@@ -572,7 +710,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible & Hashable {
|
||||
/// Returns a set of optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchSet(statement) // Set<String?>
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -582,7 +720,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
/// - returns: A set of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Wrapped?>
|
||||
@@ -621,7 +759,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> FastNullableDatabaseValueCursor<Wrapped>
|
||||
{
|
||||
try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from an SQL query.
|
||||
@@ -642,7 +780,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Wrapped?]
|
||||
{
|
||||
try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -665,7 +803,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Wrapped?>
|
||||
{
|
||||
try fetchSet(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ import Foundation
|
||||
|
||||
/// Data is convertible to and from DatabaseValue.
|
||||
extension Data: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
if let bytes = sqlite3_column_blob(sqliteStatement, index) {
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, index))
|
||||
@@ -25,10 +24,86 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
return data
|
||||
case .string(let string):
|
||||
// Implicit conversion from string to blob, just as SQLite does
|
||||
// See https://www.sqlite.org/c3ref/column_blob.html
|
||||
// See <https://www.sqlite.org/c3ref/column_blob.html>
|
||||
return string.data(using: .utf8)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
withUnsafeBytes {
|
||||
sqlite3_bind_blob(sqliteStatement, index, $0.baseAddress, Int32($0.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Conversions
|
||||
|
||||
extension Data {
|
||||
static func fastDecodeNoCopy(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: Int32,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Data
|
||||
{
|
||||
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
|
||||
throw RowDecodingError.valueMismatch(
|
||||
Data.self,
|
||||
sqliteStatement: sqliteStatement,
|
||||
index: index,
|
||||
context: context())
|
||||
}
|
||||
guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else {
|
||||
return Data()
|
||||
}
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
|
||||
}
|
||||
|
||||
static func fastDecodeNoCopy(
|
||||
fromRow row: Row,
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Data
|
||||
{
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return try fastDecodeNoCopy(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
// Support for fast decoding from adapted rows
|
||||
return try row.fastDecodeDataNoCopy(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
static func fastDecodeNoCopyIfPresent(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: Int32,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
-> Data?
|
||||
{
|
||||
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
|
||||
return nil
|
||||
}
|
||||
guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else {
|
||||
return Data()
|
||||
}
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
|
||||
}
|
||||
|
||||
static func fastDecodeNoCopyIfPresent(
|
||||
fromRow row: Row,
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Data?
|
||||
{
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return fastDecodeNoCopyIfPresent(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
// Support for fast decoding from adapted rows
|
||||
return try row.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: index)
|
||||
}
|
||||
}
|
||||
@@ -69,9 +69,11 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
guard let cString = sqlite3_column_text(sqliteStatement, index) else {
|
||||
fatalConversionError(to: DatabaseDateComponents.self, sqliteStatement: sqliteStatement, index: index)
|
||||
return nil
|
||||
}
|
||||
let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen
|
||||
let optionalComponents = cString.withMemoryRebound(
|
||||
@@ -80,7 +82,7 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC
|
||||
SQLiteDateParser().components(cString: cString, length: length)
|
||||
}
|
||||
guard let components = optionalComponents else {
|
||||
fatalConversionError(to: DatabaseDateComponents.self, sqliteStatement: sqliteStatement, index: index)
|
||||
return nil
|
||||
}
|
||||
self.dateComponents = components.dateComponents
|
||||
self.format = components.format
|
||||
|
||||
@@ -118,19 +118,21 @@ extension Date: StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_INTEGER, SQLITE_FLOAT:
|
||||
self.init(timeIntervalSince1970: sqlite3_column_double(sqliteStatement, index))
|
||||
case SQLITE_TEXT:
|
||||
let databaseDateComponents = DatabaseDateComponents(sqliteStatement: sqliteStatement, index: index)
|
||||
guard let date = Date(databaseDateComponents: databaseDateComponents) else {
|
||||
fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index)
|
||||
guard let components = DatabaseDateComponents(sqliteStatement: sqliteStatement, index: index),
|
||||
let date = Date(databaseDateComponents: components)
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate)
|
||||
default:
|
||||
fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// Decimal adopts DatabaseValueConvertible
|
||||
extension Decimal: DatabaseValueConvertible {
|
||||
public var databaseValue: DatabaseValue {
|
||||
NSDecimalNumber(decimal: self)
|
||||
.description(withLocale: Locale(identifier: "en_US_POSIX"))
|
||||
.databaseValue
|
||||
}
|
||||
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64):
|
||||
return self.init(int64)
|
||||
case .double(let double):
|
||||
return self.init(double)
|
||||
case let .string(string):
|
||||
// Must match NSNumber.fromDatabaseValue(_:)
|
||||
return self.init(string: string, locale: _posixLocale)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Decimal adopts StatementColumnConvertible
|
||||
extension Decimal: StatementColumnConvertible {
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_INTEGER:
|
||||
self.init(sqlite3_column_int64(sqliteStatement, index))
|
||||
case SQLITE_FLOAT:
|
||||
self.init(sqlite3_column_double(sqliteStatement, index))
|
||||
case SQLITE_TEXT:
|
||||
self.init(
|
||||
string: String(cString: sqlite3_column_text(sqliteStatement, index)!),
|
||||
locale: _posixLocale)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
let _posixLocale = Locale(identifier: "en_US_POSIX")
|
||||
#endif
|
||||
@@ -71,9 +71,15 @@ extension NSNumber: DatabaseValueConvertible {
|
||||
return self.init(value: int64)
|
||||
case .double(let double):
|
||||
return self.init(value: double)
|
||||
case let .string(string):
|
||||
// Must match Decimal.fromDatabaseValue(_:)
|
||||
guard let decimal = Decimal(string: string, locale: posixLocale) else { return nil }
|
||||
return NSDecimalNumber(decimal: decimal) as? Self
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private let posixLocale = Locale(identifier: "en_US_POSIX")
|
||||
#endif
|
||||
@@ -2,13 +2,18 @@ import Foundation
|
||||
|
||||
// inspired by: http://jordansmith.io/performant-date-parsing/
|
||||
|
||||
final class SQLiteDateParser {
|
||||
@usableFromInline
|
||||
struct SQLiteDateParser {
|
||||
@usableFromInline
|
||||
init() { }
|
||||
|
||||
func components(from dateString: String) -> DatabaseDateComponents? {
|
||||
dateString.withCString { cString in
|
||||
components(cString: cString, length: strlen(cString))
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func components(cString: UnsafePointer<CChar>, length: Int) -> DatabaseDateComponents? {
|
||||
assert(strlen(cString) == length)
|
||||
|
||||
@@ -161,13 +166,11 @@ final class SQLiteDateParser {
|
||||
var cString: UnsafePointer<CChar>
|
||||
var length: Int
|
||||
|
||||
@inline(__always)
|
||||
private mutating func shift() {
|
||||
cString += 1
|
||||
length -= 1
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
mutating func parse(_ scalar: Unicode.Scalar) -> Bool {
|
||||
guard length > 0, cString[0] == UInt8(ascii: scalar) else {
|
||||
return false
|
||||
@@ -176,7 +179,6 @@ final class SQLiteDateParser {
|
||||
return true
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
mutating func parseDigit() -> Int? {
|
||||
guard length > 0 else {
|
||||
return nil
|
||||
@@ -190,7 +192,6 @@ final class SQLiteDateParser {
|
||||
return Int(digit)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
mutating func parseDigit(into number: inout Int) -> Bool {
|
||||
guard let digit = parseDigit() else {
|
||||
return false
|
||||
@@ -199,7 +200,6 @@ final class SQLiteDateParser {
|
||||
return true
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
mutating func parseNNNN() -> Int? {
|
||||
var number = 0
|
||||
guard parseDigit(into: &number)
|
||||
@@ -213,7 +213,6 @@ final class SQLiteDateParser {
|
||||
return number
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
mutating func parseNN() -> Int? {
|
||||
var number = 0
|
||||
guard parseDigit(into: &number)
|
||||
|
||||
@@ -49,24 +49,25 @@ extension UUID: DatabaseValueConvertible {
|
||||
}
|
||||
|
||||
extension UUID: StatementColumnConvertible {
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_TEXT:
|
||||
let string = String(cString: sqlite3_column_text(sqliteStatement, index)!)
|
||||
guard let uuid = UUID(uuidString: string) else {
|
||||
fatalConversionError(to: UUID.self, sqliteStatement: sqliteStatement, index: index)
|
||||
return nil
|
||||
}
|
||||
self.init(uuid: uuid.uuid)
|
||||
case SQLITE_BLOB:
|
||||
guard sqlite3_column_bytes(sqliteStatement, index) == 16,
|
||||
let blob = sqlite3_column_blob(sqliteStatement, index) else
|
||||
{
|
||||
fatalConversionError(to: UUID.self, sqliteStatement: sqliteStatement, index: index)
|
||||
return nil
|
||||
}
|
||||
self.init(uuid: blob.assumingMemoryBound(to: uuid_t.self).pointee)
|
||||
default:
|
||||
fatalConversionError(to: UUID.self, sqliteStatement: sqliteStatement, index: index)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import Foundation
|
||||
|
||||
private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer {
|
||||
let dbValue: DatabaseValue
|
||||
let codingPath: [CodingKey]
|
||||
@@ -155,15 +157,13 @@ private struct DatabaseValueDecoder: Decoder {
|
||||
var userInfo: [CodingUserInfoKey: Any] { [:] }
|
||||
|
||||
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
|
||||
throw DecodingError.typeMismatch(
|
||||
type,
|
||||
DecodingError.Context(codingPath: codingPath, debugDescription: "keyed decoding is not supported"))
|
||||
// We need to switch to JSON decoding
|
||||
throw JSONRequiredError()
|
||||
}
|
||||
|
||||
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
|
||||
throw DecodingError.typeMismatch(
|
||||
UnkeyedDecodingContainer.self,
|
||||
DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported"))
|
||||
// We need to switch to JSON decoding
|
||||
throw JSONRequiredError()
|
||||
}
|
||||
|
||||
func singleValueContainer() throws -> SingleValueDecodingContainer {
|
||||
@@ -173,7 +173,20 @@ private struct DatabaseValueDecoder: Decoder {
|
||||
|
||||
extension DatabaseValueConvertible where Self: Decodable {
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
try? self.init(from: DatabaseValueDecoder(dbValue: databaseValue, codingPath: []))
|
||||
do {
|
||||
return try self.init(from: DatabaseValueDecoder(dbValue: databaseValue, codingPath: []))
|
||||
} catch is JSONRequiredError {
|
||||
guard let data = Data.fromDatabaseValue(databaseValue) else {
|
||||
return nil
|
||||
}
|
||||
let decoder = JSONDecoder()
|
||||
decoder.dataDecodingStrategy = .base64
|
||||
decoder.dateDecodingStrategy = .millisecondsSince1970
|
||||
decoder.nonConformingFloatDecodingStrategy = .throw
|
||||
return try? decoder.decode(Self.self, from: data)
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import Foundation
|
||||
|
||||
private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer {
|
||||
let encode: (DatabaseValue) -> Void
|
||||
|
||||
@@ -40,13 +42,18 @@ private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer {
|
||||
// This allows us to encode Date as String, for example.
|
||||
encode(dbValueConvertible.databaseValue)
|
||||
} else {
|
||||
try value.encode(to: DatabaseValueEncoder(encode: encode))
|
||||
try DatabaseValueEncoder(encode: encode).encode(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct DatabaseValueEncoder: Encoder {
|
||||
private class DatabaseValueEncoder: Encoder {
|
||||
let encode: (DatabaseValue) -> Void
|
||||
var requiresJSON = false
|
||||
|
||||
init(encode: @escaping (DatabaseValue) -> Void) {
|
||||
self.encode = encode
|
||||
}
|
||||
|
||||
/// The path of coding keys taken to get to this point in encoding.
|
||||
/// A `nil` value indicates an unkeyed container.
|
||||
@@ -63,7 +70,14 @@ private struct DatabaseValueEncoder: Encoder {
|
||||
/// - precondition: May not be called after a value has been encoded through
|
||||
/// a previous `self.singleValueContainer()` call.
|
||||
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> {
|
||||
fatalError("keyed encoding is not supported")
|
||||
// We need to perform JSON encoding. Unfortunately we can't access the
|
||||
// inner container of Foundation's JSONEncoder. At this point we must
|
||||
// throw an error so that the caller can retry encoding from scratch.
|
||||
// Unfortunately (bis), we can't throw right from here, so let's
|
||||
// return a JSONRequiredEncoder that will throw as soon as possible.
|
||||
requiresJSON = true
|
||||
let container = JSONRequiredEncoder.KeyedContainer<Key>(codingPath: codingPath)
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
/// Returns an encoding container appropriate for holding multiple unkeyed values.
|
||||
@@ -73,7 +87,13 @@ private struct DatabaseValueEncoder: Encoder {
|
||||
/// - precondition: May not be called after a value has been encoded through
|
||||
/// a previous `self.singleValueContainer()` call.
|
||||
func unkeyedContainer() -> UnkeyedEncodingContainer {
|
||||
fatalError("unkeyed encoding is not supported")
|
||||
// We need to perform JSON encoding. Unfortunately we can't access the
|
||||
// inner container of Foundation's JSONEncoder. At this point we must
|
||||
// throw an error so that the caller can retry encoding from scratch.
|
||||
// Unfortunately (bis), we can't throw right from here, so let's
|
||||
// return a JSONRequiredEncoder that will throw as soon as possible.
|
||||
requiresJSON = true
|
||||
return JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
|
||||
/// Returns an encoding container appropriate for holding a single primitive value.
|
||||
@@ -86,13 +106,41 @@ private struct DatabaseValueEncoder: Encoder {
|
||||
func singleValueContainer() -> SingleValueEncodingContainer {
|
||||
DatabaseValueEncodingContainer(encode: encode)
|
||||
}
|
||||
|
||||
func encode<T: Encodable>(_ value: T) throws {
|
||||
do {
|
||||
try value.encode(to: self)
|
||||
if requiresJSON {
|
||||
// Here we handle empty arrays and dictionaries.
|
||||
throw JSONRequiredError()
|
||||
}
|
||||
} catch is JSONRequiredError {
|
||||
let encoder = JSONEncoder()
|
||||
encoder.dataEncodingStrategy = .base64
|
||||
encoder.dateEncodingStrategy = .millisecondsSince1970
|
||||
encoder.nonConformingFloatEncodingStrategy = .throw
|
||||
if #available(watchOS 4.0, OSX 10.13, iOS 11.0, tvOS 11.0, *) {
|
||||
// guarantee some stability in order to ease value comparison
|
||||
encoder.outputFormatting = .sortedKeys
|
||||
}
|
||||
let jsonData = try encoder.encode(value)
|
||||
|
||||
// Store JSON String in the database for easier debugging and
|
||||
// database inspection. Thanks to SQLite weak typing, we won't
|
||||
// have any trouble decoding this string into data when we
|
||||
// eventually perform JSON decoding.
|
||||
// TODO: possible optimization: avoid this conversion to string,
|
||||
// and store raw data bytes as an SQLite string
|
||||
let jsonString = String(data: jsonData, encoding: .utf8)!
|
||||
try jsonString.encode(to: self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible where Self: Encodable {
|
||||
public var databaseValue: DatabaseValue {
|
||||
var dbValue: DatabaseValue! = nil
|
||||
let encoder = DatabaseValueEncoder(encode: { dbValue = $0 })
|
||||
try! self.encode(to: encoder)
|
||||
try! DatabaseValueEncoder(encode: { dbValue = $0 }).encode(self)
|
||||
return dbValue
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
/// SQLExpressible is free for RawRepresentable types whose raw value
|
||||
/// is itself SQLExpressible.
|
||||
///
|
||||
/// // If the RawValue adopts SQLExpressible...
|
||||
/// enum Color : Int {
|
||||
/// case red
|
||||
/// case white
|
||||
/// case rose
|
||||
/// }
|
||||
///
|
||||
/// // ... then the RawRepresentable type can freely adopt SQLExpressible:
|
||||
/// extension Color : SQLExpressible { /* empty */ }
|
||||
extension SQLSelectable where Self: RawRepresentable, Self.RawValue: SQLSelectable {
|
||||
public var sqlSelection: SQLSelection {
|
||||
rawValue.sqlSelection
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLOrderingTerm where Self: RawRepresentable, Self.RawValue: SQLOrderingTerm {
|
||||
public var sqlOrdering: SQLOrdering {
|
||||
rawValue.sqlOrdering
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLExpressible where Self: RawRepresentable, Self.RawValue: SQLExpressible {
|
||||
/// Returns the raw value as an SQL expression.
|
||||
public var sqlExpression: SQLExpression {
|
||||
@@ -17,8 +17,14 @@ extension SQLExpressible where Self: RawRepresentable, Self.RawValue: SQLExpress
|
||||
}
|
||||
}
|
||||
|
||||
/// DatabaseValueConvertible is free for RawRepresentable types whose raw value
|
||||
/// is itself DatabaseValueConvertible.
|
||||
extension StatementBinding where Self: RawRepresentable, Self.RawValue: StatementBinding {
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
rawValue.bind(to: sqliteStatement, at: index)
|
||||
}
|
||||
}
|
||||
|
||||
/// `DatabaseValueConvertible` is free for `RawRepresentable` types whose raw
|
||||
/// value is itself `DatabaseValueConvertible`.
|
||||
///
|
||||
/// // If the RawValue adopts DatabaseValueConvertible...
|
||||
/// enum Color : Int {
|
||||
@@ -27,16 +33,14 @@ extension SQLExpressible where Self: RawRepresentable, Self.RawValue: SQLExpress
|
||||
/// case rose
|
||||
/// }
|
||||
///
|
||||
/// // ... then the RawRepresentable type can freely adopt DatabaseValueConvertible:
|
||||
/// extension Color : DatabaseValueConvertible { /* empty */ }
|
||||
/// // ... then the RawRepresentable type can freely
|
||||
/// // adopt DatabaseValueConvertible:
|
||||
/// extension Color: DatabaseValueConvertible { }
|
||||
extension DatabaseValueConvertible where Self: RawRepresentable, Self.RawValue: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
rawValue.databaseValue
|
||||
}
|
||||
|
||||
/// Returns a value initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
RawValue.fromDatabaseValue(dbValue).flatMap { self.init(rawValue: $0) }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
struct JSONRequiredError: Error { }
|
||||
|
||||
/// The encoder that always ends up with a JSONRequiredError
|
||||
struct JSONRequiredEncoder: Encoder {
|
||||
var codingPath: [CodingKey]
|
||||
var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo }
|
||||
|
||||
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey {
|
||||
let container = KeyedContainer<Key>(codingPath: codingPath)
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
func unkeyedContainer() -> UnkeyedEncodingContainer { self }
|
||||
|
||||
func singleValueContainer() -> SingleValueEncodingContainer { self }
|
||||
|
||||
struct KeyedContainer<KeyType: CodingKey>: KeyedEncodingContainerProtocol {
|
||||
var codingPath: [CodingKey]
|
||||
var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo }
|
||||
|
||||
// swiftlint:disable comma
|
||||
func encodeNil(forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Bool, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int8, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int16, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int32, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int64, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt8, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt16, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt32, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt64, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Float, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Double, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: String, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode<T>(_ value: T, forKey key: KeyType) throws where T: Encodable { throw JSONRequiredError() }
|
||||
// swiftlint:enable comma
|
||||
|
||||
func nestedContainer<NestedKey>(
|
||||
keyedBy keyType: NestedKey.Type,
|
||||
forKey key: KeyType)
|
||||
-> KeyedEncodingContainer<NestedKey>
|
||||
where NestedKey: CodingKey
|
||||
{
|
||||
let container = KeyedContainer<NestedKey>(codingPath: codingPath + [key])
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
func nestedUnkeyedContainer(forKey key: KeyType) -> UnkeyedEncodingContainer {
|
||||
JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
|
||||
func superEncoder() -> Encoder {
|
||||
JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
|
||||
func superEncoder(forKey key: KeyType) -> Encoder {
|
||||
JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension JSONRequiredEncoder: SingleValueEncodingContainer {
|
||||
func encodeNil() throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Bool ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int8 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int16 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int32 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int64 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt8 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt16) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt32) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt64) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Float ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Double) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: String) throws { throw JSONRequiredError() }
|
||||
func encode<T>(_ value: T) throws where T: Encodable { throw JSONRequiredError() }
|
||||
}
|
||||
|
||||
extension JSONRequiredEncoder: UnkeyedEncodingContainer {
|
||||
var count: Int { 0 }
|
||||
|
||||
mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type)
|
||||
-> KeyedEncodingContainer<NestedKey>
|
||||
where NestedKey: CodingKey
|
||||
{
|
||||
let container = KeyedContainer<NestedKey>(codingPath: codingPath)
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { self }
|
||||
|
||||
mutating func superEncoder() -> Encoder { self }
|
||||
}
|
||||
@@ -8,7 +8,6 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
self = sqlite3_column_int64(sqliteStatement, index) != 0
|
||||
}
|
||||
@@ -85,6 +84,10 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, self ? 1 : 0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Int adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -95,14 +98,12 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = Int(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalConversionError(to: Int.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
guard let v = Int(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@@ -114,6 +115,10 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { Int(exactly: $0) }
|
||||
}
|
||||
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// Int8 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -124,14 +129,12 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = Int8(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalConversionError(to: Int8.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
guard let v = Int8(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@@ -143,6 +146,10 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int8? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { Int8(exactly: $0) }
|
||||
}
|
||||
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// Int16 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -153,14 +160,12 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = Int16(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalConversionError(to: Int16.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
guard let v = Int16(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@@ -172,6 +177,10 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int16? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { Int16(exactly: $0) }
|
||||
}
|
||||
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// Int32 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -182,14 +191,12 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = Int32(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalConversionError(to: Int32.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
guard let v = Int32(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@@ -201,6 +208,10 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int32? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { Int32(exactly: $0) }
|
||||
}
|
||||
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// Int64 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -211,7 +222,6 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
self = sqlite3_column_int64(sqliteStatement, index)
|
||||
}
|
||||
@@ -234,6 +244,10 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, self)
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -244,14 +258,12 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = UInt(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalConversionError(to: UInt.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
guard let v = UInt(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@@ -263,6 +275,10 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { UInt(exactly: $0) }
|
||||
}
|
||||
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt8 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -273,14 +289,12 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = UInt8(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalConversionError(to: UInt8.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
guard let v = UInt8(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@@ -292,6 +306,10 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt8? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { UInt8(exactly: $0) }
|
||||
}
|
||||
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt16 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -302,14 +320,12 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = UInt16(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalConversionError(to: UInt16.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
guard let v = UInt16(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@@ -321,6 +337,10 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt16? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { UInt16(exactly: $0) }
|
||||
}
|
||||
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt32 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -331,14 +351,12 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = UInt32(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalConversionError(to: UInt32.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
guard let v = UInt32(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@@ -350,6 +368,10 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt32? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { UInt32(exactly: $0) }
|
||||
}
|
||||
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt64 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -360,14 +382,12 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = UInt64(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalConversionError(to: UInt64.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
guard let v = UInt64(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@@ -379,6 +399,10 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt64? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { UInt64(exactly: $0) }
|
||||
}
|
||||
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// Double adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -389,7 +413,6 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
self = sqlite3_column_double(sqliteStatement, index)
|
||||
}
|
||||
@@ -410,6 +433,10 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_double(sqliteStatement, index, self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Float adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -420,7 +447,6 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
self = Float(sqlite3_column_double(sqliteStatement, index))
|
||||
}
|
||||
@@ -441,6 +467,10 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_double(sqliteStatement, index, Double(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// String adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -451,7 +481,6 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@inlinable
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
self = String(cString: sqlite3_column_text(sqliteStatement, index)!)
|
||||
}
|
||||
@@ -466,7 +495,7 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
switch dbValue.storage {
|
||||
case .blob(let data):
|
||||
// Implicit conversion from blob to string, just as SQLite does
|
||||
// See https://www.sqlite.org/c3ref/column_blob.html
|
||||
// See <https://www.sqlite.org/c3ref/column_blob.html>
|
||||
return String(data: data, encoding: .utf8)
|
||||
case .string(let string):
|
||||
return string
|
||||
@@ -474,6 +503,10 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_text(sqliteStatement, index, self, -1, SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
+102
-101
@@ -164,7 +164,7 @@ class DatabaseObservationBroker {
|
||||
private var statementObservations: [StatementObservation] = [] {
|
||||
didSet { observesDatabaseChanges = !statementObservations.isEmpty }
|
||||
}
|
||||
private var observesDatabaseChanges: Bool = false {
|
||||
private var observesDatabaseChanges = false {
|
||||
didSet {
|
||||
if observesDatabaseChanges == oldValue { return }
|
||||
if observesDatabaseChanges {
|
||||
@@ -200,99 +200,93 @@ class DatabaseObservationBroker {
|
||||
|
||||
/// Setups observation of changes that are about to be performed by the
|
||||
/// statement, and returns the authorizer that should be used during
|
||||
/// statement execution.
|
||||
func updateStatementWillExecute(_ statement: UpdateStatement) -> StatementAuthorizer? {
|
||||
// As statement executes, it may trigger database changes that will
|
||||
// be notified to transaction observers. As a consequence, observers
|
||||
// may disable themselves with stopObservingDatabaseChangesUntilNextTransaction()
|
||||
//
|
||||
// This method takes no argument, and requires access to the "current
|
||||
// broker", which is a per-thread global stored in
|
||||
// SchedulingWatchdog.current:
|
||||
SchedulingWatchdog.current!.databaseObservationBroker = self
|
||||
|
||||
// Fill statementObservations with observations that are interested in
|
||||
// the kind of events performed by the statement.
|
||||
//
|
||||
// Those statementObservations will be notified of individual changes
|
||||
// in databaseWillChange() and databaseDidChange().
|
||||
let eventKinds = statement.databaseEventKinds
|
||||
|
||||
/// statement execution (this allows preventing the truncate optimization
|
||||
/// when there exists a transaction observer for row deletion).
|
||||
func statementWillExecute(_ statement: Statement) -> StatementAuthorizer? {
|
||||
// If any observer observes row deletions, we'll have to disable
|
||||
// [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
|
||||
// so that observers are notified.
|
||||
var observesRowDeletion = false
|
||||
|
||||
switch eventKinds.count {
|
||||
case 0:
|
||||
// Statement has no effect on any database table.
|
||||
if transactionObservations.isEmpty == false {
|
||||
// As statement executes, it may trigger database changes that will
|
||||
// be notified to transaction observers. As a consequence, observers
|
||||
// may disable themselves with stopObservingDatabaseChangesUntilNextTransaction()
|
||||
//
|
||||
// For example: PRAGMA foreign_keys = ON
|
||||
statementObservations = []
|
||||
case 1:
|
||||
// We'll execute a simple statement without any side effect.
|
||||
// Eventual database events will thus all have the same kind. All
|
||||
// detabase events can be notified to interested observations.
|
||||
// This method takes no argument, and requires access to the "current
|
||||
// broker", which is a per-thread global stored in
|
||||
// SchedulingWatchdog.current:
|
||||
SchedulingWatchdog.current!.databaseObservationBroker = self
|
||||
|
||||
// Fill statementObservations with observations that are interested in
|
||||
// the kind of events performed by the statement.
|
||||
//
|
||||
// For example, if one observes all deletions in the table T, then
|
||||
// all individual deletions of DELETE FROM T are notified:
|
||||
let eventKind = eventKinds[0]
|
||||
statementObservations = transactionObservations.compactMap { observation in
|
||||
guard observation.observes(eventsOfKind: eventKind) else {
|
||||
// observation is not interested
|
||||
return nil
|
||||
}
|
||||
|
||||
if case .delete = eventKind {
|
||||
observesRowDeletion = true
|
||||
}
|
||||
|
||||
// observation will be notified of all individual events
|
||||
return (observation, DatabaseEventPredicate.true)
|
||||
}
|
||||
default:
|
||||
// We'll execute a complex statement with side effects performed by
|
||||
// an SQL trigger or a foreign key action. Eventual database events
|
||||
// may not all have the same kind: we need to filter them before
|
||||
// notifying interested observations.
|
||||
//
|
||||
// For example, if DELETE FROM T1 generates deletions in T1 and T2
|
||||
// by the mean of a foreign key action, then when one only observes
|
||||
// deletions in T1, one must not be notified of deletions in T2:
|
||||
statementObservations = transactionObservations.compactMap { observation in
|
||||
let observedKinds = eventKinds.filter(observation.observes)
|
||||
if observedKinds.isEmpty {
|
||||
// observation is not interested
|
||||
return nil
|
||||
}
|
||||
|
||||
for eventKind in observedKinds {
|
||||
// Those statementObservations will be notified of individual changes
|
||||
// in databaseWillChange() and databaseDidChange().
|
||||
let eventKinds = statement.databaseEventKinds
|
||||
|
||||
switch eventKinds.count {
|
||||
case 0:
|
||||
// Statement has no effect on any database table.
|
||||
//
|
||||
// For example: PRAGMA foreign_keys = ON
|
||||
statementObservations = []
|
||||
case 1:
|
||||
// We'll execute a simple statement without any side effect.
|
||||
// Eventual database events will thus all have the same kind. All
|
||||
// detabase events can be notified to interested observations.
|
||||
//
|
||||
// For example, if one observes all deletions in the table T, then
|
||||
// all individual deletions of DELETE FROM T are notified:
|
||||
let eventKind = eventKinds[0]
|
||||
statementObservations = transactionObservations.compactMap { observation in
|
||||
guard observation.observes(eventsOfKind: eventKind) else {
|
||||
// observation is not interested
|
||||
return nil
|
||||
}
|
||||
|
||||
if case .delete = eventKind {
|
||||
observesRowDeletion = true
|
||||
break
|
||||
}
|
||||
|
||||
// observation will be notified of all individual events
|
||||
return (observation, DatabaseEventPredicate.true)
|
||||
}
|
||||
default:
|
||||
// We'll execute a complex statement with side effects performed by
|
||||
// an SQL trigger or a foreign key action. Eventual database events
|
||||
// may not all have the same kind: we need to filter them before
|
||||
// notifying interested observations.
|
||||
//
|
||||
// For example, if DELETE FROM T1 generates deletions in T1 and T2
|
||||
// by the mean of a foreign key action, then when one only observes
|
||||
// deletions in T1, one must not be notified of deletions in T2:
|
||||
statementObservations = transactionObservations.compactMap { observation in
|
||||
let observedKinds = eventKinds.filter(observation.observes)
|
||||
if observedKinds.isEmpty {
|
||||
// observation is not interested
|
||||
return nil
|
||||
}
|
||||
|
||||
for eventKind in observedKinds {
|
||||
if case .delete = eventKind {
|
||||
observesRowDeletion = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// observation will only be notified of individual events that
|
||||
// match one of the observed kinds.
|
||||
return (
|
||||
observation,
|
||||
DatabaseEventPredicate.matching(
|
||||
observedKinds: observedKinds,
|
||||
advertisedKinds: eventKinds))
|
||||
}
|
||||
|
||||
// observation will only be notified of individual events that
|
||||
// match one of the observed kinds.
|
||||
return (
|
||||
observation,
|
||||
DatabaseEventPredicate.matching(
|
||||
observedKinds: observedKinds,
|
||||
advertisedKinds: eventKinds))
|
||||
}
|
||||
}
|
||||
|
||||
switch transactionState {
|
||||
case .none:
|
||||
break
|
||||
default:
|
||||
// May happen after "PRAGMA journal_mode = WAL" executed with a
|
||||
// SelectStatement.
|
||||
// TODO: Maybe this state machine should be run for *all* statements,
|
||||
// not ony update statements.
|
||||
transactionState = .none
|
||||
}
|
||||
transactionState = .none
|
||||
|
||||
if observesRowDeletion {
|
||||
return TruncateOptimizationBlocker()
|
||||
@@ -301,8 +295,10 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
}
|
||||
|
||||
func updateStatementDidFail(_ statement: UpdateStatement) throws {
|
||||
// Undo updateStatementWillExecute
|
||||
/// May throw a cancelled commit error, if a transaction observer cancels
|
||||
/// a transaction.
|
||||
func statementDidFail(_ statement: Statement) throws {
|
||||
// Undo statementWillExecute
|
||||
statementObservations = []
|
||||
SchedulingWatchdog.current!.databaseObservationBroker = nil
|
||||
|
||||
@@ -325,10 +321,14 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
}
|
||||
|
||||
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
|
||||
// Undo updateStatementWillExecute
|
||||
statementObservations = []
|
||||
SchedulingWatchdog.current!.databaseObservationBroker = nil
|
||||
/// May throw a cancelled commit error, if a transaction observer cancels
|
||||
/// an empty transaction.
|
||||
func statementDidExecute(_ statement: Statement) throws {
|
||||
// Undo statementWillExecute
|
||||
if transactionObservations.isEmpty == false {
|
||||
statementObservations = []
|
||||
SchedulingWatchdog.current!.databaseObservationBroker = nil
|
||||
}
|
||||
|
||||
// Has statement any effect on transaction/savepoints?
|
||||
if let transactionEffect = statement.transactionEffect {
|
||||
@@ -439,7 +439,7 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
}
|
||||
|
||||
// Called from updateStatementDidExecute
|
||||
// Called from statementDidExecute
|
||||
private func databaseDidCommit() {
|
||||
savepointStack.clear()
|
||||
|
||||
@@ -449,7 +449,9 @@ class DatabaseObservationBroker {
|
||||
databaseDidEndTransaction()
|
||||
}
|
||||
|
||||
// Called from updateStatementDidExecute
|
||||
// Called from statementDidExecute
|
||||
/// May throw a cancelled commit error, if a transaction observer cancels
|
||||
/// the empty transaction.
|
||||
private func databaseDidCommitEmptyDeferredTransaction() throws {
|
||||
// A statement that ends a transaction has been executed. But for
|
||||
// SQLite, no transaction at all has started, and sqlite3_commit_hook
|
||||
@@ -492,7 +494,7 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
}
|
||||
|
||||
// Called from updateStatementDidExecute or updateStatementDidFails
|
||||
// Called from statementDidExecute or statementDidFail
|
||||
private func databaseDidRollback(notifyTransactionObservers: Bool) {
|
||||
savepointStack.clear()
|
||||
|
||||
@@ -527,7 +529,7 @@ class DatabaseObservationBroker {
|
||||
//
|
||||
// Normally, notifyBufferedEvents() is called as part of statement
|
||||
// execution, and the current broker has been set in
|
||||
// updateStatementWillExecute(). An assertion should be enough:
|
||||
// statementWillExecute(). An assertion should be enough:
|
||||
//
|
||||
// assert(SchedulingWatchdog.current?.databaseObservationBroker != nil)
|
||||
//
|
||||
@@ -535,10 +537,8 @@ class DatabaseObservationBroker {
|
||||
//
|
||||
// let journalMode = String.fetchOne(db, sql: "PRAGMA journal_mode = wal")
|
||||
//
|
||||
// It runs a SelectStatement, not an UpdateStatement. But this not why
|
||||
// this case is particular. What is unexpected is that it triggers
|
||||
// the commit hook when the "PRAGMA journal_mode = wal" statement is
|
||||
// finalized, long after it has executed:
|
||||
// It triggers the commit hook when the "PRAGMA journal_mode = wal"
|
||||
// statement is finalized, long after it has executed:
|
||||
//
|
||||
// 1. Statement.deinit()
|
||||
// 2. sqlite3_finalize()
|
||||
@@ -551,7 +551,7 @@ class DatabaseObservationBroker {
|
||||
// journal mode would trigger the commit hook in sqlite3_step(),
|
||||
// not in sqlite3_finalize().
|
||||
//
|
||||
// Anyway: in this scenario, updateStatementWillExecute() has not been
|
||||
// Anyway: in this scenario, statementWillExecute() has not been
|
||||
// called, and the current broker is nil.
|
||||
//
|
||||
// Let's not try to outsmart SQLite, and build a complex state machine.
|
||||
@@ -586,7 +586,7 @@ class DatabaseObservationBroker {
|
||||
do {
|
||||
try broker.databaseWillCommit()
|
||||
broker.transactionState = .commit
|
||||
// Next step: updateStatementDidExecute()
|
||||
// Next step: statementDidExecute()
|
||||
return 0
|
||||
} catch {
|
||||
broker.transactionState = .cancelledCommit(error)
|
||||
@@ -599,11 +599,11 @@ class DatabaseObservationBroker {
|
||||
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
|
||||
switch broker.transactionState {
|
||||
case .cancelledCommit:
|
||||
// Next step: updateStatementDidFail()
|
||||
// Next step: statementDidFail()
|
||||
break
|
||||
default:
|
||||
broker.transactionState = .rollback
|
||||
// Next step: updateStatementDidExecute()
|
||||
// Next step: statementDidExecute()
|
||||
}
|
||||
}, brokerPointer)
|
||||
}
|
||||
@@ -737,7 +737,7 @@ public protocol TransactionObserver: AnyObject {
|
||||
/// As of OSX 10.11.5, and iOS 9.3.2, the built-in SQLite library
|
||||
/// does not have this enabled, so you'll need to compile your own
|
||||
/// version of SQLite:
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md>
|
||||
///
|
||||
/// The databaseDidChangeWithEvent callback is always available,
|
||||
/// and may provide most/all of what you need.
|
||||
@@ -796,7 +796,7 @@ final class TransactionObservation {
|
||||
|
||||
// A disabled observation is not interested in individual database changes.
|
||||
// It is still interested in transactions commits & rollbacks.
|
||||
var isDisabled: Bool = false
|
||||
var isDisabled = false
|
||||
|
||||
private weak var weakObserver: TransactionObserver?
|
||||
private var strongObserver: TransactionObserver?
|
||||
@@ -881,6 +881,7 @@ typealias StatementObservation = (TransactionObservation, DatabaseEventPredicate
|
||||
|
||||
/// A kind of database event. See the `TransactionObserver` protocol for
|
||||
/// more information.
|
||||
@frozen
|
||||
public enum DatabaseEventKind {
|
||||
/// The insertion of a row in a database table
|
||||
case insert(tableName: String)
|
||||
@@ -1346,7 +1347,7 @@ enum DatabaseEventPredicate {
|
||||
// MARK: - SavepointStack
|
||||
|
||||
/// The SQLite savepoint stack is described at
|
||||
/// https://www.sqlite.org/lang_savepoint.html
|
||||
/// <https://www.sqlite.org/lang_savepoint.html>
|
||||
///
|
||||
/// This class reimplements the SQLite stack, so that we can:
|
||||
///
|
||||
|
||||
+10
-2
@@ -8,7 +8,7 @@ public struct FTS3: VirtualTableModule {
|
||||
/// Options for Latin script characters. Matches the raw "remove_diacritics"
|
||||
/// tokenizer argument.
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html
|
||||
/// See <https://www.sqlite.org/fts3.html>
|
||||
public enum Diacritics {
|
||||
/// Do not remove diacritics from Latin script characters. This
|
||||
/// option matches the raw "remove_diacritics=0" tokenizer argument.
|
||||
@@ -45,10 +45,18 @@ public struct FTS3: VirtualTableModule {
|
||||
/// The virtual table module name
|
||||
public let moduleName = "fts3"
|
||||
|
||||
// TODO: remove when `makeTableDefinition()` is no longer a requirement
|
||||
/// Reserved; part of the VirtualTableModule protocol.
|
||||
///
|
||||
/// See Database.create(virtualTable:using:)
|
||||
public func makeTableDefinition() -> FTS3TableDefinition {
|
||||
preconditionFailure()
|
||||
}
|
||||
|
||||
/// Reserved; part of the VirtualTableModule protocol.
|
||||
///
|
||||
/// See Database.create(virtualTable:using:)
|
||||
public func makeTableDefinition(configuration: VirtualTableConfiguration) -> FTS3TableDefinition {
|
||||
FTS3TableDefinition()
|
||||
}
|
||||
|
||||
@@ -93,7 +101,7 @@ public final class FTS3TableDefinition {
|
||||
/// try db.create(virtualTable: "document", using: FTS3()) { t in
|
||||
/// t.tokenizer = .porter
|
||||
/// }
|
||||
/// See https://www.sqlite.org/fts3.html#creating_and_destroying_fts_tables
|
||||
/// See <https://www.sqlite.org/fts3.html#creating_and_destroying_fts_tables>
|
||||
public var tokenizer: FTS3TokenizerDescriptor?
|
||||
|
||||
/// Appends a table column.
|
||||
|
||||
@@ -7,7 +7,7 @@ public struct FTS3Pattern {
|
||||
/// Creates a pattern from a raw pattern string; throws DatabaseError on
|
||||
/// invalid syntax.
|
||||
///
|
||||
/// The pattern syntax is documented at https://www.sqlite.org/fts3.html#full_text_index_queries
|
||||
/// The pattern syntax is documented at <https://www.sqlite.org/fts3.html#full_text_index_queries>
|
||||
///
|
||||
/// try FTS3Pattern(rawPattern: "and") // OK
|
||||
/// try FTS3Pattern(rawPattern: "AND") // malformed MATCH expression: [AND]
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
/// t.tokenizer = .simple // FTS3TokenizerDescriptor
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#tokenizer
|
||||
/// See <https://www.sqlite.org/fts3.html#tokenizer>
|
||||
public struct FTS3TokenizerDescriptor {
|
||||
let name: String
|
||||
let arguments: [String]
|
||||
@@ -20,7 +20,7 @@ public struct FTS3TokenizerDescriptor {
|
||||
/// t.tokenizer = .simple
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#tokenizer
|
||||
/// See <https://www.sqlite.org/fts3.html#tokenizer>
|
||||
public static let simple = FTS3TokenizerDescriptor("simple")
|
||||
|
||||
/// The "porter" tokenizer.
|
||||
@@ -29,7 +29,7 @@ public struct FTS3TokenizerDescriptor {
|
||||
/// t.tokenizer = .porter
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#tokenizer
|
||||
/// See <https://www.sqlite.org/fts3.html#tokenizer>
|
||||
public static let porter = FTS3TokenizerDescriptor("porter")
|
||||
|
||||
/// The "unicode61" tokenizer.
|
||||
@@ -46,7 +46,7 @@ public struct FTS3TokenizerDescriptor {
|
||||
/// - tokenCharacters: Unless empty (the default), SQLite will consider
|
||||
/// these characters as token characters.
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#tokenizer
|
||||
/// See <https://www.sqlite.org/fts3.html#tokenizer>
|
||||
public static func unicode61(
|
||||
diacritics: FTS3.Diacritics = .removeLegacy,
|
||||
separators: Set<Character> = [],
|
||||
|
||||
+37
-18
@@ -5,7 +5,7 @@
|
||||
/// t.column("content")
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html
|
||||
/// See <https://www.sqlite.org/fts3.html>
|
||||
public struct FTS4: VirtualTableModule {
|
||||
|
||||
/// Creates a FTS4 module suitable for the Database
|
||||
@@ -16,7 +16,7 @@ public struct FTS4: VirtualTableModule {
|
||||
/// t.column("content")
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html
|
||||
/// See <https://www.sqlite.org/fts3.html>
|
||||
public init() {
|
||||
}
|
||||
|
||||
@@ -25,11 +25,19 @@ public struct FTS4: VirtualTableModule {
|
||||
/// The virtual table module name
|
||||
public let moduleName = "fts4"
|
||||
|
||||
// TODO: remove when `makeTableDefinition()` is no longer a requirement
|
||||
/// Reserved; part of the VirtualTableModule protocol.
|
||||
///
|
||||
/// See Database.create(virtualTable:using:)
|
||||
public func makeTableDefinition() -> FTS4TableDefinition {
|
||||
FTS4TableDefinition()
|
||||
preconditionFailure()
|
||||
}
|
||||
|
||||
/// Reserved; part of the VirtualTableModule protocol.
|
||||
///
|
||||
/// See Database.create(virtualTable:using:)
|
||||
public func makeTableDefinition(configuration: VirtualTableConfiguration) -> FTS4TableDefinition {
|
||||
FTS4TableDefinition(configuration: configuration)
|
||||
}
|
||||
|
||||
/// Reserved; part of the VirtualTableModule protocol.
|
||||
@@ -113,20 +121,26 @@ public struct FTS4: VirtualTableModule {
|
||||
|
||||
let oldRowID = "old.\(rowIDColumn.quotedDatabaseIdentifier)"
|
||||
|
||||
let ifNotExists = definition.configuration.ifNotExists
|
||||
? "IF NOT EXISTS "
|
||||
: ""
|
||||
|
||||
// swiftlint:disable line_length
|
||||
try db.execute(sql: """
|
||||
CREATE TRIGGER \("__\(tableName)_bu".quotedDatabaseIdentifier) BEFORE UPDATE ON \(content) BEGIN
|
||||
CREATE TRIGGER \(ifNotExists)\("__\(tableName)_bu".quotedDatabaseIdentifier) BEFORE UPDATE ON \(content) BEGIN
|
||||
DELETE FROM \(ftsTable) WHERE docid=\(oldRowID);
|
||||
END;
|
||||
CREATE TRIGGER \("__\(tableName)_bd".quotedDatabaseIdentifier) BEFORE DELETE ON \(content) BEGIN
|
||||
CREATE TRIGGER \(ifNotExists)\("__\(tableName)_bd".quotedDatabaseIdentifier) BEFORE DELETE ON \(content) BEGIN
|
||||
DELETE FROM \(ftsTable) WHERE docid=\(oldRowID);
|
||||
END;
|
||||
CREATE TRIGGER \("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
|
||||
CREATE TRIGGER \(ifNotExists)\("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
|
||||
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns));
|
||||
END;
|
||||
CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
|
||||
CREATE TRIGGER \(ifNotExists)\("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
|
||||
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns));
|
||||
END;
|
||||
""")
|
||||
// swiftlint:enable line_length
|
||||
|
||||
// https://www.sqlite.org/fts3.html#*fts4rebuidcmd
|
||||
|
||||
@@ -144,13 +158,14 @@ public struct FTS4: VirtualTableModule {
|
||||
/// t.column("content")
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html
|
||||
/// See <https://www.sqlite.org/fts3.html>
|
||||
public final class FTS4TableDefinition {
|
||||
enum ContentMode {
|
||||
case raw(content: String?)
|
||||
case synchronized(contentTable: String)
|
||||
}
|
||||
|
||||
fileprivate let configuration: VirtualTableConfiguration
|
||||
fileprivate var columns: [FTS4ColumnDefinition] = []
|
||||
fileprivate var contentMode: ContentMode = .raw(content: nil)
|
||||
|
||||
@@ -160,7 +175,7 @@ public final class FTS4TableDefinition {
|
||||
/// t.tokenizer = .porter
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#creating_and_destroying_fts_tables
|
||||
/// See <https://www.sqlite.org/fts3.html#creating_and_destroying_fts_tables>
|
||||
public var tokenizer: FTS3TokenizerDescriptor?
|
||||
|
||||
/// The FTS4 `content` option
|
||||
@@ -172,7 +187,7 @@ public final class FTS4TableDefinition {
|
||||
/// Setting this property invalidates any synchronization previously
|
||||
/// established with the `synchronize(withTable:)` method.
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#the_content_option_
|
||||
/// See <https://www.sqlite.org/fts3.html#the_content_option_>
|
||||
public var content: String? {
|
||||
get {
|
||||
switch contentMode {
|
||||
@@ -189,17 +204,17 @@ public final class FTS4TableDefinition {
|
||||
|
||||
/// The FTS4 `compress` option
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#the_compress_and_uncompress_options
|
||||
/// See <https://www.sqlite.org/fts3.html#the_compress_and_uncompress_options>
|
||||
public var compress: String?
|
||||
|
||||
/// The FTS4 `uncompress` option
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#the_compress_and_uncompress_options
|
||||
/// See <https://www.sqlite.org/fts3.html#the_compress_and_uncompress_options>
|
||||
public var uncompress: String?
|
||||
|
||||
/// The FTS4 `matchinfo` option
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#the_matchinfo_option
|
||||
/// See <https://www.sqlite.org/fts3.html#the_matchinfo_option>
|
||||
public var matchinfo: String?
|
||||
|
||||
/// Support for the FTS5 `prefix` option
|
||||
@@ -210,9 +225,13 @@ public final class FTS4TableDefinition {
|
||||
/// t.column("content")
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#the_prefix_option
|
||||
/// See <https://www.sqlite.org/fts3.html#the_prefix_option>
|
||||
public var prefixes: Set<Int>?
|
||||
|
||||
init(configuration: VirtualTableConfiguration) {
|
||||
self.configuration = configuration
|
||||
}
|
||||
|
||||
/// Appends a table column.
|
||||
///
|
||||
/// try db.create(virtualTable: "document", using: FTS4()) { t in
|
||||
@@ -234,7 +253,7 @@ public final class FTS4TableDefinition {
|
||||
/// content in the external table. SQL triggers make sure that the
|
||||
/// full-text table is kept up to date with the external table.
|
||||
///
|
||||
/// See https://sqlite.org/fts5.html#external_content_tables
|
||||
/// See <https://sqlite.org/fts5.html#external_content_tables>
|
||||
public func synchronize(withTable tableName: String) {
|
||||
contentMode = .synchronized(contentTable: tableName)
|
||||
}
|
||||
@@ -249,7 +268,7 @@ public final class FTS4TableDefinition {
|
||||
/// t.column("content") // FTS4ColumnDefinition
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html
|
||||
/// See <https://www.sqlite.org/fts3.html>
|
||||
public final class FTS4ColumnDefinition {
|
||||
fileprivate let name: String
|
||||
fileprivate var isIndexed: Bool
|
||||
@@ -268,7 +287,7 @@ public final class FTS4ColumnDefinition {
|
||||
/// t.column("b").notIndexed()
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#the_notindexed_option
|
||||
/// See <https://www.sqlite.org/fts3.html#the_notindexed_option>
|
||||
///
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult
|
||||
@@ -284,7 +303,7 @@ public final class FTS4ColumnDefinition {
|
||||
/// t.column("lid").asLanguageId()
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#the_languageid_option
|
||||
/// See <https://www.sqlite.org/fts3.html#the_languageid_option>
|
||||
///
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult
|
||||
|
||||
Loaded 100 of 279 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user