mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-06 05:28:44 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
baeba0dea3 | ||
|
|
3dc31ad638 | ||
|
|
4201e2a611 | ||
|
|
d9f6fa7de6 | ||
|
|
d0146762bc | ||
|
|
7e8f2e2fbc | ||
|
|
497f4b65ef | ||
|
|
03c44778ba | ||
|
|
0cc744ae16 | ||
|
|
fae3862547 | ||
|
|
70a222f3c9 | ||
|
|
5676adca99 | ||
|
|
3a77ca68c4 | ||
|
|
248437d1d6 | ||
|
|
afcde4609e | ||
|
|
2e98974373 | ||
|
|
086a33fd62 | ||
|
|
33359dd435 | ||
|
|
574d71b50c | ||
|
|
c806b706d4 | ||
|
|
c3b8c0f7e9 | ||
|
|
a1cd622892 | ||
|
|
dea3ee0b84 | ||
|
|
5c64348ea8 | ||
|
|
262ac2c476 | ||
|
|
dbfbe30749 | ||
|
|
70437bd4cb | ||
|
|
2d30b5ea1c | ||
|
|
5414111bed | ||
|
|
9168bac16e | ||
|
|
8760d36f6c | ||
|
|
141b870bc0 | ||
|
|
5e4406e78c | ||
|
|
c5426bfcf7 | ||
|
|
76561a567f | ||
|
|
8288f0c751 | ||
|
|
7dc008db8b | ||
|
|
86bb4a27a4 | ||
|
|
f2d9f50930 | ||
|
|
b9af7e6a25 | ||
|
|
00825748ff | ||
|
|
fe0edde4a9 | ||
|
|
edfea91920 | ||
|
|
319e6bcdc8 | ||
|
|
274f73e040 | ||
|
|
fab37838b2 | ||
|
|
a5a3610bf6 | ||
|
|
07e600163c | ||
|
|
14a5dc5489 | ||
|
|
46c2b94425 | ||
|
|
9a1dc7f292 | ||
|
|
c68fc37959 | ||
|
|
aa1f555e05 | ||
|
|
699e64c610 | ||
|
|
e8c1392314 | ||
|
|
c1ae47d188 | ||
|
|
13a9f1113a | ||
|
|
c4ad86863f | ||
|
|
8300a618f8 | ||
|
|
52f0038262 | ||
|
|
31710ce91c | ||
|
|
a9c75652e1 | ||
|
|
3e13e5be57 | ||
|
|
c27979a210 | ||
|
|
37d7c84bc3 | ||
|
|
62f5c8fc2f | ||
|
|
289c449dff | ||
|
|
e7b7b603d2 | ||
|
|
e7e342600b | ||
|
|
db6e3b8371 | ||
|
|
79ed15c38c | ||
|
|
6f175dcafb | ||
|
|
ca70a10bd4 | ||
|
|
ae3319e9f9 | ||
|
|
5112cb24f5 | ||
|
|
c6bbccc02e | ||
|
|
93ec4d2515 | ||
|
|
955dc6094b | ||
|
|
bd694cbc53 | ||
|
|
c115a035ec | ||
|
|
288144f347 | ||
|
|
3bdfdaa40a | ||
|
|
22949813af | ||
|
|
5c98b01484 | ||
|
|
ea5e1cd0db | ||
|
|
b5d9955442 | ||
|
|
feb5cb35b4 | ||
|
|
654c7083eb | ||
|
|
a0457928b3 | ||
|
|
4df535a3a9 | ||
|
|
0b251ec4e0 | ||
|
|
7704a9ac41 | ||
|
|
59031893ff | ||
|
|
fcfa044320 | ||
|
|
f95658e7ce | ||
|
|
2c16fcaa99 | ||
|
|
4e638016e1 | ||
|
|
5d811c0e68 | ||
|
|
9f1f51637a | ||
|
|
7c16ffcdf8 | ||
|
|
7ca582719b | ||
|
|
e4b83baa53 | ||
|
|
ac6b2933a8 | ||
|
|
92758fa51d | ||
|
|
acd06a4f5a | ||
|
|
eec6b17398 | ||
|
|
15fbf02647 | ||
|
|
c296be5057 | ||
|
|
129e178ee0 | ||
|
|
1e5caa62a8 | ||
|
|
420ed0764b | ||
|
|
ce6bbb2885 | ||
|
|
87d6c5dd29 | ||
|
|
dccd456497 | ||
|
|
520bdd64e6 | ||
|
|
72608fd016 | ||
|
|
69b51ffbd5 | ||
|
|
c9044ea07b | ||
|
|
362c40326f | ||
|
|
28d0793688 | ||
|
|
abdc2000c4 | ||
|
|
3d845b1e9f | ||
|
|
bae8c97df4 | ||
|
|
452c1d4b92 | ||
|
|
9990e6e2a6 | ||
|
|
8d0dc3eb78 | ||
|
|
0a2a3c75c1 | ||
|
|
830e6acb4f | ||
|
|
1da85dff58 | ||
|
|
dd40e3be5b | ||
|
|
224d6488a9 | ||
|
|
cac31d3294 | ||
|
|
951d5fa58d | ||
|
|
7a4f0778df | ||
|
|
5aff4d29fc | ||
|
|
402b7001ee | ||
|
|
f7d0979fb1 | ||
|
|
2289ed9d95 | ||
|
|
dfcb44016f | ||
|
|
37a434a615 | ||
|
|
0ddcf1e401 | ||
|
|
0aa673f24e | ||
|
|
b3a24daa2f | ||
|
|
8c6954cd75 | ||
|
|
283f08de07 | ||
|
|
d96543ddeb | ||
|
|
4b320f3cb5 | ||
|
|
69a6d3e3f3 | ||
|
|
93d4587732 | ||
|
|
7481b9788a | ||
|
|
acf3e0b397 | ||
|
|
88ae0fa059 | ||
|
|
a1e63d9028 | ||
|
|
2a1ad8d31c | ||
|
|
ba7cd2160f | ||
|
|
8e50383371 | ||
|
|
ffc5352840 | ||
|
|
53e849cbec | ||
|
|
b71d57d7ec | ||
|
|
4fe2b2542f | ||
|
|
8c7895d8ab | ||
|
|
ad15f4dc59 | ||
|
|
c4ef161a83 | ||
|
|
bb48025947 | ||
|
|
389a7f28c4 | ||
|
|
714cc1c734 | ||
|
|
8d0da7f870 | ||
|
|
e42e74103d | ||
|
|
4bcdb91895 | ||
|
|
938977bbca | ||
|
|
581c1c46e2 | ||
|
|
768b2ab620 | ||
|
|
4eff5ab357 | ||
|
|
888892b92f | ||
|
|
ba4f146c9c | ||
|
|
8359dd2ae2 | ||
|
|
0be80db8f9 | ||
|
|
72de142519 | ||
|
|
0a7468f56d | ||
|
|
33b5c6c616 | ||
|
|
4003d7600d | ||
|
|
a7122ba8bb | ||
|
|
dc8c85d3db | ||
|
|
fc1b4a6f35 | ||
|
|
af42623654 | ||
|
|
ab1a672336 | ||
|
|
4501d7dcde | ||
|
|
5d463d6bff | ||
|
|
9c8a9fbe32 | ||
|
|
1a89b2eae5 | ||
|
|
fd65e72bbb | ||
|
|
33e8d0875d | ||
|
|
19e75576a8 | ||
|
|
980860b2e9 | ||
|
|
eee3e36238 | ||
|
|
eaadd37e87 | ||
|
|
a1e508b1df | ||
|
|
2c8f9dffdd | ||
|
|
92fd3bf8ae | ||
|
|
c940675bf3 | ||
|
|
2a147d5029 | ||
|
|
0d236ae32c | ||
|
|
cf4654108e | ||
|
|
7e9eed9374 | ||
|
|
383581938a | ||
|
|
df50da9024 | ||
|
|
d3a65303a1 | ||
|
|
9a2bf923d2 | ||
|
|
9b27c0c651 | ||
|
|
2af85e7347 | ||
|
|
071f0f4443 | ||
|
|
903e8c96aa | ||
|
|
79a5fb9c15 | ||
|
|
46ef4b27bb | ||
|
|
1838797d38 | ||
|
|
c7d500b8ba | ||
|
|
95a09cb644 | ||
|
|
c6ab92e60a | ||
|
|
c0d5f3019b | ||
|
|
b09d5c3833 | ||
|
|
3eff1b48b1 | ||
|
|
a12fffc4e7 | ||
|
|
94715130fc | ||
|
|
313188ca0e | ||
|
|
5a68b008c6 | ||
|
|
6fe9098c76 | ||
|
|
631a914acd | ||
|
|
d1f24c9722 | ||
|
|
7b76c9319a | ||
|
|
63083c5d1e | ||
|
|
c51a3cd624 | ||
|
|
1fadb7485a | ||
|
|
58e05d13d1 | ||
|
|
d8c9692d4d | ||
|
|
f83ffd3a25 | ||
|
|
d12ff2a92b | ||
|
|
8709d6f9a9 | ||
|
|
e2806c55ff | ||
|
|
08d6c843d6 | ||
|
|
0da3726a89 | ||
|
|
36676bcad3 | ||
|
|
1509e1e9a8 | ||
|
|
4c71dd9ebe | ||
|
|
ef8d0d6334 | ||
|
|
7477b7a173 | ||
|
|
246f36821b | ||
|
|
d567ee60bf | ||
|
|
3a157d2808 | ||
|
|
7d0c2f9ef8 | ||
|
|
f356f8734a | ||
|
|
5b7f4a7ff5 | ||
|
|
e10efca17a | ||
|
|
578b9a5275 | ||
|
|
63304b3d12 | ||
|
|
39f6ca0035 | ||
|
|
5e3c62c963 | ||
|
|
6966600223 | ||
|
|
e028cbb6d5 | ||
|
|
8b3c3f48a8 | ||
|
|
2d84e72097 | ||
|
|
d91fe7b633 | ||
|
|
090df10831 | ||
|
|
f21037bb69 | ||
|
|
f3041bcc9a | ||
|
|
67b1225dfa | ||
|
|
23f2e0371e | ||
|
|
a3d8df222f | ||
|
|
632ef3707c | ||
|
|
79dc099e6d | ||
|
|
75035fb40c | ||
|
|
b4887b661c | ||
|
|
e8835af363 | ||
|
|
1fabe08332 | ||
|
|
c2e3638e8d | ||
|
|
71abced420 | ||
|
|
ac00046b07 | ||
|
|
38b5204713 | ||
|
|
4b173dece5 | ||
|
|
8ce2c09b52 | ||
|
|
8125574f8f | ||
|
|
8974360cac | ||
|
|
6e48cc1524 | ||
|
|
a1ea75ca34 | ||
|
|
81d2f21093 | ||
|
|
fd73a31abc | ||
|
|
1583ac0c08 | ||
|
|
cafbecd8af | ||
|
|
78c36612b7 | ||
|
|
a95385c740 | ||
|
|
a58ebf7c48 | ||
|
|
13623575ff | ||
|
|
87c5f913b8 | ||
|
|
41172d7967 | ||
|
|
820bc87cfe | ||
|
|
2901acfb41 | ||
|
|
681460a415 | ||
|
|
19b067405f | ||
|
|
3b494b5737 | ||
|
|
5f11a19296 | ||
|
|
3ff7675eb7 | ||
|
|
3d06841eba | ||
|
|
188c026c6b | ||
|
|
caf051f19d | ||
|
|
c4a3d934a9 | ||
|
|
b19424aa23 | ||
|
|
bc229fa6fd | ||
|
|
9beb5b553b | ||
|
|
667e6a8e06 | ||
|
|
8f9b667c29 | ||
|
|
a8e0c76a30 | ||
|
|
49609ff08e | ||
|
|
efe201e032 | ||
|
|
28c903f7ea | ||
|
|
a5b45031d2 | ||
|
|
42e178b41d | ||
|
|
c3fe2c13f4 | ||
|
|
af8a6872d9 | ||
|
|
f40a5e68ea | ||
|
|
c4ad98426c | ||
|
|
a0e3d4ad69 | ||
|
|
d64bfe1cec | ||
|
|
8a213af2ab | ||
|
|
f02659e5d7 | ||
|
|
bdf943c3d9 | ||
|
|
9f1d5bc631 | ||
|
|
f2b46679a6 | ||
|
|
c5f38af247 | ||
|
|
2bfef4f02d | ||
|
|
07ae50cbb0 | ||
|
|
7f10bf4005 | ||
|
|
9130fe7b38 | ||
|
|
340dcd1748 | ||
|
|
8919bb5810 | ||
|
|
bea98db813 | ||
|
|
05a0130c1e | ||
|
|
e486437865 | ||
|
|
1043516fb7 | ||
|
|
c9b8b81ffb | ||
|
|
99b143a55c | ||
|
|
8401f42f3e | ||
|
|
f69949edea | ||
|
|
62e33f294e | ||
|
|
2a8e48ba63 | ||
|
|
6372bf663f | ||
|
|
ac7cc09bfe | ||
|
|
c9f0d473cf | ||
|
|
8a7ffdbb67 | ||
|
|
d30baaf16c | ||
|
|
1981adeb22 | ||
|
|
8427b8b668 | ||
|
|
6db590a31b | ||
|
|
22faa03a48 | ||
|
|
d3cd0ae85a | ||
|
|
b624955bf3 | ||
|
|
1b20cd14d1 | ||
|
|
baf2f780c9 | ||
|
|
9d1997b6cd | ||
|
|
313baa0064 | ||
|
|
006eee9f51 | ||
|
|
2720caf945 | ||
|
|
62faa57bf0 | ||
|
|
abbdb995e6 | ||
|
|
fd2ae60a65 | ||
|
|
2c4cf2d06b | ||
|
|
0f5ec15d47 | ||
|
|
1c3dfb346f | ||
|
|
b76013d60b | ||
|
|
e3ed95571c | ||
|
|
c749893858 | ||
|
|
9135be3da6 | ||
|
|
9930fd3938 | ||
|
|
c62c3df00d | ||
|
|
0419d67533 | ||
|
|
32d69c5be0 | ||
|
|
c2fb23c69c | ||
|
|
47611e14f7 | ||
|
|
b90f876b5b | ||
|
|
9037d51bc7 | ||
|
|
fb8c68f5e0 | ||
|
|
4995b5bb8c | ||
|
|
c87ebfd4eb | ||
|
|
b9d0dae5ac | ||
|
|
ab2a74285d | ||
|
|
e37ab72182 | ||
|
|
891dec64a0 | ||
|
|
90086789c6 | ||
|
|
2cdcdb9cd6 | ||
|
|
9c6879bd97 | ||
|
|
fc88acc782 | ||
|
|
1578dfe26b | ||
|
|
eb5e5a7069 | ||
|
|
b58cfefa13 | ||
|
|
de4d395aea | ||
|
|
7072bd9f36 | ||
|
|
8e36bc64fd | ||
|
|
4326a705f3 | ||
|
|
eb99e294ed | ||
|
|
27acb2b967 | ||
|
|
9cf5124a52 | ||
|
|
d00282f077 | ||
|
|
2556bedcda | ||
|
|
a569acd12a | ||
|
|
5e6c462708 | ||
|
|
4e0900dffa | ||
|
|
5c61211522 | ||
|
|
0747dc5cf6 | ||
|
|
85099c8ad6 | ||
|
|
72da91a8c7 | ||
|
|
4aced858a8 | ||
|
|
786ab176c9 | ||
|
|
973af107da | ||
|
|
1911ef0172 | ||
|
|
d2e9b340c9 | ||
|
|
5b487d1722 | ||
|
|
a91da59448 | ||
|
|
2846254304 | ||
|
|
5fe765dd29 | ||
|
|
9815f44134 | ||
|
|
3f8969b88f | ||
|
|
4fc7a44a9d | ||
|
|
e132688e00 | ||
|
|
588df57840 | ||
|
|
4a8ca6fdc1 | ||
|
|
2bb2493731 | ||
|
|
c61949ceaf | ||
|
|
3fce1e00c9 | ||
|
|
2f2add1c49 | ||
|
|
697acb103f | ||
|
|
c830e43e8f | ||
|
|
834ef45ca6 | ||
|
|
279faa13e9 | ||
|
|
0309abca6f | ||
|
|
fedee67bda | ||
|
|
a6c3566aa5 | ||
|
|
52fa24e1c4 | ||
|
|
a7ecf41e3b | ||
|
|
e68e5f6265 | ||
|
|
aad5a9b060 | ||
|
|
aa064029ec | ||
|
|
e84060e01c | ||
|
|
f4f72ebb43 | ||
|
|
da51e81e38 | ||
|
|
247cbdd0d0 | ||
|
|
c528740154 | ||
|
|
37b357b050 | ||
|
|
18c376979d | ||
|
|
9cc4357a70 | ||
|
|
f2d35a052f | ||
|
|
221f378d10 | ||
|
|
06a8c8b940 | ||
|
|
eee80b421a | ||
|
|
f6e22c3636 | ||
|
|
20d77fbba5 | ||
|
|
0393ebe012 | ||
|
|
2beddcf77b | ||
|
|
e784ebbcdd | ||
|
|
30ee538dbd | ||
|
|
7939ba6e05 | ||
|
|
2785e69fc1 | ||
|
|
d472c1696d | ||
|
|
d9cfa71fc7 | ||
|
|
715e12912b | ||
|
|
b182fe27f6 | ||
|
|
5594b33933 | ||
|
|
059b8800f6 | ||
|
|
9f687b1848 | ||
|
|
a4a05b1f0a | ||
|
|
1a7b0b0626 | ||
|
|
4c467e46cf | ||
|
|
fa71edeb07 | ||
|
|
4ff436371d | ||
|
|
9d8fa0bc5a | ||
|
|
1a8ecd7889 | ||
|
|
f6614fdfda | ||
|
|
a6055df756 | ||
|
|
5af91c5eab | ||
|
|
41974c4a46 | ||
|
|
f001b5bd76 | ||
|
|
28cf457853 | ||
|
|
8ccc23333d | ||
|
|
d95954d980 | ||
|
|
3506881c2a | ||
|
|
51d127c378 | ||
|
|
2d5dd7ef63 | ||
|
|
ef23ba55a1 | ||
|
|
ffdbf2f3f1 | ||
|
|
56cad83f55 | ||
|
|
719f33f7a7 | ||
|
|
700ffacdb1 | ||
|
|
a6ef4ed55c | ||
|
|
c5da564fb3 | ||
|
|
a6b04ebb64 | ||
|
|
99ba6db257 | ||
|
|
a3cddb72b9 | ||
|
|
2a9e896095 | ||
|
|
89d522d325 | ||
|
|
3c4ff587ca | ||
|
|
e111529035 | ||
|
|
cae1f97032 | ||
|
|
20419834a6 | ||
|
|
5dabc2a20b | ||
|
|
c700f5fc68 | ||
|
|
0b71cf86f2 | ||
|
|
96159bd09c | ||
|
|
bcff802ccb | ||
|
|
376d295853 | ||
|
|
0030ad1804 | ||
|
|
4ec3e0f7d8 | ||
|
|
e36219e408 | ||
|
|
8f8f53a697 | ||
|
|
567292c72f | ||
|
|
b744f73a76 | ||
|
|
da440a5e16 | ||
|
|
017af1d5c3 | ||
|
|
1f5d75d8e9 | ||
|
|
8b80abc701 | ||
|
|
dc75ca4caf | ||
|
|
d7d4c0a54d | ||
|
|
823b094b60 | ||
|
|
06a6c982aa | ||
|
|
1d15ef01f9 | ||
|
|
f72ffcbb43 | ||
|
|
e0f2305cd9 | ||
|
|
210939d2c1 | ||
|
|
2fd071d90e | ||
|
|
badec62cdd | ||
|
|
895cda4de7 | ||
|
|
21fdc9f350 | ||
|
|
398c0ef687 | ||
|
|
3b0a9aef3c | ||
|
|
48ec0916bf | ||
|
|
10af87a7d0 | ||
|
|
96e7996f37 | ||
|
|
0f7af931a9 | ||
|
|
cfd2d80b78 | ||
|
|
0386c01aa9 | ||
|
|
2c39c91ac6 | ||
|
|
0eb51e3e8b | ||
|
|
bb931e9da7 | ||
|
|
7b2e672496 | ||
|
|
cdc6370ee5 | ||
|
|
cc762e4e1d | ||
|
|
ed525bd1d8 | ||
|
|
2b2e92c810 | ||
|
|
44d31ead76 | ||
|
|
ec163e94eb | ||
|
|
ec2ac33fec | ||
|
|
20bda2af26 | ||
|
|
7a49f6293d | ||
|
|
81b21010f1 | ||
|
|
2526e0a2f7 | ||
|
|
af1e8470c9 | ||
|
|
dfd9da68a7 | ||
|
|
5e702234f4 | ||
|
|
9020dcca9a | ||
|
|
930a4e4c1d | ||
|
|
4db77f96b7 | ||
|
|
cc12c046b9 | ||
|
|
f5c63e0997 | ||
|
|
29a26800b7 | ||
|
|
bc5eeb3b3a | ||
|
|
40d02518b0 | ||
|
|
a2556edc69 | ||
|
|
111970fda9 |
No files matched your search
+1
-1
@@ -106,7 +106,7 @@ Pods
|
||||
|
||||
# SPM
|
||||
.build
|
||||
Package.pins
|
||||
Package.resolved
|
||||
Tests/SPM/Packages
|
||||
|
||||
# Ruby
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
3.1
|
||||
4.0
|
||||
+116
-52
@@ -1,3 +1,6 @@
|
||||
# The OS X Build Environment
|
||||
# https://docs.travis-ci.com/user/reference/osx/#Xcode-version
|
||||
|
||||
language: objective-c
|
||||
xcode_project: GRDB.xcodeproj
|
||||
|
||||
@@ -12,140 +15,201 @@ jobs:
|
||||
###########################################
|
||||
## Test GRDB
|
||||
|
||||
# Test GRDBOSX (Xcode 8.3)
|
||||
# Test GRDBOSX (Xcode 9.2)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=GRDBOSX (Xcode 8.3, macOS 10.12)
|
||||
- TID=GRDBOSX (Xcode 9.2, macOS)
|
||||
script: make test_framework_GRDBOSX
|
||||
|
||||
# Test GRDBWatchOS (Xcode 8.3)
|
||||
# Test GRDBWatchOS (Xcode 9.2)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=GRDBWatchOS (Xcode 8.3, watchOS)
|
||||
- TID=GRDBWatchOS (Xcode 9.2, watchOS)
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
# Test GRDBiOS (Xcode 8.3, iOS <MAXIMUM VERSION>)
|
||||
# Test GRDBiOS (Xcode 9.2, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=GRDBiOS (Xcode 8.3, iOS <MAX>)
|
||||
- TID=GRDBiOS (Xcode 9.2, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget
|
||||
|
||||
# Test GRDBiOS (Xcode 8.3, iOS <MINIMUM VERSION>))
|
||||
# Test GRDBiOS (Xcode 9.2, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=GRDBiOS (Xcode 8.3, iOS <MIN>)
|
||||
- TID=GRDBiOS (Xcode 9.2, iOS <MIN>)
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
# Test GRDB [SPM] (Xcode 8.3, macOS 10.12)
|
||||
# Test GRDB [SPM] (Xcode 9.2, macOS)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=GRDB [SPM] (Xcode 8.3, macOS 10.12)
|
||||
- TID=GRDB [SPM] (Xcode 9.2, macOS)
|
||||
script: make test_SPM
|
||||
|
||||
# Test GRDBOSX (Xcode 9.0)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBOSX (Xcode 9.0, macOS)
|
||||
script: make test_framework_GRDBOSX
|
||||
|
||||
# Test GRDBiOS (Xcode 9.0, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBiOS (Xcode 9.0, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget
|
||||
|
||||
###########################################
|
||||
## Test GRDB (Custom SQLite)
|
||||
|
||||
# Test GRDBCustomSQLiteOSX (Xcode 8.3)
|
||||
# Test GRDBCustomSQLiteOSX (Xcode 9.2)
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteOSX (Xcode 8.3, macOS 10.12)
|
||||
- TID=GRDBCustomSQLiteOSX (Xcode 9.2, macOS)
|
||||
script: make test_framework_GRDBCustomSQLiteOSX
|
||||
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 8.3, iOS <MAXIMUM VERSION>)
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 9.2, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 8.3, iOS <MAX>)
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 9.2, iOS <MAX>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget
|
||||
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 8.3, iOS <MINIMUM VERSION>))
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 9.2, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 8.3, iOS <MIN>)
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 9.2, iOS <MIN>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
|
||||
|
||||
# Test GRDBCustomSQLiteOSX (Xcode 9.0)
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteOSX (Xcode 9.0, macOS)
|
||||
script: make test_framework_GRDBCustomSQLiteOSX
|
||||
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 9.0, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 9.0, iOS <MAX>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget
|
||||
|
||||
###########################################
|
||||
## Test GRDB (SQLCipher)
|
||||
|
||||
# Test GRDBCipherOSX (Xcode 8.3)
|
||||
# Test GRDBCipherOSX (Xcode 9.2)
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=GRDBCipherOSX (Xcode 8.3, macOS 10.12)
|
||||
- TID=GRDBCipherOSX (Xcode 9.2, macOS)
|
||||
script: make test_framework_GRDBCipherOSX
|
||||
|
||||
# Test GRDBCipheriOS (Xcode 8.3, iOS <MAXIMUM VERSION>)
|
||||
# Test GRDBCipheriOS (Xcode 9.2, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=GRDBCipheriOS (Xcode 8.3, iOS <MAX>)
|
||||
- TID=GRDBCipheriOS (Xcode 9.2, iOS <MAX>)
|
||||
script: make test_framework_GRDBCipheriOS_maxTarget
|
||||
|
||||
# Test GRDBCipheriOS (Xcode 8.3, iOS <MINIMUM VERSION>))
|
||||
# Test GRDBCipheriOS (Xcode 9.2, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=GRDBCipheriOS (Xcode 8.3, iOS <MIN>)
|
||||
- TID=GRDBCipheriOS (Xcode 9.2, iOS <MIN>)
|
||||
script: make test_framework_GRDBCipheriOS_minTarget
|
||||
|
||||
# Test GRDBCipherOSX (Xcode 9.0)
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBCipherOSX (Xcode 9.0, macOS)
|
||||
script: make test_framework_GRDBCipherOSX
|
||||
|
||||
# Test GRDBCipheriOS (Xcode 9.0, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBCipheriOS (Xcode 9.0, iOS <MAX>)
|
||||
script: make test_framework_GRDBCipheriOS_maxTarget
|
||||
|
||||
|
||||
###########################################
|
||||
## Test Installation Methods
|
||||
|
||||
# Manual Install
|
||||
# Manual Install (Xcode 9.2)
|
||||
- stage: Test Installation
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=Manual Install
|
||||
- TID=Manual Install (Xcode 9.2)
|
||||
script: make test_install_manual
|
||||
|
||||
# Manual Install (GRDBCipher)
|
||||
# Manual Install (GRDBCipher, Xcode 9.2)
|
||||
- stage: Test Installation
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=Manual Install (GRDBCipher)
|
||||
- TID=Manual Install (GRDBCipher, Xcode 9.2)
|
||||
script: make test_install_GRDBCipher
|
||||
|
||||
# Cocoapods Lint
|
||||
# Cocoapods Lint (Xcode 9.2)
|
||||
- stage: Test Installation
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.2
|
||||
install:
|
||||
- gem install cocoapods # Since Travis is not always on latest version
|
||||
env:
|
||||
- TID=Cocoapods
|
||||
- TID=Cocoapods (Xcode 9.2)
|
||||
script: make test_CocoaPodsLint
|
||||
|
||||
# SPM Install
|
||||
# Cocoapods Lint (Xcode 9.0)
|
||||
- stage: Test Installation
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9
|
||||
install:
|
||||
- gem install cocoapods # Since Travis is not always on latest version
|
||||
env:
|
||||
- TID=SPM
|
||||
- TID=Cocoapods (Xcode 9.0)
|
||||
script: make test_CocoaPodsLint
|
||||
|
||||
# SPM Install (Xcode 9.2)
|
||||
- stage: Test Installation
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=SPM (Xcode 9.2)
|
||||
script: make test_install_SPM
|
||||
|
||||
## The following doesn’t work, as `make test_CarthageBuild` does not yet work.
|
||||
## Carthage Build
|
||||
#- stage: Carthage
|
||||
# osx_image: xcode8.3
|
||||
# before_install:
|
||||
# - brew update
|
||||
# - brew outdated carthage || brew upgrade carthage
|
||||
# script: make test_CarthageBuild
|
||||
## Commented out until `make test_CarthageBuild` performs *reliably*.
|
||||
## See https://github.com/groue/GRDB.swift/pull/262
|
||||
# - stage: Test Installation
|
||||
# osx_image: xcode9.2
|
||||
# before_install:
|
||||
# - brew update
|
||||
# - brew outdated carthage || brew upgrade carthage
|
||||
# env:
|
||||
# - TID=Carthages
|
||||
# script: make test_CarthageBuild
|
||||
+861
-4
@@ -1,9 +1,866 @@
|
||||
Release Notes
|
||||
=============
|
||||
|
||||
## 2.9.0
|
||||
|
||||
Released February 25, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v2.8.0...v2.9.0)
|
||||
|
||||
### New
|
||||
|
||||
- **Changes tracking overhaul**: changes tracking, a feature previously restricted to the `Record` class and its subclasses, is now available for all records. And it has a better looking API ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#changes-tracking)).
|
||||
- **Database snapshots**: Database pools can now take database snapshots. A snapshot sees an unchanging database content, as it existed at the moment the snapshot was created ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#database-snapshots)).
|
||||
- **Improved support for joined queries**: more than a set on new APIs, we provide a set of guidelines that will help you deal with your wildest joined queries. Check the new [Joined Queries Support](https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support) documentation chapter.
|
||||
- `Database.columns(in:)` returns information about the columns of a table.
|
||||
- `Request.adapted(_:)` is no longer experimental.
|
||||
- `Configuration.allowsUnsafeTransactions` lets you leave transactions opened between two database accesses (see below).
|
||||
- Support for explicit transaction management, via the new `Database.beginTransaction`, `commit`, and `rollback` methods.
|
||||
|
||||
|
||||
### Fixed
|
||||
|
||||
- It is now a programmer error to leave a transaction opened at the end of a database access block:
|
||||
|
||||
```swift
|
||||
// Fatal error: A transaction has been left opened at the end of a database access
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.beginTransaction()
|
||||
}
|
||||
```
|
||||
|
||||
One can still opt-in for the unsafe behavior by setting the new `allowsUnsafeTransactions` configuration flag:
|
||||
|
||||
```swift
|
||||
var config = Configuration()
|
||||
config.allowsUnsafeTransactions = true
|
||||
let dbQueue = DatabaseQueue(configuration: config)
|
||||
|
||||
// OK
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.beginTransaction()
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Deprecated
|
||||
|
||||
- `Database.columnCount(in:)` is deprecated. Use `db.columns(in:).count` instead.
|
||||
- `RecordBox`, introduced in [2.7.0](#270), was ill-advised. It has been deprecated. Use [changes tracking](https://github.com/groue/GRDB.swift/blob/master/README.md#changes-tracking) methods on the Persistable protocol instead.
|
||||
- `Record.hasPersistentChangedValues` has been deprecated, renamed `hasDatabaseChanges`.
|
||||
- `Record.persistentChangedValues` has been deprecated, renamed `databaseChanges`.
|
||||
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
- The [Changes Tracking](https://github.com/groue/GRDB.swift/blob/master/README.md#changes-tracking) chapter has been updated for the new universal support for record changes.
|
||||
- A new [Database Snapshots](https://github.com/groue/GRDB.swift/blob/master/README.md#database-snapshots) chapter has been added.
|
||||
- The [Concurrency](https://github.com/groue/GRDB.swift/blob/master/README.md#concurrency) chapter has been updated for database snapshots.
|
||||
- A new [Differences between Database Queues and Pools](https://github.com/groue/GRDB.swift/blob/master/README.md#differences-between-database-queues-and-pools) chapter has been added, that attempts at visually show how much database pools are different from database queues.
|
||||
- A new [Joined Queries Support](https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support) chapter has been added.
|
||||
- The [Row Adapters](https://github.com/groue/GRDB.swift/blob/master/README.md#row-adapters) chapter has been made consistent with the new chapter on joined queries.
|
||||
- The [Codable Records](https://github.com/groue/GRDB.swift/blob/master/README.md#codable-records) chapter has been made consistent with the new chapter on joined queries.
|
||||
- The [Database Schema Introspection](https://github.com/groue/GRDB.swift/blob/master/README.md#database-schema-introspection) has been updated for `Database.columns(in:)`
|
||||
|
||||
|
||||
### API diff
|
||||
|
||||
```diff
|
||||
+struct ColumnInfo {
|
||||
+ let name: String
|
||||
+ let type: String
|
||||
+ let isNotNull: Bool
|
||||
+ let defaultValueSQL: String?
|
||||
+ let primaryKeyIndex: Int
|
||||
+}
|
||||
|
||||
struct Configuration {
|
||||
+ var allowsUnsafeTransactions: Bool
|
||||
}
|
||||
|
||||
class Database {
|
||||
+ @available(*, deprecated, message: "Use db.columns(in: tableName).count instead")
|
||||
func columnCount(in tableName: String) throws -> Int
|
||||
+ func columns(in tableName: String) throws -> [ColumnInfo]
|
||||
+ func beginTransaction(_ kind: TransactionKind? = nil) throws
|
||||
+ func rollback() throws
|
||||
+ func commit() throws
|
||||
}
|
||||
|
||||
class DatabasePool {
|
||||
+ func makeSnapshot() throws -> DatabaseSnapshot
|
||||
}
|
||||
|
||||
+class DatabaseSnapshot: DatabaseReader { }
|
||||
|
||||
extension MutablePersistable {
|
||||
+ @discardableResult
|
||||
+ func updateChanges(_ db: Database, from record: MutablePersistable) throws -> Bool
|
||||
+ func databaseEqual(_ record: Self) -> Bool
|
||||
+ func databaseChanges(from record: MutablePersistable) -> [String: DatabaseValue]
|
||||
}
|
||||
class Record {
|
||||
- final func updateChanges(_ db: Database) throws
|
||||
+ @discardableResult
|
||||
+ final func updateChanges(_ db: Database) throws -> Bool
|
||||
}
|
||||
|
||||
+@available(*, deprecated, message: "Prefer changes methods defined on the MutablePersistable protocol: databaseEqual(_:), databaseChanges(from:), updateChanges(from:)")
|
||||
class RecordBox: Record { }
|
||||
|
||||
class Row {
|
||||
+ var unscoped: Row
|
||||
+ var containsNonNullValue: Bool
|
||||
+ func hasNull(atIndex index: Int) -> Bool
|
||||
+ subscript<Record: RowConvertible>(_ scope: String) -> Record
|
||||
+ subscript<Record: RowConvertible>(_ scope: String) -> Record?
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
+ static func selectionSQL(alias: String? = nil) -> String
|
||||
+ static func numberOfSelectedColumns(_ db: Database) throws -> Int
|
||||
}
|
||||
|
||||
+struct EmptyRowAdapter: RowAdapter { }
|
||||
|
||||
struct ScopeAdapter {
|
||||
+ init(base: RowAdapter, scopes: [String: RowAdapter])
|
||||
}
|
||||
|
||||
+func splittingRowAdapters(columnCounts: [Int]) -> [RowAdapter]
|
||||
```
|
||||
|
||||
|
||||
## 2.8.0
|
||||
|
||||
Released January 29, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v2.7.0...v2.8.0)
|
||||
|
||||
**New**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.22.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- The FTS5 full-text search engine has been enhanced with [initial token queries](https://sqlite.org/fts5.html#carrotq), and FTS5Pattern has gained a new initializer: `FTS5Pattern(matchingPrefixPhrase:)`
|
||||
- The `Cursor` protocol is extended with more methods inspired by the standard Sequence protocol: `drop(while:)`, `dropFirst()`, `dropFirst(_:)`, `dropLast()`, `dropLast(_:)`, `joined(separator:)`, `prefix(_:)`, `max()`, `max(by:)`, `min()`, `min(by:)`, `prefix(while:)`, `reduce(into:_:)`, `suffix(_:)`,
|
||||
|
||||
|
||||
## 2.7.0
|
||||
|
||||
Released January 21, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v2.6.1...v2.7.0)
|
||||
|
||||
**New**
|
||||
|
||||
- The new RecordBox class brings changes tracking to any record type ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#recordbox-class)):
|
||||
|
||||
```swift
|
||||
// A regular record struct
|
||||
struct Player: RowConvertible, MutablePersistable { ... }
|
||||
|
||||
try dbQueue.inDatabase { db in
|
||||
// Fetch a boxed player
|
||||
if let boxedPlayer = try RecordBox<Player>.fetchOne(db, key: 1) {
|
||||
// boxedPlayer.value is Player
|
||||
boxedPlayer.value.score = 300
|
||||
|
||||
if boxedPlayer.hasPersistentChangedValues {
|
||||
print("player has been modified")
|
||||
}
|
||||
|
||||
// Does nothing if player has not been modified:
|
||||
try boxedPlayer.updateChanges(db)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 2.6.1
|
||||
|
||||
Released January 19, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v2.6.0...v2.6.1)
|
||||
|
||||
**Fixed**
|
||||
|
||||
- Fixed a crash that could happen when a transaction observer uses the `stopObservingDatabaseChangesUntilNextTransaction()` method.
|
||||
|
||||
|
||||
## 2.6.0
|
||||
|
||||
Released January 18, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v2.5.0...v2.6.0)
|
||||
|
||||
### New
|
||||
|
||||
- Database observation has been enhanced:
|
||||
|
||||
- `TransactionObserver.stopObservingDatabaseChangesUntilNextTransaction()` allows transaction observers to stop observing the database for the remaining extent of a transaction.
|
||||
- GRDB no longer prevents the [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt) when no transaction observers are interested in deleted rows.
|
||||
- FetchedRecordsController now avoids checking for changes in untracked rowIds.
|
||||
- `DatabaseRegion` is a new public type that helps transaction observers recognize impactful database changes. This type is not documented in the main documentation. For more information, see [DatabaseRegion reference](http://groue.github.io/GRDB.swift/docs/2.6/Structs/DatabaseRegion.html), and look at [FetchedRecordsController implementation](https://github.com/groue/GRDB.swift/blob/master/GRDB/Record/FetchedRecordsController.swift).
|
||||
- `TransactionObserver` protocol provides default implementations for rarely used callbacks.
|
||||
|
||||
- `Row` adopts RandomAccessCollection
|
||||
|
||||
### API diff
|
||||
|
||||
```diff
|
||||
extension TransactionObserver {
|
||||
+ func stopObservingDatabaseChangesUntilNextTransaction()
|
||||
+
|
||||
+ // Default implementation
|
||||
+ func databaseWillCommit() throws
|
||||
+
|
||||
+ #if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
+ // Default implementation
|
||||
+ func databaseWillChange(with event: DatabasePreUpdateEvent)
|
||||
+ #endif
|
||||
}
|
||||
|
||||
+struct DatabaseRegion: Equatable {
|
||||
+ var isEmpty: Bool
|
||||
+
|
||||
+ init()
|
||||
+
|
||||
+ func union(_ other: DatabaseRegion) -> DatabaseRegion
|
||||
+ mutating func formUnion(_ other: DatabaseRegion)
|
||||
+
|
||||
+ func isModified(byEventsOfKind eventKind: DatabaseEventKind) -> Bool
|
||||
+ func isModified(by event: DatabaseEvent) -> Bool
|
||||
+}
|
||||
|
||||
class SelectStatement {
|
||||
+ var fetchedRegion: DatabaseRegion
|
||||
+
|
||||
+ @available(*, deprecated, renamed:"DatabaseRegion")
|
||||
+ typealias SelectionInfo = DatabaseRegion
|
||||
+
|
||||
+ @available(*, deprecated, renamed:"fetchedRegion")
|
||||
+ var selectionInfo: DatabaseRegion
|
||||
}
|
||||
|
||||
enum DatabaseEventKind {
|
||||
- func impacts(_ selectionInfo: SelectStatement.SelectionInfo) -> Bool
|
||||
+ @available(*, deprecated, message: "Use DatabaseRegion.isModified(byEventsOfKind:) instead")
|
||||
+ func impacts(_ region: DatabaseRegion) -> Bool
|
||||
}
|
||||
|
||||
protocol Request {
|
||||
+ // Default implementation
|
||||
+ func fetchedRegion(_ db: Database) throws -> DatabaseRegion
|
||||
}
|
||||
|
||||
+extension Row: RandomAccessCollection {
|
||||
+}
|
||||
+extension RowIndex: Strideable {
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 2.5.0
|
||||
|
||||
Released January 11, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v2.4.2...v2.5.0)
|
||||
|
||||
### Fixed
|
||||
|
||||
- [Transaction observers](https://github.com/groue/GRDB.swift/blob/master/README.md#transactionobserver-protocol) used to be notified of some database changes they were not interested into, in case of complex statements with side effects (foreign key cascades or sql triggers). This has been fixed.
|
||||
|
||||
|
||||
### New
|
||||
|
||||
- The query interface has learned to build requests from any key (primary keys and unique keys) ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#fetching-by-key)):
|
||||
|
||||
```swift
|
||||
// SELECT * FROM players WHERE id = 1
|
||||
let request = Player.filter(key: 1)
|
||||
let player = try request.fetchOne(db) // Player?
|
||||
|
||||
// SELECT * FROM countries WHERE isoCode IN ('FR', 'US')
|
||||
let request = Country.filter(keys: ["FR", "US"])
|
||||
let countries = try request.fetchAll(db) // [Country]
|
||||
|
||||
// SELECT * FROM players WHERE email = 'arthur@example.com'
|
||||
let request = Player.filter(key: ["email": "arthur@example.com"])
|
||||
let player = try request.fetchOne(db) // Player?
|
||||
```
|
||||
|
||||
This feature has been introduced in order to ease the use of [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB):
|
||||
|
||||
```swift
|
||||
// New
|
||||
Player.filter(key: 1).rx
|
||||
.fetchOne(in: dbQueue)
|
||||
.subscribe(onNext: { player: Player? in
|
||||
print("Player 1 has changed")
|
||||
})
|
||||
```
|
||||
|
||||
|
||||
### API diff
|
||||
|
||||
```diff
|
||||
extension TableMapping {
|
||||
+ static func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> QueryInterfaceRequest<Self>
|
||||
+ static func filter<Sequence: Swift.Sequence>(keys: Sequence) -> QueryInterfaceRequest<Self> where Sequence.Element: DatabaseValueConvertible
|
||||
+ static func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest<Self>
|
||||
+ static func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest<Self>
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest where T: TableMapping {
|
||||
+ func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> QueryInterfaceRequest<T>
|
||||
+ func filter<Sequence: Swift.Sequence>(keys: Sequence) -> QueryInterfaceRequest<T> where Sequence.Element: DatabaseValueConvertible
|
||||
+ func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest<T>
|
||||
+ func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest<T>
|
||||
}
|
||||
|
||||
extension RowConvertible where Self: TableMapping {
|
||||
- static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Self?
|
||||
+ static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]?) throws -> Self?
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 2.4.2
|
||||
|
||||
Released January 6, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v2.4.1...v2.4.2)
|
||||
|
||||
**Fixed**
|
||||
|
||||
- When using a database pool, the schema introspection methods could return wrong values whenever the database schema was concurrently read and modified. This has been fixed.
|
||||
- `DatabasePool.readFromCurrentState` no longer accepts to spawn a reader when a transaction is currently opened on the writer connection.
|
||||
|
||||
|
||||
## 2.4.1
|
||||
|
||||
Released December 16, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.4.0...v2.4.1)
|
||||
|
||||
**Fixed**
|
||||
|
||||
- [#284](https://github.com/groue/GRDB.swift/pull/284): fixes a misuse of the sqlite3_config() function when configuring the global SQLite [Error Log](https://github.com/groue/GRDB.swift/blob/master/README.md#error-log)
|
||||
|
||||
|
||||
## 2.4.0
|
||||
|
||||
Released December 3, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.3.1...v2.4.0)
|
||||
|
||||
**New**
|
||||
|
||||
- [#280](https://github.com/groue/GRDB.swift/pull/280): It is now possible to add an untyped column to an existing table.
|
||||
|
||||
```swift
|
||||
try db.alter(table: "players") { t in
|
||||
t.add(column: "score")
|
||||
}
|
||||
```
|
||||
|
||||
- [#281](https://github.com/groue/GRDB.swift/pull/280): The `Database.dropFTS4SynchronizationTriggers` & `Database.dropFTS5SynchronizationTriggers` method help cleaning up synchronized full-text table ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#deleting-synchronized-full-text-tables))
|
||||
|
||||
**Breaking Change**
|
||||
|
||||
- [#282](https://github.com/groue/GRDB.swift/issues/282): This version comes with a breaking change that affects users who manually embed the GRDBCipher and GRDBCustom frameworks in their projects. This change does not affect users of the GRDB framework, or users of GRDBCipher through CocoaPods. Now, instead of embedding the GRDB.xcodeproj project, you have to embed the GRDBCipher.xcodeproj or GRDBCustom.xcodeproj. Please have a look at the updated [Encryption](https://github.com/groue/GRDB.swift/blob/master/README.md#encryption) and [Custom SQLite Builds](https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md) documentation chapters.
|
||||
|
||||
|
||||
## 2.3.1
|
||||
|
||||
Released November 8, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.3.0...v2.3.1)
|
||||
|
||||
**Fixed**
|
||||
|
||||
- GRDB 2.2.0 has introduced a fix in the way [transaction observers](https://github.com/groue/GRDB.swift/blob/master/README.md#transactionobserver-protocol) are notified of empty deferred transactions (`BEGIN; COMMIT;`). That fix was incomplete, and inconsistent.
|
||||
|
||||
Now all transactions are notified, without any exception, including:
|
||||
|
||||
```swift
|
||||
try db.execute("BEGIN; COMMIT;")
|
||||
try db.execute("SAVEPOINT foo; RELEASE SAVEPOINT foo;")
|
||||
```
|
||||
|
||||
[Rationale](https://github.com/groue/GRDB.swift/commit/820bc87cfeee701743da852f3634e2c695e911ee#diff-3e791e9db648cd302590c9b86c70757fR376)
|
||||
|
||||
|
||||
## 2.3.0
|
||||
|
||||
Released November 5, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.2.0...v2.3.0)
|
||||
|
||||
**New**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.21.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
|
||||
|
||||
## 2.2.0
|
||||
|
||||
Released October 31, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.1.0...v2.2.0)
|
||||
|
||||
**New**
|
||||
|
||||
- `Database.viewExists(_:)` returns whether a view exists in the database.
|
||||
- `Database.triggerExists(_:)` returns whether a trigger exists in the database.
|
||||
|
||||
**Fixed**
|
||||
|
||||
- `DROP VIEW` statements would not drop views ([#267](https://github.com/groue/GRDB.swift/issues/267))
|
||||
- GRDB used to incorrectly send incomplete transaction notifications to [transaction observers](https://github.com/groue/GRDB.swift/blob/master/README.md#transactionobserver-protocol) in the case of empty deferred transactions. This is no longer the case. Since empty deferred transactions have SQLite consider that no transaction started at all, they are no longer notified to transaction observers:
|
||||
|
||||
```sql
|
||||
-- Nothing happens, and thus no notification is sent
|
||||
BEGIN TRANSACTION
|
||||
COMMIT
|
||||
```
|
||||
|
||||
Those empty deferred transactions still count for the [afterNextTransactionCommit](https://github.com/groue/GRDB.swift/blob/master/README.md#after-commit-hook) database method, and the `.nextTransaction` [observation extent](https://github.com/groue/GRDB.swift/blob/master/README.md#observation-extent).
|
||||
|
||||
|
||||
## 2.1.0
|
||||
|
||||
Released October 24, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.0.3...v2.1.0)
|
||||
|
||||
### New
|
||||
|
||||
- GRDBCipher can now build from command line ([groue/sqlcipher/pull/1](https://github.com/groue/sqlcipher/pull/1) by [Darren Clark](https://github.com/darrenclark))
|
||||
- Upgrade custom SQLite builds to [v3.20.1](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- The new method `Request.asSQLRequest` allows to inspect the sql and arguments of any request:
|
||||
|
||||
```swift
|
||||
let request = Player.all()
|
||||
let sql = try request.asSQLRequest(db).sql
|
||||
print(sql) // Prints "SELECT * FROM players"
|
||||
```
|
||||
|
||||
- StatementArguments adopts Equatable
|
||||
|
||||
|
||||
### Fixed
|
||||
|
||||
- `DROP TABLE` statements would not drop temporary tables.
|
||||
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
- New FAQ: [How do I create a database in my application?](https://github.com/groue/GRDB.swift/blob/master/README.md#how-do-i-create-a-database-in-my-application)
|
||||
- New FAQ: [How do I print a request as SQL?](https://github.com/groue/GRDB.swift/blob/master/README.md#how-do-i-print-a-request-as-sql)
|
||||
- The [Codable Record](https://github.com/groue/GRDB.swift/blob/master/README.md#codable-records) chapter has been enhanced with more information and sample code.
|
||||
|
||||
|
||||
### API diff
|
||||
|
||||
```diff
|
||||
extension Request {
|
||||
+ func asSQLRequest(_ db: Database, cached: Bool = false) throws -> SQLRequest
|
||||
}
|
||||
struct SQLRequest {
|
||||
+ let sql: String
|
||||
+ let arguments: StatementArguments?
|
||||
+ let adapter: RowAdapter?
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 2.0.3
|
||||
|
||||
Released October 9, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.0.2...v2.0.3)
|
||||
|
||||
**Fixed**: Record types that conform to Encodable now encode their null columns.
|
||||
|
||||
|
||||
## 2.0.2
|
||||
|
||||
Released October 5, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.0.1...v2.0.2)
|
||||
|
||||
**Fixed**: `DROP TABLE` statements would not drop tables when run through a prepared statement.
|
||||
|
||||
|
||||
## 2.0.1
|
||||
|
||||
Released September 17, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.0...v2.0.1)
|
||||
|
||||
**Fixed**: restored support for Swift Package Manager
|
||||
|
||||
|
||||
## 2.0
|
||||
|
||||
Released September 16, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v1.3.0...v2.0)
|
||||
|
||||
**GRDB 2.0 brings support for Swift 4.** Notable changes are:
|
||||
|
||||
- **Use subscript notation when extracting row values** ([documentation](https://github.com/groue/GRDB.swift#column-values)):
|
||||
|
||||
```swift
|
||||
let name: String = row[0] // 0 is the leftmost column
|
||||
let name: String = row["name"] // Leftmost matching column - lookup is case-insensitive
|
||||
let name: String = row[Column("name")] // Using query interface's Column
|
||||
```
|
||||
|
||||
- **Support for the `Codable` protocol** ([documentation](https://github.com/groue/GRDB.swift#codable-records))
|
||||
|
||||
Record types that adopt the standard `Codable` protocol are granted with automatic adoption of GRDB record protocols. This means that you no longer have to write boilerplate code :tada::
|
||||
|
||||
```swift
|
||||
struct Player : RowConvertible, Persistable, Codable {
|
||||
static let databaseTableName = "players"
|
||||
let name: String
|
||||
let score: Int
|
||||
}
|
||||
|
||||
// Automatically derived:
|
||||
//
|
||||
// extension Player {
|
||||
// init(row: Row) {
|
||||
// name = row["name"]
|
||||
// score = row["score"]
|
||||
// }
|
||||
//
|
||||
// func encode(to container: inout PersistenceContainer) {
|
||||
// container["name"] = name
|
||||
// container["score"] = score
|
||||
// }
|
||||
// }
|
||||
|
||||
try dbQueue.inDatabase { db in
|
||||
let arthur = Player(name: "Arthur", score: 100)
|
||||
try arthur.insert(db)
|
||||
let players = try Player.fetchAll(db) // [Players]
|
||||
}
|
||||
```
|
||||
|
||||
- **Records can now specify the columns they feed from** ([documentation](https://github.com/groue/GRDB.swift#columns-selected-by-a-request)).
|
||||
|
||||
In previous versions of GRDB, `SELECT *` was the norm. GRDB 2.0 introduces `databaseSelection`, which allows any type to define its preferred set of columns:
|
||||
|
||||
```swift
|
||||
struct Player : RowConvertible, TableMapping {
|
||||
let id: Int64
|
||||
let name: String
|
||||
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
static let name = Column("name")
|
||||
}
|
||||
|
||||
init(row: Row) {
|
||||
id = row[Columns.id]
|
||||
name = row[Columns.name]
|
||||
}
|
||||
|
||||
static let databaseTableName = "players"
|
||||
static let databaseSelection: [SQLSelectable] = [Columns.id, Columns.name]
|
||||
}
|
||||
|
||||
// SELECT id, name FROM players
|
||||
let players = Player.fetchAll(db)
|
||||
```
|
||||
|
||||
- **Record protocols have more precise semantics**: RowConvertible *reads database rows*, TableMapping *builds SQL requests*, and Persistable *writes* ([documentation](https://github.com/groue/GRDB.swift#record-protocols-overview)).
|
||||
|
||||
This means that with GRDB 2.0, being able to write `Player.fetchAll(db)` does not imply that `Player.deleteAll(db)` is available: you have a better control on the abilities of your record types.
|
||||
|
||||
|
||||
### Fixed
|
||||
|
||||
- GRDB is now able to store and load zero-length blobs.
|
||||
|
||||
|
||||
### New
|
||||
|
||||
New features have been added in order to plug a few holes and support the [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) and [GRDBObjc](http://github.com/groue/GRDBObjc) companion projects:
|
||||
|
||||
- Persistable records can export themselves as dictionaries:
|
||||
|
||||
```swift
|
||||
let player = try Player.fetchOne(db, key: 1)
|
||||
let dict = player.databaseDictionary // [String: DatabaseValue]
|
||||
print(dict)
|
||||
// Prints {"id": 1, "name": "Arthur", "score": 1000}
|
||||
```
|
||||
|
||||
- Query interface requests learned how to limit the number of deleted rows:
|
||||
|
||||
```swift
|
||||
// Delete the last ten players:
|
||||
// DELETE FROM players ORDER BY score LIMIT 10
|
||||
let request = Player.order(scoreColumn).limit(10)
|
||||
try request.deleteAll(db)
|
||||
```
|
||||
|
||||
- Prepared statements know the index of their columns:
|
||||
|
||||
```swift
|
||||
let statement = try db.makeSelectStatement("SELECT a, b FROM t")
|
||||
statement.index(ofColumn: "b") // 1
|
||||
```
|
||||
|
||||
- Row cursors (of type RowCursor) expose their underlying statement:
|
||||
|
||||
```swift
|
||||
let rows = try Row.fetchCursor(db, "SELECT ...")
|
||||
let statement = rows.statement
|
||||
```
|
||||
|
||||
- One can build a Set from a cursor:
|
||||
|
||||
```swift
|
||||
let strings = try Set(String.fetchCursor(...))
|
||||
```
|
||||
|
||||
- The new `AnyDatabaseReader` and `AnyDatabaseWriter` type erasers help dealing with the `DatabaseReader` and `DatabaseWriter` protocols.
|
||||
|
||||
|
||||
### Breaking Changes
|
||||
|
||||
- Requirements have changed: Xcode 9+ / Swift 4
|
||||
|
||||
- WatchOS extension targets no longer need `libsqlite3.tbd` to be added to the *Linked Frameworks and Libraries* section of their *General* tab.
|
||||
|
||||
- The `Row.value` method has been replaced with subscript notation:
|
||||
|
||||
```diff
|
||||
-row.value(atIndex: 0)
|
||||
-row.value(named: "id")
|
||||
-row.value(Column("id"))
|
||||
+row[0]
|
||||
+row["id"]
|
||||
+row[Column("id")]
|
||||
```
|
||||
|
||||
- Date and NSDate now interpret numerical database values as timestamps that fuel `Date(timeIntervalSince1970:)`. Previous version of GRDB would interpret numbers as [julian days](https://en.wikipedia.org/wiki/Julian_day) (a date representation supported by SQLite). Support for julian days remains, with the `Date(julianDay:)` initializer.
|
||||
|
||||
- All `TableMapping` methods that would modify the database have moved to `MutablePersistable`, now the only record protocol that is able to write.
|
||||
|
||||
- The `TableMapping.selectsRowID` property has been replaced with `TableMapping.databaseSelection`.
|
||||
|
||||
To upgrade, replace:
|
||||
|
||||
```diff
|
||||
struct Player: TableMapping {
|
||||
- static let selectsRowID = true
|
||||
+ static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
|
||||
}
|
||||
```
|
||||
|
||||
- The `DatabaseCursor` type has been removed, and replaced with several concrete types that all adopt the `Cursor` protocol. Those new types allow dedicated optimizations depending on the type of the fetched elements.
|
||||
|
||||
If your application has code that depends on `DatabaseCursor`, make it target the new concrete types, or make it generic on the `Cursor` protocol, just like you'd write generic methods on the Swift `Sequence` protocol.
|
||||
|
||||
- `RowConvertible.fetchCursor(_:keys:)` returns a non-optional cursor.
|
||||
|
||||
- `Database.primaryKey(_:)` returns a non-optional PrimaryKeyInfo. When a table has no explicit primary key, the result is the hidden rowid column.
|
||||
|
||||
- The deprecated `TableMapping.primaryKeyRowComparator` method has been removed.
|
||||
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
- [WatchOS installation procedure](https://github.com/groue/GRDB.swift#installation) has been updated with new instructions.
|
||||
- The [introduction to multithreading with database pools](https://github.com/groue/GRDB.swift#database-pools) has been enhanced.
|
||||
- The [Rows as Dictionaries](https://github.com/groue/GRDB.swift#rows-as-dictionaries) chapter has been enhanced with instructions for converting a row into a dictionary.
|
||||
- The [description of cursors](https://github.com/groue/GRDB.swift#cursors) better explains how to choose between a cursor and an array.
|
||||
- The [Date and DateComponents](https://github.com/groue/GRDB.swift#date-and-datecomponents) chapter has been updated for the new support for unix timestamps.
|
||||
- The [Fatal Errors](https://github.com/groue/GRDB.swift#fatal-errors) chapter has an enhanced description of value conversion errors and how to handle them.
|
||||
- The [Usage of raw SQLite pointers](https://github.com/groue/GRDB.swift#raw-sqlite-pointers) chapter has been updated for the new `SQLite3` standard module that comes with Swift4.
|
||||
- A new [Record Protocols Overview](https://github.com/groue/GRDB.swift#record-protocols-overview) chapter has been added.
|
||||
- A new [Codable Records](https://github.com/groue/GRDB.swift#codable-records) chapter has been added.
|
||||
- A new [Columns Selected by a Request](https://github.com/groue/GRDB.swift#columns-selected-by-a-request) chapter describes the new `TableMapping.databaseSelection` property.
|
||||
- The [Exposing the RowID Column](https://github.com/groue/GRDB.swift#exposing-the-rowid-column) chapter has been updated for the new `TableMapping.databaseSelection` property.
|
||||
|
||||
|
||||
### API diff
|
||||
|
||||
```diff
|
||||
class Row {
|
||||
- func value(atIndex index: Int) -> DatabaseValueConvertible?
|
||||
- func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value?
|
||||
- func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value
|
||||
- func value(named columnName: String) -> DatabaseValueConvertible?
|
||||
- func value<Value: DatabaseValueConvertible>(named columnName: String) -> Value?
|
||||
- func value<Value: DatabaseValueConvertible>(named columnName: String) -> Value
|
||||
- func value(_ column: Column) -> DatabaseValueConvertible?
|
||||
- func value<Value: DatabaseValueConvertible>(_ column: Column) -> Value?
|
||||
- func value<Value: DatabaseValueConvertible>(_ column: Column) -> Value
|
||||
+ subscript(_ index: Int) -> DatabaseValueConvertible?
|
||||
+ subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value?
|
||||
+ subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value
|
||||
+ subscript(_ columnName: String) -> DatabaseValueConvertible?
|
||||
+ subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value?
|
||||
+ subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value
|
||||
+ subscript(_ column: Column) -> DatabaseValueConvertible?
|
||||
+ subscript<Value: DatabaseValueConvertible>(_ column: Column) -> Value?
|
||||
+ subscript<Value: DatabaseValueConvertible>(_ column: Column) -> Value
|
||||
}
|
||||
|
||||
class SelectStatement {
|
||||
+ func index(ofColumn columnName: String) -> Int?
|
||||
}
|
||||
|
||||
+extension MutablePersistable {
|
||||
+ var databaseDictionary: [String: DatabaseValue]
|
||||
+}
|
||||
|
||||
-extension TableMapping {
|
||||
+extension MutablePersistable {
|
||||
@discardableResult static func deleteAll(_ db: Database) throws -> Int
|
||||
@discardableResult static func deleteAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> Int where Sequence.Element: DatabaseValueConvertible
|
||||
@discardableResult static func deleteOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: Database, key: PrimaryKeyType?) throws -> Bool
|
||||
@discardableResult static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int
|
||||
@discardableResult static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool
|
||||
}
|
||||
-extension QueryInterfaceRequest {
|
||||
+extension QueryInterfaceRequest where RowDecoder: MutablePersistable {
|
||||
@discardableResult func deleteAll(_ db: Database) throws -> Int
|
||||
}
|
||||
|
||||
protocol TableMapping {
|
||||
- static var selectsRowID: Bool { get }
|
||||
+ static var databaseSelection: [SQLSelectable] { get }
|
||||
}
|
||||
class Record {
|
||||
- open class var selectsRowID: Bool
|
||||
+ open class var databaseSelection: [SQLSelectable]
|
||||
}
|
||||
+struct AllColumns {
|
||||
+ init()
|
||||
+}
|
||||
|
||||
class Database {
|
||||
- func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo?
|
||||
+ func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo
|
||||
}
|
||||
struct PrimaryKeyInfo {
|
||||
+ var isRowID: Bool { get }
|
||||
}
|
||||
|
||||
+extension Set {
|
||||
+ init<C: Cursor>(_ cursor: C) throws where C.Element == Element
|
||||
+}
|
||||
|
||||
-final class DatabaseCursor { }
|
||||
+final class ColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
|
||||
+ typealias Element = Value
|
||||
+}
|
||||
+final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
|
||||
+ typealias Element = Value
|
||||
+}
|
||||
+final class NullableColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
|
||||
+ typealias Element = Value?
|
||||
+}
|
||||
+final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
|
||||
+ typealias Element = Value?
|
||||
+}
|
||||
+final class RecordCursor<Record: RowConvertible> : Cursor {
|
||||
+ typealias Element = Record
|
||||
+}
|
||||
+final class RowCursor : Cursor {
|
||||
+ typealias Element = Row
|
||||
+ let statement: SelectStatement
|
||||
+}
|
||||
extension DatabaseValueConvertible {
|
||||
- static func fetchCursor(...) throws -> DatabaseCursor<Self>
|
||||
+ static func fetchCursor(...) throws -> DatabaseValueCursor<Self>
|
||||
}
|
||||
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
+ static func fetchCursor(...) throws -> ColumnCursor<Self>
|
||||
}
|
||||
extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
- static func fetchCursor(...) throws -> DatabaseCursor<Wrapped?>
|
||||
+ static func fetchCursor(...) throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
}
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
+ static func fetchCursor(...) throws -> NullableColumnCursor<Wrapped>
|
||||
}
|
||||
extension Row {
|
||||
- static func fetchCursor(...) throws -> DatabaseCursor<Row>
|
||||
+ static func fetchCursor(...) throws -> RowCursor
|
||||
}
|
||||
extension RowConvertible where Self: TableMapping {
|
||||
- static func fetchCursor(...) throws -> DatabaseCursor<Self>?
|
||||
+ static func fetchCursor(...) throws -> RecordCursor<Self>
|
||||
}
|
||||
extension TypedRequest where RowDecoder: RowConvertible {
|
||||
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder>
|
||||
+ func fetchCursor(_ db: Database) throws -> RecordCursor<RowDecoder>
|
||||
}
|
||||
extension TypedRequest where RowDecoder: DatabaseValueConvertible {
|
||||
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder>
|
||||
+ func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder>
|
||||
}
|
||||
extension TypedRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
+ func fetchCursor(_ db: Database) throws -> ColumnCursor<RowDecoder>
|
||||
}
|
||||
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible {
|
||||
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder._Wrapped?>
|
||||
+ func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor<RowDecoder._Wrapped>
|
||||
}
|
||||
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
+ func fetchCursor(_ db: Database) throws -> NullableColumnCursor<RowDecoder._Wrapped>
|
||||
}
|
||||
extension TypedRequest where RowDecoder: Row {
|
||||
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<Row>
|
||||
+ func fetchCursor(_ db: Database) throws -> RowCursor
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
- @available(*, deprecated) static func primaryKeyRowComparator(_ db: Database) throws -> (Row, Row) -> Bool
|
||||
}
|
||||
|
||||
+final class AnyDatabaseReader : DatabaseReader {
|
||||
+ init(_ base: DatabaseReader)
|
||||
+}
|
||||
+final class AnyDatabaseWriter : DatabaseWriter {
|
||||
+ init(_ base: DatabaseWriter)
|
||||
+}
|
||||
```
|
||||
|
||||
### Experimental API diff
|
||||
|
||||
```diff
|
||||
enum SQLCount {
|
||||
- case star
|
||||
+ case all
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 1.3.0
|
||||
|
||||
Released August 18, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v1.2.2...v1.3.0)
|
||||
|
||||
**New**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.20.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Complete support for all signed and unsigned integer types: from Int8 toUInt64, all integers can be stored and loaded from the database.
|
||||
|
||||
**API diff**
|
||||
|
||||
```diff
|
||||
+extension Int8: DatabaseValueConvertible, StatementColumnConvertible { }
|
||||
+extension Int16: DatabaseValueConvertible, StatementColumnConvertible { }
|
||||
+extension UInt8: DatabaseValueConvertible, StatementColumnConvertible { }
|
||||
+extension UInt16: DatabaseValueConvertible, StatementColumnConvertible { }
|
||||
+extension UInt32: DatabaseValueConvertible, StatementColumnConvertible { }
|
||||
+extension UInt64: DatabaseValueConvertible, StatementColumnConvertible { }
|
||||
+extension UInt: DatabaseValueConvertible, StatementColumnConvertible { }
|
||||
```
|
||||
|
||||
|
||||
## 1.2.2
|
||||
|
||||
Released July 20, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v1.2.1...v1.2.2)
|
||||
|
||||
**Fixed**
|
||||
|
||||
- The `Configuration.trace` function no longer leaks memory.
|
||||
|
||||
|
||||
## 1.2.1
|
||||
|
||||
Released July 19, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v1.2...v1.2.1)
|
||||
|
||||
**Fixed**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.19.3](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- The [Query Interface](https://github.com/groue/GRDB.swift/#the-query-interface) now generates `IS NULL` SQL snippets for comparisons with `DatabaseValue.null`:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM players WHERE email IS NULL
|
||||
Player.filter(Column("email") == DatabaseValue.null)
|
||||
```
|
||||
|
||||
It used to generate `= NULL` which would not behave as expected.
|
||||
|
||||
|
||||
## 1.2
|
||||
|
||||
Released July 13, 2017
|
||||
Released July 13, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v1.1...v1.2)
|
||||
|
||||
**New**
|
||||
|
||||
@@ -102,7 +959,7 @@ Released July 13, 2017
|
||||
|
||||
## 1.1
|
||||
|
||||
Released July 1, 2017
|
||||
Released July 1, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v1.0...v1.1)
|
||||
|
||||
**New**
|
||||
|
||||
@@ -1110,7 +1967,7 @@ Released September 16, 2016
|
||||
|
||||
```diff
|
||||
-let dbValue = row.databaseValue(atIndex: 0)
|
||||
+let dbValue: DatabaseValue = row.value(atIndex: 0)
|
||||
+let dbValue: DatabaseValue = row[0]
|
||||
```
|
||||
|
||||
|
||||
@@ -1466,7 +2323,7 @@ Released September 16, 2016
|
||||
|
||||
```diff
|
||||
-let dbValue = row.databaseValue(atIndex: 0)
|
||||
+let dbValue: DatabaseValue = row.value(atIndex: 0)
|
||||
+let dbValue: DatabaseValue = row[0]
|
||||
```
|
||||
|
||||
|
||||
|
||||
@@ -1,11 +1,3 @@
|
||||
//
|
||||
// ExtensionDelegate.swift
|
||||
// GRDBDemoWatchOS Extension
|
||||
//
|
||||
// Created by Gwendal Roué on 03/04/2017.
|
||||
// Copyright © 2017 Gwendal Roué. All rights reserved.
|
||||
//
|
||||
|
||||
import WatchKit
|
||||
|
||||
class ExtensionDelegate: NSObject, WKExtensionDelegate {
|
||||
|
||||
@@ -1,14 +1,7 @@
|
||||
//
|
||||
// InterfaceController.swift
|
||||
// GRDBDemoWatchOS Extension
|
||||
//
|
||||
// Created by Gwendal Roué on 03/04/2017.
|
||||
// Copyright © 2017 Gwendal Roué. All rights reserved.
|
||||
//
|
||||
|
||||
import WatchKit
|
||||
import Foundation
|
||||
import GRDB
|
||||
import SQLite3
|
||||
|
||||
class InterfaceController: WKInterfaceController {
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
5657C36E1E926B05008402E8 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 5657C36D1E926B05008402E8 /* libsqlite3.tbd */; };
|
||||
568E5FC31E926430002582E0 /* Interface.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FC11E926430002582E0 /* Interface.storyboard */; };
|
||||
568E5FC51E926430002582E0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FC41E926430002582E0 /* Assets.xcassets */; };
|
||||
568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = 568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
|
||||
@@ -21,7 +20,7 @@
|
||||
56B0360C1E8D9EBE003B6DA4 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */; };
|
||||
56B0360E1E8D9EBE003B6DA4 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */; };
|
||||
56B036111E8D9EBE003B6DA4 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */; };
|
||||
56B0361B1E8D9F38003B6DA4 /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036191E8D9F38003B6DA4 /* Database.swift */; };
|
||||
56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */; };
|
||||
56B0361C1E8D9F38003B6DA4 /* Person.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Person.swift */; };
|
||||
56B036221E8D9F4C003B6DA4 /* DemoViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */; };
|
||||
56B036231E8D9F4C003B6DA4 /* PersonEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PersonEditionViewController.swift */; };
|
||||
@@ -32,6 +31,13 @@
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
563BD2F01F8364C1006A5390 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56439B501F4CA1DC0066043F;
|
||||
remoteInfo = GRDBOSXPerformanceComparisonTests;
|
||||
};
|
||||
568E5FCD1E926430002582E0 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B035FB1E8D9EBE003B6DA4 /* Project object */;
|
||||
@@ -243,7 +249,6 @@
|
||||
/* End PBXCopyFilesBuildPhase section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
5657C36D1E926B05008402E8 /* libsqlite3.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libsqlite3.tbd; path = Platforms/WatchOS.platform/Developer/SDKs/WatchOS3.2.sdk/usr/lib/libsqlite3.tbd; sourceTree = DEVELOPER_DIR; };
|
||||
568E5FBF1E926430002582E0 /* GRDBDemoWatchOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBDemoWatchOS.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
568E5FC21E926430002582E0 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Interface.storyboard; sourceTree = "<group>"; };
|
||||
568E5FC41E926430002582E0 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
|
||||
@@ -259,7 +264,7 @@
|
||||
56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
|
||||
56B036101E8D9EBE003B6DA4 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
|
||||
56B036121E8D9EBE003B6DA4 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
56B036191E8D9F38003B6DA4 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = "<group>"; };
|
||||
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
|
||||
56B0361A1E8D9F38003B6DA4 /* Person.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Person.swift; sourceTree = "<group>"; };
|
||||
56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DemoViewController.swift; sourceTree = "<group>"; };
|
||||
56B0361F1E8D9F4C003B6DA4 /* PersonEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonEditionViewController.swift; sourceTree = "<group>"; };
|
||||
@@ -273,7 +278,6 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
5657C36E1E926B05008402E8 /* libsqlite3.tbd in Frameworks */,
|
||||
568E5FE41E926547002582E0 /* GRDB.framework in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
@@ -289,14 +293,6 @@
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
5657C36C1E926B05008402E8 /* Frameworks */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5657C36D1E926B05008402E8 /* libsqlite3.tbd */,
|
||||
);
|
||||
name = Frameworks;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
568E5FC01E926430002582E0 /* GRDBDemoWatchOS */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -326,7 +322,6 @@
|
||||
568E5FC01E926430002582E0 /* GRDBDemoWatchOS */,
|
||||
568E5FCF1E926430002582E0 /* GRDBDemoWatchOS Extension */,
|
||||
56B036041E8D9EBE003B6DA4 /* Products */,
|
||||
5657C36C1E926B05008402E8 /* Frameworks */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
@@ -344,7 +339,7 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */,
|
||||
56B036191E8D9F38003B6DA4 /* Database.swift */,
|
||||
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */,
|
||||
56B0361A1E8D9F38003B6DA4 /* Person.swift */,
|
||||
56B0361D1E8D9F3D003B6DA4 /* Controllers */,
|
||||
56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */,
|
||||
@@ -372,6 +367,7 @@
|
||||
56B0363B1E8D9F79003B6DA4 /* GRDB.framework */,
|
||||
56B0363D1E8D9F79003B6DA4 /* GRDBOSXTests.xctest */,
|
||||
56B0363F1E8D9F79003B6DA4 /* GRDBOSXPerformanceTests.xctest */,
|
||||
563BD2F11F8364C1006A5390 /* GRDBOSXPerformanceComparisonTests.xctest */,
|
||||
56B036411E8D9F79003B6DA4 /* GRDBOSXCrashTests.xctest */,
|
||||
56B036431E8D9F79003B6DA4 /* GRDBCipher.framework */,
|
||||
56B036451E8D9F79003B6DA4 /* GRDBCipherOSXTests.xctest */,
|
||||
@@ -459,7 +455,7 @@
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastSwiftUpdateCheck = 0830;
|
||||
LastUpgradeCheck = 0830;
|
||||
LastUpgradeCheck = 0900;
|
||||
ORGANIZATIONNAME = "Gwendal Roué";
|
||||
TargetAttributes = {
|
||||
568E5FBE1E926430002582E0 = {
|
||||
@@ -506,6 +502,13 @@
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXReferenceProxy section */
|
||||
563BD2F11F8364C1006A5390 /* GRDBOSXPerformanceComparisonTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBOSXPerformanceComparisonTests.xctest;
|
||||
remoteRef = 563BD2F01F8364C1006A5390 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B0363B1E8D9F79003B6DA4 /* GRDB.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
@@ -672,7 +675,7 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
56B0361C1E8D9F38003B6DA4 /* Person.swift in Sources */,
|
||||
56B0361B1E8D9F38003B6DA4 /* Database.swift in Sources */,
|
||||
56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */,
|
||||
56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */,
|
||||
56B036241E8D9F4C003B6DA4 /* PersonsViewController.swift in Sources */,
|
||||
56B036231E8D9F4C003B6DA4 /* PersonEditionViewController.swift in Sources */,
|
||||
@@ -755,7 +758,6 @@
|
||||
PRODUCT_NAME = "${TARGET_NAME}";
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
SWIFT_VERSION = 3.0;
|
||||
TARGETED_DEVICE_FAMILY = 4;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 3.2;
|
||||
};
|
||||
@@ -772,7 +774,6 @@
|
||||
PRODUCT_NAME = "${TARGET_NAME}";
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
SWIFT_VERSION = 3.0;
|
||||
TARGETED_DEVICE_FAMILY = 4;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 3.2;
|
||||
};
|
||||
@@ -790,7 +791,6 @@
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
SWIFT_VERSION = 3.0;
|
||||
TARGETED_DEVICE_FAMILY = 4;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 3.2;
|
||||
};
|
||||
@@ -808,7 +808,6 @@
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
SWIFT_VERSION = 3.0;
|
||||
TARGETED_DEVICE_FAMILY = 4;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 3.2;
|
||||
};
|
||||
@@ -824,7 +823,9 @@
|
||||
CLANG_CXX_LIBRARY = "libc++";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
||||
@@ -832,7 +833,11 @@
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
@@ -855,12 +860,12 @@
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 10.3;
|
||||
MTL_ENABLE_DEBUG_INFO = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 4.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -874,7 +879,9 @@
|
||||
CLANG_CXX_LIBRARY = "libc++";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
||||
@@ -882,7 +889,11 @@
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
@@ -899,10 +910,10 @@
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 10.3;
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
|
||||
SWIFT_VERSION = 4.0;
|
||||
VALIDATE_PRODUCT = YES;
|
||||
};
|
||||
name = Release;
|
||||
@@ -917,7 +928,6 @@
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 3.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -931,7 +941,6 @@
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 3.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0730"
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0830"
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import GRDB
|
||||
|
||||
/// A type responsible for initializing the application database.
|
||||
///
|
||||
/// See AppDelegate.setupDatabase()
|
||||
struct AppDatabase {
|
||||
|
||||
/// Creates a fully initialized database at path
|
||||
static func openDatabase(atPath path: String) throws -> DatabaseQueue {
|
||||
// Connect to the database
|
||||
// See https://github.com/groue/GRDB.swift/#database-connections
|
||||
dbQueue = try DatabaseQueue(path: path)
|
||||
|
||||
// Use DatabaseMigrator to define the database schema
|
||||
// See https://github.com/groue/GRDB.swift/#migrations
|
||||
try migrator.migrate(dbQueue)
|
||||
|
||||
return dbQueue
|
||||
}
|
||||
|
||||
/// The DatabaseMigrator that defines the database schema.
|
||||
///
|
||||
/// This migrator is exposed so that migrations can be tested.
|
||||
// See https://github.com/groue/GRDB.swift/#migrations
|
||||
static var migrator: DatabaseMigrator {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
migrator.registerMigration("createPersons") { db in
|
||||
// Create a table
|
||||
// See https://github.com/groue/GRDB.swift#create-tables
|
||||
try db.create(table: "persons") { t in
|
||||
// An integer primary key auto-generates unique IDs
|
||||
t.column("id", .integer).primaryKey()
|
||||
|
||||
// Sort person names in a localized case insensitive fashion by default
|
||||
// See https://github.com/groue/GRDB.swift/#unicode
|
||||
t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare)
|
||||
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
}
|
||||
|
||||
migrator.registerMigration("fixtures") { db in
|
||||
// Populate the persons table with random data
|
||||
for _ in 0..<8 {
|
||||
try Person(name: Person.randomName(), score: Person.randomScore()).insert(db)
|
||||
}
|
||||
}
|
||||
|
||||
// // Migrations for future application versions will be inserted here:
|
||||
// migrator.registerMigration(...) { db in
|
||||
// ...
|
||||
// }
|
||||
|
||||
return migrator
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,8 @@
|
||||
import UIKit
|
||||
import GRDB
|
||||
|
||||
// The shared database queue
|
||||
var dbQueue: DatabaseQueue!
|
||||
|
||||
@UIApplicationMain
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
@@ -8,4 +12,15 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
try! setupDatabase(application)
|
||||
return true
|
||||
}
|
||||
|
||||
private func setupDatabase(_ application: UIApplication) throws {
|
||||
let databaseURL = try FileManager.default
|
||||
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
.appendingPathComponent("db.sqlite")
|
||||
dbQueue = try AppDatabase.openDatabase(atPath: databaseURL.path)
|
||||
|
||||
// Be a nice iOS citizen, and don't consume too much memory
|
||||
// See https://github.com/groue/GRDB.swift/#memory-management
|
||||
dbQueue.setupMemoryManagement(in: application)
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
import GRDB
|
||||
import UIKit
|
||||
|
||||
// The shared database queue
|
||||
var dbQueue: DatabaseQueue!
|
||||
|
||||
func setupDatabase(_ application: UIApplication) throws {
|
||||
|
||||
// Connect to the database
|
||||
// See https://github.com/groue/GRDB.swift/#database-connections
|
||||
|
||||
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString
|
||||
let databasePath = documentsPath.appendingPathComponent("db.sqlite")
|
||||
dbQueue = try DatabaseQueue(path: databasePath)
|
||||
|
||||
|
||||
// Be a nice iOS citizen, and don't consume too much memory
|
||||
// See https://github.com/groue/GRDB.swift/#memory-management
|
||||
|
||||
dbQueue.setupMemoryManagement(in: application)
|
||||
|
||||
|
||||
// Use DatabaseMigrator to setup the database
|
||||
// See https://github.com/groue/GRDB.swift/#migrations
|
||||
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
migrator.registerMigration("createPersons") { db in
|
||||
|
||||
// Create a table
|
||||
// See https://github.com/groue/GRDB.swift#create-tables
|
||||
|
||||
try db.create(table: "persons") { t in
|
||||
// An integer primary key auto-generates unique IDs
|
||||
t.column("id", .integer).primaryKey()
|
||||
|
||||
// Sort person names in a localized case insensitive fashion by default
|
||||
// See https://github.com/groue/GRDB.swift/#unicode
|
||||
t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare)
|
||||
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
|
||||
// Populate the persons table with random data
|
||||
for _ in 0..<8 {
|
||||
try Person(name: Person.randomName(), score: Person.randomScore()).insert(db)
|
||||
}
|
||||
}
|
||||
|
||||
// // Migrations for future application versions will be inserted here:
|
||||
// migrator.registerMigration(...) { db in
|
||||
// ...
|
||||
// }
|
||||
|
||||
try migrator.migrate(dbQueue)
|
||||
}
|
||||
@@ -18,9 +18,9 @@ class Person: Record {
|
||||
}
|
||||
|
||||
required init(row: Row) {
|
||||
id = row.value(named: "id")
|
||||
name = row.value(named: "name")
|
||||
score = row.value(named: "score")
|
||||
id = row["id"]
|
||||
name = row["name"]
|
||||
score = row["score"]
|
||||
super.init(row: row)
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ Custom SQLite Builds
|
||||
|
||||
By default, GRDB uses the version of SQLite that ships with the target operating system.
|
||||
|
||||
**You can build GRDB with a custom build of [SQLite 3.19.2](https://www.sqlite.org/changes.html).**
|
||||
**You can build GRDB with a custom build of [SQLite 3.22.0](https://www.sqlite.org/changes.html).**
|
||||
|
||||
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](../../../#support-for-sqlite-pre-update-hooks).
|
||||
|
||||
@@ -11,11 +11,11 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
|
||||
**To install GRDB with a custom SQLite build:**
|
||||
|
||||
1. Clone the GRDB.swift git repository, checkout the latest tagged version, and download SQLite sources:
|
||||
1. Clone the GRDB git repository, checkout the latest tagged version, and download SQLite sources:
|
||||
|
||||
```sh
|
||||
cd [GRDB.swift directory]
|
||||
git checkout v1.2
|
||||
cd [GRDB directory]
|
||||
git checkout v2.9.0
|
||||
git submodule update --init SQLiteCustom/src
|
||||
````
|
||||
|
||||
@@ -60,7 +60,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
# !! MODIFY THESE TO MATCH YOUR PROJECT HIERARCHY !!
|
||||
#######################################################
|
||||
|
||||
# The path to the folder containing GRDB.xcodeproj:
|
||||
# The path to the folder containing GRDBCustom.xcodeproj:
|
||||
GRDB_SOURCE_PATH="${PROJECT_DIR}/GRDB"
|
||||
|
||||
# The path to your custom "SQLiteLib-USER.xcconfig":
|
||||
@@ -107,7 +107,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
|
||||
Modify the top of `GRDBCustomSQLite-INSTALL.sh` file so that it contains correct paths.
|
||||
|
||||
5. Embed the `GRDB.xcodeproj` project in your own project.
|
||||
5. Embed the `GRDBCustom.xcodeproj` project in your own project.
|
||||
|
||||
6. Add the `GRDBCustomSQLiteOSX` or `GRDBCustomSQLiteiOS` target in the **Target Dependencies** section of the **Build Phases** tab of your **application target**.
|
||||
|
||||
|
||||
@@ -1,591 +0,0 @@
|
||||
GRDB Extension Guide
|
||||
====================
|
||||
|
||||
**Some parts of GRDB are extensible, so that you can make it better fit your needs.**
|
||||
|
||||
This guide is a step-by-step tour of GRDB extensibility, around a few topics:
|
||||
|
||||
- **[Add a value type](#add-a-value-type)**
|
||||
|
||||
You'll learn how to turn UIColor into a value type that you can store, fetch, and use in your records:
|
||||
|
||||
```swift
|
||||
let rows = try Row.fetchCursor(db, "SELECT name, color FROM clothes")
|
||||
while let row = try rows.next() {
|
||||
let name: String = row.value(named: "name")
|
||||
let color: UIColor = row.value(named: "color") // <-- New! UIColor as value
|
||||
}
|
||||
```
|
||||
|
||||
- **[Add an SQLite function or operator](#add-an-sqlite-function-or-operator)**
|
||||
|
||||
You'll learn how to add support for the [STRFTIME](https://www.sqlite.org/lang_datefunc.html) function, and the [GLOB](https://www.sqlite.org/lang_expr.html#like) operator:
|
||||
|
||||
```swift
|
||||
Books.select(strftime("%Y", Column("publishedDate"))) // <-- New! strftime function
|
||||
Books.filter(Column("body").glob("*Moby-Dick*")) // <-- New! glob method
|
||||
```
|
||||
|
||||
- **[Add a new kind of SQLite expression](#add-a-new-kind-of-sqlite-expression)**
|
||||
|
||||
You'll learn how to add support for [CAST expressions](https://www.sqlite.org/lang_expr.html#castexpr):
|
||||
|
||||
```swift
|
||||
let jsonString = Column("jsonString")
|
||||
let request = Books.select(cast(jsonString, as: .blob)) // <-- New! cast function
|
||||
let rows = try Row.fetchCursor(db, request)
|
||||
while let row = try rows.next() {
|
||||
let data = row.dataNoCopy(atIndex: 0)
|
||||
}
|
||||
```
|
||||
|
||||
- **Extend the query interface requests**
|
||||
|
||||
You may need to extend the [query interface requests](../../../#requests) so that their SELECT queries could embed recursive clauses, table joins, etc.
|
||||
|
||||
Pull requests are welcome. Open issues if you have questions.
|
||||
|
||||
Meanwhile, you can build your own [custom requests](../../../#custom-requests).
|
||||
|
||||
- **[Add a custom FTS5 full-text tokenizer](FTS5Tokenizers.md)**
|
||||
|
||||
Custom tokenizers can leverage extra full-text features such as synonyms or stop words.
|
||||
|
||||
- **Support a new kind of SQL query**
|
||||
|
||||
For example, you may need to generate SQL triggers, or create specific kinds of virtual tables.
|
||||
|
||||
Pull requests are welcome. Open issues if you have questions.
|
||||
|
||||
|
||||
## Add a Value Type
|
||||
|
||||
**All value types adopt the [DatabaseValueConvertible protocol](../../../#custom-value-types).**
|
||||
|
||||
```swift
|
||||
protocol DatabaseValueConvertible {
|
||||
/// Returns a value that can be stored in the database.
|
||||
var databaseValue: DatabaseValue { get }
|
||||
|
||||
/// Returns a value initialized from databaseValue, if possible.
|
||||
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self?
|
||||
}
|
||||
```
|
||||
|
||||
The `databaseValue` property returns [DatabaseValue](../../../#databasevalue), a type that wraps the five values supported by SQLite: NULL, Int64, Double, String and Data. Since DatabaseValue has no public initializer, use `DatabaseValue.null`, or another type that already adopts the protocol: `1.databaseValue`, `"foo".databaseValue`, etc. Conversion to DatabaseValue *must not* fail.
|
||||
|
||||
The `fromDatabaseValue()` factory method returns an instance of your custom type if the databaseValue contains a suitable value. If the databaseValue does not contain a suitable value, such as "foo" for Date, `fromDatabaseValue` *must* return nil (GRDB will interpret this nil result as a conversion error, and react accordingly).
|
||||
|
||||
**What does the DatabaseValueConvertible protocol bring to a type like UIColor?**
|
||||
|
||||
Well, you will be able to use UIColor like all other [value types](../../../#values) (Bool, Int, String, Date, Swift enums, etc.):
|
||||
|
||||
- Use UIColor as [statement arguments](../../../#executing-updates):
|
||||
|
||||
```swift
|
||||
try db.execute(
|
||||
"INSERT INTO clothes (name, color) VALUES (?, ?)",
|
||||
arguments: ["Shirt", UIColor.red])
|
||||
```
|
||||
|
||||
- UIColor can be [extracted from rows](../../../#column-values):
|
||||
|
||||
```swift
|
||||
let rows = try Row.fetchCursor(db, "SELECT * FROM clothes")
|
||||
while let row = try rows.next() {
|
||||
let name: String = row.value(named: "name")
|
||||
let color: UIColor = row.value(named: "color")
|
||||
}
|
||||
```
|
||||
|
||||
- UIColor can be [directly fetched](../../../#value-queries):
|
||||
|
||||
```swift
|
||||
let colors = try UIColor.fetchAll(db, "SELECT DISTINCT color FROM clothes") // [UIColor]
|
||||
```
|
||||
|
||||
- Use UIColor in [Records](../../../#records):
|
||||
|
||||
```swift
|
||||
class ClothingItem : Record {
|
||||
var name: String
|
||||
var color: UIColor
|
||||
|
||||
required init(row: Row) {
|
||||
name = row.value(named: "name")
|
||||
color = row.value(named: "color")
|
||||
super.init(row: row)
|
||||
}
|
||||
|
||||
override func encode(to container: inout PersistenceContainer) {
|
||||
container["name"] = name
|
||||
container["color"] = color
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- Use UIColor in the [query interface](../../../#the-query-interface):
|
||||
|
||||
```swift
|
||||
let redClothes = try ClothingItem.filter(colorColumn == UIColor.red).fetchAll(db)
|
||||
```
|
||||
|
||||
**Let's have UIColor adopt DatabaseValueConvertible**
|
||||
|
||||
In order to preserve as most information as possible, we'll archive UIColor as a data blob using the NSCoding protocol. But YMMV.
|
||||
|
||||
```swift
|
||||
extension UIColor : DatabaseValueConvertible {
|
||||
|
||||
/// Encode UIColor as a data blob
|
||||
var databaseValue: DatabaseValue {
|
||||
// Use NSKeyedArchiver to build Data
|
||||
let data = NSKeyedArchiver.archivedData(withRootObject: self)
|
||||
|
||||
// Data is already DatabaseValueConvertible
|
||||
return data.databaseValue
|
||||
}
|
||||
|
||||
/// Returns a UIColor if databaseValue contains suitable data, and
|
||||
/// nil otherwise.
|
||||
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
// Only Data blobs can contain a UIColor
|
||||
guard let data = Data.fromDatabaseValue(databaseValue) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
// We're looking for an archived object
|
||||
guard let color = NSKeyedUnarchiver.unarchiveObject(with: data) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
// The cast function will return nil if the unarchived object doesn't
|
||||
// have the correct type
|
||||
return cast(color) // Converts Any to Self?
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Use the `cast` utility function when you want *non-final classes* to implement DatabaseValueConvertible. It avoids compiler errors that are not easy to deal with. Note that final classes and value types won't need it.
|
||||
|
||||
```swift
|
||||
// Workaround Swift inconvenience around factories methods of non-final classes
|
||||
func cast<T, U>(_ value: T) -> U? {
|
||||
return value as? U
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Add an SQLite Function or Operator
|
||||
|
||||
**When an SQLite [function](https://www.sqlite.org/lang_corefunc.html) or [operator](https://www.sqlite.org/lang_expr.html) is missing from GRDB**, this usually means that there hasn't been a [feature request](http://github.com/groue/GRDB.swift/issues) yet.
|
||||
|
||||
But you don't have to wait: you can extend GRDB and the query interface to add support for the missing syntax element (and eventually submit a pull request later).
|
||||
|
||||
Let's remind our goal: we'll add the [STRFTIME](https://www.sqlite.org/lang_datefunc.html) function, and the [GLOB](https://www.sqlite.org/lang_expr.html#like) operator.
|
||||
|
||||
Their SQL usage is the following:
|
||||
|
||||
```sql
|
||||
-- Publication years of books
|
||||
SELECT STRFTIME('%Y', publishedOn) FROM books;
|
||||
-- Books that talk about Moby Dick
|
||||
SELECT * FROM books WHERE body GLOB '*Moby-Dick*';
|
||||
```
|
||||
|
||||
Translated in the query interface, this gives:
|
||||
|
||||
```swift
|
||||
Books.select(strftime("%Y", Column("publishedDate")))
|
||||
Books.filter(Column("body").glob("*Moby-Dick*"))
|
||||
```
|
||||
|
||||
`strftime` is a top-level Swift function because this is how GRDB usually imports SQLite functions which do not have matching standard Swift counterpart, like AVG, LEGNTH, SUM. It helps the Swift code looking like SQL when it is relevant.
|
||||
|
||||
In the same fashion, we expose the GLOB SQL operator as the `glob` Swift method, just because `value.glob(pattern)` reads like `value GLOB pattern`.
|
||||
|
||||
Whenever you import a SQL feature to Swift, you'll have to decide: should you preserve the SQL look and feel, or adopt a well-established swiftism? It's really up to you.
|
||||
|
||||
|
||||
### STRFTIME
|
||||
|
||||
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
|
||||
The [STRFTIME](https://www.sqlite.org/lang_datefunc.html) SQL function accepts many arguments. We'll simplify it to `strftime(format, date)`, so that we can write:
|
||||
|
||||
```sql
|
||||
// Publication years of books
|
||||
// SELECT STRFTIME('%Y', publishedOn) FROM books
|
||||
Books.select(strftime("%Y", Column("publishedDate")))
|
||||
```
|
||||
|
||||
The signature of the Swift `strftime` function is:
|
||||
|
||||
```swift
|
||||
func strftime(_ format: String, _ date: SQLSpecificExpressible) -> SQLExpression
|
||||
```
|
||||
|
||||
SQLSpecificExpressible and SQLExpression are types of the [query interface](../../../#the-query-interface) that you do not usually see. We have moved down one floor, closer to the SQL guts of GRDB. We'll see more new types and protocols below.
|
||||
|
||||
The return value is SQLExpression. All GRDB functions and operators that build [query interface expressions](../../../#expressions) return values of this type. It represents actual [SQLite expressions](https://www.sqlite.org/lang_expr.html).
|
||||
|
||||
SQLExpression is a protocol, so that you can build your own [custom expressions](#add-a-new-kind-of-sqlite-expression). But GRDB ships with a variety of [built-in expressions](#built-in-expressions) that are ready-made, and here we'll use SQLExpressionFunction that is dedicated to function calls:
|
||||
|
||||
```swift
|
||||
struct SQLExpressionFunction : SQLExpression {
|
||||
/// Creates an SQL function call
|
||||
///
|
||||
/// // ABS(-1)
|
||||
/// SQLExpressionFunction(.abs, arguments: -1)
|
||||
init(_ functionName: SQLFunctionName, arguments: SQLExpressible...)
|
||||
}
|
||||
```
|
||||
|
||||
So here is the code that defines our `strftime` function:
|
||||
|
||||
```swift
|
||||
// Add a SQLFunctionName just like we add NSNotification.Name since
|
||||
// the release of Swift 3.
|
||||
extension SQLFunctionName {
|
||||
/// The `STRFTIME` SQL function
|
||||
static let strftime = SQLFunctionName("STRFTIME")
|
||||
}
|
||||
|
||||
/// Returns an expression that evaluates the `STRFTIME` SQL function.
|
||||
///
|
||||
/// // STRFTIME('%Y', date)
|
||||
/// strftime("%Y", Column("date"))
|
||||
func strftime(_ format: String, _ date: SQLSpecificExpressible) -> SQLExpression {
|
||||
return SQLExpressionFunction(.strftime, arguments: format, date)
|
||||
}
|
||||
```
|
||||
|
||||
The `strftime` function is now complete, ready to be used. We haven't yet described the SQLSpecificExpressible type of the `date` argument:
|
||||
|
||||
SQLSpecificExpressible is the protocol for all types that can be turned into a SQL expression, but types like Int, Date, or UIColor that exist outside of GRDB and the query interface. Having `strftime` accept a SQLSpecificExpressible date prevents it from polluting the global space. It is *specific* to GRDB:
|
||||
|
||||
```swift
|
||||
strftime("%Y", Date()) // Compiler error
|
||||
strftime("%Y", Column("date")) // SQLExpression: STRFTIME('%Y', date)
|
||||
```
|
||||
|
||||
You may want to compare it to another protocol, SQLExpressible, which will be described [below](#add-a-new-kind-of-sqlite-expression), when we add support for CAST SQL expressions.
|
||||
|
||||
> :point_up: **Note**: whenever you extend GRDB with a Swift function, method, or operator, you should generally make sure that its signature contains at least one GRDB-specific type. In the `strftime` function, it is the SQLSpecificExpressible protocol.
|
||||
|
||||
|
||||
### GLOB
|
||||
|
||||
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
|
||||
For the [GLOB](https://www.sqlite.org/lang_expr.html#like) operator, we want to define the glob Swift method:
|
||||
|
||||
```swift
|
||||
// Books that talk about Moby Dick
|
||||
// SELECT * FROM books WHERE body GLOB '*Moby-Dick*'
|
||||
Books.filter(Column("body").glob("*Moby-Dick*"))
|
||||
```
|
||||
|
||||
This time we can't use the SQLExpressionFunction type, because it can't generate the SQL for a binary operator. Instead, we'll use another [built-in expression](#built-in-expressions), SQLExpressionBinary:
|
||||
|
||||
```swift
|
||||
struct SQLExpressionBinary : SQLExpression {
|
||||
/// Creates an expression made of two expressions joined with a binary operator.
|
||||
///
|
||||
/// // length * width
|
||||
/// SQLExpressionBinary(.multiply, Column("length"), Column("width"))
|
||||
init(_ op: SQLBinaryOperator, _ lhs: SQLExpressible, _ rhs: SQLExpressible)
|
||||
}
|
||||
```
|
||||
|
||||
Now we have to find the signature of our Swift method. The GLOB operator accepts any value on both sides. However, what kind of Swift code should we accept?
|
||||
|
||||
```swift
|
||||
// 1) body GLOB '*Moby-Dick*' -- Yes, of course
|
||||
Column("body").glob("*Moby-Dick*")
|
||||
// 2) body GLOB pattern -- Sure, why not?
|
||||
Column("body").glob(Column("pattern"))
|
||||
// 3) 'Some Swift String' GLOB pattern - Not sure, but OK
|
||||
"Some Swift String".glob(Column("pattern"))
|
||||
// 4) 'Some Swift String' GLOB 'Another Swift String' -- NO
|
||||
"Some Swift String".glob("Another Swift String")
|
||||
```
|
||||
|
||||
We don't want the form 4, because this is an unacceptable pollution of the Swift global namespace. A good GRDB extension limits its scope to database-related code.
|
||||
|
||||
We thus have two overloaded definitions of the `glob` method:
|
||||
|
||||
```swift
|
||||
extension SQLSpecificExpressible {
|
||||
func glob(_ pattern: SQLExpressible) -> SQLExpression
|
||||
}
|
||||
extension SQLExpressible {
|
||||
func glob(_ pattern: SQLSpecificExpressible) -> SQLExpression
|
||||
}
|
||||
```
|
||||
|
||||
SQLExpressible is the protocol for all types that can be turned into a SQL expression. This includes all expressions, and all [value types](../../../#values) (including String).
|
||||
|
||||
SQLSpecificExpressible is a sub protocol of SQLExpressible protocol, restricted to all types that can be turned into a SQL expression, but types like Int, Date, or String that exist outside of GRDB and the query interface.
|
||||
|
||||
By extending both, we can define the GLOB operators for any pair that contains at least one type that is specific to GRDB - and leave the global Swift space clean.
|
||||
|
||||
The final implementation follows:
|
||||
|
||||
```swift
|
||||
// Add a SQLBinaryOperator just like we add NSNotification.Name since
|
||||
// the release of Swift 3.
|
||||
extension SQLBinaryOperator {
|
||||
/// The `GLOB` binary operator
|
||||
static let glob = SQLBinaryOperator("GLOB")
|
||||
}
|
||||
|
||||
extension SQLSpecificExpressible {
|
||||
/// Returns an SQL `GLOB` expression.
|
||||
///
|
||||
/// // body GLOB '*Moby-Dick*'
|
||||
/// Column("body").glob("*Moby-Dick*")
|
||||
func glob(_ pattern: SQLExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.glob, self, pattern)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLExpressible {
|
||||
/// Returns an SQL `GLOB` expression.
|
||||
///
|
||||
/// // 'Some Swift String' GLOB pattern
|
||||
/// "Some Swift String".glob(Column("pattern"))
|
||||
func glob(_ pattern: SQLSpecificExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.glob, self, pattern)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Built-in Expressions
|
||||
|
||||
When you extend GRDB with a new function, method, or operator that generates an [SQL expression](https://www.sqlite.org/lang_expr.html), you have to return a value the adopts the SQLExpression protocol.
|
||||
|
||||
We have already seen in our [previous](#strftime) [examples](#glob) two concrete types that generate SQL function calls and binary operators: SQLExpressionFunction and SQLExpressionBinary.
|
||||
|
||||
This section of the documentation lists all built-in expressions. Adding a custom SQLExpression type will be documented [below](#add-a-new-kind-of-sqlite-expression).
|
||||
|
||||
|
||||
#### Column and DatabaseValue
|
||||
|
||||
The [Column](../../../#the-query-interface) type from the query interface, and [DatabaseValue](../../../#databasevalue), the type that wraps the five values supported by SQLite (NULL, Int64, Double, String and Data) are expressions. They are rather trivial, and it is unlikely that you use them in your GRDB extensions.
|
||||
|
||||
|
||||
#### SQLExpressionLiteral
|
||||
|
||||
Use SQLExpressionLiteral when you need to go fast:
|
||||
|
||||
```swift
|
||||
struct SQLExpressionLiteral : SQLExpression {
|
||||
/// Creates an SQL literal expression.
|
||||
///
|
||||
/// SQLExpressionLiteral("1 + 2")
|
||||
/// SQLExpressionLiteral("? + ?", arguments: [1, 2])
|
||||
init(_ sql: String, arguments: StatementArguments? = nil)
|
||||
}
|
||||
```
|
||||
|
||||
For an example of use, see the [Add a new kind of SQLite expression](#add-a-new-kind-of-sqlite-expression) chapter.
|
||||
|
||||
|
||||
#### SQLExpressionUnary
|
||||
|
||||
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
|
||||
SQLExpressionUnary builds an expression by prefixing another expression with an unary operator:
|
||||
|
||||
```swift
|
||||
struct SQLExpressionUnary : SQLExpression {
|
||||
/// Creates an expression made of an unary operator and
|
||||
/// an operand expression.
|
||||
///
|
||||
/// // NOT favorite
|
||||
/// SQLExpressionUnary(.not, Column("favorite"))
|
||||
init(_ op: SQLUnaryOperator, _ value: SQLExpressible)
|
||||
}
|
||||
```
|
||||
|
||||
You add missing SQLite unary operators by extending SQLUnaryOperator:
|
||||
|
||||
```swift
|
||||
extension SQLUnaryOperator {
|
||||
/// The `+` unary operator
|
||||
static let plus = SQLUnaryOperator("+", needsRightSpace: false)
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
#### SQLExpressionBinary
|
||||
|
||||
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
|
||||
SQLExpressionBinary builds an expression by joining two expressions with a binary operator:
|
||||
|
||||
```swift
|
||||
struct SQLExpressionBinary : SQLExpression {
|
||||
/// Creates an expression made of two expressions joined with a binary operator.
|
||||
///
|
||||
/// // length * width
|
||||
/// SQLExpressionBinary(.multiply, Column("length"), Column("width"))
|
||||
init(_ op: SQLBinaryOperator, _ lhs: SQLExpressible, _ rhs: SQLExpressible)
|
||||
}
|
||||
```
|
||||
|
||||
You add missing SQLite binary operators by extending SQLBinaryOperator:
|
||||
|
||||
```swift
|
||||
extension SQLBinaryOperator {
|
||||
/// The `GLOB` binary operator
|
||||
static let glob = SQLBinaryOperator("GLOB")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
#### SQLExpressionFunction
|
||||
|
||||
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
|
||||
SQLExpressionFunction builds an SQL function call:
|
||||
|
||||
```swift
|
||||
struct SQLExpressionFunction : SQLExpression {
|
||||
/// Creates an SQL function call
|
||||
///
|
||||
/// // ABS(-1)
|
||||
/// SQLExpressionFunction(.abs, arguments: -1)
|
||||
init(_ functionName: SQLFunctionName, arguments: SQLExpressible...)
|
||||
}
|
||||
```
|
||||
|
||||
You add missing SQLite function names by extending SQLFunctionName:
|
||||
|
||||
```swift
|
||||
extension SQLFunctionName {
|
||||
/// The `STRFTIME` SQL function
|
||||
static let strftime = SQLFunctionName("STRFTIME")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
#### The IN Operator
|
||||
|
||||
Build a `value IN (...)` expression from any sequence of [values](../../../#values):
|
||||
|
||||
```swift
|
||||
// SQLExpression: id IN (1, 2, 3)
|
||||
[1,2,3].contains(Column("id"))
|
||||
|
||||
// SQLExpression: id NOT IN (1, 2, 3)
|
||||
![1,2,3].contains(Column("id"))
|
||||
```
|
||||
|
||||
|
||||
#### The BETWEEN Operator
|
||||
|
||||
Build a `value BETWEEN min AND max` expression from Swift ranges:
|
||||
|
||||
```swift
|
||||
// SQLExpression: id BETWEEN 1 AND 10
|
||||
1...10.contains(Column("id")
|
||||
```
|
||||
|
||||
|
||||
#### The COUNT Function
|
||||
|
||||
Build a `COUNT(...)` expression from the [count](http://groue.github.io/GRDB.swift/docs/1.2/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/1.2/Functions.html) functions:
|
||||
|
||||
```swift
|
||||
// SQLExpression: COUNT(email)
|
||||
count(Column("email"))
|
||||
|
||||
// SQLExpression: COUNT(DISTINCT email)
|
||||
count(distinct: Column("email"))
|
||||
```
|
||||
|
||||
|
||||
#### The COLLATE Operator
|
||||
|
||||
Build a `expression COLLATE collation` expression with the `collating` method:
|
||||
|
||||
```swift
|
||||
// SQLExpression: name = 'Arthur' COLLATE NOCASE
|
||||
Column("name").collating(.nocase) == "Arthur"
|
||||
```
|
||||
|
||||
|
||||
## Add a New Kind of SQLite Expression
|
||||
|
||||
GRDB does not have built-in support for the full range of the SQLite [expression grammar](https://www.sqlite.org/lang_expr.html).
|
||||
|
||||
For example, [CAST expressions](https://www.sqlite.org/lang_expr.html#castexpr) are not ready-made. They can be useful, though: a CAST expression can efficiently convert json strings to UTF-8 data blobs for you:
|
||||
|
||||
```sql
|
||||
SELECT CAST(jsonString AS BLOB) FROM books
|
||||
```
|
||||
|
||||
We'll add below a Swift `cast` function:
|
||||
|
||||
```swift
|
||||
let request = Books.select(cast(Column("jsonString"), as: .blob))
|
||||
let jsonDatas = try Data.fetchAll(db, request) // [Data]
|
||||
```
|
||||
|
||||
`cast` is a top-level Swift function because this is how GRDB usually imports SQLite features which do not have matching standard Swift counterpart. It helps the Swift code looking like SQL when it is relevant. But YMMV.
|
||||
|
||||
The signature of the `cast` function is:
|
||||
|
||||
```swift
|
||||
func cast(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression
|
||||
```
|
||||
|
||||
Database.ColumnType is a String-based enumeration of all database column types (.integer, .text, .blob, etc.) You have already used if you have [created tables](../../../#create-tables) using the query interface.
|
||||
|
||||
The return type SQLExpression is the type returned by all GRDB functions and operators that build [query interface expressions](../../../#expressions).
|
||||
|
||||
SQLExpression is a protocol. But GRDB ships with a variety of [built-in expressions](#built-in-expressions) that are ready-made, so that you generally don't have to write your custom expression type. Here we need something new. So we'll use the most versatile of all, SQLExpressionLiteral:
|
||||
|
||||
```swift
|
||||
struct SQLExpressionLiteral : SQLExpression {
|
||||
/// Creates an SQL literal expression.
|
||||
///
|
||||
/// SQLExpressionLiteral("1 + 2")
|
||||
/// SQLExpressionLiteral("? + ?", arguments: [1, 2])
|
||||
init(_ sql: String, arguments: StatementArguments? = nil)
|
||||
}
|
||||
```
|
||||
|
||||
Here is the code that defines our `cast` function:
|
||||
|
||||
|
||||
```swift
|
||||
func cast(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression {
|
||||
// Turn the value into a literal expression
|
||||
let literal: SQLExpressionLiteral = value.sqlExpression.literal
|
||||
|
||||
// Build our "CAST(value AS type)" sql snippet
|
||||
let sql = "CAST(\(literal.sql) AS \(type.rawValue))"
|
||||
|
||||
// And return a new literal expression, preserving input arguments
|
||||
return SQLExpressionLiteral(sql, arguments: literal.arguments)
|
||||
}
|
||||
```
|
||||
|
||||
We haven't yet described the SQLExpressible type of the `value` argument:
|
||||
|
||||
SQLExpressible is the protocol for all types that can be turned into a SQL expression. This includes all [value types](../../../#values) (Bool, Int, String, Date, Swift enums, etc.):
|
||||
|
||||
```swift
|
||||
cast("foo", as: .blob) // SQLExpression: CAST('foo' AS BLOB)
|
||||
cast(Column("name"), as: .blob) // SQLExpression: CAST(name AS BLOB)
|
||||
```
|
||||
|
||||
You may want to compare it to another protocol, SQLSpecificExpressible, which has been described [above](#strftime), when we were adding support for the STRFTIME SQL function.
|
||||
|
||||
> :point_up: **Note**: whenever you extend GRDB with a Swift function, method, or operator, you should generally make sure that its signature contains at least one GRDB-specific type. In the `cast` function, it is Database.ColumnType.
|
||||
|
||||
**If SQLExpressionLiteral reveals too limited for your purpose**, you may have to implement a new type that adopts the [SQLExpression](http://groue.github.io/GRDB.swift/docs/1.2/Protocols/SQLExpression.html) protocol.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 47 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 39 KiB |
@@ -10,14 +10,12 @@ To release a new GRDB version:
|
||||
- Build and run GRDBDemoiOS in Release configuration on a device
|
||||
- Archive GRDBDemoiOS
|
||||
- Check for performance regression with GRDBOSXPerformanceTests
|
||||
- On SDK upgrade, update Support/sqlite3.h
|
||||
- On https://github.com/groue/sqlcipher.git upgrade, update SQLCipher version in README.md
|
||||
- On https://github.com/swiftlyfalling/SQLiteLib upgrade, update SQLite version in README.md and Documentation/CustomSQLiteBuilds.md
|
||||
- Update GRDB version number and release date in:
|
||||
- Makefile
|
||||
- CHANGELOG.md
|
||||
- Documentation/CustomSQLiteBuilds.md
|
||||
- Documentation/ExtendingGRDB.md
|
||||
- GRDB.swift.podspec
|
||||
- GRDBCipher.podspec
|
||||
- README.md
|
||||
@@ -25,9 +23,12 @@ To release a new GRDB version:
|
||||
- Commit and tag
|
||||
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
|
||||
- Push to the master branch
|
||||
- Push to the Swift3 branch
|
||||
- Push to the Swift4 branch
|
||||
- `pod trunk push --allow-warnings GRDB.swift.podspec`
|
||||
- `pod trunk push --allow-warnings GRDBCipher.podspec`
|
||||
- `make doc`, and update index.html in the `gh-pages` branch
|
||||
- Update http://github.com/groue/GRDBDemo
|
||||
- Update http://github.com/groue/WWDCCompanion
|
||||
- Update [performance comparison](https://github.com/groue/GRDB.swift/wiki/Performance):
|
||||
|
||||
`make test_performance | Tests/parsePerformanceTests.rb | Tests/generatePerformanceReport.rb`
|
||||
@@ -0,0 +1,280 @@
|
||||
Why Adopt GRDB?
|
||||
===============
|
||||
|
||||
This document aims at exposing why GRDB could become your favorite database library.
|
||||
|
||||
We'll start with a few [core principles](#core-principles), so that you see where this library aims at. Then we'll see how GRDB [solves problems](#solving-problems) that developers often face when they use database libraries such as FMDB, FCModel, SQLite.swift, Core Data, or Realm.
|
||||
|
||||
|
||||
## Core Principles
|
||||
|
||||
### It is generally easier to access a database through "record types".
|
||||
|
||||
This is because a database row is not an easy type to deal with, and will never be, compared to a regular model. `player.name` looks and feels more natural than `playerRow[nameColumn]`, doesn't it?
|
||||
|
||||
The reputation of "active records" and ORMs has been tarnished by the recent focus on immutability, memory safety, and functional idioms that comes with languages like Swift and Rust. Features of 1st-generation records such as auto-updating, uniquing, lazy loading of relations, etc. are now considered ill-advised, if not plain harmful because of the multi-threading headaches they cause.
|
||||
|
||||
Yet recent ORMs such as Rust's [Diesel] have shown that it is possible to build record types that behave as plain and simple values. GRDB belongs to this family.
|
||||
|
||||
|
||||
### Raw SQL is sometimes the correct tool for the job.
|
||||
|
||||
Complex database queries sometimes need to be prototyped and debugged in an SQL shell. Once perfected, the process of translating this raw SQL query into calls to a query builder can be long and painful, with no guarantee of success. And the resulting code often lacks the legibility of the initial SQL. When this happens, the query builder is no longer useful: whoever wants to write raw SQL should always be welcome.
|
||||
|
||||
|
||||
### The database file is the single source of truth.
|
||||
|
||||
Each Core Data's managed object context has its own version of the database. This can be useful when developing a macOS application full of inspector panels and nested undo stacks. But that's about it.
|
||||
|
||||
In the same vein, each application thread has its own version of a Realm database, with non trivial synchronization points.
|
||||
|
||||
Conversely, GRDB assumes that many apps want to use the database as a reliable and unambiguous storage.
|
||||
|
||||
|
||||
### Applications developers have specific needs.
|
||||
|
||||
GRDB puts all bets on SQLite, and focuses on front-end GUI applications.
|
||||
|
||||
This means that dealing with servers, MySQL, or PostgreSQL is out of scope. GRDB is not an alternative to IBM's [Swift-Kuery], Vapor's [Fluent], or Perfect's [StORM].
|
||||
|
||||
Focusing on SQLite and applications has allowed GRDB to build features usually only found in company-sponsored libraries: migrations, changes tracking, database observation, multi-threading safety, table view animations, support for reactive streams...
|
||||
|
||||
Some will call GRDB "opinionated", or "bloated". Well, the bet of GRDB is that developers can take great profit from a library that provides efficient and community-tested solutions to existing problems. For example, one can not address the multithreading difficulties of Core Data or Realm without looking at database concurrency and records straight in the face.
|
||||
|
||||
Since you don't have to take my words for granted, we'll now see how GRDB actually solves common problems that developers face with other database libraries.
|
||||
|
||||
|
||||
## Solving Problems
|
||||
|
||||
What is the purpose of the above principles, if not providing solutions to difficulties and limitations of other persistence libraries?
|
||||
|
||||
|
||||
### Allow any Swift struct or class to become a database record
|
||||
|
||||
Most libraries that provide record types want you to subclass a root class: NSManagedObject, Realm.Object, FCModel.
|
||||
|
||||
The main problem with those root classes is that they are classes. You can't define records from plain Swift structs, and leverage all advantages of Swift value types: immutability, multi-threading safety, etc.
|
||||
|
||||
With GRDB, any type can become a database record. For example, let's start from this `Place` struct:
|
||||
|
||||
```swift
|
||||
struct Place {
|
||||
var id: Int64?
|
||||
let title: String
|
||||
let coordinate: CLLocationCoordinate2D
|
||||
}
|
||||
```
|
||||
|
||||
By adopting the [RowConvertible] protocol, places can be loaded from SQL requests:
|
||||
|
||||
```swift
|
||||
extension Place: RowConvertible { ... }
|
||||
let places = try Place.fetchAll(db, "SELECT * FROM places") // [Place]
|
||||
```
|
||||
|
||||
Add the [TableMapping] protocol, and SQL requests are generated for you:
|
||||
|
||||
```swift
|
||||
extension Place: TableMapping { ... }
|
||||
let place = try Place.fetchOne(db, key: 1) // Place?
|
||||
```
|
||||
|
||||
Add the [Persistable] protocol, and places know how to insert, update and delete themselves:
|
||||
|
||||
```swift
|
||||
extension Place: Persistable { ... }
|
||||
try place.delete(db)
|
||||
```
|
||||
|
||||
Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with database change notifications, with many advantages.
|
||||
|
||||
|
||||
### Allow database records to cross threads
|
||||
|
||||
As soon as records are immutable values, they can safely be used from different threads. You no longer have to pass object ids or references between threads, as in Core Data or Realm:
|
||||
|
||||
```swift
|
||||
if let player = try Player.fetchOne(db, key: 1) {
|
||||
DispatchQueue.main.async {
|
||||
nameField.text = player.name
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Replace auto-updating records with notifications of database changes
|
||||
|
||||
GRDB records are plain values, like other values in your application. They are not tied to the database. Sometimes you build them from scratch, and sometimes you fetch them:
|
||||
|
||||
```swift
|
||||
let player = Player(name: "arthur", score: 1000)
|
||||
let players = try Player.fetchAll(db)
|
||||
```
|
||||
|
||||
**Fetched records behave just like an in-memory cache of the database content.** Your application is free to decide, on its own, how it should handle the lifetime of those cached values: by ignoring future database changes, by observing database changes and react accordingly, or in any way deemed relevant.
|
||||
|
||||
There are several ways to be notified of database changes. You can build on top of the low-level [TransactionObserver] protocol. Or you can use [FetchedRecordsController], which looks a lot like Core Data's NSFetchedResultsController, and is able to animate table and collection views. And don't forget [RxGRDB], a set of reactive extensions based on [RxSwift]:
|
||||
|
||||
```swift
|
||||
Player.all().rx
|
||||
.fetchAll(in: dbQueue)
|
||||
.subscribe(onNext: { players: [Player] in
|
||||
print("Players have changed")
|
||||
})
|
||||
```
|
||||
|
||||
No matter which observation technique you use, you have common guarantees:
|
||||
|
||||
First, notifications only come from database changes safely saved on disk. This is part of the "database as the single source of truth" core principle. You won't get notifications from unsaved changes or changes that have an opportunity to be rollbacked.
|
||||
|
||||
Next, you choose the dispatch queue on which notifications happen. It can be on the special "writer queue", which allows you to process changes before any other thread has any opportunity to perform further database modifications. But notifications can also happen on the queue of your choice (generally the main queue, by default, as in the example above). Of course, GRDB makes sure notifications happen in the same order as database transactions.
|
||||
|
||||
Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, and even SQL triggers.
|
||||
|
||||
|
||||
### Non-blocking database reads
|
||||
|
||||
GRDB ships with two ways to access databases, [database queues](https://github.com/groue/GRDB.swift/blob/master/README.md#database-queues) and [pools](https://github.com/groue/GRDB.swift/blob/master/README.md#database-pools).
|
||||
|
||||
Database queues look a lot like FMDB's [FMDatabaseQueue](https://github.com/ccgus/fmdb#using-fmdatabasequeue-and-thread-safety): they serialize database accesses in a serial dispatch queue. There is never more than one thread that is accessing the database. This means that a long running database transaction that happens in a background thread, such as the synchronization of your local database from a remote server, can block your UI. As long as the queue is busy, the main thread can't fetch the values it wants to display on screen.
|
||||
|
||||
[Database pools](https://github.com/groue/GRDB.swift/blob/master/README.md#database-pools) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured).
|
||||
|
||||
|
||||
### Strong and clear multi-threading guarantees
|
||||
|
||||
I'd like to compare GRDB's handling of concurrency with other libraries. To be as clear as possible, we'll identity a few threats, or potential sources of bugs, and wonder if those are handled by the library, or left to the host application.
|
||||
|
||||
The more threats are handled by the application, the more skilled and careful a developer has to be in order to avoid them.
|
||||
|
||||
- **Concurrent writes**: Two threads want to write in the database as the same time. SQLite does not allow that.
|
||||
- **Isolation troubles**: As two database queries run one after the other, a concurrent thread sneaks in and modifies the database in between. The two queries can thus perform inconsistent fetches or updates, unless they are properly isolated. Lack of isolation may display funny values on the screen, trigger a relational constraint error, or silently corrupt the database content.
|
||||
- **Conflicts**: The same piece of data is both edited by the application user, and refreshed from a network operation. What will eventually be stored in the database? Can any conflict be noticed?
|
||||
- **Blocked UI**: Can it happen that the UI is blocked because the main thread has to wait for a background thread to release a lock on the database?
|
||||
|
||||
|
||||
| Library | Concurrent Writes | Isolation Trouble | Conflicts | Blocked UI |
|
||||
| ------- | ----------------- | ----------------- | --------- | ---------- |
|
||||
| FMDB's FMDatabase | Handled by the application | Handled by the application | Handled by the application | Handled by the application |
|
||||
| FMDB's FMDatabaseQueue | :white_check_mark: | :white_check_mark: | Handled by the application | UI is blocked |
|
||||
| SQLite.swift | :white_check_mark: | Handled by the application | Handled by the application | Handled by the application |
|
||||
| Core Data | Handled by the application, because of the constant threat of conflict errors | :white_check_mark: | Handled by the application, and it is very difficult because of the subtleties of Core Data's conflict policies | Handled by the application |
|
||||
| GRDB's DatabaseQueue | :white_check_mark: | :white_check_mark: | Handled by the application | UI is blocked |
|
||||
| GRDB's DatabasePool | :white_check_mark: | :white_check_mark: | Handled by the application | :white_check_mark: (as long as the maximum number of readers has not been reached) |
|
||||
|
||||
I had to omit Realm and FCModel from the list, because I don't know them well enough. Yet I'd bet that Realm shares some behaviors with Core Data, and FCModel shares some behaviors with FMDatabaseQueue.
|
||||
|
||||
We can see that the threat of conflicts is *always* left to the application. Core Data provides conflict policies, but no one can pretend that they are easy to use or test. This is an argument for leaving the application 100% responsible for conflict handling, in hope that simple ones can be handled in a simple way. A weaker way to say this is that conflict handling at the library level can wait :sweat_smile:.
|
||||
|
||||
Finally, raw FMDatabase, SQLite.swift, and Core Data are the hardest tools, and you'd better be a very skilled developer in order to use them properly.
|
||||
|
||||
For further information about GRDB concurrency, check its detailed [Concurrency Guide].
|
||||
|
||||
|
||||
### Never pay for using raw SQL
|
||||
|
||||
SQL is a weird language. Born in the 70s, easy to [misuse](https://xkcd.com/327/), feared by some developers, despised by others, and yet wonderfully concise and powerful.
|
||||
|
||||
GRDB provides high-level record methods that generate SQL for you:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM players ORDER BY score DESC LIMIT 10
|
||||
let bestPlayers: [Player] = try Player
|
||||
.order(scoreColumn.desc)
|
||||
.limit(10)
|
||||
.fetchAll(db)
|
||||
|
||||
// SELECT MAX(score) FROM players
|
||||
let maximumScore: Int? = try Player
|
||||
.select(max(scoreColumn))
|
||||
.asRequestOf(Int.self)
|
||||
.fetchOne(db)
|
||||
|
||||
// SELECT COUNT(*) FROM players WHERE score = ?
|
||||
let exAequoCount: Int = try Player
|
||||
.filter(scoreColumn == maximumScore)
|
||||
.fetchCount(db)
|
||||
```
|
||||
|
||||
But you can *always* switch to SQL when you want to:
|
||||
|
||||
```swift
|
||||
let bestPlayers: [Player] = try Player.fetchAll(db, """
|
||||
SELECT * FROM players ORDER BY score DESC LIMIT 10
|
||||
""")
|
||||
|
||||
let maximumScore: Int? = try Int.fetchOne(db, """
|
||||
SELECT MAX(score) FROM players
|
||||
""")
|
||||
|
||||
let exAequoCount: Int? = try Int.fetchOne(db, """
|
||||
SELECT COUNT(*) FROM players WHERE score = ?
|
||||
""", arguments: [maximumScore])
|
||||
```
|
||||
|
||||
SQL is also welcome in high-level database observation tools like [FetchedRecordsController] and [RxGRDB]:
|
||||
|
||||
```swift
|
||||
SQLRequest("SELECT * FROM players ORDER BY score DESC LIMIT 10")
|
||||
.asRequest(of: Player.self)
|
||||
.rx
|
||||
.fetchAll(in: dbQueue)
|
||||
.subscribe(onNext: { players: [Player] in
|
||||
print("Best 10 players have changed")
|
||||
})
|
||||
```
|
||||
|
||||
You can of course deal with raw database rows, and fetch [lazy cursors](https://github.com/groue/GRDB.swift/blob/master/README.md#cursors) instead of arrays:
|
||||
|
||||
```swift
|
||||
let rows = try Row.fetchCursor(db, "SELECT * FROM players")
|
||||
while let row = try rows.next() {
|
||||
let id: Int64 = row["id"]
|
||||
let name: String = row["name"]
|
||||
let score: Int = row["score"]
|
||||
}
|
||||
```
|
||||
|
||||
When you feel like your code clarity would be enhanced by hiding your custom SQL in a dedicated method, you can build [custom requests](https://github.com/groue/GRDB.swift/blob/master/README.md#custom-requests):
|
||||
|
||||
```swift
|
||||
extension Player {
|
||||
static func customRequest(...) -> AnyTypedRequest<Player> {
|
||||
return SQLRequest("""
|
||||
SELECT ...
|
||||
""", arguments: ...)
|
||||
.asRequestOf(Player.self)
|
||||
}
|
||||
}
|
||||
|
||||
let players = Player.customRequest(...).fetchAll(db)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
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]: https://github.com/groue/GRDB.swift/blob/master/README.md#concurrency
|
||||
[Core Data]: https://developer.apple.com/documentation/coredata
|
||||
[DatabasePool]: https://github.com/groue/GRDB.swift/blob/master/README.md#database-pools
|
||||
[Diesel]: http://diesel.rs
|
||||
[FCModel]: https://github.com/marcoarment/FCModel
|
||||
[FetchedRecordsController]: https://github.com/groue/GRDB.swift/blob/master/README.md#fetchedrecordscontroller
|
||||
[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
|
||||
[Persistable]: https://github.com/groue/GRDB.swift/blob/master/README.md#records
|
||||
[Realm]: http://realm.io
|
||||
[RowConvertible]: https://github.com/groue/GRDB.swift/blob/master/README.md#records
|
||||
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
|
||||
[RxSwift]: https://github.com/ReactiveX/RxSwift
|
||||
[SQLite.swift]: http://github.com/stephencelis/SQLite.swift
|
||||
[StORM]: https://www.perfect.org/docs/StORM.html
|
||||
[Swift-Kuery]: http://github.com/IBM-Swift/Swift-Kuery
|
||||
[TableMapping]: https://github.com/groue/GRDB.swift/blob/master/README.md#records
|
||||
[TransactionObserver]: https://github.com/groue/GRDB.swift/blob/master/README.md#transactionobserver-protocol
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '1.2'
|
||||
s.version = '2.9.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A Swift application toolkit for SQLite databases.'
|
||||
@@ -13,7 +13,7 @@ Pod::Spec.new do |s|
|
||||
s.osx.deployment_target = '10.9'
|
||||
s.watchos.deployment_target = '2.0'
|
||||
|
||||
s.source_files = 'GRDB/**/*.swift', 'Support/*.{c,h}'
|
||||
s.source_files = 'GRDB/**/*.swift', 'Support/*.h'
|
||||
s.module_map = 'Support/module.modulemap'
|
||||
s.framework = 'Foundation'
|
||||
s.library = 'sqlite3'
|
||||
|
||||
+406
-3625
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0810"
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Release"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56439B2D1F4CA1DC0066043F"
|
||||
BuildableName = "GRDBOSXPerformanceComparisonTests.xctest"
|
||||
BlueprintName = "GRDBOSXPerformanceComparisonTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0730"
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -10,6 +10,7 @@
|
||||
buildConfiguration = "Release"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
@@ -30,6 +31,7 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0810"
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0810"
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
+24
@@ -16,13 +16,37 @@
|
||||
<FileRef
|
||||
location = "group:TransactionObserver.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Issue156.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:MyPlayground.playground">
|
||||
</FileRef>
|
||||
</Group>
|
||||
<FileRef
|
||||
location = "group:CHANGELOG.md">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:README.md">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:TODO.md">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Documentation/ReleaseProcess.md">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Makefile">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:GRDB.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:GRDBCustom.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:GRDBCipher.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj">
|
||||
</FileRef>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import Foundation
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// Configuration for a DatabaseQueue or DatabasePool.
|
||||
@@ -42,6 +43,38 @@ public struct Configuration {
|
||||
/// Default: deferred
|
||||
public var defaultTransactionKind: Database.TransactionKind = .deferred
|
||||
|
||||
/// If false, it is a programmer error to leave a transaction opened at the
|
||||
/// end of a database access block.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
///
|
||||
/// // fatal error: A transaction has been left opened at the end of a database access
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.beginTransaction()
|
||||
/// }
|
||||
///
|
||||
/// If true, one can leave opened transaction at the end of database access
|
||||
/// blocks:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.allowsUnsafeTransactions = true
|
||||
/// let dbQueue = DatabaseQueue(configuration: config)
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.beginTransaction()
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.commit()
|
||||
/// }
|
||||
///
|
||||
/// This configuration flag has no effect on DatabasePool readers: those
|
||||
/// never allow leaving a transaction opened at the end of a read access.
|
||||
///
|
||||
/// Default: false
|
||||
public var allowsUnsafeTransactions: Bool = false
|
||||
|
||||
// MARK: - Concurrency
|
||||
|
||||
|
||||
+499
-70
@@ -1,3 +1,16 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// Parts of this file are derived from the Swift.org open source project:
|
||||
//
|
||||
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// MARK: - Array, Sequence, Set extensions
|
||||
|
||||
extension Array {
|
||||
/// Creates an array containing the elements of a cursor.
|
||||
///
|
||||
@@ -11,6 +24,30 @@ extension Array {
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<IteratorCursor<Iterator>, SegmentOfResult>> {
|
||||
return IteratorCursor(self).flatMap(transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension Set {
|
||||
/// Creates a set containing the elements of a cursor.
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, "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.
|
||||
///
|
||||
/// ## Overview
|
||||
@@ -33,19 +70,11 @@ extension Array {
|
||||
/// - A cursor can not be repeated.
|
||||
///
|
||||
/// The protocol comes with default implementations for many operations similar
|
||||
/// to those defined by Swift's LazySequenceProtocol:
|
||||
///
|
||||
/// - `func contains(Self.Element)`
|
||||
/// - `func contains(where: (Self.Element) throws -> Bool)`
|
||||
/// - `func enumerated()`
|
||||
/// - `func filter((Self.Element) throws -> Bool)`
|
||||
/// - `func first(where: (Self.Element) throws -> Bool)`
|
||||
/// - `func flatMap<ElementOfResult>((Self.Element) throws -> ElementOfResult?)`
|
||||
/// - `func flatMap<SegmentOfResult>((Self.Element) throws -> SegmentOfResult)`
|
||||
/// - `func forEach((Self.Element) throws -> Void)`
|
||||
/// - `func joined()`
|
||||
/// - `func map<T>((Self.Element) throws -> T)`
|
||||
/// - `func reduce<Result>(Result, (Result, Self.Element) throws -> Result)`
|
||||
/// to those defined by Swift's Sequence protocol: `contains`, `dropFirst`,
|
||||
/// `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`,
|
||||
/// `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`,
|
||||
/// `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`,
|
||||
/// `suffix`.
|
||||
public protocol Cursor : class {
|
||||
/// The type of element traversed by the cursor.
|
||||
associatedtype Element
|
||||
@@ -55,32 +84,6 @@ public protocol Cursor : class {
|
||||
func next() throws -> Element?
|
||||
}
|
||||
|
||||
/// A type-erased cursor of Element.
|
||||
///
|
||||
/// This cursor forwards its next() method to an arbitrary underlying cursor
|
||||
/// having the same Element type, hiding the specifics of the underlying
|
||||
/// cursor.
|
||||
public class AnyCursor<Element> : Cursor {
|
||||
/// Creates a cursor that wraps a base cursor but whose type depends only on
|
||||
/// the base cursor’s element type
|
||||
public init<C: Cursor>(_ base: C) where C.Element == Element {
|
||||
element = base.next
|
||||
}
|
||||
|
||||
/// Creates a cursor that wraps the given closure in its next() method
|
||||
public init(_ body: @escaping () throws -> Element?) {
|
||||
element = body
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
public func next() throws -> Element? {
|
||||
return try element()
|
||||
}
|
||||
|
||||
private let element: () throws -> Element?
|
||||
}
|
||||
|
||||
extension Cursor {
|
||||
/// Returns a Boolean value indicating whether the cursor contains an
|
||||
/// element that satisfies the given predicate.
|
||||
@@ -135,6 +138,102 @@ extension Cursor {
|
||||
return map(transform).filter { $0 != nil }.map { $0! }
|
||||
}
|
||||
|
||||
/// Returns a cursor that skips any initial elements that satisfy
|
||||
/// `predicate`.
|
||||
///
|
||||
/// - Parameter predicate: A closure that takes an element of the cursir as
|
||||
/// its argument and returns `true` if the element should be skipped or
|
||||
/// `false` otherwise. Once `predicate` returns `false` it will not be
|
||||
/// called again.
|
||||
public func drop(while predicate: @escaping (Element) throws -> Bool) -> DropWhileCursor<Self> {
|
||||
return DropWhileCursor(self, predicate: predicate)
|
||||
}
|
||||
|
||||
/// Returns a cursor containing all but the given number of initial
|
||||
/// elements.
|
||||
///
|
||||
/// If the number of elements to drop exceeds the number of elements in
|
||||
/// the cursor, the result is an empty cursor.
|
||||
///
|
||||
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropFirst(2))
|
||||
/// // Prints "[3, 4, 5]"
|
||||
/// try print(numbers.dropFirst(10))
|
||||
/// // Prints "[]"
|
||||
///
|
||||
/// - Parameter n: The number of elements to drop from the beginning of
|
||||
/// the cursor. `n` must be greater than or equal to zero.
|
||||
/// - Returns: A cursor starting after the specified number of
|
||||
/// elements.
|
||||
public func dropFirst(_ n: Int) -> DropFirstCursor<Self> {
|
||||
return DropFirstCursor(self, limit: n)
|
||||
}
|
||||
|
||||
/// Returns a cursor containing all but the first element of the cursor.
|
||||
///
|
||||
/// The following example drops the first element from a cursor of integers.
|
||||
///
|
||||
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropFirst())
|
||||
/// // Prints "[2, 3, 4, 5]"
|
||||
///
|
||||
/// If the cursor has no elements, the result is an empty cursor.
|
||||
///
|
||||
/// - Returns: A cursor starting after the first element of the cursor.
|
||||
public func dropFirst() -> DropFirstCursor<Self> {
|
||||
return dropFirst(1)
|
||||
}
|
||||
|
||||
/// Returns an array containing all but the given number of final
|
||||
/// elements.
|
||||
///
|
||||
/// The cursor must be finite. If the number of elements to drop exceeds
|
||||
/// the number of elements in the cursor, the result is an empty array.
|
||||
///
|
||||
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropLast(2))
|
||||
/// // Prints "[1, 2, 3]"
|
||||
/// try print(numbers.dropLast(10))
|
||||
/// // Prints "[]"
|
||||
///
|
||||
/// - Parameter n: The number of elements to drop off the end of the
|
||||
/// cursor. `n` must be greater than or equal to zero.
|
||||
/// - Returns: An array leaving off the specified number of elements.
|
||||
public func dropLast(_ n: Int) throws -> [Element] {
|
||||
GRDBPrecondition(n >= 0, "Can't drop a negative number of elements from a cursor")
|
||||
if n == 0 { return try Array(self) }
|
||||
|
||||
var result: [Element] = []
|
||||
var ringBuffer: [Element] = []
|
||||
var i = ringBuffer.startIndex
|
||||
|
||||
while let element = try next() {
|
||||
if ringBuffer.count < n {
|
||||
ringBuffer.append(element)
|
||||
} else {
|
||||
result.append(ringBuffer[i])
|
||||
ringBuffer[i] = element
|
||||
i = ringBuffer.index(after: i) % n
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/// Returns an array containing all but the last element of the cursor.
|
||||
///
|
||||
/// The following example drops the last element from a cursor of integers.
|
||||
///
|
||||
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropLast())
|
||||
/// // Prints "[1, 2, 3, 4]"
|
||||
///
|
||||
/// If the cursor has no elements, the result is an empty cursor.
|
||||
///
|
||||
/// - Returns: An array leaving off the last element of the cursor.
|
||||
public func dropLast() throws -> [Element] {
|
||||
return try dropLast(1)
|
||||
}
|
||||
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult: Sequence>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, IteratorCursor<SegmentOfResult.Iterator>>> {
|
||||
@@ -160,17 +259,152 @@ extension Cursor {
|
||||
return MapCursor(self, transform)
|
||||
}
|
||||
|
||||
/// Returns the result of calling the given combining closure with each
|
||||
/// element of this sequence and an accumulating value.
|
||||
public func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) throws -> Result {
|
||||
var result = initialResult
|
||||
while let element = try next() {
|
||||
result = try nextPartialResult(result, element)
|
||||
/// Returns the maximum element in the cursor, using the given predicate as
|
||||
/// the comparison between elements.
|
||||
///
|
||||
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
|
||||
/// if its first argument should be ordered before its second
|
||||
/// argument; otherwise, `false`.
|
||||
/// - Returns: The cursor's maximum element, according to
|
||||
/// `areInIncreasingOrder`. If the cursor has no elements, returns `nil`.
|
||||
public func max(by areInIncreasingOrder: (Element, Element) throws -> Bool) throws -> Element? {
|
||||
guard var result = try next() else {
|
||||
return nil
|
||||
}
|
||||
while let e = try next() {
|
||||
if try areInIncreasingOrder(result, e) {
|
||||
result = e
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/// Returns the minimum element in the cursor, using the given predicate as
|
||||
/// the comparison between elements.
|
||||
///
|
||||
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
|
||||
/// if its first argument should be ordered before its second
|
||||
/// argument; otherwise, `false`.
|
||||
/// - Returns: The cursor's minimum element, according to
|
||||
/// `areInIncreasingOrder`. If the cursor has no elements, returns `nil`.
|
||||
public func min(by areInIncreasingOrder: (Element, Element) throws -> Bool) throws -> Element? {
|
||||
guard var result = try next() else {
|
||||
return nil
|
||||
}
|
||||
while let e = try next() {
|
||||
if try areInIncreasingOrder(e, result) {
|
||||
result = e
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/// Returns a cursor, up to the specified maximum length, containing the
|
||||
/// initial elements of the cursor.
|
||||
///
|
||||
/// If the maximum length exceeds the number of elements in the cursor,
|
||||
/// the result contains all the elements in the cursor.
|
||||
///
|
||||
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.prefix(2))
|
||||
/// // Prints "[1, 2]"
|
||||
/// try print(numbers.prefix(10))
|
||||
/// // Prints "[1, 2, 3, 4, 5]"
|
||||
///
|
||||
/// - Parameter maxLength: The maximum number of elements to return. The
|
||||
/// value of `maxLength` must be greater than or equal to zero.
|
||||
/// - Returns: A cursor starting at the beginning of this cursor
|
||||
/// with at most `maxLength` elements.
|
||||
public func prefix(_ maxLength: Int) -> PrefixCursor<Self> {
|
||||
return PrefixCursor(self, maxLength: maxLength)
|
||||
}
|
||||
|
||||
/// Returns a cursor of the initial consecutive elements that satisfy
|
||||
/// `predicate`.
|
||||
///
|
||||
/// - Parameter predicate: A closure that takes an element of the cursor as
|
||||
/// its argument and returns `true` if the element should be included or
|
||||
/// `false` otherwise. Once `predicate` returns `false` it will not be
|
||||
/// called again.
|
||||
public func prefix(while predicate: @escaping (Element) throws -> Bool) -> PrefixWhileCursor<Self> {
|
||||
return PrefixWhileCursor(self, predicate: predicate)
|
||||
}
|
||||
|
||||
/// Returns the result of calling the given combining closure with each
|
||||
/// element of this cursor and an accumulating value.
|
||||
public func reduce<Result>(
|
||||
_ initialResult: Result,
|
||||
_ nextPartialResult: (Result, Element) throws -> Result)
|
||||
throws -> Result
|
||||
{
|
||||
var accumulator = initialResult
|
||||
while let element = try next() {
|
||||
accumulator = try nextPartialResult(accumulator, element)
|
||||
}
|
||||
return accumulator
|
||||
}
|
||||
|
||||
/// Returns the result of calling the given combining closure with each
|
||||
/// element of this cursor and an accumulating value.
|
||||
public func reduce<Result>(
|
||||
into initialResult: Result,
|
||||
_ updateAccumulatingResult: (inout Result, Element) throws -> Void)
|
||||
throws -> Result
|
||||
{
|
||||
var accumulator = initialResult
|
||||
while let element = try next() {
|
||||
try updateAccumulatingResult(&accumulator, element)
|
||||
}
|
||||
return accumulator
|
||||
}
|
||||
|
||||
/// Returns an array, up to the given maximum length, containing the
|
||||
/// final elements of the cursor.
|
||||
///
|
||||
/// The cursor must be finite. If the maximum length exceeds the number of
|
||||
/// elements in the cursor, the result contains all the elements in the
|
||||
/// cursor.
|
||||
///
|
||||
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.suffix(2))
|
||||
/// // Prints "[4, 5]"
|
||||
/// try print(numbers.suffix(10))
|
||||
/// // Prints "[1, 2, 3, 4, 5]"
|
||||
///
|
||||
/// - Parameter maxLength: The maximum number of elements to return. The
|
||||
/// value of `maxLength` must be greater than or equal to zero.
|
||||
public func suffix(_ maxLength: Int) throws -> [Element] {
|
||||
GRDBPrecondition(maxLength >= 0, "Can't take a suffix of negative length from a cursor")
|
||||
if maxLength == 0 {
|
||||
return []
|
||||
}
|
||||
|
||||
var ringBuffer: [Element] = []
|
||||
ringBuffer.reserveCapacity(maxLength)
|
||||
|
||||
var i = ringBuffer.startIndex
|
||||
|
||||
while let element = try next() {
|
||||
if ringBuffer.count < maxLength {
|
||||
ringBuffer.append(element)
|
||||
} else {
|
||||
ringBuffer[i] = element
|
||||
i += 1
|
||||
i %= maxLength
|
||||
}
|
||||
}
|
||||
|
||||
if i != ringBuffer.startIndex {
|
||||
let s0 = ringBuffer[i..<ringBuffer.endIndex]
|
||||
let s1 = ringBuffer[0..<i]
|
||||
return Array([s0, s1].joined())
|
||||
}
|
||||
return ringBuffer
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Equatable elements
|
||||
|
||||
extension Cursor where Element: Equatable {
|
||||
/// Returns a Boolean value indicating whether the cursor contains the
|
||||
/// given element.
|
||||
@@ -184,6 +418,36 @@ extension Cursor where Element: Equatable {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Comparable elements
|
||||
|
||||
extension Cursor where Element: Comparable {
|
||||
/// Returns the maximum element in the cursor.
|
||||
///
|
||||
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
|
||||
/// if its first argument should be ordered before its second
|
||||
/// argument; otherwise, `false`.
|
||||
/// - Returns: The cursor's maximum element, according to
|
||||
/// `areInIncreasingOrder`. If the cursor has no elements, returns
|
||||
/// `nil`.
|
||||
public func max() throws -> Element? {
|
||||
return try max(by: <)
|
||||
}
|
||||
|
||||
/// Returns the minimum element in the cursor.
|
||||
///
|
||||
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
|
||||
/// if its first argument should be ordered before its second
|
||||
/// argument; otherwise, `false`.
|
||||
/// - Returns: The cursor's minimum element, according to
|
||||
/// `areInIncreasingOrder`. If the cursor has no elements, returns
|
||||
/// `nil`.
|
||||
public func min() throws -> Element? {
|
||||
return try min(by: <)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Cursor elements
|
||||
|
||||
extension Cursor where Element: Cursor {
|
||||
/// Returns the elements of this cursor of cursors, concatenated.
|
||||
public func joined() -> FlattenCursor<Self> {
|
||||
@@ -191,13 +455,122 @@ extension Cursor where Element: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Sequence elements
|
||||
|
||||
extension Cursor where Element: Sequence {
|
||||
/// Returns the elements of this cursor of sequences, concatenated.
|
||||
public func joined() -> FlattenCursor<MapCursor<Self, IteratorCursor<Self.Element.Iterator>>> {
|
||||
public func joined() -> FlattenCursor<MapCursor<Self, IteratorCursor<Element.Iterator>>> {
|
||||
return flatMap { $0 }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: String elements
|
||||
|
||||
extension Cursor where Element: StringProtocol {
|
||||
/// Returns the elements of this cursor of sequences, concatenated.
|
||||
public func joined(separator: String = "") throws -> String {
|
||||
if separator.isEmpty {
|
||||
var result = ""
|
||||
while let x = try next() {
|
||||
result.append(String(x))
|
||||
}
|
||||
return result
|
||||
} else {
|
||||
var result = ""
|
||||
if let first = try next() {
|
||||
result.append(String(first))
|
||||
while let next = try next() {
|
||||
result.append(separator)
|
||||
result.append(String(next))
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Specialized Cursors
|
||||
|
||||
/// A type-erased cursor of Element.
|
||||
///
|
||||
/// This cursor forwards its next() method to an arbitrary underlying cursor
|
||||
/// having the same Element type, hiding the specifics of the underlying
|
||||
/// cursor.
|
||||
public class AnyCursor<Element> : Cursor {
|
||||
private let element: () throws -> Element?
|
||||
|
||||
/// Creates a cursor that wraps a base cursor but whose type depends only on
|
||||
/// the base cursor’s element type
|
||||
public init<C: Cursor>(_ base: C) where C.Element == Element {
|
||||
element = base.next
|
||||
}
|
||||
|
||||
/// Creates a cursor that wraps the given closure in its next() method
|
||||
public init(_ body: @escaping () throws -> Element?) {
|
||||
element = body
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
/// :nodoc:
|
||||
public func next() throws -> Element? {
|
||||
return try element()
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public final class DropFirstCursor<Base: Cursor> : Cursor {
|
||||
private let base: Base
|
||||
private let limit: Int
|
||||
private var dropped: Int = 0
|
||||
|
||||
init(_ base: Base, limit: Int) {
|
||||
GRDBPrecondition(limit >= 0, "Can't drop a negative number of elements from a cursor")
|
||||
self.base = base
|
||||
self.limit = limit
|
||||
}
|
||||
|
||||
public func next() throws -> Base.Element? {
|
||||
while dropped < limit {
|
||||
if try base.next() == nil {
|
||||
dropped = limit
|
||||
return nil
|
||||
}
|
||||
dropped += 1
|
||||
}
|
||||
return try base.next()
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor whose elements consist of the elements that follow the initial
|
||||
/// consecutive elements of some base cursor that satisfy a given predicate.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class DropWhileCursor<Base: Cursor> : Cursor {
|
||||
private let base: Base
|
||||
private let predicate: (Base.Element) throws -> Bool
|
||||
private var predicateHasFailed = false
|
||||
|
||||
init(_ base: Base, predicate: @escaping (Base.Element) throws -> Bool) {
|
||||
self.base = base
|
||||
self.predicate = predicate
|
||||
}
|
||||
|
||||
public func next() throws -> Base.Element? {
|
||||
if predicateHasFailed {
|
||||
return try base.next()
|
||||
}
|
||||
|
||||
while let nextElement = try base.next() {
|
||||
if try !predicate(nextElement) {
|
||||
predicateHasFailed = true
|
||||
return nextElement
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// An enumeration of the elements of a cursor.
|
||||
///
|
||||
/// To create an instance of `EnumeratedCursor`, call the `enumerated()` method
|
||||
@@ -210,27 +583,35 @@ extension Cursor where Element: Sequence {
|
||||
/// }
|
||||
/// // Prints: "0: foo"
|
||||
/// // Prints: "1: bar"
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class EnumeratedCursor<Base: Cursor> : Cursor {
|
||||
private let base: Base
|
||||
private var index: Int
|
||||
|
||||
init(_ base: Base) {
|
||||
self.index = 0
|
||||
self.base = base
|
||||
self.index = 0
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
/// :nodoc:
|
||||
public func next() throws -> (Int, Base.Element)? {
|
||||
guard let element = try base.next() else { return nil }
|
||||
defer { index += 1 }
|
||||
return (index, element)
|
||||
}
|
||||
|
||||
private var index: Int
|
||||
private var base: Base
|
||||
}
|
||||
|
||||
/// A cursor whose elements consist of the elements of some base cursor that
|
||||
/// also satisfy a given predicate.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class FilterCursor<Base: Cursor> : Cursor {
|
||||
private let base: Base
|
||||
private let isIncluded: (Base.Element) throws -> Bool
|
||||
|
||||
init(_ base: Base, _ isIncluded: @escaping (Base.Element) throws -> Bool) {
|
||||
self.base = base
|
||||
self.isIncluded = isIncluded
|
||||
@@ -238,6 +619,7 @@ public final class FilterCursor<Base: Cursor> : Cursor {
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
/// :nodoc:
|
||||
public func next() throws -> Base.Element? {
|
||||
while let element = try base.next() {
|
||||
if try isIncluded(element) {
|
||||
@@ -246,22 +628,25 @@ public final class FilterCursor<Base: Cursor> : Cursor {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private let base: Base
|
||||
private let isIncluded: (Base.Element) throws -> Bool
|
||||
}
|
||||
|
||||
/// A cursor consisting of all the elements contained in each segment contained
|
||||
/// in some Base cursor.
|
||||
///
|
||||
/// See Cursor.joined(), Cursor.flatMap(_:), Sequence.flatMap(_:)
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Cursor {
|
||||
private let base: Base
|
||||
private var inner: Base.Element?
|
||||
|
||||
init(_ base: Base) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
/// :nodoc:
|
||||
public func next() throws -> Base.Element.Element? {
|
||||
while true {
|
||||
if let element = try inner?.next() {
|
||||
@@ -273,16 +658,18 @@ public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Curs
|
||||
self.inner = inner
|
||||
}
|
||||
}
|
||||
|
||||
private var inner: Base.Element?
|
||||
private let base: Base
|
||||
}
|
||||
|
||||
/// A Cursor whose elements consist of those in a Base Cursor passed through a
|
||||
/// transform function returning Element.
|
||||
///
|
||||
/// See Cursor.map(_:)
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class MapCursor<Base: Cursor, Element> : Cursor {
|
||||
private let base: Base
|
||||
private let transform: (Base.Element) throws -> Element
|
||||
|
||||
init(_ base: Base, _ transform: @escaping (Base.Element) throws -> Element) {
|
||||
self.base = base
|
||||
self.transform = transform
|
||||
@@ -290,18 +677,70 @@ public final class MapCursor<Base: Cursor, Element> : Cursor {
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
/// :nodoc:
|
||||
public func next() throws -> Element? {
|
||||
guard let element = try base.next() else { return nil }
|
||||
return try transform(element)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// A cursor that only consumes up to `n` elements from an underlying
|
||||
/// `Base` cursor.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class PrefixCursor<Base: Cursor> : Cursor {
|
||||
private let base: Base
|
||||
private let transform: (Base.Element) throws -> Element
|
||||
private let maxLength: Int
|
||||
private var taken = 0
|
||||
|
||||
init(_ base: Base, maxLength: Int) {
|
||||
self.base = base
|
||||
self.maxLength = maxLength
|
||||
}
|
||||
|
||||
public func next() throws -> Base.Element? {
|
||||
if taken >= maxLength { return nil }
|
||||
taken += 1
|
||||
|
||||
if let next = try base.next() {
|
||||
return next
|
||||
}
|
||||
|
||||
taken = maxLength
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor whose elements consist of the initial consecutive elements of
|
||||
/// some base cursor that satisfy a given predicate.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class PrefixWhileCursor<Base: Cursor> : Cursor {
|
||||
private let base: Base
|
||||
private let predicate: (Base.Element) throws -> Bool
|
||||
private var predicateHasFailed = false
|
||||
|
||||
init(_ base: Base, predicate: @escaping (Base.Element) throws -> Bool) {
|
||||
self.base = base
|
||||
self.predicate = predicate
|
||||
}
|
||||
|
||||
public func next() throws -> Base.Element? {
|
||||
if !predicateHasFailed, let nextElement = try base.next() {
|
||||
if try predicate(nextElement) {
|
||||
return nextElement
|
||||
} else {
|
||||
predicateHasFailed = true
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// A Cursor whose elements are those of a sequence iterator.
|
||||
public final class IteratorCursor<Base: IteratorProtocol> : Cursor {
|
||||
|
||||
private var base: Base
|
||||
|
||||
/// Creates a cursor from a sequence iterator.
|
||||
public init(_ base: Base) {
|
||||
self.base = base
|
||||
@@ -314,18 +753,8 @@ public final class IteratorCursor<Base: IteratorProtocol> : Cursor {
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
/// :nodoc:
|
||||
public func next() -> Base.Element? {
|
||||
return base.next()
|
||||
}
|
||||
|
||||
private var base: Base
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<IteratorCursor<Self.Iterator>, SegmentOfResult>> {
|
||||
return IteratorCursor(self).flatMap(transform)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,530 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Database Schema
|
||||
|
||||
/// Clears the database schema cache.
|
||||
///
|
||||
/// You may need to clear the cache manually if the database schema is
|
||||
/// modified by another connection.
|
||||
public func clearSchemaCache() {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
schemaCache.clear()
|
||||
|
||||
// We also clear updateStatementCache and selectStatementCache 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()
|
||||
publicStatementCache.clear()
|
||||
}
|
||||
|
||||
/// Returns whether a table exists.
|
||||
public func tableExists(_ tableName: String) throws -> Bool {
|
||||
// SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html)
|
||||
return try Row.fetchOne(self, "SELECT 1 FROM (SELECT sql, type, name FROM sqlite_master UNION SELECT sql, type, name FROM sqlite_temp_master) WHERE type = 'table' AND LOWER(name) = ?", arguments: [tableName.lowercased()]) != nil
|
||||
}
|
||||
|
||||
/// Returns whether a view exists.
|
||||
public func viewExists(_ viewName: String) throws -> Bool {
|
||||
// SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html)
|
||||
return try Row.fetchOne(self, "SELECT 1 FROM (SELECT sql, type, name FROM sqlite_master UNION SELECT sql, type, name FROM sqlite_temp_master) WHERE type = 'view' AND LOWER(name) = ?", arguments: [viewName.lowercased()]) != nil
|
||||
}
|
||||
|
||||
/// Returns whether a trigger exists.
|
||||
public func triggerExists(_ triggerName: String) throws -> Bool {
|
||||
// SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html)
|
||||
return try Row.fetchOne(self, "SELECT 1 FROM (SELECT sql, type, name FROM sqlite_master UNION SELECT sql, type, name FROM sqlite_temp_master) WHERE type = 'trigger' AND LOWER(name) = ?", arguments: [triggerName.lowercased()]) != nil
|
||||
}
|
||||
|
||||
/// The primary key for table named `tableName`.
|
||||
///
|
||||
/// 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
|
||||
/// "rowid" column.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
public func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
|
||||
if let primaryKey = schemaCache.primaryKey(tableName) {
|
||||
return primaryKey
|
||||
}
|
||||
|
||||
// https://www.sqlite.org/pragma.html
|
||||
//
|
||||
// > PRAGMA database.table_info(table-name);
|
||||
// >
|
||||
// > This pragma returns one row for each column in the named table.
|
||||
// > Columns in the result set include the column name, data type,
|
||||
// > whether or not the column can be NULL, and the default value for
|
||||
// > the column. The "pk" column in the result set is zero for columns
|
||||
// > that are not part of the primary key, and is the index of the
|
||||
// > column in the primary key for columns that are part of the primary
|
||||
// > key.
|
||||
//
|
||||
// CREATE TABLE players (
|
||||
// id INTEGER PRIMARY KEY,
|
||||
// name TEXT,
|
||||
// score INTEGER)
|
||||
//
|
||||
// PRAGMA table_info("players")
|
||||
//
|
||||
// cid | name | type | notnull | dflt_value | pk |
|
||||
// 0 | id | INTEGER | 0 | NULL | 1 |
|
||||
// 1 | name | TEXT | 0 | NULL | 0 |
|
||||
// 2 | score | INTEGER | 0 | NULL | 0 |
|
||||
|
||||
let columns = try self.columns(in: tableName)
|
||||
|
||||
let primaryKey: PrimaryKeyInfo
|
||||
let pkColumns = columns
|
||||
.filter { $0.primaryKeyIndex > 0 }
|
||||
.sorted { $0.primaryKeyIndex < $1.primaryKeyIndex }
|
||||
|
||||
switch pkColumns.count {
|
||||
case 0:
|
||||
// No explicit primary key => primary key is hidden rowID column
|
||||
primaryKey = .hiddenRowID
|
||||
case 1:
|
||||
// Single column
|
||||
let pkColumn = pkColumns.first!
|
||||
|
||||
// https://www.sqlite.org/lang_createtable.html:
|
||||
//
|
||||
// > With one exception noted below, if a rowid table has a primary
|
||||
// > key that consists of a single column and the declared type of
|
||||
// > that column is "INTEGER" in any mixture of upper and lower
|
||||
// > case, then the column becomes an alias for the rowid. Such a
|
||||
// > column is usually referred to as an "integer primary key".
|
||||
// > A PRIMARY KEY column only becomes an integer primary key if the
|
||||
// > declared type name is exactly "INTEGER". Other integer type
|
||||
// > names like "INT" or "BIGINT" or "SHORT INTEGER" or "UNSIGNED
|
||||
// > INTEGER" causes the primary key column to behave as an ordinary
|
||||
// > table column with integer affinity and a unique index, not as
|
||||
// > an alias for the rowid.
|
||||
// >
|
||||
// > The exception mentioned above is that if the declaration of a
|
||||
// > column with declared type "INTEGER" includes an "PRIMARY KEY
|
||||
// > DESC" clause, it does not become an alias for the rowid [...]
|
||||
//
|
||||
// FIXME: We ignore the exception, and consider all INTEGER primary
|
||||
// keys as aliases for the rowid:
|
||||
if pkColumn.type.uppercased() == "INTEGER" {
|
||||
primaryKey = .rowID(pkColumn.name)
|
||||
} else {
|
||||
primaryKey = .regular([pkColumn.name])
|
||||
}
|
||||
default:
|
||||
// Multi-columns primary key
|
||||
primaryKey = .regular(pkColumns.map { $0.name })
|
||||
}
|
||||
|
||||
schemaCache.set(primaryKey: primaryKey, forTable: tableName)
|
||||
return primaryKey
|
||||
}
|
||||
|
||||
/// The number of columns in the table named `tableName`.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
@available(*, deprecated, message: "Use db.columns(in: tableName).count instead")
|
||||
public func columnCount(in tableName: String) throws -> Int {
|
||||
return try columns(in: tableName).count
|
||||
}
|
||||
|
||||
/// The indexes on table named `tableName`; returns the empty array if the
|
||||
/// table does not exist.
|
||||
///
|
||||
/// Note: SQLite does not define any index for INTEGER PRIMARY KEY columns:
|
||||
/// this method does not return any index that represents this primary key.
|
||||
///
|
||||
/// If you want to know if a set of columns uniquely identify a row, prefer
|
||||
/// table(_:hasUniqueKey:) instead.
|
||||
public func indexes(on tableName: String) throws -> [IndexInfo] {
|
||||
if let indexes = schemaCache.indexes(on: tableName) {
|
||||
return indexes
|
||||
}
|
||||
|
||||
let indexes = try Row.fetchAll(self, "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))").map { row -> IndexInfo in
|
||||
let indexName: String = row[1]
|
||||
let unique: Bool = row[2]
|
||||
let columns = try Row.fetchAll(self, "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))")
|
||||
.map { ($0[0] as Int, $0[2] as String) }
|
||||
.sorted { $0.0 < $1.0 }
|
||||
.map { $0.1 }
|
||||
return IndexInfo(name: indexName, columns: columns, unique: unique)
|
||||
}
|
||||
|
||||
schemaCache.set(indexes: indexes, forTable: tableName)
|
||||
return indexes
|
||||
}
|
||||
|
||||
/// True if a sequence of columns uniquely identifies a row, that is to say
|
||||
/// if the columns are the primary key, or if there is a unique index on them.
|
||||
public func table<T: Sequence>(_ tableName: String, hasUniqueKey columns: T) throws -> Bool where T.Iterator.Element == String {
|
||||
return try columnsForUniqueKey(Array(columns), in: tableName) != nil
|
||||
}
|
||||
|
||||
/// The foreign keys defined on table named `tableName`.
|
||||
public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo] {
|
||||
if let foreignKeys = schemaCache.foreignKeys(on: tableName) {
|
||||
return foreignKeys
|
||||
}
|
||||
|
||||
var rawForeignKeys: [(destinationTable: String, mapping: [(origin: String, destination: String?, seq: Int)])] = []
|
||||
var previousId: Int? = nil
|
||||
for row in try Row.fetchAll(self, "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") {
|
||||
// row = <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]
|
||||
let table: String = row[2]
|
||||
let origin: String = row[3]
|
||||
let destination: String? = row[4]
|
||||
|
||||
if previousId == id {
|
||||
rawForeignKeys[rawForeignKeys.count - 1].mapping.append((origin: origin, destination: destination, seq: seq))
|
||||
} else {
|
||||
rawForeignKeys.append((destinationTable: table, mapping: [(origin: origin, destination: destination, seq: seq)]))
|
||||
previousId = id
|
||||
}
|
||||
}
|
||||
|
||||
let foreignKeys = try rawForeignKeys.map { (destinationTable, columnMapping) -> ForeignKeyInfo in
|
||||
let orderedMapping = columnMapping
|
||||
.sorted { $0.seq < $1.seq }
|
||||
.map { (origin: $0.origin, destination: $0 .destination) }
|
||||
|
||||
let completeMapping: [(origin: String, destination: String)]
|
||||
if orderedMapping.contains(where: { (_, destination) in destination == nil }) {
|
||||
let pk = try primaryKey(destinationTable)
|
||||
completeMapping = zip(pk.columns, orderedMapping).map { (pkColumn, arrow) in
|
||||
(origin: arrow.origin, destination: pkColumn)
|
||||
}
|
||||
} else {
|
||||
completeMapping = orderedMapping.map { (origin, destination) in
|
||||
(origin: origin, destination: destination!)
|
||||
}
|
||||
}
|
||||
return ForeignKeyInfo(destinationTable: destinationTable, mapping: completeMapping)
|
||||
}
|
||||
|
||||
schemaCache.set(foreignKeys: foreignKeys, forTable: tableName)
|
||||
return foreignKeys
|
||||
}
|
||||
|
||||
/// Returns the actual name of the database table
|
||||
func canonicalName(table: String) throws -> String {
|
||||
if let canonicalName = schemaCache.canonicalName(table: table) {
|
||||
return canonicalName
|
||||
}
|
||||
|
||||
guard let canonicalName = try String.fetchOne(self, """
|
||||
SELECT name FROM (
|
||||
SELECT name, type FROM sqlite_master
|
||||
UNION
|
||||
SELECT name, type FROM sqlite_temp_master)
|
||||
WHERE type = 'table' AND LOWER(name) = ?
|
||||
""", arguments: [table.lowercased()])
|
||||
else {
|
||||
throw DatabaseError(message: "no such table: \(table)")
|
||||
}
|
||||
|
||||
schemaCache.set(canonicalName: canonicalName, forTable: table)
|
||||
return canonicalName
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
/// The columns in the table named `tableName`
|
||||
///
|
||||
/// - 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
|
||||
}
|
||||
|
||||
// https://www.sqlite.org/pragma.html
|
||||
//
|
||||
// > PRAGMA database.table_info(table-name);
|
||||
// >
|
||||
// > This pragma returns one row for each column in the named table.
|
||||
// > Columns in the result set include the column name, data type,
|
||||
// > whether or not the column can be NULL, and the default value for
|
||||
// > the column. The "pk" column in the result set is zero for columns
|
||||
// > that are not part of the primary key, and is the index of the
|
||||
// > column in the primary key for columns that are part of the primary
|
||||
// > key.
|
||||
//
|
||||
// CREATE TABLE players (
|
||||
// id INTEGER PRIMARY KEY,
|
||||
// firstName TEXT,
|
||||
// lastName TEXT)
|
||||
//
|
||||
// PRAGMA table_info("players")
|
||||
//
|
||||
// cid | name | type | notnull | dflt_value | pk |
|
||||
// 0 | id | INTEGER | 0 | NULL | 1 |
|
||||
// 1 | name | TEXT | 0 | NULL | 0 |
|
||||
// 2 | score | INTEGER | 0 | NULL | 0 |
|
||||
|
||||
if sqlite3_libversion_number() < 3008005 {
|
||||
// Work around a bug in SQLite where PRAGMA table_info would
|
||||
// return a result even after the table was deleted.
|
||||
if try !tableExists(tableName) {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
}
|
||||
}
|
||||
let columns = try ColumnInfo
|
||||
.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
|
||||
.sorted(by: { $0.cid < $1.cid })
|
||||
guard columns.count > 0 else {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
}
|
||||
|
||||
schemaCache.set(columns: columns, forTable: tableName)
|
||||
return columns
|
||||
}
|
||||
|
||||
/// If there exists a unique key on columns, return the columns
|
||||
/// ordered as the matching index (or primay key). Case of returned columns
|
||||
/// is not guaranteed.
|
||||
func columnsForUniqueKey<T: Sequence>(_ columns: T, in tableName: String) throws -> [String]? where T.Iterator.Element == String {
|
||||
let primaryKey = try self.primaryKey(tableName) // first, so that we fail early and consistently should the table not exist
|
||||
let lowercasedColumns = Set(columns.map { $0.lowercased() })
|
||||
if Set(primaryKey.columns.map { $0.lowercased() }) == lowercasedColumns {
|
||||
return primaryKey.columns
|
||||
}
|
||||
if let index = try indexes(on: tableName).first(where: { index in index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns }) {
|
||||
// There is an explicit unique index on the columns
|
||||
return index.columns
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// A column of a database table.
|
||||
///
|
||||
/// This type closely matches the information returned by the
|
||||
/// `table_info` pragma.
|
||||
///
|
||||
/// > CREATE TABLE players (
|
||||
/// id INTEGER PRIMARY KEY,
|
||||
/// firstName TEXT,
|
||||
/// lastName TEXT)
|
||||
/// > PRAGMA table_info("players")
|
||||
/// cid name type notnull dflt_value pk
|
||||
/// ---- ----- ------- -------- ---------- ---
|
||||
/// 0 id INTEGER 0 NULL 1
|
||||
/// 1 name TEXT 0 NULL 0
|
||||
/// 2 score INTEGER 0 NULL 0
|
||||
///
|
||||
/// See `Database.columns(in:)` and https://www.sqlite.org/pragma.html#pragma_table_info
|
||||
public struct ColumnInfo : RowConvertible {
|
||||
let cid: Int
|
||||
|
||||
/// The column name
|
||||
public let name: String
|
||||
|
||||
/// The column data type
|
||||
public let type: String
|
||||
|
||||
/// True if and only if the column is constrained to be not null.
|
||||
public let isNotNull: Bool
|
||||
|
||||
/// The SQL snippet that defines the default value, if any.
|
||||
///
|
||||
/// When nil, the column has no default value.
|
||||
///
|
||||
/// When not nil, it contains an SQL string that defines an expression. That
|
||||
/// expression may be a literal, as `1`, or `'foo'`. It may also contain a
|
||||
/// non-constant expression such as `CURRENT_TIMESTAMP`.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try db.execute("""
|
||||
/// CREATE TABLE players(
|
||||
/// id INTEGER PRIMARY KEY,
|
||||
/// name TEXT DEFAULT 'Anonymous',
|
||||
/// score INT DEFAULT 0,
|
||||
/// creationDate DATE DEFAULT CURRENT_TIMESTAMP
|
||||
/// )
|
||||
/// """)
|
||||
/// let columnInfos = try db.columns(in: "players")
|
||||
/// columnInfos[0].defaultValueSQL // nil
|
||||
/// columnInfos[1].defaultValueSQL // "'Anoynymous'"
|
||||
/// columnInfos[2].defaultValueSQL // "0"
|
||||
/// columnInfos[3].defaultValueSQL // "CURRENT_TIMESTAMP"
|
||||
public let defaultValueSQL: String?
|
||||
|
||||
/// Zero for columns that are not part of the primary key.
|
||||
///
|
||||
/// Before SQLite 3.7.16, it is 1 for columns that are part of the
|
||||
/// primary key.
|
||||
///
|
||||
/// Starting from SQLite 3.7.16, it is the one-based index of the column in
|
||||
/// 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
|
||||
public let primaryKeyIndex: Int
|
||||
|
||||
/// :nodoc:
|
||||
public init(row: Row) {
|
||||
cid = row["cid"]
|
||||
name = row["name"]
|
||||
type = row["type"]
|
||||
isNotNull = row["notnull"]
|
||||
defaultValueSQL = row["dflt_value"]
|
||||
primaryKeyIndex = row["pk"]
|
||||
}
|
||||
}
|
||||
|
||||
/// An index on a database table.
|
||||
///
|
||||
/// See `Database.indexes(on:)`
|
||||
public struct IndexInfo {
|
||||
/// The name of the index
|
||||
public let name: String
|
||||
|
||||
/// The indexed columns
|
||||
public let columns: [String]
|
||||
|
||||
/// True if the index is unique
|
||||
public let isUnique: Bool
|
||||
|
||||
init(name: String, columns: [String], unique: Bool) {
|
||||
self.name = name
|
||||
self.columns = columns
|
||||
self.isUnique = unique
|
||||
}
|
||||
}
|
||||
|
||||
/// Primary keys are returned from the Database.primaryKey(_:) method.
|
||||
///
|
||||
/// When the table's primary key is the rowid:
|
||||
///
|
||||
/// // CREATE TABLE items (name TEXT)
|
||||
/// let pk = try db.primaryKey("items")
|
||||
/// pk.columns // ["rowid"]
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // true
|
||||
///
|
||||
/// // CREATE TABLE citizens (
|
||||
/// // id INTEGER PRIMARY KEY,
|
||||
/// // name TEXT
|
||||
/// // )
|
||||
/// let pk = try db.primaryKey("citizens")!
|
||||
/// pk.columns // ["id"]
|
||||
/// pk.rowIDColumn // "id"
|
||||
/// pk.isRowID // true
|
||||
///
|
||||
/// When the table's primary key is not the rowid:
|
||||
///
|
||||
/// // CREATE TABLE countries (
|
||||
/// // isoCode TEXT NOT NULL PRIMARY KEY
|
||||
/// // name TEXT
|
||||
/// // )
|
||||
/// let pk = db.primaryKey("countries")!
|
||||
/// pk.columns // ["isoCode"]
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // false
|
||||
///
|
||||
/// // CREATE TABLE citizenships (
|
||||
/// // citizenID INTEGER NOT NULL REFERENCES citizens(id)
|
||||
/// // countryIsoCode TEXT NOT NULL REFERENCES countries(isoCode)
|
||||
/// // PRIMARY KEY (citizenID, countryIsoCode)
|
||||
/// // )
|
||||
/// let pk = db.primaryKey("citizenships")!
|
||||
/// pk.columns // ["citizenID", "countryIsoCode"]
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // false
|
||||
public struct PrimaryKeyInfo {
|
||||
private enum Impl {
|
||||
/// The hidden rowID.
|
||||
case hiddenRowID
|
||||
|
||||
/// An INTEGER PRIMARY KEY column that aliases the Row ID.
|
||||
/// Associated string is the column name.
|
||||
case rowID(String)
|
||||
|
||||
/// Any primary key, but INTEGER PRIMARY KEY.
|
||||
/// Associated strings are column names.
|
||||
case regular([String])
|
||||
}
|
||||
|
||||
private let impl: Impl
|
||||
|
||||
static func rowID(_ column: String) -> PrimaryKeyInfo {
|
||||
return PrimaryKeyInfo(impl: .rowID(column))
|
||||
}
|
||||
|
||||
static func regular(_ columns: [String]) -> PrimaryKeyInfo {
|
||||
assert(!columns.isEmpty)
|
||||
return PrimaryKeyInfo(impl: .regular(columns))
|
||||
}
|
||||
|
||||
static let hiddenRowID = PrimaryKeyInfo(impl: .hiddenRowID)
|
||||
|
||||
/// The columns in the primary key; this array is never empty.
|
||||
public var columns: [String] {
|
||||
switch impl {
|
||||
case .hiddenRowID:
|
||||
return [Column.rowID.name]
|
||||
case .rowID(let column):
|
||||
return [column]
|
||||
case .regular(let columns):
|
||||
return columns
|
||||
}
|
||||
}
|
||||
|
||||
/// When not nil, the name of the column that contains the INTEGER PRIMARY KEY.
|
||||
public var rowIDColumn: String? {
|
||||
switch impl {
|
||||
case .hiddenRowID:
|
||||
return nil
|
||||
case .rowID(let column):
|
||||
return column
|
||||
case .regular:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// When true, the primary key is the rowid:
|
||||
public var isRowID: Bool {
|
||||
switch impl {
|
||||
case .hiddenRowID:
|
||||
return true
|
||||
case .rowID:
|
||||
return true
|
||||
case .regular:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// You get foreign keys from table names, with the
|
||||
/// `foreignKeys(on:)` method.
|
||||
public struct ForeignKeyInfo {
|
||||
/// The name of the destination table
|
||||
public let destinationTable: String
|
||||
|
||||
/// The column to column mapping
|
||||
public let mapping: [(origin: String, destination: String)]
|
||||
|
||||
/// The origin columns
|
||||
public var originColumns: [String] {
|
||||
return mapping.map { $0.origin }
|
||||
}
|
||||
|
||||
/// The destination columns
|
||||
public var destinationColumns: [String] {
|
||||
return mapping.map { $0.destination }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
import Foundation
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Statements
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?")
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: A SelectStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func makeSelectStatement(_ sql: String) throws -> SelectStatement {
|
||||
return try makeSelectStatement(sql, prepFlags: 0)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players 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.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
func makeSelectStatement(_ sql: String, prepFlags: Int32) throws -> SelectStatement {
|
||||
return try SelectStatement.prepare(sql: sql, prepFlags: prepFlags, in: self)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?")
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
///
|
||||
/// 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: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func cachedSelectStatement(_ sql: String) throws -> SelectStatement {
|
||||
return try publicStatementCache.selectStatement(sql)
|
||||
}
|
||||
|
||||
/// Returns a cached statement that does not conflict with user's cached statements.
|
||||
func internalCachedSelectStatement(_ sql: String) throws -> SelectStatement {
|
||||
return try internalStatementCache.selectStatement(sql)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeUpdateStatement("INSERT INTO players (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// - 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 {
|
||||
return try makeUpdateStatement(sql, prepFlags: 0)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeUpdateStatement("INSERT INTO players (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.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
func makeUpdateStatement(_ sql: String, prepFlags: Int32) throws -> UpdateStatement {
|
||||
return try UpdateStatement.prepare(sql: sql, prepFlags: prepFlags, in: self)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedUpdateStatement("INSERT INTO players (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: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func cachedUpdateStatement(_ sql: String) throws -> UpdateStatement {
|
||||
return try publicStatementCache.updateStatement(sql)
|
||||
}
|
||||
|
||||
/// Returns a cached statement that does not conflict with user's cached statements.
|
||||
func internalCachedUpdateStatement(_ sql: String) throws -> UpdateStatement {
|
||||
return try internalStatementCache.updateStatement(sql)
|
||||
}
|
||||
|
||||
/// Executes one or several SQL statements, separated by semi-colons.
|
||||
///
|
||||
/// try db.execute(
|
||||
/// "INSERT INTO players (name) VALUES (:name)",
|
||||
/// arguments: ["name": "Arthur"])
|
||||
///
|
||||
/// try db.execute("""
|
||||
/// INSERT INTO players (name) VALUES (?);
|
||||
/// INSERT INTO players (name) VALUES (?);
|
||||
/// INSERT INTO players (name) VALUES (?);
|
||||
/// """, arguments; ['Arthur', 'Barbara', 'Craig'])
|
||||
///
|
||||
/// This method may throw a DatabaseError.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func execute(_ sql: String, arguments: StatementArguments? = nil) 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.
|
||||
//
|
||||
// Here we build two functions:
|
||||
// - consumeArguments returns arguments for a statement
|
||||
// - validateRemainingArguments validates the remaining arguments, after
|
||||
// all statements have been executed, in the same way
|
||||
// as Statement.validate(arguments:)
|
||||
|
||||
var arguments = arguments ?? StatementArguments()
|
||||
let initialValuesCount = arguments.values.count
|
||||
let consumeArguments = { (statement: UpdateStatement) throws -> StatementArguments in
|
||||
let bindings = try arguments.consume(statement, allowingRemainingValues: true)
|
||||
return StatementArguments(bindings)
|
||||
}
|
||||
let validateRemainingArguments = {
|
||||
if !arguments.values.isEmpty {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)")
|
||||
}
|
||||
}
|
||||
|
||||
// Iterate SQL statements
|
||||
let sqlCodeUnits = sql.utf8CString
|
||||
try sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
|
||||
let sqlStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
|
||||
let sqlEnd = sqlStart + sqlCodeUnits.count
|
||||
var statementStart = sqlStart
|
||||
while statementStart < sqlEnd - 1 {
|
||||
var statementEnd: UnsafePointer<Int8>? = nil
|
||||
do {
|
||||
let statement: UpdateStatement
|
||||
// Compile
|
||||
do {
|
||||
let statementCompilationAuthorizer = StatementCompilationAuthorizer()
|
||||
authorizer = statementCompilationAuthorizer
|
||||
defer { authorizer = nil }
|
||||
|
||||
statement = try UpdateStatement(
|
||||
database: self,
|
||||
statementStart: statementStart,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: 0,
|
||||
authorizer: statementCompilationAuthorizer)
|
||||
}
|
||||
|
||||
// Execute
|
||||
let arguments = try consumeArguments(statement)
|
||||
statement.unsafeSetArguments(arguments)
|
||||
try statement.execute()
|
||||
|
||||
// Next
|
||||
statementStart = statementEnd!
|
||||
} catch is EmptyStatementError {
|
||||
// End
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Force arguments validity: it is a programmer error to provide
|
||||
// arguments that do not match the statement.
|
||||
try! validateRemainingArguments() // throws if there are remaining arguments.
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
func updateStatementWillExecute(_ statement: UpdateStatement) {
|
||||
observationBroker.updateStatementWillExecute(statement)
|
||||
}
|
||||
|
||||
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
|
||||
if statement.invalidatesDatabaseSchemaCache {
|
||||
clearSchemaCache()
|
||||
}
|
||||
|
||||
try observationBroker.updateStatementDidExecute(statement)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
func selectStatementDidFail(_ statement: SelectStatement) {
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
+457
-2189
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,53 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// A Collation is a string comparison function used by SQLite.
|
||||
public final class DatabaseCollation {
|
||||
public let name: String
|
||||
let function: (Int32, UnsafeRawPointer?, Int32, UnsafeRawPointer?) -> ComparisonResult
|
||||
|
||||
/// Creates a collation.
|
||||
///
|
||||
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// db.add(collation: collation)
|
||||
/// try db.execute("CREATE TABLE files (name TEXT COLLATE localized_standard")
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The function name.
|
||||
/// - function: A function that compares two strings.
|
||||
public init(_ name: String, function: @escaping (String, String) -> ComparisonResult) {
|
||||
self.name = name
|
||||
self.function = { (length1, buffer1, length2, buffer2) in
|
||||
// Buffers are not C strings: they do not end with \0.
|
||||
let string1 = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped), length: Int(length1), encoding: .utf8, freeWhenDone: false)!
|
||||
let string2 = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped), length: Int(length2), encoding: .utf8, freeWhenDone: false)!
|
||||
return function(string1, string2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseCollation : Hashable {
|
||||
/// :nodoc:
|
||||
public var hashValue: Int {
|
||||
// Collation equality is based on the sqlite3_strnicmp SQLite function.
|
||||
// (see https://www.sqlite.org/c3ref/create_collation.html). Computing
|
||||
// a hash value that honors the Swift Hashable contract (value equality
|
||||
// implies hash equality) is thus non trivial. But it's not that
|
||||
// important, since this hashValue is only used when one adds
|
||||
// or removes a collation from a database connection.
|
||||
return 0
|
||||
}
|
||||
|
||||
/// 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
|
||||
return sqlite3_stricmp(lhs.name, lhs.name) == 0
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import Foundation
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible {
|
||||
@@ -24,24 +25,6 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
|
||||
return self == primaryResultCode
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
// sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, iOSApplicationExtension 8.2, *) {
|
||||
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
|
||||
} else {
|
||||
return "\(rawValue)"
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
public static func == (_ lhs: ResultCode, _ rhs: ResultCode) -> Bool {
|
||||
return lhs.rawValue == rhs.rawValue
|
||||
}
|
||||
|
||||
/// Returns true if the code on the left matches the code on the right.
|
||||
///
|
||||
/// Primary result codes match themselves and their extended result codes,
|
||||
@@ -154,11 +137,36 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
|
||||
public static let SQLITE_WARNING_AUTOINDEX = ResultCode(rawValue: (SQLITE_WARNING.rawValue | (1<<8)))
|
||||
public static let SQLITE_AUTH_USER = ResultCode(rawValue: (SQLITE_AUTH.rawValue | (1<<8)))
|
||||
public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8)))
|
||||
}
|
||||
|
||||
// Equatable
|
||||
extension ResultCode {
|
||||
/// :nodoc:
|
||||
public static func == (_ lhs: ResultCode, _ rhs: ResultCode) -> Bool {
|
||||
return lhs.rawValue == rhs.rawValue
|
||||
}
|
||||
}
|
||||
|
||||
// CustomStringConvertible
|
||||
extension ResultCode {
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
// sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, iOSApplicationExtension 8.2, *) {
|
||||
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
|
||||
} else {
|
||||
return "\(rawValue)"
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
/// DatabaseError wraps an SQLite error.
|
||||
public struct DatabaseError : Error {
|
||||
public struct DatabaseError : Error, CustomStringConvertible, CustomNSError {
|
||||
|
||||
/// The SQLite error code (see
|
||||
/// https://www.sqlite.org/rescode.html#primary_result_code_list).
|
||||
@@ -219,10 +227,11 @@ public struct DatabaseError : Error {
|
||||
let arguments: StatementArguments?
|
||||
}
|
||||
|
||||
extension DatabaseError: CustomStringConvertible {
|
||||
/// A textual representation of `self`.
|
||||
// CustomStringConvertible
|
||||
extension DatabaseError {
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
var description = "SQLite error \(extendedResultCode.rawValue)"
|
||||
var description = "SQLite error \(resultCode.rawValue)"
|
||||
if let sql = sql {
|
||||
description += " with statement `\(sql)`"
|
||||
}
|
||||
@@ -236,19 +245,23 @@ extension DatabaseError: CustomStringConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseError : CustomNSError {
|
||||
// CustomNSError
|
||||
extension DatabaseError {
|
||||
|
||||
/// NSError bridging: the domain of the error.
|
||||
/// :nodoc:
|
||||
public static var errorDomain: String {
|
||||
return "GRDB.DatabaseError"
|
||||
}
|
||||
|
||||
/// NSError bridging: the error code within the given domain.
|
||||
/// :nodoc:
|
||||
public var errorCode: Int {
|
||||
return Int(extendedResultCode.rawValue)
|
||||
}
|
||||
|
||||
/// NSError bridging: the user-info dictionary.
|
||||
/// :nodoc:
|
||||
public var errorUserInfo: [String : Any] {
|
||||
return [NSLocalizedDescriptionKey: description]
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// An SQL function or aggregate.
|
||||
@@ -8,8 +10,8 @@ public final class DatabaseFunction {
|
||||
let argumentCount: Int32?
|
||||
let pure: Bool
|
||||
private let kind: Kind
|
||||
fileprivate var nArg: Int32 { return argumentCount ?? -1 }
|
||||
fileprivate var eTextRep: Int32 { return (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
|
||||
private var nArg: Int32 { return argumentCount ?? -1 }
|
||||
private var eTextRep: Int32 { return (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
|
||||
|
||||
/// Returns an SQL function.
|
||||
///
|
||||
@@ -309,11 +311,13 @@ public final class DatabaseFunction {
|
||||
|
||||
extension DatabaseFunction : Hashable {
|
||||
/// The hash value
|
||||
/// :nodoc:
|
||||
public var hashValue: Int {
|
||||
return name.hashValue ^ nArg.hashValue
|
||||
}
|
||||
|
||||
/// Two functions are equal if they share the same name and arity.
|
||||
/// :nodoc:
|
||||
public static func == (lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool {
|
||||
return lhs.name == rhs.name && lhs.nArg == rhs.nArg
|
||||
}
|
||||
@@ -356,10 +360,10 @@ public protocol DatabaseAggregate {
|
||||
/// aggregate function.
|
||||
///
|
||||
/// -- One value
|
||||
/// SELECT maxLength(name) FROM persons
|
||||
/// SELECT maxLength(name) FROM players
|
||||
///
|
||||
/// -- Two values
|
||||
/// SELECT maxFullNameLength(firstName, lastName) FROM persons
|
||||
/// SELECT maxFullNameLength(firstName, lastName) FROM players
|
||||
///
|
||||
/// This method is never called after the finalize() method has been called.
|
||||
mutating func step(_ dbValues: [DatabaseValue]) throws
|
||||
|
||||
+166
-107
@@ -1,17 +1,34 @@
|
||||
import Foundation
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
#if os(iOS)
|
||||
import UIKit
|
||||
#endif
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#endif
|
||||
|
||||
/// A DatabasePool grants concurrent accesses to an SQLite database.
|
||||
public final class DatabasePool {
|
||||
private let writer: SerializedDatabase
|
||||
private var readerConfig: Configuration
|
||||
private var readerPool: Pool<SerializedDatabase>!
|
||||
|
||||
// MARK: - Initializers
|
||||
private var functions = Set<DatabaseFunction>()
|
||||
private var collations = Set<DatabaseCollation>()
|
||||
|
||||
#if os(iOS)
|
||||
private weak var application: UIApplication?
|
||||
#endif
|
||||
|
||||
// MARK: - Database Information
|
||||
|
||||
/// The path to the database.
|
||||
public var path: String {
|
||||
return writer.path
|
||||
}
|
||||
|
||||
// MARK: - Initializer
|
||||
|
||||
/// Opens the SQLite database at path *path*.
|
||||
///
|
||||
@@ -22,19 +39,15 @@ public final class DatabasePool {
|
||||
/// - parameters:
|
||||
/// - path: The path to the database file.
|
||||
/// - configuration: A configuration.
|
||||
/// - maximumReaderCount: The maximum number of readers. Default is 5.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public init(path: String, configuration: Configuration = Configuration()) throws {
|
||||
GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1")
|
||||
|
||||
// Writer and readers share the same database schema cache
|
||||
let sharedSchemaCache = SharedDatabaseSchemaCache()
|
||||
|
||||
// Writer
|
||||
writer = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
schemaCache: sharedSchemaCache)
|
||||
schemaCache: SimpleDatabaseSchemaCache())
|
||||
|
||||
// Activate WAL Mode unless readonly
|
||||
if !configuration.readonly {
|
||||
@@ -63,21 +76,13 @@ public final class DatabasePool {
|
||||
readerConfig = configuration
|
||||
readerConfig.readonly = true
|
||||
readerConfig.defaultTransactionKind = .deferred // Make it the default for readers. Other transaction kinds are forbidden by SQLite in read-only connections.
|
||||
readerConfig.allowsUnsafeTransactions = false // Because there's no guarantee that one can get the same reader in order to close its opened transaction.
|
||||
readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: { [unowned self] in
|
||||
let reader = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: self.readerConfig,
|
||||
schemaCache: sharedSchemaCache)
|
||||
|
||||
reader.sync { db in
|
||||
for function in self.functions {
|
||||
db.add(function: function)
|
||||
}
|
||||
for collation in self.collations {
|
||||
db.add(collation: collation)
|
||||
}
|
||||
}
|
||||
|
||||
schemaCache: SimpleDatabaseSchemaCache())
|
||||
reader.sync { self.setupDatabase($0) }
|
||||
return reader
|
||||
})
|
||||
}
|
||||
@@ -92,17 +97,20 @@ public final class DatabasePool {
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// The path to the database.
|
||||
public var path: String {
|
||||
return writer.path
|
||||
private func setupDatabase(_ db: Database) {
|
||||
for function in self.functions {
|
||||
db.add(function: function)
|
||||
}
|
||||
for collation in self.collations {
|
||||
db.add(collation: collation)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - WAL Management
|
||||
|
||||
}
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
// MARK: - WAL Checkpoints
|
||||
|
||||
/// Runs a WAL checkpoint
|
||||
///
|
||||
/// See https://www.sqlite.org/wal.html and
|
||||
@@ -121,10 +129,12 @@ public final class DatabasePool {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
// MARK: - Memory management
|
||||
|
||||
|
||||
/// Free as much memory as possible.
|
||||
///
|
||||
/// This method blocks the current thread until all database accesses are completed.
|
||||
@@ -155,8 +165,6 @@ public final class DatabasePool {
|
||||
center.addObserver(self, selector: #selector(DatabasePool.applicationDidEnterBackground(_:)), name: .UIApplicationDidEnterBackground, object: nil)
|
||||
}
|
||||
|
||||
private var application: UIApplication!
|
||||
|
||||
@objc private func applicationDidEnterBackground(_ notification: NSNotification) {
|
||||
guard let application = application else {
|
||||
return
|
||||
@@ -183,24 +191,12 @@ public final class DatabasePool {
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// MARK: - Not public
|
||||
|
||||
fileprivate let writer: SerializedDatabase
|
||||
fileprivate var readerConfig: Configuration
|
||||
fileprivate var readerPool: Pool<SerializedDatabase>! = nil // var and nil-initialized so that we can use `self` when creating readerPool in DatabasePool.init()
|
||||
|
||||
fileprivate var functions = Set<DatabaseFunction>()
|
||||
fileprivate var collations = Set<DatabaseCollation>()
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - Encryption
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
extension DatabasePool {
|
||||
|
||||
// MARK: - Encryption
|
||||
|
||||
/// Changes the passphrase of an encrypted database
|
||||
public func change(passphrase: String) throws {
|
||||
@@ -212,19 +208,15 @@ public final class DatabasePool {
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - DatabaseReader
|
||||
|
||||
extension DatabasePool : DatabaseReader {
|
||||
|
||||
// MARK: - Read From Database
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// Synchronously executes a read-only block in a protected dispatch queue,
|
||||
/// and returns its result. The block is wrapped in a deferred transaction.
|
||||
///
|
||||
/// let persons = try dbPool.read { db in
|
||||
/// try Person.fetchAll(...)
|
||||
/// let players = try dbPool.read { db in
|
||||
/// try Player.fetchAll(...)
|
||||
/// }
|
||||
///
|
||||
/// The block is completely isolated. Eventual concurrent database updates
|
||||
@@ -255,6 +247,8 @@ extension DatabasePool : DatabaseReader {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
// See DatabasePoolTests.testReadMethodIsolationOfBlock().
|
||||
try db.inTransaction(.deferred) {
|
||||
// Reset the schema cache before running user code in snapshot isolation
|
||||
db.schemaCache = SimpleDatabaseSchemaCache()
|
||||
result = try block(db)
|
||||
return .commit
|
||||
}
|
||||
@@ -292,7 +286,11 @@ extension DatabasePool : DatabaseReader {
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
return try readerPool.get { reader in
|
||||
try reader.sync(block)
|
||||
try reader.sync { db in
|
||||
// No schema cache when snapshot isolation is not established
|
||||
db.schemaCache = EmptyDatabaseSchemaCache()
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -328,7 +326,11 @@ extension DatabasePool : DatabaseReader {
|
||||
return try reader.reentrantSync(block)
|
||||
} else {
|
||||
return try readerPool.get { reader in
|
||||
try reader.sync(block)
|
||||
try reader.sync { db in
|
||||
// No schema cache when snapshot isolation is not established
|
||||
db.schemaCache = EmptyDatabaseSchemaCache()
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -355,7 +357,6 @@ extension DatabasePool : DatabaseReader {
|
||||
return readers.first { $0.onValidQueue }
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
@@ -387,7 +388,6 @@ extension DatabasePool : DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// Add or redefine a collation.
|
||||
@@ -417,10 +417,6 @@ extension DatabasePool : DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - DatabaseWriter
|
||||
|
||||
extension DatabasePool : DatabaseWriter {
|
||||
|
||||
// MARK: - Writing in Database
|
||||
@@ -510,25 +506,25 @@ extension DatabasePool : DatabaseWriter {
|
||||
return try writer.reentrantSync(block)
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// Asynchronously executes a read-only block in a protected dispatch queue,
|
||||
/// wrapped in a deferred transaction.
|
||||
///
|
||||
/// This method must be called from the writing dispatch queue.
|
||||
/// This method must be called from the writing dispatch queue, outside of a
|
||||
/// transaction. You'll get a fatal error otherwise.
|
||||
///
|
||||
/// The *block* argument is guaranteed to see the database in the last
|
||||
/// committed state at the moment this method is called. Eventual concurrent
|
||||
/// database updates are *not visible* inside the block.
|
||||
///
|
||||
/// try dbPool.write { db in
|
||||
/// try db.execute("DELETE FROM persons")
|
||||
/// try db.execute("DELETE FROM players")
|
||||
/// try dbPool.readFromCurrentState { db in
|
||||
/// // Guaranteed to be zero
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
|
||||
/// }
|
||||
/// try db.execute("INSERT INTO persons ...")
|
||||
/// try db.execute("INSERT INTO players ...")
|
||||
/// }
|
||||
///
|
||||
/// This method blocks the current thread until the isolation guarantee has
|
||||
@@ -538,55 +534,78 @@ extension DatabasePool : DatabaseWriter {
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
/// happen while establishing the read access to the database.
|
||||
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws {
|
||||
writer.preconditionValidQueue()
|
||||
// https://www.sqlite.org/isolation.html
|
||||
//
|
||||
// > In WAL mode, SQLite exhibits "snapshot isolation". When a read
|
||||
// > transaction starts, that reader continues to see an unchanging
|
||||
// > "snapshot" of the database file as it existed at the moment in time
|
||||
// > when the read transaction started. Any write transactions that
|
||||
// > commit while the read transaction is active are still invisible to
|
||||
// > the read transaction, because the reader is seeing a snapshot of
|
||||
// > database file from a prior moment in time.
|
||||
//
|
||||
// That's exactly what we need. But what does "when read transaction
|
||||
// starts" mean?
|
||||
//
|
||||
// http://www.sqlite.org/lang_transaction.html
|
||||
//
|
||||
// > Deferred [transaction] means that no locks are acquired on the
|
||||
// > database until the database is first accessed. [...] Locks are not
|
||||
// > acquired until the first read or write operation. [...] Because the
|
||||
// > acquisition of locks is deferred until they are needed, it is
|
||||
// > possible that another thread or process could create a separate
|
||||
// > transaction and write to the database after the BEGIN on the
|
||||
// > current thread has executed.
|
||||
//
|
||||
// Now that's precise enough: SQLite defers "snapshot isolation" until
|
||||
// the first SELECT:
|
||||
//
|
||||
// Reader Writer
|
||||
// BEGIN DEFERRED TRANSACTION
|
||||
// UPDATE ... (1)
|
||||
// Here the change (1) is visible
|
||||
// SELECT ...
|
||||
// UPDATE ... (2)
|
||||
// Here the change (2) is not visible
|
||||
//
|
||||
// The readFromCurrentState method says that no change should be visible
|
||||
// at all. We thus have to perform a select that establishes the
|
||||
// snapshot isolation before we release the writer queue:
|
||||
//
|
||||
// Reader Writer
|
||||
// BEGIN DEFERRED TRANSACTION
|
||||
// SELECT anything
|
||||
// UPDATE ...
|
||||
// Here the change is not visible by GRDB user
|
||||
|
||||
// Check that we're on the writer queue...
|
||||
writer.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction.")
|
||||
}
|
||||
|
||||
// The semaphore that blocks the writing dispatch queue until snapshot
|
||||
// isolation has been established:
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
|
||||
var readError: Error? = nil
|
||||
try readerPool.get { reader in
|
||||
reader.async { db in
|
||||
// https://www.sqlite.org/isolation.html
|
||||
//
|
||||
// > In WAL mode, SQLite exhibits "snapshot isolation". When a
|
||||
// > read transaction starts, that reader continues to see an
|
||||
// > unchanging "snapshot" of the database file as it existed at
|
||||
// > the moment in time when the read transaction started.
|
||||
// > Any write transactions that commit while the read
|
||||
// > transaction is active are still invisible to the read
|
||||
// > transaction, because the reader is seeing a snapshot of
|
||||
// > database file from a prior moment in time.
|
||||
//
|
||||
// This documentation is NOT accurate. SQLite actually defers
|
||||
// isolation until the first SELECT:
|
||||
//
|
||||
// Reader Writer
|
||||
// BEGIN DEFERRED TRANSACTION
|
||||
// UPDATE ... (1)
|
||||
// Here the change (1) is visible
|
||||
// SELECT ...
|
||||
// UPDATE ... (2)
|
||||
// Here the change (2) is not visible
|
||||
//
|
||||
// This is not the guarantee expected by this method: no change
|
||||
// at all should be visible.
|
||||
//
|
||||
// Workaround: perform an initial read before releasing the
|
||||
// writer queue:
|
||||
//
|
||||
// Reader Writer
|
||||
// BEGIN DEFERRED TRANSACTION
|
||||
// SELECT anything -- the work around
|
||||
// UPDATE ...
|
||||
// Here the change is not visible by GRDB user
|
||||
do {
|
||||
try db.beginTransaction(.deferred)
|
||||
assert(db.isInsideTransaction)
|
||||
try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").cursor().next() // doesn't work with cached statement
|
||||
try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").cursor().next()
|
||||
} catch {
|
||||
readError = error
|
||||
semaphore.signal() // Release the writer queue and rethrow error
|
||||
return
|
||||
}
|
||||
semaphore.signal() // We can release the writer queue now that we are isolated for good
|
||||
|
||||
// Reset the schema cache before running user code in snapshot isolation
|
||||
db.schemaCache = SimpleDatabaseSchemaCache()
|
||||
block(db)
|
||||
|
||||
_ = try? db.commit() // Ignore commit error
|
||||
}
|
||||
}
|
||||
@@ -597,3 +616,43 @@ extension DatabasePool : DatabaseWriter {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
// MARK: - Snapshots
|
||||
|
||||
/// Creates a database snapshot.
|
||||
//:
|
||||
/// The snapshot sees an unchanging database content, as it existed at the
|
||||
/// moment it was created.
|
||||
///
|
||||
/// When you want to control the latest committed changes seen by a
|
||||
/// snapshot, create it from the pool's writer protected dispatch queue:
|
||||
///
|
||||
/// let snapshot1 = try dbPool.write { db -> DatabaseSnapshot in
|
||||
/// try Player.deleteAll()
|
||||
/// return dbPool.makeSnapshot()
|
||||
/// }
|
||||
/// // <- Other threads may modify the database here
|
||||
/// let snapshot2 = try dbPool.makeSnapshot()
|
||||
///
|
||||
/// try snapshot1.read { db in
|
||||
/// // Guaranteed to be zero
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// try snapshot2.read { db in
|
||||
/// // Could be anything
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// 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
|
||||
public func makeSnapshot() throws -> DatabaseSnapshot {
|
||||
let snapshot = try DatabaseSnapshot(path: path, configuration: writer.configuration)
|
||||
snapshot.read { setupDatabase($0) }
|
||||
return snapshot
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,22 @@ import UIKit
|
||||
|
||||
/// A DatabaseQueue serializes access to an SQLite database.
|
||||
public final class DatabaseQueue {
|
||||
private var serializedDatabase: SerializedDatabase
|
||||
#if os(iOS)
|
||||
private weak var application: UIApplication?
|
||||
#endif
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// The database configuration
|
||||
public var configuration: Configuration {
|
||||
return serializedDatabase.configuration
|
||||
}
|
||||
|
||||
/// The path to the database file; it is ":memory:" for in-memory databases.
|
||||
public var path: String {
|
||||
return serializedDatabase.path
|
||||
}
|
||||
|
||||
// MARK: - Initializers
|
||||
|
||||
@@ -50,28 +66,17 @@ public final class DatabaseQueue {
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// The database configuration
|
||||
public var configuration: Configuration {
|
||||
return serializedDatabase.configuration
|
||||
}
|
||||
|
||||
/// The path to the database file; it is ":memory:" for in-memory databases.
|
||||
public var path: String {
|
||||
return serializedDatabase.path
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Database access
|
||||
|
||||
}
|
||||
|
||||
extension DatabaseQueue {
|
||||
|
||||
// MARK: - Database Access
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// let persons = try dbQueue.inDatabase { db in
|
||||
/// try Person.fetchAll(...)
|
||||
/// let players = try dbQueue.inDatabase { db in
|
||||
/// try Player.fetchAll(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
@@ -111,10 +116,12 @@ public final class DatabaseQueue {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
extension DatabaseQueue {
|
||||
|
||||
// MARK: - Memory management
|
||||
|
||||
|
||||
/// Free as much memory as possible.
|
||||
///
|
||||
/// This method blocks the current thread until all database accesses are completed.
|
||||
@@ -124,7 +131,6 @@ public final class DatabaseQueue {
|
||||
inDatabase { $0.releaseMemory() }
|
||||
}
|
||||
|
||||
|
||||
#if os(iOS)
|
||||
/// Listens to UIApplicationDidEnterBackgroundNotification and
|
||||
/// UIApplicationDidReceiveMemoryWarningNotification in order to release
|
||||
@@ -140,8 +146,6 @@ public final class DatabaseQueue {
|
||||
center.addObserver(self, selector: #selector(DatabaseQueue.applicationDidEnterBackground(_:)), name: .UIApplicationDidEnterBackground, object: nil)
|
||||
}
|
||||
|
||||
private var application: UIApplication?
|
||||
|
||||
@objc private func applicationDidEnterBackground(_ notification: NSNotification) {
|
||||
guard let application = application else {
|
||||
return
|
||||
@@ -168,37 +172,13 @@ public final class DatabaseQueue {
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// MARK: - Not public
|
||||
|
||||
// https://www.sqlite.org/isolation.html
|
||||
//
|
||||
// > Within a single database connection X, a SELECT statement always
|
||||
// > sees all changes to the database that are completed prior to the
|
||||
// > start of the SELECT statement, whether committed or uncommitted.
|
||||
// > And the SELECT statement obviously does not see any changes that
|
||||
// > occur after the SELECT statement completes. But what about changes
|
||||
// > that occur while the SELECT statement is running? What if a SELECT
|
||||
// > statement is started and the sqlite3_step() interface steps through
|
||||
// > roughly half of its output, then some UPDATE statements are run by
|
||||
// > the application that modify the table that the SELECT statement is
|
||||
// > reading, then more calls to sqlite3_step() are made to finish out
|
||||
// > the SELECT statement? Will the later steps of the SELECT statement
|
||||
// > see the changes made by the UPDATE or not? The answer is that this
|
||||
// > behavior is undefined.
|
||||
//
|
||||
// This is why we use a serialized database:
|
||||
fileprivate var serializedDatabase: SerializedDatabase
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - Encryption
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
extension DatabaseQueue {
|
||||
|
||||
|
||||
// MARK: - Encryption
|
||||
|
||||
/// Changes the passphrase of an encrypted database
|
||||
public func change(passphrase: String) throws {
|
||||
try inDatabase { try $0.change(passphrase: passphrase) }
|
||||
@@ -206,19 +186,15 @@ public final class DatabaseQueue {
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - DatabaseReader
|
||||
|
||||
extension DatabaseQueue : DatabaseReader {
|
||||
|
||||
// MARK: - DatabaseReader Protocol Adoption
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// Synchronously executes a read-only block in a protected dispatch queue,
|
||||
/// and returns its result.
|
||||
///
|
||||
/// let persons = try dbQueue.read { db in
|
||||
/// try Person.fetchAll(...)
|
||||
/// let players = try dbQueue.read { db in
|
||||
/// try Player.fetchAll(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
@@ -244,6 +220,8 @@ extension DatabaseQueue : DatabaseReader {
|
||||
}
|
||||
|
||||
/// Alias for `inDatabase`. See `DatabaseReader.unsafeRead`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try inDatabase(block)
|
||||
}
|
||||
@@ -257,11 +235,12 @@ extension DatabaseQueue : DatabaseReader {
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try serializedDatabase.reentrantSync(block)
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
@@ -285,7 +264,6 @@ extension DatabaseQueue : DatabaseReader {
|
||||
inDatabase { $0.remove(function: function) }
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// Add or redefine a collation.
|
||||
@@ -307,15 +285,11 @@ extension DatabaseQueue : DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - DatabaseWriter
|
||||
|
||||
extension DatabaseQueue : DatabaseWriter {
|
||||
|
||||
// MARK: - DatabaseWriter Protocol Adoption
|
||||
|
||||
|
||||
/// Alias for `inDatabase`. See `DatabaseWriter.write`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try inDatabase(block)
|
||||
}
|
||||
@@ -326,22 +300,34 @@ extension DatabaseQueue : DatabaseWriter {
|
||||
/// SQLCipher, attempts to write in the database throw a DatabaseError whose
|
||||
/// resultCode is `SQLITE_READONLY`.
|
||||
///
|
||||
/// This method must be called from the protected database dispatch queue.
|
||||
/// This method must be called from the protected database dispatch queue,
|
||||
/// outside of a transaction. You'll get a fatal error otherwise.
|
||||
///
|
||||
/// See `DatabaseWriter.readFromCurrentState`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func readFromCurrentState(_ block: @escaping (Database) -> Void) {
|
||||
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
serializedDatabase.execute { readOnly($0, block) }
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, *) {
|
||||
serializedDatabase.execute { readOnly($0, block) }
|
||||
} else {
|
||||
serializedDatabase.execute(block)
|
||||
}
|
||||
#endif
|
||||
// Check that we're on the correct queue...
|
||||
serializedDatabase.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction.")
|
||||
|
||||
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
readOnly(db, block)
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, *) {
|
||||
readOnly(db, block)
|
||||
} else {
|
||||
block(db)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Unsafe Database Access
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
@@ -356,19 +342,13 @@ extension DatabaseQueue : DatabaseWriter {
|
||||
}
|
||||
}
|
||||
|
||||
// Wraps the block between two `PRAGMA query_only` statements.
|
||||
//
|
||||
// This method is unsafe because the two calls to `PRAGMA query_only` are
|
||||
// not guaranteed to be serialized (some other thread could mess with this).
|
||||
private func readOnly<T>(_ db: Database, _ block: (Database) throws -> T) rethrows -> T {
|
||||
if db.configuration.readonly {
|
||||
guard !db.configuration.readonly else {
|
||||
return try block(db)
|
||||
} else {
|
||||
try! db.execute("PRAGMA query_only = 1") // Assume can't fail
|
||||
let result = try block(db)
|
||||
try! db.execute("PRAGMA query_only = 0") // Assume can't fail
|
||||
return result
|
||||
}
|
||||
|
||||
// Assume those pragmas never fail
|
||||
try! db.execute("PRAGMA query_only = 1")
|
||||
defer { try! db.execute("PRAGMA query_only = 0") }
|
||||
return try block(db)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// The protocol for all types that can fetch values from a database.
|
||||
@@ -206,3 +208,57 @@ extension DatabaseReader {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A type-erased DatabaseReader
|
||||
///
|
||||
/// Instances of AnyDatabaseReader forward their methods to an arbitrary
|
||||
/// underlying database reader.
|
||||
public final class AnyDatabaseReader : DatabaseReader {
|
||||
private let base: DatabaseReader
|
||||
|
||||
/// Creates a database reader that wraps a base database reader.
|
||||
public init(_ base: DatabaseReader) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// :nodoc:
|
||||
public func read<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.read(block)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeRead(block)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeReentrantRead(block)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// :nodoc:
|
||||
public func add(function: DatabaseFunction) {
|
||||
base.add(function: function)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func remove(function: DatabaseFunction) {
|
||||
base.remove(function: function)
|
||||
}
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// :nodoc:
|
||||
public func add(collation: DatabaseCollation) {
|
||||
base.add(collation: collation)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
base.remove(collation: collation)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
/// DatabaseRegion defines a region in the database. DatabaseRegion is dedicated
|
||||
/// to help transaction observers recognize impactful database changes in their
|
||||
/// `observes(eventsOfKind:)` and `databaseDidChange(with:)` methods.
|
||||
///
|
||||
/// A database region is the union of any number of "table regions", which can
|
||||
/// cover a full table, or the combination of columns and rows (identified by
|
||||
/// their rowids):
|
||||
///
|
||||
/// |Table1 | |Table2 | |Table3 | |Table4 | |Table5 |
|
||||
/// |-------| |-------| |-------| |-------| |-------|
|
||||
/// |x|x|x|x| |x| | | | |x|x|x|x| |x|x| |x| | | | | |
|
||||
/// |x|x|x|x| |x| | | | | | | | | | | | | | | |x| | |
|
||||
/// |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | |
|
||||
/// |x|x|x|x| |x| | | | | | | | | | | | | | | | | | |
|
||||
///
|
||||
/// You don't create a database region directly. Instead, you use one of
|
||||
/// those methods:
|
||||
///
|
||||
/// - `SelectStatement.fetchedRegion`:
|
||||
///
|
||||
/// let statement = db.makeSelectStatement("SELECT name, score FROM players")
|
||||
/// print(statement.fetchedRegion)
|
||||
/// // prints "players(name,score)"
|
||||
///
|
||||
/// - `Request.fetchedRegion(_:)`
|
||||
///
|
||||
/// let request = Player.filter(key: 1)
|
||||
/// try print(request.fetchedRegion(db))
|
||||
/// // prints "players(*)[1]"
|
||||
///
|
||||
/// Database regions returned by requests can be more precise than regions
|
||||
/// returned by select statements. Especially, regions returned by statements
|
||||
/// don't know about rowids:
|
||||
///
|
||||
/// // A plain statement
|
||||
/// let statement = db.makeSelectStatement("SELECT * FROM players WHERE id = 1")
|
||||
/// statement.fetchedRegion // "players(*)"
|
||||
///
|
||||
/// // A query interface request that executes the same statement:
|
||||
/// let request = Player.filter(key: 1)
|
||||
/// try request.fetchedRegion(db) // "players(*)[1]"
|
||||
public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
private let tableRegions: [String: TableRegion]?
|
||||
private init(tableRegions: [String: TableRegion]?) {
|
||||
self.tableRegions = tableRegions
|
||||
}
|
||||
|
||||
/// Returns whether the region is empty.
|
||||
public var isEmpty: Bool {
|
||||
guard let tableRegions = tableRegions else { return false }
|
||||
return tableRegions.isEmpty
|
||||
}
|
||||
|
||||
/// The full database: (All columns in all tables) × (all rows)
|
||||
static let fullDatabase = DatabaseRegion(tableRegions: nil)
|
||||
|
||||
/// The empty database region
|
||||
public init() {
|
||||
self.init(tableRegions: [:])
|
||||
}
|
||||
|
||||
/// A full table: (all columns in the table) × (all rows)
|
||||
init(table: String) {
|
||||
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>) {
|
||||
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>) {
|
||||
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: rowIds)])
|
||||
}
|
||||
|
||||
/// Returns the intersection of this region and the given one.
|
||||
///
|
||||
/// This method is not public because there is no known public use case for
|
||||
/// this intersection. It is currently only used as support for
|
||||
/// the isModified(byEventsOfKind:) method.
|
||||
func intersection(_ other: DatabaseRegion) -> DatabaseRegion {
|
||||
guard let tableRegions = tableRegions else { return other }
|
||||
guard let otherTableRegions = other.tableRegions else { return self }
|
||||
|
||||
var tableRegionsIntersection: [String: TableRegion] = [:]
|
||||
for (table, tableRegion) in tableRegions {
|
||||
guard let otherTableRegion = otherTableRegions
|
||||
.first(where: { (otherTable, _) in otherTable == table })?
|
||||
.value else { continue }
|
||||
let tableRegionIntersection = tableRegion.intersection(otherTableRegion)
|
||||
guard !tableRegionIntersection.isEmpty else { continue }
|
||||
tableRegionsIntersection[table] = tableRegionIntersection
|
||||
}
|
||||
|
||||
return DatabaseRegion(tableRegions: tableRegionsIntersection)
|
||||
}
|
||||
|
||||
/// Only keeps those rowIds in the given table
|
||||
func tableIntersection(_ table: String, rowIds: Set<Int64>) -> DatabaseRegion {
|
||||
guard var tableRegions = tableRegions else {
|
||||
return DatabaseRegion(table: table, rowIds: rowIds)
|
||||
}
|
||||
|
||||
guard let tableRegion = tableRegions[table] else {
|
||||
return self
|
||||
}
|
||||
|
||||
let intersection = tableRegion.intersection(TableRegion(columns: nil, rowIds: rowIds))
|
||||
if intersection.isEmpty {
|
||||
tableRegions.removeValue(forKey: table)
|
||||
} else {
|
||||
tableRegions[table] = intersection
|
||||
}
|
||||
return DatabaseRegion(tableRegions: tableRegions)
|
||||
}
|
||||
|
||||
/// Returns the union of this region and the given one.
|
||||
public func union(_ other: DatabaseRegion) -> DatabaseRegion {
|
||||
guard let tableRegions = tableRegions else { return .fullDatabase }
|
||||
guard let otherTableRegions = other.tableRegions else { return .fullDatabase }
|
||||
|
||||
var tableRegionsUnion: [String: TableRegion] = [:]
|
||||
let tableNames = Set(tableRegions.map { $0.key }).union(Set(otherTableRegions.map { $0.key }))
|
||||
for table in tableNames {
|
||||
let tableRegion = tableRegions[table]
|
||||
let otherTableRegion = otherTableRegions[table]
|
||||
let tableRegionUnion: TableRegion
|
||||
switch (tableRegion, otherTableRegion) {
|
||||
case (nil, nil):
|
||||
preconditionFailure()
|
||||
case (nil, let tableRegion?), (let tableRegion?, nil):
|
||||
tableRegionUnion = tableRegion
|
||||
case (let tableRegion?, let otherTableRegion?):
|
||||
tableRegionUnion = tableRegion.union(otherTableRegion)
|
||||
}
|
||||
tableRegionsUnion[table] = tableRegionUnion
|
||||
}
|
||||
|
||||
return DatabaseRegion(tableRegions: tableRegionsUnion)
|
||||
}
|
||||
|
||||
/// Inserts the given region into this region
|
||||
public mutating func formUnion(_ other: DatabaseRegion) {
|
||||
self = union(other)
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseRegion {
|
||||
|
||||
// MARK: - Database Events
|
||||
|
||||
/// Returns whether the content in the region would be impacted if the
|
||||
/// database were modified by an event of this kind.
|
||||
public func isModified(byEventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
return !intersection(eventKind.modifiedRegion).isEmpty
|
||||
}
|
||||
|
||||
/// Returns whether the content in the region is impacted by this event.
|
||||
///
|
||||
/// - precondition: event has been filtered by the same region
|
||||
/// in the TransactionObserver.observes(eventsOfKind:) method, by calling
|
||||
/// region.isModified(byEventsOfKind:)
|
||||
public func isModified(by event: DatabaseEvent) -> Bool {
|
||||
guard let tableRegions = tableRegions else {
|
||||
return true
|
||||
}
|
||||
|
||||
switch tableRegions.count {
|
||||
case 1:
|
||||
// The precondition applies here:
|
||||
//
|
||||
// The region contains a single table. Due to the
|
||||
// filtering of events performed in observes(eventsOfKind:), the
|
||||
// event argument is guaranteed to be about the fetched table.
|
||||
// We thus only have to check for rowIds.
|
||||
assert(event.tableName == tableRegions[tableRegions.startIndex].key) // sanity check
|
||||
guard let rowIds = tableRegions[tableRegions.startIndex].value.rowIds else {
|
||||
return true
|
||||
}
|
||||
return rowIds.contains(event.rowID)
|
||||
default:
|
||||
guard let tableRegion = tableRegions[event.tableName] else {
|
||||
// Shouldn't happen if the precondition is met.
|
||||
fatalError("precondition failure: event was not filtered out in observes(eventsOfKind:) by region.isModified(byEventsOfKind:)")
|
||||
}
|
||||
guard let rowIds = tableRegion.rowIds else {
|
||||
return true
|
||||
}
|
||||
return rowIds.contains(event.rowID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Equatable
|
||||
extension DatabaseRegion {
|
||||
/// :nodoc:
|
||||
public static func == (lhs: DatabaseRegion, rhs: DatabaseRegion) -> Bool {
|
||||
switch (lhs.tableRegions, rhs.tableRegions) {
|
||||
case (nil, nil):
|
||||
return true
|
||||
case (let ltableRegions?, let rtableRegions?):
|
||||
let ltableNames = Set(ltableRegions.map { $0.key })
|
||||
let rtableNames = Set(rtableRegions.map { $0.key })
|
||||
guard ltableNames == rtableNames else {
|
||||
return false
|
||||
}
|
||||
for tableName in ltableNames {
|
||||
if ltableRegions[tableName]! != rtableRegions[tableName]! {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// CustomStringConvertible
|
||||
extension DatabaseRegion {
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
guard let tableRegions = tableRegions else {
|
||||
return "full database"
|
||||
}
|
||||
if tableRegions.isEmpty {
|
||||
return "empty"
|
||||
}
|
||||
return tableRegions
|
||||
.sorted(by: { (l, r) in l.key < r.key })
|
||||
.map { (table, tableRegion) in
|
||||
var desc = table
|
||||
if let columns = tableRegion.columns {
|
||||
desc += "(" + columns.sorted().joined(separator: ",") + ")"
|
||||
} else {
|
||||
desc += "(*)"
|
||||
}
|
||||
if let rowIds = tableRegion.rowIds {
|
||||
desc += "[" + rowIds.sorted().map { "\($0)" }.joined(separator: ",") + "]"
|
||||
}
|
||||
return desc
|
||||
}
|
||||
.joined(separator: ",")
|
||||
}
|
||||
}
|
||||
|
||||
private struct TableRegion: Equatable {
|
||||
var columns: Set<String>? // nil means "all columns"
|
||||
var rowIds: Set<Int64>? // nil means "all rowids"
|
||||
|
||||
var isEmpty: Bool {
|
||||
if let columns = columns, columns.isEmpty { return true }
|
||||
if let rowIds = rowIds, rowIds.isEmpty { return true }
|
||||
return false
|
||||
}
|
||||
|
||||
static func == (lhs: TableRegion, rhs: TableRegion) -> Bool {
|
||||
if lhs.columns != rhs.columns { return false }
|
||||
if lhs.rowIds != rhs.rowIds { return false }
|
||||
return true
|
||||
}
|
||||
|
||||
func intersection(_ other: TableRegion) -> TableRegion {
|
||||
let columnsIntersection: Set<String>?
|
||||
switch (self.columns, other.columns) {
|
||||
case (nil, let columns), (let columns, nil):
|
||||
columnsIntersection = columns
|
||||
case (let columns?, let other?):
|
||||
columnsIntersection = columns.intersection(other)
|
||||
}
|
||||
|
||||
let rowIdsIntersection: Set<Int64>?
|
||||
switch (self.rowIds, other.rowIds) {
|
||||
case (nil, let rowIds), (let rowIds, nil):
|
||||
rowIdsIntersection = rowIds
|
||||
case (let rowIds?, let other?):
|
||||
rowIdsIntersection = rowIds.intersection(other)
|
||||
}
|
||||
|
||||
return TableRegion(columns: columnsIntersection, rowIds: rowIdsIntersection)
|
||||
}
|
||||
|
||||
func union(_ other: TableRegion) -> TableRegion {
|
||||
let columnsUnion: Set<String>?
|
||||
switch (self.columns, other.columns) {
|
||||
case (nil, _), (_, nil):
|
||||
columnsUnion = nil
|
||||
case (let columns?, let other?):
|
||||
columnsUnion = columns.union(other)
|
||||
}
|
||||
|
||||
let rowIdsUnion: Set<Int64>?
|
||||
switch (self.rowIds, other.rowIds) {
|
||||
case (nil, _), (_, nil):
|
||||
rowIdsUnion = nil
|
||||
case (let rowIds?, let other?):
|
||||
rowIdsUnion = rowIds.union(other)
|
||||
}
|
||||
|
||||
return TableRegion(columns: columnsUnion, rowIds: rowIdsUnion)
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,12 @@
|
||||
/// The protocol for schema cache.
|
||||
///
|
||||
/// This protocol must not contain values that are valid for a single connection
|
||||
/// only, because several connections can share the same schema cache.
|
||||
///
|
||||
/// Statements can't be cached here, for example.
|
||||
/// The protocol for database schema cache.
|
||||
protocol DatabaseSchemaCache {
|
||||
mutating func clear()
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo??
|
||||
mutating func set(primaryKey: PrimaryKeyInfo?, forTable table: String)
|
||||
func canonicalName(table: String) -> String?
|
||||
mutating func set(canonicalName: String, forTable table: String)
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo?
|
||||
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String)
|
||||
|
||||
func columns(in table: String) -> [ColumnInfo]?
|
||||
mutating func set(columns: [ColumnInfo], forTable table: String)
|
||||
@@ -21,24 +19,34 @@ protocol DatabaseSchemaCache {
|
||||
}
|
||||
|
||||
/// A thread-unsafe database schema cache
|
||||
final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
private var primaryKeys: [String: PrimaryKeyInfo?] = [:]
|
||||
struct SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
private var canonicalNames: [String: String] = [:]
|
||||
private var primaryKeys: [String: PrimaryKeyInfo] = [:]
|
||||
private var columns: [String: [ColumnInfo]] = [:]
|
||||
private var indexes: [String: [IndexInfo]] = [:]
|
||||
private var foreignKeys: [String: [ForeignKeyInfo]] = [:]
|
||||
|
||||
func clear() {
|
||||
mutating func clear() {
|
||||
canonicalNames = [:]
|
||||
primaryKeys = [:]
|
||||
columns = [:]
|
||||
indexes = [:]
|
||||
foreignKeys = [:]
|
||||
}
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo?? {
|
||||
func canonicalName(table: String) -> String? {
|
||||
return canonicalNames[table]
|
||||
}
|
||||
|
||||
mutating func set(canonicalName: String, forTable table: String) {
|
||||
canonicalNames[table] = table
|
||||
}
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
|
||||
return primaryKeys[table]
|
||||
}
|
||||
|
||||
func set(primaryKey: PrimaryKeyInfo?, forTable table: String) {
|
||||
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
|
||||
primaryKeys[table] = primaryKey
|
||||
}
|
||||
|
||||
@@ -46,7 +54,7 @@ final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
return columns[table]
|
||||
}
|
||||
|
||||
func set(columns: [ColumnInfo], forTable table: String) {
|
||||
mutating func set(columns: [ColumnInfo], forTable table: String) {
|
||||
self.columns[table] = columns
|
||||
}
|
||||
|
||||
@@ -54,7 +62,7 @@ final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
return indexes[table]
|
||||
}
|
||||
|
||||
func set(indexes: [IndexInfo], forTable table: String) {
|
||||
mutating func set(indexes: [IndexInfo], forTable table: String) {
|
||||
self.indexes[table] = indexes
|
||||
}
|
||||
|
||||
@@ -62,48 +70,27 @@ final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
return foreignKeys[table]
|
||||
}
|
||||
|
||||
func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
|
||||
mutating func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
|
||||
self.foreignKeys[table] = foreignKeys
|
||||
}
|
||||
}
|
||||
|
||||
/// A thread-safe database schema cache
|
||||
final class SharedDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
private let cache = ReadWriteBox(SimpleDatabaseSchemaCache())
|
||||
/// An always empty database schema cache
|
||||
struct EmptyDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
func clear() { }
|
||||
|
||||
func clear() {
|
||||
cache.write { $0.clear() }
|
||||
}
|
||||
func canonicalName(table: String) -> String? { return nil }
|
||||
func set(canonicalName: String, forTable table: String) { }
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo?? {
|
||||
return cache.read { $0.primaryKey(table) }
|
||||
}
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo? { return nil }
|
||||
func set(primaryKey: PrimaryKeyInfo, forTable table: String) { }
|
||||
|
||||
func set(primaryKey: PrimaryKeyInfo?, forTable table: String) {
|
||||
cache.write { $0.set(primaryKey: primaryKey, forTable: table) }
|
||||
}
|
||||
func columns(in table: String) -> [ColumnInfo]? { return nil }
|
||||
func set(columns: [ColumnInfo], forTable table: String) { }
|
||||
|
||||
func columns(in table: String) -> [ColumnInfo]? {
|
||||
return cache.read { $0.columns(in: table) }
|
||||
}
|
||||
func indexes(on table: String) -> [IndexInfo]? { return nil }
|
||||
func set(indexes: [IndexInfo], forTable table: String) { }
|
||||
|
||||
func set(columns: [ColumnInfo], forTable table: String) {
|
||||
cache.write { $0.set(columns: columns, forTable: table) }
|
||||
}
|
||||
|
||||
func indexes(on table: String) -> [IndexInfo]? {
|
||||
return cache.read { $0.indexes(on: table) }
|
||||
}
|
||||
|
||||
func set(indexes: [IndexInfo], forTable table: String) {
|
||||
cache.write { $0.set(indexes: indexes, forTable: table) }
|
||||
}
|
||||
|
||||
func foreignKeys(on table: String) -> [ForeignKeyInfo]? {
|
||||
return cache.read { $0.foreignKeys(on: table) }
|
||||
}
|
||||
|
||||
func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
|
||||
cache.write { $0.set(foreignKeys: foreignKeys, forTable: table) }
|
||||
}
|
||||
func foreignKeys(on table: String) -> [ForeignKeyInfo]? { return nil }
|
||||
func set(foreignKeys: [ForeignKeyInfo], forTable table: String) { }
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
/// A DatabaseSnapshot sees an unchanging database content, as it existed at the
|
||||
/// moment it was created.
|
||||
///
|
||||
/// See DatabasePool.makeSnapshot()
|
||||
///
|
||||
/// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html
|
||||
public class DatabaseSnapshot : DatabaseReader {
|
||||
private var serializedDatabase: SerializedDatabase
|
||||
|
||||
/// The database configuration
|
||||
var configuration: Configuration {
|
||||
return serializedDatabase.configuration
|
||||
}
|
||||
|
||||
init(path: String, configuration: Configuration = Configuration()) throws {
|
||||
var configuration = configuration
|
||||
configuration.readonly = true
|
||||
configuration.allowsUnsafeTransactions = true // Snaphost keeps a long-lived transaction
|
||||
|
||||
serializedDatabase = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
schemaCache: SimpleDatabaseSchemaCache())
|
||||
|
||||
try serializedDatabase.sync { db in
|
||||
// Assert WAL mode
|
||||
let journalMode = try String.fetchOne(db, "PRAGMA journal_mode")
|
||||
guard journalMode == "wal" else {
|
||||
throw DatabaseError(message: "WAL mode is not activated at path: \(path)")
|
||||
}
|
||||
|
||||
// Establish snapshot isolation (see deinit)
|
||||
try db.beginTransaction(.deferred)
|
||||
|
||||
// Take snapshot
|
||||
// See DatabasePool.readFromCurrentState for a complete discussion
|
||||
try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").cursor().next()
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
// Leave snapshot isolation
|
||||
serializedDatabase.sync { db in
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// DatabaseReader
|
||||
extension DatabaseSnapshot {
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// Synchronously executes a read-only block that takes a database
|
||||
/// connection, and returns its result.
|
||||
///
|
||||
/// let players = try snapshot.read { db in
|
||||
/// try Player.fetchAll(...)
|
||||
/// }
|
||||
///
|
||||
/// - 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 {
|
||||
return try serializedDatabase.sync(block)
|
||||
}
|
||||
|
||||
/// Alias for `read`. See `DatabaseReader.unsafeRead`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.sync(block)
|
||||
}
|
||||
|
||||
/// Alias for `read`. See `DatabaseReader.unsafeReentrantRead`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try serializedDatabase.sync(block)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
///
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int + 1
|
||||
/// }
|
||||
/// snapshot.add(function: fn)
|
||||
/// try snapshot.read { db in
|
||||
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
|
||||
/// }
|
||||
public func add(function: DatabaseFunction) {
|
||||
serializedDatabase.sync { $0.add(function: function) }
|
||||
}
|
||||
|
||||
/// Remove an SQL function.
|
||||
public func remove(function: DatabaseFunction) {
|
||||
serializedDatabase.sync { $0.remove(function: function) }
|
||||
}
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// Add or redefine a collation.
|
||||
///
|
||||
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// snapshot.add(collation: collation)
|
||||
/// let files = try snapshot.read { db in
|
||||
/// try File.fetchAll(db, "SELECT * FROM files ORDER BY name COLLATE localized_standard")
|
||||
/// }
|
||||
public func add(collation: DatabaseCollation) {
|
||||
serializedDatabase.sync { $0.add(collation: collation) }
|
||||
}
|
||||
|
||||
/// Remove a collation.
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
serializedDatabase.sync { $0.remove(collation: collation) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import Foundation
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
// MARK: - DatabaseValue
|
||||
@@ -9,7 +10,12 @@ import Foundation
|
||||
/// DatabaseValue is the intermediate type between SQLite and your values.
|
||||
///
|
||||
/// See https://www.sqlite.org/datatype3.html
|
||||
public struct DatabaseValue {
|
||||
public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLExpressible, SQLExpression {
|
||||
/// The SQLite storage
|
||||
public let storage: Storage
|
||||
|
||||
/// The NULL DatabaseValue.
|
||||
public static let null = DatabaseValue(storage: .null)
|
||||
|
||||
/// An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB).
|
||||
public enum Storage : Equatable {
|
||||
@@ -61,12 +67,6 @@ public struct DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
/// The SQLite storage
|
||||
public let storage: Storage
|
||||
|
||||
/// The NULL DatabaseValue.
|
||||
public static let null = DatabaseValue(storage: .null)
|
||||
|
||||
/// Creates a DatabaseValue from Any.
|
||||
///
|
||||
/// The result is nil unless object adopts DatabaseValueConvertible.
|
||||
@@ -77,7 +77,6 @@ public struct DatabaseValue {
|
||||
self = convertible.databaseValue
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Extracting Value
|
||||
|
||||
/// Returns true if databaseValue is NULL.
|
||||
@@ -90,13 +89,9 @@ public struct DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Not Public
|
||||
|
||||
init(storage: Storage) {
|
||||
// This initializer is not public because Storage is not a safe type:
|
||||
// one can create a Storage of zero-length Data, which is invalid
|
||||
// because SQLite can't store zero-length blobs.
|
||||
self.storage = storage
|
||||
}
|
||||
|
||||
@@ -112,9 +107,12 @@ public struct DatabaseValue {
|
||||
case SQLITE_TEXT:
|
||||
storage = .string(String(cString: sqlite3_value_text(sqliteValue)!))
|
||||
case SQLITE_BLOB:
|
||||
let bytes = unsafeBitCast(sqlite3_value_blob(sqliteValue), to: UnsafePointer<UInt8>.self)
|
||||
let count = Int(sqlite3_value_bytes(sqliteValue))
|
||||
storage = .blob(Data(bytes: bytes, count: count)) // copy bytes
|
||||
if let bytes = sqlite3_value_blob(sqliteValue) {
|
||||
let count = Int(sqlite3_value_bytes(sqliteValue))
|
||||
storage = .blob(Data(bytes: bytes, count: count)) // copy bytes
|
||||
} else {
|
||||
storage = .blob(Data())
|
||||
}
|
||||
case let type:
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError("Unexpected SQLite value type: \(type)")
|
||||
@@ -133,9 +131,12 @@ public struct DatabaseValue {
|
||||
case SQLITE_TEXT:
|
||||
storage = .string(String(cString: sqlite3_column_text(sqliteStatement, Int32(index))))
|
||||
case SQLITE_BLOB:
|
||||
let bytes = unsafeBitCast(sqlite3_column_blob(sqliteStatement, Int32(index)), to: UnsafePointer<UInt8>.self)
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
storage = .blob(Data(bytes: bytes, count: count)) // copy bytes
|
||||
if let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) {
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
storage = .blob(Data(bytes: bytes, count: count)) // copy bytes
|
||||
} else {
|
||||
storage = .blob(Data())
|
||||
}
|
||||
case let type:
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError("Unexpected SQLite column type: \(type)")
|
||||
@@ -143,13 +144,13 @@ public struct DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Hashable & Equatable
|
||||
|
||||
/// DatabaseValue adopts Hashable.
|
||||
extension DatabaseValue : Hashable {
|
||||
// Hashable
|
||||
extension DatabaseValue {
|
||||
|
||||
/// The hash value
|
||||
/// :nodoc:
|
||||
public var hashValue: Int {
|
||||
switch storage {
|
||||
case .null:
|
||||
@@ -190,9 +191,9 @@ extension DatabaseValue : Hashable {
|
||||
case (.double(let lhs), .double(let rhs)):
|
||||
return lhs == rhs
|
||||
case (.int64(let lhs), .double(let rhs)):
|
||||
return int64EqualDouble(lhs, rhs)
|
||||
return Int64(exactly: rhs) == lhs
|
||||
case (.double(let lhs), .int64(let rhs)):
|
||||
return int64EqualDouble(rhs, lhs)
|
||||
return rhs == Int64(exactly: lhs)
|
||||
case (.string(let lhs), .string(let rhs)):
|
||||
return lhs == rhs
|
||||
case (.blob(let lhs), .blob(let rhs)):
|
||||
@@ -203,16 +204,16 @@ extension DatabaseValue : Hashable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if i and d hold exactly the same value, and if converting one
|
||||
/// type to the other does not lose any information.
|
||||
private func int64EqualDouble(_ i: Int64, _ d: Double) -> Bool {
|
||||
// See http://stackoverflow.com/questions/33719132/how-to-test-for-lossless-double-integer-conversion/33784296#33784296
|
||||
return (d >= Double(Int64.min))
|
||||
&& (d < Double(Int64.max))
|
||||
&& (round(d) == d)
|
||||
&& (i == Int64(d))
|
||||
}
|
||||
// MARK: - SQLSelectable
|
||||
|
||||
extension DatabaseValue {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func qualified(by qualifier: SQLTableQualifier) -> DatabaseValue {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Lossless conversions
|
||||
|
||||
@@ -292,11 +293,8 @@ extension DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - DatabaseValueConvertible & SQLExpressible & SQLExpression
|
||||
|
||||
/// DatabaseValue adopts DatabaseValueConvertible.
|
||||
extension DatabaseValue : DatabaseValueConvertible {
|
||||
// DatabaseValueConvertible
|
||||
extension DatabaseValue {
|
||||
/// Returns self
|
||||
public var databaseValue: DatabaseValue {
|
||||
return self
|
||||
@@ -308,17 +306,19 @@ extension DatabaseValue : DatabaseValueConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValue : SQLExpressible {
|
||||
|
||||
// SQLExpressible
|
||||
extension DatabaseValue {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public var sqlExpression: SQLExpression {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
/// DatabaseValue adopts SQLExpression.
|
||||
extension DatabaseValue : SQLExpression {
|
||||
// SQLExpression
|
||||
extension DatabaseValue {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
// fast path for NULL
|
||||
if isNull {
|
||||
@@ -336,6 +336,7 @@ extension DatabaseValue : SQLExpression {
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public var negated: SQLExpression {
|
||||
switch storage {
|
||||
case .null:
|
||||
@@ -361,11 +362,9 @@ extension DatabaseValue : SQLExpression {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
/// DatabaseValue adopts CustomStringConvertible.
|
||||
extension DatabaseValue : CustomStringConvertible {
|
||||
/// A textual representation of `self`.
|
||||
// CustomStringConvertible
|
||||
extension DatabaseValue {
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
switch storage {
|
||||
case .null:
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
// MARK: - DatabaseValueConvertible
|
||||
|
||||
/// Types that adopt DatabaseValueConvertible can be initialized from
|
||||
@@ -6,12 +12,12 @@
|
||||
/// The protocol comes with built-in methods that allow to fetch cursors,
|
||||
/// arrays, or single values:
|
||||
///
|
||||
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // DatabaseCursor<String>
|
||||
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
|
||||
/// try String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// try String.fetchCursor(statement, arguments:...) // DatabaseCursor<String>
|
||||
/// try String.fetchCursor(statement, arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(statement, arguments:...) // [String]
|
||||
/// try String.fetchOne(statement, arguments:...) // String?
|
||||
///
|
||||
@@ -24,38 +30,115 @@ public protocol DatabaseValueConvertible : SQLExpressible {
|
||||
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self?
|
||||
}
|
||||
|
||||
// SQLExpressible adoption
|
||||
extension DatabaseValueConvertible {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public var sqlExpression: SQLExpression {
|
||||
return databaseValue
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor of database values extracted from a single column.
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let urls: DatabaseValueCursor<URL> = try URL.fetchCursor(db, "SELECT url FROM links")
|
||||
/// while let url = urls.next() { // URL
|
||||
/// print(url)
|
||||
/// }
|
||||
/// }
|
||||
public final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
|
||||
private let statement: SelectStatement
|
||||
private let sqliteStatement: SQLiteStatement
|
||||
private let columnIndex: Int32
|
||||
private var done = false
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
// We'll read from leftmost column at index 0, unless adapter mangles columns
|
||||
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func next() throws -> Value? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: columnIndex)
|
||||
return dbValue.losslessConvert() as Value
|
||||
case let code:
|
||||
statement.database.selectStatementDidFail(statement)
|
||||
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor of optional database values extracted from a single column.
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let urls: NullableDatabaseValueCursor<URL> = try Optional<URL>.fetchCursor(db, "SELECT url FROM links")
|
||||
/// while let url = urls.next() { // URL?
|
||||
/// print(url)
|
||||
/// }
|
||||
/// }
|
||||
public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
|
||||
private let statement: SelectStatement
|
||||
private let sqliteStatement: SQLiteStatement
|
||||
private let columnIndex: Int32
|
||||
private var done = false
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
// We'll read from leftmost column at index 0, unless adapter mangles columns
|
||||
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func next() throws -> Value?? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: columnIndex)
|
||||
return dbValue.losslessConvert() as Value?
|
||||
case let code:
|
||||
statement.database.selectStatementDidFail(statement)
|
||||
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// DatabaseValueConvertible comes with built-in methods that allow to fetch
|
||||
/// cursors, arrays, or single values:
|
||||
///
|
||||
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // DatabaseCursor<String>
|
||||
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
|
||||
/// try String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// try String.fetchCursor(statement, arguments:...) // DatabaseCursor<String>
|
||||
/// 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.
|
||||
extension DatabaseValueConvertible {
|
||||
|
||||
|
||||
// MARK: Fetching From SelectStatement
|
||||
|
||||
/// Returns a cursor over values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let names = try String.fetchCursor(statement) // DatabaseCursor<String>
|
||||
/// let names = try String.fetchCursor(statement) // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
@@ -71,13 +154,8 @@ extension DatabaseValueConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
|
||||
// Reuse a single mutable row for performance
|
||||
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
return statement.cursor(arguments: arguments, next: {
|
||||
let dbValue: DatabaseValue = row.value(atIndex: 0)
|
||||
return dbValue.losslessConvert(sql: statement.sql, arguments: arguments) as Self
|
||||
})
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> {
|
||||
return try DatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from a prepared statement.
|
||||
@@ -110,12 +188,8 @@ extension DatabaseValueConvertible {
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
|
||||
// Reuse a single mutable row for performance
|
||||
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
let cursor: DatabaseCursor<Self?> = statement.cursor(arguments: arguments, next: {
|
||||
let dbValue: DatabaseValue = row.value(atIndex: 0)
|
||||
return dbValue.losslessConvert(sql: statement.sql, arguments: arguments) as Self?
|
||||
})
|
||||
// fetchOne returns nil if there is no row, or if there is a row with a null value
|
||||
let cursor = try NullableDatabaseValueCursor<Self>(statement: statement, arguments: arguments, adapter: adapter)
|
||||
return try cursor.next() ?? nil
|
||||
}
|
||||
}
|
||||
@@ -127,8 +201,8 @@ extension DatabaseValueConvertible {
|
||||
/// Returns a cursor over values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn)
|
||||
/// let names = try String.fetchCursor(db, request) // DatabaseCursor<String>
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try String.fetchCursor(db, request) // Cursor of String
|
||||
/// for let name = try names.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
@@ -143,7 +217,7 @@ extension DatabaseValueConvertible {
|
||||
/// - request: A fetch request.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseCursor<Self> {
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseValueCursor<Self> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
@@ -151,7 +225,7 @@ extension DatabaseValueConvertible {
|
||||
/// Returns an array of values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn)
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try String.fetchAll(db, request) // [String]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -167,7 +241,7 @@ extension DatabaseValueConvertible {
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn)
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let name = try String.fetchOne(db, request) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -184,7 +258,7 @@ extension DatabaseValueConvertible {
|
||||
|
||||
/// Returns a cursor over values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try String.fetchCursor(db, "SELECT name FROM ...") // DatabaseCursor<String>
|
||||
/// let names = try String.fetchCursor(db, "SELECT name FROM ...") // Cursor of String
|
||||
/// while let name = try name.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
@@ -201,7 +275,7 @@ extension DatabaseValueConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> {
|
||||
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
@@ -243,11 +317,11 @@ extension DatabaseValueConvertible {
|
||||
/// Swift's Optional comes with built-in methods that allow to fetch cursors
|
||||
/// and arrays of optional DatabaseValueConvertible:
|
||||
///
|
||||
/// try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // DatabaseCursor<String?>
|
||||
/// try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// try Optional<String>.fetchCursor(statement, arguments:...) // DatabaseCursor<String?>
|
||||
/// try Optional<String>.fetchCursor(statement, arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(statement, arguments:...) // [String?]
|
||||
///
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
@@ -258,7 +332,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
/// Returns a cursor over optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchCursor(statement) // DatabaseCursor<String?>
|
||||
/// let names = try Optional<String>.fetchCursor(statement) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
@@ -274,13 +348,8 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Wrapped?> {
|
||||
// Reuse a single mutable row for performance
|
||||
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
return statement.cursor(arguments: arguments, next: {
|
||||
let dbValue: DatabaseValue = row.value(atIndex: 0)
|
||||
return dbValue.losslessConvert(sql: statement.sql, arguments: arguments) as Wrapped?
|
||||
})
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> {
|
||||
return try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a prepared statement.
|
||||
@@ -306,8 +375,8 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
/// Returns a cursor over optional values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn)
|
||||
/// let names = try Optional<String>.fetchCursor(db, request) // DatabaseCursor<String?>
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try Optional<String>.fetchCursor(db, request) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
@@ -322,7 +391,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
/// - requet: A fetch request.
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseCursor<Wrapped?> {
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> NullableDatabaseValueCursor<Wrapped> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
@@ -330,7 +399,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
/// Returns an array of optional values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn)
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try Optional<String>.fetchAll(db, request) // [String?]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -347,7 +416,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a cursor over optional values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // DatabaseCursor<String?>
|
||||
/// let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
@@ -364,7 +433,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Wrapped?> {
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> {
|
||||
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
|
||||
@@ -41,65 +41,23 @@ public protocol DatabaseWriter : DatabaseReader {
|
||||
/// Synchronously or asynchronously executes a read-only block that takes a
|
||||
/// database connection.
|
||||
///
|
||||
/// This method must be called from a writing dispatch queue.
|
||||
/// This method must be called from a writing dispatch queue, outside of any
|
||||
/// transaction. You'll get a fatal error otherwise.
|
||||
///
|
||||
/// The *block* argument is guaranteed to see the database in the state it
|
||||
/// has at the moment this method is called (see below). Eventual concurrent
|
||||
/// The *block* argument is guaranteed to see the database in the last
|
||||
/// committed state at the moment this method is called. Eventual concurrent
|
||||
/// database updates are *not visible* inside the block.
|
||||
///
|
||||
/// What is the "current state" of the database?
|
||||
/// For example:
|
||||
///
|
||||
/// - When this method is called outside of any transaction, the current
|
||||
/// state is the last committed state.
|
||||
///
|
||||
/// try writer.write { db in
|
||||
/// try db.execute("DELETE FROM persons")
|
||||
/// try writer.readFromCurrentState { db in
|
||||
/// // Guaranteed to be zero
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
|
||||
/// }
|
||||
/// try db.execute("INSERT INTO persons ...")
|
||||
/// try writer.write { db in
|
||||
/// try db.execute("DELETE FROM players")
|
||||
/// try writer.readFromCurrentState { db in
|
||||
/// // Guaranteed to be zero
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
|
||||
/// }
|
||||
///
|
||||
/// - When this method is called inside an uncommitted transation, the
|
||||
/// current state depends on the caller:
|
||||
///
|
||||
/// DatabasePool.readFromCurrentState runs *block* asynchronously in a
|
||||
/// concurrent reader dispatch queue, and release the writing dispatch
|
||||
/// queue early, before the block has finished. In the example below,
|
||||
/// the insertion runs concurrently with the select, and the select sees
|
||||
/// the database in its last committed state.
|
||||
///
|
||||
/// try dbPool.write { db in
|
||||
/// try db.execute("DELETE FROM persons")
|
||||
/// db.inTransaction {
|
||||
/// try db.execute("INSERT INTO persons ...")
|
||||
/// try dbPool.readFromCurrentState { db in
|
||||
/// // Zero
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
|
||||
/// }
|
||||
/// return .commit
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// DatabaseQueue.readFromCurrentState simply runs *block* synchronously,
|
||||
/// and returns when the block has completed. In the example below, the
|
||||
/// select sees the uncommitted state of the database, and the insertion
|
||||
/// is run after the select.
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// try db.execute("DELETE FROM persons")
|
||||
/// db.inTransaction {
|
||||
/// try db.execute("INSERT INTO persons ...")
|
||||
/// try dbQueue.readFromCurrentState { db in
|
||||
/// // One
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
|
||||
/// }
|
||||
/// return .commit
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
/// try db.execute("INSERT INTO players ...")
|
||||
/// }
|
||||
func readFromCurrentState(_ block: @escaping (Database) -> Void) throws
|
||||
}
|
||||
|
||||
@@ -123,3 +81,74 @@ extension DatabaseWriter {
|
||||
write { $0.remove(transactionObserver: transactionObserver) }
|
||||
}
|
||||
}
|
||||
|
||||
/// A type-erased DatabaseWriter
|
||||
///
|
||||
/// Instances of AnyDatabaseWriter forward their methods to an arbitrary
|
||||
/// underlying database writer.
|
||||
public final class AnyDatabaseWriter : DatabaseWriter {
|
||||
private let base: DatabaseWriter
|
||||
|
||||
/// Creates a database writer that wraps a base database writer.
|
||||
public init(_ base: DatabaseWriter) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// :nodoc:
|
||||
public func read<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.read(block)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeRead(block)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeReentrantRead(block)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws {
|
||||
try base.readFromCurrentState(block)
|
||||
}
|
||||
|
||||
// MARK: - Writing in Database
|
||||
|
||||
/// :nodoc:
|
||||
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try base.write(block)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try base.unsafeReentrantWrite(block)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// :nodoc:
|
||||
public func add(function: DatabaseFunction) {
|
||||
base.add(function: function)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func remove(function: DatabaseFunction) {
|
||||
base.remove(function: function)
|
||||
}
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// :nodoc:
|
||||
public func add(collation: DatabaseCollation) {
|
||||
base.add(collation: collation)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
base.remove(collation: collation)
|
||||
}
|
||||
}
|
||||
+187
-84
@@ -4,9 +4,9 @@
|
||||
/// value, record):
|
||||
///
|
||||
/// let request: Request = ...
|
||||
/// try Row.fetchCursor(db, request) // DatabaseCursor<Row>
|
||||
/// try Row.fetchCursor(db, request) // RowCursor
|
||||
/// try String.fetchAll(db, request) // [String]
|
||||
/// try Person.fetchOne(db, request) // Person?
|
||||
/// try Player.fetchOne(db, request) // Player?
|
||||
public protocol Request {
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
@@ -22,6 +22,13 @@ public protocol Request {
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
func fetchCount(_ db: Database) throws -> Int
|
||||
|
||||
/// The database region that the request looks into.
|
||||
///
|
||||
/// This method has a default implementation.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
func fetchedRegion(_ db: Database) throws -> DatabaseRegion
|
||||
}
|
||||
|
||||
extension Request {
|
||||
@@ -36,6 +43,26 @@ extension Request {
|
||||
let sql = "SELECT COUNT(*) FROM (\(statement.sql))"
|
||||
return try Int.fetchOne(db, sql, arguments: statement.arguments)!
|
||||
}
|
||||
|
||||
/// Returns an equivalent SQLRequest.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: An SQLRequest
|
||||
public func asSQLRequest(_ db: Database, cached: Bool = false) throws -> SQLRequest {
|
||||
let (statement, adapter) = try prepare(db)
|
||||
return SQLRequest(statement.sql, arguments: statement.arguments, adapter: adapter, cached: cached)
|
||||
}
|
||||
|
||||
/// The database region that the request looks into.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
let (statement, _) = try prepare(db)
|
||||
return statement.fetchedRegion
|
||||
}
|
||||
}
|
||||
|
||||
extension Request {
|
||||
@@ -44,20 +71,18 @@ extension Request {
|
||||
/// The returned request can fetch if the type T is fetchable (Row,
|
||||
/// value, record).
|
||||
///
|
||||
/// // minHeight in Double?
|
||||
/// let minHeight = Person
|
||||
/// .select(min(heightColumn))
|
||||
/// .asRequest(of: Double.self) // <--
|
||||
/// // Int?
|
||||
/// let maxScore = Player
|
||||
/// .select(max(scoreColumn))
|
||||
/// .asRequest(of: Int.self) // <--
|
||||
/// .fetchOne(db)
|
||||
///
|
||||
/// - parameter type: The fetched type T
|
||||
/// - returns: A typed request bound to type T.
|
||||
public func asRequest<T>(of type: T.Type) -> AnyTypedRequest<T> {
|
||||
return AnyTypedRequest { try self.prepare($0) }
|
||||
return AnyTypedRequest(self)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns an adapted request.
|
||||
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedRequest<Self> {
|
||||
return AdaptedRequest(self, adapter)
|
||||
@@ -66,6 +91,9 @@ extension Request {
|
||||
|
||||
/// An adapted request.
|
||||
public struct AdaptedRequest<Base: Request> : Request {
|
||||
private let base: Base
|
||||
private let adapter: (Database) throws -> RowAdapter
|
||||
|
||||
/// Creates an adapted request from a base request and a closure that builds
|
||||
/// a row adapter from a database connection.
|
||||
init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) {
|
||||
@@ -73,10 +101,7 @@ public struct AdaptedRequest<Base: Request> : Request {
|
||||
self.adapter = adapter
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
let (statement, baseAdapter) = try base.prepare(db)
|
||||
if let baseAdapter = baseAdapter {
|
||||
@@ -86,15 +111,15 @@ public struct AdaptedRequest<Base: Request> : Request {
|
||||
}
|
||||
}
|
||||
|
||||
/// The number of rows fetched by the request.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try base.fetchCount(db)
|
||||
}
|
||||
|
||||
private let base: Base
|
||||
private let adapter: (Database) throws -> RowAdapter
|
||||
/// :nodoc:
|
||||
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try base.fetchedRegion(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// A type-erased Request.
|
||||
@@ -102,35 +127,53 @@ public struct AdaptedRequest<Base: Request> : Request {
|
||||
/// An instance of AnyRequest forwards its operations to an underlying request,
|
||||
/// hiding its specifics.
|
||||
public struct AnyRequest : Request {
|
||||
private let base: Request
|
||||
|
||||
/// Creates a new request that wraps and forwards operations to `request`.
|
||||
public init(_ request: Request) {
|
||||
self._prepare = { try request.prepare($0) }
|
||||
base = request
|
||||
}
|
||||
|
||||
/// Creates a new request whose `prepare()` method wraps and forwards
|
||||
/// operations the argument closure.
|
||||
public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) {
|
||||
_prepare = prepare
|
||||
struct PrepareRequest: Request {
|
||||
let base: (Database) throws -> (SelectStatement, RowAdapter?)
|
||||
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try base(db)
|
||||
}
|
||||
}
|
||||
base = PrepareRequest(base: prepare)
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try _prepare(db)
|
||||
return try base.prepare(db)
|
||||
}
|
||||
|
||||
private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?)
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try base.fetchCount(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try base.fetchedRegion(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// A Request built from raw SQL.
|
||||
public struct SQLRequest : Request {
|
||||
public let sql: String
|
||||
public let arguments: StatementArguments?
|
||||
public let adapter: RowAdapter?
|
||||
private let cache: Cache?
|
||||
|
||||
/// Creates a new request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
///
|
||||
/// let request = SQLRequest("SELECT * FROM persons")
|
||||
/// let request = SQLRequest("SELECT * FROM persons WHERE id = ?", arguments: [1])
|
||||
/// let request = SQLRequest("SELECT * FROM players")
|
||||
/// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
@@ -140,14 +183,14 @@ public struct SQLRequest : Request {
|
||||
/// prepared statement.
|
||||
/// - returns: A SQLRequest
|
||||
public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) {
|
||||
self.init(sql, arguments: arguments, adapter: adapter, fromCache: cached ? .user : nil)
|
||||
self.init(sql, arguments: arguments, adapter: adapter, fromCache: cached ? .public : nil)
|
||||
}
|
||||
|
||||
/// Creates a new request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
///
|
||||
/// let request = SQLRequest("SELECT * FROM persons")
|
||||
/// let request = SQLRequest("SELECT * FROM persons WHERE id = ?", arguments: [1])
|
||||
/// let request = SQLRequest("SELECT * FROM players")
|
||||
/// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
@@ -155,23 +198,28 @@ public struct SQLRequest : Request {
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - statementCacheName: Optional statement cache name.
|
||||
/// - returns: A SQLRequest
|
||||
init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache statementCacheName: Database.StatementCacheName?) {
|
||||
init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache cache: Cache?) {
|
||||
self.sql = sql
|
||||
self.arguments = arguments
|
||||
self.adapter = adapter
|
||||
self.statementCacheName = statementCacheName
|
||||
self.cache = cache
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
///
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
let statement: SelectStatement
|
||||
if let statementCacheName = statementCacheName {
|
||||
statement = try db.selectStatement(sql, fromCache: statementCacheName)
|
||||
} else {
|
||||
switch cache {
|
||||
case .none:
|
||||
statement = try db.makeSelectStatement(sql)
|
||||
case .public?:
|
||||
statement = try db.cachedSelectStatement(sql)
|
||||
case .internal?:
|
||||
statement = try db.internalCachedSelectStatement(sql)
|
||||
}
|
||||
if let arguments = arguments {
|
||||
try statement.setArgumentsWithValidation(arguments)
|
||||
@@ -179,10 +227,17 @@ public struct SQLRequest : Request {
|
||||
return (statement, adapter)
|
||||
}
|
||||
|
||||
private let sql: String
|
||||
private let arguments: StatementArguments?
|
||||
private let adapter: RowAdapter?
|
||||
private let statementCacheName: Database.StatementCacheName?
|
||||
/// There are two statement caches: one for statements generated by the
|
||||
/// user, and one for the statements generated by GRDB. Those are separated
|
||||
/// so that GRDB has no opportunity to inadvertently modify the arguments of
|
||||
/// user's cached statements.
|
||||
enum Cache {
|
||||
/// The public cache, for library user
|
||||
case `public`
|
||||
|
||||
/// The internal cache, for grdb
|
||||
case `internal`
|
||||
}
|
||||
}
|
||||
|
||||
/// The protocol for requests that know how to decode database rows.
|
||||
@@ -190,11 +245,11 @@ public struct SQLRequest : Request {
|
||||
/// Typed requests can fetch if their associated type RowDecoder is able to
|
||||
/// decode rows (Row, value, record)
|
||||
///
|
||||
/// struct Person: RowConvertible { ... }
|
||||
/// let request: ... // Some TypedRequest that fetches Person
|
||||
/// try request.fetchCursor(db) // DatabaseCursor<Person>
|
||||
/// try request.fetchAll(db) // [Person]
|
||||
/// try request.fetchOne(db) // Person?
|
||||
/// struct Player: RowConvertible { ... }
|
||||
/// let request: ... // Some TypedRequest that fetches Player
|
||||
/// try request.fetchCursor(db) // Cursor of Player
|
||||
/// try request.fetchAll(db) // [Player]
|
||||
/// try request.fetchOne(db) // Player?
|
||||
public protocol TypedRequest : Request {
|
||||
|
||||
/// The type that can convert raw database rows to fetched values
|
||||
@@ -212,32 +267,31 @@ extension TypedRequest {
|
||||
|
||||
/// An adapted typed request.
|
||||
public struct AdaptedTypedRequest<Base: TypedRequest> : TypedRequest {
|
||||
|
||||
/// The type that can convert raw database rows to fetched values
|
||||
public typealias RowDecoder = Base.RowDecoder
|
||||
|
||||
private let base: AdaptedRequest<Base>
|
||||
|
||||
/// Creates an adapted request from a base request and a closure that builds
|
||||
/// a row adapter from a database connection.
|
||||
init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) {
|
||||
adaptedRequest = AdaptedRequest(base, adapter)
|
||||
self.base = AdaptedRequest(base, adapter)
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try adaptedRequest.prepare(db)
|
||||
return try base.prepare(db)
|
||||
}
|
||||
|
||||
/// The number of rows fetched by the request.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try adaptedRequest.fetchCount(db)
|
||||
return try base.fetchCount(db)
|
||||
}
|
||||
|
||||
private let adaptedRequest: AdaptedRequest<Base>
|
||||
/// :nodoc:
|
||||
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try base.fetchedRegion(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// A type-erased TypedRequest.
|
||||
@@ -247,27 +301,39 @@ public struct AdaptedTypedRequest<Base: TypedRequest> : TypedRequest {
|
||||
public struct AnyTypedRequest<T> : TypedRequest {
|
||||
/// The type that can convert raw database rows to fetched values
|
||||
public typealias RowDecoder = T
|
||||
private let base: Request
|
||||
|
||||
/// Support for Request.asRequest(of:)
|
||||
/// Not public because not type-safe.
|
||||
fileprivate init(_ request: Request) {
|
||||
base = request
|
||||
}
|
||||
|
||||
/// Creates a new request that wraps and forwards operations to `request`.
|
||||
public init<Request>(_ request: Request) where Request: TypedRequest, Request.RowDecoder == RowDecoder {
|
||||
self._prepare = { try request.prepare($0) }
|
||||
base = request
|
||||
}
|
||||
|
||||
/// Creates a new request whose `prepare()` method wraps and forwards
|
||||
/// operations the argument closure.
|
||||
public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) {
|
||||
_prepare = prepare
|
||||
base = AnyRequest(prepare)
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try _prepare(db)
|
||||
return try base.prepare(db)
|
||||
}
|
||||
|
||||
private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?)
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try base.fetchCount(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try base.fetchedRegion(db)
|
||||
}
|
||||
}
|
||||
|
||||
extension TypedRequest where RowDecoder: RowConvertible {
|
||||
@@ -276,9 +342,9 @@ extension TypedRequest where RowDecoder: RowConvertible {
|
||||
|
||||
/// A cursor over fetched records.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Person
|
||||
/// let persons = try request.fetchCursor(db) // DatabaseCursor<Person>
|
||||
/// while let person = try persons.next() { // Person
|
||||
/// let request: ... // Some TypedRequest that fetches Player
|
||||
/// let players = try request.fetchCursor(db) // Cursor of Player
|
||||
/// while let player = try players.next() { // Player
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
@@ -290,14 +356,14 @@ extension TypedRequest where RowDecoder: RowConvertible {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder> {
|
||||
public func fetchCursor(_ db: Database) throws -> RecordCursor<RowDecoder> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched records.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Person
|
||||
/// let persons = try request.fetchAll(db) // [Person]
|
||||
/// let request: ... // Some TypedRequest that fetches Player
|
||||
/// let players = try request.fetchAll(db) // [Player]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of records.
|
||||
@@ -308,8 +374,8 @@ extension TypedRequest where RowDecoder: RowConvertible {
|
||||
|
||||
/// The first fetched record.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Person
|
||||
/// let person = try request.fetchOne(db) // Person?
|
||||
/// let request: ... // Some TypedRequest that fetches Player
|
||||
/// let player = try request.fetchOne(db) // Player?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional record.
|
||||
@@ -326,7 +392,7 @@ extension TypedRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// A cursor over fetched values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let strings = try request.fetchCursor(db) // DatabaseCursor<String>
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String
|
||||
/// while let string = try strings.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
@@ -339,7 +405,7 @@ extension TypedRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder> {
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
@@ -378,7 +444,7 @@ extension TypedRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// A cursor over fetched values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let strings = try request.fetchCursor(db) // DatabaseCursor<String>
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String
|
||||
/// while let string = try strings.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
@@ -391,7 +457,7 @@ extension TypedRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder> {
|
||||
public func fetchCursor(_ db: Database) throws -> ColumnCursor<RowDecoder> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
@@ -430,7 +496,7 @@ extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped:
|
||||
/// A cursor over fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchCursor(db) // DatabaseCursor<String?>
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String?
|
||||
/// while let string = try strings.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
@@ -443,7 +509,7 @@ extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped:
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder._Wrapped?> {
|
||||
public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor<RowDecoder._Wrapped> {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
@@ -460,6 +526,43 @@ extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped:
|
||||
}
|
||||
}
|
||||
|
||||
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching Optional values
|
||||
|
||||
/// A cursor over fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String?
|
||||
/// while let string = try strings.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> NullableColumnCursor<RowDecoder._Wrapped> {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchAll(db) // [String?]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchAll(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
extension TypedRequest where RowDecoder: Row {
|
||||
|
||||
// MARK: Fetching Rows
|
||||
@@ -467,10 +570,10 @@ extension TypedRequest where RowDecoder: Row {
|
||||
/// A cursor over fetched rows.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Row
|
||||
/// let rows = try request.fetchCursor(db) // DatabaseCursor<Row>
|
||||
/// let rows = try request.fetchCursor(db) // RowCursor
|
||||
/// while let row = try rows.next() { // Row
|
||||
/// let id: Int64 = row.value(atIndex: 0)
|
||||
/// let name: String = row.value(atIndex: 1)
|
||||
/// let id: Int64 = row[0]
|
||||
/// let name: String = row[1]
|
||||
/// }
|
||||
///
|
||||
/// Fetched rows are reused during the cursor iteration: don't turn a row
|
||||
@@ -489,7 +592,7 @@ extension TypedRequest where RowDecoder: Row {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<Row> {
|
||||
public func fetchCursor(_ db: Database) throws -> RowCursor {
|
||||
return try Row.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
|
||||
+267
-135
@@ -1,12 +1,30 @@
|
||||
import Foundation
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// A database row.
|
||||
public final class Row {
|
||||
public final class Row : Equatable, Hashable, RandomAccessCollection, ExpressibleByDictionaryLiteral, CustomStringConvertible {
|
||||
let impl: RowImpl
|
||||
|
||||
/// Unless we are producing a row array, we use a single row when iterating
|
||||
/// a statement:
|
||||
///
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT ...")
|
||||
/// let players = try Player.fetchAll(db, "SELECT ...")
|
||||
///
|
||||
/// This row keeps an unmanaged reference to the statement, and a handle to
|
||||
/// the sqlite statement, so that we avoid many retain/release invocations.
|
||||
///
|
||||
/// The statementRef is released in deinit.
|
||||
let statementRef: Unmanaged<SelectStatement>?
|
||||
let sqliteStatement: SQLiteStatement?
|
||||
|
||||
/// The number of columns in the row.
|
||||
public let count: Int
|
||||
|
||||
// MARK: - Building rows
|
||||
|
||||
/// Creates an empty row.
|
||||
@@ -48,26 +66,11 @@ public final class Row {
|
||||
|
||||
// MARK: - Not Public
|
||||
|
||||
let impl: RowImpl
|
||||
|
||||
/// Returns true if and only if the row was fetched from a database.
|
||||
var isFetched: Bool {
|
||||
return impl.isFetched
|
||||
}
|
||||
|
||||
/// Unless we are producing a row array, we use a single row when iterating
|
||||
/// a statement:
|
||||
///
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT ...")
|
||||
/// let persons = try Person.fetchAll(db, "SELECT ...")
|
||||
///
|
||||
/// This row keeps an unmanaged reference to the statement, and a handle to
|
||||
/// the sqlite statement, so that we avoid many retain/release invocations.
|
||||
///
|
||||
/// The statementRef is released in deinit.
|
||||
let statementRef: Unmanaged<SelectStatement>?
|
||||
let sqliteStatement: SQLiteStatement?
|
||||
|
||||
deinit {
|
||||
statementRef?.release()
|
||||
}
|
||||
@@ -83,6 +86,7 @@ public final class Row {
|
||||
self.statementRef = statementRef
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
self.impl = StatementRowImpl(sqliteStatement: statement.sqliteStatement, statementRef: statementRef)
|
||||
self.count = Int(sqlite3_column_count(sqliteStatement))
|
||||
}
|
||||
|
||||
/// Creates a row that contain a copy of the current state of the
|
||||
@@ -95,17 +99,9 @@ public final class Row {
|
||||
self.init(impl: StatementCopyRowImpl(sqliteStatement: sqliteStatement, columnNames: statementRef.takeUnretainedValue().columnNames))
|
||||
}
|
||||
|
||||
/// Creates a row from the *current state* of the SQLite statement.
|
||||
///
|
||||
/// The row is implemented on top of StatementCopyRowImpl, which *copies*
|
||||
/// the values from the SQLite statement so that further iteration of the
|
||||
/// statement does not modify the row.
|
||||
convenience init(copiedFromSQLiteStatement sqliteStatement: SQLiteStatement, columnNames: [String]) {
|
||||
self.init(impl: StatementCopyRowImpl(sqliteStatement: sqliteStatement, columnNames: columnNames))
|
||||
}
|
||||
|
||||
init(impl: RowImpl) {
|
||||
self.impl = impl
|
||||
self.count = impl.count
|
||||
self.statementRef = nil
|
||||
self.sqliteStatement = nil
|
||||
}
|
||||
@@ -135,12 +131,48 @@ extension Row {
|
||||
|
||||
// MARK: - Extracting Values
|
||||
|
||||
/// Returns true if and only if one column contains a non-null value, or if
|
||||
/// the row was fetched with a row adapter that defines a scoped row that
|
||||
/// contains a non-null value.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, "SELECT 'foo', 1")!
|
||||
/// row.containsNonNullValue // true
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, "SELECT NULL, NULL")!
|
||||
/// row.containsNonNullValue // false
|
||||
public var containsNonNullValue: Bool {
|
||||
for i in (0..<count) {
|
||||
if !hasNull(atIndex: i) { return true }
|
||||
}
|
||||
|
||||
for name in scopeNames where scoped(on: name)!.containsNonNullValue {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
/// Returns true if the row contains null at given index.
|
||||
///
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
/// righmost column.
|
||||
///
|
||||
/// This method is equivalent to `row[index] == nil`, but may be preferred
|
||||
/// in performance-critical code because it can avoid decoding database
|
||||
/// values.
|
||||
public func hasNull(atIndex index: Int) -> Bool {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
|
||||
return impl.hasNull(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns Int64, Double, String, Data or nil, depending on the value
|
||||
/// stored at the given index.
|
||||
///
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
/// righmost column.
|
||||
public func value(atIndex index: Int) -> DatabaseValueConvertible? {
|
||||
public subscript(_ index: Int) -> DatabaseValueConvertible? {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
|
||||
return impl.databaseValue(atUncheckedIndex: index).storage.value
|
||||
}
|
||||
@@ -153,9 +185,9 @@ extension Row {
|
||||
/// If the SQLite value is NULL, the result is nil. Otherwise the SQLite
|
||||
/// value is converted to the requested type `Value`. Should this conversion
|
||||
/// fail, a fatal error is raised.
|
||||
public func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value? {
|
||||
public subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value? {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
return impl.value(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
@@ -170,12 +202,12 @@ extension Row {
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
public func value<Value: DatabaseValueConvertible & StatementColumnConvertible>(atIndex index: Int) -> Value? {
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value? {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
|
||||
guard let sqliteStatement = sqliteStatement else {
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
if let sqliteStatement = sqliteStatement { // fast path
|
||||
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
}
|
||||
return Row.statementColumnConvertible(atUncheckedIndex: index, in: sqliteStatement)
|
||||
return impl.fastValue(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
@@ -185,9 +217,9 @@ extension Row {
|
||||
///
|
||||
/// This method crashes if the fetched SQLite value is NULL, or if the
|
||||
/// SQLite value can not be converted to `Value`.
|
||||
public func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value {
|
||||
public subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
return impl.value(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
@@ -201,12 +233,12 @@ extension Row {
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
public func value<Value: DatabaseValueConvertible & StatementColumnConvertible>(atIndex index: Int) -> Value {
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
|
||||
guard let sqliteStatement = sqliteStatement else {
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
if let sqliteStatement = sqliteStatement { // fast path
|
||||
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
}
|
||||
return Row.statementColumnConvertible(atUncheckedIndex: index, in: sqliteStatement)
|
||||
return impl.fastValue(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns Int64, Double, String, Data or nil, depending on the value
|
||||
@@ -216,12 +248,12 @@ extension Row {
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// The result is nil if the row does not contain the column.
|
||||
public func value(named columnName: String) -> DatabaseValueConvertible? {
|
||||
public subscript(_ columnName: String) -> DatabaseValueConvertible? {
|
||||
// IMPLEMENTATION NOTE
|
||||
// This method has a single know use case: checking if the value is nil,
|
||||
// as in:
|
||||
//
|
||||
// if row.value(named: "foo") != nil { ... }
|
||||
// if row["foo"] != nil { ... }
|
||||
//
|
||||
// Without this method, the code above would not compile.
|
||||
guard let index = impl.index(ofColumn: columnName) else {
|
||||
@@ -238,11 +270,11 @@ extension Row {
|
||||
/// If the column is missing or if the SQLite value is NULL, the result is
|
||||
/// nil. Otherwise the SQLite value is converted to the requested type
|
||||
/// `Value`. Should this conversion fail, a fatal error is raised.
|
||||
public func value<Value: DatabaseValueConvertible>(named columnName: String) -> Value? {
|
||||
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value? {
|
||||
guard let index = impl.index(ofColumn: columnName) else {
|
||||
return nil
|
||||
}
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
return impl.value(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -257,14 +289,14 @@ extension Row {
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
public func value<Value: DatabaseValueConvertible & StatementColumnConvertible>(named columnName: String) -> Value? {
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value? {
|
||||
guard let index = impl.index(ofColumn: columnName) else {
|
||||
return nil
|
||||
}
|
||||
guard let sqliteStatement = sqliteStatement else {
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
if let sqliteStatement = sqliteStatement { // fast path
|
||||
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
}
|
||||
return Row.statementColumnConvertible(atUncheckedIndex: index, in: sqliteStatement)
|
||||
return impl.fastValue(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -276,12 +308,12 @@ extension Row {
|
||||
///
|
||||
/// This method crashes if the fetched SQLite value is NULL, or if the
|
||||
/// SQLite value can not be converted to `Value`.
|
||||
public func value<Value: DatabaseValueConvertible>(named columnName: String) -> Value {
|
||||
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value {
|
||||
guard let index = impl.index(ofColumn: columnName) else {
|
||||
// Programmer error
|
||||
fatalError("no such column: \(columnName)")
|
||||
}
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
return impl.value(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -297,15 +329,15 @@ extension Row {
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
public func value<Value: DatabaseValueConvertible & StatementColumnConvertible>(named columnName: String) -> Value {
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value {
|
||||
guard let index = impl.index(ofColumn: columnName) else {
|
||||
// Programmer error
|
||||
fatalError("no such column: \(columnName)")
|
||||
}
|
||||
guard let sqliteStatement = sqliteStatement else {
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
if let sqliteStatement = sqliteStatement { // fast path
|
||||
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
}
|
||||
return Row.statementColumnConvertible(atUncheckedIndex: index, in: sqliteStatement)
|
||||
return impl.fastValue(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns Int64, Double, String, NSData or nil, depending on the value
|
||||
@@ -315,8 +347,8 @@ extension Row {
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// The result is nil if the row does not contain the column.
|
||||
public func value(_ column: Column) -> DatabaseValueConvertible? {
|
||||
return value(named: column.name)
|
||||
public subscript(_ column: Column) -> DatabaseValueConvertible? {
|
||||
return self[column.name]
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -327,8 +359,8 @@ extension Row {
|
||||
/// If the column is missing or if the SQLite value is NULL, the result is
|
||||
/// nil. Otherwise the SQLite value is converted to the requested type
|
||||
/// `Value`. Should this conversion fail, a fatal error is raised.
|
||||
public func value<Value: DatabaseValueConvertible>(_ column: Column) -> Value? {
|
||||
return value(named: column.name)
|
||||
public subscript<Value: DatabaseValueConvertible>(_ column: Column) -> Value? {
|
||||
return self[column.name]
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -343,8 +375,8 @@ extension Row {
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
public func value<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ column: Column) -> Value? {
|
||||
return value(named: column.name)
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ column: Column) -> Value? {
|
||||
return self[column.name]
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -356,8 +388,8 @@ extension Row {
|
||||
///
|
||||
/// This method crashes if the fetched SQLite value is NULL, or if the
|
||||
/// SQLite value can not be converted to `Value`.
|
||||
public func value<Value: DatabaseValueConvertible>(_ column: Column) -> Value {
|
||||
return value(named: column.name)
|
||||
public subscript<Value: DatabaseValueConvertible>(_ column: Column) -> Value {
|
||||
return self[column.name]
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -373,8 +405,8 @@ extension Row {
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
public func value<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ column: Column) -> Value {
|
||||
return value(named: column.name)
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ column: Column) -> Value {
|
||||
return self[column.name]
|
||||
}
|
||||
|
||||
/// Returns the optional Data at given index.
|
||||
@@ -441,21 +473,36 @@ extension Row {
|
||||
|
||||
extension Row {
|
||||
|
||||
// MARK: - Helpers
|
||||
// MARK: - Extracting Records
|
||||
|
||||
fileprivate static func statementColumnConvertible<Value: StatementColumnConvertible>(atUncheckedIndex index: Int, in sqliteStatement: SQLiteStatement) -> Value? {
|
||||
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
|
||||
/// Returns the record encoded in the given scope.
|
||||
///
|
||||
/// A fatal error is raised in the row was not fetched with a row adapter
|
||||
/// that defines this scope.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support
|
||||
/// for more information.
|
||||
public subscript<Record: RowConvertible>(_ scope: String) -> Record {
|
||||
guard let scopedRow = scoped(on: scope) else {
|
||||
// Programmer error
|
||||
fatalError("no such scope: \(scope)")
|
||||
}
|
||||
return Record(row: scopedRow)
|
||||
}
|
||||
|
||||
/// Returns the record encoded in the given scope, if and only if the scope
|
||||
/// has been defined by a row adapter, and the scoped row contains a
|
||||
/// non-null value. Otherwise, return nil.
|
||||
///
|
||||
/// This subscript is designed to handle left joined records.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support
|
||||
/// for more information.
|
||||
public subscript<Record: RowConvertible>(_ scope: String) -> Record? {
|
||||
guard let scopedRow = scoped(on: scope), scopedRow.containsNonNullValue else {
|
||||
return nil
|
||||
}
|
||||
return Value.init(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
}
|
||||
|
||||
fileprivate static func statementColumnConvertible<Value: StatementColumnConvertible>(atUncheckedIndex index: Int, in sqliteStatement: SQLiteStatement) -> Value {
|
||||
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
|
||||
// Programmer error
|
||||
fatalError("could not convert database value NULL to \(Value.self)")
|
||||
}
|
||||
return Value.init(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
return Record(row: scopedRow)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -463,8 +510,12 @@ extension Row {
|
||||
|
||||
// MARK: - Scopes
|
||||
|
||||
/// Returns a scoped row, if the row was fetched along with a row adapter
|
||||
/// that defines this scope.
|
||||
var scopeNames: Set<String> {
|
||||
return impl.scopeNames
|
||||
}
|
||||
|
||||
/// Returns a scoped row, if the row was fetched with a row adapter that
|
||||
/// defines this scope.
|
||||
///
|
||||
/// // Two adapters
|
||||
/// let fooAdapter = ColumnMapping(["value": "foo"])
|
||||
@@ -481,14 +532,54 @@ extension Row {
|
||||
///
|
||||
/// // Scoped rows:
|
||||
/// if let fooRow = row.scoped(on: "foo") {
|
||||
/// fooRow.value(named: "value") // "foo"
|
||||
/// fooRow["value"] // "foo"
|
||||
/// }
|
||||
/// if let barRow = row.scopeed(on: "bar") {
|
||||
/// barRow.value(named: "value") // "bar"
|
||||
/// barRow["value"] // "bar"
|
||||
/// }
|
||||
public func scoped(on name: String) -> Row? {
|
||||
return impl.scoped(on: name)
|
||||
}
|
||||
|
||||
/// Returns a copy of the row, without any scoped row (if the row was fetched
|
||||
/// with a row adapter that defines scopes).
|
||||
public var unscoped: Row {
|
||||
return Row(impl: ArrayRowImpl(columns: map { ($0, $1) }))
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor of database rows. For example:
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let rows: RowCursor = try Row.fetchCursor(db, "SELECT * FROM players")
|
||||
/// }
|
||||
public final class RowCursor : Cursor {
|
||||
public let statement: SelectStatement
|
||||
private let sqliteStatement: SQLiteStatement
|
||||
private let row: Row // Reused for performance
|
||||
private var done = false
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
self.row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func next() throws -> Row? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return row
|
||||
case let code:
|
||||
statement.database.selectStatementDidFail(statement)
|
||||
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Row {
|
||||
@@ -498,10 +589,10 @@ extension Row {
|
||||
/// Returns a cursor over rows fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT ...")
|
||||
/// let rows = try Row.fetchCursor(statement) // DatabaseCursor<Row>
|
||||
/// let rows = try Row.fetchCursor(statement) // RowCursor
|
||||
/// while let row = try rows.next() { // Row
|
||||
/// let id: Int64 = row.value(atIndex: 0)
|
||||
/// let name: String = row.value(atIndex: 1)
|
||||
/// let id: Int64 = row[0]
|
||||
/// let name: String = row[1]
|
||||
/// }
|
||||
///
|
||||
/// Fetched rows are reused during the cursor iteration: don't turn a row
|
||||
@@ -524,10 +615,8 @@ extension Row {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Row> {
|
||||
// Reuse a single mutable row for performance
|
||||
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
return statement.cursor(arguments: arguments, next: { row })
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor {
|
||||
return try RowCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of rows fetched from a prepared statement.
|
||||
@@ -571,11 +660,11 @@ extension Row {
|
||||
///
|
||||
/// let idColumn = Column("id")
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(idColumn, nameColumn)
|
||||
/// let rows = try Row.fetchCursor(db) // DatabaseCursor<Row>
|
||||
/// let request = Player.select(idColumn, nameColumn)
|
||||
/// let rows = try Row.fetchCursor(db) // RowCursor
|
||||
/// while let row = try rows.next() { // Row
|
||||
/// let id: Int64 = row.value(atIndex: 0)
|
||||
/// let name: String = row.value(atIndex: 1)
|
||||
/// let id: Int64 = row[0]
|
||||
/// let name: String = row[1]
|
||||
/// }
|
||||
///
|
||||
/// Fetched rows are reused during the cursor iteration: don't turn a row
|
||||
@@ -596,7 +685,7 @@ extension Row {
|
||||
/// - request: A fetch request.
|
||||
/// - returns: A cursor over fetched rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseCursor<Row> {
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> RowCursor {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
@@ -605,7 +694,7 @@ extension Row {
|
||||
///
|
||||
/// let idColumn = Column("id")
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(idColumn, nameColumn)
|
||||
/// let request = Player.select(idColumn, nameColumn)
|
||||
/// let rows = try Row.fetchAll(db, request)
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -619,7 +708,7 @@ extension Row {
|
||||
///
|
||||
/// let idColumn = Column("id")
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(idColumn, nameColumn)
|
||||
/// let request = Player.select(idColumn, nameColumn)
|
||||
/// let row = try Row.fetchOne(db, request)
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -636,10 +725,10 @@ extension Row {
|
||||
|
||||
/// Returns a cursor over rows fetched from an SQL query.
|
||||
///
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT id, name FROM persons") // DatabaseCursor<Row>
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT id, name FROM players") // RowCursor
|
||||
/// while let row = try rows.next() { // Row
|
||||
/// let id: Int64 = row.value(atIndex: 0)
|
||||
/// let name: String = row.value(atIndex: 1)
|
||||
/// let id: Int64 = row[0]
|
||||
/// let name: String = row[1]
|
||||
/// }
|
||||
///
|
||||
/// Fetched rows are reused during the cursor iteration: don't turn a row
|
||||
@@ -662,7 +751,7 @@ extension Row {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Row> {
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor {
|
||||
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
@@ -697,7 +786,8 @@ extension Row {
|
||||
}
|
||||
}
|
||||
|
||||
extension Row : ExpressibleByDictionaryLiteral {
|
||||
// ExpressibleByDictionaryLiteral
|
||||
extension Row {
|
||||
|
||||
/// Creates a row initialized with elements. Column order is preserved, and
|
||||
/// duplicated columns names are allowed.
|
||||
@@ -710,22 +800,20 @@ extension Row : ExpressibleByDictionaryLiteral {
|
||||
}
|
||||
}
|
||||
|
||||
extension Row : Collection {
|
||||
// RandomAccessCollection
|
||||
extension Row {
|
||||
|
||||
// MARK: - Row as a Collection of (ColumnName, DatabaseValue) Pairs
|
||||
|
||||
/// The number of columns in the row.
|
||||
public var count: Int {
|
||||
return impl.count
|
||||
}
|
||||
|
||||
/// The index of the first (ColumnName, DatabaseValue) pair.
|
||||
/// :nodoc:
|
||||
public var startIndex: RowIndex {
|
||||
return Index(0)
|
||||
}
|
||||
|
||||
/// The "past-the-end" index, successor of the index of the last
|
||||
/// (ColumnName, DatabaseValue) pair.
|
||||
/// :nodoc:
|
||||
public var endIndex: RowIndex {
|
||||
return Index(count)
|
||||
}
|
||||
@@ -738,25 +826,14 @@ extension Row : Collection {
|
||||
impl.columnName(atUncheckedIndex: index),
|
||||
impl.databaseValue(atUncheckedIndex: index))
|
||||
}
|
||||
|
||||
/// Returns the position immediately after `i`.
|
||||
///
|
||||
/// - Precondition: `(startIndex..<endIndex).contains(i)`
|
||||
public func index(after i: RowIndex) -> RowIndex {
|
||||
return RowIndex(i.index + 1)
|
||||
}
|
||||
|
||||
/// Replaces `i` with its successor.
|
||||
public func formIndex(after i: inout RowIndex) {
|
||||
i = RowIndex(i.index + 1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Row adopts Equatable.
|
||||
extension Row : Equatable {
|
||||
// Equatable
|
||||
extension Row {
|
||||
|
||||
/// Returns true if and only if both rows have the same columns and values,
|
||||
/// in the same order. Columns are compared in a case-sensitive way.
|
||||
/// :nodoc:
|
||||
public static func == (lhs: Row, rhs: Row) -> Bool {
|
||||
if lhs === rhs {
|
||||
return true
|
||||
@@ -766,10 +843,7 @@ extension Row : Equatable {
|
||||
return false
|
||||
}
|
||||
|
||||
var liter = lhs.makeIterator()
|
||||
var riter = rhs.makeIterator()
|
||||
|
||||
while let (lcol, lval) = liter.next(), let (rcol, rval) = riter.next() {
|
||||
for ((lcol, lval), (rcol, rval)) in zip(lhs, rhs) {
|
||||
guard lcol == rcol else {
|
||||
return false
|
||||
}
|
||||
@@ -796,18 +870,19 @@ extension Row : Equatable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Row adopts Hashable.
|
||||
extension Row : Hashable {
|
||||
// Hashable
|
||||
extension Row {
|
||||
/// The hash value
|
||||
/// :nodoc:
|
||||
public var hashValue: Int {
|
||||
return columnNames.reduce(0) { (acc, column) in acc ^ column.hashValue } ^
|
||||
databaseValues.reduce(0) { (acc, dbValue) in acc ^ dbValue.hashValue }
|
||||
}
|
||||
}
|
||||
|
||||
/// Row adopts CustomStringConvertible.
|
||||
extension Row: CustomStringConvertible {
|
||||
/// A textual representation of `self`.
|
||||
// CustomStringConvertible
|
||||
extension Row {
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
return "<Row"
|
||||
+ map { (column, dbValue) in
|
||||
@@ -820,22 +895,38 @@ extension Row: CustomStringConvertible {
|
||||
|
||||
// MARK: - RowIndex
|
||||
|
||||
/// Indexes to (columnName, dbValue) pairs in a database row.
|
||||
public struct RowIndex : Comparable {
|
||||
/// Indexes to (ColumnName, DatabaseValue) pairs in a database row.
|
||||
public struct RowIndex : Comparable, Strideable {
|
||||
let index: Int
|
||||
init(_ index: Int) { self.index = index }
|
||||
|
||||
/// Equality operator
|
||||
}
|
||||
|
||||
// Comparable
|
||||
extension RowIndex {
|
||||
/// :nodoc:
|
||||
public static func == (lhs: RowIndex, rhs: RowIndex) -> Bool {
|
||||
return lhs.index == rhs.index
|
||||
}
|
||||
|
||||
// Comparison operator
|
||||
/// :nodoc:
|
||||
public static func < (lhs: RowIndex, rhs: RowIndex) -> Bool {
|
||||
return lhs.index < rhs.index
|
||||
}
|
||||
}
|
||||
|
||||
// Strideable: support for Row: RandomAccessCollection
|
||||
extension RowIndex {
|
||||
/// :nodoc:
|
||||
public func distance(to other: RowIndex) -> Int {
|
||||
return other.index - index
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func advanced(by n: Int) -> RowIndex {
|
||||
return RowIndex(index + n)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - RowImpl
|
||||
|
||||
@@ -844,6 +935,9 @@ protocol RowImpl {
|
||||
var count: Int { get }
|
||||
var isFetched: Bool { get }
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue
|
||||
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value
|
||||
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value?
|
||||
func hasNull(atUncheckedIndex index:Int) -> Bool
|
||||
func dataNoCopy(atUncheckedIndex index:Int) -> Data?
|
||||
func columnName(atUncheckedIndex index: Int) -> String
|
||||
|
||||
@@ -858,6 +952,27 @@ protocol RowImpl {
|
||||
func copy(_ row: Row) -> Row
|
||||
}
|
||||
|
||||
extension RowImpl {
|
||||
func hasNull(atUncheckedIndex index:Int) -> Bool {
|
||||
return databaseValue(atUncheckedIndex: index).isNull
|
||||
}
|
||||
|
||||
func value<Value: DatabaseValueConvertible>(atUncheckedIndex index: Int) -> Value {
|
||||
return databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
|
||||
func value<Value: DatabaseValueConvertible>(atUncheckedIndex index: Int) -> Value? {
|
||||
return databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
|
||||
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value {
|
||||
return databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
|
||||
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value? {
|
||||
return databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
}
|
||||
|
||||
/// See Row.init(dictionary:)
|
||||
private struct ArrayRowImpl : RowImpl {
|
||||
@@ -969,9 +1084,13 @@ private struct StatementRowImpl : RowImpl {
|
||||
init(sqliteStatement: SQLiteStatement, statementRef: Unmanaged<SelectStatement>) {
|
||||
self.statementRef = statementRef
|
||||
self.sqliteStatement = sqliteStatement
|
||||
// Optimize row.value(named: "...")
|
||||
// Optimize row["..."]
|
||||
let lowercaseColumnNames = (0..<sqlite3_column_count(sqliteStatement)).map { String(cString: sqlite3_column_name(sqliteStatement, Int32($0))).lowercased() }
|
||||
self.lowercaseColumnIndexes = Dictionary(keyValueSequence: lowercaseColumnNames.enumerated().map { ($1, $0) }.reversed())
|
||||
self.lowercaseColumnIndexes = Dictionary(
|
||||
lowercaseColumnNames
|
||||
.enumerated()
|
||||
.map { ($0.element, $0.offset) },
|
||||
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
|
||||
}
|
||||
|
||||
var count: Int {
|
||||
@@ -982,12 +1101,17 @@ private struct StatementRowImpl : RowImpl {
|
||||
return true
|
||||
}
|
||||
|
||||
func hasNull(atUncheckedIndex index:Int) -> Bool {
|
||||
// Avoid extracting values, because this modifies the statement.
|
||||
return sqlite3_column_type(sqliteStatement, Int32(index)) == SQLITE_NULL
|
||||
}
|
||||
|
||||
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
|
||||
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
|
||||
return nil
|
||||
}
|
||||
guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else {
|
||||
return nil
|
||||
return Data()
|
||||
}
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
|
||||
@@ -997,6 +1121,14 @@ private struct StatementRowImpl : RowImpl {
|
||||
return DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
}
|
||||
|
||||
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value {
|
||||
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
}
|
||||
|
||||
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value? {
|
||||
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
}
|
||||
|
||||
func columnName(atUncheckedIndex index: Int) -> String {
|
||||
return statementRef.takeUnretainedValue().columnNames[index]
|
||||
}
|
||||
|
||||
+136
-18
@@ -1,8 +1,50 @@
|
||||
import Foundation
|
||||
|
||||
/// Returns an array of row adapters that split a row according to the input
|
||||
/// number of columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let sql = "SELECT 1, 2,3,4, 5,6, 7,8"
|
||||
/// // <.><. . .><. .><. .>
|
||||
/// let adapters = splittingRowAdapters([1, 3, 2])
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "a": adapters[0],
|
||||
/// "b": adapters[1],
|
||||
/// "c": adapters[2],
|
||||
/// "d": adapters[3]])
|
||||
/// let row = try Row.fetchOne(db, sql, adapter: adapter)
|
||||
/// row.scoped(on: "a") // [1]
|
||||
/// row.scoped(on: "b") // [2, 3, 4]
|
||||
/// row.scoped(on: "c") // [5, 6]
|
||||
/// row.scoped(on: "d") // [7, 8]
|
||||
public func splittingRowAdapters(columnCounts: [Int]) -> [RowAdapter] {
|
||||
guard !columnCounts.isEmpty else {
|
||||
// Identity adapter
|
||||
return [SuffixRowAdapter(fromIndex: 0)]
|
||||
}
|
||||
|
||||
// [1, 3, 2] -> [0, 1, 4, 6]
|
||||
let columnIndexes = columnCounts.reduce(into: [0]) { (acc, count) in
|
||||
acc.append(acc.last! + count)
|
||||
}
|
||||
|
||||
// [0, 1, 4, 6] -> [(0..<1), (1..<4), (4..<6)]
|
||||
let rangeAdapters = zip(columnIndexes, columnIndexes.suffix(from: 1))
|
||||
.map { RangeRowAdapter($0..<$1) }
|
||||
|
||||
// (6...)
|
||||
let suffixAdapter = SuffixRowAdapter(fromIndex: columnIndexes.last!)
|
||||
|
||||
// [(0..<1), (1..<4), (4..<6), (6...)]
|
||||
return rangeAdapters + [suffixAdapter]
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// LayoutedColumnMapping is a type that supports the RowAdapter protocol.
|
||||
///
|
||||
/// :nodoc:
|
||||
public struct LayoutedColumnMapping {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -39,10 +81,11 @@ public struct LayoutedColumnMapping {
|
||||
/// try Row.fetchOne(db, "SELECT NULL, 'foo', 'bar'", adapter: FooBarAdapter())
|
||||
public init<S: Sequence>(layoutColumns: S) where S.Iterator.Element == (Int, String) {
|
||||
self.layoutColumns = Array(layoutColumns)
|
||||
self.lowercaseColumnIndexes = Dictionary(keyValueSequence: layoutColumns
|
||||
.enumerated()
|
||||
.map { ($1.1.lowercased(), $0) }
|
||||
.reversed()) // reversed() so that the the dictionary caches leftmost indexes
|
||||
self.lowercaseColumnIndexes = Dictionary(
|
||||
layoutColumns
|
||||
.enumerated()
|
||||
.map { ($0.element.1.lowercased(), $0.offset) },
|
||||
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
|
||||
}
|
||||
|
||||
func baseColumnIndex(atMappingIndex index: Int) -> Int {
|
||||
@@ -55,6 +98,8 @@ public struct LayoutedColumnMapping {
|
||||
}
|
||||
|
||||
/// LayoutedColumnMapping adopts LayoutedRowAdapter
|
||||
///
|
||||
/// :nodoc:
|
||||
extension LayoutedColumnMapping : LayoutedRowAdapter {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -71,6 +116,7 @@ extension LayoutedColumnMapping : LayoutedRowAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
extension LayoutedColumnMapping : RowLayout {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -90,6 +136,8 @@ extension LayoutedColumnMapping : RowLayout {
|
||||
///
|
||||
/// GRBD ships with a ready-made type that adopts this protocol:
|
||||
/// LayoutedColumnMapping.
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol LayoutedRowAdapter {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -107,6 +155,8 @@ public protocol LayoutedRowAdapter {
|
||||
///
|
||||
/// RowLayout is a protocol that supports the RowAdapter protocol. It describes
|
||||
/// a layout of a base row.
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol RowLayout {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -123,11 +173,15 @@ public protocol RowLayout {
|
||||
|
||||
extension SelectStatement : RowLayout {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public var layoutColumns: [(Int, String)] {
|
||||
return Array(columnNames.enumerated())
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func layoutIndex(ofColumn name: String) -> Int? {
|
||||
return index(ofColumn: name)
|
||||
}
|
||||
@@ -185,7 +239,7 @@ extension RowAdapter {
|
||||
/// - parameter scopes: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
public func addingScopes(_ scopes: [String: RowAdapter]) -> RowAdapter {
|
||||
return ScopeAdapter(mainAdapter: self, scopes: scopes)
|
||||
return ScopeAdapter(base: self, scopes: scopes)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,6 +249,19 @@ extension RowAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/// EmptyRowAdapter is a row adapter that hides all columns.
|
||||
public struct EmptyRowAdapter: RowAdapter {
|
||||
/// Creates an EmptyRowAdapter
|
||||
public init() { }
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
return LayoutedColumnMapping(layoutColumns: [])
|
||||
}
|
||||
}
|
||||
|
||||
/// ColumnMapping is a row adapter that maps column names.
|
||||
///
|
||||
/// let adapter = ColumnMapping(["foo": "bar"])
|
||||
@@ -213,6 +280,8 @@ public struct ColumnMapping : RowAdapter {
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
let layoutColumns = try mapping
|
||||
.map { (mappedColumn, baseColumn) -> (Int, String) in
|
||||
@@ -249,6 +318,8 @@ public struct SuffixRowAdapter : RowAdapter {
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
return LayoutedColumnMapping(layoutColumns: layout.layoutColumns.suffix(from: index))
|
||||
}
|
||||
@@ -278,6 +349,8 @@ public struct RangeRowAdapter : RowAdapter {
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
return LayoutedColumnMapping(layoutColumns: layout.layoutColumns[range])
|
||||
}
|
||||
@@ -300,36 +373,64 @@ public struct RangeRowAdapter : RowAdapter {
|
||||
///
|
||||
/// // Scoped rows:
|
||||
/// if let fooRow = row.scoped(on: "foo") {
|
||||
/// fooRow.value(named: "value") // "foo"
|
||||
/// fooRow["value"] // "foo"
|
||||
/// }
|
||||
/// if let barRow = row.scopeed(on: "bar") {
|
||||
/// barRow.value(named: "value") // "bar"
|
||||
/// barRow["value"] // "bar"
|
||||
/// }
|
||||
public struct ScopeAdapter : RowAdapter {
|
||||
|
||||
/// The main adapter
|
||||
let mainAdapter: RowAdapter
|
||||
/// The base adapter
|
||||
let base: RowAdapter
|
||||
|
||||
/// The scope adapters
|
||||
let scopes: [String: RowAdapter]
|
||||
|
||||
/// Creates a scoped adapter.
|
||||
/// Creates an adapter that preserves row contents and add scoped rows.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let adapter = ScopeAdapter(["suffix": SuffixRowAdapter(fromIndex: 1)])
|
||||
/// let row = try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: adapter)!
|
||||
/// row // [1, 2, 3]
|
||||
/// row.scoped(on: "suffix") // [2, 3]
|
||||
///
|
||||
/// - parameter scopes: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
public init(_ scopes: [String: RowAdapter]) {
|
||||
self.mainAdapter = SuffixRowAdapter(fromIndex: 0) // Use SuffixRowAdapter(fromIndex: 0) as the identity adapter
|
||||
self.scopes = scopes
|
||||
// Use SuffixRowAdapter(fromIndex: 0) as the identity adapter
|
||||
self.init(base: SuffixRowAdapter(fromIndex: 0), scopes: scopes)
|
||||
}
|
||||
|
||||
init(mainAdapter: RowAdapter, scopes: [String: RowAdapter]) {
|
||||
self.mainAdapter = mainAdapter
|
||||
/// Creates an adapter based on the base adapter, and add scoped rows.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let baseAdapter = RangeRowAdapter(0..<1)
|
||||
/// let adapter = ScopeAdapter(base: baseAdapter, scopes: ["suffix": SuffixRowAdapter(fromIndex: 1)])
|
||||
/// let row = try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: adapter)!
|
||||
/// row // [1]
|
||||
/// row.scoped(on: "initial") // [2, 3]
|
||||
///
|
||||
/// If the base adapter already defines scopes, the given scopes replace
|
||||
/// eventual existing scopes with the same name.
|
||||
///
|
||||
/// This initializer is equivalent to `baseAdapter.addingScopes(scopes)`.
|
||||
///
|
||||
/// - parameter base: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
/// - parameter scopes: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
public init(base: RowAdapter, scopes: [String: RowAdapter]) {
|
||||
self.base = base
|
||||
self.scopes = scopes
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
let layoutedAdapter = try mainAdapter.layoutedAdapter(from: layout)
|
||||
let layoutedAdapter = try base.layoutedAdapter(from: layout)
|
||||
var layoutedScopes = layoutedAdapter.scopes
|
||||
for (name, adapter) in scopes {
|
||||
try layoutedScopes[name] = adapter.layoutedAdapter(from: layout)
|
||||
@@ -389,12 +490,29 @@ struct AdapterRowImpl : RowImpl {
|
||||
return base.isFetched
|
||||
}
|
||||
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
|
||||
return base.value(atIndex: mapping.baseColumnIndex(atMappingIndex: index))
|
||||
func hasNull(atUncheckedIndex index: Int) -> Bool {
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return base.impl.hasNull(atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return base.impl.databaseValue(atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value {
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return base.impl.fastValue(atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value? {
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return base.impl.fastValue(atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
|
||||
return base.dataNoCopy(atIndex: mapping.baseColumnIndex(atMappingIndex: index))
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return base.impl.dataNoCopy(atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func columnName(atUncheckedIndex index: Int) -> String {
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
import Dispatch
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#endif
|
||||
|
||||
/// SchedulingWatchdog makes sure that databases connections are used on correct
|
||||
/// dispatch queues, and warns the user with a fatal error whenever she misuses
|
||||
/// a database connection.
|
||||
@@ -20,14 +16,15 @@ import Dispatch
|
||||
/// of the dispatch queue, a SchedulingWatchdog that allows that database only.
|
||||
///
|
||||
/// Later on, the queue can be shared by several databases with the method
|
||||
/// allowing(databases:execute:). See SerializedDatabase.sync() for
|
||||
/// an example.
|
||||
/// inheritingAllowedDatabases(from:execute:). See SerializedDatabase.sync()
|
||||
/// for an example.
|
||||
///
|
||||
/// - preconditionValidQueue() crashes whenever a database is used in an invalid
|
||||
/// dispatch queue.
|
||||
final class SchedulingWatchdog {
|
||||
private static let specificKey = DispatchSpecificKey<SchedulingWatchdog>()
|
||||
private(set) var allowedDatabases: [Database]
|
||||
var databaseObservationBroker: DatabaseObservationBroker?
|
||||
|
||||
private init(allowedDatabase database: Database) {
|
||||
allowedDatabases = [database]
|
||||
@@ -40,27 +37,22 @@ final class SchedulingWatchdog {
|
||||
return queue
|
||||
}
|
||||
|
||||
// Temporarily allows `databases` while executing `body`
|
||||
func allowing<T>(databases: [Database], execute body: () throws -> T) rethrows -> T {
|
||||
func inheritingAllowedDatabases<T>(from other: SchedulingWatchdog, execute body: () throws -> T) rethrows -> T {
|
||||
let backup = allowedDatabases
|
||||
allowedDatabases.append(contentsOf: databases)
|
||||
allowedDatabases.append(contentsOf: other.allowedDatabases)
|
||||
defer { allowedDatabases = backup }
|
||||
return try body()
|
||||
}
|
||||
|
||||
static func preconditionValidQueue(_ db: Database, _ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
|
||||
GRDBPrecondition(allows(db), message, file: file, line: line)
|
||||
}
|
||||
|
||||
static func allows(_ db: Database) -> Bool {
|
||||
return current?.allows(db) ?? false
|
||||
}
|
||||
|
||||
func allows(_ db: Database) -> Bool {
|
||||
return allowedDatabases.contains { $0 === db }
|
||||
GRDBPrecondition(current?.allows(db) ?? false, message, file: file, line: line)
|
||||
}
|
||||
|
||||
static var current: SchedulingWatchdog? {
|
||||
return DispatchQueue.getSpecific(key: specificKey)
|
||||
}
|
||||
|
||||
func allows(_ db: Database) -> Bool {
|
||||
return allowedDatabases.contains { $0 === db }
|
||||
}
|
||||
}
|
||||
@@ -81,7 +81,8 @@ final class SerializedDatabase {
|
||||
guard let watchdog = SchedulingWatchdog.current else {
|
||||
// Case 1
|
||||
return try queue.sync {
|
||||
try block(db)
|
||||
defer { preconditionNoTransactionLeft(db) }
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,8 +91,9 @@ final class SerializedDatabase {
|
||||
|
||||
// Case 3
|
||||
return try queue.sync {
|
||||
try SchedulingWatchdog.current!.allowing(databases: watchdog.allowedDatabases) {
|
||||
try block(db)
|
||||
try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) {
|
||||
defer { preconditionNoTransactionLeft(db) }
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -125,19 +127,22 @@ final class SerializedDatabase {
|
||||
guard let watchdog = SchedulingWatchdog.current else {
|
||||
// Case 1
|
||||
return try queue.sync {
|
||||
try block(db)
|
||||
defer { preconditionNoTransactionLeft(db) }
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
|
||||
// Case 2
|
||||
if watchdog.allows(db) {
|
||||
defer { preconditionNoTransactionLeft(db) }
|
||||
return try block(db)
|
||||
}
|
||||
|
||||
// Case 3
|
||||
return try queue.sync {
|
||||
try SchedulingWatchdog.current!.allowing(databases: watchdog.allowedDatabases) {
|
||||
try block(db)
|
||||
try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) {
|
||||
defer { preconditionNoTransactionLeft(db) }
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -146,12 +151,13 @@ final class SerializedDatabase {
|
||||
func async(_ block: @escaping (Database) -> Void) {
|
||||
queue.async {
|
||||
block(self.db)
|
||||
self.preconditionNoTransactionLeft(self.db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if any only if the current dispatch queue is valid.
|
||||
var onValidQueue: Bool {
|
||||
return SchedulingWatchdog.allows(db)
|
||||
return SchedulingWatchdog.current?.allows(db) ?? false
|
||||
}
|
||||
|
||||
/// Executes the block in the current queue.
|
||||
@@ -166,4 +172,9 @@ final class SerializedDatabase {
|
||||
func preconditionValidQueue(_ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
|
||||
SchedulingWatchdog.preconditionValidQueue(db, message, file: file, line: line)
|
||||
}
|
||||
|
||||
/// Fatal error if a transaction has been left opened.
|
||||
func preconditionNoTransactionLeft(_ db: Database, _ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access", file: StaticString = #file, line: UInt = #line) {
|
||||
GRDBPrecondition(configuration.allowsUnsafeTransactions || !db.isInsideTransaction, message, file: file, line: line)
|
||||
}
|
||||
}
|
||||
+319
-221
@@ -1,12 +1,20 @@
|
||||
import Foundation
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// A raw SQLite statement, suitable for the SQLite C API.
|
||||
public typealias SQLiteStatement = OpaquePointer
|
||||
|
||||
/// Statements are separated by semicolons and white spaces
|
||||
let statementSeparatorCharacterSet = CharacterSet(charactersIn: ";").union(.whitespacesAndNewlines)
|
||||
|
||||
/// An error emitted when one tries to compile an empty statement.
|
||||
struct EmptyStatementError : Error {
|
||||
}
|
||||
|
||||
/// A statement represents an SQL query.
|
||||
///
|
||||
/// It is the base class of UpdateStatement that executes *update statements*,
|
||||
@@ -20,47 +28,54 @@ public class Statement {
|
||||
public var sql: String {
|
||||
// trim white space and semicolumn for homogeneous output
|
||||
return String(cString: sqlite3_sql(sqliteStatement))
|
||||
.trimmingCharacters(in: CharacterSet(charactersIn: ";").union(.whitespacesAndNewlines))
|
||||
.trimmingCharacters(in: statementSeparatorCharacterSet)
|
||||
}
|
||||
|
||||
/// The database
|
||||
unowned let database: Database
|
||||
|
||||
init(database: Database, sqliteStatement: SQLiteStatement) {
|
||||
self.database = database
|
||||
self.sqliteStatement = sqliteStatement
|
||||
}
|
||||
|
||||
fileprivate init(database: Database, sql: String, observer: StatementCompilationObserver) throws {
|
||||
/// Creates a prepared statement.
|
||||
///
|
||||
/// - 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)
|
||||
/// - throws: DatabaseError in case of compilation error, and
|
||||
/// EmptyStatementError if the compiled string is blank or empty.
|
||||
init(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
prepFlags: Int32) throws
|
||||
{
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
|
||||
observer.start()
|
||||
defer { observer.stop() }
|
||||
|
||||
let sqlCodeUnits = sql.utf8CString
|
||||
var sqliteStatement: SQLiteStatement? = nil
|
||||
var code: Int32 = 0
|
||||
var remainingSQL = ""
|
||||
sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
|
||||
let sqlStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
|
||||
var sqlEnd: UnsafePointer<Int8>? = nil
|
||||
code = sqlite3_prepare_v2(database.sqliteConnection, sqlStart, -1, &sqliteStatement, &sqlEnd)
|
||||
let remainingData = Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: sqlEnd!), count: sqlStart + sqlCodeUnits.count - sqlEnd! - 1, deallocator: .none)
|
||||
remainingSQL = String(data: remainingData, encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
// sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
|
||||
#if GRDBCUSTOMSQLITE
|
||||
let code = sqlite3_prepare_v3(database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), &sqliteStatement, statementEnd)
|
||||
#else
|
||||
let code = sqlite3_prepare_v2(database.sqliteConnection, statementStart, -1, &sqliteStatement, statementEnd)
|
||||
#endif
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql)
|
||||
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: String(cString: statementStart))
|
||||
}
|
||||
|
||||
guard remainingSQL.isEmpty else {
|
||||
sqlite3_finalize(sqliteStatement)
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Multiple statements found. To execute multiple statements, use Database.execute() instead.", sql: sql, arguments: nil)
|
||||
guard let statement = sqliteStatement else {
|
||||
// I wish we could simply return nil, and make this initializer failable.
|
||||
//
|
||||
// Unfortunately, there is a Swift bug with failable+throwing initializers:
|
||||
// https://bugs.swift.org/browse/SR-6067
|
||||
//
|
||||
// We thus use sentinel error for empty statements.
|
||||
throw EmptyStatementError()
|
||||
}
|
||||
|
||||
self.database = database
|
||||
self.sqliteStatement = sqliteStatement!
|
||||
|
||||
self.sqliteStatement = statement
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -94,7 +109,7 @@ public class Statement {
|
||||
guard let cString = sqlite3_bind_parameter_name(self.sqliteStatement, Int32($0 + 1)) else {
|
||||
return nil
|
||||
}
|
||||
return String(String(cString: cString).characters.dropFirst()) // Drop initial ":", "@", "$"
|
||||
return String(String(cString: cString).dropFirst()) // Drop initial ":", "@", "$"
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -124,7 +139,7 @@ public class Statement {
|
||||
clearBindings()
|
||||
|
||||
var valuesIterator = arguments.values.makeIterator()
|
||||
for (index, argumentName) in sqliteArgumentNames.enumerated() {
|
||||
for (index, argumentName) in zip(Int32(1)..., sqliteArgumentNames) {
|
||||
if let argumentName = argumentName, let value = arguments.namedValues[argumentName] {
|
||||
bind(value, at: index)
|
||||
} else if let value = valuesIterator.next() {
|
||||
@@ -145,26 +160,26 @@ public class Statement {
|
||||
// Apply
|
||||
reset()
|
||||
clearBindings()
|
||||
for (index, dbValue) in bindings.enumerated() {
|
||||
for (index, dbValue) in zip(Int32(1)..., bindings) {
|
||||
bind(dbValue, at: index)
|
||||
}
|
||||
}
|
||||
|
||||
// 0-based index
|
||||
private func bind(_ dbValue: DatabaseValue, at index: Int) {
|
||||
// 1-based index
|
||||
private func bind(_ dbValue: DatabaseValue, at index: Int32) {
|
||||
let code: Int32
|
||||
switch dbValue.storage {
|
||||
case .null:
|
||||
code = sqlite3_bind_null(sqliteStatement, Int32(index + 1))
|
||||
code = sqlite3_bind_null(sqliteStatement, index)
|
||||
case .int64(let int64):
|
||||
code = sqlite3_bind_int64(sqliteStatement, Int32(index + 1), int64)
|
||||
code = sqlite3_bind_int64(sqliteStatement, index, int64)
|
||||
case .double(let double):
|
||||
code = sqlite3_bind_double(sqliteStatement, Int32(index + 1), double)
|
||||
code = sqlite3_bind_double(sqliteStatement, index, double)
|
||||
case .string(let string):
|
||||
code = sqlite3_bind_text(sqliteStatement, Int32(index + 1), string, -1, SQLITE_TRANSIENT)
|
||||
code = sqlite3_bind_text(sqliteStatement, index, string, -1, SQLITE_TRANSIENT)
|
||||
case .blob(let data):
|
||||
code = data.withUnsafeBytes { bytes in
|
||||
sqlite3_bind_blob(sqliteStatement, Int32(index + 1), bytes, Int32(data.count), SQLITE_TRANSIENT)
|
||||
sqlite3_bind_blob(sqliteStatement, index, bytes, Int32(data.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,15 +201,84 @@ public class Statement {
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func prepare(withArguments arguments: StatementArguments?) throws {
|
||||
fileprivate func prepare(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 setArgumentsWithValidation(arguments)
|
||||
try! setArgumentsWithValidation(arguments)
|
||||
} else if argumentsNeedValidation {
|
||||
try validate(arguments: self.arguments)
|
||||
try! validate(arguments: self.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - AuthorizedStatement
|
||||
|
||||
/// A common protocol for UpdateStatement and SelectStatement
|
||||
protocol AuthorizedStatement {
|
||||
// This initializer should be a required initializer of Statement.
|
||||
//
|
||||
// But Swift requires this required initializer to be public:
|
||||
// https://bugs.swift.org/browse/SR-2347
|
||||
//
|
||||
// We work around SR-2347 with this internal protocol.
|
||||
init(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
prepFlags: Int32,
|
||||
authorizer: StatementCompilationAuthorizer) throws
|
||||
}
|
||||
|
||||
extension AuthorizedStatement {
|
||||
// Static function instead of an initializer because initializer doesn't
|
||||
// compile due to the "capturing of an uninitialized self" in
|
||||
// `sqlCodeUnits.withUnsafeBufferPointer`.
|
||||
static func prepare(sql: String, prepFlags: Int32, in database: Database) throws -> Self {
|
||||
let authorizer = StatementCompilationAuthorizer()
|
||||
database.authorizer = authorizer
|
||||
defer { database.authorizer = nil }
|
||||
|
||||
let sqlCodeUnits = sql.utf8CString
|
||||
return try sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
|
||||
let statementStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
|
||||
var statementEnd: UnsafePointer<Int8>? = nil
|
||||
let statement: Self
|
||||
do {
|
||||
statement = try self.init(
|
||||
database: database,
|
||||
statementStart: statementStart,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: prepFlags,
|
||||
authorizer: authorizer)
|
||||
} catch is EmptyStatementError {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_ERROR,
|
||||
message: "empty statement",
|
||||
sql: sql,
|
||||
arguments: nil)
|
||||
}
|
||||
|
||||
let remainingData = Data(
|
||||
bytesNoCopy: UnsafeMutableRawPointer(mutating: statementEnd!),
|
||||
count: statementStart + sqlCodeUnits.count - statementEnd! - 1,
|
||||
deallocator: .none)
|
||||
|
||||
let remainingSQL = String(data: remainingData, encoding: .utf8)!
|
||||
.trimmingCharacters(in: statementSeparatorCharacterSet)
|
||||
|
||||
guard remainingSQL.isEmpty else {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: "Multiple statements found. To execute multiple statements, use Database.execute() instead.",
|
||||
sql: sql,
|
||||
arguments: nil)
|
||||
}
|
||||
|
||||
return statement
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SelectStatement
|
||||
|
||||
@@ -203,151 +287,124 @@ public class Statement {
|
||||
/// You create SelectStatement with the Database.makeSelectStatement() method:
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM persons WHERE age > ?")
|
||||
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?")
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
/// }
|
||||
public final class SelectStatement : Statement {
|
||||
/// Information about the table and columns read by a SelectStatement
|
||||
public private(set) var selectionInfo: SelectionInfo
|
||||
/// :nodoc:
|
||||
@available(*, deprecated, renamed:"DatabaseRegion")
|
||||
public typealias SelectionInfo = DatabaseRegion
|
||||
|
||||
init(database: Database, sql: String) throws {
|
||||
self.selectionInfo = SelectionInfo()
|
||||
let observer = StatementCompilationObserver(database)
|
||||
try super.init(database: database, sql: sql, observer: observer)
|
||||
Database.preconditionValidSelectStatement(sql: sql, observer: observer)
|
||||
self.selectionInfo = observer.selectionInfo
|
||||
/// :nodoc:
|
||||
@available(*, deprecated, renamed:"fetchedRegion")
|
||||
public var selectionInfo: DatabaseRegion { return fetchedRegion }
|
||||
|
||||
/// The database region that the statement looks into.
|
||||
public private(set) var fetchedRegion: DatabaseRegion
|
||||
|
||||
/// Creates a prepared statement.
|
||||
///
|
||||
/// - 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)
|
||||
/// - authorizer: A StatementCompilationAuthorizer
|
||||
/// - throws: DatabaseError in case of compilation error, and
|
||||
/// EmptyStatementError if the compiled string is blank or empty.
|
||||
init(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
prepFlags: Int32,
|
||||
authorizer: StatementCompilationAuthorizer) throws
|
||||
{
|
||||
self.fetchedRegion = DatabaseRegion()
|
||||
try super.init(
|
||||
database: database,
|
||||
statementStart: statementStart,
|
||||
statementEnd: statementEnd,
|
||||
prepFlags: prepFlags)
|
||||
|
||||
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.")
|
||||
|
||||
self.fetchedRegion = authorizer.region
|
||||
}
|
||||
|
||||
/// The number of columns in the resulting rows.
|
||||
public lazy var columnCount: Int = {
|
||||
Int(sqlite3_column_count(self.sqliteStatement))
|
||||
}()
|
||||
public var columnCount: Int {
|
||||
return 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..<self.columnCount).map { (index: Int) -> String in String(cString: sqlite3_column_name(sqliteStatement, Int32(index))) }
|
||||
return (0..<Int32(self.columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
|
||||
}()
|
||||
|
||||
/// Cache for indexOfColumn(). Keys are lowercase.
|
||||
/// Cache for index(ofColumn:). Keys are lowercase.
|
||||
private lazy var columnIndexes: [String: Int] = {
|
||||
return Dictionary(keyValueSequence: self.columnNames.enumerated().map { ($1.lowercased(), $0) }.reversed())
|
||||
return 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.
|
||||
func index(ofColumn name: String) -> Int? {
|
||||
public func index(ofColumn name: String) -> Int? {
|
||||
return columnIndexes[name.lowercased()]
|
||||
}
|
||||
|
||||
/// Creates a DatabaseCursor
|
||||
func cursor<Element>(arguments: StatementArguments? = nil, next element: @escaping () throws -> Element) -> DatabaseCursor<Element> {
|
||||
// Check that cursor is built on a valid queue.
|
||||
SchedulingWatchdog.preconditionValidQueue(database, "Database was not used on the correct thread.")
|
||||
|
||||
// Force arguments validity: it is a programmer error to provide
|
||||
// arguments that do not match the statement.
|
||||
try! prepare(withArguments: arguments)
|
||||
|
||||
reset()
|
||||
return DatabaseCursor(statement: self, element: element)
|
||||
/// Creates a cursor over the statement. This cursor does not produce any
|
||||
/// value, and is only intended to give access to the sqlite3_step()
|
||||
/// low-level function.
|
||||
func cursor(arguments: StatementArguments? = nil) -> StatementCursor {
|
||||
return StatementCursor(statement: self, arguments: arguments)
|
||||
}
|
||||
|
||||
/// Creates a cursor whose results are ignored
|
||||
func cursor(arguments: StatementArguments? = nil) -> DatabaseCursor<Void> {
|
||||
return cursor(arguments: arguments) { }
|
||||
}
|
||||
|
||||
/// Information about the table and columns read by a SelectStatement
|
||||
public struct SelectionInfo : CustomStringConvertible {
|
||||
mutating func insert(table: String) {
|
||||
tables.insert(table)
|
||||
}
|
||||
|
||||
mutating func insert(column: String, ofTable table: String) {
|
||||
if columns[table] != nil {
|
||||
columns[table]!.insert(column)
|
||||
} else {
|
||||
columns[table] = [column]
|
||||
}
|
||||
}
|
||||
|
||||
/// If true, selection is unknown
|
||||
let isUnknown: Bool
|
||||
|
||||
/// Relevant iff isUnknown is false
|
||||
func contains(anyColumnFrom table: String) -> Bool {
|
||||
return tables.contains(table) || columns.index(forKey: table) != nil
|
||||
}
|
||||
|
||||
/// Relevant iff isUnknown is false
|
||||
func contains(anyColumnIn columns: Set<String>, from table: String) -> Bool {
|
||||
return tables.contains(table) || !(self.columns[table]?.isDisjoint(with: columns) ?? true)
|
||||
}
|
||||
|
||||
init() {
|
||||
self.init(isUnknown: false)
|
||||
}
|
||||
|
||||
static func unknown() -> SelectionInfo {
|
||||
return self.init(isUnknown: true)
|
||||
}
|
||||
|
||||
// `SELECT a, b FROM t1` -> ["t1": ["a", "b"]]
|
||||
private var columns: [String: Set<String>] = [:]
|
||||
|
||||
// `SELECT COUNT(*) FROM t1` -> ["t1"]
|
||||
private var tables: Set<String> = []
|
||||
|
||||
private init(isUnknown: Bool) {
|
||||
self.isUnknown = isUnknown
|
||||
}
|
||||
|
||||
/// A textual representation of `self`.
|
||||
public var description: String {
|
||||
// TODO: include tables in the description
|
||||
return columns
|
||||
.sorted { $0.key < $1.key }
|
||||
.map { (table, columns) in "\(table)(\(columns.sorted().joined(separator: ", ")))" }
|
||||
.joined(separator: ", ")
|
||||
}
|
||||
/// Utility function for cursors
|
||||
func cursorReset(arguments: StatementArguments? = nil) {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
prepare(withArguments: arguments)
|
||||
reset()
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor on a statement
|
||||
public final class DatabaseCursor<Element> : Cursor {
|
||||
fileprivate let statement: SelectStatement
|
||||
// Hide AuthorizedStatement from Jazzy
|
||||
extension SelectStatement: AuthorizedStatement { }
|
||||
|
||||
/// A cursor that iterates a database statement without producing any value.
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let statement = db.makeSelectStatement("SELECT * FROM players")
|
||||
/// let cursor: StatementCursor = statement.cursor()
|
||||
/// }
|
||||
public final class StatementCursor: Cursor {
|
||||
public let statement: SelectStatement
|
||||
private let sqliteStatement: SQLiteStatement
|
||||
private let element: () throws -> Element?
|
||||
private var done = false
|
||||
|
||||
// Fileprivate so that only SelectStatement can instantiate a database cursor
|
||||
fileprivate init(statement: SelectStatement, element: @escaping () throws -> Element?) {
|
||||
// Use SelectStatement.cursor() instead
|
||||
fileprivate init(statement: SelectStatement, arguments: StatementArguments? = nil) {
|
||||
self.statement = statement
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
self.element = element
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or `nil` if no next element
|
||||
/// exists. Once nil has been returned, all subsequent calls return nil.
|
||||
///
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT ...") // DatabaseCursor<Row>
|
||||
/// while let row = try rows.next() { // Row
|
||||
/// let id: Int64 = row.value(atIndex: 0)
|
||||
/// let name: String = row.value(atIndex: 1)
|
||||
/// }
|
||||
public func next() throws -> Element? {
|
||||
if done {
|
||||
return nil
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func next() throws -> Void? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return try element()
|
||||
return .some(())
|
||||
case let code:
|
||||
statement.database.selectStatementDidFail(statement)
|
||||
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
@@ -363,51 +420,57 @@ public final class DatabaseCursor<Element> : Cursor {
|
||||
/// You create UpdateStatement with the Database.makeUpdateStatement() method:
|
||||
///
|
||||
/// try dbQueue.inTransaction { db in
|
||||
/// let statement = try db.makeUpdateStatement("INSERT INTO persons (name) VALUES (?)")
|
||||
/// let statement = try db.makeUpdateStatement("INSERT INTO players (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// return .commit
|
||||
/// }
|
||||
public final class UpdateStatement : Statement {
|
||||
enum TransactionStatementInfo {
|
||||
enum SavepointAction : String {
|
||||
case begin = "BEGIN"
|
||||
case release = "RELEASE"
|
||||
case rollback = "ROLLBACK"
|
||||
}
|
||||
|
||||
enum TransactionAction : String {
|
||||
case begin = "BEGIN"
|
||||
case commit = "COMMIT"
|
||||
case rollback = "ROLLBACK"
|
||||
}
|
||||
|
||||
case transaction(action: TransactionAction)
|
||||
case savepoint(name: String, action: SavepointAction)
|
||||
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
|
||||
private(set) var transactionStatementInfo: TransactionStatementInfo?
|
||||
|
||||
private(set) var transactionEffect: TransactionEffect?
|
||||
private(set) var databaseEventKinds: [DatabaseEventKind]
|
||||
|
||||
init(database: Database, sqliteStatement: SQLiteStatement, invalidatesDatabaseSchemaCache: Bool, transactionStatementInfo: TransactionStatementInfo?, databaseEventKinds: [DatabaseEventKind]) {
|
||||
self.invalidatesDatabaseSchemaCache = invalidatesDatabaseSchemaCache
|
||||
self.transactionStatementInfo = transactionStatementInfo
|
||||
self.databaseEventKinds = databaseEventKinds
|
||||
super.init(database: database, sqliteStatement: sqliteStatement)
|
||||
}
|
||||
|
||||
init(database: Database, sql: String) throws {
|
||||
/// Creates a prepared statement.
|
||||
///
|
||||
/// - 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)
|
||||
/// - authorizer: A StatementCompilationAuthorizer
|
||||
/// - throws: DatabaseError in case of compilation error, and
|
||||
/// EmptyStatementError if the compiled string is blank or empty.
|
||||
init(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
prepFlags: Int32,
|
||||
authorizer: StatementCompilationAuthorizer) throws
|
||||
{
|
||||
self.invalidatesDatabaseSchemaCache = false
|
||||
self.databaseEventKinds = []
|
||||
|
||||
let observer = StatementCompilationObserver(database)
|
||||
try super.init(database: database, sql: sql, observer: observer)
|
||||
self.invalidatesDatabaseSchemaCache = observer.invalidatesDatabaseSchemaCache
|
||||
self.transactionStatementInfo = observer.transactionStatementInfo
|
||||
self.databaseEventKinds = observer.databaseEventKinds
|
||||
try super.init(
|
||||
database: database,
|
||||
statementStart: statementStart,
|
||||
statementEnd: statementEnd,
|
||||
prepFlags: prepFlags)
|
||||
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
|
||||
self.transactionEffect = authorizer.transactionEffect
|
||||
self.databaseEventKinds = authorizer.databaseEventKinds
|
||||
}
|
||||
|
||||
/// Executes the SQL query.
|
||||
@@ -416,11 +479,7 @@ public final class UpdateStatement : Statement {
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func execute(arguments: StatementArguments? = nil) throws {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
|
||||
// Force arguments validity: it is a programmer error to provide
|
||||
// arguments that do not match the statement.
|
||||
try! prepare(withArguments: arguments)
|
||||
|
||||
prepare(withArguments: arguments)
|
||||
reset()
|
||||
database.updateStatementWillExecute(self)
|
||||
|
||||
@@ -446,21 +505,20 @@ public final class UpdateStatement : Statement {
|
||||
continue
|
||||
|
||||
case SQLITE_DONE:
|
||||
database.updateStatementDidExecute(self)
|
||||
try database.updateStatementDidExecute(self)
|
||||
return
|
||||
|
||||
case let code:
|
||||
// Failure
|
||||
//
|
||||
// Let database rethrow eventual transaction observer error:
|
||||
try database.updateStatementDidFail(self)
|
||||
|
||||
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql, arguments: self.arguments) // Error uses self.arguments, not the optional arguments parameter.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Hide AuthorizedStatement from Jazzy
|
||||
extension UpdateStatement: AuthorizedStatement { }
|
||||
|
||||
|
||||
// MARK: - StatementArguments
|
||||
|
||||
@@ -495,13 +553,13 @@ public final class UpdateStatement : Statement {
|
||||
/// To fill named arguments, feed StatementArguments with a dictionary:
|
||||
///
|
||||
/// db.execute(
|
||||
/// "INSERT ... (:name, :age)",
|
||||
/// arguments: StatementArguments(["name": "Arthur", "age": 41]))
|
||||
/// "INSERT ... (:name, :score)",
|
||||
/// arguments: StatementArguments(["name": "Arthur", "score": 41]))
|
||||
///
|
||||
/// // Dictionary literals are automatically converted:
|
||||
/// db.execute(
|
||||
/// "INSERT ... (:name, :age)",
|
||||
/// arguments: ["name": "Arthur", "age": 41])
|
||||
/// "INSERT ... (:name, :score)",
|
||||
/// arguments: ["name": "Arthur", "score": 41])
|
||||
///
|
||||
/// ## Concatenating Arguments
|
||||
///
|
||||
@@ -535,40 +593,47 @@ public final class UpdateStatement : Statement {
|
||||
/// let row = try Row.fetchOne(db, sql, arguments: [1, 2, "bar"] + ["foo": "foo"])!
|
||||
/// print(row)
|
||||
/// // Prints <Row two:2 foo:"foo" one:1 foo2:"foo" bar:"bar">
|
||||
public struct StatementArguments {
|
||||
public struct StatementArguments: CustomStringConvertible, Equatable, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral {
|
||||
var values: [DatabaseValue] = []
|
||||
var namedValues: [String: DatabaseValue] = [:]
|
||||
|
||||
public var isEmpty: Bool {
|
||||
return values.isEmpty && namedValues.isEmpty
|
||||
}
|
||||
|
||||
|
||||
// MARK: Empty Arguments
|
||||
|
||||
/// Creates empty StatementArguments.
|
||||
init() {
|
||||
}
|
||||
|
||||
// MARK: Positional Arguments
|
||||
|
||||
/// Initializes arguments from a sequence of optional values.
|
||||
/// Creates statement arguments from a sequence of optional values.
|
||||
///
|
||||
/// let values: [DatabaseValueConvertible?] = ["foo", 1, nil]
|
||||
/// db.execute("INSERT ... (?,?,?)", arguments: StatementArguments(values))
|
||||
///
|
||||
/// - parameter sequence: A sequence of DatabaseValueConvertible values.
|
||||
/// - returns: A StatementArguments.
|
||||
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Iterator.Element == DatabaseValueConvertible? {
|
||||
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Element == DatabaseValueConvertible? {
|
||||
values = sequence.map { $0?.databaseValue ?? .null }
|
||||
}
|
||||
|
||||
/// Initializes arguments from a sequence of optional values.
|
||||
/// Creates statement arguments from a sequence of optional values.
|
||||
///
|
||||
/// let values: [String] = ["foo", "bar"]
|
||||
/// db.execute("INSERT ... (?,?)", arguments: StatementArguments(values))
|
||||
///
|
||||
/// - parameter sequence: A sequence of DatabaseValueConvertible values.
|
||||
/// - returns: A StatementArguments.
|
||||
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Iterator.Element: DatabaseValueConvertible {
|
||||
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Element: DatabaseValueConvertible {
|
||||
values = sequence.map { $0.databaseValue }
|
||||
}
|
||||
|
||||
/// Initializes arguments from [Any].
|
||||
///
|
||||
/// The result is nil unless all objects adopt DatabaseValueConvertible.
|
||||
/// Creates statement arguments from any array. The result is nil unless all
|
||||
/// array elements adopt DatabaseValueConvertible.
|
||||
///
|
||||
/// - parameter array: An array
|
||||
/// - returns: A StatementArguments.
|
||||
@@ -586,8 +651,8 @@ public struct StatementArguments {
|
||||
|
||||
// MARK: Named Arguments
|
||||
|
||||
/// Initializes arguments from a sequence of (key, value) dictionary, such as
|
||||
/// a dictionary.
|
||||
/// Creates statement arguments from a sequence of (key, value) dictionary,
|
||||
/// such as a dictionary.
|
||||
///
|
||||
/// let values: [String: DatabaseValueConvertible?] = ["firstName": nil, "lastName": "Miller"]
|
||||
/// db.execute("INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
|
||||
@@ -595,22 +660,22 @@ public struct StatementArguments {
|
||||
/// - parameter sequence: A sequence of (key, value) pairs
|
||||
/// - returns: A StatementArguments.
|
||||
public init(_ dictionary: [String: DatabaseValueConvertible?]) {
|
||||
namedValues = Dictionary(keys: dictionary.keys) { dictionary[$0]!?.databaseValue ?? .null }
|
||||
namedValues = dictionary.mapValues { $0?.databaseValue ?? .null }
|
||||
}
|
||||
|
||||
/// Initializes arguments from a sequence of (key, value) pairs, such as
|
||||
/// a dictionary.
|
||||
/// Creates statement arguments from a sequence of (key, value) pairs, such
|
||||
/// as a dictionary.
|
||||
///
|
||||
/// let values: [String: DatabaseValueConvertible?] = ["firstName": nil, "lastName": "Miller"]
|
||||
/// db.execute("INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
|
||||
///
|
||||
/// - parameter sequence: A sequence of (key, value) pairs
|
||||
/// - returns: A StatementArguments.
|
||||
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Iterator.Element == (String, DatabaseValueConvertible?) {
|
||||
namedValues = Dictionary(keyValueSequence: sequence.map { ($0, $1?.databaseValue ?? .null) })
|
||||
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Element == (String, DatabaseValueConvertible?) {
|
||||
namedValues = Dictionary(uniqueKeysWithValues: sequence.map { ($0.0, $0.1?.databaseValue ?? .null) })
|
||||
}
|
||||
|
||||
/// Initializes arguments from [AnyHashable: Any].
|
||||
/// Creates statement arguments from [AnyHashable: Any].
|
||||
///
|
||||
/// The result is nil unless all dictionary keys are strings, and values
|
||||
/// adopt DatabaseValueConvertible.
|
||||
@@ -788,12 +853,6 @@ public struct StatementArguments {
|
||||
|
||||
// MARK: Not Public
|
||||
|
||||
var values: [DatabaseValue] = []
|
||||
var namedValues: [String: DatabaseValue] = [:]
|
||||
|
||||
init() {
|
||||
}
|
||||
|
||||
mutating func consume(_ statement: Statement, allowingRemainingValues: Bool) throws -> [DatabaseValue] {
|
||||
let initialValuesCount = values.count
|
||||
let bindings = try statement.sqliteArgumentNames.map { argumentName -> DatabaseValue in
|
||||
@@ -820,7 +879,8 @@ public struct StatementArguments {
|
||||
}
|
||||
}
|
||||
|
||||
extension StatementArguments : ExpressibleByArrayLiteral {
|
||||
// ExpressibleByArrayLiteral
|
||||
extension StatementArguments {
|
||||
/// Returns a StatementArguments from an array literal:
|
||||
///
|
||||
/// db.selectRows("SELECT ...", arguments: ["Arthur", 41])
|
||||
@@ -829,17 +889,19 @@ extension StatementArguments : ExpressibleByArrayLiteral {
|
||||
}
|
||||
}
|
||||
|
||||
extension StatementArguments : ExpressibleByDictionaryLiteral {
|
||||
// ExpressibleByDictionaryLiteral
|
||||
extension StatementArguments {
|
||||
/// Returns a StatementArguments from a dictionary literal:
|
||||
///
|
||||
/// db.selectRows("SELECT ...", arguments: ["name": "Arthur", "age": 41])
|
||||
/// db.selectRows("SELECT ...", arguments: ["name": "Arthur", "score": 41])
|
||||
public init(dictionaryLiteral elements: (String, DatabaseValueConvertible?)...) {
|
||||
self.init(elements)
|
||||
}
|
||||
}
|
||||
|
||||
extension StatementArguments : CustomStringConvertible {
|
||||
/// A textual representation of `self`.
|
||||
// CustomStringConvertible
|
||||
extension StatementArguments {
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
let valuesDescriptions = values.map { $0.description }
|
||||
let namedValuesDescriptions = namedValues.map { (key, value) -> String in
|
||||
@@ -849,6 +911,16 @@ extension StatementArguments : CustomStringConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
// Equatable
|
||||
extension StatementArguments {
|
||||
/// :nodoc:
|
||||
public static func == (lhs: StatementArguments, rhs: StatementArguments) -> Bool {
|
||||
if lhs.values != rhs.values { return false }
|
||||
if lhs.namedValues != rhs.namedValues { return false }
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/// A thread-unsafe statement cache
|
||||
struct StatementCache {
|
||||
unowned let db: Database
|
||||
@@ -864,7 +936,20 @@ struct StatementCache {
|
||||
return statement
|
||||
}
|
||||
|
||||
let statement = try db.makeSelectStatement(sql)
|
||||
#if GRDBCUSTOMSQLITE
|
||||
// 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
|
||||
let statement = try db.makeSelectStatement(sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
|
||||
#else
|
||||
let statement = try db.makeSelectStatement(sql)
|
||||
#endif
|
||||
selectStatements[sql] = statement
|
||||
return statement
|
||||
}
|
||||
@@ -874,7 +959,20 @@ struct StatementCache {
|
||||
return statement
|
||||
}
|
||||
|
||||
let statement = try db.makeUpdateStatement(sql)
|
||||
#if GRDBCUSTOMSQLITE
|
||||
// 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
|
||||
let statement = try db.makeUpdateStatement(sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
|
||||
#else
|
||||
let statement = try db.makeUpdateStatement(sql)
|
||||
#endif
|
||||
updateStatements[sql] = statement
|
||||
return statement
|
||||
}
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// A protocol around sqlite3_set_authorizer
|
||||
protocol StatementAuthorizer : class {
|
||||
func authorize(
|
||||
_ actionCode: Int32,
|
||||
_ cString1: UnsafePointer<Int8>?,
|
||||
_ cString2: UnsafePointer<Int8>?,
|
||||
_ cString3: UnsafePointer<Int8>?,
|
||||
_ cString4: UnsafePointer<Int8>?)
|
||||
-> Int32
|
||||
}
|
||||
|
||||
/// A class that gathers information about one statement during its compilation.
|
||||
final class StatementCompilationAuthorizer : StatementAuthorizer {
|
||||
/// What this statements reads
|
||||
var region = DatabaseRegion()
|
||||
|
||||
/// What this statements writes
|
||||
var databaseEventKinds: [DatabaseEventKind] = []
|
||||
|
||||
/// True if a statement alter the schema in a way that required schema cache
|
||||
/// invalidation. For example, adding a column to a table invalidates the
|
||||
/// schema cache, but not creating a table.
|
||||
var invalidatesDatabaseSchemaCache = false
|
||||
|
||||
/// Not nil if a statement is a BEGIN/COMMIT/ROLLBACK/RELEASE transaction or
|
||||
/// savepoint statement.
|
||||
var transactionEffect: UpdateStatement.TransactionEffect?
|
||||
|
||||
private var isDropStatement = false
|
||||
|
||||
func authorize(
|
||||
_ actionCode: Int32,
|
||||
_ cString1: UnsafePointer<Int8>?,
|
||||
_ cString2: UnsafePointer<Int8>?,
|
||||
_ cString3: UnsafePointer<Int8>?,
|
||||
_ cString4: UnsafePointer<Int8>?)
|
||||
-> Int32
|
||||
{
|
||||
// print("StatementCompilationAuthorizer: \(actionCode) \([cString1, cString2, cString3, cString4].flatMap { $0.map({ String(cString: $0) }) })")
|
||||
|
||||
switch actionCode {
|
||||
case SQLITE_DROP_TABLE, SQLITE_DROP_VTABLE, SQLITE_DROP_TEMP_TABLE,
|
||||
SQLITE_DROP_INDEX, SQLITE_DROP_TEMP_INDEX:
|
||||
isDropStatement = true
|
||||
invalidatesDatabaseSchemaCache = true
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_DROP_VIEW, SQLITE_DROP_TEMP_VIEW,
|
||||
SQLITE_DROP_TRIGGER, SQLITE_CREATE_TEMP_TRIGGER:
|
||||
isDropStatement = true
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_DETACH, SQLITE_ALTER_TABLE,
|
||||
SQLITE_CREATE_INDEX, SQLITE_CREATE_TEMP_INDEX:
|
||||
invalidatesDatabaseSchemaCache = true
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_READ:
|
||||
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
|
||||
guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
|
||||
if columnName.isEmpty {
|
||||
// SELECT COUNT(*) FROM table
|
||||
region.formUnion(DatabaseRegion(table: tableName))
|
||||
} else {
|
||||
// SELECT column FROM table
|
||||
region.formUnion(DatabaseRegion(table: tableName, columns: [columnName]))
|
||||
}
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_INSERT:
|
||||
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
|
||||
databaseEventKinds.append(.insert(tableName: tableName))
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_DELETE:
|
||||
if isDropStatement { return SQLITE_OK }
|
||||
guard let cString1 = cString1 else { return SQLITE_OK }
|
||||
|
||||
// Deletions from sqlite_master and sqlite_temp_master are not like
|
||||
// other deletions: the update hook does not notify them, and they
|
||||
// are prevented when the truncate optimization is disabled.
|
||||
// Let's authorize such deletions by returning SQLITE_OK:
|
||||
guard strcmp(cString1, "sqlite_master") != 0 else { return SQLITE_OK }
|
||||
guard strcmp(cString1, "sqlite_temp_master") != 0 else { return SQLITE_OK }
|
||||
|
||||
// Now we prevent the truncate optimization so that transaction
|
||||
// observers are notified of individual row deletions.
|
||||
databaseEventKinds.append(.delete(tableName: String(cString: cString1)))
|
||||
return SQLITE_IGNORE
|
||||
|
||||
case SQLITE_UPDATE:
|
||||
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
|
||||
guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
|
||||
insertUpdateEventKind(tableName: tableName, columnName: columnName)
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_TRANSACTION:
|
||||
guard let cString1 = cString1 else { return SQLITE_OK }
|
||||
if strcmp(cString1, "BEGIN") == 0 {
|
||||
transactionEffect = .beginTransaction
|
||||
} else if strcmp(cString1, "COMMIT") == 0 {
|
||||
transactionEffect = .commitTransaction
|
||||
} else if strcmp(cString1, "ROLLBACK") == 0 {
|
||||
transactionEffect = .rollbackTransaction
|
||||
}
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_SAVEPOINT:
|
||||
guard let cString1 = cString1 else { return SQLITE_OK }
|
||||
guard let name = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
|
||||
if strcmp(cString1, "BEGIN") == 0 {
|
||||
transactionEffect = .beginSavepoint(name)
|
||||
} else if strcmp(cString1, "RELEASE") == 0 {
|
||||
transactionEffect = .releaseSavepoint(name)
|
||||
} else if strcmp(cString1, "ROLLBACK") == 0 {
|
||||
transactionEffect = .rollbackSavepoint(name)
|
||||
}
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_FUNCTION:
|
||||
// Starting SQLite 3.19.0, `SELECT COUNT(*) FROM table` triggers
|
||||
// an authorization callback for SQLITE_READ with an empty
|
||||
// column: http://www.sqlite.org/changes.html#version_3_19_0
|
||||
//
|
||||
// Before SQLite 3.19.0, `SELECT COUNT(*) FROM table` does not
|
||||
// trigger any authorization callback that tells about the
|
||||
// counted table: any use of the COUNT function makes the
|
||||
// region undetermined (the full database).
|
||||
guard sqlite3_libversion_number() < 3019000 else { return SQLITE_OK }
|
||||
guard let cString2 = cString2 else { return SQLITE_OK }
|
||||
if sqlite3_stricmp(cString2, "COUNT") == 0 {
|
||||
region = .fullDatabase
|
||||
}
|
||||
return SQLITE_OK
|
||||
|
||||
default:
|
||||
return SQLITE_OK
|
||||
}
|
||||
}
|
||||
|
||||
func insertUpdateEventKind(tableName: String, columnName: String) {
|
||||
for (index, eventKind) in databaseEventKinds.enumerated() {
|
||||
if case .update(let t, let columnNames) = eventKind, t == tableName {
|
||||
var columnNames = columnNames
|
||||
columnNames.insert(columnName)
|
||||
databaseEventKinds[index] = .update(tableName: tableName, columnNames: columnNames)
|
||||
return
|
||||
}
|
||||
}
|
||||
databaseEventKinds.append(.update(tableName: tableName, columnNames: [columnName]))
|
||||
}
|
||||
}
|
||||
|
||||
/// This authorizer prevents the [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
|
||||
/// which makes transaction observers unable to observe individual deletions
|
||||
/// when user runs `DELETE FROM t` statements.
|
||||
//
|
||||
/// Warning: to perform well, this authorizer must be used during statement
|
||||
/// execution, not during statement compilation.
|
||||
final class TruncateOptimizationBlocker : StatementAuthorizer {
|
||||
func authorize(
|
||||
_ actionCode: Int32,
|
||||
_ cString1: UnsafePointer<Int8>?,
|
||||
_ cString2: UnsafePointer<Int8>?,
|
||||
_ cString3: UnsafePointer<Int8>?,
|
||||
_ cString4: UnsafePointer<Int8>?)
|
||||
-> Int32
|
||||
{
|
||||
// print("TruncateOptimizationBlocker: \(actionCode) \([cString1, cString2, cString3, cString4].flatMap { $0.map({ String(cString: $0) }) })")
|
||||
return (actionCode == SQLITE_DELETE) ? SQLITE_IGNORE : SQLITE_OK
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,46 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// When a type adopts both DatabaseValueConvertible and
|
||||
/// StatementColumnConvertible, it is granted with faster access to the SQLite
|
||||
/// database values.
|
||||
/// 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
|
||||
/// improvements.
|
||||
///
|
||||
/// To use it, have a value type adopt both StatementColumnConvertible and
|
||||
/// DatabaseValueConvertible. GRDB will then automatically apply the
|
||||
/// optimization whenever direct access to SQLite is possible:
|
||||
///
|
||||
/// let rows = Row.fetchCursor(db, "SELECT ...")
|
||||
/// while let row = try rows.next() {
|
||||
/// let int: Int = row[0] // there
|
||||
/// }
|
||||
/// let ints = Int.fetchAll(db, "SELECT ...") // there
|
||||
/// struct Player {
|
||||
/// init(row: Row) {
|
||||
/// name = row["name"] // there
|
||||
/// score = row["score"] // there
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// StatementColumnConvertible is already adopted by all Swift integer types,
|
||||
/// Float, Double, String, and Bool.
|
||||
public protocol StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
/// Initializes a value from a raw SQLite statement pointer.
|
||||
///
|
||||
/// As an example, here is the how Int64 adopts StatementColumnConvertible:
|
||||
/// For example, here is the how Int64 adopts StatementColumnConvertible:
|
||||
///
|
||||
/// extension Int64: StatementColumnConvertible {
|
||||
/// public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
/// init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
/// self = sqlite3_column_int64(sqliteStatement, index)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// When you implement this method, don't check for NULL.
|
||||
/// This initializer is never called for NULL database values: don't perform
|
||||
/// any extra check.
|
||||
///
|
||||
/// See https://www.sqlite.org/c3ref/column_blob.html for more information.
|
||||
///
|
||||
@@ -27,6 +50,114 @@ public protocol StatementColumnConvertible {
|
||||
init(sqliteStatement: SQLiteStatement, index: Int32)
|
||||
}
|
||||
|
||||
extension StatementColumnConvertible {
|
||||
|
||||
@inline(__always)
|
||||
static func losslessConvert(sqliteStatement: SQLiteStatement, index: Int32) -> Self? {
|
||||
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else {
|
||||
return nil
|
||||
}
|
||||
return self.init(sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
static func losslessConvert(sqliteStatement: SQLiteStatement, index: Int32) -> Self {
|
||||
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else {
|
||||
// Programmer error
|
||||
fatalError("could not convert database value NULL to \(Self.self)")
|
||||
}
|
||||
return self.init(sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// A cursor of database values extracted from a single column.
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let names: ColumnCursor<String> = try String.fetchCursor(db, "SELECT name FROM players")
|
||||
/// while let name = names.next() { // String
|
||||
/// print(name)
|
||||
/// }
|
||||
/// }
|
||||
public final class ColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
|
||||
private let statement: SelectStatement
|
||||
private let sqliteStatement: SQLiteStatement
|
||||
private let columnIndex: Int32
|
||||
private var done = false
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
// We'll read from leftmost column at index 0, unless adapter mangles columns
|
||||
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func next() throws -> Value? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
if sqlite3_column_type(sqliteStatement, columnIndex) == SQLITE_NULL {
|
||||
var error = "could not convert database value NULL to \(Value.self) with statement `\(statement.sql)`"
|
||||
if !statement.arguments.isEmpty {
|
||||
error += " arguments \(statement.arguments)"
|
||||
}
|
||||
fatalError(error)
|
||||
}
|
||||
return Value(sqliteStatement: sqliteStatement, index: columnIndex)
|
||||
case let code:
|
||||
statement.database.selectStatementDidFail(statement)
|
||||
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor of optional database values extracted from a single column.
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let emails: NullableColumnCursor<String> = try Optional<String>.fetchCursor(db, "SELECT email FROM players")
|
||||
/// while let email = emails.next() { // String?
|
||||
/// print(email ?? "<NULL>")
|
||||
/// }
|
||||
/// }
|
||||
public final class NullableColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
|
||||
private let statement: SelectStatement
|
||||
private let sqliteStatement: SQLiteStatement
|
||||
private let columnIndex: Int32
|
||||
private var done = false
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
// We'll read from leftmost column at index 0, unless adapter mangles columns
|
||||
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func next() throws -> Value?? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
if sqlite3_column_type(sqliteStatement, columnIndex) == SQLITE_NULL {
|
||||
return .some(nil)
|
||||
}
|
||||
return Value(sqliteStatement: sqliteStatement, index: columnIndex)
|
||||
case let code:
|
||||
statement.database.selectStatementDidFail(statement)
|
||||
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Types that adopt both DatabaseValueConvertible and
|
||||
/// StatementColumnConvertible can be efficiently initialized from
|
||||
@@ -41,7 +172,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// Returns a cursor over values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let names = try String.fetchCursor(statement) // DatabaseCursor<String>
|
||||
/// let names = try String.fetchCursor(statement) // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
@@ -57,20 +188,8 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
|
||||
// We'll read from leftmost column at index 0, unless adapter mangles columns
|
||||
let columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
|
||||
let sqliteStatement = statement.sqliteStatement
|
||||
return statement.cursor(arguments: arguments, next: {
|
||||
if sqlite3_column_type(sqliteStatement, columnIndex) == SQLITE_NULL {
|
||||
var error = "could not convert database value NULL to \(Self.self) with statement `\(statement.sql)`"
|
||||
if let arguments = arguments, !arguments.isEmpty {
|
||||
error += " arguments \(arguments)"
|
||||
}
|
||||
fatalError(error)
|
||||
}
|
||||
return Self.init(sqliteStatement: sqliteStatement, index: columnIndex)
|
||||
})
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> ColumnCursor<Self> {
|
||||
return try ColumnCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from a prepared statement.
|
||||
@@ -100,15 +219,8 @@ 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, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
|
||||
// We'll read from leftmost column at index 0, unless adapter mangles columns
|
||||
let columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
|
||||
let sqliteStatement = statement.sqliteStatement
|
||||
let cursor: DatabaseCursor<Self?> = statement.cursor(arguments: arguments, next: {
|
||||
if sqlite3_column_type(sqliteStatement, columnIndex) == SQLITE_NULL {
|
||||
return nil
|
||||
}
|
||||
return Self.init(sqliteStatement: sqliteStatement, index: columnIndex)
|
||||
})
|
||||
// fetchOne returns nil if there is no row, or if there is a row with a null value
|
||||
let cursor = try NullableColumnCursor<Self>(statement: statement, arguments: arguments, adapter: adapter)
|
||||
return try cursor.next() ?? nil
|
||||
}
|
||||
}
|
||||
@@ -120,8 +232,8 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// Returns a cursor over values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn)
|
||||
/// let names = try String.fetchCursor(db, request) // DatabaseCursor<String>
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try String.fetchCursor(db, request) // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
@@ -136,7 +248,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - request: A fetch request.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseCursor<Self> {
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> ColumnCursor<Self> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
@@ -144,7 +256,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// Returns an array of values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn)
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try String.fetchAll(db, request) // [String]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -160,7 +272,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn)
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let name = try String.fetchOne(db, request) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -177,7 +289,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
/// Returns a cursor over values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try String.fetchCursor(db, "SELECT name FROM ...") // DatabaseCursor<String>
|
||||
/// let names = try String.fetchCursor(db, "SELECT name FROM ...") // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
@@ -194,7 +306,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> ColumnCursor<Self> {
|
||||
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
@@ -228,3 +340,143 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Swift's Optional comes with built-in methods that allow to fetch cursors
|
||||
/// and arrays of optional DatabaseValueConvertible:
|
||||
///
|
||||
/// try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("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
|
||||
|
||||
/// Returns a cursor over optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchCursor(statement) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableColumnCursor<Wrapped> {
|
||||
return try NullableColumnCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchAll(statement) // [String?]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
|
||||
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching From Request
|
||||
|
||||
/// Returns a cursor over optional values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try Optional<String>.fetchCursor(db, request) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - requet: A fetch request.
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> NullableColumnCursor<Wrapped> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try Optional<String>.fetchAll(db, request) // [String?]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ request: Request) throws -> [Wrapped?] {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchAll(statement, adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching From SQL
|
||||
|
||||
/// Returns a cursor over optional values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableColumnCursor<Wrapped> {
|
||||
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String?]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - parameter arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
|
||||
return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,23 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// Data is convertible to and from DatabaseValue.
|
||||
extension Data : DatabaseValueConvertible {
|
||||
extension Data : DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
if let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) {
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
self.init(bytes: bytes, count: count) // copy bytes
|
||||
} else {
|
||||
self.init()
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
// SQLite cant' store zero-length blobs.
|
||||
guard count > 0 else {
|
||||
return .null
|
||||
}
|
||||
return DatabaseValue(storage: .blob(self))
|
||||
}
|
||||
|
||||
|
||||
+15
-1
@@ -13,7 +13,7 @@ import Foundation
|
||||
///
|
||||
/// // ... then the ReferenceConvertible type can freely adopt DatabaseValueConvertible:
|
||||
/// extension Foo : DatabaseValueConvertible { /* empty */ }
|
||||
extension ReferenceConvertible where Self: DatabaseValueConvertible, Self.ReferenceType: DatabaseValueConvertible {
|
||||
extension DatabaseValueConvertible where Self: ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
@@ -25,3 +25,17 @@ extension ReferenceConvertible where Self: DatabaseValueConvertible, Self.Refere
|
||||
return ReferenceType.fromDatabaseValue(dbValue).flatMap { cast($0) }
|
||||
}
|
||||
}
|
||||
|
||||
public extension DatabaseValueConvertible where Self: Decodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible {
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
// Preserve custom database decoding
|
||||
return ReferenceType.fromDatabaseValue(databaseValue).flatMap { cast($0) }
|
||||
}
|
||||
}
|
||||
|
||||
public extension DatabaseValueConvertible where Self: Encodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible {
|
||||
public var databaseValue: DatabaseValue {
|
||||
// Preserve custom database encoding
|
||||
return (self as! ReferenceType).databaseValue
|
||||
}
|
||||
}
|
||||
@@ -3,26 +3,75 @@ import Foundation
|
||||
/// NSDate is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
extension NSDate : DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// Returns a database value that contains the date encoded as
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return storageDateFormatter.string(from: self as Date).databaseValue
|
||||
return (self as Date).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a Date initialized from *dbValue*, if possible.
|
||||
/// Returns a date initialized from dbValue, if possible.
|
||||
///
|
||||
/// If database value contains a number, that number is interpreted as a
|
||||
/// timeinterval since 00:00:00 UTC on 1 January 1970.
|
||||
///
|
||||
/// If database value contains a string, that string is interpreted as a
|
||||
/// [SQLite date](https://sqlite.org/lang_datefunc.html) in the UTC time
|
||||
/// zone. Nil is returned if the date string does not contain at least the
|
||||
/// year, month and day components. Other components (minutes, etc.)
|
||||
/// are set to zero if missing.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
if let databaseDateComponents = DatabaseDateComponents.fromDatabaseValue(dbValue) {
|
||||
return cast(fromDatabaseDateComponents(databaseDateComponents))
|
||||
guard let date = Date.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
}
|
||||
if let julianDayNumber = Double.fromDatabaseValue(dbValue) {
|
||||
return cast(fromJulianDayNumber(julianDayNumber))
|
||||
return cast(date)
|
||||
}
|
||||
}
|
||||
|
||||
/// Date is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
extension Date : DatabaseValueConvertible {
|
||||
/// Returns a database value that contains the date encoded as
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return storageDateFormatter.string(from: self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a date initialized from dbValue, if possible.
|
||||
///
|
||||
/// If database value contains a number, that number is interpreted as a
|
||||
/// timeinterval since 00:00:00 UTC on 1 January 1970.
|
||||
///
|
||||
/// If database value contains a string, that string is interpreted as a
|
||||
/// [SQLite date](https://sqlite.org/lang_datefunc.html) in the UTC time
|
||||
/// zone. Nil is returned if the date string does not contain at least the
|
||||
/// year, month and day components. Other components (minutes, etc.)
|
||||
/// are set to zero if missing.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Date? {
|
||||
if let databaseDateComponents = DatabaseDateComponents.fromDatabaseValue(dbValue) {
|
||||
return Date(databaseDateComponents: databaseDateComponents)
|
||||
}
|
||||
if let timestamp = Double.fromDatabaseValue(dbValue) {
|
||||
return Date(timeIntervalSince1970: timestamp)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private static func fromJulianDayNumber(_ julianDayNumber: Double) -> Date? {
|
||||
private init?(databaseDateComponents: DatabaseDateComponents) {
|
||||
guard databaseDateComponents.format.hasYMDComponents else {
|
||||
// Refuse to turn hours without any date information into Date:
|
||||
return nil
|
||||
}
|
||||
guard let date = UTCCalendar.date(from: databaseDateComponents.dateComponents) else {
|
||||
return nil
|
||||
}
|
||||
self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate)
|
||||
}
|
||||
|
||||
/// Creates a date from a [Julian Day](https://en.wikipedia.org/wiki/Julian_day).
|
||||
public init?(julianDay: Double) {
|
||||
// Conversion uses the same algorithm as SQLite: https://www.sqlite.org/src/artifact/8ec787fed4929d8c
|
||||
let JD = Int64(julianDayNumber * 86400000)
|
||||
// TODO: check for overflows one day, and return nil when computation can't complete.
|
||||
let JD = Int64(julianDay * 86400000)
|
||||
let Z = Int(((JD + 43200000)/86400000))
|
||||
var A = Int(((Double(Z) - 1867216.25)/36524.25))
|
||||
A = Z + 1 + A - (A/4)
|
||||
@@ -52,22 +101,13 @@ extension NSDate : DatabaseValueConvertible {
|
||||
dateComponents.second = Int(second)
|
||||
dateComponents.nanosecond = Int((second - Double(Int(second))) * 1.0e9)
|
||||
|
||||
return UTCCalendar.date(from: dateComponents)!
|
||||
}
|
||||
|
||||
private static func fromDatabaseDateComponents(_ databaseDateComponents: DatabaseDateComponents) -> Date? {
|
||||
guard databaseDateComponents.format.hasYMDComponents else {
|
||||
// Refuse to turn hours without any date information into Date:
|
||||
guard let date = UTCCalendar.date(from: dateComponents) else {
|
||||
return nil
|
||||
}
|
||||
return UTCCalendar.date(from: databaseDateComponents.dateComponents)!
|
||||
self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate)
|
||||
}
|
||||
}
|
||||
|
||||
/// Date is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
extension Date : DatabaseValueConvertible { }
|
||||
|
||||
/// The DatabaseDate date formatter for stored dates.
|
||||
private let storageDateFormatter: DateFormatter = {
|
||||
let formatter = DateFormatter()
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer {
|
||||
let dbValue: DatabaseValue
|
||||
let codingPath: [CodingKey]
|
||||
|
||||
/// Decodes a null value.
|
||||
///
|
||||
/// - returns: Whether the encountered value was null.
|
||||
func decodeNil() -> Bool {
|
||||
return dbValue.isNull
|
||||
}
|
||||
|
||||
/// Decodes a single value of the given type.
|
||||
///
|
||||
/// - parameter type: The type to decode as.
|
||||
/// - returns: A value of the requested type.
|
||||
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type.
|
||||
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
|
||||
func decode(_ type: Bool.Type) throws -> Bool { return dbValue.losslessConvert() }
|
||||
func decode(_ type: Int.Type) throws -> Int { return dbValue.losslessConvert() }
|
||||
func decode(_ type: Int8.Type) throws -> Int8 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: Int16.Type) throws -> Int16 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: Int32.Type) throws -> Int32 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: Int64.Type) throws -> Int64 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: UInt.Type) throws -> UInt { return dbValue.losslessConvert() }
|
||||
func decode(_ type: UInt8.Type) throws -> UInt8 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: UInt16.Type) throws -> UInt16 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: UInt32.Type) throws -> UInt32 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: UInt64.Type) throws -> UInt64 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: Float.Type) throws -> Float { return dbValue.losslessConvert() }
|
||||
func decode(_ type: Double.Type) throws -> Double { return dbValue.losslessConvert() }
|
||||
func decode(_ type: String.Type) throws -> String { return dbValue.losslessConvert() }
|
||||
|
||||
/// Decodes a single value of the given type.
|
||||
///
|
||||
/// - parameter type: The type to decode as.
|
||||
/// - returns: A value of the requested type.
|
||||
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type.
|
||||
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
|
||||
func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
|
||||
if let type = T.self as? DatabaseValueConvertible.Type {
|
||||
// Prefer DatabaseValueConvertible decoding over Decodable.
|
||||
// This allows custom database decoding, such as decoding Date from
|
||||
// String, for example.
|
||||
return type.fromDatabaseValue(dbValue) as! T
|
||||
} else {
|
||||
return try T(from: DatabaseValueDecoder(dbValue: dbValue, codingPath: codingPath))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct DatabaseValueDecoder: Decoder {
|
||||
let dbValue: DatabaseValue
|
||||
|
||||
init(dbValue: DatabaseValue, codingPath: [CodingKey]) {
|
||||
self.dbValue = dbValue
|
||||
self.codingPath = codingPath
|
||||
}
|
||||
|
||||
// Decoder
|
||||
let codingPath: [CodingKey]
|
||||
var userInfo: [CodingUserInfoKey : Any] { return [:] }
|
||||
|
||||
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
|
||||
throw DecodingError.typeMismatch(
|
||||
type,
|
||||
DecodingError.Context(codingPath: codingPath, debugDescription: "keyed decoding is not supported"))
|
||||
}
|
||||
|
||||
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
|
||||
throw DecodingError.typeMismatch(
|
||||
UnkeyedDecodingContainer.self,
|
||||
DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported"))
|
||||
}
|
||||
|
||||
func singleValueContainer() throws -> SingleValueDecodingContainer {
|
||||
return DatabaseValueDecodingContainer(dbValue: dbValue, codingPath: codingPath)
|
||||
}
|
||||
}
|
||||
|
||||
public extension DatabaseValueConvertible where Self: Decodable {
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
return try? self.init(from: DatabaseValueDecoder(dbValue: databaseValue, codingPath: []))
|
||||
}
|
||||
}
|
||||
|
||||
public extension DatabaseValueConvertible where Self: Decodable & RawRepresentable, Self.RawValue: DatabaseValueConvertible {
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
// Preserve custom database decoding
|
||||
return RawValue.fromDatabaseValue(databaseValue).flatMap { self.init(rawValue: $0) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer {
|
||||
let encode: (DatabaseValue) -> Void
|
||||
|
||||
var codingPath: [CodingKey] { return [] }
|
||||
|
||||
/// Encodes a null value.
|
||||
///
|
||||
/// - throws: `EncodingError.invalidValue` if a null value is invalid in the current context for this format.
|
||||
/// - precondition: May not be called after a previous `self.encode(_:)` call.
|
||||
mutating func encodeNil() throws { encode(.null) }
|
||||
|
||||
/// Encodes a single value of the given type.
|
||||
///
|
||||
/// - parameter value: The value to encode.
|
||||
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
|
||||
/// - precondition: May not be called after a previous `self.encode(_:)` call.
|
||||
mutating func encode(_ value: Bool) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: Int) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: Int8) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: Int16) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: Int32) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: Int64) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: UInt) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: UInt8) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: UInt16) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: UInt32) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: UInt64) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: Float) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: Double) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: String) throws { encode(value.databaseValue) }
|
||||
|
||||
/// Encodes a single value of the given type.
|
||||
///
|
||||
/// - parameter value: The value to encode.
|
||||
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
|
||||
/// - precondition: May not be called after a previous `self.encode(_:)` call.
|
||||
mutating func encode<T>(_ value: T) throws where T : Encodable {
|
||||
if let dbValueConvertible = value as? DatabaseValueConvertible {
|
||||
// Prefer DatabaseValueConvertible encoding over Decodable.
|
||||
// This allows us to encode Date as String, for example.
|
||||
encode(dbValueConvertible.databaseValue)
|
||||
} else {
|
||||
try value.encode(to: DatabaseValueEncoder(encode: encode))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct DatabaseValueEncoder : Encoder {
|
||||
let encode: (DatabaseValue) -> Void
|
||||
|
||||
/// The path of coding keys taken to get to this point in encoding.
|
||||
/// A `nil` value indicates an unkeyed container.
|
||||
var codingPath: [CodingKey] { return [] }
|
||||
|
||||
/// Any contextual information set by the user for encoding.
|
||||
var userInfo: [CodingUserInfoKey : Any] = [:]
|
||||
|
||||
init(encode: @escaping (DatabaseValue) -> Void) {
|
||||
self.encode = encode
|
||||
}
|
||||
|
||||
/// Returns an encoding container appropriate for holding multiple values keyed by the given key type.
|
||||
///
|
||||
/// - parameter type: The key type to use for the container.
|
||||
/// - returns: A new keyed encoding container.
|
||||
/// - precondition: May not be called after a prior `self.unkeyedContainer()` call.
|
||||
/// - 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")
|
||||
}
|
||||
|
||||
/// Returns an encoding container appropriate for holding multiple unkeyed values.
|
||||
///
|
||||
/// - returns: A new empty unkeyed container.
|
||||
/// - precondition: May not be called after a prior `self.container(keyedBy:)` call.
|
||||
/// - 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")
|
||||
}
|
||||
|
||||
/// Returns an encoding container appropriate for holding a single primitive value.
|
||||
///
|
||||
/// - returns: A new empty single value container.
|
||||
/// - precondition: May not be called after a prior `self.container(keyedBy:)` call.
|
||||
/// - precondition: May not be called after a prior `self.unkeyedContainer()` call.
|
||||
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
|
||||
func singleValueContainer() -> SingleValueEncodingContainer {
|
||||
return DatabaseValueEncodingContainer(encode: encode)
|
||||
}
|
||||
}
|
||||
|
||||
public extension DatabaseValueConvertible where Self: Encodable {
|
||||
public var databaseValue: DatabaseValue {
|
||||
var dbValue: DatabaseValue! = nil
|
||||
let encoder = DatabaseValueEncoder(encode: { dbValue = $0 })
|
||||
try! self.encode(to: encoder)
|
||||
return dbValue
|
||||
}
|
||||
}
|
||||
|
||||
public extension DatabaseValueConvertible where Self: Encodable & RawRepresentable, Self.RawValue: DatabaseValueConvertible {
|
||||
public var databaseValue: DatabaseValue {
|
||||
// Preserve custom database encoding
|
||||
return rawValue.databaseValue
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -10,7 +10,7 @@
|
||||
///
|
||||
/// // ... then the RawRepresentable type can freely adopt DatabaseValueConvertible:
|
||||
/// extension Color : DatabaseValueConvertible { /* empty */ }
|
||||
extension RawRepresentable where Self: DatabaseValueConvertible, Self.RawValue: DatabaseValueConvertible {
|
||||
extension DatabaseValueConvertible where Self: RawRepresentable, Self.RawValue: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
@@ -1,5 +1,7 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
// MARK: - Value Types
|
||||
@@ -114,17 +116,64 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns an Int initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64):
|
||||
return Int(exactly: int64)
|
||||
case .double(let double):
|
||||
guard double >= Double(Int64.min) else { return nil }
|
||||
guard double < Double(Int64.max) else { return nil }
|
||||
return Int(exactly: Int64(double))
|
||||
default:
|
||||
return nil
|
||||
return Int64.fromDatabaseValue(dbValue).flatMap { Int(exactly: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Int8 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = Int8(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalError("could not convert database value \(int64) to Int8")
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an Int8 initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int8? {
|
||||
return Int64.fromDatabaseValue(dbValue).flatMap { Int8(exactly: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Int16 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = Int16(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalError("could not convert database value \(int64) to Int16")
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an Int16 initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int16? {
|
||||
return Int64.fromDatabaseValue(dbValue).flatMap { Int16(exactly: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Int32 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -151,16 +200,7 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns an Int32 initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int32? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64):
|
||||
return Int32(exactly: int64)
|
||||
case .double(let double):
|
||||
guard double >= Double(Int64.min) else { return nil }
|
||||
guard double < Double(Int64.max) else { return nil }
|
||||
return Int32(exactly: Int64(double))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
return Int64.fromDatabaseValue(dbValue).flatMap { Int32(exactly: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,6 +236,146 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = UInt(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalError("could not convert database value \(int64) to UInt")
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an Int initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt? {
|
||||
return Int64.fromDatabaseValue(dbValue).flatMap { UInt(exactly: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt8 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = UInt8(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalError("could not convert database value \(int64) to UInt8")
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an UInt8 initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt8? {
|
||||
return Int64.fromDatabaseValue(dbValue).flatMap { UInt8(exactly: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt16 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = UInt16(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalError("could not convert database value \(int64) to UInt16")
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an UInt16 initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt16? {
|
||||
return Int64.fromDatabaseValue(dbValue).flatMap { UInt16(exactly: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt32 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = UInt32(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalError("could not convert database value \(int64) to UInt32")
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an UInt32 initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt32? {
|
||||
return Int64.fromDatabaseValue(dbValue).flatMap { UInt32(exactly: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt64 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = UInt64(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalError("could not convert database value \(int64) to UInt64")
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an UInt64 initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt64? {
|
||||
return Int64.fromDatabaseValue(dbValue).flatMap { UInt64(exactly: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Double adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
extension Double: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
@@ -298,7 +478,7 @@ extension DatabaseFunction {
|
||||
/// capitalized:
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.capitalized)
|
||||
/// let request = Player.select(nameColumn.capitalized)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
public static let capitalize = DatabaseFunction("swiftCapitalizedString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
@@ -317,7 +497,7 @@ extension DatabaseFunction {
|
||||
/// lowercased:
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.lowercased())
|
||||
/// let request = Player.select(nameColumn.lowercased())
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
public static let lowercase = DatabaseFunction("swiftLowercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
@@ -336,7 +516,7 @@ extension DatabaseFunction {
|
||||
/// uppercased:
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.uppercased())
|
||||
/// let request = Player.select(nameColumn.uppercased())
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
public static let uppercase = DatabaseFunction("swiftUppercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
@@ -357,7 +537,7 @@ extension DatabaseFunction {
|
||||
/// localizedCapitalized:
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.localizedCapitalized)
|
||||
/// let request = Player.select(nameColumn.localizedCapitalized)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
|
||||
public static let localizedCapitalize = DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { dbValues in
|
||||
@@ -377,7 +557,7 @@ extension DatabaseFunction {
|
||||
/// localizedLowercased:
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.localizedLowercased)
|
||||
/// let request = Player.select(nameColumn.localizedLowercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
|
||||
public static let localizedLowercase = DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
@@ -397,7 +577,7 @@ extension DatabaseFunction {
|
||||
/// localizedUppercased:
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.localizedUppercased)
|
||||
/// let request = Player.select(nameColumn.localizedUppercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
|
||||
public static let localizedUppercase = DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
@@ -433,7 +613,7 @@ extension DatabaseCollation {
|
||||
///
|
||||
/// let collationName = DatabaseCollation.caseInsensitiveCompare.name
|
||||
/// dbQueue.execute(
|
||||
/// "CREATE TABLE persons (" +
|
||||
/// "CREATE TABLE players (" +
|
||||
/// "name TEXT COLLATE \(collationName)" +
|
||||
/// ")"
|
||||
/// )
|
||||
@@ -451,7 +631,7 @@ extension DatabaseCollation {
|
||||
///
|
||||
/// let collationName = DatabaseCollation.caseInsensitiveCompare.name
|
||||
/// dbQueue.execute(
|
||||
/// "CREATE TABLE persons (" +
|
||||
/// "CREATE TABLE players (" +
|
||||
/// "name TEXT COLLATE \(collationName)" +
|
||||
/// ")"
|
||||
/// )
|
||||
@@ -469,7 +649,7 @@ extension DatabaseCollation {
|
||||
///
|
||||
/// let collationName = DatabaseCollation.localizedCaseInsensitiveCompare.name
|
||||
/// dbQueue.execute(
|
||||
/// "CREATE TABLE persons (" +
|
||||
/// "CREATE TABLE players (" +
|
||||
/// "name TEXT COLLATE \(collationName)" +
|
||||
/// ")"
|
||||
/// )
|
||||
@@ -487,7 +667,7 @@ extension DatabaseCollation {
|
||||
///
|
||||
/// let collationName = DatabaseCollation.localizedCompare.name
|
||||
/// dbQueue.execute(
|
||||
/// "CREATE TABLE persons (" +
|
||||
/// "CREATE TABLE players (" +
|
||||
/// "name TEXT COLLATE \(collationName)" +
|
||||
/// ")"
|
||||
/// )
|
||||
@@ -505,7 +685,7 @@ extension DatabaseCollation {
|
||||
///
|
||||
/// let collationName = DatabaseCollation.localizedStandardCompare.name
|
||||
/// dbQueue.execute(
|
||||
/// "CREATE TABLE persons (" +
|
||||
/// "CREATE TABLE players (" +
|
||||
/// "name TEXT COLLATE \(collationName)" +
|
||||
/// ")"
|
||||
/// )
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+32
-24
@@ -95,7 +95,7 @@ public struct FTS4 : VirtualTableModule {
|
||||
case .synchronized(let contentTable):
|
||||
// https://www.sqlite.org/fts3.html#_external_content_fts4_tables_
|
||||
|
||||
let rowIDColumn = (try? db.primaryKey(contentTable))??.rowIDColumn ?? "rowid"
|
||||
let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name
|
||||
let ftsTable = tableName.quotedDatabaseIdentifier
|
||||
let content = contentTable.quotedDatabaseIdentifier
|
||||
let indexedColumns = definition.columns.map { $0.name }
|
||||
@@ -110,25 +110,20 @@ public struct FTS4 : VirtualTableModule {
|
||||
|
||||
let oldRowID = "old.\(rowIDColumn.quotedDatabaseIdentifier)"
|
||||
|
||||
try db.execute(
|
||||
"CREATE TRIGGER \("__\(contentTable)_bu".quotedDatabaseIdentifier) BEFORE UPDATE ON \(content) BEGIN " +
|
||||
"DELETE FROM \(ftsTable) WHERE docid=\(oldRowID); " +
|
||||
"END")
|
||||
|
||||
try db.execute(
|
||||
"CREATE TRIGGER \("__\(contentTable)_bd".quotedDatabaseIdentifier) BEFORE DELETE ON \(content) BEGIN " +
|
||||
"DELETE FROM \(ftsTable) WHERE docid=\(oldRowID); " +
|
||||
"END")
|
||||
|
||||
try db.execute(
|
||||
"CREATE TRIGGER \("__\(contentTable)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN " +
|
||||
"INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns)); " +
|
||||
"END")
|
||||
|
||||
try db.execute(
|
||||
"CREATE TRIGGER \("__\(contentTable)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN " +
|
||||
"INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns)); " +
|
||||
"END")
|
||||
try db.execute("""
|
||||
CREATE TRIGGER \("__\(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
|
||||
DELETE FROM \(ftsTable) WHERE docid=\(oldRowID);
|
||||
END;
|
||||
CREATE TRIGGER \("__\(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
|
||||
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns));
|
||||
END;
|
||||
""")
|
||||
|
||||
// https://www.sqlite.org/fts3.html#*fts4rebuidcmd
|
||||
|
||||
@@ -247,7 +242,7 @@ public final class FTS4TableDefinition {
|
||||
///
|
||||
/// You get instances of this class when you create an FTS4 table:
|
||||
///
|
||||
/// try db.create(virtualTable: "persons", using: FTS4()) { t in
|
||||
/// try db.create(virtualTable: "documents", using: FTS4()) { t in
|
||||
/// t.column("content") // FTS4ColumnDefinition
|
||||
/// }
|
||||
///
|
||||
@@ -266,7 +261,7 @@ public final class FTS4ColumnDefinition {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// Excludes the column from the full-text index.
|
||||
///
|
||||
/// try db.create(virtualTable: "persons", using: FTS4()) { t in
|
||||
/// try db.create(virtualTable: "documents", using: FTS4()) { t in
|
||||
/// t.column("a")
|
||||
/// t.column("b").notIndexed()
|
||||
/// }
|
||||
@@ -274,6 +269,7 @@ public final class FTS4ColumnDefinition {
|
||||
/// See https://www.sqlite.org/fts3.html#the_notindexed_option
|
||||
///
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
/// :nodoc:
|
||||
@discardableResult
|
||||
public func notIndexed() -> Self {
|
||||
// notindexed FTS4 option was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
|
||||
@@ -284,7 +280,7 @@ public final class FTS4ColumnDefinition {
|
||||
#else
|
||||
/// Excludes the column from the full-text index.
|
||||
///
|
||||
/// try db.create(virtualTable: "persons", using: FTS4()) { t in
|
||||
/// try db.create(virtualTable: "documents", using: FTS4()) { t in
|
||||
/// t.column("a")
|
||||
/// t.column("b").notIndexed()
|
||||
/// }
|
||||
@@ -304,7 +300,7 @@ public final class FTS4ColumnDefinition {
|
||||
|
||||
/// Uses the column as the Int32 language id hidden column.
|
||||
///
|
||||
/// try db.create(virtualTable: "persons", using: FTS4()) { t in
|
||||
/// try db.create(virtualTable: "documents", using: FTS4()) { t in
|
||||
/// t.column("a")
|
||||
/// t.column("lid").asLanguageId()
|
||||
/// }
|
||||
@@ -318,3 +314,15 @@ public final class FTS4ColumnDefinition {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
/// Deletes the synchronization triggers for a synchronized FTS4 table
|
||||
public func dropFTS4SynchronizationTriggers(forTable tableName: String) throws {
|
||||
try execute("""
|
||||
DROP TRIGGER IF EXISTS \("__\(tableName)_bu".quotedDatabaseIdentifier);
|
||||
DROP TRIGGER IF EXISTS \("__\(tableName)_bd".quotedDatabaseIdentifier);
|
||||
DROP TRIGGER IF EXISTS \("__\(tableName)_au".quotedDatabaseIdentifier);
|
||||
DROP TRIGGER IF EXISTS \("__\(tableName)_ai".quotedDatabaseIdentifier);
|
||||
""")
|
||||
}
|
||||
}
|
||||
+45
-29
@@ -62,7 +62,7 @@
|
||||
}
|
||||
case .synchronized(let contentTable):
|
||||
arguments.append("content=\(contentTable.sqlExpression.sql)")
|
||||
if let rowIDColumn = try db.primaryKey(contentTable)?.rowIDColumn {
|
||||
if let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn {
|
||||
arguments.append("content_rowid=\(rowIDColumn.sqlExpression.sql)")
|
||||
}
|
||||
}
|
||||
@@ -93,7 +93,7 @@
|
||||
case .synchronized(let contentTable):
|
||||
// https://sqlite.org/fts5.html#external_content_tables
|
||||
|
||||
let rowIDColumn = (try? db.primaryKey(contentTable))??.rowIDColumn ?? "rowid"
|
||||
let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name
|
||||
let ftsTable = tableName.quotedDatabaseIdentifier
|
||||
let content = contentTable.quotedDatabaseIdentifier
|
||||
let indexedColumns = definition.columns.map { $0.name }
|
||||
@@ -110,21 +110,18 @@
|
||||
.map { "old.\($0.quotedDatabaseIdentifier)" }
|
||||
.joined(separator: ", ")
|
||||
|
||||
try db.execute(
|
||||
"CREATE TRIGGER \("__\(contentTable)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN " +
|
||||
"INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); " +
|
||||
"END")
|
||||
|
||||
try db.execute(
|
||||
"CREATE TRIGGER \("__\(contentTable)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN " +
|
||||
"INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); " +
|
||||
"END")
|
||||
|
||||
try db.execute(
|
||||
"CREATE TRIGGER \("__\(contentTable)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN " +
|
||||
"INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); " +
|
||||
"INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); " +
|
||||
"END")
|
||||
try db.execute("""
|
||||
CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
|
||||
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
|
||||
END;
|
||||
CREATE TRIGGER \("__\(tableName)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN
|
||||
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
|
||||
END;
|
||||
CREATE TRIGGER \("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
|
||||
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
|
||||
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
|
||||
END;
|
||||
""")
|
||||
|
||||
// https://sqlite.org/fts5.html#the_rebuild_command
|
||||
|
||||
@@ -132,17 +129,25 @@
|
||||
}
|
||||
}
|
||||
|
||||
static func api(_ db: Database) -> UnsafePointer<fts5_api>? {
|
||||
do {
|
||||
return try Data.fetchOne(db, "SELECT fts5()").flatMap { data in
|
||||
guard data.count == MemoryLayout<UnsafePointer<fts5_api>>.size else {
|
||||
return nil
|
||||
}
|
||||
return data.withUnsafeBytes { $0.pointee }
|
||||
}
|
||||
} catch {
|
||||
return nil
|
||||
static func api(_ db: Database) -> UnsafePointer<fts5_api> {
|
||||
let sqliteConnection = db.sqliteConnection
|
||||
var statement: SQLiteStatement? = nil
|
||||
var api: UnsafePointer<fts5_api>? = nil
|
||||
let type: StaticString = "fts5_api_ptr"
|
||||
|
||||
let code = sqlite3_prepare_v3(db.sqliteConnection, "SELECT fts5(?)", -1, 0, &statement, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
fatalError("FTS5 is not available")
|
||||
}
|
||||
defer { sqlite3_finalize(statement) }
|
||||
type.utf8Start.withMemoryRebound(to: Int8.self, capacity: type.utf8CodeUnitCount) { typePointer in
|
||||
_ = sqlite3_bind_pointer(statement, 1, &api, typePointer, nil)
|
||||
}
|
||||
sqlite3_step(statement)
|
||||
guard let result = api else {
|
||||
fatalError("FTS5 is not available")
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -279,7 +284,7 @@
|
||||
///
|
||||
/// You get instances of this class when you create an FTS5 table:
|
||||
///
|
||||
/// try db.create(virtualTable: "persons", using: FTS5()) { t in
|
||||
/// try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
/// t.column("content") // FTS5ColumnDefinition
|
||||
/// }
|
||||
///
|
||||
@@ -295,7 +300,7 @@
|
||||
|
||||
/// Excludes the column from the full-text index.
|
||||
///
|
||||
/// try db.create(virtualTable: "persons", using: FTS5()) { t in
|
||||
/// try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
/// t.column("a")
|
||||
/// t.column("b").notIndexed()
|
||||
/// }
|
||||
@@ -314,4 +319,15 @@
|
||||
/// The FTS5 rank column
|
||||
public static let rank = Column("rank")
|
||||
}
|
||||
|
||||
extension Database {
|
||||
/// Deletes the synchronization triggers for a synchronized FTS5 table
|
||||
public func dropFTS5SynchronizationTriggers(forTable tableName: String) throws {
|
||||
try execute("""
|
||||
DROP TRIGGER IF EXISTS \("__\(tableName)_ai".quotedDatabaseIdentifier);
|
||||
DROP TRIGGER IF EXISTS \("__\(tableName)_ad".quotedDatabaseIdentifier);
|
||||
DROP TRIGGER IF EXISTS \("__\(tableName)_au".quotedDatabaseIdentifier);
|
||||
""")
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -38,7 +38,7 @@
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Custom FTS5 Tokenizers
|
||||
// MARK: - FTS5
|
||||
|
||||
private class FTS5TokenizerConstructor {
|
||||
let db: Database
|
||||
@@ -55,10 +55,7 @@
|
||||
/// class MyTokenizer : FTS5CustomTokenizer { ... }
|
||||
/// db.add(tokenizer: MyTokenizer.self)
|
||||
public func add<Tokenizer: FTS5CustomTokenizer>(tokenizer: Tokenizer.Type) {
|
||||
guard let api = FTS5.api(self) else {
|
||||
// Assume a GRDB bug or an SQLite miscompilation: there is no point throwing any error.
|
||||
fatalError("FTS5 is not enabled")
|
||||
}
|
||||
let api = FTS5.api(self)
|
||||
|
||||
// Swift won't let the @convention(c) xCreate() function below create
|
||||
// an instance of the generic Tokenizer type.
|
||||
|
||||
@@ -44,6 +44,19 @@
|
||||
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
|
||||
}
|
||||
|
||||
/// Creates a pattern that matches a contiguous string prefix; returns
|
||||
/// nil if no pattern could be built.
|
||||
///
|
||||
/// FTS5Pattern(matchingPrefixPhrase: "") // nil
|
||||
/// FTS5Pattern(matchingPrefixPhrase: "foo bar") // ^"foo bar"
|
||||
///
|
||||
/// - parameter string: The string to turn into an FTS5 pattern
|
||||
public init?(matchingPrefixPhrase string: String) {
|
||||
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil }
|
||||
guard !tokens.isEmpty else { return nil }
|
||||
try? self.init(rawPattern: "^\"" + tokens.joined(separator: " ") + "\"")
|
||||
}
|
||||
|
||||
init(rawPattern: String, allowedColumns: [String] = []) throws {
|
||||
// Correctness above all: use SQLite to validate the pattern.
|
||||
//
|
||||
@@ -77,6 +90,8 @@
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - FTS5
|
||||
|
||||
/// Creates a pattern from a raw pattern string; throws DatabaseError on
|
||||
/// invalid syntax.
|
||||
///
|
||||
|
||||
@@ -106,8 +106,9 @@
|
||||
}
|
||||
|
||||
extension Database {
|
||||
/// MARK: - FTS5 Tokenizers
|
||||
|
||||
// MARK: - FTS5
|
||||
|
||||
/// Private type that makes a pre-registered FTS5 tokenizer available
|
||||
/// through the FTS5Tokenizer protocol.
|
||||
private final class FTS5RegisteredTokenizer : FTS5Tokenizer {
|
||||
@@ -188,9 +189,7 @@
|
||||
/// }
|
||||
/// }
|
||||
public func makeTokenizer(_ descriptor: FTS5TokenizerDescriptor) throws -> FTS5Tokenizer {
|
||||
guard let api = FTS5.api(self) else {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "FTS5 API not found")
|
||||
}
|
||||
let api = FTS5.api(self)
|
||||
|
||||
let xTokenizerPointer: UnsafeMutablePointer<fts5_tokenizer> = .allocate(capacity: 1)
|
||||
defer { xTokenizerPointer.deallocate(capacity: 1) }
|
||||
|
||||
@@ -48,8 +48,8 @@ extension RowConvertible where Self: TableMapping {
|
||||
public static func fetch(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) -> Any { preconditionFailure() }
|
||||
}
|
||||
|
||||
@available(*, unavailable, message:"DatabaseSequence has been replaced by DatabaseCursor.")
|
||||
@available(*, unavailable, message:"DatabaseSequence has been replaced by Cursor.")
|
||||
public struct DatabaseSequence<T> { }
|
||||
|
||||
@available(*, unavailable, message:"DatabaseIterator has been replaced by DatabaseCursor.")
|
||||
@available(*, unavailable, message:"DatabaseIterator has been replaced by Cursor.")
|
||||
public struct DatabaseIterator<T> { }
|
||||
@@ -4,6 +4,6 @@ extension Database {
|
||||
}
|
||||
|
||||
extension DatabaseValue {
|
||||
@available(*, unavailable, message:"DatabaseSequence has been replaced by DatabaseCursor.")
|
||||
@available(*, unavailable, message:"DatabaseSequence has been replaced by Cursor.")
|
||||
public func value() -> Any { preconditionFailure() }
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
extension Row {
|
||||
@available(*, unavailable, message:"use subscript instead: row[index]")
|
||||
public func value(atIndex index: Int) -> DatabaseValueConvertible? { preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message:"use subscript instead: row[index]")
|
||||
public func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value? { preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message:"use subscript instead: row[index]")
|
||||
public func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value { preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message:"use subscript instead: row[column]")
|
||||
public func value(named name: String) -> DatabaseValueConvertible? { preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message:"use subscript instead: row[column]")
|
||||
public func value<Value: DatabaseValueConvertible>(named name: String) -> Value? { preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message:"use subscript instead: row[column]")
|
||||
public func value<Value: DatabaseValueConvertible>(named name: String) -> Value { preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message:"use subscript instead: row[column]")
|
||||
public func value(_ column: Column) -> DatabaseValueConvertible? { preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message:"use subscript instead: row[column]")
|
||||
public func value<Value: DatabaseValueConvertible>(_ column: Column) -> Value? { preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message:"use subscript instead: row[column]")
|
||||
public func value<Value: DatabaseValueConvertible>(_ column: Column) -> Value { preconditionFailure() }
|
||||
}
|
||||
@@ -10,29 +10,31 @@
|
||||
/// var migrator = DatabaseMigrator()
|
||||
///
|
||||
/// // v1.0 database
|
||||
/// migrator.registerMigration("createPersons") { db in
|
||||
/// try db.execute(
|
||||
/// "CREATE TABLE persons (" +
|
||||
/// "id INTEGER PRIMARY KEY, " +
|
||||
/// "creationDate TEXT, " +
|
||||
/// "name TEXT NOT NULL" +
|
||||
/// ")")
|
||||
/// migrator.registerMigration("createAuthors") { db in
|
||||
/// try db.execute("""
|
||||
/// CREATE TABLE authors (
|
||||
/// id INTEGER PRIMARY KEY,
|
||||
/// creationDate TEXT,
|
||||
/// name TEXT NOT NULL
|
||||
/// )
|
||||
/// """)
|
||||
/// }
|
||||
///
|
||||
/// migrator.registerMigration("createBooks") { db in
|
||||
/// try db.execute(
|
||||
/// "CREATE TABLE books (" +
|
||||
/// "uuid TEXT PRIMARY KEY, " +
|
||||
/// "ownerID INTEGER NOT NULL " +
|
||||
/// " REFERENCES persons(id) " +
|
||||
/// " ON DELETE CASCADE ON UPDATE CASCADE, " +
|
||||
/// "title TEXT NOT NULL" +
|
||||
/// ")")
|
||||
/// try db.execute("""
|
||||
/// CREATE TABLE books (
|
||||
/// uuid TEXT PRIMARY KEY,
|
||||
/// authorID INTEGER NOT NULL
|
||||
/// REFERENCES authors(id)
|
||||
/// ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
/// title TEXT NOT NULL
|
||||
/// )
|
||||
/// """)
|
||||
/// }
|
||||
///
|
||||
/// // v2.0 database
|
||||
/// migrator.registerMigration("AddAgeToPersons") { db in
|
||||
/// try db.execute("ALTER TABLE persons ADD COLUMN age INT")
|
||||
/// migrator.registerMigration("AddBirthYearToAuthors") { db in
|
||||
/// try db.execute("ALTER TABLE authors ADD COLUMN birthYear INT")
|
||||
/// }
|
||||
///
|
||||
/// try migrator.migrate(dbQueue)
|
||||
@@ -44,13 +46,14 @@ public struct DatabaseMigrator {
|
||||
|
||||
/// Registers a migration.
|
||||
///
|
||||
/// migrator.registerMigration("createPersons") { db in
|
||||
/// try db.execute(
|
||||
/// "CREATE TABLE persons (" +
|
||||
/// "id INTEGER PRIMARY KEY, " +
|
||||
/// "creationDate TEXT, " +
|
||||
/// "name TEXT NOT NULL" +
|
||||
/// ")")
|
||||
/// migrator.registerMigration("createPlayers") { db in
|
||||
/// try db.execute("""
|
||||
/// CREATE TABLE players (
|
||||
/// id INTEGER PRIMARY KEY,
|
||||
/// creationDate TEXT,
|
||||
/// name TEXT NOT NULL
|
||||
/// )
|
||||
/// """)
|
||||
/// }
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -64,13 +67,14 @@ public struct DatabaseMigrator {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter
|
||||
///
|
||||
/// // Add a NOT NULL constraint on persons.name:
|
||||
/// // Add a NOT NULL constraint on players.name:
|
||||
/// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in
|
||||
/// try db.execute(
|
||||
/// "CREATE TABLE new_persons (id INTEGER PRIMARY KEY, name TEXT NOT NULL);" +
|
||||
/// "INSERT INTO new_persons SELECT * FROM persons;" +
|
||||
/// "DROP TABLE persons;" +
|
||||
/// "ALTER TABLE new_persons RENAME TO persons;")
|
||||
/// try db.execute("""
|
||||
/// CREATE TABLE new_players (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
|
||||
/// INSERT INTO new_players SELECT * FROM players;
|
||||
/// DROP TABLE players;
|
||||
/// ALTER TABLE new_players RENAME TO players;
|
||||
/// """)
|
||||
/// }
|
||||
///
|
||||
/// While your migration code runs with disabled foreign key checks, those
|
||||
@@ -81,6 +85,8 @@ public struct DatabaseMigrator {
|
||||
/// - identifier: The migration identifier.
|
||||
/// - block: The migration block that performs SQL statements.
|
||||
/// - precondition: No migration with the same same as already been registered.
|
||||
///
|
||||
/// :nodoc:
|
||||
public mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void) {
|
||||
registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate))
|
||||
}
|
||||
@@ -88,13 +94,14 @@ public struct DatabaseMigrator {
|
||||
@available(iOS 8.2, OSX 10.10, *)
|
||||
/// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter
|
||||
///
|
||||
/// // Add a NOT NULL constraint on persons.name:
|
||||
/// // Add a NOT NULL constraint on players.name:
|
||||
/// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in
|
||||
/// try db.execute(
|
||||
/// "CREATE TABLE new_persons (id INTEGER PRIMARY KEY, name TEXT NOT NULL);" +
|
||||
/// "INSERT INTO new_persons SELECT * FROM persons;" +
|
||||
/// "DROP TABLE persons;" +
|
||||
/// "ALTER TABLE new_persons RENAME TO persons;")
|
||||
/// try db.execute("""
|
||||
/// CREATE TABLE new_players (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
|
||||
/// INSERT INTO new_players SELECT * FROM players;
|
||||
/// DROP TABLE players;
|
||||
/// ALTER TABLE new_players RENAME TO players;
|
||||
/// """)
|
||||
/// }
|
||||
///
|
||||
/// While your migration code runs with disabled foreign key checks, those
|
||||
|
||||
@@ -1,23 +1,40 @@
|
||||
/// A column in the database
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift#the-query-interface
|
||||
public struct Column {
|
||||
public struct Column : SQLExpression {
|
||||
/// The hidden rowID column
|
||||
public static let rowID = Column("rowid")
|
||||
|
||||
/// The name of the column
|
||||
public let name: String
|
||||
|
||||
private var qualifier: SQLTableQualifier?
|
||||
|
||||
/// Creates a column given its name.
|
||||
public init(_ name: String) {
|
||||
self.name = name
|
||||
}
|
||||
}
|
||||
|
||||
extension Column : SQLExpression {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
if let qualifierName = qualifier?.name {
|
||||
return qualifierName.quotedDatabaseIdentifier + "." + name.quotedDatabaseIdentifier
|
||||
}
|
||||
return name.quotedDatabaseIdentifier
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func qualified(by qualifier: SQLTableQualifier) -> Column {
|
||||
if self.qualifier != nil {
|
||||
// Never requalify
|
||||
return self
|
||||
}
|
||||
var column = self
|
||||
column.qualifier = qualifier
|
||||
return column
|
||||
}
|
||||
}
|
||||
@@ -31,14 +31,12 @@ extension TableMapping {
|
||||
/// // SELECT * FROM books WHERE books MATCH '...'
|
||||
/// var request = Book.matching(pattern)
|
||||
///
|
||||
/// If the `selectsRowID` type property is true, then the selection includes
|
||||
/// the hidden "rowid" column:
|
||||
///
|
||||
/// // SELECT *, rowid FROM books WHERE books MATCH '...'
|
||||
/// var request = Book.matching(pattern)
|
||||
///
|
||||
/// If the search pattern is nil, the request does not match any
|
||||
/// database row.
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public static func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<Self> {
|
||||
return all().matching(pattern)
|
||||
}
|
||||
|
||||
@@ -12,6 +12,10 @@
|
||||
///
|
||||
/// If the search pattern is nil, the request does not match any
|
||||
/// database row.
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest<T> {
|
||||
switch query.source {
|
||||
case .table(let name, let alias)?:
|
||||
@@ -36,12 +40,6 @@
|
||||
/// // SELECT * FROM books WHERE books MATCH '...'
|
||||
/// var request = Book.matching(pattern)
|
||||
///
|
||||
/// If the `selectsRowID` type property is true, then the selection
|
||||
/// includes the hidden "rowid" column:
|
||||
///
|
||||
/// // SELECT *, rowid FROM books WHERE books MATCH '...'
|
||||
/// var request = Book.matching(pattern)
|
||||
///
|
||||
/// If the search pattern is nil, the request does not match any
|
||||
/// database row.
|
||||
public static func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest<Self> {
|
||||
|
||||
@@ -16,6 +16,8 @@ extension QueryInterfaceRequest : TypedRequest {
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try query.prepare(db)
|
||||
}
|
||||
@@ -23,9 +25,18 @@ extension QueryInterfaceRequest : TypedRequest {
|
||||
/// The number of rows fetched by the request.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try query.fetchCount(db)
|
||||
}
|
||||
|
||||
/// The database region that the request looks into.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try query.fetchedRegion(db)
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
@@ -34,13 +45,13 @@ extension QueryInterfaceRequest {
|
||||
|
||||
/// A new QueryInterfaceRequest with a new net of selected columns.
|
||||
///
|
||||
/// // SELECT id, email FROM persons
|
||||
/// var request = Person.all()
|
||||
/// // SELECT id, email FROM players
|
||||
/// var request = Player.all()
|
||||
/// request = request.select(Column("id"), Column("email"))
|
||||
///
|
||||
/// Any previous selection is replaced:
|
||||
///
|
||||
/// // SELECT email FROM persons
|
||||
/// // SELECT email FROM players
|
||||
/// request
|
||||
/// .select(Column("id"))
|
||||
/// .select(Column("email"))
|
||||
@@ -50,13 +61,13 @@ extension QueryInterfaceRequest {
|
||||
|
||||
/// A new QueryInterfaceRequest with a new net of selected columns.
|
||||
///
|
||||
/// // SELECT id, email FROM persons
|
||||
/// var request = Person.all()
|
||||
/// // SELECT id, email FROM players
|
||||
/// var request = Player.all()
|
||||
/// request = request.select([Column("id"), Column("email")])
|
||||
///
|
||||
/// Any previous selection is replaced:
|
||||
///
|
||||
/// // SELECT email FROM persons
|
||||
/// // SELECT email FROM players
|
||||
/// request
|
||||
/// .select([Column("id")])
|
||||
/// .select([Column("email")])
|
||||
@@ -68,13 +79,13 @@ extension QueryInterfaceRequest {
|
||||
|
||||
/// A new QueryInterfaceRequest with a new net of selected columns.
|
||||
///
|
||||
/// // SELECT id, email FROM persons
|
||||
/// var request = Person.all()
|
||||
/// // SELECT id, email FROM players
|
||||
/// var request = Player.all()
|
||||
/// request = request.select(sql: "id, email")
|
||||
///
|
||||
/// Any previous selection is replaced:
|
||||
///
|
||||
/// // SELECT email FROM persons
|
||||
/// // SELECT email FROM players
|
||||
/// request
|
||||
/// .select(sql: "id")
|
||||
/// .select(sql: "email")
|
||||
@@ -84,12 +95,12 @@ extension QueryInterfaceRequest {
|
||||
|
||||
/// A new QueryInterfaceRequest which returns distinct rows.
|
||||
///
|
||||
/// // SELECT DISTINCT * FROM persons
|
||||
/// var request = Person.all()
|
||||
/// // SELECT DISTINCT * FROM players
|
||||
/// var request = Player.all()
|
||||
/// request = request.distinct()
|
||||
///
|
||||
/// // SELECT DISTINCT name FROM persons
|
||||
/// var request = Person.select(Column("name"))
|
||||
/// // SELECT DISTINCT name FROM players
|
||||
/// var request = Player.select(Column("name"))
|
||||
/// request = request.distinct()
|
||||
public func distinct() -> QueryInterfaceRequest<T> {
|
||||
var query = self.query
|
||||
@@ -100,24 +111,24 @@ extension QueryInterfaceRequest {
|
||||
/// A new QueryInterfaceRequest with the provided *predicate* added to the
|
||||
/// eventual set of already applied predicates.
|
||||
///
|
||||
/// // SELECT * FROM persons WHERE email = 'arthur@example.com'
|
||||
/// var request = Person.all()
|
||||
/// // SELECT * FROM players WHERE email = 'arthur@example.com'
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(Column("email") == "arthur@example.com")
|
||||
public func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest<T> {
|
||||
var query = self.query
|
||||
if let whereExpression = query.whereExpression {
|
||||
query.whereExpression = whereExpression && predicate.sqlExpression
|
||||
} else {
|
||||
query.whereExpression = predicate.sqlExpression
|
||||
}
|
||||
return QueryInterfaceRequest(query: query)
|
||||
return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in
|
||||
if let expression = expression {
|
||||
return expression && predicate.sqlExpression
|
||||
} else {
|
||||
return predicate.sqlExpression
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// A new QueryInterfaceRequest with the provided *predicate* added to the
|
||||
/// eventual set of already applied predicates.
|
||||
///
|
||||
/// // SELECT * FROM persons WHERE email = 'arthur@example.com'
|
||||
/// var request = Person.all()
|
||||
/// // SELECT * FROM players WHERE email = 'arthur@example.com'
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(sql: "email = ?", arguments: ["arthur@example.com"])
|
||||
public func filter(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<T> {
|
||||
return filter(SQLExpressionLiteral(sql, arguments: arguments))
|
||||
@@ -160,13 +171,13 @@ extension QueryInterfaceRequest {
|
||||
|
||||
/// A new QueryInterfaceRequest with the provided *orderings*.
|
||||
///
|
||||
/// // SELECT * FROM persons ORDER BY name
|
||||
/// var request = Person.all()
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// var request = Player.all()
|
||||
/// request = request.order(Column("name"))
|
||||
///
|
||||
/// Any previous ordering is replaced:
|
||||
///
|
||||
/// // SELECT * FROM persons ORDER BY name
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// request
|
||||
/// .order(Column("email"))
|
||||
/// .reversed()
|
||||
@@ -177,13 +188,13 @@ extension QueryInterfaceRequest {
|
||||
|
||||
/// A new QueryInterfaceRequest with the provided *orderings*.
|
||||
///
|
||||
/// // SELECT * FROM persons ORDER BY name
|
||||
/// var request = Person.all()
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// var request = Player.all()
|
||||
/// request = request.order([Column("name")])
|
||||
///
|
||||
/// Any previous ordering is replaced:
|
||||
///
|
||||
/// // SELECT * FROM persons ORDER BY name
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// request
|
||||
/// .order([Column("email")])
|
||||
/// .reversed()
|
||||
@@ -197,13 +208,13 @@ extension QueryInterfaceRequest {
|
||||
|
||||
/// A new QueryInterfaceRequest with the provided *sql* used for sorting.
|
||||
///
|
||||
/// // SELECT * FROM persons ORDER BY name
|
||||
/// var request = Person.all()
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// var request = Player.all()
|
||||
/// request = request.order(sql: "name")
|
||||
///
|
||||
/// Any previous ordering is replaced:
|
||||
///
|
||||
/// // SELECT * FROM persons ORDER BY name
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// request
|
||||
/// .order(sql: "email")
|
||||
/// .order(sql: "name")
|
||||
@@ -213,8 +224,8 @@ extension QueryInterfaceRequest {
|
||||
|
||||
/// A new QueryInterfaceRequest sorted in reversed order.
|
||||
///
|
||||
/// // SELECT * FROM persons ORDER BY name DESC
|
||||
/// var request = Person.all().order(Column("name"))
|
||||
/// // SELECT * FROM players ORDER BY name DESC
|
||||
/// var request = Player.all().order(Column("name"))
|
||||
/// request = request.reversed()
|
||||
public func reversed() -> QueryInterfaceRequest<T> {
|
||||
var query = self.query
|
||||
@@ -225,8 +236,8 @@ extension QueryInterfaceRequest {
|
||||
/// A QueryInterfaceRequest which fetches *limit* rows, starting
|
||||
/// at *offset*.
|
||||
///
|
||||
/// // SELECT * FROM persons LIMIT 1
|
||||
/// var request = Person.all()
|
||||
/// // SELECT * FROM players LIMIT 1
|
||||
/// var request = Player.all()
|
||||
/// request = request.limit(1)
|
||||
public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest<T> {
|
||||
var query = self.query
|
||||
@@ -235,7 +246,126 @@ extension QueryInterfaceRequest {
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
extension QueryInterfaceRequest where T: TableMapping {
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM players WHERE id = 1
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(key: 1)
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> QueryInterfaceRequest<T> {
|
||||
guard let key = key else {
|
||||
return T.none()
|
||||
}
|
||||
|
||||
return filter(keys: [key])
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM players WHERE id IN (1, 2, 3)
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(keys: [1, 2, 3])
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public func filter<Sequence: Swift.Sequence>(keys: Sequence) -> QueryInterfaceRequest<T> where Sequence.Element: DatabaseValueConvertible {
|
||||
let keys = Array(keys)
|
||||
let makePredicate: (Column) -> SQLExpression
|
||||
switch keys.count {
|
||||
case 0:
|
||||
return T.none()
|
||||
case 1:
|
||||
makePredicate = { $0 == keys[0] }
|
||||
default:
|
||||
makePredicate = { keys.contains($0) }
|
||||
}
|
||||
|
||||
return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in
|
||||
let primaryKey = try db.primaryKey(T.databaseTableName)
|
||||
GRDBPrecondition(primaryKey.columns.count == 1, "Requesting by key requires a single-column primary key in the table \(T.databaseTableName)")
|
||||
let keysPredicate = makePredicate(Column(primaryKey.columns[0]))
|
||||
if let expression = expression {
|
||||
return expression && keysPredicate
|
||||
} else {
|
||||
return keysPredicate
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM passports WHERE personId = 1 AND countryCode = 'FR'
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(key: ["personId": 1, "countryCode": "FR"])
|
||||
///
|
||||
/// When executed, this request raises a fatal error if there is no unique
|
||||
/// index on the key columns.
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest<T> {
|
||||
guard let key = key else {
|
||||
return T.none()
|
||||
}
|
||||
|
||||
return filter(keys: [key])
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM passports WHERE (personId = 1 AND countryCode = 'FR') OR ...
|
||||
/// let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...])
|
||||
///
|
||||
/// When executed, this request raises a fatal error if there is no unique
|
||||
/// index on the key columns.
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest<T> {
|
||||
guard !keys.isEmpty else {
|
||||
return T.none()
|
||||
}
|
||||
|
||||
return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in
|
||||
let keyPredicates: [SQLExpression] = try keys.map { key in
|
||||
// Prevent filter(db, keys: [[:]])
|
||||
GRDBPrecondition(!key.isEmpty, "Invalid empty key dictionary")
|
||||
|
||||
// Prevent filter(keys: [["foo": 1, "bar": 2]]) where
|
||||
// ("foo", "bar") is not a unique key (primary key or columns of a
|
||||
// unique index)
|
||||
guard let orderedColumns = try db.columnsForUniqueKey(key.keys, in: T.databaseTableName) else {
|
||||
fatalError("table \(T.databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))")
|
||||
}
|
||||
|
||||
let lowercaseOrderedColumns = orderedColumns.map { $0.lowercased() }
|
||||
let columnPredicates: [SQLExpression] = key
|
||||
// Sort key columns in the same order as the unique index
|
||||
.sorted { (kv1, kv2) in lowercaseOrderedColumns.index(of: kv1.0.lowercased())! < lowercaseOrderedColumns.index(of: kv2.0.lowercased())! }
|
||||
.map { (column, value) in Column(column) == value }
|
||||
return SQLBinaryOperator.and.join(columnPredicates)! // not nil because columnPredicates is not empty
|
||||
}
|
||||
|
||||
let keysPredicate = SQLBinaryOperator.or.join(keyPredicates)! // not nil because keyPredicates is not empty
|
||||
|
||||
if let expression = expression {
|
||||
return expression && keysPredicate
|
||||
} else {
|
||||
return keysPredicate
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest where RowDecoder: MutablePersistable {
|
||||
|
||||
// MARK: Deleting
|
||||
|
||||
@@ -257,22 +387,14 @@ extension TableMapping {
|
||||
|
||||
/// Creates a QueryInterfaceRequest which fetches all records.
|
||||
///
|
||||
/// // SELECT * FROM persons
|
||||
/// var request = Person.all()
|
||||
/// // SELECT * FROM players
|
||||
/// let request = Player.all()
|
||||
///
|
||||
/// If the `selectsRowID` type property is true, then the selection includes
|
||||
/// the hidden "rowid" column:
|
||||
///
|
||||
/// // SELECT *, rowid FROM persons
|
||||
/// var request = Person.all()
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public static func all() -> QueryInterfaceRequest<Self> {
|
||||
let selection: [SQLSelectable]
|
||||
if selectsRowID {
|
||||
selection = [SQLStar(), Column.rowID]
|
||||
} else {
|
||||
selection = [SQLStar()]
|
||||
}
|
||||
return QueryInterfaceRequest(query: QueryInterfaceSelectQueryDefinition(select: selection, from: .table(name: databaseTableName, alias: nil)))
|
||||
return QueryInterfaceRequest(query: QueryInterfaceSelectQueryDefinition(select: databaseSelection, from: .table(name: databaseTableName, alias: nil)))
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest which fetches no record.
|
||||
@@ -282,52 +404,102 @@ extension TableMapping {
|
||||
|
||||
/// Creates a QueryInterfaceRequest which selects *selection*.
|
||||
///
|
||||
/// // SELECT id, email FROM persons
|
||||
/// var request = Person.select(Column("id"), Column("email"))
|
||||
/// // SELECT id, email FROM players
|
||||
/// let request = Player.select(Column("id"), Column("email"))
|
||||
public static func select(_ selection: SQLSelectable...) -> QueryInterfaceRequest<Self> {
|
||||
return all().select(selection)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest which selects *selection*.
|
||||
///
|
||||
/// // SELECT id, email FROM persons
|
||||
/// var request = Person.select([Column("id"), Column("email")])
|
||||
/// // SELECT id, email FROM players
|
||||
/// let request = Player.select([Column("id"), Column("email")])
|
||||
public static func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest<Self> {
|
||||
return all().select(selection)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest which selects *sql*.
|
||||
///
|
||||
/// // SELECT id, email FROM persons
|
||||
/// var request = Person.select(sql: "id, email")
|
||||
/// // SELECT id, email FROM players
|
||||
/// let request = Player.select(sql: "id, email")
|
||||
public static func select(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self> {
|
||||
return all().select(sql: sql, arguments: arguments)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM persons WHERE email = 'arthur@example.com'
|
||||
/// var request = Person.filter(Column("email") == "arthur@example.com")
|
||||
/// // SELECT * FROM players WHERE email = 'arthur@example.com'
|
||||
/// let request = Player.filter(Column("email") == "arthur@example.com")
|
||||
///
|
||||
/// If the `selectsRowID` type property is true, then the selection includes
|
||||
/// the hidden "rowid" column:
|
||||
///
|
||||
/// // SELECT *, rowid FROM persons WHERE email = 'arthur@example.com'
|
||||
/// var request = Person.filter(Column("email") == "arthur@example.com")
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public static func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest<Self> {
|
||||
return all().filter(predicate)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM players WHERE id = 1
|
||||
/// let request = Player.filter(key: 1)
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public static func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> QueryInterfaceRequest<Self> {
|
||||
return all().filter(key: key)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM players WHERE id IN (1, 2, 3)
|
||||
/// let request = Player.filter(keys: [1, 2, 3])
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public static func filter<Sequence: Swift.Sequence>(keys: Sequence) -> QueryInterfaceRequest<Self> where Sequence.Element: DatabaseValueConvertible {
|
||||
return all().filter(keys: keys)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM passports WHERE personId = 1 AND countryCode = 'FR'
|
||||
/// let request = Passport.filter(key: ["personId": 1, "countryCode": "FR"])
|
||||
///
|
||||
/// When executed, this request raises a fatal error if there is no unique
|
||||
/// index on the key columns.
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public static func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest<Self> {
|
||||
return all().filter(key: key)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM passports WHERE (personId = 1 AND countryCode = 'FR') OR ...
|
||||
/// let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...])
|
||||
///
|
||||
/// When executed, this request raises a fatal error if there is no unique
|
||||
/// index on the key columns.
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public static func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest<Self> {
|
||||
return all().filter(keys: keys)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM persons WHERE email = 'arthur@example.com'
|
||||
/// var request = Person.filter(sql: "email = ?", arguments: ["arthur@example.com"])
|
||||
/// // SELECT * FROM players WHERE email = 'arthur@example.com'
|
||||
/// let request = Player.filter(sql: "email = ?", arguments: ["arthur@example.com"])
|
||||
///
|
||||
/// If the `selectsRowID` type property is true, then the selection includes
|
||||
/// the hidden "rowid" column:
|
||||
///
|
||||
/// // SELECT *, rowid FROM persons WHERE email = 'arthur@example.com'
|
||||
/// var request = Person.filter(sql: "email = ?", arguments: ["arthur@example.com"])
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public static func filter(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self> {
|
||||
return all().filter(sql: sql, arguments: arguments)
|
||||
}
|
||||
@@ -335,14 +507,12 @@ extension TableMapping {
|
||||
/// Creates a QueryInterfaceRequest sorted according to the
|
||||
/// provided *orderings*.
|
||||
///
|
||||
/// // SELECT * FROM persons ORDER BY name
|
||||
/// var request = Person.order(Column("name"))
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// let request = Player.order(Column("name"))
|
||||
///
|
||||
/// If the `selectsRowID` type property is true, then the selection includes
|
||||
/// the hidden "rowid" column:
|
||||
///
|
||||
/// // SELECT *, rowid FROM persons ORDER BY name
|
||||
/// var request = Person.order(Column("name"))
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public static func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest<Self> {
|
||||
return all().order(orderings)
|
||||
}
|
||||
@@ -350,28 +520,24 @@ extension TableMapping {
|
||||
/// Creates a QueryInterfaceRequest sorted according to the
|
||||
/// provided *orderings*.
|
||||
///
|
||||
/// // SELECT * FROM persons ORDER BY name
|
||||
/// var request = Person.order([Column("name")])
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// let request = Player.order([Column("name")])
|
||||
///
|
||||
/// If the `selectsRowID` type property is true, then the selection includes
|
||||
/// the hidden "rowid" column:
|
||||
///
|
||||
/// // SELECT *, rowid FROM persons ORDER BY name
|
||||
/// var request = Person.order([Column("name")])
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public static func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest<Self> {
|
||||
return all().order(orderings)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest sorted according to *sql*.
|
||||
///
|
||||
/// // SELECT * FROM persons ORDER BY name
|
||||
/// var request = Person.order(sql: "name")
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// let request = Player.order(sql: "name")
|
||||
///
|
||||
/// If the `selectsRowID` type property is true, then the selection includes
|
||||
/// the hidden "rowid" column:
|
||||
///
|
||||
/// // SELECT *, rowid FROM persons ORDER BY name
|
||||
/// var request = Person.order(sql: "name")
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public static func order(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self> {
|
||||
return all().order(sql: sql, arguments: arguments)
|
||||
}
|
||||
@@ -379,14 +545,12 @@ extension TableMapping {
|
||||
/// Creates a QueryInterfaceRequest which fetches *limit* rows, starting at
|
||||
/// *offset*.
|
||||
///
|
||||
/// // SELECT * FROM persons LIMIT 1
|
||||
/// var request = Person.limit(1)
|
||||
/// // SELECT * FROM players LIMIT 1
|
||||
/// let request = Player.limit(1)
|
||||
///
|
||||
/// If the `selectsRowID` type property is true, then the selection includes
|
||||
/// the hidden "rowid" column:
|
||||
///
|
||||
/// // SELECT *, rowid FROM persons LIMIT 1
|
||||
/// var request = Person.limit(1)
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public static func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest<Self> {
|
||||
return all().limit(limit, offset: offset)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,28 @@
|
||||
// MARK: - QueryInterfaceSelectQueryDefinition
|
||||
|
||||
struct DatabasePromise<T> {
|
||||
let resolve: (Database) throws -> T
|
||||
|
||||
init(value: T) {
|
||||
self.resolve = { _ in value }
|
||||
}
|
||||
|
||||
init(_ resolve: @escaping (Database) throws -> T) {
|
||||
self.resolve = resolve
|
||||
}
|
||||
|
||||
func map(_ transform: @escaping (Database, T) throws -> T) -> DatabasePromise {
|
||||
return DatabasePromise { db in
|
||||
try transform(db, self.resolve(db))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct QueryInterfaceSelectQueryDefinition {
|
||||
var selection: [SQLSelectable]
|
||||
var isDistinct: Bool
|
||||
var source: SQLSource?
|
||||
var whereExpression: SQLExpression?
|
||||
var wherePromise: DatabasePromise<SQLExpression?>
|
||||
var groupByExpressions: [SQLExpression]
|
||||
var orderings: [SQLOrderingTerm]
|
||||
var isReversed: Bool
|
||||
@@ -25,7 +43,7 @@ struct QueryInterfaceSelectQueryDefinition {
|
||||
self.selection = selection
|
||||
self.isDistinct = isDistinct
|
||||
self.source = source
|
||||
self.whereExpression = whereExpression
|
||||
self.wherePromise = DatabasePromise(value: whereExpression)
|
||||
self.groupByExpressions = groupByExpressions
|
||||
self.orderings = orderings
|
||||
self.isReversed = isReversed
|
||||
@@ -33,7 +51,13 @@ struct QueryInterfaceSelectQueryDefinition {
|
||||
self.limit = limit
|
||||
}
|
||||
|
||||
func sql(_ arguments: inout StatementArguments?) -> String {
|
||||
func mapWhereExpression(_ transform: @escaping (Database, SQLExpression?) throws -> SQLExpression?) -> QueryInterfaceSelectQueryDefinition {
|
||||
var query = self
|
||||
query.wherePromise = query.wherePromise.map(transform)
|
||||
return query
|
||||
}
|
||||
|
||||
func sql(_ db: Database, _ arguments: inout StatementArguments?) throws -> String {
|
||||
var sql = "SELECT"
|
||||
|
||||
if isDistinct {
|
||||
@@ -44,10 +68,10 @@ struct QueryInterfaceSelectQueryDefinition {
|
||||
sql += " " + selection.map { $0.resultColumnSQL(&arguments) }.joined(separator: ", ")
|
||||
|
||||
if let source = source {
|
||||
sql += " FROM " + source.sourceSQL(&arguments)
|
||||
sql += try " FROM " + source.sourceSQL(db, &arguments)
|
||||
}
|
||||
|
||||
if let whereExpression = whereExpression {
|
||||
if let whereExpression = try wherePromise.resolve(db) {
|
||||
sql += " WHERE " + whereExpression.expressionSQL(&arguments)
|
||||
}
|
||||
|
||||
@@ -59,26 +83,7 @@ struct QueryInterfaceSelectQueryDefinition {
|
||||
sql += " HAVING " + havingExpression.expressionSQL(&arguments)
|
||||
}
|
||||
|
||||
var orderings = self.orderings
|
||||
if isReversed {
|
||||
if orderings.isEmpty {
|
||||
// https://www.sqlite.org/lang_createtable.html#rowid
|
||||
//
|
||||
// > The rowid value can be accessed using one of the special
|
||||
// > case-independent names "rowid", "oid", or "_rowid_" in
|
||||
// > place of a column name. If a table contains a user defined
|
||||
// > column named "rowid", "oid" or "_rowid_", then that name
|
||||
// > always refers the explicitly declared column and cannot be
|
||||
// > used to retrieve the integer rowid value.
|
||||
//
|
||||
// Here we assume that rowid is not a custom column.
|
||||
// TODO: support for user-defined rowid column.
|
||||
// TODO: support for WITHOUT ROWID tables.
|
||||
orderings = [Column.rowID.desc]
|
||||
} else {
|
||||
orderings = orderings.map { $0.reversed }
|
||||
}
|
||||
}
|
||||
let orderings = self.queryOrderings
|
||||
if !orderings.isEmpty {
|
||||
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ")
|
||||
}
|
||||
@@ -101,27 +106,59 @@ struct QueryInterfaceSelectQueryDefinition {
|
||||
fatalError("Can't delete query with GROUP BY expression")
|
||||
}
|
||||
|
||||
guard limit == nil else {
|
||||
// Programmer error
|
||||
fatalError("Can't delete query with limit")
|
||||
}
|
||||
|
||||
var sql = "DELETE"
|
||||
var arguments: StatementArguments? = StatementArguments()
|
||||
|
||||
if let source = source {
|
||||
sql += " FROM " + source.sourceSQL(&arguments)
|
||||
sql += try " FROM " + source.sourceSQL(db, &arguments)
|
||||
}
|
||||
|
||||
if let whereExpression = whereExpression {
|
||||
if let whereExpression = try wherePromise.resolve(db) {
|
||||
sql += " WHERE " + whereExpression.expressionSQL(&arguments)
|
||||
}
|
||||
|
||||
if let limit = limit {
|
||||
let orderings = self.queryOrderings
|
||||
if !orderings.isEmpty {
|
||||
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ")
|
||||
}
|
||||
|
||||
if Database.sqliteCompileOptions.contains("ENABLE_UPDATE_DELETE_LIMIT") {
|
||||
sql += " LIMIT " + limit.sql
|
||||
} else {
|
||||
fatalError("Can't delete query with limit")
|
||||
}
|
||||
}
|
||||
|
||||
let statement = try db.makeUpdateStatement(sql)
|
||||
statement.arguments = arguments!
|
||||
return statement
|
||||
}
|
||||
|
||||
private var queryOrderings: [SQLOrderingTerm] {
|
||||
if isReversed {
|
||||
if orderings.isEmpty {
|
||||
// https://www.sqlite.org/lang_createtable.html#rowid
|
||||
//
|
||||
// > The rowid value can be accessed using one of the special
|
||||
// > case-independent names "rowid", "oid", or "_rowid_" in
|
||||
// > place of a column name. If a table contains a user defined
|
||||
// > column named "rowid", "oid" or "_rowid_", then that name
|
||||
// > always refers the explicitly declared column and cannot be
|
||||
// > used to retrieve the integer rowid value.
|
||||
//
|
||||
// Here we assume that rowid is not a custom column.
|
||||
// TODO: support for user-defined rowid column.
|
||||
// TODO: support for WITHOUT ROWID tables.
|
||||
return [Column.rowID.desc]
|
||||
} else {
|
||||
return orderings.map { $0.reversed }
|
||||
}
|
||||
} else {
|
||||
return orderings
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove ordering
|
||||
var unorderedQuery: QueryInterfaceSelectQueryDefinition {
|
||||
var query = self
|
||||
@@ -134,7 +171,7 @@ struct QueryInterfaceSelectQueryDefinition {
|
||||
extension QueryInterfaceSelectQueryDefinition : Request {
|
||||
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
var arguments: StatementArguments? = StatementArguments()
|
||||
let sql = self.sql(&arguments)
|
||||
let sql = try self.sql(db, &arguments)
|
||||
let statement = try db.makeSelectStatement(sql)
|
||||
try statement.setArgumentsWithValidation(arguments!)
|
||||
return (statement, nil)
|
||||
@@ -144,6 +181,42 @@ extension QueryInterfaceSelectQueryDefinition : Request {
|
||||
return try Int.fetchOne(db, countQuery)!
|
||||
}
|
||||
|
||||
/// The database region that the request looks into.
|
||||
func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
let (statement, _) = try prepare(db)
|
||||
let region = statement.fetchedRegion
|
||||
|
||||
// Can we intersect the region with rowIds?
|
||||
//
|
||||
// Give up unless request feeds from a single database table
|
||||
guard let source = source else {
|
||||
return region
|
||||
}
|
||||
guard case .table(name: let tableName, alias: _) = source else {
|
||||
return region
|
||||
}
|
||||
|
||||
// Give up unless primary key is rowId
|
||||
let primaryKeyInfo = try db.primaryKey(tableName)
|
||||
guard primaryKeyInfo.isRowID else {
|
||||
return region
|
||||
}
|
||||
|
||||
// Give up unless there is a where clause
|
||||
guard let whereExpression = try wherePromise.resolve(db) else {
|
||||
return region
|
||||
}
|
||||
|
||||
// The whereExpression knows better
|
||||
guard let rowIds = whereExpression.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else {
|
||||
return region
|
||||
}
|
||||
|
||||
// Database regions are case-insensitive: use the canonical table name
|
||||
let canonicalTableName = try db.canonicalName(table: tableName)
|
||||
return region.tableIntersection(canonicalTableName, rowIds: rowIds)
|
||||
}
|
||||
|
||||
private var countQuery: QueryInterfaceSelectQueryDefinition {
|
||||
guard groupByExpressions.isEmpty && limit == nil else {
|
||||
// SELECT ... GROUP BY ...
|
||||
@@ -176,7 +249,7 @@ extension QueryInterfaceSelectQueryDefinition : Request {
|
||||
// ->
|
||||
// SELECT COUNT(*) FROM tableName ...
|
||||
var countQuery = unorderedQuery
|
||||
countQuery.selection = [SQLExpressionCount(SQLStar())]
|
||||
countQuery.selection = [SQLExpressionCount(AllColumns())]
|
||||
return countQuery
|
||||
}
|
||||
}
|
||||
@@ -184,7 +257,7 @@ extension QueryInterfaceSelectQueryDefinition : Request {
|
||||
// SELECT COUNT(*) FROM (self)
|
||||
private var trivialCountQuery: QueryInterfaceSelectQueryDefinition {
|
||||
return QueryInterfaceSelectQueryDefinition(
|
||||
select: [SQLExpressionCount(SQLStar())],
|
||||
select: [SQLExpressionCount(AllColumns())],
|
||||
from: .query(query: unorderedQuery, alias: nil))
|
||||
}
|
||||
}
|
||||
@@ -193,7 +266,7 @@ indirect enum SQLSource {
|
||||
case table(name: String, alias: String?)
|
||||
case query(query: QueryInterfaceSelectQueryDefinition, alias: String?)
|
||||
|
||||
func sourceSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
func sourceSQL(_ db: Database, _ arguments: inout StatementArguments?) throws -> String {
|
||||
switch self {
|
||||
case .table(let table, let alias):
|
||||
if let alias = alias {
|
||||
@@ -203,9 +276,9 @@ indirect enum SQLSource {
|
||||
}
|
||||
case .query(let query, let alias):
|
||||
if let alias = alias {
|
||||
return "(" + query.sql(&arguments) + ") AS " + alias.quotedDatabaseIdentifier
|
||||
return try "(" + query.sql(db, &arguments) + ") AS " + alias.quotedDatabaseIdentifier
|
||||
} else {
|
||||
return "(" + query.sql(&arguments) + ")"
|
||||
return try "(" + query.sql(db, &arguments) + ")"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -227,8 +300,8 @@ struct SQLLimit {
|
||||
extension SQLCount {
|
||||
var sqlSelectable: SQLSelectable {
|
||||
switch self {
|
||||
case .star:
|
||||
return SQLExpressionCount(SQLStar())
|
||||
case .all:
|
||||
return SQLExpressionCount(AllColumns())
|
||||
case .distinct(let expression):
|
||||
return SQLExpressionCountDistinct(expression)
|
||||
}
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
///
|
||||
/// let email: SQLCollatedExpression = Column("email").collating(.nocase)
|
||||
///
|
||||
/// // SELECT * FROM persons WHERE email = 'arthur@example.com' COLLATE NOCASE
|
||||
/// Persons.filter(email == "arthur@example.com")
|
||||
/// // SELECT * FROM players WHERE email = 'arthur@example.com' COLLATE NOCASE
|
||||
/// Players.filter(email == "arthur@example.com")
|
||||
public struct SQLCollatedExpression {
|
||||
/// The tainted expression
|
||||
public let expression: SQLExpression
|
||||
@@ -18,8 +18,8 @@ public struct SQLCollatedExpression {
|
||||
///
|
||||
/// let email: SQLCollatedExpression = Column("email").collating(.nocase)
|
||||
///
|
||||
/// // SELECT * FROM persons ORDER BY email COLLATE NOCASE ASC
|
||||
/// Persons.order(email.asc)
|
||||
/// // SELECT * FROM players ORDER BY email COLLATE NOCASE ASC
|
||||
/// Players.order(email.asc)
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
public var asc: SQLOrderingTerm {
|
||||
@@ -30,8 +30,8 @@ public struct SQLCollatedExpression {
|
||||
///
|
||||
/// let email: SQLCollatedExpression = Column("email").collating(.nocase)
|
||||
///
|
||||
/// // SELECT * FROM persons ORDER BY email COLLATE NOCASE DESC
|
||||
/// Persons.order(email.desc)
|
||||
/// // SELECT * FROM players ORDER BY email COLLATE NOCASE DESC
|
||||
/// Players.order(email.desc)
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
public var desc: SQLOrderingTerm {
|
||||
@@ -51,11 +51,15 @@ public struct SQLCollatedExpression {
|
||||
extension SQLCollatedExpression : SQLOrderingTerm {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public var reversed: SQLOrderingTerm {
|
||||
return desc
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return sqlExpression.orderingTermSQL(&arguments)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// SQLCollection is the protocol for types that can be checked for inclusion.
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol SQLCollection {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -28,12 +30,6 @@ public protocol SQLCollection {
|
||||
///
|
||||
/// Returns an expression that check whether the collection contains
|
||||
/// the expression.
|
||||
///
|
||||
/// The default implementation returns a SQLExpressionContains which applies
|
||||
/// the `IN` operator:
|
||||
///
|
||||
/// let request = Person.select(Column("id"))
|
||||
/// request.contains(Column("id")) // id IN (SELECT id FROM persons)
|
||||
func contains(_ value: SQLExpressible) -> SQLExpression
|
||||
}
|
||||
|
||||
@@ -43,10 +39,7 @@ public protocol SQLCollection {
|
||||
extension SQLCollection {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns a SQLExpressionContains which applies the `IN` operator:
|
||||
///
|
||||
/// let request = Person.select(Column("id"))
|
||||
/// request.contains(Column("id")) // id IN (SELECT id FROM persons)
|
||||
/// Returns a SQLExpressionContains which applies the `IN` SQL operator.
|
||||
public func contains(_ value: SQLExpressible) -> SQLExpression {
|
||||
return SQLExpressionContains(value, self)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
/// like Column.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol SQLExpressible {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -27,6 +29,8 @@ public protocol SQLExpressible {
|
||||
/// and it adopts SQLSpecificExpressible.
|
||||
///
|
||||
/// On the other side, Int adopts SQLExpressible (via DatabaseValueConvertible).
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol SQLSpecificExpressible : SQLExpressible {
|
||||
// SQLExpressible can be adopted by Swift standard types, and user
|
||||
// types, through the DatabaseValueConvertible protocol which inherits
|
||||
@@ -53,11 +57,15 @@ public protocol SQLSpecificExpressible : SQLExpressible {
|
||||
extension SQLExpressible where Self: SQLOrderingTerm {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public var reversed: SQLOrderingTerm {
|
||||
return SQLOrdering.desc(sqlExpression)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return sqlExpression.expressionSQL(&arguments)
|
||||
}
|
||||
@@ -68,17 +76,30 @@ extension SQLExpressible where Self: SQLOrderingTerm {
|
||||
extension SQLExpressible where Self: SQLSelectable {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func resultColumnSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return sqlExpression.expressionSQL(&arguments)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func countedSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return sqlExpression.expressionSQL(&arguments)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func count(distinct: Bool) -> SQLCount? {
|
||||
return sqlExpression.count(distinct: distinct)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func columnCount(_ db: Database) throws -> Int {
|
||||
return 1
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@ extension SQLExpression {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Converts an expression to an SQLExpressionLiteral
|
||||
///
|
||||
/// :nodoc:
|
||||
public var literal: SQLExpressionLiteral {
|
||||
var arguments: StatementArguments? = []
|
||||
let sql = expressionSQL(&arguments)
|
||||
@@ -57,6 +59,8 @@ public struct SQLExpressionLiteral : SQLExpression {
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
if let literalArguments = self.arguments {
|
||||
guard arguments != nil else {
|
||||
@@ -68,6 +72,13 @@ public struct SQLExpressionLiteral : SQLExpression {
|
||||
}
|
||||
return sql
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionLiteral {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionUnary
|
||||
@@ -75,6 +86,8 @@ public struct SQLExpressionLiteral : SQLExpression {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// SQLUnaryOperator is a SQLite unary operator.
|
||||
///
|
||||
/// :nodoc:
|
||||
public struct SQLUnaryOperator : Hashable {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -97,11 +110,15 @@ public struct SQLUnaryOperator : Hashable {
|
||||
}
|
||||
|
||||
/// The hash value
|
||||
///
|
||||
/// :nodoc:
|
||||
public var hashValue: Int {
|
||||
return sql.hashValue
|
||||
}
|
||||
|
||||
/// Equality operator
|
||||
///
|
||||
/// :nodoc:
|
||||
public static func == (lhs: SQLUnaryOperator, rhs: SQLUnaryOperator) -> Bool {
|
||||
return lhs.sql == rhs.sql
|
||||
}
|
||||
@@ -113,6 +130,8 @@ public struct SQLUnaryOperator : Hashable {
|
||||
/// an operand expression.
|
||||
///
|
||||
/// SQLExpressionUnary(.not, Column("favorite"))
|
||||
///
|
||||
/// :nodoc:
|
||||
public struct SQLExpressionUnary : SQLExpression {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -137,9 +156,18 @@ public struct SQLExpressionUnary : SQLExpression {
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return op.sql + (op.needsRightSpace ? " " : "") + expression.expressionSQL(&arguments)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionUnary {
|
||||
return SQLExpressionUnary(op, expression.qualified(by: qualifier))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionBinary
|
||||
@@ -147,6 +175,8 @@ public struct SQLExpressionUnary : SQLExpression {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// SQLBinaryOperator is a SQLite binary operator.
|
||||
///
|
||||
/// :nodoc:
|
||||
public struct SQLBinaryOperator : Hashable {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -191,6 +221,30 @@ public struct SQLBinaryOperator : Hashable {
|
||||
public static func == (lhs: SQLBinaryOperator, rhs: SQLBinaryOperator) -> Bool {
|
||||
return lhs.sql == rhs.sql
|
||||
}
|
||||
|
||||
// TODO: make it an extension of Sequence (like joined(separator:)) when Swift can better handle existentials
|
||||
// TODO: make it public eventually
|
||||
/// Return nil if expressions is empty.
|
||||
func join(_ expressions: [SQLExpression]) -> SQLExpression? {
|
||||
switch expressions.count {
|
||||
case 0:
|
||||
return nil
|
||||
case 1:
|
||||
return expressions[0]
|
||||
default:
|
||||
let literals = expressions.map { $0.literal }
|
||||
let firstLiteral = literals[0]
|
||||
var sql = firstLiteral.sql
|
||||
var arguments = firstLiteral.arguments ?? StatementArguments()
|
||||
for literal in literals.suffix(from: 1) {
|
||||
sql += " \(self.sql) \(literal.sql)"
|
||||
if let args = literal.arguments {
|
||||
arguments += args
|
||||
}
|
||||
}
|
||||
return SQLExpressionLiteral("(\(sql))", arguments: arguments.isEmpty ? nil : arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
@@ -199,6 +253,8 @@ public struct SQLBinaryOperator : Hashable {
|
||||
/// binary operator.
|
||||
///
|
||||
/// SQLExpressionBinary(.multiply, Column("length"), Column("width"))
|
||||
///
|
||||
/// :nodoc:
|
||||
public struct SQLExpressionBinary : SQLExpression {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -241,6 +297,63 @@ public struct SQLExpressionBinary : SQLExpression {
|
||||
return SQLExpressionNot(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
|
||||
switch op {
|
||||
case .equal, .is:
|
||||
// Look for `id == 1` or `id IS 1`?
|
||||
switch (lhs, rhs) {
|
||||
case (let column as Column, let dbValue as DatabaseValue),
|
||||
(let dbValue as DatabaseValue, let column as Column):
|
||||
// Look for `id == 1`, `rowid == 1`, `1 == id`, `1 == rowid`
|
||||
|
||||
var rowIdNames = [Column.rowID.name.lowercased()]
|
||||
if let rowIdName = rowIdName {
|
||||
rowIdNames.append(rowIdName.lowercased())
|
||||
}
|
||||
|
||||
guard rowIdNames.contains(column.name.lowercased()) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
if let rowId = Int64.fromDatabaseValue(dbValue) {
|
||||
return [rowId]
|
||||
} else {
|
||||
return []
|
||||
}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
|
||||
case .and:
|
||||
let lids = lhs.matchedRowIds(rowIdName: rowIdName)
|
||||
let rids = rhs.matchedRowIds(rowIdName: rowIdName)
|
||||
switch (lids, rids) {
|
||||
case (nil, nil): return nil
|
||||
case let (ids?, nil), let (nil, ids?): return ids
|
||||
case let (lids?, rids?): return lids.intersection(rids)
|
||||
}
|
||||
|
||||
case .or:
|
||||
let lids = lhs.matchedRowIds(rowIdName: rowIdName)
|
||||
let rids = rhs.matchedRowIds(rowIdName: rowIdName)
|
||||
switch (lids, rids) {
|
||||
case let (lids?, rids?): return lids.union(rids)
|
||||
default: return nil
|
||||
}
|
||||
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionBinary {
|
||||
return SQLExpressionBinary(op, lhs.qualified(by: qualifier), rhs.qualified(by: qualifier))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionContains
|
||||
@@ -272,6 +385,38 @@ struct SQLExpressionContains : SQLExpression {
|
||||
var negated: SQLExpression {
|
||||
return SQLExpressionContains(expression, collection, negated: !isNegated)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
|
||||
// Look for `id IN (1, 2, 3)`
|
||||
guard let column = expression as? Column,
|
||||
let array = collection as? SQLExpressionsArray else
|
||||
{
|
||||
return nil
|
||||
}
|
||||
|
||||
var rowIdNames = [Column.rowID.name.lowercased()]
|
||||
if let rowIdName = rowIdName {
|
||||
rowIdNames.append(rowIdName.lowercased())
|
||||
}
|
||||
|
||||
guard rowIdNames.contains(column.name.lowercased()) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
var rowIDs: Set<Int64> = []
|
||||
for expression in array.expressions {
|
||||
guard let dbValue = expression as? DatabaseValue else { return nil }
|
||||
if let rowId = Int64.fromDatabaseValue(dbValue) {
|
||||
rowIDs.insert(rowId)
|
||||
}
|
||||
}
|
||||
return rowIDs
|
||||
}
|
||||
|
||||
func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionContains {
|
||||
return SQLExpressionContains(expression.qualified(by: qualifier), collection, negated: isNegated)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionBetween
|
||||
@@ -307,6 +452,14 @@ struct SQLExpressionBetween : SQLExpression {
|
||||
var negated: SQLExpression {
|
||||
return SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated)
|
||||
}
|
||||
|
||||
func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionBetween {
|
||||
return SQLExpressionBetween(
|
||||
expression.qualified(by: qualifier),
|
||||
lowerBound.qualified(by: qualifier),
|
||||
upperBound.qualified(by: qualifier),
|
||||
negated: isNegated)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionFunction
|
||||
@@ -318,6 +471,8 @@ public struct SQLFunctionName : Hashable {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The SQL function name
|
||||
///
|
||||
/// :nodoc:
|
||||
public let sql: String
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
@@ -325,16 +480,22 @@ public struct SQLFunctionName : Hashable {
|
||||
/// Creates a function name
|
||||
///
|
||||
/// SQLFunctionName("ABS")
|
||||
///
|
||||
/// :nodoc:
|
||||
public init(_ sql: String) {
|
||||
self.sql = sql
|
||||
}
|
||||
|
||||
/// The hash value
|
||||
///
|
||||
/// :nodoc:
|
||||
public var hashValue: Int {
|
||||
return sql.hashValue
|
||||
}
|
||||
|
||||
/// Equality operator
|
||||
///
|
||||
/// :nodoc:
|
||||
public static func == (lhs: SQLFunctionName, rhs: SQLFunctionName) -> Bool {
|
||||
return lhs.sql == rhs.sql
|
||||
}
|
||||
@@ -346,6 +507,8 @@ public struct SQLFunctionName : Hashable {
|
||||
///
|
||||
/// // ABS(-1)
|
||||
/// SQLExpressionFunction(.abs, [-1.databaseValue])
|
||||
///
|
||||
/// :nodoc:
|
||||
public struct SQLExpressionFunction : SQLExpression {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -382,6 +545,13 @@ public struct SQLExpressionFunction : SQLExpression {
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return functionName.sql + "(" + (self.arguments.map { $0.expressionSQL(&arguments) } as [String]).joined(separator: ", ") + ")"
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionFunction {
|
||||
return SQLExpressionFunction(functionName, arguments: arguments.map { $0.qualified(by: qualifier) })
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionCount
|
||||
@@ -401,6 +571,10 @@ struct SQLExpressionCount : SQLExpression {
|
||||
func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return "COUNT(" + counted.countedSQL(&arguments) + ")"
|
||||
}
|
||||
|
||||
func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionCount {
|
||||
return SQLExpressionCount(counted.qualified(by: qualifier))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionCountDistinct
|
||||
@@ -419,6 +593,10 @@ struct SQLExpressionCountDistinct : SQLExpression {
|
||||
func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return "COUNT(DISTINCT " + counted.expressionSQL(&arguments) + ")"
|
||||
}
|
||||
|
||||
func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionCountDistinct {
|
||||
return SQLExpressionCountDistinct(counted.qualified(by: qualifier))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionCollate
|
||||
@@ -438,11 +616,14 @@ struct SQLExpressionCollate : SQLExpression {
|
||||
|
||||
func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
let sql = expression.expressionSQL(&arguments)
|
||||
let chars = sql.characters
|
||||
if chars.last! == ")" {
|
||||
return String(chars.prefix(upTo: chars.index(chars.endIndex, offsetBy: -1))) + " COLLATE " + collationName.rawValue + ")"
|
||||
if sql.last! == ")" {
|
||||
return String(sql.prefix(upTo: sql.index(sql.endIndex, offsetBy: -1))) + " COLLATE " + collationName.rawValue + ")"
|
||||
} else {
|
||||
return sql + " COLLATE " + collationName.rawValue
|
||||
}
|
||||
}
|
||||
|
||||
func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionCollate {
|
||||
return SQLExpressionCollate(expression.qualified(by: qualifier), collationName: collationName)
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,8 @@
|
||||
/// - SQLExpressionExists
|
||||
/// - SQLExpressionFunction
|
||||
/// - SQLExpressionCollate
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderingTerm {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
@@ -53,6 +55,11 @@ public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderi
|
||||
/// let expression = [1,2,3].contains(Column("id")) // id IN (1,2,3)
|
||||
/// expression.negated // id NOT IN (1,2,3)
|
||||
var negated: SQLExpression { get }
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns the rowIds matched by the expression.
|
||||
func matchedRowIds(rowIdName: String?) -> Set<Int64>? // TODO: this method should take SQLTableQualifier in account
|
||||
}
|
||||
|
||||
extension SQLExpression {
|
||||
@@ -64,9 +71,19 @@ extension SQLExpression {
|
||||
/// let column = Column("favorite")
|
||||
/// column.negated // NOT favorite
|
||||
///
|
||||
/// :nodoc:
|
||||
public var negated: SQLExpression {
|
||||
return SQLExpressionNot(self)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The default implementation returns nil
|
||||
///
|
||||
/// :nodoc:
|
||||
public func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// SQLExpression: SQLExpressible
|
||||
@@ -74,6 +91,8 @@ extension SQLExpression {
|
||||
extension SQLExpression {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public var sqlExpression: SQLExpression {
|
||||
return self
|
||||
}
|
||||
@@ -84,6 +103,8 @@ extension SQLExpression {
|
||||
extension SQLExpression {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func count(distinct: Bool) -> SQLCount? {
|
||||
if distinct {
|
||||
// SELECT DISTINCT expr FROM tableName ...
|
||||
@@ -94,7 +115,7 @@ extension SQLExpression {
|
||||
// SELECT expr FROM tableName ...
|
||||
// ->
|
||||
// SELECT COUNT(*) FROM tableName ...
|
||||
return .star
|
||||
return .all
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -115,4 +136,8 @@ struct SQLExpressionNot : SQLExpression {
|
||||
var negated: SQLExpression {
|
||||
return expression
|
||||
}
|
||||
|
||||
func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionNot {
|
||||
return SQLExpressionNot(expression.qualified(by: qualifier))
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@
|
||||
///
|
||||
/// The protocol for all types that can be used as an SQL ordering term, as
|
||||
/// described at https://www.sqlite.org/syntax/ordering-term.html
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol SQLOrderingTerm {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
|
||||
@@ -1,24 +1,88 @@
|
||||
// MARK: - SQLStar
|
||||
// MARK: - AllColumns
|
||||
|
||||
struct SQLStar : SQLSelectable {
|
||||
func resultColumnSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
/// AllColumns is the `*` in `SELECT *`.
|
||||
///
|
||||
/// You use AllColumns in your custom implementation of
|
||||
/// TableMapping.databaseSelection.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct Player : TableMapping {
|
||||
/// static var databaseTableName = "players"
|
||||
/// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
|
||||
/// }
|
||||
///
|
||||
/// // SELECT *, rowid FROM players
|
||||
/// let request = Player.all()
|
||||
public struct AllColumns {
|
||||
private var qualifier: SQLTableQualifier?
|
||||
|
||||
///
|
||||
public init() { }
|
||||
}
|
||||
|
||||
extension AllColumns : SQLSelectable {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func resultColumnSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
if let qualifierName = qualifier?.name {
|
||||
return qualifierName.quotedDatabaseIdentifier + ".*"
|
||||
}
|
||||
return "*"
|
||||
}
|
||||
|
||||
func countedSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func countedSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
guard qualifier == nil else {
|
||||
// SELECT COUNT(t.*) is invalid SQL
|
||||
fatalError("Not implemented, or invalid query")
|
||||
}
|
||||
return "*"
|
||||
}
|
||||
|
||||
func count(distinct: Bool) -> SQLCount? {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func count(distinct: Bool) -> SQLCount? {
|
||||
// SELECT DISTINCT * FROM tableName ...
|
||||
guard !distinct else {
|
||||
return nil
|
||||
}
|
||||
|
||||
guard qualifier == nil else {
|
||||
return nil
|
||||
}
|
||||
|
||||
// SELECT * FROM tableName ...
|
||||
// ->
|
||||
// SELECT COUNT(*) FROM tableName ...
|
||||
return .star
|
||||
return .all
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func qualified(by qualifier: SQLTableQualifier) -> AllColumns {
|
||||
if self.qualifier != nil {
|
||||
// Never requalify
|
||||
return self
|
||||
}
|
||||
var allColumns = AllColumns()
|
||||
allColumns.qualifier = qualifier
|
||||
return allColumns
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func columnCount(_ db: Database) throws -> Int {
|
||||
guard let qualifier = qualifier else {
|
||||
fatalError("Can't compute number of columns without a qualifier")
|
||||
}
|
||||
return try db.columns(in: qualifier.tableName).count
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,4 +109,12 @@ struct SQLAliasedExpression : SQLSelectable {
|
||||
func count(distinct: Bool) -> SQLCount? {
|
||||
return expression.count(distinct: distinct)
|
||||
}
|
||||
|
||||
func qualified(by qualifier: SQLTableQualifier) -> SQLAliasedExpression {
|
||||
return SQLAliasedExpression(expression.qualified(by: qualifier), alias: alias)
|
||||
}
|
||||
|
||||
func columnCount(_ db: Database) throws -> Int {
|
||||
return 1
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@
|
||||
///
|
||||
/// SQLSelectable is the protocol for types that can be selected, as
|
||||
/// described at https://www.sqlite.org/syntax/result-column.html
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol SQLSelectable {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
func resultColumnSQL(_ arguments: inout StatementArguments?) -> String
|
||||
@@ -13,16 +15,41 @@ public protocol SQLSelectable {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
func count(distinct: Bool) -> SQLCount?
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
func columnCount(_ db: Database) throws -> Int
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
func qualified(by qualifier: SQLTableQualifier) -> Self
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public class SQLTableQualifier {
|
||||
var tableName: String
|
||||
private var alias: String?
|
||||
|
||||
init(tableName: String, alias: String?) {
|
||||
self.tableName = tableName
|
||||
self.alias = alias
|
||||
}
|
||||
|
||||
var name: String? {
|
||||
return alias
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Counting
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public enum SQLCount {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Represents COUNT(*)
|
||||
case star
|
||||
case all
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
|
||||
@@ -39,7 +39,7 @@ extension SQLSpecificExpressible {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// Person.filter(Column("email").collating(.nocase) == "contact@example.com")
|
||||
/// Player.filter(Column("email").collating(.nocase) == "contact@example.com")
|
||||
public func collating(_ collation: Database.CollationName) -> SQLCollatedExpression {
|
||||
return SQLCollatedExpression(sqlExpression, collationName: collation)
|
||||
}
|
||||
@@ -48,7 +48,7 @@ extension SQLSpecificExpressible {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// Person.filter(Column("name").collating(.localizedStandardCompare) == "Hervé")
|
||||
/// Player.filter(Column("name").collating(.localizedStandardCompare) == "Hervé")
|
||||
public func collating(_ collation: DatabaseCollation) -> SQLCollatedExpression {
|
||||
return SQLCollatedExpression(sqlExpression, collationName: Database.CollationName(collation.name))
|
||||
}
|
||||
|
||||
@@ -151,7 +151,7 @@ extension SQLSpecificExpressible {
|
||||
/// capitalized String property. It is NULL for non-String arguments.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.capitalized)
|
||||
/// let request = Player.select(nameColumn.capitalized)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
public var capitalized: SQLExpression {
|
||||
return DatabaseFunction.capitalize.apply(sqlExpression)
|
||||
@@ -161,7 +161,7 @@ extension SQLSpecificExpressible {
|
||||
/// lowercased String property. It is NULL for non-String arguments.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.lowercased())
|
||||
/// let request = Player.select(nameColumn.lowercased())
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
public var lowercased: SQLExpression {
|
||||
return DatabaseFunction.lowercase.apply(sqlExpression)
|
||||
@@ -171,7 +171,7 @@ extension SQLSpecificExpressible {
|
||||
/// uppercased String property. It is NULL for non-String arguments.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.uppercased())
|
||||
/// let request = Player.select(nameColumn.uppercased())
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
public var uppercased: SQLExpression {
|
||||
return DatabaseFunction.uppercase.apply(sqlExpression)
|
||||
@@ -183,7 +183,7 @@ extension SQLSpecificExpressible {
|
||||
/// localizedCapitalized String property. It is NULL for non-String arguments.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.localizedCapitalized)
|
||||
/// let request = Player.select(nameColumn.localizedCapitalized)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
|
||||
public var localizedCapitalized: SQLExpression {
|
||||
@@ -194,7 +194,7 @@ extension SQLSpecificExpressible {
|
||||
/// localizedLowercased String property. It is NULL for non-String arguments.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.localizedLowercased)
|
||||
/// let request = Player.select(nameColumn.localizedLowercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
|
||||
public var localizedLowercased: SQLExpression {
|
||||
@@ -205,7 +205,7 @@ extension SQLSpecificExpressible {
|
||||
/// localizedUppercased String property. It is NULL for non-String arguments.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.localizedUppercased)
|
||||
/// let request = Player.select(nameColumn.localizedUppercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
|
||||
public var localizedUppercased: SQLExpression {
|
||||
|
||||
@@ -14,6 +14,28 @@ extension SQLBinaryOperator {
|
||||
static let isNot = SQLBinaryOperator("IS NOT", negated: "IS")
|
||||
}
|
||||
|
||||
// Outputs "x = y" or "x IS NULL"
|
||||
private func isEqual(_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression {
|
||||
switch (lhs, rhs) {
|
||||
case (let lhs, let rhs as DatabaseValue):
|
||||
switch rhs.storage {
|
||||
case .null:
|
||||
return SQLExpressionBinary(.is, lhs, DatabaseValue.null)
|
||||
default:
|
||||
return SQLExpressionBinary(.equal, lhs, rhs)
|
||||
}
|
||||
case (let lhs as DatabaseValue, let rhs):
|
||||
switch lhs.storage {
|
||||
case .null:
|
||||
return SQLExpressionBinary(.is, rhs, DatabaseValue.null)
|
||||
default:
|
||||
return SQLExpressionBinary(.equal, lhs, rhs)
|
||||
}
|
||||
default:
|
||||
return SQLExpressionBinary(.equal, lhs, rhs)
|
||||
}
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `=` SQL operator.
|
||||
///
|
||||
/// // name = 'Arthur'
|
||||
@@ -24,11 +46,7 @@ extension SQLBinaryOperator {
|
||||
/// // name IS NULL
|
||||
/// Column("name") == nil
|
||||
public func == (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression {
|
||||
if let rhs = rhs {
|
||||
return SQLExpressionBinary(.equal, lhs.sqlExpression, rhs.sqlExpression)
|
||||
} else {
|
||||
return SQLExpressionBinary(.`is`, lhs.sqlExpression, DatabaseValue.null)
|
||||
}
|
||||
return isEqual(lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `=` SQL operator.
|
||||
@@ -71,11 +89,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression {
|
||||
/// // name IS NULL
|
||||
/// nil == Column("name")
|
||||
public func == (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
if let lhs = lhs {
|
||||
return SQLExpressionBinary(.equal, lhs.sqlExpression, rhs.sqlExpression)
|
||||
} else {
|
||||
return SQLExpressionBinary(.`is`, rhs.sqlExpression, DatabaseValue.null)
|
||||
}
|
||||
return isEqual(lhs?.sqlExpression ?? DatabaseValue.null, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `=` SQL operator.
|
||||
@@ -113,7 +127,7 @@ public func == (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
/// // email = login
|
||||
/// Column("email") == Column("login")
|
||||
public func == (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.equal, lhs.sqlExpression, rhs.sqlExpression)
|
||||
return isEqual(lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<>` SQL operator.
|
||||
@@ -126,11 +140,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL
|
||||
/// // name IS NOT NULL
|
||||
/// Column("name") != nil
|
||||
public func != (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression {
|
||||
if let rhs = rhs {
|
||||
return SQLExpressionBinary(.notEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
} else {
|
||||
return SQLExpressionBinary(.isNot, lhs.sqlExpression, DatabaseValue.null)
|
||||
}
|
||||
return isEqual(lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null).negated
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<>` SQL operator.
|
||||
@@ -173,11 +183,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression {
|
||||
/// // name IS NOT NULL
|
||||
/// nil != Column("name")
|
||||
public func != (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
if let lhs = lhs {
|
||||
return SQLExpressionBinary(.notEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
} else {
|
||||
return SQLExpressionBinary(.isNot, rhs.sqlExpression, DatabaseValue.null)
|
||||
}
|
||||
return isEqual(lhs?.sqlExpression ?? DatabaseValue.null, rhs.sqlExpression).negated
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<>` SQL operator.
|
||||
@@ -215,7 +221,7 @@ public func != (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
/// // email <> login
|
||||
/// Column("email") != Column("login")
|
||||
public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.notEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
return isEqual(lhs.sqlExpression, rhs.sqlExpression).negated
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `IS` SQL operator.
|
||||
@@ -223,7 +229,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL
|
||||
/// // name IS 'Arthur'
|
||||
/// Column("name") === "Arthur"
|
||||
public func === (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression {
|
||||
return SQLExpressionBinary(.`is`, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null)
|
||||
return SQLExpressionBinary(.is, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `IS` SQL operator.
|
||||
@@ -240,9 +246,9 @@ public func === (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpress
|
||||
/// "Arthur" === Column("name")
|
||||
public func === (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
if let lhs = lhs {
|
||||
return SQLExpressionBinary(.`is`, lhs.sqlExpression, rhs.sqlExpression)
|
||||
return SQLExpressionBinary(.is, lhs.sqlExpression, rhs.sqlExpression)
|
||||
} else {
|
||||
return SQLExpressionBinary(.`is`, rhs.sqlExpression, DatabaseValue.null)
|
||||
return SQLExpressionBinary(.is, rhs.sqlExpression, DatabaseValue.null)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -251,7 +257,7 @@ public func === (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpres
|
||||
/// // name IS 'Arthur' COLLATE NOCASE
|
||||
/// "Arthur" === Column("name").collating(.nocase)
|
||||
public func === (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression {
|
||||
return SQLExpressionCollate(lhs == rhs.expression, collationName: rhs.collationName)
|
||||
return SQLExpressionCollate(lhs === rhs.expression, collationName: rhs.collationName)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `IS` SQL operator.
|
||||
@@ -259,7 +265,7 @@ public func === (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpress
|
||||
/// // email IS login
|
||||
/// Column("email") === Column("login")
|
||||
public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.`is`, lhs.sqlExpression, rhs.sqlExpression)
|
||||
return SQLExpressionBinary(.is, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `IS NOT` SQL operator.
|
||||
@@ -325,8 +331,8 @@ extension SQLBinaryOperator {
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<` SQL operator.
|
||||
///
|
||||
/// // age < 18
|
||||
/// Column("age") < 18
|
||||
/// // score < 18
|
||||
/// Column("score") < 18
|
||||
public func < (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
@@ -341,8 +347,8 @@ public func < (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<` SQL operator.
|
||||
///
|
||||
/// // 18 < age
|
||||
/// 18 < Column("age")
|
||||
/// // 18 < score
|
||||
/// 18 < Column("score")
|
||||
public func < (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
@@ -365,8 +371,8 @@ public func < (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<=` SQL operator.
|
||||
///
|
||||
/// // age <= 18
|
||||
/// Column("age") <= 18
|
||||
/// // score <= 18
|
||||
/// Column("score") <= 18
|
||||
public func <= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
@@ -381,8 +387,8 @@ public func <= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpressio
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<=` SQL operator.
|
||||
///
|
||||
/// // 18 <= age
|
||||
/// 18 <= Column("age")
|
||||
/// // 18 <= score
|
||||
/// 18 <= Column("score")
|
||||
public func <= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
@@ -405,15 +411,15 @@ public func <= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL
|
||||
|
||||
/// An SQL expression that compares two expressions with the `>` SQL operator.
|
||||
///
|
||||
/// // age > 18
|
||||
/// Column("age") > 18
|
||||
/// // score > 18
|
||||
/// Column("score") > 18
|
||||
public func > (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `>` SQL operator.
|
||||
///
|
||||
/// // age > 'Arthur' COLLATE NOCASE
|
||||
/// // name > 'Arthur' COLLATE NOCASE
|
||||
/// Column("name").collating(.nocase) > "Arthur"
|
||||
public func > (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression {
|
||||
return SQLExpressionCollate(lhs.expression > rhs, collationName: lhs.collationName)
|
||||
@@ -421,8 +427,8 @@ public func > (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression
|
||||
|
||||
/// An SQL expression that compares two expressions with the `>` SQL operator.
|
||||
///
|
||||
/// // 18 > age
|
||||
/// 18 > Column("age")
|
||||
/// // 18 > score
|
||||
/// 18 > Column("score")
|
||||
public func > (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
@@ -445,8 +451,8 @@ public func > (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE
|
||||
|
||||
/// An SQL expression that compares two expressions with the `>=` SQL operator.
|
||||
///
|
||||
/// // age >= 18
|
||||
/// Column("age") >= 18
|
||||
/// // score >= 18
|
||||
/// Column("score") >= 18
|
||||
public func >= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
@@ -461,16 +467,16 @@ public func >= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpressio
|
||||
|
||||
/// An SQL expression that compares two expressions with the `>=` SQL operator.
|
||||
///
|
||||
/// // 18 >= age
|
||||
/// 18 >= Column("age")
|
||||
/// // 18 >= score
|
||||
/// 18 >= Column("score")
|
||||
public func >= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `>=` SQL operator.
|
||||
///
|
||||
/// // 'Arthur' >= age COLLATE NOCASE
|
||||
/// "Arthur" >= Column("age").collating(.nocase)
|
||||
/// // 'Arthur' >= name COLLATE NOCASE
|
||||
/// "Arthur" >= Column("name").collating(.nocase)
|
||||
public func >= (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression {
|
||||
return SQLExpressionCollate(lhs >= rhs.expression, collationName: rhs.collationName)
|
||||
}
|
||||
@@ -581,7 +587,7 @@ extension SQLBinaryOperator {
|
||||
|
||||
extension SQLUnaryOperator {
|
||||
/// The `-` unary operator
|
||||
public static let minus = SQLUnaryOperator("-", needsRightSpace: false)
|
||||
static let minus = SQLUnaryOperator("-", needsRightSpace: false)
|
||||
}
|
||||
|
||||
/// An SQL arithmetic multiplication.
|
||||
|
||||
@@ -19,7 +19,9 @@ extension Database {
|
||||
/// - parameters:
|
||||
/// - name: The table name.
|
||||
/// - temporary: If true, creates a temporary table.
|
||||
/// - ifNotExists: If false, no error is thrown if table already exists.
|
||||
/// - ifNotExists: If false (the default), an error is thrown if the
|
||||
/// table already exists. Otherwise, the table is created unless it
|
||||
/// already exists.
|
||||
/// - withoutRowID: If true, uses WITHOUT ROWID optimization.
|
||||
/// - body: A closure that defines table columns and constraints.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
@@ -46,7 +48,9 @@ extension Database {
|
||||
/// - parameters:
|
||||
/// - name: The table name.
|
||||
/// - temporary: If true, creates a temporary table.
|
||||
/// - ifNotExists: If false, no error is thrown if table already exists.
|
||||
/// - ifNotExists: If false (the default), an error is thrown if the
|
||||
/// table already exists. Otherwise, the table is created unless it
|
||||
/// already exists.
|
||||
/// - withoutRowID: If true, uses WITHOUT ROWID optimization.
|
||||
/// - body: A closure that defines table columns and constraints.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
@@ -75,7 +79,9 @@ extension Database {
|
||||
/// - parameters:
|
||||
/// - name: The table name.
|
||||
/// - temporary: If true, creates a temporary table.
|
||||
/// - ifNotExists: If false, no error is thrown if table already exists.
|
||||
/// - ifNotExists: If false (the default), an error is thrown if the
|
||||
/// table already exists. Otherwise, the table is created unless it
|
||||
/// already exists.
|
||||
/// - body: A closure that defines table columns and constraints.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, body: (TableDefinition) -> Void) throws {
|
||||
@@ -97,7 +103,7 @@ extension Database {
|
||||
|
||||
/// Modifies a database table.
|
||||
///
|
||||
/// try db.alter(table: "persons") { t in
|
||||
/// try db.alter(table: "players") { t in
|
||||
/// t.add(column: "url", .text)
|
||||
/// }
|
||||
///
|
||||
@@ -126,7 +132,7 @@ extension Database {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// Creates an index.
|
||||
///
|
||||
/// try db.create(index: "personByEmail", on: "person", columns: ["email"])
|
||||
/// try db.create(index: "playerByEmail", on: "player", columns: ["email"])
|
||||
///
|
||||
/// SQLite can also index expressions (https://www.sqlite.org/expridx.html)
|
||||
/// and use specific collations. To create such an index, use a raw SQL
|
||||
@@ -154,7 +160,7 @@ extension Database {
|
||||
#else
|
||||
/// Creates an index.
|
||||
///
|
||||
/// try db.create(index: "personByEmail", on: "person", columns: ["email"])
|
||||
/// try db.create(index: "playerByEmail", on: "player", columns: ["email"])
|
||||
///
|
||||
/// SQLite can also index expressions (https://www.sqlite.org/expridx.html)
|
||||
/// and use specific collations. To create such an index, use a raw SQL
|
||||
@@ -180,7 +186,7 @@ extension Database {
|
||||
|
||||
/// Creates a partial index.
|
||||
///
|
||||
/// try db.create(index: "personByEmail", on: "person", columns: ["email"], condition: Column("email") != nil)
|
||||
/// try db.create(index: "playerByEmail", on: "player", columns: ["email"], condition: Column("email") != nil)
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createindex.html, and
|
||||
/// https://www.sqlite.org/partialindex.html
|
||||
@@ -217,7 +223,7 @@ extension Database {
|
||||
/// You don't create instances of this class. Instead, you use the Database
|
||||
/// `create(table:)` method:
|
||||
///
|
||||
/// try db.create(table: "persons") { t in // t is TableDefinition
|
||||
/// try db.create(table: "players") { t in // t is TableDefinition
|
||||
/// t.column(...)
|
||||
/// }
|
||||
///
|
||||
@@ -244,7 +250,7 @@ public final class TableDefinition {
|
||||
|
||||
/// Appends a table column.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("name", .text)
|
||||
/// }
|
||||
///
|
||||
@@ -264,9 +270,9 @@ public final class TableDefinition {
|
||||
/// Defines the table primary key.
|
||||
///
|
||||
/// try db.create(table: "citizenships") { t in
|
||||
/// t.column("personID", .integer)
|
||||
/// t.column("citizenID", .integer)
|
||||
/// t.column("countryCode", .text)
|
||||
/// t.primaryKey(["personID", "countryCode"])
|
||||
/// t.primaryKey(["citizenID", "countryCode"])
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html#primkeyconst and
|
||||
@@ -304,9 +310,9 @@ public final class TableDefinition {
|
||||
///
|
||||
/// try db.create(table: "passport") { t in
|
||||
/// t.column("issueDate", .date)
|
||||
/// t.column("personID", .integer)
|
||||
/// t.column("citizenID", .integer)
|
||||
/// t.column("countryCode", .text)
|
||||
/// t.foreignKey(["personID", "countryCode"], references: "citizenships", onDelete: .cascade)
|
||||
/// t.foreignKey(["citizenID", "countryCode"], references: "citizenships", onDelete: .cascade)
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/foreignkeys.html
|
||||
@@ -327,7 +333,7 @@ public final class TableDefinition {
|
||||
|
||||
/// Adds a CHECK constraint.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("personalPhone", .text)
|
||||
/// t.column("workPhone", .text)
|
||||
/// let personalPhone = Column("personalPhone")
|
||||
@@ -344,7 +350,7 @@ public final class TableDefinition {
|
||||
|
||||
/// Adds a CHECK constraint.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("personalPhone", .text)
|
||||
/// t.column("workPhone", .text)
|
||||
/// t.check(sql: "personalPhone IS NOT NULL OR workPhone IS NOT NULL")
|
||||
@@ -422,11 +428,9 @@ public final class TableDefinition {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((destinationColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else if table == name {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else if let primaryKey = try db.primaryKey(table) {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKey.columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else {
|
||||
// Programmer error
|
||||
fatalError("explicit referenced column(s) required, since table \(table) has no primary key")
|
||||
let primaryKey = try db.primaryKey(table)
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKey.columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
}
|
||||
if let deleteAction = deleteAction {
|
||||
chunks.append("ON DELETE")
|
||||
@@ -471,7 +475,7 @@ public final class TableDefinition {
|
||||
/// You don't create instances of this class. Instead, you use the Database
|
||||
/// `alter(table:)` method:
|
||||
///
|
||||
/// try db.alter(table: "persons") { t in // t is TableAlteration
|
||||
/// try db.alter(table: "players") { t in // t is TableAlteration
|
||||
/// t.add(column: ...)
|
||||
/// }
|
||||
///
|
||||
@@ -486,7 +490,7 @@ public final class TableAlteration {
|
||||
|
||||
/// Appends a column to the table.
|
||||
///
|
||||
/// try db.alter(table: "persons") { t in
|
||||
/// try db.alter(table: "players") { t in
|
||||
/// t.add(column: "url", .text)
|
||||
/// }
|
||||
///
|
||||
@@ -497,7 +501,7 @@ public final class TableAlteration {
|
||||
/// - returns: An ColumnDefinition that allows you to refine the
|
||||
/// column definition.
|
||||
@discardableResult
|
||||
public func add(column name: String, _ type: Database.ColumnType) -> ColumnDefinition {
|
||||
public func add(column name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition {
|
||||
let column = ColumnDefinition(name: name, type: type)
|
||||
addedColumns.append(column)
|
||||
return column
|
||||
@@ -528,11 +532,11 @@ public final class TableAlteration {
|
||||
///
|
||||
/// You get instances of this class when you create or alter a database table:
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column(...) // ColumnDefinition
|
||||
/// }
|
||||
///
|
||||
/// try db.alter(table: "persons") { t in
|
||||
/// try db.alter(table: "players") { t in
|
||||
/// t.add(column: ...) // ColumnDefinition
|
||||
/// }
|
||||
///
|
||||
@@ -561,7 +565,7 @@ public final class ColumnDefinition {
|
||||
|
||||
/// Adds a primary key constraint on the column.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("id", .integer).primaryKey()
|
||||
/// }
|
||||
///
|
||||
@@ -581,7 +585,7 @@ public final class ColumnDefinition {
|
||||
|
||||
/// Adds a NOT NULL constraint on the column.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("name", .text).notNull()
|
||||
/// }
|
||||
///
|
||||
@@ -598,7 +602,7 @@ public final class ColumnDefinition {
|
||||
|
||||
/// Adds a UNIQUE constraint on the column.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("email", .text).unique()
|
||||
/// }
|
||||
///
|
||||
@@ -615,7 +619,7 @@ public final class ColumnDefinition {
|
||||
|
||||
/// Adds an index of the column.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("email", .text).indexed()
|
||||
/// }
|
||||
///
|
||||
@@ -632,7 +636,7 @@ public final class ColumnDefinition {
|
||||
|
||||
/// Adds a CHECK constraint on the column.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("name", .text).check { length($0) > 0 }
|
||||
/// }
|
||||
///
|
||||
@@ -649,7 +653,7 @@ public final class ColumnDefinition {
|
||||
|
||||
/// Adds a CHECK constraint on the column.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("name", .text).check(sql: "LENGTH(name) > 0")
|
||||
/// }
|
||||
///
|
||||
@@ -665,7 +669,7 @@ public final class ColumnDefinition {
|
||||
|
||||
/// Defines the default column value.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("name", .text).defaults(to: "Anonymous")
|
||||
/// }
|
||||
///
|
||||
@@ -681,7 +685,7 @@ public final class ColumnDefinition {
|
||||
|
||||
/// Defines the default column value.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("creationDate", .DateTime).defaults(sql: "CURRENT_TIMESTAMP")
|
||||
/// }
|
||||
///
|
||||
@@ -697,7 +701,7 @@ public final class ColumnDefinition {
|
||||
|
||||
// Defines the default column collation.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("email", .text).collate(.nocase)
|
||||
/// }
|
||||
///
|
||||
@@ -713,7 +717,7 @@ public final class ColumnDefinition {
|
||||
|
||||
// Defines the default column collation.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("name", .text).collate(.localizedCaseInsensitiveCompare)
|
||||
/// }
|
||||
///
|
||||
@@ -815,11 +819,11 @@ public final class ColumnDefinition {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\(column.quotedDatabaseIdentifier))")
|
||||
} else if table.lowercased() == tableName.lowercased() {
|
||||
// implicit autoreference
|
||||
let primaryKeyColumns = try primaryKeyColumns ?? db.primaryKey(table)?.columns ?? [Column.rowID.name]
|
||||
let primaryKeyColumns = try primaryKeyColumns ?? db.primaryKey(table).columns
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else {
|
||||
// implicit external reference
|
||||
let primaryKeyColumns = try db.primaryKey(table)?.columns ?? [Column.rowID.name]
|
||||
let primaryKeyColumns = try db.primaryKey(table).columns
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
}
|
||||
if let deleteAction = deleteAction {
|
||||
|
||||
@@ -39,7 +39,7 @@ public protocol VirtualTableModule {
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Database Schema: Virtual Table
|
||||
// MARK: - Database Schema
|
||||
|
||||
/// Creates a virtual database table.
|
||||
///
|
||||
@@ -49,7 +49,9 @@ extension Database {
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The table name.
|
||||
/// - ifNotExists: If false, no error is thrown if table already exists.
|
||||
/// - ifNotExists: If false (the default), an error is thrown if the
|
||||
/// table already exists. Otherwise, the table is created unless it
|
||||
/// already exists.
|
||||
/// - module: The name of an SQLite virtual table module.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func create(virtualTable name: String, ifNotExists: Bool = false, using module: String) throws {
|
||||
@@ -88,7 +90,9 @@ extension Database {
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The table name.
|
||||
/// - ifNotExists: If false, no error is thrown if table already exists.
|
||||
/// - ifNotExists: If false (the default), an error is thrown if the
|
||||
/// table already exists. Otherwise, the table is created unless it
|
||||
/// already exists.
|
||||
/// - module: a VirtualTableModule
|
||||
/// - body: An optional closure that defines the virtual table.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
|
||||
@@ -85,7 +85,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
if let isSameRecord = isSameRecord {
|
||||
itemsAreIdenticalFactory = { _ in { isSameRecord($0.record, $1.record) } }
|
||||
} else {
|
||||
itemsAreIdenticalFactory = { _ in { _ in false } }
|
||||
itemsAreIdenticalFactory = { _ in { _,_ in false } }
|
||||
}
|
||||
|
||||
try self.init(
|
||||
@@ -95,7 +95,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
itemsAreIdenticalFactory: itemsAreIdenticalFactory)
|
||||
}
|
||||
|
||||
fileprivate init<Request>(
|
||||
private init<Request>(
|
||||
_ databaseWriter: DatabaseWriter,
|
||||
request: Request,
|
||||
queue: DispatchQueue,
|
||||
@@ -104,8 +104,8 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
{
|
||||
self.itemsAreIdenticalFactory = itemsAreIdenticalFactory
|
||||
self.request = request
|
||||
(self.selectionInfo, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
|
||||
try FetchedRecordsController.fetchSelectionInfoAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory)
|
||||
(self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
|
||||
try FetchedRecordsController.fetchRegionAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory)
|
||||
}
|
||||
self.databaseWriter = databaseWriter
|
||||
self.queue = queue
|
||||
@@ -133,7 +133,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
let initialItems = try Item<Record>.fetchAll(db, request)
|
||||
fetchedItems = initialItems
|
||||
if let fetchAndNotifyChanges = fetchAndNotifyChanges {
|
||||
let observer = FetchedRecordsObserver(selectionInfo: self.selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges)
|
||||
let observer = FetchedRecordsObserver(region: self.region, fetchAndNotifyChanges: fetchAndNotifyChanges)
|
||||
self.observer = observer
|
||||
observer.items = initialItems
|
||||
db.add(transactionObserver: observer)
|
||||
@@ -162,8 +162,8 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
/// main queue unless stated otherwise in the controller's initializer).
|
||||
public func setRequest<Request>(_ request: Request) throws where Request: TypedRequest, Request.RowDecoder == Record {
|
||||
self.request = request
|
||||
(self.selectionInfo, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
|
||||
try FetchedRecordsController.fetchSelectionInfoAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory)
|
||||
(self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
|
||||
try FetchedRecordsController.fetchRegionAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory)
|
||||
}
|
||||
|
||||
// No observer: don't look for changes
|
||||
@@ -179,7 +179,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
// and notify eventual changes
|
||||
let initialItems = fetchedItems
|
||||
databaseWriter.write { db in
|
||||
let observer = FetchedRecordsObserver(selectionInfo: selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges)
|
||||
let observer = FetchedRecordsObserver(region: region, fetchAndNotifyChanges: fetchAndNotifyChanges)
|
||||
self.observer = observer
|
||||
observer.items = initialItems
|
||||
db.add(transactionObserver: observer)
|
||||
@@ -211,11 +211,33 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
onChange: ((FetchedRecordsController<Record>, Record, FetchedRecordChange) -> ())? = nil,
|
||||
didChange: ((FetchedRecordsController<Record>) -> ())? = nil)
|
||||
{
|
||||
// I hate you SE-0110.
|
||||
let wrappedWillChange: ((FetchedRecordsController<Record>, Void) -> ())?
|
||||
if let willChange = willChange {
|
||||
wrappedWillChange = { (controller, _) in willChange(controller) }
|
||||
} else {
|
||||
wrappedWillChange = nil
|
||||
}
|
||||
|
||||
let wrappedDidChange: ((FetchedRecordsController<Record>, Void) -> ())?
|
||||
if let didChange = didChange {
|
||||
wrappedDidChange = { (controller, _) in didChange(controller) }
|
||||
} else {
|
||||
wrappedDidChange = nil
|
||||
}
|
||||
|
||||
trackChanges(
|
||||
fetchAlongside: { _ in },
|
||||
willChange: willChange.map { callback in { (controller, _) in callback(controller) } },
|
||||
willChange: wrappedWillChange,
|
||||
onChange: onChange,
|
||||
didChange: didChange.map { callback in { (controller, _) in callback(controller) } })
|
||||
didChange: wrappedDidChange)
|
||||
|
||||
// Without bloody SE-0110:
|
||||
// trackChanges(
|
||||
// fetchAlongside: { _ in },
|
||||
// willChange: willChange.map { callback in { (controller, _) in callback(controller) } },
|
||||
// onChange: onChange,
|
||||
// didChange: didChange.map { callback in { (controller, _) in callback(controller) } })
|
||||
}
|
||||
|
||||
/// Registers changes notification callbacks.
|
||||
@@ -277,7 +299,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
onChange: onChange,
|
||||
didChange: didChange,
|
||||
didProcessTransaction: didProcessTransaction)
|
||||
let observer = FetchedRecordsObserver(selectionInfo: selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges)
|
||||
let observer = FetchedRecordsObserver(region: region, fetchAndNotifyChanges: fetchAndNotifyChanges)
|
||||
self.observer = observer
|
||||
if let initialItems = initialItems {
|
||||
observer.items = initialItems
|
||||
@@ -348,16 +370,16 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
fileprivate var fetchedItems: [Item<Record>]?
|
||||
|
||||
/// The record comparator
|
||||
fileprivate var itemsAreIdentical: ItemComparator<Record>
|
||||
private var itemsAreIdentical: ItemComparator<Record>
|
||||
|
||||
/// The record comparator factory (support for request change)
|
||||
fileprivate let itemsAreIdenticalFactory: ItemComparatorFactory<Record>
|
||||
private let itemsAreIdenticalFactory: ItemComparatorFactory<Record>
|
||||
|
||||
/// The request
|
||||
fileprivate var request: Request
|
||||
|
||||
/// The observed selection info
|
||||
fileprivate var selectionInfo : SelectStatement.SelectionInfo
|
||||
/// The observed database region
|
||||
private var region : DatabaseRegion
|
||||
|
||||
/// The eventual current database observer
|
||||
private var observer: FetchedRecordsObserver<Record>?
|
||||
@@ -365,16 +387,15 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
/// The eventual error handler
|
||||
fileprivate var errorHandler: ((FetchedRecordsController<Record>, Error) -> ())?
|
||||
|
||||
private static func fetchSelectionInfoAndComparator(
|
||||
private static func fetchRegionAndComparator(
|
||||
_ db: Database,
|
||||
request: Request,
|
||||
itemsAreIdenticalFactory: ItemComparatorFactory<Record>) throws
|
||||
-> (SelectStatement.SelectionInfo, ItemComparator<Record>)
|
||||
-> (DatabaseRegion, ItemComparator<Record>)
|
||||
{
|
||||
let (statement, _) = try request.prepare(db)
|
||||
let selectionInfo = statement.selectionInfo
|
||||
let region = try request.fetchedRegion(db)
|
||||
let itemsAreIdentical = try itemsAreIdenticalFactory(db)
|
||||
return (selectionInfo, itemsAreIdentical)
|
||||
return (region, itemsAreIdentical)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -461,29 +482,25 @@ extension FetchedRecordsController where Record: TableMapping {
|
||||
// non-null value.
|
||||
let itemsAreIdenticalFactory: ItemComparatorFactory<Record> = { db in
|
||||
// Extract primary key columns from database table
|
||||
let columns: [String]
|
||||
if let primaryKey = try db.primaryKey(Record.databaseTableName) {
|
||||
columns = primaryKey.columns
|
||||
} else if Record.selectsRowID {
|
||||
columns = [Column.rowID.name]
|
||||
} else {
|
||||
// No primary key => can't compare rows
|
||||
return { _ in false }
|
||||
}
|
||||
let columns = try db.primaryKey(Record.databaseTableName).columns
|
||||
|
||||
// Compare primary keys
|
||||
assert(!columns.isEmpty)
|
||||
return { (lItem, rItem) in
|
||||
var notNullValue = false
|
||||
for column in columns {
|
||||
let lValue: DatabaseValue = lItem.row.value(named: column)
|
||||
let rValue: DatabaseValue = rItem.row.value(named: column)
|
||||
let lValue: DatabaseValue = lItem.row[column]
|
||||
let rValue: DatabaseValue = rItem.row[column]
|
||||
if lValue != rValue {
|
||||
// different primary keys
|
||||
return false
|
||||
}
|
||||
if !lValue.isNull || !rValue.isNull {
|
||||
notNullValue = true
|
||||
}
|
||||
}
|
||||
// identical primary keys
|
||||
return true
|
||||
// identical primary keys iff at least one value is not null
|
||||
return notNullValue
|
||||
}
|
||||
}
|
||||
try self.init(
|
||||
@@ -504,15 +521,15 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
|
||||
var needsComputeChanges: Bool
|
||||
var items: [Item<Record>]! // ought to be not nil when observer has started tracking transactions
|
||||
let queue: DispatchQueue // protects items
|
||||
let selectionInfo: SelectStatement.SelectionInfo
|
||||
let region: DatabaseRegion
|
||||
var fetchAndNotifyChanges: (FetchedRecordsObserver<Record>) -> ()
|
||||
|
||||
init(selectionInfo: SelectStatement.SelectionInfo, fetchAndNotifyChanges: @escaping (FetchedRecordsObserver<Record>) -> ()) {
|
||||
init(region: DatabaseRegion, fetchAndNotifyChanges: @escaping (FetchedRecordsObserver<Record>) -> ()) {
|
||||
self.isValid = true
|
||||
self.items = nil
|
||||
self.needsComputeChanges = false
|
||||
self.queue = DispatchQueue(label: "GRDB.FetchedRecordsObserver")
|
||||
self.selectionInfo = selectionInfo
|
||||
self.region = region
|
||||
self.fetchAndNotifyChanges = fetchAndNotifyChanges
|
||||
}
|
||||
|
||||
@@ -521,22 +538,17 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
|
||||
}
|
||||
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
return eventKind.impacts(selectionInfo)
|
||||
return region.isModified(byEventsOfKind: eventKind)
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
/// Part of the TransactionObserverType protocol
|
||||
func databaseWillChange(with event: DatabasePreUpdateEvent) { }
|
||||
#endif
|
||||
|
||||
/// Part of the TransactionObserverType protocol
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
needsComputeChanges = true
|
||||
if region.isModified(by: event) {
|
||||
needsComputeChanges = true
|
||||
stopObservingDatabaseChangesUntilNextTransaction()
|
||||
}
|
||||
}
|
||||
|
||||
/// Part of the TransactionObserverType protocol
|
||||
func databaseWillCommit() throws { }
|
||||
|
||||
/// Part of the TransactionObserverType protocol
|
||||
func databaseDidRollback(_ db: Database) {
|
||||
needsComputeChanges = false
|
||||
@@ -559,7 +571,7 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
|
||||
|
||||
// MARK: - Changes
|
||||
|
||||
fileprivate func makeFetchFunction<Record, T>(
|
||||
private func makeFetchFunction<Record, T>(
|
||||
controller: FetchedRecordsController<Record>,
|
||||
fetchAlongside: @escaping (Database) throws -> T,
|
||||
willProcessTransaction: @escaping () -> (),
|
||||
@@ -634,7 +646,7 @@ fileprivate func makeFetchFunction<Record, T>(
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func makeFetchAndNotifyChangesFunction<Record, T>(
|
||||
private func makeFetchAndNotifyChangesFunction<Record, T>(
|
||||
controller: FetchedRecordsController<Record>,
|
||||
fetchAlongside: @escaping (Database) throws -> T,
|
||||
itemsAreIdentical: @escaping ItemComparator<Record>,
|
||||
@@ -704,7 +716,7 @@ fileprivate func makeFetchAndNotifyChangesFunction<Record, T>(
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func computeChanges<Record>(from s: [Item<Record>], to t: [Item<Record>], itemsAreIdentical: ItemComparator<Record>) -> [ItemChange<Record>] {
|
||||
private func computeChanges<Record>(from s: [Item<Record>], to t: [Item<Record>], itemsAreIdentical: ItemComparator<Record>) -> [ItemChange<Record>] {
|
||||
let m = s.count
|
||||
let n = t.count
|
||||
|
||||
@@ -776,7 +788,7 @@ fileprivate func computeChanges<Record>(from s: [Item<Record>], to t: [Item<Reco
|
||||
func changedValues(from oldRow: Row, to newRow: Row) -> [String: DatabaseValue] {
|
||||
var changedValues: [String: DatabaseValue] = [:]
|
||||
for (column, newValue) in newRow {
|
||||
let oldValue: DatabaseValue? = oldRow.value(named: column)
|
||||
let oldValue: DatabaseValue? = oldRow[column]
|
||||
if newValue != oldValue {
|
||||
changedValues[column] = oldValue
|
||||
}
|
||||
@@ -840,7 +852,7 @@ fileprivate func computeChanges<Record>(from s: [Item<Record>], to t: [Item<Reco
|
||||
return standardize(changes: d[m][n], itemsAreIdentical: itemsAreIdentical)
|
||||
}
|
||||
|
||||
fileprivate func identicalItemArrays<Record>(_ lhs: [Item<Record>], _ rhs: [Item<Record>]) -> Bool {
|
||||
private func identicalItemArrays<Record>(_ lhs: [Item<Record>], _ rhs: [Item<Record>]) -> Bool {
|
||||
guard lhs.count == rhs.count else {
|
||||
return false
|
||||
}
|
||||
@@ -855,8 +867,8 @@ fileprivate func identicalItemArrays<Record>(_ lhs: [Item<Record>], _ rhs: [Item
|
||||
|
||||
// MARK: - UITableView Support
|
||||
|
||||
fileprivate typealias ItemComparator<Record: RowConvertible> = (Item<Record>, Item<Record>) -> Bool
|
||||
fileprivate typealias ItemComparatorFactory<Record: RowConvertible> = (Database) throws -> ItemComparator<Record>
|
||||
private typealias ItemComparator<Record: RowConvertible> = (Item<Record>, Item<Record>) -> Bool
|
||||
private typealias ItemComparatorFactory<Record: RowConvertible> = (Database) throws -> ItemComparator<Record>
|
||||
|
||||
extension FetchedRecordsController {
|
||||
|
||||
@@ -986,8 +998,6 @@ public enum FetchedRecordChange {
|
||||
}
|
||||
|
||||
extension FetchedRecordChange: CustomStringConvertible {
|
||||
|
||||
/// A textual representation of `self`.
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .insertion(let indexPath):
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
private struct PersistableKeyedEncodingContainer<Key: CodingKey> : KeyedEncodingContainerProtocol {
|
||||
let encode: (_ value: DatabaseValueConvertible?, _ key: String) -> Void
|
||||
|
||||
init(encode: @escaping (_ value: DatabaseValueConvertible?, _ key: String) -> Void) {
|
||||
self.encode = encode
|
||||
}
|
||||
|
||||
/// The path of coding keys taken to get to this point in encoding.
|
||||
/// A `nil` value indicates an unkeyed container.
|
||||
var codingPath: [CodingKey] { return [] }
|
||||
|
||||
/// Encodes the given value for the given key.
|
||||
///
|
||||
/// - parameter value: The value to encode.
|
||||
/// - parameter key: The key to associate the value with.
|
||||
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
|
||||
mutating func encode(_ value: Bool, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: Int, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: Int8, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: Int16, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: Int32, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: Int64, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: UInt, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: UInt8, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: UInt16, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: UInt32, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: UInt64, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: Float, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: Double, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: String, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
|
||||
/// Encodes the given value for the given key.
|
||||
///
|
||||
/// - parameter value: The value to encode.
|
||||
/// - parameter key: The key to associate the value with.
|
||||
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
|
||||
mutating func encode<T>(_ value: T, forKey key: Key) throws where T : Encodable {
|
||||
if T.self is DatabaseValueConvertible.Type {
|
||||
// Prefer DatabaseValueConvertible encoding over Decodable.
|
||||
// This allows us to encode Date as String, for example.
|
||||
encode((value as! DatabaseValueConvertible), key.stringValue)
|
||||
} else {
|
||||
try value.encode(to: PersistableEncoder(codingPath: [key], encode: encode))
|
||||
}
|
||||
}
|
||||
|
||||
// Provide explicit encoding of optionals, because default implementation does not encode nil values.
|
||||
mutating func encodeNil(forKey key: Key) throws { encode(nil, key.stringValue) }
|
||||
mutating func encodeIfPresent(_ value: Bool?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: Int?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: Int8?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: Int16?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: Int32?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: Int64?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: UInt?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: UInt8?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: UInt16?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: UInt32?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: UInt64?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: Float?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: Double?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: String?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent<T>(_ value: T?, forKey key: Key) throws where T : Encodable { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
|
||||
/// Stores a keyed encoding container for the given key and returns it.
|
||||
///
|
||||
/// - parameter keyType: The key type to use for the container.
|
||||
/// - parameter key: The key to encode the container for.
|
||||
/// - returns: A new keyed encoding container.
|
||||
mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
|
||||
/// Stores an unkeyed encoding container for the given key and returns it.
|
||||
///
|
||||
/// - parameter key: The key to encode the container for.
|
||||
/// - returns: A new unkeyed encoding container.
|
||||
mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
|
||||
/// Stores a new nested container for the default `super` key and returns a new `Encoder` instance for encoding `super` into that container.
|
||||
///
|
||||
/// Equivalent to calling `superEncoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`.
|
||||
///
|
||||
/// - returns: A new `Encoder` to pass to `super.encode(to:)`.
|
||||
mutating func superEncoder() -> Encoder {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
|
||||
/// Stores a new nested container for the given key and returns a new `Encoder` instance for encoding `super` into that container.
|
||||
///
|
||||
/// - parameter key: The key to encode `super` for.
|
||||
/// - returns: A new `Encoder` to pass to `super.encode(to:)`.
|
||||
mutating func superEncoder(forKey key: Key) -> Encoder {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
}
|
||||
|
||||
private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer {
|
||||
let key: CodingKey
|
||||
let encode: (_ value: DatabaseValueConvertible?, _ key: String) -> Void
|
||||
|
||||
var codingPath: [CodingKey] { return [key] }
|
||||
|
||||
/// Encodes a null value.
|
||||
///
|
||||
/// - throws: `EncodingError.invalidValue` if a null value is invalid in the current context for this format.
|
||||
/// - precondition: May not be called after a previous `self.encode(_:)` call.
|
||||
func encodeNil() throws { encode(nil, key.stringValue) }
|
||||
|
||||
/// Encodes a single value of the given type.
|
||||
///
|
||||
/// - parameter value: The value to encode.
|
||||
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
|
||||
/// - precondition: May not be called after a previous `self.encode(_:)` call.
|
||||
func encode(_ value: Bool) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: Int) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: Int8) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: Int16) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: Int32) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: Int64) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: UInt) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: UInt8) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: UInt16) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: UInt32) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: UInt64) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: Float) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: Double) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: String) throws { encode(value, key.stringValue) }
|
||||
|
||||
/// Encodes a single value of the given type.
|
||||
///
|
||||
/// - parameter value: The value to encode.
|
||||
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
|
||||
/// - precondition: May not be called after a previous `self.encode(_:)` call.
|
||||
func encode<T>(_ value: T) throws where T : Encodable {
|
||||
if let dbValueConvertible = value as? DatabaseValueConvertible {
|
||||
// Prefer DatabaseValueConvertible encoding over Decodable.
|
||||
// This allows us to encode Date as String, for example.
|
||||
encode(dbValueConvertible.databaseValue, key.stringValue)
|
||||
} else {
|
||||
try value.encode(to: PersistableEncoder(codingPath: [key], encode: encode))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct PersistableEncoder : Encoder {
|
||||
/// The path of coding keys taken to get to this point in encoding.
|
||||
/// A `nil` value indicates an unkeyed container.
|
||||
var codingPath: [CodingKey]
|
||||
|
||||
/// Any contextual information set by the user for encoding.
|
||||
var userInfo: [CodingUserInfoKey : Any] = [:]
|
||||
|
||||
let encode: (_ value: DatabaseValueConvertible?, _ key: String) -> Void
|
||||
|
||||
init(codingPath: [CodingKey], encode: @escaping (_ value: DatabaseValueConvertible?, _ key: String) -> Void) {
|
||||
self.codingPath = codingPath
|
||||
self.encode = encode
|
||||
}
|
||||
|
||||
/// Returns an encoding container appropriate for holding multiple values keyed by the given key type.
|
||||
///
|
||||
/// - parameter type: The key type to use for the container.
|
||||
/// - returns: A new keyed encoding container.
|
||||
/// - precondition: May not be called after a prior `self.unkeyedContainer()` call.
|
||||
/// - 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> {
|
||||
// Asked for a keyed type: top level required
|
||||
guard codingPath.isEmpty else {
|
||||
fatalError("unkeyed encoding is not supported")
|
||||
}
|
||||
return KeyedEncodingContainer(PersistableKeyedEncodingContainer<Key>(encode: encode))
|
||||
}
|
||||
|
||||
/// Returns an encoding container appropriate for holding multiple unkeyed values.
|
||||
///
|
||||
/// - returns: A new empty unkeyed container.
|
||||
/// - precondition: May not be called after a prior `self.container(keyedBy:)` call.
|
||||
/// - 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")
|
||||
}
|
||||
|
||||
/// Returns an encoding container appropriate for holding a single primitive value.
|
||||
///
|
||||
/// - returns: A new empty single value container.
|
||||
/// - precondition: May not be called after a prior `self.container(keyedBy:)` call.
|
||||
/// - precondition: May not be called after a prior `self.unkeyedContainer()` call.
|
||||
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
|
||||
func singleValueContainer() -> SingleValueEncodingContainer {
|
||||
return DatabaseValueEncodingContainer(key: codingPath.last!, encode: encode)
|
||||
}
|
||||
}
|
||||
|
||||
extension MutablePersistable where Self: Encodable {
|
||||
public func encode(to container: inout PersistenceContainer) {
|
||||
// The inout container parameter won't enter an escaping closure since
|
||||
// SE-0035: https://github.com/apple/swift-evolution/blob/master/proposals/0035-limit-inout-capture.md
|
||||
//
|
||||
// So let's use it in a non-escaping closure:
|
||||
func encode(_ encode: (_ value: DatabaseValueConvertible?, _ key: String) -> Void) {
|
||||
withoutActuallyEscaping(encode) { escapableEncode in
|
||||
let encoder = PersistableEncoder(codingPath: [], encode: escapableEncode)
|
||||
try! self.encode(to: encoder)
|
||||
}
|
||||
}
|
||||
encode { (value, key) in
|
||||
container[key] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
+218
-26
@@ -1,15 +1,28 @@
|
||||
extension Database.ConflictResolution {
|
||||
var invalidatesLastInsertedRowID: Bool {
|
||||
switch self {
|
||||
case .abort, .fail, .rollback, .replace:
|
||||
return false
|
||||
case .ignore:
|
||||
// Statement may have succeeded without inserting any row
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - PersistenceError
|
||||
|
||||
/// An error thrown by a type that adopts Persistable.
|
||||
public enum PersistenceError: Error {
|
||||
public enum PersistenceError: Error, CustomStringConvertible {
|
||||
|
||||
/// Thrown by MutablePersistable.update() when no matching row could be
|
||||
/// found in the database.
|
||||
case recordNotFound(MutablePersistable)
|
||||
}
|
||||
|
||||
extension PersistenceError : CustomStringConvertible {
|
||||
/// A textual representation of `self`.
|
||||
// CustomStringConvertible
|
||||
extension PersistenceError {
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .recordNotFound(let persistable):
|
||||
@@ -18,13 +31,12 @@ extension PersistenceError : CustomStringConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - PersistenceContainer
|
||||
|
||||
/// Use persistence containers in the `encode(to:)` method of your
|
||||
/// persistable records:
|
||||
///
|
||||
/// struct Person : MutablePersistable {
|
||||
/// struct Player : MutablePersistable {
|
||||
/// var id: Int64?
|
||||
/// var name: String?
|
||||
///
|
||||
@@ -38,12 +50,20 @@ public struct PersistenceContainer {
|
||||
fileprivate var storage: [String: DatabaseValueConvertible?]
|
||||
|
||||
/// Accesses the value associated with the given column.
|
||||
///
|
||||
/// It is undefined behavior to set different values for the same column.
|
||||
/// Column names are case insensitive, so defining both "name" and "NAME"
|
||||
/// is considered undefined behavior.
|
||||
public subscript(_ column: String) -> DatabaseValueConvertible? {
|
||||
get { return storage[column] ?? nil }
|
||||
set { storage.updateValue(newValue, forKey: column) }
|
||||
}
|
||||
|
||||
/// Accesses the value associated with the given column.
|
||||
///
|
||||
/// It is undefined behavior to set different values for the same column.
|
||||
/// Column names are case insensitive, so defining both "name" and "NAME"
|
||||
/// is considered undefined behavior.
|
||||
public subscript(_ column: Column) -> DatabaseValueConvertible? {
|
||||
get { return self[column.name] }
|
||||
set { self[column.name] = newValue }
|
||||
@@ -78,6 +98,8 @@ public struct PersistenceContainer {
|
||||
|
||||
/// Accesses the value associated with the given column, in a
|
||||
/// case-insensitive fashion.
|
||||
///
|
||||
/// :nodoc:
|
||||
subscript(caseInsensitive column: String) -> DatabaseValueConvertible? {
|
||||
get {
|
||||
if let value = storage[column] {
|
||||
@@ -124,7 +146,6 @@ extension Row {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - MutablePersistable
|
||||
|
||||
/// The MutablePersistable protocol uses this type in order to handle SQLite
|
||||
@@ -170,7 +191,7 @@ public protocol MutablePersistable : TableMapping {
|
||||
///
|
||||
/// Primary key columns, if any, must be included.
|
||||
///
|
||||
/// struct Person : MutablePersistable {
|
||||
/// struct Player : MutablePersistable {
|
||||
/// var id: Int64?
|
||||
/// var name: String?
|
||||
///
|
||||
@@ -179,6 +200,10 @@ public protocol MutablePersistable : TableMapping {
|
||||
/// container["name"] = name
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// It is undefined behavior to set different values for the same column.
|
||||
/// Column names are case insensitive, so defining both "name" and "NAME"
|
||||
/// is considered undefined behavior.
|
||||
func encode(to container: inout PersistenceContainer)
|
||||
|
||||
/// Notifies the record that it was succesfully inserted.
|
||||
@@ -189,7 +214,7 @@ public protocol MutablePersistable : TableMapping {
|
||||
///
|
||||
/// This method is optional: the default implementation does nothing.
|
||||
///
|
||||
/// struct Person : MutablePersistable {
|
||||
/// struct Player : MutablePersistable {
|
||||
/// var id: Int64?
|
||||
/// var name: String?
|
||||
///
|
||||
@@ -203,7 +228,6 @@ public protocol MutablePersistable : TableMapping {
|
||||
/// - column: The name of the eventual INTEGER PRIMARY KEY column.
|
||||
mutating func didInsert(with rowID: Int64, for column: String?)
|
||||
|
||||
|
||||
// MARK: - CRUD
|
||||
|
||||
/// Executes an INSERT statement.
|
||||
@@ -289,6 +313,13 @@ public protocol MutablePersistable : TableMapping {
|
||||
func exists(_ db: Database) throws -> Bool
|
||||
}
|
||||
|
||||
extension MutablePersistable {
|
||||
/// A dictionary whose keys are the columns encoded in the `encode(to:)` method.
|
||||
public var databaseDictionary: [String: DatabaseValue] {
|
||||
return PersistenceContainer(self).storage.mapValues { $0?.databaseValue ?? .null }
|
||||
}
|
||||
}
|
||||
|
||||
extension MutablePersistable {
|
||||
/// Describes the conflict policy for insertions and updates.
|
||||
///
|
||||
@@ -304,7 +335,6 @@ extension MutablePersistable {
|
||||
public mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
}
|
||||
|
||||
|
||||
// MARK: - CRUD
|
||||
|
||||
/// Executes an INSERT statement.
|
||||
@@ -332,7 +362,7 @@ extension MutablePersistable {
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// PersistenceError.recordNotFound is thrown if the primary key does not
|
||||
/// match any row in the database.
|
||||
public func update<Sequence: Swift.Sequence>(_ db: Database, columns: Sequence) throws where Sequence.Iterator.Element == Column {
|
||||
public func update<Sequence: Swift.Sequence>(_ db: Database, columns: Sequence) throws where Sequence.Element == Column {
|
||||
try update(db, columns: Set(columns.map { $0.name }))
|
||||
}
|
||||
|
||||
@@ -343,7 +373,7 @@ extension MutablePersistable {
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// PersistenceError.recordNotFound is thrown if the primary key does not
|
||||
/// match any row in the database.
|
||||
public func update<Sequence: Swift.Sequence>(_ db: Database, columns: Sequence) throws where Sequence.Iterator.Element == String {
|
||||
public func update<Sequence: Swift.Sequence>(_ db: Database, columns: Sequence) throws where Sequence.Element == String {
|
||||
try update(db, columns: Set(columns))
|
||||
}
|
||||
|
||||
@@ -359,6 +389,30 @@ extension MutablePersistable {
|
||||
try update(db, columns: Set(columns.map { $0.name }))
|
||||
}
|
||||
|
||||
/// If the record has differences from the other record, executes an UPDATE
|
||||
/// statement so that those changes and only those changes are saved in
|
||||
/// the database.
|
||||
///
|
||||
/// This method is guaranteed to have saved the eventual changes in the
|
||||
/// database if it returns without error.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter columns: The columns to update.
|
||||
/// - returns: Whether the record had changes.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// PersistenceError.recordNotFound is thrown if the primary key does not
|
||||
/// match any row in the database and record could not be updated.
|
||||
@discardableResult
|
||||
public func updateChanges(_ db: Database, from record: MutablePersistable) throws -> Bool {
|
||||
let changedColumns = Set(databaseChanges(from: record).keys)
|
||||
if changedColumns.isEmpty {
|
||||
return false
|
||||
} else {
|
||||
try update(db, columns: changedColumns)
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes an INSERT or an UPDATE statement so that `self` is saved in
|
||||
/// the database.
|
||||
///
|
||||
@@ -383,13 +437,49 @@ extension MutablePersistable {
|
||||
return try performExists(db)
|
||||
}
|
||||
|
||||
// MARK: - Changes Tracking
|
||||
|
||||
/// Returns a boolean indicating whether this record and the other record
|
||||
/// have the same database representation.
|
||||
public func databaseEqual(_ record: Self) -> Bool {
|
||||
return databaseChangesIterator(from: record).next() == nil
|
||||
}
|
||||
|
||||
/// A dictionary of values changed from the other record.
|
||||
///
|
||||
/// Its keys are column names. Its values come from the other record.
|
||||
///
|
||||
/// Note that this method is not symmetrical, not only in terms of values,
|
||||
/// but also in terms of columns. When the two records don't define the
|
||||
/// same set of columns in their `encode(to:)` method, only the columns
|
||||
/// defined by the receiver record are considered.
|
||||
public func databaseChanges(from record: MutablePersistable) -> [String: DatabaseValue] {
|
||||
return Dictionary(uniqueKeysWithValues: databaseChangesIterator(from: record))
|
||||
}
|
||||
|
||||
fileprivate func databaseChangesIterator(from record: MutablePersistable) -> AnyIterator<(String, DatabaseValue)> {
|
||||
let oldContainer = PersistenceContainer(record)
|
||||
var newValueIterator = PersistenceContainer(self).makeIterator()
|
||||
return AnyIterator {
|
||||
// Loop until we find a change, or exhaust columns:
|
||||
while let (column, newValue) = newValueIterator.next() {
|
||||
let oldValue = oldContainer[caseInsensitive: column]
|
||||
let oldDbValue = oldValue?.databaseValue ?? .null
|
||||
let newDbValue = newValue?.databaseValue ?? .null
|
||||
if newDbValue != oldDbValue {
|
||||
return (column, oldDbValue)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CRUD Internals
|
||||
|
||||
/// Return true if record has a non-null primary key
|
||||
fileprivate func canUpdate(_ db: Database) throws -> Bool {
|
||||
let databaseTableName = type(of: self).databaseTableName
|
||||
let primaryKey = try db.primaryKey(databaseTableName) ?? PrimaryKeyInfo.hiddenRowID
|
||||
let primaryKey = try db.primaryKey(databaseTableName)
|
||||
let container = PersistenceContainer(self)
|
||||
for column in primaryKey.columns {
|
||||
if let value = container[caseInsensitive: column], !value.databaseValue.isNull {
|
||||
@@ -502,15 +592,117 @@ extension MutablePersistable {
|
||||
|
||||
}
|
||||
|
||||
extension Database.ConflictResolution {
|
||||
var invalidatesLastInsertedRowID: Bool {
|
||||
switch self {
|
||||
case .abort, .fail, .rollback, .replace:
|
||||
return false
|
||||
case .ignore:
|
||||
// Statement may have succeeded without inserting any row
|
||||
return true
|
||||
extension MutablePersistable {
|
||||
|
||||
// MARK: - Deleting All
|
||||
|
||||
/// Deletes all records; returns the number of deleted rows.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: The number of deleted rows
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
@discardableResult
|
||||
public static func deleteAll(_ db: Database) throws -> Int {
|
||||
return try all().deleteAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
extension MutablePersistable {
|
||||
|
||||
// MARK: - Deleting by Single-Column Primary Key
|
||||
|
||||
/// Delete records identified by their primary keys; returns the number of
|
||||
/// deleted rows.
|
||||
///
|
||||
/// // DELETE FROM players WHERE id IN (1, 2, 3)
|
||||
/// try Player.deleteAll(db, keys: [1, 2, 3])
|
||||
///
|
||||
/// // DELETE FROM countries WHERE code IN ('FR', 'US', 'DE')
|
||||
/// try Country.deleteAll(db, keys: ["FR", "US", "DE"])
|
||||
///
|
||||
/// When the table has no explicit primary key, GRDB uses the hidden
|
||||
/// "rowid" column:
|
||||
///
|
||||
/// // DELETE FROM documents WHERE rowid IN (1, 2, 3)
|
||||
/// try Document.deleteAll(db, keys: [1, 2, 3])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - keys: A sequence of primary keys.
|
||||
/// - returns: The number of deleted rows
|
||||
@discardableResult
|
||||
public static func deleteAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> Int where Sequence.Element: DatabaseValueConvertible {
|
||||
let keys = Array(keys)
|
||||
if keys.isEmpty {
|
||||
// Avoid hitting the database
|
||||
return 0
|
||||
}
|
||||
return try filter(keys: keys).deleteAll(db)
|
||||
}
|
||||
|
||||
/// Delete a record, identified by its primary key; returns whether a
|
||||
/// database row was deleted.
|
||||
///
|
||||
/// // DELETE FROM players WHERE id = 123
|
||||
/// try Player.deleteOne(db, key: 123)
|
||||
///
|
||||
/// // DELETE FROM countries WHERE code = 'FR'
|
||||
/// try Country.deleteOne(db, key: "FR")
|
||||
///
|
||||
/// When the table has no explicit primary key, GRDB uses the hidden
|
||||
/// "rowid" column:
|
||||
///
|
||||
/// // DELETE FROM documents WHERE rowid = 1
|
||||
/// try Document.deleteOne(db, key: 1)
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - key: A primary key value.
|
||||
/// - returns: Whether a database row was deleted.
|
||||
@discardableResult
|
||||
public static func deleteOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: Database, key: PrimaryKeyType?) throws -> Bool {
|
||||
guard let key = key else {
|
||||
// Avoid hitting the database
|
||||
return false
|
||||
}
|
||||
return try deleteAll(db, keys: [key]) > 0
|
||||
}
|
||||
}
|
||||
|
||||
extension MutablePersistable {
|
||||
|
||||
// MARK: - Deleting by Key
|
||||
|
||||
/// Delete records identified by the provided unique keys (primary key or
|
||||
/// any key with a unique index on it); returns the number of deleted rows.
|
||||
///
|
||||
/// try Player.deleteAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - keys: An array of key dictionaries.
|
||||
/// - returns: The number of deleted rows
|
||||
@discardableResult
|
||||
public static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int {
|
||||
if keys.isEmpty {
|
||||
// Avoid hitting the database
|
||||
return 0
|
||||
}
|
||||
return try filter(keys: keys).deleteAll(db)
|
||||
}
|
||||
|
||||
/// Delete a record, identified by a unique key (the primary key or any key
|
||||
/// with a unique index on it); returns whether a database row was deleted.
|
||||
///
|
||||
/// Player.deleteOne(db, key: ["name": Arthur"])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - key: A dictionary of values.
|
||||
/// - returns: Whether a database row was deleted.
|
||||
@discardableResult
|
||||
public static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool {
|
||||
return try deleteAll(db, keys: [key]) > 0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -679,7 +871,7 @@ final class DAO {
|
||||
|
||||
init(_ db: Database, _ record: MutablePersistable) throws {
|
||||
let databaseTableName = type(of: record).databaseTableName
|
||||
let primaryKey = try db.primaryKey(databaseTableName) ?? PrimaryKeyInfo.hiddenRowID
|
||||
let primaryKey = try db.primaryKey(databaseTableName)
|
||||
let persistenceContainer = PersistenceContainer(record)
|
||||
|
||||
GRDBPrecondition(!persistenceContainer.isEmpty, "\(type(of: record)): invalid empty persistence container")
|
||||
@@ -696,7 +888,7 @@ final class DAO {
|
||||
onConflict: onConflict,
|
||||
tableName: databaseTableName,
|
||||
insertedColumns: persistenceContainer.columns)
|
||||
let statement = try db.updateStatement(query.sql, fromCache: .grdb)
|
||||
let statement = try db.internalCachedUpdateStatement(query.sql)
|
||||
statement.unsafeSetArguments(StatementArguments(persistenceContainer.values))
|
||||
return statement
|
||||
}
|
||||
@@ -742,7 +934,7 @@ final class DAO {
|
||||
tableName: databaseTableName,
|
||||
updatedColumns: updatedColumns,
|
||||
conditionColumns: primaryKeyColumns)
|
||||
let statement = try db.updateStatement(query.sql, fromCache: .grdb)
|
||||
let statement = try db.internalCachedUpdateStatement(query.sql)
|
||||
statement.unsafeSetArguments(StatementArguments(updatedValues + primaryKeyValues))
|
||||
return statement
|
||||
}
|
||||
@@ -759,7 +951,7 @@ final class DAO {
|
||||
let query = DeleteQuery(
|
||||
tableName: databaseTableName,
|
||||
conditionColumns: primaryKeyColumns)
|
||||
let statement = try db.updateStatement(query.sql, fromCache: .grdb)
|
||||
let statement = try db.internalCachedUpdateStatement(query.sql)
|
||||
statement.unsafeSetArguments(StatementArguments(primaryKeyValues))
|
||||
return statement
|
||||
}
|
||||
@@ -776,7 +968,7 @@ final class DAO {
|
||||
let query = ExistsQuery(
|
||||
tableName: databaseTableName,
|
||||
conditionColumns: primaryKeyColumns)
|
||||
let statement = try db.selectStatement(query.sql, fromCache: .grdb)
|
||||
let statement = try db.internalCachedSelectStatement(query.sql)
|
||||
statement.unsafeSetArguments(StatementArguments(primaryKeyValues))
|
||||
return statement
|
||||
}
|
||||
|
||||
+94
-48
@@ -13,7 +13,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
/// Creates a Record from a row.
|
||||
required public init(row: Row) {
|
||||
if row.isFetched {
|
||||
// Take care of the hasPersistentChangedValues flag.
|
||||
// Take care of the hasDatabaseChanges flag.
|
||||
//
|
||||
// Row may be a reused row which will turn invalid as soon as the
|
||||
// SQLite statement is iterated. We need to store an
|
||||
@@ -30,9 +30,9 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
/// This table name is required by the insert, update, save, delete,
|
||||
/// and exists methods.
|
||||
///
|
||||
/// class Person : Record {
|
||||
/// class Player : Record {
|
||||
/// override class var databaseTableName: String {
|
||||
/// return "persons"
|
||||
/// return "players"
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
@@ -60,20 +60,37 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
return PersistenceConflictPolicy(insert: .abort, update: .abort)
|
||||
}
|
||||
|
||||
/// This flag tells whether the hidden "rowid" column should be fetched
|
||||
/// with other columns.
|
||||
/// The default request selection.
|
||||
///
|
||||
/// Its default value is false:
|
||||
/// Unless this method is overriden, requests select all columns:
|
||||
///
|
||||
/// // SELECT * FROM persons
|
||||
/// try Person.fetchAll(db)
|
||||
/// // SELECT * FROM players
|
||||
/// try Player.fetchAll(db)
|
||||
///
|
||||
/// When true, the rowid column is fetched:
|
||||
/// You can override this property and provide an explicit list
|
||||
/// of columns:
|
||||
///
|
||||
/// // SELECT *, rowid FROM persons
|
||||
/// try Person.fetchAll(db)
|
||||
open class var selectsRowID: Bool {
|
||||
return false
|
||||
/// class RestrictedPlayer : Record {
|
||||
/// override static var databaseSelection: [SQLSelectable] {
|
||||
/// return [Column("id"), Column("name")]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT id, name FROM players
|
||||
/// try RestrictedPlayer.fetchAll(db)
|
||||
///
|
||||
/// You can also add extra columns such as the `rowid` column:
|
||||
///
|
||||
/// class ExtendedPlayer : Player {
|
||||
/// override static var databaseSelection: [SQLSelectable] {
|
||||
/// return [AllColumns(), Column.rowID]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT *, rowid FROM players
|
||||
/// try ExtendedPlayer.fetchAll(db)
|
||||
open class var databaseSelection: [SQLSelectable] {
|
||||
return [AllColumns()]
|
||||
}
|
||||
|
||||
|
||||
@@ -84,7 +101,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
///
|
||||
/// Primary key columns, if any, must be included.
|
||||
///
|
||||
/// class Person : Record {
|
||||
/// class Player : Record {
|
||||
/// var id: Int64?
|
||||
/// var name: String?
|
||||
///
|
||||
@@ -107,7 +124,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
///
|
||||
/// The implementation of the base Record class does nothing.
|
||||
///
|
||||
/// class Person : Record {
|
||||
/// class Player : Record {
|
||||
/// var id: Int64?
|
||||
/// var name: String?
|
||||
///
|
||||
@@ -129,7 +146,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
/// `encode(to:)` method.
|
||||
///
|
||||
/// The eventual primary key is copied, as well as the
|
||||
/// `hasPersistentChangedValues` flag.
|
||||
/// `hasDatabaseChanges` flag.
|
||||
///
|
||||
/// - returns: A copy of self.
|
||||
open func copy() -> Self {
|
||||
@@ -164,11 +181,18 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
/// you may set it to true or false when you know better. Setting it to
|
||||
/// false does not prevent it from turning true on subsequent modifications
|
||||
/// of the record.
|
||||
public var hasPersistentChangedValues: Bool {
|
||||
get { return makePersistentChangedValuesIterator().next() != nil }
|
||||
public var hasDatabaseChanges: Bool {
|
||||
get { return databaseChangesIterator().next() != nil }
|
||||
set { referenceRow = newValue ? nil : Row(self) }
|
||||
}
|
||||
|
||||
/// Deprecated alias for `hasDatabaseChanges`.
|
||||
@available(*, deprecated, renamed: "hasDatabaseChanges")
|
||||
public var hasPersistentChangedValues: Bool {
|
||||
get { return hasDatabaseChanges }
|
||||
set { hasDatabaseChanges = newValue }
|
||||
}
|
||||
|
||||
/// A dictionary of changes that have not been saved.
|
||||
///
|
||||
/// Its keys are column names, and values the old values that have been
|
||||
@@ -177,30 +201,31 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
/// Unless the record has actually been fetched or saved, the old values
|
||||
/// are nil.
|
||||
///
|
||||
/// See `hasPersistentChangedValues` for more information.
|
||||
public var persistentChangedValues: [String: DatabaseValue?] {
|
||||
var persistentChangedValues: [String: DatabaseValue?] = [:]
|
||||
|
||||
for (key, value) in makePersistentChangedValuesIterator() {
|
||||
persistentChangedValues[key] = value
|
||||
}
|
||||
return persistentChangedValues
|
||||
/// See `hasDatabaseChanges` for more information.
|
||||
public var databaseChanges: [String: DatabaseValue?] {
|
||||
return Dictionary(uniqueKeysWithValues: databaseChangesIterator())
|
||||
}
|
||||
|
||||
// A change iterator that is used by both hasPersistentChangedValues and
|
||||
/// Deprecated alias for `databaseChanges`.
|
||||
@available(*, deprecated, renamed: "databaseChanges")
|
||||
public var persistentChangedValues: [String: DatabaseValue?] {
|
||||
return databaseChanges
|
||||
}
|
||||
|
||||
// A change iterator that is used by both hasDatabaseChanges and
|
||||
// persistentChangedValues properties.
|
||||
private func makePersistentChangedValuesIterator() -> AnyIterator<(column: String, old: DatabaseValue?)> {
|
||||
private func databaseChangesIterator() -> AnyIterator<(String, DatabaseValue?)> {
|
||||
let oldRow = referenceRow
|
||||
var newValueIterator = PersistenceContainer(self).makeIterator()
|
||||
return AnyIterator {
|
||||
// Loop until we find a change, or exhaust columns:
|
||||
while let (column, newValue) = newValueIterator.next() {
|
||||
let new = newValue?.databaseValue ?? .null
|
||||
guard let oldRow = oldRow, let old: DatabaseValue = oldRow.value(named: column) else {
|
||||
return (column: column, old: nil)
|
||||
let newDbValue = newValue?.databaseValue ?? .null
|
||||
guard let oldRow = oldRow, let oldDbValue: DatabaseValue = oldRow[column] else {
|
||||
return (column, nil)
|
||||
}
|
||||
if new != old {
|
||||
return (column: column, old: old)
|
||||
if newDbValue != oldDbValue {
|
||||
return (column, oldDbValue)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -208,7 +233,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
}
|
||||
|
||||
|
||||
/// Reference row for the *hasPersistentChangedValues* property.
|
||||
/// Reference row for the *hasDatabaseChanges* property.
|
||||
var referenceRow: Row?
|
||||
|
||||
|
||||
@@ -216,8 +241,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
|
||||
/// Executes an INSERT statement.
|
||||
///
|
||||
/// On success, this method sets the *hasPersistentChangedValues* flag
|
||||
/// to false.
|
||||
/// On success, this method sets the *hasDatabaseChanges* flag to false.
|
||||
///
|
||||
/// This method is guaranteed to have inserted a row in the database if it
|
||||
/// returns without error.
|
||||
@@ -240,20 +264,19 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
didInsert(with: rowID, for: rowIDColumn)
|
||||
|
||||
// Update persistenceContainer with inserted id, so that we can
|
||||
// set hasPersistentChangedValues to false:
|
||||
// set hasDatabaseChanges to false:
|
||||
if let rowIDColumn = rowIDColumn {
|
||||
persistenceContainer[caseInsensitive: rowIDColumn] = rowID
|
||||
}
|
||||
}
|
||||
|
||||
// Set hasPersistentChangedValues to false
|
||||
// Set hasDatabaseChanges to false
|
||||
referenceRow = Row(persistenceContainer)
|
||||
}
|
||||
|
||||
/// Executes an UPDATE statement.
|
||||
///
|
||||
/// On success, this method sets the *hasPersistentChangedValues* flag
|
||||
/// to false.
|
||||
/// On success, this method sets the *hasDatabaseChanges* flag to false.
|
||||
///
|
||||
/// This method is guaranteed to have updated a row in the database if it
|
||||
/// returns without error.
|
||||
@@ -267,7 +290,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
// The simplest code would be:
|
||||
//
|
||||
// try performUpdate(db, columns: columns)
|
||||
// hasPersistentChangedValues = false
|
||||
// hasDatabaseChanges = false
|
||||
//
|
||||
// But this would trigger two calls to `encode(to:)`.
|
||||
let dao = try DAO(db, self)
|
||||
@@ -280,10 +303,35 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
throw PersistenceError.recordNotFound(self)
|
||||
}
|
||||
|
||||
// Set hasPersistentChangedValues to false
|
||||
// Set hasDatabaseChanges to false
|
||||
referenceRow = Row(dao.persistenceContainer)
|
||||
}
|
||||
|
||||
/// If the record has been changed, executes an UPDATE statement so that
|
||||
/// those changes and only those changes are saved in the database.
|
||||
///
|
||||
/// On success, this method sets the *hasDatabaseChanges* flag to false.
|
||||
///
|
||||
/// This method is guaranteed to have saved the eventual changes in the
|
||||
/// database if it returns without error.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter columns: The columns to update.
|
||||
/// - returns: Whether the record had changes.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// PersistenceError.recordNotFound is thrown if the primary key does not
|
||||
/// match any row in the database and record could not be updated.
|
||||
@discardableResult
|
||||
final public func updateChanges(_ db: Database) throws -> Bool {
|
||||
let changedColumns = Set(databaseChanges.keys)
|
||||
if changedColumns.isEmpty {
|
||||
return false
|
||||
} else {
|
||||
try update(db, columns: changedColumns)
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes an INSERT or an UPDATE statement so that `self` is saved in
|
||||
/// the database.
|
||||
///
|
||||
@@ -292,8 +340,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
///
|
||||
/// Otherwise, performs an insert.
|
||||
///
|
||||
/// On success, this method sets the *hasPersistentChangedValues* flag
|
||||
/// to false.
|
||||
/// On success, this method sets the *hasDatabaseChanges* flag to false.
|
||||
///
|
||||
/// This method is guaranteed to have inserted or updated a row in the
|
||||
/// database if it returns without error.
|
||||
@@ -307,8 +354,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
|
||||
/// Executes a DELETE statement.
|
||||
///
|
||||
/// On success, this method sets the *hasPersistentChangedValues* flag
|
||||
/// to true.
|
||||
/// On success, this method sets the *hasDatabaseChanges* flag to true.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: Whether a database row was deleted.
|
||||
@@ -318,8 +364,8 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
defer {
|
||||
// Future calls to update() will throw NotFound. Make the user
|
||||
// a favor and make sure this error is thrown even if she checks the
|
||||
// hasPersistentChangedValues flag:
|
||||
hasPersistentChangedValues = true
|
||||
// hasDatabaseChanges flag:
|
||||
hasDatabaseChanges = true
|
||||
}
|
||||
return try performDelete(db)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
/// RecordBox is a subclass of Record that aims at giving any record type the
|
||||
/// changes tracking provided by the Record class.
|
||||
///
|
||||
/// // A Regular record struct
|
||||
/// struct Player: RowConvertible, MutablePersistable, Codable {
|
||||
/// static let databaseTableName = "players"
|
||||
/// var id: Int64?
|
||||
/// var name: String
|
||||
/// var score: Int
|
||||
/// mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
/// id = rowID
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// // Fetch a player record
|
||||
/// let playerRecord = try RecordBox<Player>.fetchOne(db, key: 1)!
|
||||
///
|
||||
/// // Profit from changes tracking
|
||||
/// playerRecord.value.score = 300
|
||||
/// playerRecord.hasPersistentChangedValues // true
|
||||
/// playerRecord.persistentChangedValues["score"] // 100 (the old value)
|
||||
/// }
|
||||
@available(*, deprecated, message: "Prefer changes methods defined on the MutablePersistable protocol: databaseEqual(_:), databaseChanges(from:), updateChanges(from:)")
|
||||
public final class RecordBox<T: RowConvertible & MutablePersistable>: Record {
|
||||
/// The boxed record
|
||||
public var value: T
|
||||
|
||||
/// Creates a RecordBox that wraps the given record
|
||||
public init(value: T) {
|
||||
self.value = value
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - RowConvertible
|
||||
|
||||
/// Initializes a record from `row`.
|
||||
public required init(row: Row) {
|
||||
self.value = T(row: row)
|
||||
super.init(row: row)
|
||||
}
|
||||
|
||||
// MARK: - TableMapping
|
||||
|
||||
/// :nodoc:
|
||||
override public class var databaseTableName: String {
|
||||
return T.databaseTableName
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
override public class var databaseSelection: [SQLSelectable] {
|
||||
return T.databaseSelection
|
||||
}
|
||||
|
||||
// MARK: - MutablePersistable
|
||||
|
||||
/// :nodoc:
|
||||
override public class var persistenceConflictPolicy: PersistenceConflictPolicy {
|
||||
return T.persistenceConflictPolicy
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
override public func encode(to container: inout PersistenceContainer) {
|
||||
value.encode(to: &container)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
override public func didInsert(with rowID: Int64, for column: String?) {
|
||||
value.didInsert(with: rowID, for: column)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
override public func insert(_ db: Database) throws {
|
||||
try value.insert(db)
|
||||
hasPersistentChangedValues = false
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
override public func update(_ db: Database, columns: Set<String>) throws {
|
||||
try value.update(db, columns: columns)
|
||||
hasPersistentChangedValues = false
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
@discardableResult
|
||||
override public func delete(_ db: Database) throws -> Bool {
|
||||
defer {
|
||||
// Future calls to update() will throw NotFound. Make the user
|
||||
// a favor and make sure this error is thrown even if she checks the
|
||||
// hasPersistentChangedValues flag:
|
||||
hasPersistentChangedValues = true
|
||||
}
|
||||
return try value.delete(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func exists(_ db: Database) throws -> Bool {
|
||||
return try value.exists(db)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainerProtocol {
|
||||
let decoder: RowDecoder
|
||||
|
||||
init(decoder: RowDecoder) {
|
||||
self.decoder = decoder
|
||||
}
|
||||
|
||||
var codingPath: [CodingKey] { return decoder.codingPath }
|
||||
|
||||
/// All the keys the `Decoder` has for this container.
|
||||
///
|
||||
/// Different keyed containers from the same `Decoder` may return different keys here; it is possible to encode with multiple key types which are not convertible to one another. This should report all keys present which are convertible to the requested type.
|
||||
var allKeys: [Key] {
|
||||
let row = decoder.row
|
||||
let columnNames = Set(row.columnNames)
|
||||
let scopeNames = row.scopeNames
|
||||
return columnNames.union(scopeNames).flatMap { Key(stringValue: $0) }
|
||||
}
|
||||
|
||||
/// Returns whether the `Decoder` contains a value associated with the given key.
|
||||
///
|
||||
/// The value associated with the given key may be a null value as appropriate for the data format.
|
||||
///
|
||||
/// - parameter key: The key to search for.
|
||||
/// - returns: Whether the `Decoder` has an entry for the given key.
|
||||
func contains(_ key: Key) -> Bool {
|
||||
let row = decoder.row
|
||||
return row.hasColumn(key.stringValue) || (row.scoped(on: key.stringValue) != nil)
|
||||
}
|
||||
|
||||
/// Decodes a null value for the given key.
|
||||
///
|
||||
/// - parameter key: The key that the decoded value is associated with.
|
||||
/// - returns: Whether the encountered value was null.
|
||||
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
|
||||
func decodeNil(forKey key: Key) throws -> Bool {
|
||||
let row = decoder.row
|
||||
return row[key.stringValue] == nil && (row.scoped(on: key.stringValue) == nil)
|
||||
}
|
||||
|
||||
/// Decodes a value of the given type for the given key.
|
||||
///
|
||||
/// - parameter type: The type of value to decode.
|
||||
/// - parameter key: The key that the decoded value is associated with.
|
||||
/// - returns: A value of the requested type, if present for the given key and convertible to the requested type.
|
||||
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type.
|
||||
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
|
||||
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
|
||||
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: String.Type, forKey key: Key) throws -> String { return decoder.row[key.stringValue] }
|
||||
|
||||
/// Decodes a value of the given type for the given key, if present.
|
||||
///
|
||||
/// This method returns nil if the container does not have a value
|
||||
/// associated with key, or if the value is null. The difference between
|
||||
/// these states can be distinguished with a contains(_:) call.
|
||||
func decodeIfPresent<T>(_ type: T.Type, forKey key: Key) throws -> T? where T : Decodable {
|
||||
let row = decoder.row
|
||||
|
||||
// Try column
|
||||
if row.hasColumn(key.stringValue) {
|
||||
let dbValue: DatabaseValue = row[key.stringValue]
|
||||
if let type = T.self as? DatabaseValueConvertible.Type {
|
||||
// Prefer DatabaseValueConvertible decoding over Decodable.
|
||||
// This allows decoding Date from String, or DatabaseValue from NULL.
|
||||
return type.fromDatabaseValue(dbValue) as! T?
|
||||
} else if dbValue.isNull {
|
||||
return nil
|
||||
} else {
|
||||
return try T(from: RowDecoder(row: row, codingPath: codingPath + [key]))
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback on scope
|
||||
if let scopedRow = row.scoped(on: key.stringValue), scopedRow.containsNonNullValue {
|
||||
return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key]))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Decodes a value of the given type for the given key.
|
||||
///
|
||||
/// - parameter type: The type of value to decode.
|
||||
/// - parameter key: The key that the decoded value is associated with.
|
||||
/// - returns: A value of the requested type, if present for the given key and convertible to the requested type.
|
||||
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type.
|
||||
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
|
||||
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
|
||||
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable {
|
||||
let row = decoder.row
|
||||
|
||||
// Try column
|
||||
if row.hasColumn(key.stringValue) {
|
||||
let dbValue: DatabaseValue = row[key.stringValue]
|
||||
if let type = T.self as? DatabaseValueConvertible.Type {
|
||||
// Prefer DatabaseValueConvertible decoding over Decodable.
|
||||
// This allows decoding Date from String, or DatabaseValue from NULL.
|
||||
return type.fromDatabaseValue(dbValue) as! T
|
||||
} else {
|
||||
return try T(from: RowDecoder(row: row, codingPath: codingPath + [key]))
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback on scope
|
||||
if let scopedRow = row.scoped(on: key.stringValue) {
|
||||
return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key]))
|
||||
}
|
||||
|
||||
let path = (codingPath.map { $0.stringValue } + [key.stringValue]).joined(separator: ".")
|
||||
fatalError("No such column or scope: \(path)")
|
||||
}
|
||||
|
||||
/// Returns the data stored for the given key as represented in a container keyed by the given key type.
|
||||
///
|
||||
/// - parameter type: The key type to use for the container.
|
||||
/// - parameter key: The key that the nested container is associated with.
|
||||
/// - returns: A keyed decoding container view into `self`.
|
||||
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is not a keyed container.
|
||||
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey {
|
||||
fatalError("not implemented")
|
||||
}
|
||||
|
||||
/// Returns the data stored for the given key as represented in an unkeyed container.
|
||||
///
|
||||
/// - parameter key: The key that the nested container is associated with.
|
||||
/// - returns: An unkeyed decoding container view into `self`.
|
||||
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is not an unkeyed container.
|
||||
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
|
||||
throw DecodingError.typeMismatch(
|
||||
UnkeyedDecodingContainer.self,
|
||||
DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported"))
|
||||
}
|
||||
|
||||
/// Returns a `Decoder` instance for decoding `super` from the container associated with the default `super` key.
|
||||
///
|
||||
/// Equivalent to calling `superDecoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`.
|
||||
///
|
||||
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
|
||||
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the default `super` key.
|
||||
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the default `super` key.
|
||||
public func superDecoder() throws -> Decoder {
|
||||
return decoder
|
||||
}
|
||||
|
||||
/// Returns a `Decoder` instance for decoding `super` from the container associated with the given key.
|
||||
///
|
||||
/// - parameter key: The key to decode `super` for.
|
||||
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
|
||||
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
|
||||
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
|
||||
public func superDecoder(forKey key: Key) throws -> Decoder {
|
||||
return decoder
|
||||
}
|
||||
}
|
||||
|
||||
private struct RowSingleValueDecodingContainer: SingleValueDecodingContainer {
|
||||
let row: Row
|
||||
var codingPath: [CodingKey]
|
||||
let column: CodingKey
|
||||
|
||||
/// Decodes a null value.
|
||||
///
|
||||
/// - returns: Whether the encountered value was null.
|
||||
func decodeNil() -> Bool {
|
||||
return row[column.stringValue] == nil
|
||||
}
|
||||
|
||||
/// Decodes a single value of the given type.
|
||||
///
|
||||
/// - parameter type: The type to decode as.
|
||||
/// - returns: A value of the requested type.
|
||||
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type.
|
||||
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
|
||||
func decode(_ type: Bool.Type) throws -> Bool { return row[column.stringValue] }
|
||||
func decode(_ type: Int.Type) throws -> Int { return row[column.stringValue] }
|
||||
func decode(_ type: Int8.Type) throws -> Int8 { return row[column.stringValue] }
|
||||
func decode(_ type: Int16.Type) throws -> Int16 { return row[column.stringValue] }
|
||||
func decode(_ type: Int32.Type) throws -> Int32 { return row[column.stringValue] }
|
||||
func decode(_ type: Int64.Type) throws -> Int64 { return row[column.stringValue] }
|
||||
func decode(_ type: UInt.Type) throws -> UInt { return row[column.stringValue] }
|
||||
func decode(_ type: UInt8.Type) throws -> UInt8 { return row[column.stringValue] }
|
||||
func decode(_ type: UInt16.Type) throws -> UInt16 { return row[column.stringValue] }
|
||||
func decode(_ type: UInt32.Type) throws -> UInt32 { return row[column.stringValue] }
|
||||
func decode(_ type: UInt64.Type) throws -> UInt64 { return row[column.stringValue] }
|
||||
func decode(_ type: Float.Type) throws -> Float { return row[column.stringValue] }
|
||||
func decode(_ type: Double.Type) throws -> Double { return row[column.stringValue] }
|
||||
func decode(_ type: String.Type) throws -> String { return row[column.stringValue] }
|
||||
|
||||
/// Decodes a single value of the given type.
|
||||
///
|
||||
/// - parameter type: The type to decode as.
|
||||
/// - returns: A value of the requested type.
|
||||
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type.
|
||||
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
|
||||
func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
|
||||
if let type = T.self as? DatabaseValueConvertible.Type {
|
||||
// Prefer DatabaseValueConvertible decoding over Decodable.
|
||||
// This allows decoding Date from String, or DatabaseValue from NULL.
|
||||
return type.fromDatabaseValue(row[column.stringValue]) as! T
|
||||
} else {
|
||||
return try T(from: RowDecoder(row: row, codingPath: [column]))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct RowDecoder: Decoder {
|
||||
let row: Row
|
||||
|
||||
init(row: Row, codingPath: [CodingKey]) {
|
||||
self.row = row
|
||||
self.codingPath = codingPath
|
||||
}
|
||||
|
||||
// Decoder
|
||||
let codingPath: [CodingKey]
|
||||
var userInfo: [CodingUserInfoKey : Any] { return [:] }
|
||||
|
||||
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
|
||||
return KeyedDecodingContainer(RowKeyedDecodingContainer<Key>(decoder: self))
|
||||
}
|
||||
|
||||
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
|
||||
throw DecodingError.typeMismatch(
|
||||
UnkeyedDecodingContainer.self,
|
||||
DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported"))
|
||||
}
|
||||
|
||||
func singleValueContainer() throws -> SingleValueDecodingContainer {
|
||||
// Asked for a value type: column name required
|
||||
guard let codingKey = codingPath.last else {
|
||||
throw DecodingError.typeMismatch(
|
||||
RowDecoder.self,
|
||||
DecodingError.Context(codingPath: codingPath, debugDescription: "single value decoding requires a coding key"))
|
||||
}
|
||||
return RowSingleValueDecodingContainer(row: row, codingPath: codingPath, column: codingKey)
|
||||
}
|
||||
}
|
||||
|
||||
extension RowConvertible where Self: Decodable {
|
||||
/// Initializes a record from `row`.
|
||||
public init(row: Row) {
|
||||
try! self.init(from: RowDecoder(row: row, codingPath: []))
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,9 @@ extension RowConvertible where Self: TableMapping {
|
||||
|
||||
/// A cursor over all records fetched from the database.
|
||||
///
|
||||
/// let persons = try Person.fetchCursor(db) // DatabaseCursor<Person>
|
||||
/// while let person = try persons.next() { // Person
|
||||
/// // SELECT * FROM players
|
||||
/// let players = try Player.fetchCursor(db) // Cursor of Player
|
||||
/// while let player = try players.next() { // Player
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
@@ -16,16 +17,25 @@ extension RowConvertible where Self: TableMapping {
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database) throws -> DatabaseCursor<Self> {
|
||||
public static func fetchCursor(_ db: Database) throws -> RecordCursor<Self> {
|
||||
return try all().fetchCursor(db)
|
||||
}
|
||||
|
||||
/// An array of all records fetched from the database.
|
||||
///
|
||||
/// let persons = try Person.fetchAll(db) // [Person]
|
||||
/// // SELECT * FROM players
|
||||
/// let players = try Player.fetchAll(db) // [Player]
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
@@ -35,7 +45,12 @@ extension RowConvertible where Self: TableMapping {
|
||||
|
||||
/// The first found record.
|
||||
///
|
||||
/// let person = try Person.fetchOne(db) // Person?
|
||||
/// // SELECT * FROM players
|
||||
/// let player = try Player.fetchOne(db) // Player?
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
@@ -50,8 +65,8 @@ extension RowConvertible where Self: TableMapping {
|
||||
|
||||
/// Returns a cursor over records, given their primary keys.
|
||||
///
|
||||
/// let persons = try Person.fetchCursor(db, keys: [1, 2, 3]) // DatabaseCursor<Person>
|
||||
/// while let person = try persons.next() {
|
||||
/// let players = try Player.fetchCursor(db, keys: [1, 2, 3]) // Cursor of Player
|
||||
/// while let player = try players.next() { // Player
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
@@ -62,16 +77,13 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// - keys: A sequence of primary keys.
|
||||
/// - returns: A cursor over fetched records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> DatabaseCursor<Self>? where Sequence.Iterator.Element: DatabaseValueConvertible {
|
||||
guard let statement = try makeFetchByPrimaryKeyStatement(db, keys: keys) else {
|
||||
return nil
|
||||
}
|
||||
return try fetchCursor(statement)
|
||||
public static func fetchCursor<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> RecordCursor<Self> where Sequence.Element: DatabaseValueConvertible {
|
||||
return try filter(keys: keys).fetchCursor(db)
|
||||
}
|
||||
|
||||
/// Returns an array of records, given their primary keys.
|
||||
///
|
||||
/// let persons = try Person.fetchAll(db, keys: [1, 2, 3]) // [Person]
|
||||
/// let players = try Player.fetchAll(db, keys: [1, 2, 3]) // [Player]
|
||||
///
|
||||
/// The order of records in the returned array is undefined.
|
||||
///
|
||||
@@ -80,16 +92,18 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// - keys: A sequence of primary keys.
|
||||
/// - returns: An array of records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> [Self] where Sequence.Iterator.Element: DatabaseValueConvertible {
|
||||
guard let statement = try makeFetchByPrimaryKeyStatement(db, keys: keys) else {
|
||||
public static func fetchAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> [Self] where Sequence.Element: DatabaseValueConvertible {
|
||||
let keys = Array(keys)
|
||||
if keys.isEmpty {
|
||||
// Avoid hitting the database
|
||||
return []
|
||||
}
|
||||
return try fetchAll(statement)
|
||||
return try filter(keys: keys).fetchAll(db)
|
||||
}
|
||||
|
||||
/// Returns a single record given its primary key.
|
||||
///
|
||||
/// let person = try Person.fetchOne(db, key: 123) // Person?
|
||||
/// let player = try Player.fetchOne(db, key: 123) // Player?
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
@@ -98,43 +112,10 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: Database, key: PrimaryKeyType?) throws -> Self? {
|
||||
guard let key = key else {
|
||||
// Avoid hitting the database
|
||||
return nil
|
||||
}
|
||||
return try fetchOne(makeFetchByPrimaryKeyStatement(db, keys: [key])!)
|
||||
}
|
||||
|
||||
// Returns "SELECT * FROM table WHERE id IN (?,?,?)"
|
||||
//
|
||||
// Returns nil if values is empty.
|
||||
private static func makeFetchByPrimaryKeyStatement<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> SelectStatement? where Sequence.Iterator.Element: DatabaseValueConvertible {
|
||||
// Fail early if database table does not exist.
|
||||
let databaseTableName = self.databaseTableName
|
||||
let primaryKey = try db.primaryKey(databaseTableName)
|
||||
|
||||
// Fail early if database table has not one column in its primary key
|
||||
let columns = primaryKey?.columns ?? []
|
||||
GRDBPrecondition(columns.count <= 1, "requires single column primary key in table: \(databaseTableName)")
|
||||
let column = columns.first ?? Column.rowID.name
|
||||
|
||||
let keys = Array(keys)
|
||||
switch keys.count {
|
||||
case 0:
|
||||
// Avoid performing useless SELECT
|
||||
return nil
|
||||
case 1:
|
||||
// SELECT * FROM table WHERE id = ?
|
||||
let sql = "SELECT \(defaultSelection) FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) = ?"
|
||||
let statement = try db.makeSelectStatement(sql)
|
||||
statement.arguments = StatementArguments(keys)
|
||||
return statement
|
||||
case let count:
|
||||
// SELECT * FROM table WHERE id IN (?,?,?)
|
||||
let keysSQL = databaseQuestionMarks(count: count)
|
||||
let sql = "SELECT \(defaultSelection) FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) IN (\(keysSQL))"
|
||||
let statement = try db.makeSelectStatement(sql)
|
||||
statement.arguments = StatementArguments(keys)
|
||||
return statement
|
||||
}
|
||||
return try filter(key: key).fetchOne(db)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,8 +126,8 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// Returns a cursor over records identified by the provided unique keys
|
||||
/// (primary key or any key with a unique index on it).
|
||||
///
|
||||
/// let persons = try Person.fetchCursor(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // DatabaseCursor<Person>
|
||||
/// while let person = try persons.next() { // Person
|
||||
/// let players = try Player.fetchCursor(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // Cursor of Player
|
||||
/// while let player = try players.next() { // Player
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
@@ -157,17 +138,14 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// - keys: An array of key dictionaries.
|
||||
/// - returns: A cursor over fetched records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> DatabaseCursor<Self>? {
|
||||
guard let statement = try makeFetchByKeyStatement(db, keys: keys) else {
|
||||
return nil
|
||||
}
|
||||
return try fetchCursor(statement)
|
||||
public static func fetchCursor(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> RecordCursor<Self> {
|
||||
return try filter(keys: keys).fetchCursor(db)
|
||||
}
|
||||
|
||||
/// Returns an array of records identified by the provided unique keys
|
||||
/// (primary key or any key with a unique index on it).
|
||||
///
|
||||
/// let persons = try Person.fetchAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // [Person]
|
||||
/// let players = try Player.fetchAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // [Player]
|
||||
///
|
||||
/// The order of records in the returned array is undefined.
|
||||
///
|
||||
@@ -177,71 +155,28 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// - returns: An array of records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> [Self] {
|
||||
guard let statement = try makeFetchByKeyStatement(db, keys: keys) else {
|
||||
if keys.isEmpty {
|
||||
// Avoid hitting the database
|
||||
return []
|
||||
}
|
||||
return try fetchAll(statement)
|
||||
return try filter(keys: keys).fetchAll(db)
|
||||
}
|
||||
|
||||
/// Returns a single record identified by a unique key (the primary key or
|
||||
/// any key with a unique index on it).
|
||||
///
|
||||
/// let person = try Person.fetchOne(db, key: ["name": Arthur"]) // Person?
|
||||
/// let player = try Player.fetchOne(db, key: ["name": Arthur"]) // Player?
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - key: A dictionary of values.
|
||||
/// - returns: An optional record.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Self? {
|
||||
return try fetchOne(makeFetchByKeyStatement(db, keys: [key])!)
|
||||
}
|
||||
|
||||
// Returns "SELECT * FROM table WHERE (a = ? AND b = ?) OR (a = ? AND b = ?) ...
|
||||
//
|
||||
// Returns nil if keys is empty.
|
||||
//
|
||||
// If there is no unique index on the columns, the method raises a fatal
|
||||
// (unless fatalErrorOnMissingUniqueIndex is false, for testability).
|
||||
static func makeFetchByKeyStatement(_ db: Database, keys: [[String: DatabaseValueConvertible?]], fatalErrorOnMissingUniqueIndex: Bool = true) throws -> SelectStatement? {
|
||||
// Avoid performing useless SELECT
|
||||
guard keys.count > 0 else {
|
||||
public static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]?) throws -> Self? {
|
||||
guard let key = key else {
|
||||
// Avoid hitting the database
|
||||
return nil
|
||||
}
|
||||
|
||||
let databaseTableName = self.databaseTableName
|
||||
var arguments: [DatabaseValueConvertible?] = []
|
||||
var whereClauses: [String] = []
|
||||
for dictionary in keys {
|
||||
GRDBPrecondition(dictionary.count > 0, "Invalid empty key dictionary")
|
||||
let columns = Array(dictionary.keys)
|
||||
guard let orderedColumns = try db.columnsForUniqueKey(columns, in: databaseTableName) else {
|
||||
let error = DatabaseError(resultCode: .SQLITE_MISUSE, message: "table \(databaseTableName) has no unique index on column(s) \(columns.sorted().joined(separator: ", "))")
|
||||
if fatalErrorOnMissingUniqueIndex {
|
||||
// Programmer error
|
||||
fatalError(error.description)
|
||||
} else {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
arguments.append(contentsOf: orderedColumns.map { orderedColumn in
|
||||
dictionary.first { (column, value) in column.lowercased() == orderedColumn.lowercased() }!.value
|
||||
})
|
||||
whereClauses.append("(" + (orderedColumns.map { "\($0.quotedDatabaseIdentifier) = ?" } as [String]).joined(separator: " AND ") + ")")
|
||||
}
|
||||
|
||||
let whereClause = whereClauses.joined(separator: " OR ")
|
||||
let sql = "SELECT \(defaultSelection) FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(whereClause)"
|
||||
let statement = try db.makeSelectStatement(sql)
|
||||
statement.arguments = StatementArguments(arguments)
|
||||
return statement
|
||||
}
|
||||
|
||||
fileprivate static var defaultSelection: String {
|
||||
if selectsRowID {
|
||||
return "*, rowid"
|
||||
} else {
|
||||
return "*"
|
||||
}
|
||||
return try filter(key: key).fetchOne(db)
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,30 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// Types that adopt RowConvertible can be initialized from a database Row.
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, "SELECT ...")!
|
||||
/// let person = Person(row)
|
||||
/// let player = Player(row)
|
||||
///
|
||||
/// The protocol comes with built-in methods that allow to fetch cursors,
|
||||
/// arrays, or single records:
|
||||
///
|
||||
/// try Person.fetchCursor(db, "SELECT ...", arguments:...) // DatabaseCursor<Person>
|
||||
/// try Person.fetchAll(db, "SELECT ...", arguments:...) // [Person]
|
||||
/// try Person.fetchOne(db, "SELECT ...", arguments:...) // Person?
|
||||
/// try Player.fetchCursor(db, "SELECT ...", arguments:...) // Cursor of Player
|
||||
/// try Player.fetchAll(db, "SELECT ...", arguments:...) // [Player]
|
||||
/// try Player.fetchOne(db, "SELECT ...", arguments:...) // Player?
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT ...")
|
||||
/// try Person.fetchCursor(statement, arguments:...) // DatabaseCursor<Person>
|
||||
/// try Person.fetchAll(statement, arguments:...) // [Person]
|
||||
/// try Person.fetchOne(statement, arguments:...) // Person?
|
||||
/// try Player.fetchCursor(statement, arguments:...) // Cursor of Player
|
||||
/// try Player.fetchAll(statement, arguments:...) // [Player]
|
||||
/// try Player.fetchOne(statement, arguments:...) // Player?
|
||||
///
|
||||
/// RowConvertible is adopted by Record.
|
||||
public protocol RowConvertible {
|
||||
|
||||
/// Initializes a record from `row`.
|
||||
/// Creates a record from `row`.
|
||||
///
|
||||
/// For performance reasons, the row argument may be reused during the
|
||||
/// iteration of a fetch query. If you want to keep the row for later use,
|
||||
@@ -26,15 +32,50 @@ public protocol RowConvertible {
|
||||
init(row: Row)
|
||||
}
|
||||
|
||||
/// A cursor of records. For example:
|
||||
///
|
||||
/// struct Player : RowConvertible { ... }
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let players: RecordCursor<Player> = try Player.fetchCursor(db, "SELECT * FROM players")
|
||||
/// }
|
||||
public final class RecordCursor<Record: RowConvertible> : Cursor {
|
||||
private let statement: SelectStatement
|
||||
private let row: Row // Reused for performance
|
||||
private let sqliteStatement: SQLiteStatement
|
||||
private var done = false
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
self.row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func next() throws -> Record? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return Record(row: row)
|
||||
case let code:
|
||||
statement.database.selectStatementDidFail(statement)
|
||||
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension RowConvertible {
|
||||
|
||||
// MARK: Fetching From SelectStatement
|
||||
|
||||
/// A cursor over records fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT * FROM persons")
|
||||
/// let persons = try Person.fetchCursor(statement) // DatabaseCursor<Person>
|
||||
/// while let person = try persons.next() { // Person
|
||||
/// let statement = try db.makeSelectStatement("SELECT * FROM players")
|
||||
/// let players = try Player.fetchCursor(statement) // Cursor of Player
|
||||
/// while let player = try players.next() { // Player
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
@@ -49,17 +90,14 @@ extension RowConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
|
||||
// Reuse a single mutable row for performance.
|
||||
// It is the record's responsibility to copy the row if needed.
|
||||
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
return statement.cursor(arguments: arguments, next: { self.init(row: row) })
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self> {
|
||||
return try RecordCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of records fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT * FROM persons")
|
||||
/// let persons = try Person.fetchAll(statement) // [Person]
|
||||
/// let statement = try db.makeSelectStatement("SELECT * FROM players")
|
||||
/// let players = try Player.fetchAll(statement) // [Player]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
@@ -73,8 +111,8 @@ extension RowConvertible {
|
||||
|
||||
/// Returns a single record fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT * FROM persons")
|
||||
/// let person = try Person.fetchOne(statement) // Person?
|
||||
/// let statement = try db.makeSelectStatement("SELECT * FROM players")
|
||||
/// let player = try Player.fetchOne(statement) // Player?
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
@@ -94,8 +132,8 @@ extension RowConvertible {
|
||||
/// Returns a cursor over records fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("firstName")
|
||||
/// let request = Person.order(nameColumn)
|
||||
/// let identities = try Identity.fetchCursor(db, request) // DatabaseCursor<Identity>
|
||||
/// let request = Player.order(nameColumn)
|
||||
/// let identities = try Identity.fetchCursor(db, request) // Cursor of Identity
|
||||
/// while let identity = try identities.next() { // Identity
|
||||
/// ...
|
||||
/// }
|
||||
@@ -110,7 +148,7 @@ extension RowConvertible {
|
||||
/// - request: A fetch request.
|
||||
/// - returns: A cursor over fetched records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseCursor<Self> {
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> RecordCursor<Self> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
@@ -118,7 +156,7 @@ extension RowConvertible {
|
||||
/// Returns an array of records fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.order(nameColumn)
|
||||
/// let request = Player.order(nameColumn)
|
||||
/// let identities = try Identity.fetchAll(db, request) // [Identity]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -131,7 +169,7 @@ extension RowConvertible {
|
||||
/// Returns a single record fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.order(nameColumn)
|
||||
/// let request = Player.order(nameColumn)
|
||||
/// let identity = try Identity.fetchOne(db, request) // Identity?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -148,8 +186,8 @@ extension RowConvertible {
|
||||
|
||||
/// Returns a cursor over records fetched from an SQL query.
|
||||
///
|
||||
/// let persons = try Person.fetchCursor(db, "SELECT * FROM persons") // DatabaseCursor<Person>
|
||||
/// while let person = try persons.next() { // Person
|
||||
/// let players = try Player.fetchCursor(db, "SELECT * FROM players") // Cursor of Player
|
||||
/// while let player = try players.next() { // Player
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
@@ -165,13 +203,13 @@ extension RowConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self> {
|
||||
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of records fetched from an SQL query.
|
||||
///
|
||||
/// let persons = try Person.fetchAll(db, "SELECT * FROM persons") // [Person]
|
||||
/// let players = try Player.fetchAll(db, "SELECT * FROM players") // [Player]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
@@ -186,7 +224,7 @@ extension RowConvertible {
|
||||
|
||||
/// Returns a single record fetched from an SQL query.
|
||||
///
|
||||
/// let person = try Person.fetchOne(db, "SELECT * FROM persons") // Person?
|
||||
/// let player = try Player.fetchOne(db, "SELECT * FROM players") // Player?
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
|
||||
+77
-219
@@ -4,37 +4,61 @@
|
||||
/// Types that adopt both TableMapping and RowConvertible are granted with
|
||||
/// built-in methods that allow to fetch instances identified by key:
|
||||
///
|
||||
/// try Person.fetchOne(db, key: 123) // Person?
|
||||
/// try Citizenship.fetchOne(db, key: ["personId": 12, "countryId": 45]) // Citizenship?
|
||||
/// try Player.fetchOne(db, key: 123) // Player?
|
||||
/// try Citizenship.fetchOne(db, key: ["citizenId": 12, "countryId": 45]) // Citizenship?
|
||||
///
|
||||
/// TableMapping is adopted by Record.
|
||||
public protocol TableMapping {
|
||||
/// The name of the database table
|
||||
/// The name of the database table used to build requests.
|
||||
///
|
||||
/// struct Player : TableMapping {
|
||||
/// static var databaseTableName = "players"
|
||||
/// }
|
||||
///
|
||||
/// // SELECT * FROM players
|
||||
/// try Player.fetchAll(db)
|
||||
static var databaseTableName: String { get }
|
||||
|
||||
/// This flag tells whether the hidden "rowid" column should be fetched
|
||||
/// with other columns.
|
||||
/// The default request selection.
|
||||
///
|
||||
/// Its default value is false:
|
||||
/// Unless said otherwise, requests select all columns:
|
||||
///
|
||||
/// // SELECT * FROM persons
|
||||
/// try Person.fetchAll(db)
|
||||
/// // SELECT * FROM players
|
||||
/// try Player.fetchAll(db)
|
||||
///
|
||||
/// When true, the rowid column is fetched:
|
||||
/// You can provide a custom implementation and provide an explicit list
|
||||
/// of columns:
|
||||
///
|
||||
/// // SELECT *, rowid FROM persons
|
||||
/// try Person.fetchAll(db)
|
||||
static var selectsRowID: Bool { get }
|
||||
/// struct RestrictedPlayer : TableMapping {
|
||||
/// static var databaseTableName = "players"
|
||||
/// static var databaseSelection = [Column("id"), Column("name")]
|
||||
/// }
|
||||
///
|
||||
/// // SELECT id, name FROM players
|
||||
/// try RestrictedPlayer.fetchAll(db)
|
||||
///
|
||||
/// You can also add extra columns such as the `rowid` column:
|
||||
///
|
||||
/// struct ExtendedPlayer : TableMapping {
|
||||
/// static var databaseTableName = "players"
|
||||
/// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
|
||||
/// }
|
||||
///
|
||||
/// // SELECT *, rowid FROM players
|
||||
/// try ExtendedPlayer.fetchAll(db)
|
||||
static var databaseSelection: [SQLSelectable] { get }
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
/// Default value: false.
|
||||
public static var selectsRowID: Bool { return false }
|
||||
/// Default value: `[AllColumns()]`.
|
||||
public static var databaseSelection: [SQLSelectable] {
|
||||
return [AllColumns()]
|
||||
}
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
|
||||
// MARK: Counting All
|
||||
// MARK: - Counting All
|
||||
|
||||
/// The number of records.
|
||||
///
|
||||
@@ -46,219 +70,53 @@ extension TableMapping {
|
||||
|
||||
extension TableMapping {
|
||||
|
||||
// MARK: Deleting All
|
||||
// MARK: - SQL Generation
|
||||
|
||||
/// Deletes all records; returns the number of deleted rows.
|
||||
/// The selection as an SQL String.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: The number of deleted rows
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
@discardableResult
|
||||
public static func deleteAll(_ db: Database) throws -> Int {
|
||||
return try all().deleteAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
|
||||
// MARK: Deleting by Single-Column Primary Key
|
||||
|
||||
/// Delete records identified by their primary keys; returns the number of
|
||||
/// deleted rows.
|
||||
/// For example:
|
||||
///
|
||||
/// try Person.deleteAll(db, keys: [1, 2, 3])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - keys: A sequence of primary keys.
|
||||
/// - returns: The number of deleted rows
|
||||
@discardableResult
|
||||
public static func deleteAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> Int where Sequence.Iterator.Element: DatabaseValueConvertible {
|
||||
guard let statement = try makeDeleteByPrimaryKeyStatement(db, keys: keys) else {
|
||||
return 0
|
||||
}
|
||||
try statement.execute()
|
||||
return db.changesCount
|
||||
}
|
||||
|
||||
/// Delete a record, identified by its primary key; returns whether a
|
||||
/// database row was deleted.
|
||||
///
|
||||
/// try Person.deleteOne(db, key: 123)
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - key: A primary key value.
|
||||
/// - returns: Whether a database row was deleted.
|
||||
@discardableResult
|
||||
public static func deleteOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: Database, key: PrimaryKeyType?) throws -> Bool {
|
||||
guard let key = key else {
|
||||
return false
|
||||
}
|
||||
return try deleteAll(db, keys: [key]) > 0
|
||||
}
|
||||
|
||||
// Returns "DELETE FROM table WHERE id IN (?,?,?)"
|
||||
//
|
||||
// Returns nil if keys is empty.
|
||||
private static func makeDeleteByPrimaryKeyStatement<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> UpdateStatement? where Sequence.Iterator.Element: DatabaseValueConvertible {
|
||||
// Fail early if database table does not exist.
|
||||
let databaseTableName = self.databaseTableName
|
||||
let primaryKey = try db.primaryKey(databaseTableName)
|
||||
|
||||
// Fail early if database table has not one column in its primary key
|
||||
let columns = primaryKey?.columns ?? []
|
||||
GRDBPrecondition(columns.count <= 1, "requires single column primary key in table: \(databaseTableName)")
|
||||
let column = columns.first ?? Column.rowID.name
|
||||
|
||||
let keys = Array(keys)
|
||||
switch keys.count {
|
||||
case 0:
|
||||
// Avoid performing useless DELETE
|
||||
return nil
|
||||
case 1:
|
||||
// DELETE FROM table WHERE id = ?
|
||||
let sql = "DELETE FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) = ?"
|
||||
let statement = try db.makeUpdateStatement(sql)
|
||||
statement.arguments = StatementArguments(keys)
|
||||
return statement
|
||||
case let count:
|
||||
// DELETE FROM table WHERE id IN (?,?,?)
|
||||
let keysSQL = databaseQuestionMarks(count: count)
|
||||
let sql = "DELETE FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) IN (\(keysSQL))"
|
||||
let statement = try db.makeUpdateStatement(sql)
|
||||
statement.arguments = StatementArguments(keys)
|
||||
return statement
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
|
||||
// MARK: Deleting by Key
|
||||
|
||||
/// Delete records identified by the provided unique keys (primary key or
|
||||
/// any key with a unique index on it); returns the number of deleted rows.
|
||||
///
|
||||
/// try Person.deleteAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - keys: An array of key dictionaries.
|
||||
/// - returns: The number of deleted rows
|
||||
@discardableResult
|
||||
public static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int {
|
||||
guard let statement = try makeDeleteByKeyStatement(db, keys: keys) else {
|
||||
return 0
|
||||
}
|
||||
try statement.execute()
|
||||
return db.changesCount
|
||||
}
|
||||
|
||||
/// Delete a record, identified by a unique key (the primary key or any key
|
||||
/// with a unique index on it); returns whether a database row was deleted.
|
||||
///
|
||||
/// Person.deleteOne(db, key: ["name": Arthur"])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - key: A dictionary of values.
|
||||
/// - returns: Whether a database row was deleted.
|
||||
@discardableResult
|
||||
public static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool {
|
||||
return try deleteAll(db, keys: [key]) > 0
|
||||
}
|
||||
|
||||
// Returns "DELETE FROM table WHERE (a = ? AND b = ?) OR (a = ? AND b = ?) ...
|
||||
//
|
||||
// Returns nil if keys is empty.
|
||||
//
|
||||
// If there is no unique index on the columns, the method raises a fatal
|
||||
// (unless fatalErrorOnMissingUniqueIndex is false, for testability).
|
||||
static func makeDeleteByKeyStatement(_ db: Database, keys: [[String: DatabaseValueConvertible?]], fatalErrorOnMissingUniqueIndex: Bool = true) throws -> UpdateStatement? {
|
||||
// Avoid performing useless SELECT
|
||||
guard keys.count > 0 else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let databaseTableName = self.databaseTableName
|
||||
var arguments: [DatabaseValueConvertible?] = []
|
||||
var whereClauses: [String] = []
|
||||
for dictionary in keys {
|
||||
GRDBPrecondition(dictionary.count > 0, "Invalid empty key dictionary")
|
||||
let columns = Array(dictionary.keys)
|
||||
guard let orderedColumns = try db.columnsForUniqueKey(columns, in: databaseTableName) else {
|
||||
let error = DatabaseError(resultCode: .SQLITE_MISUSE, message: "table \(databaseTableName) has no unique index on column(s) \(columns.sorted().joined(separator: ", "))")
|
||||
if fatalErrorOnMissingUniqueIndex {
|
||||
fatalError(error.description)
|
||||
} else {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
arguments.append(contentsOf: orderedColumns.map { orderedColumn in
|
||||
dictionary.first { (column, value) in column.lowercased() == orderedColumn.lowercased() }!.value
|
||||
})
|
||||
whereClauses.append("(" + (orderedColumns.map { "\($0.quotedDatabaseIdentifier) = ?" } as [String]).joined(separator: " AND ") + ")")
|
||||
}
|
||||
|
||||
let whereClause = whereClauses.joined(separator: " OR ")
|
||||
let sql = "DELETE FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(whereClause)"
|
||||
let statement = try db.makeUpdateStatement(sql)
|
||||
statement.arguments = StatementArguments(arguments)
|
||||
return statement
|
||||
}
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
/// Returns a function that returns the primary key of a row.
|
||||
///
|
||||
/// If the table has no primary key, and selectsRowID is true, the primary
|
||||
/// key is the "rowid" column.
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let primaryKey = try Person.rowPrimaryKey(db)
|
||||
/// let row = try Row.fetchOne(db, "SELECT * FROM persons")!
|
||||
/// primaryKey(row) // ["id": 1]
|
||||
/// struct Player: TableMapping {
|
||||
/// static let databaseTableName = "players"
|
||||
/// }
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
static func rowPrimaryKey(_ db: Database) throws -> (Row) -> [String: DatabaseValue] {
|
||||
if let primaryKey = try db.primaryKey(databaseTableName) {
|
||||
let columns = primaryKey.columns
|
||||
return { row in Dictionary(keys: columns) { row.value(named: $0) } }
|
||||
} else if selectsRowID {
|
||||
return { row in [Column.rowID.name: row.value(Column.rowID)] }
|
||||
} else {
|
||||
return { _ in [:] }
|
||||
}
|
||||
/// // SELECT "players".* FROM players
|
||||
/// let sql = "SELECT \(Player.selectionSQL()) FROM players"
|
||||
///
|
||||
/// // SELECT "p".* FROM players AS p
|
||||
/// let sql = "SELECT \(Player.selectionSQL(alias: "p")) FROM players AS p"
|
||||
public static func selectionSQL(alias: String? = nil) -> String {
|
||||
let qualifier = SQLTableQualifier(tableName: databaseTableName, alias: alias ?? databaseTableName)
|
||||
let selection = databaseSelection.map { $0.qualified(by: qualifier) }
|
||||
var arguments: StatementArguments? = nil
|
||||
return selection
|
||||
.map { $0.resultColumnSQL(&arguments) }
|
||||
.joined(separator: ", ")
|
||||
}
|
||||
|
||||
/// Returns a function that returns true if and only if two rows have the
|
||||
/// same primary key and both primary keys contain at least one non-null
|
||||
/// value.
|
||||
/// Returns the number of selected columns.
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let comparator = try Person.primaryKeyRowComparator(db)
|
||||
/// let row0 = Row(["id": nil, "name": "Unsaved"])
|
||||
/// let row1 = Row(["id": 1, "name": "Arthur"])
|
||||
/// let row2 = Row(["id": 1, "name": "Arthur"])
|
||||
/// let row3 = Row(["id": 2, "name": "Barbara"])
|
||||
/// comparator(row0, row0) // false
|
||||
/// comparator(row1, row2) // true
|
||||
/// comparator(row1, row3) // false
|
||||
/// For example:
|
||||
///
|
||||
/// struct Player: TableMapping {
|
||||
/// static let databaseTableName = "players"
|
||||
/// }
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
/// - attention: This method is deprecated. It will be removed is the next
|
||||
/// major version of the library, without any replacement.
|
||||
@available(*, deprecated)
|
||||
public static func primaryKeyRowComparator(_ db: Database) throws -> (Row, Row) -> Bool {
|
||||
let primaryKey = try rowPrimaryKey(db)
|
||||
return { (lhs, rhs) in
|
||||
let (lhs, rhs) = (primaryKey(lhs), primaryKey(rhs))
|
||||
guard lhs.contains(where: { !$1.isNull }) else { return false }
|
||||
guard rhs.contains(where: { !$1.isNull }) else { return false }
|
||||
return lhs == rhs
|
||||
}
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("id", .integer).primaryKey()
|
||||
/// t.column("name", .text)
|
||||
/// t.column("score", .integer)
|
||||
/// }
|
||||
///
|
||||
/// // 3
|
||||
/// try Player.numberOfSelectedColumns(db)
|
||||
/// }
|
||||
public static func numberOfSelectedColumns(_ db: Database) throws -> Int {
|
||||
let qualifier = SQLTableQualifier(tableName: databaseTableName, alias: nil)
|
||||
return try databaseSelection
|
||||
.map { try $0.qualified(by: qualifier).columnCount(db) }
|
||||
.reduce(0, +)
|
||||
}
|
||||
}
|
||||
|
||||
+8
-24
@@ -1,9 +1,5 @@
|
||||
import Foundation
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#endif
|
||||
|
||||
// MARK: - Public
|
||||
|
||||
extension String {
|
||||
@@ -27,16 +23,24 @@ public func databaseQuestionMarks(count: Int) -> String {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// This protocol is an implementation detail of GRDB. Don't use it.
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol _OptionalProtocol {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
associatedtype _Wrapped
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// This conformance is an implementation detail of GRDB. Don't rely on it.
|
||||
///
|
||||
/// :nodoc:
|
||||
extension Optional : _OptionalProtocol {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public typealias _Wrapped = Wrapped
|
||||
}
|
||||
|
||||
@@ -48,8 +52,6 @@ func GRDBPrecondition(_ condition: @autoclosure() -> Bool, _ message: @autoclosu
|
||||
/// Custom precondition function which aims at solving
|
||||
/// https://bugs.swift.org/browse/SR-905 and
|
||||
/// https://github.com/groue/GRDB.swift/issues/37
|
||||
///
|
||||
/// TODO: remove this function when https://bugs.swift.org/browse/SR-905 is solved.
|
||||
if !condition() {
|
||||
fatalError(message, file: file, line: line)
|
||||
}
|
||||
@@ -69,21 +71,3 @@ extension Array {
|
||||
}
|
||||
}
|
||||
|
||||
extension Dictionary {
|
||||
|
||||
/// Create a dictionary with the keys and values in the given sequence.
|
||||
init<Sequence: Swift.Sequence>(keyValueSequence: Sequence) where Sequence.Iterator.Element == (Key, Value) {
|
||||
self.init(minimumCapacity: keyValueSequence.underestimatedCount)
|
||||
for (key, value) in keyValueSequence {
|
||||
self[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a dictionary from keys and a value builder.
|
||||
init<Sequence: Swift.Sequence>(keys: Sequence, value: (Key) -> Value) where Sequence.Iterator.Element == Key {
|
||||
self.init(minimumCapacity: keys.underestimatedCount)
|
||||
for key in keys {
|
||||
self[key] = value(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDBCipher'
|
||||
s.version = '1.2'
|
||||
s.version = '2.9.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A Swift application toolkit for SQLite databases.'
|
||||
@@ -13,12 +13,12 @@ Pod::Spec.new do |s|
|
||||
s.osx.deployment_target = '10.9'
|
||||
s.watchos.deployment_target = '2.0'
|
||||
|
||||
s.source_files = 'GRDB/**/*.swift', 'SQLCipher/*.h', 'Support/grdb_config.{c,h}'
|
||||
s.source_files = 'GRDB/**/*.swift', 'SQLCipher/*.h', 'Support/grdb_config.h'
|
||||
s.module_map = 'SQLCipher/module.modulemap'
|
||||
s.xcconfig = {
|
||||
'OTHER_SWIFT_FLAGS' => '$(inherited) -DSQLITE_HAS_CODEC -DGRDBCIPHER',
|
||||
'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_HAS_CODEC -D GRDBCIPHER',
|
||||
'OTHER_CFLAGS' => '$(inherited) -DSQLITE_HAS_CODEC -DGRDBCIPHER',
|
||||
'GCC_PREPROCESSOR_DEFINITIONS' => '$(inherited) SQLITE_HAS_CODEC=1'
|
||||
'GCC_PREPROCESSOR_DEFINITIONS' => '$(inherited) SQLITE_HAS_CODEC=1 GRDBCIPHER=1'
|
||||
}
|
||||
s.framework = 'Foundation'
|
||||
s.dependency 'SQLCipher', '~> 3.4.1'
|
||||
|
||||
Executable
+3199
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
<FileRef
|
||||
location = "self:GRDBCipher.xcodeproj">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
Loaded 100 of 270 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user