Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a88067a815 | ||
|
|
6fd3a7b225 | ||
|
|
6b1910fce7 | ||
|
|
5ee47c3c27 | ||
|
|
5652a01366 | ||
|
|
132d01f9f7 | ||
|
|
1d760ff9ce | ||
|
|
dc4d516493 | ||
|
|
62c6187ad4 | ||
|
|
18154f29be | ||
|
|
df4d5b8603 | ||
|
|
a7b8a73dba | ||
|
|
278c18adfc | ||
|
|
cbd494e3b9 | ||
|
|
c73fb0dd9b | ||
|
|
c966eb3ecf | ||
|
|
217b0a3f3e | ||
|
|
e604a10860 | ||
|
|
ac4f4c6611 | ||
|
|
162da80e4f | ||
|
|
315496928b | ||
|
|
d82cbb6853 | ||
|
|
5fed231856 | ||
|
|
45dfe7d7f1 | ||
|
|
c7d1cca023 | ||
|
|
615f4159d6 | ||
|
|
8057572357 | ||
|
|
da63037948 | ||
|
|
2d3dafad7d | ||
|
|
7ed967b502 | ||
|
|
f545789205 | ||
|
|
79373d5b74 | ||
|
|
f97088d63a | ||
|
|
860faf19f7 | ||
|
|
0f54779386 | ||
|
|
6f125bd3d7 | ||
|
|
4483f037a4 | ||
|
|
20296652dd | ||
|
|
d80922954a | ||
|
|
d67814ef61 | ||
|
|
fb550d30a0 | ||
|
|
a715c6328d | ||
|
|
bffe4d32f5 | ||
|
|
3fd00012d1 | ||
|
|
6d901b06e9 | ||
|
|
f677310703 | ||
|
|
0200f64e6c | ||
|
|
c6b5c935bb | ||
|
|
2d30f06f54 | ||
|
|
a98350d206 | ||
|
|
6918bda82d | ||
|
|
a065926fb1 | ||
|
|
0569b95a5a | ||
|
|
d17866d3fd | ||
|
|
6c0f1dc389 | ||
|
|
e7750e6fe0 | ||
|
|
e4addc4243 | ||
|
|
d35ad59f9c | ||
|
|
07609e8a3f | ||
|
|
f4e2645e13 | ||
|
|
c352ca70b2 | ||
|
|
b182a26759 | ||
|
|
c493b17232 | ||
|
|
94d34a744d | ||
|
|
0cda88bd28 | ||
|
|
c62ccf1de7 | ||
|
|
5760b9c0cc | ||
|
|
75525bdb56 | ||
|
|
2fa57cdafa | ||
|
|
2319572552 | ||
|
|
5f26a71c5b | ||
|
|
d0558ee2f0 | ||
|
|
fc09fd6654 | ||
|
|
1ea5d1713a | ||
|
|
aa0ae00c56 | ||
|
|
0372c1dd63 | ||
|
|
c052b44999 | ||
|
|
f27d6b07c0 | ||
|
|
4f8b681737 | ||
|
|
5b9ae9371b | ||
|
|
68f4db468a | ||
|
|
62dbc78090 | ||
|
|
bd7bec22a1 | ||
|
|
722e74db6a | ||
|
|
e9439a1d58 | ||
|
|
3c70814cdc | ||
|
|
fea89100d9 | ||
|
|
2c3d0b1e17 | ||
|
|
478ae7bc24 | ||
|
|
da81c8b87c | ||
|
|
4088a477ec | ||
|
|
85dcd32c8d | ||
|
|
62c72c20e9 | ||
|
|
1b4e26f61c | ||
|
|
474310e00b | ||
|
|
7a475ad476 | ||
|
|
65ac210dfb | ||
|
|
f19e5bf67c | ||
|
|
419bedd73b | ||
|
|
8eb58926a4 | ||
|
|
ccacbc9706 | ||
|
|
7db59867cb | ||
|
|
37aa7feee9 | ||
|
|
e49800d21d | ||
|
|
078aa83e3b | ||
|
|
8ef4c9b241 | ||
|
|
f9157da590 | ||
|
|
27120643b9 | ||
|
|
306033b63b | ||
|
|
d988be49a6 | ||
|
|
1a5661c890 | ||
|
|
ccaad8d860 | ||
|
|
c9d95af646 | ||
|
|
3e081f0dd6 | ||
|
|
444525d748 | ||
|
|
c778e1ac0c | ||
|
|
bfe037c61d | ||
|
|
e2790c863f | ||
|
|
3c3df9ad24 | ||
|
|
3c30e6d0c1 | ||
|
|
a5ad4dd23d | ||
|
|
0505b1cef9 | ||
|
|
2ac6f9766a | ||
|
|
10fcd1092f | ||
|
|
cbcbbe9c8f | ||
|
|
2b7b03846e | ||
|
|
05f9854cea | ||
|
|
8cb67f1c22 | ||
|
|
48987f39c3 | ||
|
|
e5f711f68c | ||
|
|
ac92fc95e3 | ||
|
|
ed15498871 | ||
|
|
97a05b97d9 | ||
|
|
0b69aa82fd | ||
|
|
bf07c49171 | ||
|
|
c59d42dfca | ||
|
|
80b15f7f07 | ||
|
|
9647a78ed6 | ||
|
|
2c743531d0 | ||
|
|
9e967ccc93 | ||
|
|
86330000db | ||
|
|
af597736f6 | ||
|
|
119ce30ad1 | ||
|
|
85c3f12b86 | ||
|
|
f95e01cbd5 | ||
|
|
21eb87fa49 | ||
|
|
4614cfda06 | ||
|
|
a4bda6da96 | ||
|
|
2d2b8494d0 | ||
|
|
7ce6a8a094 | ||
|
|
3756c43691 | ||
|
|
bfc4738097 | ||
|
|
afcb9183ad | ||
|
|
c3474471f7 | ||
|
|
65c009a018 | ||
|
|
d60fe3c22f | ||
|
|
5727163966 | ||
|
|
d72000c6a3 | ||
|
|
381f716e4b | ||
|
|
eee2c65c14 | ||
|
|
c01c4d6de5 | ||
|
|
f4c763dc31 | ||
|
|
66989f2ff7 | ||
|
|
73aada9194 | ||
|
|
5665a2428a | ||
|
|
ba0c771346 | ||
|
|
66dc482b02 | ||
|
|
3c20adb0c6 | ||
|
|
1bffc4f628 | ||
|
|
97a84c6470 | ||
|
|
70c6f3ec44 | ||
|
|
ccd73bf63d | ||
|
|
d4327faf0a | ||
|
|
87b54f5da2 | ||
|
|
a28ae9a523 | ||
|
|
055a4882f8 | ||
|
|
90d5316781 | ||
|
|
303a0cc150 | ||
|
|
08ef740002 | ||
|
|
5d196c449d | ||
|
|
fdb2f63e60 | ||
|
|
c83d390e60 | ||
|
|
a6ac69eded | ||
|
|
1914ace5f9 | ||
|
|
88ddce5fac | ||
|
|
23d428290b | ||
|
|
ff104686f6 | ||
|
|
a9ea6dd8bf | ||
|
|
9866ed1dfc | ||
|
|
65a347fd98 | ||
|
|
7e50869d39 | ||
|
|
703ce643b5 | ||
|
|
42d2891df8 | ||
|
|
f0effaa4fa | ||
|
|
022fee8788 | ||
|
|
25a2bd653c | ||
|
|
c03de9cc16 | ||
|
|
97d06a0fae | ||
|
|
154125d3ae | ||
|
|
c4b7e0017b | ||
|
|
469814985e | ||
|
|
f16105ad03 | ||
|
|
4309eaba64 | ||
|
|
1580be3883 | ||
|
|
b4b5d9b602 | ||
|
|
27dd08f945 | ||
|
|
b9c4d26731 | ||
|
|
7217f696b6 | ||
|
|
880f8c8bdd | ||
|
|
6f7efa2b9a | ||
|
|
3a11d94bee | ||
|
|
e68bd077ee | ||
|
|
e84e984c23 | ||
|
|
12de05dc9b | ||
|
|
ea8110110c | ||
|
|
79d6b02a2f | ||
|
|
1195439226 | ||
|
|
ff2629a31c | ||
|
|
61e74f9ad4 | ||
|
|
f711978145 | ||
|
|
a647e200d9 | ||
|
|
294a04e9f6 | ||
|
|
9792edc008 | ||
|
|
143f3d1673 | ||
|
|
121f7be847 | ||
|
|
4af7fda4f2 | ||
|
|
56f332122d | ||
|
|
d494d12293 | ||
|
|
ce6afd680d | ||
|
|
dfd5dd2478 | ||
|
|
327f07422f | ||
|
|
6b33e656be | ||
|
|
97a7117564 | ||
|
|
e8fefc82a1 | ||
|
|
0963b162e7 | ||
|
|
5210ae8385 | ||
|
|
78dc7aee15 | ||
|
|
cf1360701c | ||
|
|
b3fb61858a | ||
|
|
8d6708a12e | ||
|
|
06f6b31368 | ||
|
|
9562e8eac4 | ||
|
|
1325a3a6a2 | ||
|
|
89058f4447 | ||
|
|
f6da862145 | ||
|
|
0c464def7f | ||
|
|
e824c70e7d | ||
|
|
7a583e02e8 | ||
|
|
98d381ed67 | ||
|
|
e16d29f277 | ||
|
|
6bf322f79e | ||
|
|
c42aab26e3 | ||
|
|
e16b320cda | ||
|
|
9d4bef1c9a | ||
|
|
b392458c1c | ||
|
|
031b55eca6 | ||
|
|
3e0486743b | ||
|
|
7ab9a8b29a | ||
|
|
22086c088f | ||
|
|
3ee231afd3 | ||
|
|
4ffced0b7b | ||
|
|
ed6673f2f5 | ||
|
|
7935168379 | ||
|
|
3c891b7ebd | ||
|
|
8f5c7985e5 | ||
|
|
2150b6688a | ||
|
|
65b8fbb361 | ||
|
|
2bb894108c | ||
|
|
26d2245ae8 | ||
|
|
2b78a646ed | ||
|
|
1c59278115 | ||
|
|
2824636650 | ||
|
|
5a884ad93d | ||
|
|
dab8e28f6d | ||
|
|
e831c64e93 | ||
|
|
50f64dc45d | ||
|
|
24872373c4 | ||
|
|
f04efea09c | ||
|
|
cda254bb2d | ||
|
|
c1d1797576 | ||
|
|
a0faf6aa68 | ||
|
|
c6db8962b3 | ||
|
|
5a9085c34d | ||
|
|
c698b30c0a | ||
|
|
dfa40ea18f | ||
|
|
936c92eba6 | ||
|
|
b0155b8aca | ||
|
|
84eef52cb0 | ||
|
|
46fba47efb | ||
|
|
bf3f97b64d | ||
|
|
b605076bd0 | ||
|
|
329b034423 | ||
|
|
5e0535d511 | ||
|
|
b96d71d937 | ||
|
|
28c32c6af8 | ||
|
|
f80c5ce348 | ||
|
|
6a582869c6 | ||
|
|
813f28e5da | ||
|
|
cc16a00f5a | ||
|
|
4f74997235 | ||
|
|
2f4187b084 | ||
|
|
9a6d6cf9c0 | ||
|
|
26e2db02aa | ||
|
|
d66f2c8cfd | ||
|
|
6f239a5ad3 | ||
|
|
2224042114 | ||
|
|
4fe201f8aa | ||
|
|
3973b66ab3 | ||
|
|
e48b654ad6 | ||
|
|
3467376d7a | ||
|
|
1b6f9f9971 | ||
|
|
c70b627f92 | ||
|
|
435f5ff559 | ||
|
|
0b34ad55b6 | ||
|
|
262cdc5b9a | ||
|
|
19061934ce | ||
|
|
7614f36bbd | ||
|
|
f48180549d | ||
|
|
93aa9bf3e5 | ||
|
|
4d60dc6cbb | ||
|
|
1698afadb9 | ||
|
|
9aa67f9db9 | ||
|
|
57d12e6c47 | ||
|
|
cc9fbed07e | ||
|
|
8718d525d4 | ||
|
|
3beba2b578 | ||
|
|
1b08a822ee | ||
|
|
7865b0a2ee | ||
|
|
a31984724e | ||
|
|
a504452846 | ||
|
|
00b0dc2a04 | ||
|
|
41e0885bce | ||
|
|
694adcec64 | ||
|
|
5dd86d2453 | ||
|
|
b9d4a5215a | ||
|
|
456d2aee75 | ||
|
|
02890a6d3a | ||
|
|
0f503fe0db | ||
|
|
bfdd0696da | ||
|
|
130e510f8c | ||
|
|
512764403f | ||
|
|
b85eca3260 | ||
|
|
73975e4462 | ||
|
|
816887b811 | ||
|
|
20baaf9a7f | ||
|
|
9578f984ec | ||
|
|
3b7f232aef | ||
|
|
df1ed3cf2f | ||
|
|
59eceb9af1 | ||
|
|
d7e821785d | ||
|
|
b264087a3b | ||
|
|
759bb8cd25 | ||
|
|
4486f73432 | ||
|
|
224e0b7d58 | ||
|
|
9db86ff2d6 | ||
|
|
f3af89cb6a | ||
|
|
98e9cc7861 | ||
|
|
30f7b39a42 | ||
|
|
6b9e7e7eb3 | ||
|
|
f6e6758525 | ||
|
|
039dd37759 | ||
|
|
e9dd8b2b09 | ||
|
|
ee64f8ff9d | ||
|
|
db546bf478 | ||
|
|
5a7c6fb33f | ||
|
|
fa7ae31894 | ||
|
|
48097ba7e7 | ||
|
|
7c684d06c1 | ||
|
|
c8321201d8 | ||
|
|
ea421865aa | ||
|
|
f5019eeb60 | ||
|
|
62222f441d | ||
|
|
0e43f1b95a | ||
|
|
50cd4418d2 | ||
|
|
e1b14d4ee5 | ||
|
|
ce0df653f4 | ||
|
|
11f8807545 | ||
|
|
7af846c87f | ||
|
|
9f46f34d16 | ||
|
|
e62df26a53 | ||
|
|
b71de1559a | ||
|
|
c2c587752c | ||
|
|
fd029ff230 | ||
|
|
c534193f5c | ||
|
|
7b29156664 | ||
|
|
9ed8cb3eff | ||
|
|
a7d02b90a5 | ||
|
|
522639282d | ||
|
|
eb98f50891 | ||
|
|
f07735f05f | ||
|
|
32675b38f1 | ||
|
|
d35d6fc2f8 | ||
|
|
fa26faa6fd | ||
|
|
91a3557281 | ||
|
|
f09e0b5ed2 | ||
|
|
0580705b1e | ||
|
|
0c7e14eb9b | ||
|
|
92e8ef9b87 | ||
|
|
692af926be | ||
|
|
a17669b082 | ||
|
|
2ff8c66b9e | ||
|
|
be53b0d403 | ||
|
|
ba02ba4237 | ||
|
|
0d2ede4440 | ||
|
|
bf89883ff5 | ||
|
|
efcc3a3dfb | ||
|
|
fefeb1e9e2 | ||
|
|
f12436e55b | ||
|
|
98c4356638 | ||
|
|
e5c4fb7e30 | ||
|
|
4f9878a1da | ||
|
|
8557d113a3 | ||
|
|
9400e7f5d5 | ||
|
|
193509db58 | ||
|
|
d7ce175b8e | ||
|
|
0a8001a128 | ||
|
|
b46a8c897a | ||
|
|
bad8d85729 | ||
|
|
eb6f6e57ff | ||
|
|
cc495e3fd5 | ||
|
|
d190a26737 | ||
|
|
7ee4e269c3 | ||
|
|
f7465896fa | ||
|
|
4c8574aa4c | ||
|
|
7475c25fa7 | ||
|
|
3379bf3b08 | ||
|
|
7af3f48150 | ||
|
|
1b8511ab51 | ||
|
|
355ae49bc2 | ||
|
|
8c3274bd3c | ||
|
|
591384576f | ||
|
|
cdda2852d3 | ||
|
|
03992ab45c | ||
|
|
1f4b374bce | ||
|
|
a5b2757128 | ||
|
|
b961962f93 | ||
|
|
c64b2d1032 | ||
|
|
3ccfcb61ce | ||
|
|
e4c6029e72 | ||
|
|
d448bd8bd5 | ||
|
|
e999ab5ecb | ||
|
|
db8585aa85 | ||
|
|
e2545b3427 | ||
|
|
38a161f92b | ||
|
|
d14ac3e8d3 | ||
|
|
09087bdbf9 | ||
|
|
538252a4bf | ||
|
|
371e8f0dbe | ||
|
|
b8c5af5cef | ||
|
|
ddd22a1dfb | ||
|
|
2d3a9991d4 | ||
|
|
7f513cbc1d | ||
|
|
812f30fb75 | ||
|
|
86e32cdc23 | ||
|
|
554cbaa307 | ||
|
|
6a0cc838da | ||
|
|
4811bc3c5b | ||
|
|
65c94590eb | ||
|
|
5e67ca5566 | ||
|
|
d7ef314a15 | ||
|
|
a3c43efb85 | ||
|
|
9dcd0b8f42 | ||
|
|
349e34b1c1 | ||
|
|
66bce33a36 | ||
|
|
f67232b80f | ||
|
|
6b32c3aeec | ||
|
|
f3bc08160d | ||
|
|
1cca8a2303 | ||
|
|
ac215430c2 | ||
|
|
7f8a088306 | ||
|
|
2717b52e97 | ||
|
|
25cf030498 | ||
|
|
4bfab90750 | ||
|
|
95ddae7968 | ||
|
|
62fad30af5 | ||
|
|
c9373929ca | ||
|
|
01b47a833a | ||
|
|
a398c6dc99 | ||
|
|
32a40b18fd | ||
|
|
c7fcde83cf | ||
|
|
a9cd4faff0 | ||
|
|
ddccbaacdb | ||
|
|
6a7ecb2c63 | ||
|
|
0b07a6a696 | ||
|
|
58a36ec509 | ||
|
|
ebdfa9e52a | ||
|
|
4c145b11a5 | ||
|
|
c14739cb4a | ||
|
|
5b841cf4cb | ||
|
|
8fa17c578c | ||
|
|
183612a4e3 | ||
|
|
e3fbfe6541 | ||
|
|
69b9d04aad | ||
|
|
ffd1222990 | ||
|
|
07266d0b31 | ||
|
|
eb8ec327a8 | ||
|
|
f79b60083e | ||
|
|
fc50302e14 | ||
|
|
4896741706 | ||
|
|
fd7783c39d | ||
|
|
c60a945610 | ||
|
|
ef9bab627d | ||
|
|
9ca2a2e782 | ||
|
|
3613b6ed45 | ||
|
|
adc7079943 | ||
|
|
cd8fbbe8f2 | ||
|
|
e5726f3993 | ||
|
|
14c3c7865e | ||
|
|
9dd5fd198b | ||
|
|
2595729c8c | ||
|
|
6b6a422ead | ||
|
|
72a4e2073f | ||
|
|
1fa93abb5b | ||
|
|
81c763750f | ||
|
|
944f4309a8 | ||
|
|
b302051f87 | ||
|
|
070f85b541 | ||
|
|
71d97b04a5 | ||
|
|
b1edf78f13 | ||
|
|
fa5198354a | ||
|
|
e8803804ec | ||
|
|
baa9695678 | ||
|
|
a42a5cc2ca | ||
|
|
db7edd389f | ||
|
|
985794e733 | ||
|
|
5d0e37e2cc | ||
|
|
e69fb4a0db | ||
|
|
8512607fb6 | ||
|
|
299bfef7b5 | ||
|
|
a7f99b83f9 | ||
|
|
e7f1153c85 | ||
|
|
f873bb1cfb | ||
|
|
aadc58d349 | ||
|
|
5e75f0e0aa | ||
|
|
a450df823b | ||
|
|
af305afc2a | ||
|
|
3d15751e44 | ||
|
|
a09b8522ad | ||
|
|
16186b6ac7 | ||
|
|
1c2bd4134c | ||
|
|
c4b6fbec76 | ||
|
|
974055b90b | ||
|
|
4bf5724543 | ||
|
|
19ba7d67e8 | ||
|
|
34eff46e56 | ||
|
|
0529869617 | ||
|
|
81ce5c9134 | ||
|
|
6656f72782 | ||
|
|
dfb013bf78 | ||
|
|
2b37e28691 | ||
|
|
69fc6a0496 | ||
|
|
daba7e13fc | ||
|
|
580fa6a554 | ||
|
|
e90ef7aa6e | ||
|
|
d1e1dcd097 | ||
|
|
16354be1c5 | ||
|
|
a0fddfe7ec | ||
|
|
d6a459ad78 | ||
|
|
7b4dc14485 | ||
|
|
7208f53176 | ||
|
|
2c9bef6440 | ||
|
|
820772fc6d | ||
|
|
710cea5437 | ||
|
|
b6ede15b18 | ||
|
|
aa536813d9 | ||
|
|
2b9932c1ee | ||
|
|
2efb4e0d7d | ||
|
|
64935e78e3 | ||
|
|
831ded3ec2 | ||
|
|
bbf8e773f8 | ||
|
|
e4073cbe9a | ||
|
|
6d0bdd3a4d | ||
|
|
698dc262e0 | ||
|
|
41cd4c2140 | ||
|
|
12106387d1 | ||
|
|
17864d3dcc | ||
|
|
4e26e8e744 | ||
|
|
7f66c85e67 | ||
|
|
9efd5965ea | ||
|
|
2b4a920732 | ||
|
|
16025356bf | ||
|
|
7015b66636 | ||
|
|
f604005b4c | ||
|
|
1c318892c9 | ||
|
|
f66cf92bba | ||
|
|
559aae0263 | ||
|
|
74bb9c11d7 | ||
|
|
98dc5df039 | ||
|
|
d85a7883bb | ||
|
|
d1db8406f4 | ||
|
|
c8bb6873be | ||
|
|
b54a8f7fe8 | ||
|
|
9cdebc45c0 | ||
|
|
f8b6c1a285 | ||
|
|
1fb12a2fdf | ||
|
|
e3d25bda61 | ||
|
|
eb05c9b87d | ||
|
|
8145915d19 | ||
|
|
62ef81c5fb | ||
|
|
d4fa4c9d5e | ||
|
|
64cb3091cf | ||
|
|
b5ff80e858 | ||
|
|
cae66fd5e0 | ||
|
|
79871e2d00 | ||
|
|
fa1abdff2b | ||
|
|
af00fd0f30 | ||
|
|
f90a408630 | ||
|
|
f3e9c29f82 | ||
|
|
3ed7174838 | ||
|
|
0a83848cfc | ||
|
|
047ada75c7 | ||
|
|
129d2fae06 | ||
|
|
15a97f2b2b | ||
|
|
975d15733f | ||
|
|
62f091a40b | ||
|
|
078f259061 |
No files matched your search
@@ -0,0 +1 @@
|
||||
github: [groue]
|
||||
@@ -106,7 +106,8 @@ Podfile.lock
|
||||
|
||||
# SPM
|
||||
.build
|
||||
Package.resolved
|
||||
GRDB.xcworkspace/xcshareddata/swiftpm
|
||||
#Package.resolved
|
||||
Tests/SPM/Packages
|
||||
|
||||
# Ruby
|
||||
|
||||
@@ -1,12 +1,3 @@
|
||||
[submodule "Tests/Performance/fmdb"]
|
||||
path = Tests/Performance/fmdb
|
||||
url = https://github.com/ccgus/fmdb.git
|
||||
[submodule "Tests/Performance/SQLite.swift"]
|
||||
path = Tests/Performance/SQLite.swift
|
||||
url = https://github.com/stephencelis/SQLite.swift.git
|
||||
[submodule "Tests/Performance/Realm"]
|
||||
path = Tests/Performance/Realm
|
||||
url = https://github.com/realm/realm-cocoa.git
|
||||
[submodule "SQLiteCustom/src"]
|
||||
path = SQLiteCustom/src
|
||||
url = https://github.com/swiftlyfalling/SQLiteLib.git
|
||||
@@ -1,6 +1,11 @@
|
||||
# The OS X Build Environment
|
||||
# https://docs.travis-ci.com/user/reference/osx/#xcode-version
|
||||
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
- development
|
||||
|
||||
language: objective-c
|
||||
xcode_project: GRDB.xcodeproj
|
||||
|
||||
@@ -23,413 +28,181 @@ jobs:
|
||||
include:
|
||||
|
||||
###########################################
|
||||
## Test GRDB Xcode 11
|
||||
## Test GRDB Xcode 11.4
|
||||
|
||||
- stage: Test GRDB Xcode 11
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBOSX (Swift 5.1, macOS)
|
||||
script: make test_framework_GRDBOSX_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 11
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBOSX (Swift 4.2, macOS)
|
||||
script: make test_framework_GRDBOSX_minSwift
|
||||
|
||||
- stage: Test GRDB Xcode 11
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBWatchOS (watchOS)
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
- stage: Test GRDB Xcode 11
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 5.1, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 11
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget_minSwift
|
||||
|
||||
# - stage: Test GRDB Xcode 11
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode11
|
||||
# env:
|
||||
# - TID=GRDBiOS (Swift 5.1, iOS <MIN>)
|
||||
# script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 11
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 5.1, iOS <MIN>)
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 5.1, tvOS <MAX>)
|
||||
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 11
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 4.2, tvOS <MAX>)
|
||||
script: make test_framework_GRDBtvOS_maxTarget_minSwift
|
||||
|
||||
# - stage: Test GRDB Xcode 11
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode11
|
||||
# env:
|
||||
# - TID=GRDBtvOS (Swift 5.1, tvOS <MIN>)
|
||||
# script: make test_framework_GRDBtvOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 11
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 5.1, tvOS <MIN>)
|
||||
script: make test_framework_GRDBtvOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDB [SPM] (macOS)
|
||||
script: make test_SPM
|
||||
|
||||
###########################################
|
||||
## Test GRDBCustom Xcode 11
|
||||
## Test GRDBCustom Xcode 11.4
|
||||
|
||||
- stage: Test GRDBCustom Xcode 11
|
||||
- stage: Test GRDBCustom Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBOSX (Swift 5.1, macOS)
|
||||
script: make test_framework_GRDBCustomSQLiteOSX
|
||||
|
||||
- stage: Test GRDBCustom Xcode 11
|
||||
- stage: Test GRDBCustom Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 5.1, iOS <MAX>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDBCustom Xcode 11
|
||||
- stage: Test GRDBCustom Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_minSwift
|
||||
|
||||
# - stage: Test GRDBCustom Xcode 11
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode11
|
||||
# env:
|
||||
# - TID=GRDBiOS (Swift 5.1, iOS <MIN>)
|
||||
# script: make test_framework_GRDBCustomSQLiteiOS_minTarget
|
||||
- stage: Test GRDBCustom Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 5.1, iOS <MIN>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
|
||||
|
||||
###########################################
|
||||
## Test SQLCipher Xcode 11
|
||||
## Test SQLCipher Xcode 11.4
|
||||
|
||||
- stage: Test SQLCipher Xcode 11
|
||||
- stage: Test SQLCipher Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=SQLCipher 3
|
||||
script: make test_framework_SQLCipher3
|
||||
|
||||
- stage: Test SQLCipher Xcode 11
|
||||
- stage: Test SQLCipher Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=SQLCipher 4
|
||||
script: make test_framework_SQLCipher4
|
||||
|
||||
###########################################
|
||||
## Test Installation Xcode 11
|
||||
## Test Installation Xcode 11.4
|
||||
|
||||
# Manual Install
|
||||
- stage: Test Installation Xcode 11
|
||||
- stage: Test Installation Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=Manual Install
|
||||
script: make test_install_manual
|
||||
|
||||
# CocoaPods Lint
|
||||
- stage: Test Installation Xcode 11
|
||||
- stage: Test Installation Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=CocoaPods Lint
|
||||
script: make test_CocoaPodsLint_GRDB
|
||||
|
||||
# CocoaPods Install GRDB
|
||||
- stage: Test Installation Xcode 11
|
||||
- stage: Test Installation Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=CocoaPods GRDB (framework)
|
||||
script: make test_install_GRDB_CocoaPods_framework
|
||||
|
||||
# CocoaPods Install GRDB
|
||||
- stage: Test Installation Xcode 11
|
||||
- stage: Test Installation Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=CocoaPods GRDB (static)
|
||||
script: make test_install_GRDB_CocoaPods_static
|
||||
|
||||
# SPM Install
|
||||
- stage: Test Installation Xcode 11
|
||||
- stage: Test Installation Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=SPM Package
|
||||
script: make test_install_SPM_Package
|
||||
|
||||
# SPM Install
|
||||
- stage: Test Installation Xcode 11
|
||||
- stage: Test Installation Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=SPM Package in Xcode Project
|
||||
script: make test_install_SPM_Project
|
||||
|
||||
# Custom SQLite Install
|
||||
- stage: Test Installation Xcode 11
|
||||
- stage: Test Installation Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
env:
|
||||
- TID=Custom SQLite
|
||||
script: make test_install_customSQLite
|
||||
|
||||
###########################################
|
||||
## Test GRDB Xcode 10.3
|
||||
|
||||
- stage: Test GRDB Xcode 10.3
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.3
|
||||
env:
|
||||
- TID=GRDBOSX (Swift 5, macOS)
|
||||
script: make test_framework_GRDBOSX_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.3
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.3
|
||||
env:
|
||||
- TID=GRDBWatchOS (watchOS)
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
- stage: Test GRDB Xcode 10.3
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.3
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 5, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.3
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.3
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 5, iOS <MIN>)
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 10.3
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.3
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 5, tvOS <MAX>)
|
||||
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.3
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.3
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 5, tvOS <MIN>)
|
||||
script: make test_framework_GRDBtvOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 10.3
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.3
|
||||
env:
|
||||
- TID=GRDB [SPM] (macOS)
|
||||
script: make test_SPM
|
||||
|
||||
###########################################
|
||||
## Test GRDB Xcode 10.2
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDBOSX (Swift 5, macOS)
|
||||
script: make test_framework_GRDBOSX_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDBWatchOS (watchOS)
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 5, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 5, iOS <MIN>)
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 5, tvOS <MAX>)
|
||||
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 5, tvOS <MIN>)
|
||||
script: make test_framework_GRDBtvOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDB [SPM] (macOS)
|
||||
script: make test_SPM
|
||||
|
||||
###########################################
|
||||
## Test GRDB Xcode 10.1
|
||||
|
||||
- stage: Test GRDB Xcode 10.1
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.1
|
||||
env:
|
||||
- TID=GRDBOSX (Swift 4.2, macOS)
|
||||
script: make test_framework_GRDBOSX_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.1
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.1
|
||||
env:
|
||||
- TID=GRDBWatchOS (watchOS)
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
- stage: Test GRDB Xcode 10.1
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.1
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.1
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.1
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 4.2, iOS <MIN>)
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 10.1
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.1
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 4.2, tvOS <MAX>)
|
||||
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.1
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.1
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 4.2, tvOS <MIN>)
|
||||
script: make test_framework_GRDBtvOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 10.1
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.1
|
||||
env:
|
||||
- TID=GRDB [SPM] (macOS)
|
||||
script: make test_SPM
|
||||
|
||||
###########################################
|
||||
## Test GRDB Xcode 10
|
||||
|
||||
- stage: Test GRDB Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=GRDBOSX (Swift 4.2, macOS)
|
||||
script: make test_framework_GRDBOSX_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=GRDBWatchOS (watchOS)
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
- stage: Test GRDB Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 4.2, iOS <MIN>)
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 4.2, tvOS <MAX>)
|
||||
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 4.2, tvOS <MIN>)
|
||||
script: make test_framework_GRDBtvOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=GRDB [SPM] (macOS)
|
||||
script: make test_SPM
|
||||
|
||||
# CocoaPods Install GRDB
|
||||
- stage: Test Installation Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=CocoaPods GRDB (framework)
|
||||
script: make test_install_GRDB_CocoaPods_framework
|
||||
|
||||
# CocoaPods Install GRDB
|
||||
- stage: Test Installation Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=CocoaPods GRDB (static)
|
||||
script: make test_install_GRDB_CocoaPods_static
|
||||
|
||||
# Custom SQLite Install
|
||||
- stage: Test Installation Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=Custom SQLite
|
||||
script: make test_install_customSQLite
|
||||
@@ -0,0 +1,105 @@
|
||||
# Brag Document
|
||||
|
||||
Here is a list of people who were happy to meet GRDB :-)
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/layoutsubviews/status/1249940744929816582
|
||||
|
||||
> Mixing SQLite / GRDB with Combine is my whole world right now, and it is delightful.
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/steipete/status/1231105339954802694
|
||||
|
||||
> It [Core Data] gets the job done, but folks made some really amazing Swift native sqlite wrappers.
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/BelleBCooper/status/1223148814980091904
|
||||
|
||||
> I LOVE GRDB and highly recommend it. If you don’t need it now, do keep it in mind for future because it’s great and the documentation and support are top notch.
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/layoutSubviews/status/1202092984822648832
|
||||
|
||||
> GRDB is quickly becoming the best package I have ever dealt with.
|
||||
> What an exceptional piece of work: the philosophy, the documentation, the API, the abstractions, the Swiftiness👌
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/fpillet/status/1193608995405209607
|
||||
|
||||
> GRDB keeps being the best-in-class interface to your database, and if you're not using it you're missing out. As always, amazing work from @groue !
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/lordmooch/status/1193537540583755776
|
||||
|
||||
> Best SQLite/Swift integration 😀👍🏻
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/BelleBCooper/status/1192195655743111168
|
||||
|
||||
> I’ve been working on a side project recently that uses SwiftUI (+UIKit for parent controllers and nav), Combine, GRDB, and GRDBCombine for automatic updating based on DB changes. I’m really liking this setup.
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/BelleBCooper/status/1186034269577048064
|
||||
|
||||
> Working on a new project today and using GRDB by @groue for the backend. This is my go-to for new Swift projects. Highly recommend it!
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/krzyzanowskim/status/1156568071303290882
|
||||
|
||||
> I think GRDB.swift is a godsend. So far sooooo good. (change my mind?)
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/iOSDevWeekly/status/1133780078398021637
|
||||
|
||||
> How had I never heard of GRDB before this week? Was I the only one missing out, or is this wonderful database library from @groue news to you all too? https://buff.ly/2X8yHGf #iosdev
|
||||
|
||||
----
|
||||
|
||||
https://twitter.com/micpringle/status/1132264501812891648
|
||||
|
||||
> Spent the last few weeks integrating it and it’s amazing! And this release brings a whole load more features—especially excited about eager loading of hasMany relationships.
|
||||
>
|
||||
> Quite possibly one of the best documented open source libs I’ve come across as well👌🏼
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/danielemargutti/status/1132217792902647808
|
||||
|
||||
> It’s a great successor for FMDB with tons of great stuff. Worth a look, we have choose it in our new project even if, actually, I preferred not using some of the ‘ORM’ like features.
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/lordmooch/status/1131664588494254086
|
||||
|
||||
> Woohoo! Absolutely superb Swift library for SQLite - I love it 😀
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/JadenGeller/status/1115483150564487168
|
||||
|
||||
> Wow, there are some *really* good looking SQLite frameworks in Swift.
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/strawb3rryx7/status/1073620070784516096
|
||||
|
||||
> If you looking for a SQLite wrapper in Swift, just take a look the GRDB library! 👇🏼 https://github.com/groue/GRDB.swift Well-maintained and documented! ✊🏼
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/BelleBCooper/status/1047017928112128000
|
||||
|
||||
> http://blog.bellebcooper.com/2018-10-02-16-39.html
|
||||
>
|
||||
> I love the way issues are handled in GRDB (SQLite for Swift). Groue is so friendly, and always goes above-and-beyond in helping to solve problems or explore new features for the library. It makes me happy to be a GRDB user.
|
||||
|
||||
@@ -11,8 +11,21 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
-->
|
||||
|
||||
|
||||
#### 5.x Releases
|
||||
|
||||
- `5.0.x` Development - [GRDB5 Branch](#grdb5-branch)
|
||||
|
||||
|
||||
#### 4.x Releases
|
||||
|
||||
- `4.14.x` Releases - [4.14.0](#4140)
|
||||
- `4.13.x` Releases - [4.13.0](#4130)
|
||||
- `4.12.x` Releases - [4.12.0](#4120) | [4.12.1](#4121) | [4.12.2](#4122)
|
||||
- `4.11.x` Releases - [4.11.0](#4110)
|
||||
- `4.10.x` Releases - [4.10.0](#4100)
|
||||
- `4.9.x` Releases - [4.9.0](#490)
|
||||
- `4.8.x` Releases - [4.8.0](#480) | [4.8.1](#481)
|
||||
- `4.7.x` Releases - [4.7.0](#470)
|
||||
- `4.6.x` Releases - [4.6.0](#460) | [4.6.1](#461) | [4.6.2](#462)
|
||||
- `4.5.x` Releases - [4.5.0](#450)
|
||||
- `4.4.x` Releases - [4.4.0](#440)
|
||||
@@ -63,6 +76,250 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
## Next Release
|
||||
-->
|
||||
|
||||
## GRDB5 Branch
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
- The [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) Guide helps migrating your apps and turn your attention where it needs to focus during the upgrade.
|
||||
- The [ValueObservation](README.md#valueobservation) chapter has been fully rewritten and describes the new ValueObservation behaviors.
|
||||
- The [DatabaseError](README.md#databaseerror) chapter demonstrates the new way to catch and match DatabaseError on their codes, in a fashion similar to CocoaError et al.
|
||||
- The [Batch Updates](README.md#update-requests) chapter has been updated for the new `set(to:)` method.
|
||||
|
||||
### New
|
||||
|
||||
- [#749](https://github.com/groue/GRDB.swift/pull/749): Drop submodules used by performance tests
|
||||
- [#754](https://github.com/groue/GRDB.swift/pull/754): Match DatabaseError on ResultCode
|
||||
- [#756](https://github.com/groue/GRDB.swift/pull/756): Export the underlying SQLite library
|
||||
|
||||
### Breaking Changes
|
||||
|
||||
- [#719](https://github.com/groue/GRDB.swift/pull/719): Bump required Swift version to 5.2
|
||||
- [#720](https://github.com/groue/GRDB.swift/pull/720): Turn deprecated APIs into unavailable ones
|
||||
- [#722](https://github.com/groue/GRDB.swift/pull/722): SE-0253: Callable values of user-defined nominal types
|
||||
- [#728](https://github.com/groue/GRDB.swift/pull/728): Make ValueObservation error handling mandatory
|
||||
- [#729](https://github.com/groue/GRDB.swift/pull/729): ValueObservation always emits an initial value
|
||||
- [#731](https://github.com/groue/GRDB.swift/pull/731): Hide ValueObservation implementation details
|
||||
- [#732](https://github.com/groue/GRDB.swift/pull/732): Remove ValueObservation.compactMap
|
||||
- [#736](https://github.com/groue/GRDB.swift/pull/736): Relax ValueObservation Guarantees
|
||||
- [#737](https://github.com/groue/GRDB.swift/pull/737): Force implicit database region for ValueObservation
|
||||
- [#738](https://github.com/groue/GRDB.swift/pull/738): Remove all observationForCount/All/First methods
|
||||
- [#742](https://github.com/groue/GRDB.swift/pull/742): ValueObservation scheduling is no longer an attribute of the observation
|
||||
- [#745](https://github.com/groue/GRDB.swift/pull/745): Explicit ValueObservation cancellation
|
||||
- [#747](https://github.com/groue/GRDB.swift/pull/747): Rename GRDBCustomSQLite to GRDB
|
||||
- [#750](https://github.com/groue/GRDB.swift/pull/750): Batch updates do not need any operator
|
||||
- [#752](https://github.com/groue/GRDB.swift/pull/752): Remove ValueObservation.combine
|
||||
|
||||
|
||||
## 4.14.0
|
||||
|
||||
Released April 23, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v4.13.0...v4.14.0)
|
||||
|
||||
**New**
|
||||
|
||||
- [#766](https://github.com/groue/GRDB.swift/pull/766) by [@mtancock](https://github.com/mtancock): Add Codable support to DatabaseDateComponents
|
||||
|
||||
|
||||
## 4.13.0
|
||||
|
||||
Released April 15, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v4.12.2...v4.13.0)
|
||||
|
||||
**Fixed**
|
||||
|
||||
- Restored support for Xcode 10.0 and Xcode 10.1, broken in 4.12.2
|
||||
- [#759](https://github.com/groue/GRDB.swift/pull/759): Fix batch updates of complex requests
|
||||
|
||||
**New**
|
||||
|
||||
- [#761](https://github.com/groue/GRDB.swift/pull/761): Deprecate the batch update `<-` operator
|
||||
|
||||
|
||||
## 4.12.2
|
||||
|
||||
Released April 13, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v4.12.1...v4.12.2)
|
||||
|
||||
**Fixed**
|
||||
|
||||
- [#757](https://github.com/groue/GRDB.swift/pull/757): Don't load association inflections unless necessary
|
||||
|
||||
|
||||
## 4.12.1
|
||||
|
||||
Released March 29, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v4.12.0...v4.12.1)
|
||||
|
||||
**Fixed**
|
||||
|
||||
- [#744](https://github.com/groue/GRDB.swift/pull/744): Fix DatabaseMigrator deadlock with serial target queues
|
||||
|
||||
|
||||
## 4.12.0
|
||||
|
||||
Released March 21, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v4.11.0...v4.12.0)
|
||||
|
||||
**New**
|
||||
|
||||
- Batch updates now accept nil assignments:
|
||||
|
||||
```swift
|
||||
// UPDATE player SET score = NULL
|
||||
try Player.updateAll(db, scoreColumn <- nil)
|
||||
```
|
||||
|
||||
- DatabaseMigrator can now recreate the database if a migration has been removed, or renamed (addresses [#725](https://github.com/groue/GRDB.swift/issues/725)).
|
||||
|
||||
- DatabaseMigrator querying methods have been enhanced:
|
||||
|
||||
```swift
|
||||
// New
|
||||
dbQueue.read(migrator.hasCompletedMigrations)
|
||||
dbQueue.read(migrator.completedMigrations).contains("v2")
|
||||
dbQueue.read(migrator.completedMigrations).last == "v2"
|
||||
dbQueue.read(migrator.appliedMigrations)
|
||||
|
||||
// Deprecated
|
||||
migrator.hasCompletedMigrations(in: dbQueue)
|
||||
migrator.hasCompletedMigrations(in: dbQueue, through: "v2")
|
||||
migrator.lastCompletedMigration(in: dbQueue) == "v2"
|
||||
migrator.appliedMigrations(in: dbQueue)
|
||||
```
|
||||
|
||||
|
||||
## 4.11.0
|
||||
|
||||
Released March 2, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v4.10.0...v4.11.0)
|
||||
|
||||
### New
|
||||
|
||||
- [#706](https://github.com/groue/GRDB.swift/pull/706): Enhance SQLLiteral and SQL interpolation again
|
||||
- [#710](https://github.com/groue/GRDB.swift/pull/710): Check if all migrations have been applied
|
||||
- [#712](https://github.com/groue/GRDB.swift/pull/712) by [@pakko972](https://github.com/pakko972): Automatic iOS memory management
|
||||
- [#713](https://github.com/groue/GRDB.swift/pull/713): Enhance DatabaseMigrator isolation
|
||||
|
||||
### Breaking Change
|
||||
|
||||
- [#709](https://github.com/groue/GRDB.swift/pull/709): Simplify DatabaseMigrator API
|
||||
|
||||
Database migrations have a new behavior which is a breaking change. However, it is very unlikely to impact your application.
|
||||
|
||||
In previous versions of GRDB, a foreign key violation would immediately prevent a migration from successfully complete. Now, foreign key checks are deferred until the end of each migration. This means that some migrations will change their behavior:
|
||||
|
||||
```swift
|
||||
// Used to fail, now succeeds
|
||||
migrator.registerMigration(...) { db in
|
||||
try violateForeignKeyConstraint(db)
|
||||
try fixForeignKeyConstraint(db)
|
||||
}
|
||||
|
||||
// The catch clause is no longer called
|
||||
migrator.registerMigration(...) { db in
|
||||
do {
|
||||
try performChanges(db)
|
||||
} catch let error as DatabaseError where error.resultCode == .SQL_CONSTRAINT {
|
||||
// Handle foreign key error
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If your application happens to define migrations that are impacted by this change, please open an issue so that we find a way to restore the previous behavior.
|
||||
|
||||
|
||||
## 4.10.0
|
||||
|
||||
Released February 23, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v4.9.0...v4.10.0)
|
||||
|
||||
**New**
|
||||
|
||||
- [#689](https://github.com/groue/GRDB.swift/pull/689) by [@gjeck](https://github.com/gjeck): Add support for renaming columns within a table
|
||||
- [#690](https://github.com/groue/GRDB.swift/pull/690): Enhance SQLLiteral and SQL interpolation
|
||||
|
||||
|
||||
## 4.9.0
|
||||
|
||||
Released January 17, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v4.8.1...v4.9.0)
|
||||
|
||||
**New**
|
||||
|
||||
- [#683](https://github.com/groue/GRDB.swift/pull/683): String concatenation
|
||||
- [#685](https://github.com/groue/GRDB.swift/pull/685) by [@gjeck](https://github.com/gjeck): Add cache for TableRecord.defaultDatabaseTableName
|
||||
|
||||
|
||||
## 4.8.1
|
||||
|
||||
Released January 12, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v4.8.0...v4.8.1)
|
||||
|
||||
**Fixed**
|
||||
|
||||
- [#677](https://github.com/groue/GRDB.swift/pull/677): Fix associations altered by another association
|
||||
|
||||
|
||||
## 4.8.0
|
||||
|
||||
Released January 8, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v4.7.0...v4.8.0)
|
||||
|
||||
**New**
|
||||
|
||||
- [#676](https://github.com/groue/GRDB.swift/pull/676): More batch delete and update
|
||||
|
||||
|
||||
## 4.7.0
|
||||
|
||||
Released December 18, 2019 • [diff](https://github.com/groue/GRDB.swift/compare/v4.6.2...v4.7.0)
|
||||
|
||||
**New**
|
||||
|
||||
- [#656](https://github.com/groue/GRDB.swift/pull/656): Type inference of selected columns
|
||||
- [#659](https://github.com/groue/GRDB.swift/pull/659): Database interruption
|
||||
- [#660](https://github.com/groue/GRDB.swift/pull/660): Database Lock Prevention
|
||||
- [#662](https://github.com/groue/GRDB.swift/pull/662): Upgrade custom SQLite builds to version 3.30.1 (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib))
|
||||
- [#668](https://github.com/groue/GRDB.swift/pull/668): Database Suspension
|
||||
|
||||
### Breaking Changes
|
||||
|
||||
[Custom SQLite builds](Documentation/CustomSQLiteBuilds.md) now disable by default the support for the [Double-quoted String Literals misfeature](https://sqlite.org/quirks.html#dblquote). This is a technically a breaking change, but it fixes an SQLite bug. You can restore the previous behavior if your application relies on it:
|
||||
|
||||
```swift
|
||||
// Enable support for the Double-quoted String Literals misfeature
|
||||
var configuration = Configuration()
|
||||
configuration.acceptsDoubleQuotedStringLiterals = true
|
||||
let dbQueue = try DatabaseQueue(path: ..., configuration: configuration)
|
||||
```
|
||||
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
The new [Interrupt a Database](README.md#interrupt-a-database) chapter documents the new `interrupt()` method.
|
||||
|
||||
The new [Sharing a Datatase in an App Group Container](Documentation/AppGroupContainers.md) guide explains how to setup GRDB when you share a database in an iOS App Group container.
|
||||
|
||||
|
||||
### API Diff
|
||||
|
||||
```diff
|
||||
struct Configuration {
|
||||
+ var observesSuspensionNotifications: Bool // Experimental
|
||||
+ var acceptsDoubleQuotedStringLiterals: Bool
|
||||
}
|
||||
|
||||
class Database {
|
||||
+ static let suspendNotification: Notification.Name // Experimental
|
||||
+ static let resumeNotification: Notification.Name // Experimental
|
||||
}
|
||||
|
||||
extension DatabaseError {
|
||||
+ var isInterruptionError: Bool { get }
|
||||
}
|
||||
|
||||
protocol DatabaseReader {
|
||||
+ func interrupt()
|
||||
}
|
||||
|
||||
extension SQLSpecificExpressible {
|
||||
+ #if GRDBCUSTOMSQLITE
|
||||
+ var ascNullsLast: SQLOrderingTerm { get }
|
||||
+ var descNullsFirst: SQLOrderingTerm { get }
|
||||
+ #endif
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 4.6.2
|
||||
|
||||
@@ -1998,7 +2255,7 @@ Released September 17, 2017 • [diff](https://github.com/groue/GRDB.swift/co
|
||||
**Fixed**: restored support for Swift Package Manager
|
||||
|
||||
|
||||
## 2.0
|
||||
## 2.0.0
|
||||
|
||||
Released September 16, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v1.3.0...v2.0)
|
||||
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
Sharing a Database in an App Group Container
|
||||
============================================
|
||||
|
||||
On iOS, you can share database files between multiple processes by storing them in an [App Group Container](https://developer.apple.com/documentation/foundation/nsfilemanager/1412643-containerurlforsecurityapplicati).
|
||||
|
||||
A shared database is accessed from several SQLite connections, from several processes. This creates challenges at various levels:
|
||||
|
||||
1. **Database setup** may be attempted by multiple processes, concurrently.
|
||||
2. **SQLite** may throw `SQLITE_BUSY` errors, code 5, "database is locked".
|
||||
3. **iOS** may kill your application with a `0xDEAD10CC` exception.
|
||||
4. **GRDB** database observation misses changes performed by external processes.
|
||||
|
||||
We'll address all of those challenges below.
|
||||
|
||||
- [Use a Database Pool]
|
||||
- [How to limit the `SQLITE_BUSY` error]
|
||||
- [How to limit the `0xDEAD10CC` exception]
|
||||
- [How to perform cross-process database observation]
|
||||
|
||||
|
||||
## Use a Database Pool
|
||||
|
||||
In order to access a shared database, use a [Database Pool]. It opens the database in the [WAL mode](https://www.sqlite.org/wal.html), which helps sharing a database.
|
||||
|
||||
Since several processes may open the database at the same time, protect the creation of the database pool with an [NSFileCoordinator].
|
||||
|
||||
- In a process that can create and write in the database, use this sample code:
|
||||
|
||||
```swift
|
||||
/// Returns an initialized database pool at the shared location databaseURL
|
||||
func openSharedDatabase(at databaseURL: URL) throws -> DatabasePool {
|
||||
let coordinator = NSFileCoordinator(filePresenter: nil)
|
||||
var coordinatorError: NSError?
|
||||
var dbPool: DatabasePool?
|
||||
var dbError: Error?
|
||||
coordinator.coordinate(writingItemAt: databaseURL, options: .forMerging, error: &coordinatorError, byAccessor: { url in
|
||||
do {
|
||||
dbPool = try openDatabase(at: url)
|
||||
} catch {
|
||||
dbError = error
|
||||
}
|
||||
})
|
||||
if let error = dbError ?? coordinatorError {
|
||||
throw error
|
||||
}
|
||||
return dbPool!
|
||||
}
|
||||
|
||||
private func openDatabase(at databaseURL: URL) throws -> DatabasePool {
|
||||
let dbPool = try DatabasePool(path: databaseURL.path)
|
||||
|
||||
// Perform here other database setups, such as defining
|
||||
// the database schema with a DatabaseMigrator.
|
||||
try migrator.migrate(dbPool)
|
||||
return dbPool
|
||||
}
|
||||
```
|
||||
|
||||
- In a process that only reads in the database, use this sample code:
|
||||
|
||||
```swift
|
||||
/// Returns an initialized database pool at the shared location databaseURL,
|
||||
/// or nil if the database is not created yet, or does not have the required
|
||||
/// schema version.
|
||||
func openSharedReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
|
||||
let coordinator = NSFileCoordinator(filePresenter: nil)
|
||||
var coordinatorError: NSError?
|
||||
var dbPool: DatabasePool?
|
||||
var dbError: Error?
|
||||
coordinator.coordinate(readingItemAt: databaseURL, options: .withoutChanges, error: &coordinatorError, byAccessor: { url in
|
||||
do {
|
||||
dbPool = try openReadOnlyDatabase(at: url)
|
||||
} catch {
|
||||
dbError = error
|
||||
}
|
||||
})
|
||||
if let error = dbError ?? coordinatorError {
|
||||
throw error
|
||||
}
|
||||
return dbPool
|
||||
}
|
||||
|
||||
private func openReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
|
||||
do {
|
||||
var configuration = Configuration()
|
||||
configuration.readonly = true
|
||||
let dbPool = try DatabasePool(path: databaseURL.path, configuration: configuration)
|
||||
|
||||
// Check here if the database schema is correct, for example
|
||||
// with a DatabaseMigrator.
|
||||
if try dbPool.read(migrator.hasCompletedMigrations) {
|
||||
return dbPool
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
} catch {
|
||||
if FileManager.default.fileExists(atPath: databaseURL.path) {
|
||||
throw error
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## How to limit the `SQLITE_BUSY` error
|
||||
|
||||
> The SQLITE_BUSY result code indicates that the database file could not be written (or in some cases read) because of concurrent activity by some other database connection, usually a database connection in a separate process.
|
||||
|
||||
See https://www.sqlite.org/rescode.html#busy for more information about this error.
|
||||
|
||||
If several processes want to write in the database, configure the database pool of each process that wants to write:
|
||||
|
||||
```swift
|
||||
var configuration = Configuration()
|
||||
configuration.busyMode = .timeout(/* a TimeInterval */)
|
||||
configuration.defaultTransactionKind = .immediate
|
||||
let dbPool = try DatabasePool(path: ..., configuration: configuration)
|
||||
```
|
||||
|
||||
With such a setup, you may still get `SQLITE_BUSY` (5, "database is locked") errors from all write operations. They will occur if the database remains locked by another process for longer than the specified timeout.
|
||||
|
||||
```swift
|
||||
do {
|
||||
try dbPool.write { db in ... }
|
||||
} catch let error as DatabaseError where error.resultCode == .SQLITE_BUSY {
|
||||
// Another process won't let you write. Deal with it.
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: **Tip**: In order to be nice to other processes, measure the duration of your longest writes, and attempt at optimizing the ones that last for too long.
|
||||
|
||||
|
||||
## How to limit the `0xDEAD10CC` exception
|
||||
|
||||
> The exception code 0xDEAD10CC indicates that an application has been terminated by the OS because it held on to a file lock or sqlite database lock during suspension.
|
||||
|
||||
See https://developer.apple.com/library/archive/technotes/tn2151/_index.html for more information about this exception.
|
||||
|
||||
1. If you use SQLCipher, use SQLCipher 4+, and call the `cipher_plaintext_header_size` pragma from your database preparation function:
|
||||
|
||||
```swift
|
||||
var configuration = Configuration()
|
||||
configuration.prepareDatabase = { (db: Database) in
|
||||
try db.usePassphrase("secret")
|
||||
try db.execute(sql: "PRAGMA cipher_plaintext_header_size = 32")
|
||||
}
|
||||
let dbPool = try DatabasePool(path: ..., configuration: configuration)
|
||||
```
|
||||
|
||||
This will avoid https://github.com/sqlcipher/sqlcipher/issues/255.
|
||||
|
||||
2. [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features) In each process that wants to write in the database:
|
||||
|
||||
Set the `observesSuspensionNotifications` configuration flag:
|
||||
|
||||
```swift
|
||||
var configuration = Configuration()
|
||||
configuration.suspendsOnBackgroundTimeExpiration = true
|
||||
let dbPool = try DatabasePool(path: ..., configuration: configuration)
|
||||
```
|
||||
|
||||
Post `Database.suspendNotification` when the application is about to be [suspended](https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle). You can for example post this notification from `UIApplicationDelegate.applicationDidEnterBackground(_:)`, or in the expiration handler of a [background task](https://forums.developer.apple.com/thread/85066).
|
||||
|
||||
```swift
|
||||
@UIApplicationMain
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
func applicationDidEnterBackground(_ application: UIApplication) {
|
||||
// Suspend databases
|
||||
NotificationCenter.default.post(name: Database.suspendNotification, object: self)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Post `Database.resumeNotification` from `UIApplicationDelegate.applicationWillEnterForeground(_:)` (or `SceneDelegate.sceneWillEnterForeground(_:)` for scene-based applications):
|
||||
|
||||
```swift
|
||||
@UIApplicationMain
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
func applicationWillEnterForeground(_ application: UIApplication) {
|
||||
// Resume databases
|
||||
NotificationCenter.default.post(name: Database.resumeNotification, object: self)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If the application uses the background modes supported by iOS, post `Database.resumeNotification` method from each and every background mode callback that may use the database. For example, if your application supports background fetches:
|
||||
|
||||
```swift
|
||||
@UIApplicationMain
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
|
||||
// Resume databases
|
||||
NotificationCenter.default.post(name: Database.resumeNotification, object: self)
|
||||
// Proceed with background fetch
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Suspended databases greatly reduce the odds of `0xDEAD10CC` exception are greatly reduced. If you see one in your crash logs, please open an issue!
|
||||
|
||||
In exchange, you will get `SQLITE_INTERRUPT` (9) or `SQLITE_ABORT` (4) errors, with messages "Database is suspended", "Transaction was aborted", or "interrupted", for any attempt at writing in the database when it is suspended.
|
||||
|
||||
You can catch those errors:
|
||||
|
||||
```swift
|
||||
do {
|
||||
try dbPool.write { db in ... }
|
||||
} catch let error as DatabaseError where error.isInterruptionError {
|
||||
// Oops, the database is suspended.
|
||||
// Maybe try again after database is resumed?
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## How to perform cross-process database observation
|
||||
|
||||
GRDB [Database Observation] features, as well as [GRDBCombine] and [RxGRDB], are not able to notify database changes performed by other processes.
|
||||
|
||||
Whenever you need to notify other processes that the database has been changed, you will have to use a cross-process notification mechanism such as [NSFileCoordinator] or [CFNotificationCenterGetDarwinNotifyCenter].
|
||||
|
||||
You can trigger those notifications automatically with [DatabaseRegionObservation]:
|
||||
|
||||
```swift
|
||||
// Notify all changes made to the "player" and "team" database tables
|
||||
let observation = DatabaseRegionObservation(tracking: Player.all(), Team.all())
|
||||
let observer = try observation.start(in: dbPool) { (db: Database) in
|
||||
// Notify other processes
|
||||
}
|
||||
|
||||
// Notify all changes made to the database
|
||||
let observation = DatabaseRegionObservation(tracking: DatabaseRegion.fullDatabase)
|
||||
let observer = try observation.start(in: dbPool) { (db: Database) in
|
||||
// Notify other processes
|
||||
}
|
||||
```
|
||||
|
||||
[Use a Database Pool]: #use-a-database-pool
|
||||
[How to limit the `SQLITE_BUSY` error]: #how-to-limit-the-sqlite_busy-error
|
||||
[How to limit the `0xDEAD10CC` exception]: #how-to-limit-the-0xdead10cc-exception
|
||||
[How to perform cross-process database observation]: #how-to-perform-cross-process-database-observation
|
||||
[Database Pool]: ../README.md#database-pools
|
||||
[Database Observation]: ../README.md#database-changes-observation
|
||||
[GRDBCombine]: http://github.com/groue/GRDBCombine
|
||||
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
|
||||
[NSFileCoordinator]: https://developer.apple.com/documentation/foundation/nsfilecoordinator
|
||||
[CFNotificationCenterGetDarwinNotifyCenter]: https://developer.apple.com/documentation/corefoundation/1542572-cfnotificationcentergetdarwinnot
|
||||
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
|
||||
@@ -91,14 +91,14 @@ With GRDB associations, we can streamline these operations (and others), by decl
|
||||
extension Author {
|
||||
static let books = hasMany(Book.self)
|
||||
var books: QueryInterfaceRequest<Book> {
|
||||
return request(for: Author.books)
|
||||
request(for: Author.books)
|
||||
}
|
||||
}
|
||||
|
||||
extension Book {
|
||||
static let author = belongsTo(Author.self)
|
||||
var author: QueryInterfaceRequest<Author> {
|
||||
return request(for: Book.author)
|
||||
request(for: Book.author)
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -165,7 +165,7 @@ Generally speaking, associations use the [TableRecord], [FetchableRecord], and [
|
||||
extension Book: EncodableRecord {
|
||||
// The request for the author of a book.
|
||||
var author: QueryInterfaceRequest<Author> {
|
||||
return request(for: Book.author)
|
||||
request(for: Book.author)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -283,7 +283,7 @@ See [Convention for the HasOne Association] for some sample code that defines th
|
||||
The **HasManyThrough** association is often used to set up a many-to-many connection with another record. This association indicates that the declaring record can be matched with zero or more instances of another record by proceeding through a third record. For example, consider the practice of passport delivery. The relevant association declarations could look like this:
|
||||
|
||||
```swift
|
||||
struct Country: TableRecord, EncodableRecord {
|
||||
struct Country: TableRecord {
|
||||
static let passports = hasMany(Passport.self)
|
||||
static let citizens = hasMany(Citizen.self, through: passports, using: Passport.citizen)
|
||||
...
|
||||
@@ -294,7 +294,7 @@ struct Passport: TableRecord {
|
||||
static let citizen = belongsTo(Citizen.self)
|
||||
}
|
||||
|
||||
struct Citizen: TableRecord, EncodableRecord {
|
||||
struct Citizen: TableRecord {
|
||||
static let passports = hasMany(Passport.self)
|
||||
static let countries = hasMany(Country.self, through: passports, using: Passport.country)
|
||||
...
|
||||
@@ -327,7 +327,7 @@ As in the examples above, **HasManyThrough** association is always built from tw
|
||||
```swift
|
||||
struct Document: TableRecord {
|
||||
static let paragraphs = hasMany(
|
||||
Paragraph.self,
|
||||
Paragraph.self,
|
||||
through: Document.hasMany(Section.self),
|
||||
using: Section.hasMany(Paragraph.self))
|
||||
...
|
||||
@@ -342,9 +342,9 @@ See [Building Requests from Associations] in order to learn how to use the HasMa
|
||||
A **HasOneThrough** association sets up a one-to-one connection with another record. This association indicates that the declaring record can be matched with one instance of another record by proceeding through a third record. For example, if each book belongs to a library, and each library has one address, then one knows where the book should be returned to:
|
||||
|
||||
```swift
|
||||
struct Book: TableRecord, EncodableRecord {
|
||||
struct Book: TableRecord {
|
||||
static let library = belongsTo(Library.self)
|
||||
static let returnAddress = hasOne(Address.self, through: library, using: library.address)
|
||||
static let returnAddress = hasOne(Address.self, through: library, using: Library.address)
|
||||
...
|
||||
}
|
||||
|
||||
@@ -785,7 +785,7 @@ struct Book: TableRecord, EncodableRecord {
|
||||
|
||||
/// The request for the author of a book
|
||||
var author: QueryInterfaceRequest<Author> {
|
||||
return request(for: Book.author)
|
||||
request(for: Book.author)
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -806,7 +806,7 @@ struct Author: TableRecord, EncodableRecord {
|
||||
|
||||
/// The request for the books of an author
|
||||
var books: QueryInterfaceRequest<Book> {
|
||||
return request(for: Author.books)
|
||||
request(for: Author.books)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1140,7 +1140,7 @@ extension Team {
|
||||
static let players = hasMany(Player.self).order(Column("position"))
|
||||
|
||||
var players: QueryInterfaceRequest<Player> {
|
||||
return request(for: Team.players)
|
||||
request(for: Team.players)
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -1148,18 +1148,18 @@ extension Team {
|
||||
Things are very similar for **HasManyThrough** associations. Now each player knows its position in the teams it belongs to:
|
||||
|
||||
```swift
|
||||
private struct Team: FetchableRecord, TableRecord {
|
||||
struct Team: FetchableRecord, TableRecord {
|
||||
var id: Int64
|
||||
var name: String
|
||||
}
|
||||
|
||||
private struct PlayerRole: FetchableRecord, TableRecord {
|
||||
struct PlayerRole: FetchableRecord, TableRecord {
|
||||
var teamId: Int64
|
||||
var playerId: Int64
|
||||
var position: Int
|
||||
}
|
||||
|
||||
private struct Player: FetchableRecord, TableRecord {
|
||||
struct Player: FetchableRecord, TableRecord {
|
||||
var id: Int64
|
||||
var name: String
|
||||
}
|
||||
@@ -1174,7 +1174,7 @@ extension Team {
|
||||
static let players = hasMany(Player.self, through: playerRoles, using: PlayerRole.player)
|
||||
|
||||
var players: QueryInterfaceRequest<Player> {
|
||||
return request(for: Team.players)
|
||||
request(for: Team.players)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1374,6 +1374,60 @@ When you join or include an association several times, with the same **[associat
|
||||
.including(optional: association.select(selection2))
|
||||
```
|
||||
|
||||
**Those rules exist so that you can design fluent interfaces that build complex requests out of simple building blocks.**
|
||||
|
||||
For example, we can start by defining base requests as extensions to the [DerivableRequest Protocol]:
|
||||
|
||||
```swift
|
||||
// Author requests
|
||||
extension DerivableRequest where RowDecoder == Author {
|
||||
/// Filters authors by country
|
||||
func filter(country: String) -> Self {
|
||||
filter(Column("country") == country)
|
||||
}
|
||||
}
|
||||
|
||||
// Book requests
|
||||
extension DerivableRequest where RowDecoder == Book {
|
||||
/// Filters books by author country
|
||||
func filter(authorCountry: String) -> Self {
|
||||
joining(required: Book.author.filter(country: country))
|
||||
}
|
||||
|
||||
/// Order books by author name and then book title
|
||||
func orderedByAuthorNameAndYear() -> Self {
|
||||
let authorAlias = TableAlias()
|
||||
return self
|
||||
.joining(optional: Book.author.aliased(authorAlias))
|
||||
.order(
|
||||
authorAlias[Column("name")].collating(.localizedCaseInsensitiveCompare),
|
||||
Column("year"))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And then compose those in a fluent style:
|
||||
|
||||
```swift
|
||||
struct BookInfo: FetchableRecord, Decodable {
|
||||
var book: Book
|
||||
var author: Author
|
||||
}
|
||||
|
||||
// SELECT book.*, author.*
|
||||
// FROM book
|
||||
// JOIN author ON author.id = book.authorId AND author.country = 'FR'
|
||||
// ORDER BY author.name COLLATE ..., book.year
|
||||
let bookInfos = try Book.all()
|
||||
.filter(authorCountry: "FR")
|
||||
.orderedByAuthorNameAndYear()
|
||||
.including(required: Book.author)
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
Remember that those refinement rules only apply when an association is joined or included several times, with the same **[association key](#the-structure-of-a-joined-request)**. Changing this key stops merging associations together. See [Isolation of Multiple Aggregates] for a longer discussion.
|
||||
|
||||
|
||||
Fetching Values from Associations
|
||||
=================================
|
||||
@@ -1556,8 +1610,7 @@ And who is the most able to know those coding keys? BookInfo itself, thanks to i
|
||||
```swift
|
||||
extension BookInfo {
|
||||
static func all() -> QueryInterfaceRequest<BookInfo> {
|
||||
return Book
|
||||
.including(optional: Book.coverImage)
|
||||
Book.including(optional: Book.coverImage)
|
||||
.including(required: Book.author
|
||||
.forKey(CodingKeys.authorInfo) // (1)
|
||||
.including(optional: Person.country))
|
||||
@@ -1577,7 +1630,7 @@ let bookInfos = try BookInfo.all().fetchAll(db, request) // [BookInfo]
|
||||
|
||||
## Decoding a Joined Request with FetchableRecord
|
||||
|
||||
When [Dedocable](#decoding-a-joined-request-with-a-decodable-record) records provides convenient decoding of joined rows, you may want a little more control over row decoding.
|
||||
When [Decodable](#decoding-a-joined-request-with-a-decodable-record) records provides convenient decoding of joined rows, you may want a little more control over row decoding.
|
||||
|
||||
The `init(row:)` initializer of the [FetchableRecord] protocol is what you look after:
|
||||
|
||||
@@ -1704,7 +1757,7 @@ When you need to compute aggregates **from a single record**, you use [regular a
|
||||
struct Author: TableRecord, EncodableRecord {
|
||||
static let books = hasMany(Book.self)
|
||||
var books: QueryInterfaceRequest<Book> {
|
||||
return request(for: Author.books)
|
||||
request(for: Author.books)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2247,22 +2300,22 @@ let request = Author.all().filter(country: "FR").orderedByName()
|
||||
let request = Book.all().filter(country: "ES")
|
||||
```
|
||||
|
||||
Thos methods are defined on extensions to the `DerivableRequest` protocol:
|
||||
Those methods are defined on extensions to the `DerivableRequest` protocol:
|
||||
|
||||
```swift
|
||||
extension DerivableRequest where RowDecoder == Author {
|
||||
func filter(country: String) -> Self {
|
||||
return filter(Column("country") == country)
|
||||
filter(Column("country") == country)
|
||||
}
|
||||
|
||||
func orderedByName() -> Self {
|
||||
return order(Column("name").collating(.localizedCaseInsensitiveCompare))
|
||||
order(Column("name").collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
}
|
||||
|
||||
extension DerivableRequest where RowDecoder == Book {
|
||||
func filter(country: String) -> Self {
|
||||
return joining(required: Book.author.filter(country: country))
|
||||
joining(required: Book.author.filter(country: country))
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -2326,7 +2379,7 @@ This documentation owns a lot to the [Active Record Associations](http://guides.
|
||||
|
||||
**GRDB**
|
||||
|
||||
Copyright (C) 2019 Gwendal Roué
|
||||
Copyright (C) 2015-2020 Gwendal Roué
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
@@ -111,7 +111,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
|
||||
6. Add the `GRDBCustomSQLiteOSX` or `GRDBCustomSQLiteiOS` target in the **Target Dependencies** section of the **Build Phases** tab of your **application target**.
|
||||
|
||||
7. Add the `GRDBCustomSQLite.framework` from the targetted platform to the **Embedded Binaries** section of the **General** tab of your **application target**.
|
||||
7. Add the `GRDBCustomSQLite.framework` from the targeted platform to the **Embedded Binaries** section of the **General** tab of your **application target**.
|
||||
|
||||
8. Add a Run Script phase for your target in the **Pre-actions** section of the **Build** tab of your **application scheme**:
|
||||
|
||||
@@ -128,7 +128,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
Now you can use GRDB with your custom SQLite build:
|
||||
|
||||
```swift
|
||||
import GRDBCustomSQLite
|
||||
import GRDB
|
||||
|
||||
let dbQueue = try DatabaseQueue(...)
|
||||
```
|
||||
@@ -15,6 +15,7 @@ class ExtensionDelegate: NSObject, WKExtensionDelegate {
|
||||
// Use this method to pause ongoing tasks, disable timers, etc.
|
||||
}
|
||||
|
||||
@available(watchOSApplicationExtension 3.0, *)
|
||||
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
|
||||
// Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one.
|
||||
for task in backgroundTasks {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import WatchKit
|
||||
import Foundation
|
||||
import GRDB
|
||||
import SQLite3
|
||||
|
||||
class InterfaceController: WKInterfaceController {
|
||||
|
||||
|
||||
@@ -43,20 +43,6 @@
|
||||
remoteGlobalIDString = 56E5D7F91B4D422D00430942;
|
||||
remoteInfo = GRDBOSXTests;
|
||||
};
|
||||
56606D0D2355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 560C981A1C0E22D300BF8471;
|
||||
remoteInfo = GRDBOSXPerformanceTests;
|
||||
};
|
||||
56606D0F2355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56439B501F4CA1DC0066043F;
|
||||
remoteInfo = GRDBOSXPerformanceComparisonTests;
|
||||
};
|
||||
56606D112355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
@@ -224,8 +210,6 @@
|
||||
children = (
|
||||
56606D0A2355931F00185962 /* GRDB.framework */,
|
||||
56606D0C2355931F00185962 /* GRDBOSXTests.xctest */,
|
||||
56606D0E2355931F00185962 /* GRDBOSXPerformanceTests.xctest */,
|
||||
56606D102355931F00185962 /* GRDBOSXPerformanceComparisonTests.xctest */,
|
||||
56606D122355931F00185962 /* GRDBOSXCrashTests.xctest */,
|
||||
56606D142355931F00185962 /* GRDB.framework */,
|
||||
56606D162355931F00185962 /* GRDBiOSTests.xctest */,
|
||||
@@ -432,20 +416,6 @@
|
||||
remoteRef = 56606D0B2355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56606D0E2355931F00185962 /* GRDBOSXPerformanceTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBOSXPerformanceTests.xctest;
|
||||
remoteRef = 56606D0D2355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56606D102355931F00185962 /* GRDBOSXPerformanceComparisonTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBOSXPerformanceComparisonTests.xctest;
|
||||
remoteRef = 56606D0F2355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56606D122355931F00185962 /* GRDBOSXCrashTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
@@ -608,7 +578,6 @@
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
TARGETED_DEVICE_FAMILY = 4;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 3.2;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -625,7 +594,6 @@
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
TARGETED_DEVICE_FAMILY = 4;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 3.2;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
@@ -643,7 +611,6 @@
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
TARGETED_DEVICE_FAMILY = 4;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 3.2;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -661,7 +628,6 @@
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
TARGETED_DEVICE_FAMILY = 4;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 3.2;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
@@ -715,12 +681,14 @@
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
|
||||
MTL_ENABLE_DEBUG_INFO = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 5.0;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 2.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -768,11 +736,13 @@
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
|
||||
SWIFT_VERSION = 5.0;
|
||||
VALIDATE_PRODUCT = YES;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 2.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1030"
|
||||
LastUpgradeVersion = "1130"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -55,8 +55,6 @@
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
@@ -66,8 +64,8 @@
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
<Testables>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
@@ -91,17 +89,6 @@
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</RemoteRunnable>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
BuildableName = "GRDBDemoWatchOS.app"
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1030"
|
||||
LastUpgradeVersion = "1130"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -18,9 +18,5 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
.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/blob/master/README.md#memory-management
|
||||
dbQueue.setupMemoryManagement(in: application)
|
||||
}
|
||||
}
|
||||
@@ -1,71 +1,112 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"size" : "20x20",
|
||||
"idiom" : "iphone",
|
||||
"size" : "29x29",
|
||||
"filename" : "icon_20pt@2x.png",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"size" : "20x20",
|
||||
"idiom" : "iphone",
|
||||
"size" : "29x29",
|
||||
"filename" : "icon_20pt@3x.png",
|
||||
"scale" : "3x"
|
||||
},
|
||||
{
|
||||
"size" : "29x29",
|
||||
"idiom" : "iphone",
|
||||
"size" : "40x40",
|
||||
"filename" : "icon_29pt@2x.png",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"size" : "29x29",
|
||||
"idiom" : "iphone",
|
||||
"filename" : "icon_29pt@3x.png",
|
||||
"scale" : "3x"
|
||||
},
|
||||
{
|
||||
"size" : "40x40",
|
||||
"idiom" : "iphone",
|
||||
"filename" : "icon_40pt@2x.png",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"size" : "40x40",
|
||||
"idiom" : "iphone",
|
||||
"filename" : "icon_40pt@3x.png",
|
||||
"scale" : "3x"
|
||||
},
|
||||
{
|
||||
"size" : "60x60",
|
||||
"idiom" : "iphone",
|
||||
"filename" : "Icon-60@2x.png",
|
||||
"filename" : "icon_60pt@2x.png",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"size" : "60x60",
|
||||
"idiom" : "iphone",
|
||||
"filename" : "Icon-60@3x.png",
|
||||
"filename" : "icon_60pt@3x.png",
|
||||
"scale" : "3x"
|
||||
},
|
||||
{
|
||||
"size" : "20x20",
|
||||
"idiom" : "ipad",
|
||||
"filename" : "icon_20pt.png",
|
||||
"scale" : "1x"
|
||||
},
|
||||
{
|
||||
"size" : "20x20",
|
||||
"idiom" : "ipad",
|
||||
"filename" : "icon_20pt@2x-1.png",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"size" : "29x29",
|
||||
"idiom" : "ipad",
|
||||
"filename" : "icon_29pt.png",
|
||||
"scale" : "1x"
|
||||
},
|
||||
{
|
||||
"idiom" : "ipad",
|
||||
"size" : "29x29",
|
||||
"idiom" : "ipad",
|
||||
"filename" : "icon_29pt@2x-1.png",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "ipad",
|
||||
"size" : "40x40",
|
||||
"idiom" : "ipad",
|
||||
"filename" : "icon_40pt.png",
|
||||
"scale" : "1x"
|
||||
},
|
||||
{
|
||||
"idiom" : "ipad",
|
||||
"size" : "40x40",
|
||||
"idiom" : "ipad",
|
||||
"filename" : "icon_40pt@2x-1.png",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "ipad",
|
||||
"size" : "76x76",
|
||||
"idiom" : "ipad",
|
||||
"filename" : "icon_76pt.png",
|
||||
"scale" : "1x"
|
||||
},
|
||||
{
|
||||
"idiom" : "ipad",
|
||||
"size" : "76x76",
|
||||
"idiom" : "ipad",
|
||||
"filename" : "icon_76pt@2x.png",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "ipad",
|
||||
"size" : "83.5x83.5",
|
||||
"idiom" : "ipad",
|
||||
"filename" : "icon_83.5@2x.png",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"size" : "1024x1024",
|
||||
"idiom" : "ios-marketing",
|
||||
"filename" : "Icon.png",
|
||||
"scale" : "1x"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
|
||||
|
Before Width: | Height: | Size: 3.8 KiB |
|
Before Width: | Height: | Size: 5.7 KiB |
|
After Width: | Height: | Size: 329 KiB |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 2.6 KiB |
|
After Width: | Height: | Size: 2.6 KiB |
|
After Width: | Height: | Size: 4.7 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 4.5 KiB |
|
After Width: | Height: | Size: 4.5 KiB |
|
After Width: | Height: | Size: 7.8 KiB |
|
After Width: | Height: | Size: 2.6 KiB |
|
After Width: | Height: | Size: 6.9 KiB |
|
After Width: | Height: | Size: 6.9 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 6.5 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 20 KiB |
@@ -1,10 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14313.18" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
|
||||
<device id="retina4_7" orientation="portrait">
|
||||
<adaptation id="fullscreen"/>
|
||||
</device>
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="15505" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
|
||||
<device id="retina4_7" orientation="portrait" appearance="light"/>
|
||||
<dependencies>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14283.14"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="15510"/>
|
||||
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
|
||||
</dependencies>
|
||||
<scenes>
|
||||
@@ -12,23 +10,23 @@
|
||||
<scene sceneID="Juk-Ad-tZ2">
|
||||
<objects>
|
||||
<tableViewController id="iNr-Oe-muq" customClass="PlayerEditionViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" dataMode="static" style="plain" separatorStyle="none" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="vlV-lc-eQA">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" dataMode="static" style="plain" separatorStyle="none" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="28" sectionFooterHeight="28" id="vlV-lc-eQA">
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
|
||||
<sections>
|
||||
<tableViewSection id="Nzq-eO-jT3">
|
||||
<cells>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="2gb-gB-918">
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
|
||||
<rect key="frame" x="0.0" y="28" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="2gb-gB-918" id="iyM-TJ-JB4">
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Name" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="m5m-Zs-j0z">
|
||||
<rect key="frame" x="16" y="12" width="343" height="20"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Name" adjustsFontForContentSizeCategory="YES" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="m5m-Zs-j0z">
|
||||
<rect key="frame" x="16" y="11.5" width="343" height="21"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<textInputTraits key="textInputTraits" autocapitalizationType="words" autocorrectionType="no" spellCheckingType="no" returnKeyType="next"/>
|
||||
<connections>
|
||||
<outlet property="delegate" destination="iNr-Oe-muq" id="K2p-7d-teD"/>
|
||||
@@ -43,15 +41,15 @@
|
||||
</tableViewCellContentView>
|
||||
</tableViewCell>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="vp3-Ft-Gth">
|
||||
<rect key="frame" x="0.0" y="44" width="375" height="44"/>
|
||||
<rect key="frame" x="0.0" y="72" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="vp3-Ft-Gth" id="ccO-0O-u72">
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Score" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="rZ9-Fa-cyr">
|
||||
<rect key="frame" x="16" y="12" width="343" height="20"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Score" adjustsFontForContentSizeCategory="YES" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="rZ9-Fa-cyr">
|
||||
<rect key="frame" x="16" y="11.5" width="343" height="21"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<textInputTraits key="textInputTraits" autocorrectionType="no" spellCheckingType="no" keyboardType="numberPad" returnKeyType="done"/>
|
||||
</textField>
|
||||
</subviews>
|
||||
@@ -103,7 +101,7 @@
|
||||
<objects>
|
||||
<navigationController id="ein-Sr-i8w" sceneMemberID="viewController">
|
||||
<navigationBar key="navigationBar" contentMode="scaleToFill" id="zIT-dB-Mfo">
|
||||
<rect key="frame" x="0.0" y="20" width="375" height="44"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="56"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
</navigationBar>
|
||||
<connections>
|
||||
@@ -119,7 +117,7 @@
|
||||
<objects>
|
||||
<navigationController id="UAh-8N-CM8" sceneMemberID="viewController">
|
||||
<navigationBar key="navigationBar" contentMode="scaleToFill" id="U7d-1C-GnL">
|
||||
<rect key="frame" x="0.0" y="20" width="375" height="44"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
</navigationBar>
|
||||
<connections>
|
||||
@@ -134,30 +132,29 @@
|
||||
<scene sceneID="9su-ms-vdJ">
|
||||
<objects>
|
||||
<tableViewController id="PJp-Eq-ZjA" customClass="PlayersViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="tX0-ON-WSI">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="-1" estimatedSectionHeaderHeight="-1" sectionFooterHeight="-1" estimatedSectionFooterHeight="-1" id="tX0-ON-WSI">
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
|
||||
<prototypes>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" reuseIdentifier="Player" textLabel="G8y-VE-YRu" detailTextLabel="NNc-J4-xiE" style="IBUITableViewCellStyleValue1" id="bFj-Hd-fwd">
|
||||
<rect key="frame" x="0.0" y="28" width="375" height="44"/>
|
||||
<rect key="frame" x="0.0" y="28" width="375" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="bFj-Hd-fwd" id="kDf-TZ-xhb">
|
||||
<rect key="frame" x="0.0" y="0.0" width="341" height="43.5"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="348" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="G8y-VE-YRu">
|
||||
<rect key="frame" x="16" y="12" width="31.5" height="19.5"/>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontForContentSizeCategory="YES" adjustsFontSizeToFit="NO" id="G8y-VE-YRu">
|
||||
<rect key="frame" x="16" y="12" width="33.5" height="20.5"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Detail" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="NNc-J4-xiE">
|
||||
<rect key="frame" x="298.5" y="12" width="41.5" height="19.5"/>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Detail" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontForContentSizeCategory="YES" adjustsFontSizeToFit="NO" id="NNc-J4-xiE">
|
||||
<rect key="frame" x="296" y="12" width="44" height="20.5"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<color key="textColor" red="0.5568627451" green="0.5568627451" blue="0.57647058819999997" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<color key="textColor" systemColor="secondaryLabelColor" red="0.23529411759999999" green="0.23529411759999999" blue="0.26274509800000001" alpha="0.59999999999999998" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
</subviews>
|
||||
|
||||
@@ -35,11 +35,11 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
|
||||
extension Player {
|
||||
static func orderedByName() -> QueryInterfaceRequest<Player> {
|
||||
return Player.order(Columns.name)
|
||||
Player.order(Columns.name)
|
||||
}
|
||||
|
||||
static func orderedByScore() -> QueryInterfaceRequest<Player> {
|
||||
return Player.order(Columns.score.desc, Columns.name)
|
||||
Player.order(Columns.score.desc, Columns.name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,10 +57,10 @@ extension Player {
|
||||
"Zazie", "Zoé"]
|
||||
|
||||
static func randomName() -> String {
|
||||
return names.randomElement()!
|
||||
names.randomElement()!
|
||||
}
|
||||
|
||||
static func randomScore() -> Int {
|
||||
return 10 * Int.random(in: 0...100)
|
||||
10 * Int.random(in: 0...100)
|
||||
}
|
||||
}
|
||||
@@ -10,8 +10,8 @@ class PlayersViewController: UITableViewController {
|
||||
|
||||
@IBOutlet private weak var newPlayerButtonItem: UIBarButtonItem!
|
||||
private var players: [Player] = []
|
||||
private var playersObserver: TransactionObserver?
|
||||
private var playerCountObserver: TransactionObserver?
|
||||
private var playersCancellable: DatabaseCancellable?
|
||||
private var playerCountCancellable: DatabaseCancellable?
|
||||
private var playerOrdering: PlayerOrdering = .byScore {
|
||||
didSet {
|
||||
configureOrderingBarButtonItem()
|
||||
@@ -59,12 +59,12 @@ class PlayersViewController: UITableViewController {
|
||||
switch playerOrdering {
|
||||
case .byScore:
|
||||
navigationItem.rightBarButtonItem = UIBarButtonItem(
|
||||
title: "Score ⬇︎",
|
||||
title: "Score ▼",
|
||||
style: .plain,
|
||||
target: self, action: #selector(sortByName))
|
||||
case .byName:
|
||||
navigationItem.rightBarButtonItem = UIBarButtonItem(
|
||||
title: "Name ⬆︎",
|
||||
title: "Name ▲",
|
||||
style: .plain,
|
||||
target: self, action: #selector(sortByScore))
|
||||
}
|
||||
@@ -75,11 +75,10 @@ class PlayersViewController: UITableViewController {
|
||||
let observation = ValueObservation.tracking { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
playerCountObserver = observation.start(
|
||||
playerCountCancellable = observation.start(
|
||||
in: dbQueue,
|
||||
onError: { error in
|
||||
fatalError("Unexpected error: \(error)")
|
||||
},
|
||||
scheduling: .immediate,
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] count in
|
||||
guard let self = self else { return }
|
||||
switch count {
|
||||
@@ -96,45 +95,47 @@ class PlayersViewController: UITableViewController {
|
||||
let observation = ValueObservation.tracking { db in
|
||||
try request.fetchAll(db)
|
||||
}
|
||||
playersObserver = observation.start(
|
||||
playersCancellable = observation.start(
|
||||
in: dbQueue,
|
||||
onError: { error in
|
||||
fatalError("Unexpected error: \(error)")
|
||||
},
|
||||
scheduling: .immediate,
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
|
||||
// Compute difference between current and new list of players
|
||||
let difference = players
|
||||
.difference(from: self.players)
|
||||
.inferringMoves()
|
||||
|
||||
// Apply those changes to the table view
|
||||
self.tableView.performBatchUpdates({
|
||||
self.players = players
|
||||
for change in difference {
|
||||
switch change {
|
||||
case let .remove(offset, _, associatedWith):
|
||||
if let associatedWith = associatedWith {
|
||||
self.tableView.moveRow(
|
||||
at: IndexPath(row: offset, section: 0),
|
||||
to: IndexPath(row: associatedWith, section: 0))
|
||||
} else {
|
||||
self.tableView.deleteRows(
|
||||
at: [IndexPath(row: offset, section: 0)],
|
||||
with: .fade)
|
||||
}
|
||||
case let .insert(offset, _, associatedWith):
|
||||
if associatedWith == nil {
|
||||
self.tableView.insertRows(
|
||||
at: [IndexPath(row: offset, section: 0)],
|
||||
with: .fade)
|
||||
}
|
||||
}
|
||||
}
|
||||
}, completion: nil)
|
||||
self.updateTableView(players)
|
||||
})
|
||||
}
|
||||
|
||||
private func updateTableView(_ players: [Player]) {
|
||||
// Compute difference between current and new list of players
|
||||
let difference = players
|
||||
.difference(from: self.players)
|
||||
.inferringMoves()
|
||||
|
||||
// Apply those changes to the table view
|
||||
tableView.performBatchUpdates({
|
||||
self.players = players
|
||||
for change in difference {
|
||||
switch change {
|
||||
case let .remove(offset, _, associatedWith):
|
||||
if let associatedWith = associatedWith {
|
||||
self.tableView.moveRow(
|
||||
at: IndexPath(row: offset, section: 0),
|
||||
to: IndexPath(row: associatedWith, section: 0))
|
||||
} else {
|
||||
self.tableView.deleteRows(
|
||||
at: [IndexPath(row: offset, section: 0)],
|
||||
with: .fade)
|
||||
}
|
||||
case let .insert(offset, _, associatedWith):
|
||||
if associatedWith == nil {
|
||||
self.tableView.insertRows(
|
||||
at: [IndexPath(row: offset, section: 0)],
|
||||
with: .fade)
|
||||
}
|
||||
}
|
||||
}
|
||||
}, completion: nil)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -174,7 +175,7 @@ extension PlayersViewController {
|
||||
|
||||
extension PlayersViewController {
|
||||
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
||||
return players.count
|
||||
players.count
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
||||
|
||||
@@ -313,7 +313,7 @@ final class SynonymsTokenizer : FTS5WrapperTokenizer {
|
||||
}
|
||||
|
||||
func synonyms(for token: String) -> Set<String>? {
|
||||
return synonyms.first { $0.contains(token) }
|
||||
synonyms.first { $0.contains(token) }
|
||||
}
|
||||
|
||||
func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
|
||||
|
||||
@@ -227,11 +227,11 @@ The table view data source asks the fetched records controller to provide releva
|
||||
|
||||
```swift
|
||||
func numberOfSections(in tableView: UITableView) -> Int {
|
||||
return fetchedRecordsController.sections.count
|
||||
fetchedRecordsController.sections.count
|
||||
}
|
||||
|
||||
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
||||
return fetchedRecordsController.sections[section].numberOfRecords
|
||||
fetchedRecordsController.sections[section].numberOfRecords
|
||||
}
|
||||
|
||||
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
||||
|
||||
@@ -1,522 +0,0 @@
|
||||
Migrating From GRDB 2 to GRDB 3
|
||||
===============================
|
||||
|
||||
GRDB 3 comes with new features, but also a few breaking changes, and a set of updated good practices. This guide aims at helping you upgrading your applications.
|
||||
|
||||
**For all users**
|
||||
|
||||
- [Swift 4.1 Required]
|
||||
- [iOS 8 Sunsetting]
|
||||
- [Database Schema Recommendations]
|
||||
- [Record Protocols Renaming]
|
||||
- [Columns Definition]
|
||||
|
||||
**By topic**
|
||||
|
||||
- [If You Use Database Queues]
|
||||
- [If You Use Database Pools]
|
||||
- [If You Use Database Snapshots]
|
||||
- [If You Use Record Types]
|
||||
- [If You Use Custom Requests]
|
||||
- [If You Use RxGRDB]
|
||||
- [Notable Documentation Updates]
|
||||
|
||||
|
||||
## Swift 4.1 Required
|
||||
|
||||
GRDB 3 uses [conditional conformances], introduced in Swift 4.1. It can only be built on Xcode 9.3+.
|
||||
|
||||
|
||||
## iOS 8 Sunsetting
|
||||
|
||||
GRDB 3 is only tested on iOS 9+, due to a limitation in Xcode 9.3. Code that targets older versions of SQLite and iOS is still there, but is not supported.
|
||||
|
||||
|
||||
## Database Schema Recommendations
|
||||
|
||||
GRDB 2 was totally schema-agnostic, and would gladly accept any database.
|
||||
|
||||
GRDB 3 still accepts any database, but brings two schema recommendations:
|
||||
|
||||
- :bulb: Integer primary keys should be auto-incremented, in order to avoid any row id to be reused.
|
||||
|
||||
When ids can be reused, your app and [database observation tools] may think that a row was updated, when it was actually deleted, then replaced. Depending on your application needs, this may be OK. Or not.
|
||||
|
||||
GRDB 3 thus comes with a new good practice: use the `autoIncrementedPrimaryKey` method when you create a database table with an integer primary key:
|
||||
|
||||
```diff
|
||||
try db.create(table: "author") { t in
|
||||
- t.column("id", .integer).primaryKey() // GRDB 2
|
||||
+ t.autoIncrementedPrimaryKey("id") // GRDB 3 recommendation
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
- :bulb: Database table names should be singular, and camel-cased. Make them look like Swift identifiers: `place`, `country`, `postalAddress`, 'httpRequest'.
|
||||
|
||||
This will help you using the new [Associations] feature when you need it. Database table names that follow another naming convention are totally OK, but you will need to perform extra configuration.
|
||||
|
||||
This convention is applied by the default implementation of the `TableRecord.databaseTableName`: see [If You Use Record Types] below.
|
||||
|
||||
Since you are reading this guide, your application has already defined its database schema. You can migrate it in order to apply the new recommendations, if needed. Below is a sample code that uses [DatabaseMigrator], the recommended tool for managing your database schema:
|
||||
|
||||
```swift
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
// Existing GRDB 2 migration:
|
||||
migrator.registerMigration("initial") { db in
|
||||
try db.create(table: "authors") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
try db.create(table: "books") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.column("authorId", .integer).notNull().references("authors")
|
||||
t.column("title", .text).notNull()
|
||||
}
|
||||
}
|
||||
|
||||
// New GRDB 3 migration:
|
||||
// - Rename tables so that they look like Swift identifiers (singular and camelCased)
|
||||
// - Make integer primary keys auto-incremented
|
||||
//
|
||||
// Since several tables are recreated from scratch, referential integrity
|
||||
// constraints may break during the process. The
|
||||
// registerMigrationWithDeferredForeignKeyCheck method makes sure that foreign
|
||||
// key checks are temporarily disabled, and checked at the end:
|
||||
migrator.registerMigrationWithDeferredForeignKeyCheck("GRDB3") { db in
|
||||
try db.create(table: "author") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
try db.create(table: "book") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("authorId", .integer).notNull().references("author")
|
||||
t.column("title", .text).notNull()
|
||||
}
|
||||
try db.execute("""
|
||||
INSERT INTO author SELECT * FROM authors;
|
||||
INSERT INTO book SELECT * FROM books;
|
||||
""")
|
||||
try db.drop(table: "authors")
|
||||
try db.drop(table: "books")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Record Protocols Renaming
|
||||
|
||||
GRDB 3 has renamed the [record protocols]:
|
||||
|
||||
- `RowConvertible` -> `FetchableRecord`
|
||||
- `TableMapping` -> `TableRecord`
|
||||
- `Persistable` -> `PersistableRecord`
|
||||
- `MutablePersistable` -> `MutablePersistableRecord`
|
||||
|
||||
After upgrading, build your project: the compiler will guide you through the renaming by the way of fixits.
|
||||
|
||||
|
||||
## Columns Definition
|
||||
|
||||
GRDB 2 has you define columns of the query interface with the Column type:
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
let nameColumn = Column("name")
|
||||
let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db)
|
||||
```
|
||||
|
||||
A recommended practice was to define enum namespaces in record types:
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
struct Player: RowConvertible, TableMapping {
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
static let name = Column("name")
|
||||
static let score = Column("score")
|
||||
}
|
||||
|
||||
init(row: Row) {
|
||||
id = row[Columns.id]
|
||||
name = row[Columns.name]
|
||||
score = row[Columns.score]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In GRDB 3, `Column` is still there, but a new `ColumnExpression` protocol has been introduced in order to streamline column enums:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
struct Player: FetchableRecord, TableRecord {
|
||||
enum Columns: String, ColumnExpression {
|
||||
case id, name, score
|
||||
}
|
||||
|
||||
init(row: Row) {
|
||||
id = row[Columns.id]
|
||||
name = row[Columns.name]
|
||||
score = row[Columns.score]
|
||||
}
|
||||
}
|
||||
|
||||
extension Player {
|
||||
static func filter(name: String) -> QueryInterfaceRequest<Player> {
|
||||
return filter(Columns.name == name)
|
||||
}
|
||||
|
||||
static var maximumScore: QueryInterfaceRequest<Int> {
|
||||
return select(max(Columns.score), as: Int.self)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
When your record adopts the Codable protocol, you can use its [coding keys](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types) to safely define database columns:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
struct Player: Codable {
|
||||
var id: Int64
|
||||
var name: String
|
||||
var score: Int
|
||||
}
|
||||
|
||||
extension Player: FetchableRecord, PersistableRecord {
|
||||
enum Columns {
|
||||
static let id = Column(CodingKeys.id.stringValue)
|
||||
static let name = Column(CodingKeys.name.stringValue)
|
||||
static let score = Column(CodingKeys.score.stringValue)
|
||||
}
|
||||
|
||||
static func filter(name: String) -> QueryInterfaceRequest<Player> {
|
||||
return filter(Columns.name == name)
|
||||
}
|
||||
|
||||
static var maximumScore: QueryInterfaceRequest<Int> {
|
||||
return select(max(Columns.score), as: Int.self)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## If You Use Database Queues
|
||||
|
||||
With GRDB 2, you used to access the database through the `inDatabase` or `inTransaction` [DatabaseQueue] methods:
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
let players = try dbQueue.inDatabase { db in
|
||||
try Player.fetchAll(db)
|
||||
}
|
||||
|
||||
try dbQueue.inDatabase { db in
|
||||
try player.updateChanges(db)
|
||||
}
|
||||
|
||||
var balance: Amount! = nil
|
||||
try dbQueue.inTransaction { db in
|
||||
try Credit(destinationAccout, amount).insert(db)
|
||||
try Debit(sourceAccount, amount).insert(db)
|
||||
balance = try sourceAccount.fetchBalance(db)
|
||||
return .commit
|
||||
}
|
||||
```
|
||||
|
||||
The code above still runs, unchanged, in GRDB 3.
|
||||
|
||||
Yet it is now recommended that you use the `read` and `write` methods instead:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
let players = try dbQueue.read { db in
|
||||
try Player.fetchAll(db)
|
||||
}
|
||||
|
||||
try dbQueue.write { db in
|
||||
try player.updateChanges(db)
|
||||
}
|
||||
|
||||
let balance = try dbQueue.write { db in
|
||||
try Credit(destinationAccout, amount).insert(db)
|
||||
try Debit(sourceAccount, amount).insert(db)
|
||||
return try sourceAccount.fetchBalance(db)
|
||||
}
|
||||
```
|
||||
|
||||
The purpose of the new `read` and `write` methods is to soothe the "transaction mental load" of previous versions of GRDB, a legacy of the [FMDB] heritage. All developers can *forget* to open transactions, with the unfortunate consequence that the database may end up containing inconsistent values. Experienced developers may *wonder* whether they should open transactions or not, even when this doesn't matter a lot.
|
||||
|
||||
With GRDB 3, use `read` when you need to read values. It's impossible to write within a `read` block, which means that you can be sure that no unwanted side effect can happen.
|
||||
|
||||
When you need to write, use `write`: your database changes are automatically wrapped in a transaction, with the guarantee that all changes are written to disk, or, should any error happen, none at all.
|
||||
|
||||
Of course, precise transaction handling sometimes matter. Check the updated [Transactions and Savepoints] chapter.
|
||||
|
||||
|
||||
## If You Use Database Pools
|
||||
|
||||
With GRDB 2, you used to access the database through the `read`, `write` or `writeInTransaction` [DatabasePool] methods:
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
let players = try dbPool.read { db in
|
||||
try Player.fetchAll(db)
|
||||
}
|
||||
|
||||
try dbPool.write { db in
|
||||
try player.updateChanges(db)
|
||||
}
|
||||
|
||||
var balance: Amount! = nil
|
||||
try dbPool.writeInTransaction { db in
|
||||
try Credit(destinationAccout, amount).insert(db)
|
||||
try Debit(sourceAccount, amount).insert(db)
|
||||
balance = try sourceAccount.fetchBalance(db)
|
||||
return .commit
|
||||
}
|
||||
```
|
||||
|
||||
In GRDB 3, the `write` method has changed: it now automatically wraps your database changes in a transaction, which means that the last block can be rewritten as below:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
let balance = try dbPool.write { db in
|
||||
try Credit(destinationAccout, amount).insert(db)
|
||||
try Debit(sourceAccount, amount).insert(db)
|
||||
return try sourceAccount.fetchBalance(db)
|
||||
}
|
||||
```
|
||||
|
||||
Side effect: you can no longer open explicit transactions inside a `write` block:
|
||||
|
||||
```swift
|
||||
// GRDB 2: OK
|
||||
// GRDB 3: SQLite error 1 with statement `BEGIN DEFERRED TRANSACTION`:
|
||||
// cannot start a transaction within a transaction
|
||||
try dbPool.write { db in
|
||||
try db.inTransaction { ... }
|
||||
}
|
||||
```
|
||||
|
||||
When precise transaction handling is needed, check the updated [Transactions and Savepoints] chapter.
|
||||
|
||||
The purpose of this change is to prevent an easy misuse of database pools in previous GRDB versions. Unless writes were wrapped inside an explicit transactions, concurrent reads could see an inconsistent state of the database:
|
||||
|
||||
```swift
|
||||
// GRDB 2: unsafe
|
||||
// GRDB 3: safe
|
||||
try dbPool.write { db in
|
||||
try Credit(destinationAccout, amount).insert(db)
|
||||
try Debit(sourceAccount, amount).insert(db)
|
||||
}
|
||||
```
|
||||
|
||||
Since `write` now wraps your changes in a transaction, you have the guarantee that concurrent reads can't see them until they are all written to disk.
|
||||
|
||||
|
||||
## If You Use Database Snapshots
|
||||
|
||||
With GRDB 2, you used to create [database snapshots] with the `makeSnaphot` [DatabasePool] method. For example:
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
let snapshot: DatabaseSnapshot = try dbPool.write { db in
|
||||
try Player.deleteAll()
|
||||
return dbPool.makeSnapshot()
|
||||
}
|
||||
|
||||
// Guaranteed to be zero
|
||||
let count = try snapshot.read { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
GRDB 3 will crash the above code on the `makeSnapshot()` line, with a fatal error: "makeSnapshot() must not be called from inside a transaction."
|
||||
|
||||
To avoid this error, you will need [precise transaction handling]:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
let snapshot: DatabaseSnapshot = try dbPool.writeWithoutTransaction { db in
|
||||
try Player.deleteAll()
|
||||
return dbPool.makeSnapshot()
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## If You Use Record Types
|
||||
|
||||
Record types that adopt the former TableMapping protocol, renamed TableRecord, used to declare their table name:
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
struct Place: TableMapping {
|
||||
static let databaseTableName = "place"
|
||||
}
|
||||
print(Place.databaseTableName) // print "place"
|
||||
```
|
||||
|
||||
With GRDB 3, the `databaseTableName` property gets a default implementation:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
struct Place: TableRecord { }
|
||||
print(Place.databaseTableName) // print "place"
|
||||
```
|
||||
|
||||
That default name follows the [Database Schema Recommendations]: it is singular, camel-cased, and looks like a Swift identifier:
|
||||
|
||||
- Place: `place`
|
||||
- Country: `country`
|
||||
- PostalAddress: `postalAddress`
|
||||
- HTTPRequest: `httpRequest`
|
||||
- TOEFL: `toefl`
|
||||
|
||||
When you subclass the Record class, the Swift compiler won't let you profit from this default name: you have to keep on providing an explicit table name:
|
||||
|
||||
```swift
|
||||
// GRDB 2 and GRDB 3
|
||||
class Place: Record {
|
||||
override var databaseTableName: String {
|
||||
return "place"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## If You Use Custom Requests
|
||||
|
||||
[Custom requests] let you escape the limitations of the [query interface], when it can not generate the requests you need.
|
||||
|
||||
You may, for example, use `SQLRequest`:
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
extension Player {
|
||||
static func filter(color: Color) -> AnyTypedRequest<Player> {
|
||||
let sql = "SELECT * FROM players WHERE color = ?"
|
||||
let request = SQLRequest(sql, arguments: [color])
|
||||
return request.asRequest(of: Player.self)
|
||||
}
|
||||
}
|
||||
|
||||
let players = try Player.filter(color: .red).fetchAll(db)
|
||||
```
|
||||
|
||||
The `AnyTypedRequest` type is no longer available, and `SQLRequest` is now a generic type:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
extension Player {
|
||||
static func filter(color: Color) -> SQLRequest<Player> {
|
||||
let sql = "SELECT * FROM players WHERE color = ?"
|
||||
return SQLRequest(sql, arguments: [color])
|
||||
}
|
||||
}
|
||||
|
||||
let players = try Player.filter(color: .red).fetchAll(db)
|
||||
```
|
||||
|
||||
See the updated [Custom Requests](../README.md#custom-requests) chapter for more information.
|
||||
|
||||
|
||||
## If You Use RxGRDB
|
||||
|
||||
Some RxGRDB APIs have slighly changed. Did you track multiple requests at the same time with "fetch tokens"?
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
dbQueue.rx
|
||||
.fetchTokens(in: [request, ...])
|
||||
.mapFetch { db in try fetchResult(db) }
|
||||
.subscribe(...)
|
||||
```
|
||||
|
||||
Now you'll write instead:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
ValueObservation
|
||||
.tracking([request, ...], fetch: { db in try fetchResult(db) })
|
||||
.rx
|
||||
.fetch(in: dbQueue)
|
||||
.subscribe(...)
|
||||
```
|
||||
|
||||
It's just a syntactic change, without any impact on the runtime.
|
||||
|
||||
GRDB 3.6 also introduces a new protocol, [DatabaseRegionConvertible], that allows a better encapsulation of complex requests, and a streamlined observable definition.
|
||||
|
||||
For example:
|
||||
|
||||
```swift
|
||||
// GRDB 2: Track a team and its players
|
||||
let teamId = 1
|
||||
let teamRequest = Team.filter(key: teamId)
|
||||
let playersRequest = Player.filter(teamId: teamId)
|
||||
dbQueue.rx
|
||||
.fetchTokens(in: [teamRequest, playersRequest])
|
||||
.mapFetch { db -> TeamInfo? in
|
||||
guard let team = try teamRequest.fetchOne(db) else {
|
||||
return nil
|
||||
}
|
||||
let players = try playersRequest.fetchAll(db)
|
||||
return TeamInfo(team: team, players: players)
|
||||
}
|
||||
.subscribe(onNext: { teamInfo: TeamInfo? in
|
||||
...
|
||||
})
|
||||
|
||||
// GRDB 3: Track a team and its players
|
||||
struct TeamInfoRequest: DatabaseRegionConvertible { ... }
|
||||
let request = TeamInfoRequest(teamId: 1)
|
||||
ValueObservation.tracking(request, fetch: { try request.fetchOne($0) })
|
||||
.rx
|
||||
.fetch(in: dbQueue)
|
||||
.subscribe(onNext: { teamInfo: TeamInfo? in
|
||||
...
|
||||
})
|
||||
```
|
||||
|
||||
|
||||
## Notable Documentation Updates
|
||||
|
||||
If you have time, you may dig deeper in GRDB 3 with those updated documentation chapter:
|
||||
|
||||
- [Database Queues](../README.md#database-queues): focus on the new `read` and `write` methods.
|
||||
- [Transactions and Savepoints](../README.md#transactions-and-savepoints): the chapter has been rewritten in order to introduce transactions as a power-user feature.
|
||||
- [ScopeAdapter](../README.md#scopeadapter): do you use row adapters? If so, have a look.
|
||||
- [Examples of Record Definitions](../README.md#examples-of-record-definitions): this new chapter provides a handy reference of the three main ways to define record types (Codable, plain struct, Record subclass).
|
||||
- [SQL Operators](../README.md#sql-operators): the chapter introduces the new `joined(operator:)` method that lets you join a chain of expressions with `AND` or `OR` without nesting: `[cond1, cond2, ...].joined(operator: .and)`.
|
||||
- [Custom Requests](../README.md#custom-requests): the old `Request` and `TypedRequest` protocols have been replaced with `FetchRequest`. If you want to know more about custom requests, check this chapter.
|
||||
- [Migrations](../README.md#migrations): learn how to check if a migration has been applied (very useful for migration tests).
|
||||
|
||||
|
||||
[How To Upgrade]: #how-to-upgrade
|
||||
[Database Schema Recommendations]: #database-schema-recommendations
|
||||
[Record Protocols Renaming]: #record-protocols-renaming
|
||||
[Columns Definition]: #columns-definition
|
||||
[Swift 4.1 Required]: #swift-41-required
|
||||
[iOS 8 Sunsetting]: #ios-8-sunsetting
|
||||
[If You Use Database Queues]: #if-you-use-database-queues
|
||||
[If You Use Database Pools]: #if-you-use-database-pools
|
||||
[If You Use Database Snapshots]: #if-you-use-database-snapshots
|
||||
[If You Use Record Types]: #if-you-use-record-types
|
||||
[If You Use Custom Requests]: #if-you-use-custom-requests
|
||||
[If You Use RxGRDB]: #if-you-use-rxgrdb
|
||||
[Notable Documentation Updates]: #notable-documentation-updates
|
||||
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
|
||||
[Associations]: AssociationsBasics.md
|
||||
[DatabaseMigrator]: ../README.md#migrations
|
||||
[database observation tools]: ../README.md#database-changes-observation
|
||||
[Transactions and Savepoints]: ../README.md#transactions-and-savepoints
|
||||
[precise transaction handling]: ../README.md#transactions-and-savepoints
|
||||
[DatabaseQueue]: ../README.md#database-queues
|
||||
[DatabasePool]: ../README.md#database-pools
|
||||
[database snapshots]: ../README.md#database-snapshots
|
||||
[FMDB]: http://github.com/ccgus/fmdb
|
||||
[record protocols]: ../README.md#record-protocols-overview
|
||||
[Custom requests]: ../README.md#custom-requests
|
||||
[query interface]: ../README.md#the-query-interface
|
||||
[DatabaseRegionConvertible]: https://github.com/groue/GRDB.swift#the-databaseregionconvertible-protocol
|
||||
[conditional conformances]: https://github.com/apple/swift-evolution/blob/master/proposals/0143-conditional-conformances.md
|
||||
@@ -1,187 +0,0 @@
|
||||
Migrating From GRDB 3 to GRDB 4
|
||||
===============================
|
||||
|
||||
GRDB 4 comes with new features, but also a few breaking changes. This guide aims at helping you upgrading your applications.
|
||||
|
||||
- [New requirements](#new-requirements)
|
||||
- [Raw SQL](#raw-sql)
|
||||
- [ValueObservation](#valueobservation)
|
||||
- [Associations](#associations)
|
||||
- [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md)
|
||||
- [SQLCipher](#sqlcipher)
|
||||
- [PersistenceError.recordNotFound](#persistenceerrorrecordnotfound)
|
||||
|
||||
|
||||
### New requirements
|
||||
|
||||
GRDB now requires Swift 4.2+ and Xcode 10+. Swift 4.0 and 4.1 are no longer supported. Xcode 9 is no longer supported.
|
||||
|
||||
iOS 8 is no longer supported. The minimum iOS target is now iOS 9.
|
||||
|
||||
|
||||
### Raw SQL
|
||||
|
||||
Whenever your application uses raw SQL queries or snippets, you will now always have to use the `sql` argument label:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
try db.execute("INSERT INTO player (name) VALUES (?)", arguments: ["Arthur"])
|
||||
let playerCount = try Int.fetchOne(db, "SELECT COUNT(*) FROM player")
|
||||
|
||||
// GRDB 4
|
||||
try db.execute(sql: "INSERT INTO player (name) VALUES (?)", arguments: ["Arthur"])
|
||||
let playerCount = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM player")
|
||||
```
|
||||
|
||||
This change was made necessary by the introduction of [SQL Interpolation].
|
||||
|
||||
|
||||
### ValueObservation
|
||||
|
||||
[ValueObservation] has been refreshed in GRDB 4.
|
||||
|
||||
To guarantee asynchronous notifications, and never ever block your main thread, use the `.async(onQueue:startImmediately:)` scheduling:
|
||||
|
||||
```swift
|
||||
// On main queue
|
||||
var observation = Player.observationForAll()
|
||||
observation.scheduling = .async(onQueue: .main, startImmediately: true)
|
||||
let observer = try observation.start(
|
||||
in: dbQueue,
|
||||
onError: { error in ... },
|
||||
onChange: { (players: [Player]) in
|
||||
// On main queue
|
||||
print("fresh players: \(players)")s
|
||||
})
|
||||
// <- here "fresh players" is not printed yet.
|
||||
```
|
||||
|
||||
In GRDB 3, this scheduling used to be named `.queue(_: startImmediately:)`.
|
||||
|
||||
The second breaking change is `ValueObservation.extent`, which was removed in GRDB 4. Now all observations last until the observer returned by the `start` method is deallocated.
|
||||
|
||||
|
||||
### Associations
|
||||
|
||||
GRDB 4 brought a few new [associations] features:
|
||||
|
||||
- **Indirect associations** [HasOneThrough] and [HasManyThrough] let you define associations from a record to another through a third one. For example, they let you easily express many-to-many relations such as "a country has many citizens through its passports":
|
||||
|
||||
```swift
|
||||
struct Country: TableRecord, EncodableRecord {
|
||||
static let passports = hasMany(Passport.self)
|
||||
// New!
|
||||
static let citizens = hasMany(Citizen.self, through: passports, using: Passport.citizen)
|
||||
var citizens: QueryInterfaceRequest<Citizen> {
|
||||
return request(for: Country.citizens)
|
||||
}
|
||||
}
|
||||
|
||||
struct Passport: TableRecord {
|
||||
static let citizen = belongsTo(Citizen.self)
|
||||
}
|
||||
|
||||
struct Citizen: TableRecord {
|
||||
}
|
||||
|
||||
let country: Country = ...
|
||||
let citizens: [Citizen] = try dbQueue.read { db in
|
||||
try country.citizens.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||

|
||||
|
||||
- **Eager loading of HasMany associations**: The new `including(all:)` method lets you load arrays or sets of associated records in a single request:
|
||||
|
||||
```swift
|
||||
// All authors with their respective books
|
||||
let request = Author.including(all: Author.books)
|
||||
|
||||
// This request can feed the following record:
|
||||
struct AuthorInfo: FetchableRecord, Decodable {
|
||||
var author: Author
|
||||
var books: [Book] // all associated books
|
||||
}
|
||||
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
See [Joining And Prefetching Associated Records] for more information.
|
||||
|
||||
- **Automatic pluralization and singularization** of association identifiers.
|
||||
|
||||
GRDB will automatically **pluralize** or **singularize** names in order to help you easily associate records.
|
||||
|
||||
For example, the Book and Author records will automatically feed properties named `books`, `author`, or `bookCount` in your decoded records, without any explicit configuration, as long as the names of the backing database tables are "book" and "author".
|
||||
|
||||
The GRDB pluralization mechanisms are very powerful, being capable of pluralizing and singularizing both regular and irregular words (it's directly inspired from the battle-tested [Ruby on Rails inflections](https://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-pluralize)).
|
||||
|
||||
However, this change may have introduced some incompatibilities with GRDB 3 associations. Check [The Structure of a Joined Request] for more information.
|
||||
|
||||
|
||||
### SQLCipher
|
||||
|
||||
The integration of GRDB with SQLCipher has changed.
|
||||
|
||||
1. With GRDB 3, it was possible to perform a manual installation, or to use CocoaPods and the GRDBCipher pod.
|
||||
|
||||
With GRDB 4, CocoaPods is the only supported installation method. And the GRDBCipher pod is discontinued, replaced with GRDB.swift/SQLCipher:
|
||||
|
||||
```diff
|
||||
-pod 'GRDBCipher'
|
||||
+pod 'GRDB.swift/SQLCipher'
|
||||
```
|
||||
|
||||
In your Swift code, you no longer import the GRDBCipher module, but GRDB:
|
||||
|
||||
```diff
|
||||
-import GRDBCipher
|
||||
+import GRDB
|
||||
```
|
||||
|
||||
2. The default SQLCipher version which comes with GRDB 4 is now SQLCipher 4, which is incompatible with SQLCipher 3. SQLCipher 3 is still supported, though. See [Encryption] for more details.
|
||||
|
||||
3. The `cipherPageSize` and `kdfIterations` configuration properties are discontinued. With GRDB 4, run sql pragmas in the `prepareDatabase` property of the configuration:
|
||||
|
||||
```swift
|
||||
var configuration = Configuration()
|
||||
configuration.passphrase = "secret"
|
||||
configuration.prepareDatabase = { db in
|
||||
try db.execute(sql: "PRAGMA cipher_page_size = 4096")
|
||||
try db.execute(sql: "PRAGMA kdf_iter = 128000")
|
||||
}
|
||||
let dbQueue = try DatabaseQueue(path: "...", configuration: configuration)
|
||||
```
|
||||
|
||||
|
||||
### PersistenceError.recordNotFound
|
||||
|
||||
PersistenceError.recordNotFound is thrown whenever a record update method does not find any database row to update. It was refactored in GRDB 4:
|
||||
|
||||
```swift
|
||||
public enum PersistenceError: Error {
|
||||
case recordNotFound(databaseTableName: String, key: [String: DatabaseValue])
|
||||
}
|
||||
|
||||
do {
|
||||
try player.updateChanges {
|
||||
$0.score += 1000
|
||||
}
|
||||
} catch let error as PersistenceError.recordNotFound {
|
||||
// Update failed because player does not exist in the database
|
||||
print(error)
|
||||
// prints "Key not found in table player: [id:42]"
|
||||
}
|
||||
```
|
||||
|
||||
[SQL Interpolation]: SQLInterpolation.md
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[Encryption]: ../README.md#encryption
|
||||
[HasOneThrough]: AssociationsBasics.md#hasonethrough
|
||||
[HasManyThrough]: AssociationsBasics.md#hasmanythrough
|
||||
[PersistableRecord]: ../README.md#persistablerecord-protocol
|
||||
[associations]: AssociationsBasics.md
|
||||
[EncodableRecord]: ../README.md#persistablerecord-protocol
|
||||
[The Structure of a Joined Request]: AssociationsBasics.md#the-structure-of-a-joined-request
|
||||
[Joining And Prefetching Associated Records]: AssociationsBasics.md#joining-and-prefetching-associated-records
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
Migrating From GRDB 4 to GRDB 5
|
||||
===============================
|
||||
|
||||
**This guide aims at helping you upgrading your applications from GRDB 4 to GRDB 5.**
|
||||
|
||||
- [Preparing the Migration to GRDB 5](#preparing-the-migration-to-grdb-5)
|
||||
- [New requirements](#new-requirements)
|
||||
- [ValueObservation](#valueobservation)
|
||||
- [Other Changes](#other-changes)
|
||||
|
||||
|
||||
## Preparing the Migration to GRDB 5
|
||||
|
||||
If you haven't made it yet, upgrade to the [latest GRDB 4 release](https://github.com/groue/GRDB.swift/tags) first, and fix any deprecation warning prior to the GRDB 5 upgrade.
|
||||
|
||||
GRDB 5 ships with fix-its that will suggest simple syntactic changes, and won't require you to think much.
|
||||
|
||||
Your attention will be needed, though, in the area of database observation.
|
||||
|
||||
|
||||
## New requirements
|
||||
|
||||
GRDB requirements have been bumped:
|
||||
|
||||
- **Swift 5.2+** (was Swift 4.2+)
|
||||
- **Xcode 11.4+** (was Xcode 10.0+)
|
||||
- iOS 9.0+ (unchanged)
|
||||
- **macOS 10.10+** (was macOS 10.9+)
|
||||
- tvOS 9.0+ (unchanged)
|
||||
- watchOS 2.0+ (unchanged)
|
||||
|
||||
|
||||
## ValueObservation
|
||||
|
||||
[ValueObservation] is the database observation tool that tracks changes in database values. It has quite changed in GRDB 5.
|
||||
|
||||
Those changes have the vanilla GRDB, [GRDBCombine], and [RxGRDB], offer a common API, and a common behavior. This greatly helps choosing or switching your preferred database observation technique. In previous versions of GRDB, the three companion libraries used to have subtle differences that were just opportunities for bugs.
|
||||
|
||||
In the end, this migration step might require some work. But it's for the benefit of all!
|
||||
|
||||
- [Creating ValueObservation](#creating-valueobservation)
|
||||
- [Starting ValueObservation](#starting-valueobservation)
|
||||
- [Runtime Behavior of ValueObservation](#runtime-behavior-of-valueobservation)
|
||||
- [Removed ValueObservation Methods](#removed-valueobservation-methods)
|
||||
|
||||
### Creating ValueObservation
|
||||
|
||||
In GRDB 5, you *always* create a ValueObservation by providing a function that fetches the observed value:
|
||||
|
||||
```swift
|
||||
// GRDB 5
|
||||
let observation = ValueObservation.tracking { db in
|
||||
/* fetch and return the observed value */
|
||||
}
|
||||
|
||||
// For example, an observation of [Player], which tracks all players:
|
||||
let observation = ValueObservation.tracking { db in
|
||||
try Player.fetchAll(db)
|
||||
}
|
||||
|
||||
// The same observation, using shorthand notation:
|
||||
let observation = ValueObservation.tracking(Player.fetchAll)
|
||||
```
|
||||
|
||||
If the tracked value is computed from several database requests that are not always the same, make sure you use the `trackingVaryingRegion` method, as below. See [Observing a Varying Database Region] for more information.
|
||||
|
||||
```swift
|
||||
// An observation which does not always execute the same requests:
|
||||
let observation = ValueObservation.trackingVaryingRegion { db -> Int in
|
||||
let preference = try Preference.fetchOne(db) ?? .default
|
||||
switch preference.selection {
|
||||
case .food: return try Food.fetchCount(db)
|
||||
case .beverage: return try Beverage.fetchCount(db)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Several methods that build observations were removed:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
let observation = request.observationForCount()
|
||||
let observation = request.observationForFirst()
|
||||
let observation = request.observationForAll()
|
||||
let observation = ValueObservation.tracking(value: someFetchFunction)
|
||||
let observation = ValueObservation.tracking(..., fetch: { db in ... })
|
||||
|
||||
// NEW: GRDB 5
|
||||
let observation = ValueObservation.tracking(request.fetchCount)
|
||||
let observation = ValueObservation.tracking(request.fetchOne)
|
||||
let observation = ValueObservation.tracking(request.fetchAll)
|
||||
let observation = ValueObservation.tracking(someFetchFunction)
|
||||
let observation = ValueObservation.tracking { db in ... }
|
||||
```
|
||||
|
||||
Finally, ValueObservation used to let application define custom "reducers" based on a protocol name ValueReducer, which was removed in GRDB 5. See the [#731](https://github.com/groue/GRDB.swift/pull/731) conversation for a solution towards a replacement.
|
||||
|
||||
<details>
|
||||
<summary>RxGRDB impact</summary>
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
request.rx.observeCount(in: dbQueue)
|
||||
request.rx.observeFirst(in: dbQueue)
|
||||
request.rx.observeAll(in: dbQueue)
|
||||
|
||||
// NEW: GRDB 5
|
||||
ValueObservation.tracking(request.fetchCount).rx.observe(in: dbQueue)
|
||||
ValueObservation.tracking(request.fetchOne).rx.observe(in: dbQueue)
|
||||
ValueObservation.tracking(request.fetchAll).rx.observe(in: dbQueue)
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
### Starting ValueObservation
|
||||
|
||||
The `start` method which starts observing the database has changed as well.
|
||||
|
||||
```swift
|
||||
// Start observing the database
|
||||
let cancellable = observation.start(
|
||||
in: dbQueue,
|
||||
onError: { error in ... },
|
||||
onChange: { value in print("fresh value: \(value)") })
|
||||
```
|
||||
|
||||
1. The result of the `start` method is now a DatabaseCancellable which allows you to explicitly stop an observation:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
let observer: TransactionObserver?
|
||||
observer = observation.start(...)
|
||||
observer = nil // Stop the observation
|
||||
|
||||
// NEW: GRDB 5
|
||||
let cancellable: DatabaseCancellable
|
||||
cancellable = observation.start(...)
|
||||
cancellable.cancel() // Stop the observation
|
||||
```
|
||||
|
||||
The returned DatabaseCancellable cancels itself when it gets deinitialized.
|
||||
|
||||
2. The `onError` handler of the `start` method is now mandatory:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
do {
|
||||
try observation.start(in: dbQueue) { value in
|
||||
print("fresh value: \(value)")
|
||||
}
|
||||
} catch { ... }
|
||||
|
||||
// NEW: GRDB 5
|
||||
observation.start(
|
||||
in: dbQueue,
|
||||
onError: { error in ... },
|
||||
onChange: { value in print("fresh value: \(value)") })
|
||||
```
|
||||
|
||||
|
||||
### Runtime Behavior of ValueObservation
|
||||
|
||||
**The behavior of ValueObservation has changed**.
|
||||
|
||||
The changes can quite impact your application. We'll describe them below, as well as the strategies to restore the previous behavior when needed.
|
||||
|
||||
1. ValueObservation used to notify its initial value *immediately* when the observation starts. Now, it notifies fresh values on the main thread, *asynchronously*, by default.
|
||||
|
||||
This means that the parts of your application that rely on this immediate value to, say, set up their user interface, have to be modified. Otherwise, they may suffer from a brief flash of missing data, during the short amount of time between the beginning of the observation, and the asynchronous delivery of the initial value.
|
||||
|
||||
To be granted with an immediate, synchronous, delivery of the initial value, insert a `scheduling: .immediate` argument in the `start` method:
|
||||
|
||||
```swift
|
||||
let observation = ValueObservation.tracking(Player.fetchAll)
|
||||
let cancellable = observation.start(
|
||||
in: dbQueue,
|
||||
// Opt in for immediate notification of the initial value
|
||||
scheduling: .immediate,
|
||||
onError: { error in ... },
|
||||
onChange: { [weak self] (players: [Player]) in
|
||||
guard let self = self else { return }
|
||||
self.updateView(players)
|
||||
})
|
||||
// <- Here the view has already been updated.
|
||||
```
|
||||
|
||||
Note that the `.immediate` scheduling requires that the observation starts from the main thread. A fatal error is raised otherwise.
|
||||
|
||||
<details>
|
||||
<summary>GRDBCombine impact</summary>
|
||||
|
||||
```swift
|
||||
let observation = ValueObservation.tracking(Player.fetchAll)
|
||||
let cancellable = observation
|
||||
.publisher(in: dbQueue)
|
||||
// Opt in for immediate notification of the initial value
|
||||
.scheduling(.immediate)
|
||||
.sink(...)
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>RxGRDB impact</summary>
|
||||
|
||||
```swift
|
||||
let observation = ValueObservation.tracking(Player.fetchAll)
|
||||
let disposable = observation
|
||||
.rx.observe(in: dbQueue)
|
||||
// Opt in for immediate notification of the initial value
|
||||
.scheduling(.immediate)
|
||||
.subscribe(...)
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
2. ValueObservation used to notify one fresh value for each and every database transaction that had an impact on the tracked value. Now, it may coalesce notifications. If your application relies on exactly one notification per transaction, use [DatabaseRegionObservation] instead.
|
||||
|
||||
3. Some value observations used to automatically remove duplicate values. This is no longer automatic. If your application relies on distinct consecutive values, use the [removeDuplicates] operator.
|
||||
|
||||
4. ValueObservation used to prevent a database connection (DatabaseQueue or DatabasePool) from closing. Now an observation just stops emitting any fresh value when the database connection closes.
|
||||
|
||||
5. ValueObservation used to be able to restart notifying fresh values after it has notified an error. Now an error marks the end of the observation.
|
||||
|
||||
6. ValueObservation used to have a `scheduling` property, which has been removed.
|
||||
|
||||
You can remove the explicit request to dispatch fresh values asynchronously on the main dispatch queue, because it is now the default behavior:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
var observation = ValueObservation.tracking(...)
|
||||
observation.scheduling = .async(onQueue: .main, startImmediately: true)
|
||||
observation.start(in: dbQueue, onError: ..., onChange: ...)
|
||||
|
||||
// NEW: GRDB 5
|
||||
let observation = ValueObservation.tracking(...)
|
||||
observation.start(in: dbQueue, onError: ..., onChange: ...)
|
||||
```
|
||||
|
||||
For other dispatch queues, use the `scheduling` parameter of the `start` method:
|
||||
|
||||
```swift
|
||||
let queue: DispatchQueue = ...
|
||||
|
||||
// BEFORE: GRDB 4
|
||||
var observation = ValueObservation.tracking(...)
|
||||
observation.scheduling = .async(onQueue: queue, startImmediately: true)
|
||||
observation.start(in: dbQueue, onError: ..., onChange: ...)
|
||||
|
||||
// NEW: GRDB 5
|
||||
let observation = ValueObservation.tracking(...)
|
||||
observation.start(in: dbQueue, scheduling: .async(onQueue: queue), onError: ..., onChange: ...)
|
||||
```
|
||||
|
||||
The GRDB 4 `startImmediately` parameter is no longer supported: ValueObservation now always emits an initial value, without waiting for eventual changes. It is up to your application to ignore this initial value if it wants to.
|
||||
|
||||
|
||||
### Removed ValueObservation Methods
|
||||
|
||||
1. ValueObservation used to have a `compactMap` method. This method has been removed without any replacement.
|
||||
|
||||
If your application uses GRDBCombine or RxGRDB, then use the `compactMap` method from Combine or RxSwift instead.
|
||||
|
||||
2. ValueObservation used to have a `combine` method. This method has been removed without any replacement.
|
||||
|
||||
In your application, replace combined observations with a single observation:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
let playerCountObservation = ValueObservation.tracking(Player.fetchCount)
|
||||
let bestPlayersObservation = ValueObservation.tracking(Player
|
||||
.limit(10)
|
||||
.order(Column("score").desc)
|
||||
.fetchAll)
|
||||
let observation = ValueObservation
|
||||
.combine(playerCountObservation, bestPlayersObservation)
|
||||
.map(HallOfFame.init)
|
||||
|
||||
// NEW: GRDB 5
|
||||
let observation = ValueObservation.tracking { db -> HallOfFame in
|
||||
let playerCount = try Player.fetchCount(db)
|
||||
let bestPlayers = try Player
|
||||
.limit(10)
|
||||
.order(Column("score").desc)
|
||||
.fetchAll(db)
|
||||
return HallOfFame(playerCount: playerCount, bestPlayers: bestPlayers)
|
||||
}
|
||||
```
|
||||
|
||||
As is previous versions of GRDB, do not use the `combineLatest` operators of Combine or RxSwift in order to combine several ValueObservation. You would lose all guarantees of [data consistency](https://en.wikipedia.org/wiki/Consistency_(database_systems)).
|
||||
|
||||
|
||||
## Other Changes
|
||||
|
||||
1. [Batch updates] used to rely of the `<-` operator. This operator has been removed. Use the `set(to:)` method instead:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
try Player.updateAll(db, Column("score") <- 0)
|
||||
|
||||
// NEW: GRDB 5
|
||||
try Player.updateAll(db, Column("score").set(to: 0))
|
||||
```
|
||||
|
||||
2. [Custom SQL functions] are now [callable values](https://github.com/apple/swift-evolution/blob/master/proposals/0253-callable.md):
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
Player.select(myFunction.call(Column("name")))
|
||||
|
||||
// NEW: GRDB 5
|
||||
Player.select(myFunction(Column("name")))
|
||||
```
|
||||
|
||||
3. If you happen to implement custom fetch requests with the `FetchRequest` protocol, you now have to define the `makePreparedRequest(_:forSingleResult:)` method:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
struct MyRequest: FetchRequest {
|
||||
func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) {
|
||||
let statement: SelectStatement = ...
|
||||
let adapter: RowAdapter? = ...
|
||||
return (statement, adapter)
|
||||
}
|
||||
}
|
||||
|
||||
// NEW: GRDB 5
|
||||
struct MyRequest: FetchRequest {
|
||||
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
|
||||
let statement: SelectStatement = ...
|
||||
let adapter: RowAdapter? = ...
|
||||
return PreparedRequest(statement: statement, adapter: adapter)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
4. The module name for [custom SQLite builds](CustomSQLiteBuilds.md) is now the plain `GRDB`:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
import GRDBCustomSQLite
|
||||
|
||||
// NEW: GRDB 5
|
||||
import GRDB
|
||||
```
|
||||
|
||||
5. Importing the `GRDB` module grants access to the [SQLite C interface](https://www.sqlite.org/c3ref/intro.html). You don't need any longer to import the underlying SQLite library:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
import CSQLite // When GRDB is included with the Swift Package Manager
|
||||
import SQLCipher // When GRDB is linked to SQLCipher
|
||||
import SQLite3 // When GRDB is linked to System SQLite
|
||||
let sqliteVersion = String(cString: sqlite3_libversion())
|
||||
|
||||
// NEW: GRDB 5
|
||||
import GRDB
|
||||
let sqliteVersion = String(cString: sqlite3_libversion())
|
||||
```
|
||||
|
||||
|
||||
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
|
||||
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
|
||||
[GRDBCombine]: http://github.com/groue/GRDBCombine
|
||||
[Observing a Varying Database Region]: ../README.md#observing-a-varying-database-region
|
||||
[removeDuplicates]: ../README.md#valueobservationremoveduplicates
|
||||
[Custom SQL functions]: ../README.md#custom-sql-functions
|
||||
[Batch updates]: ../README.md#update-requests
|
||||
@@ -197,7 +197,7 @@ extension DerivableRequest where RowDecoder == Author {
|
||||
|
||||
/// Returns a request for all authors from a country
|
||||
func filter(country: String) -> Self {
|
||||
return filter(Author.Columns.country == country)
|
||||
filter(Author.Columns.country == country)
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -230,8 +230,8 @@ extension DerivableRequest where RowDecoder == Book {
|
||||
func filter(authorCountry: String) -> Self {
|
||||
// A book is from a country if it can be
|
||||
// joined with an author from that country:
|
||||
// ---------------------------------v
|
||||
return joining(required: Book.author.filter(country: authorCountry))
|
||||
// ---------------------------v
|
||||
joining(required: Book.author.filter(country: authorCountry))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -249,7 +249,7 @@ Not *every requests* can be expressed on `DerivableRequest`. For example, [Assoc
|
||||
extension QueryInterfaceRequest where RowDecoder == Author {
|
||||
/// Returns a request for all authors with at least one book
|
||||
func havingBooks() -> QueryInterfaceRequest<Author> {
|
||||
return having(Author.books.isEmpty == false)
|
||||
having(Author.books.isEmpty == false)
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -388,14 +388,14 @@ A last extension on your record types will further help navigation from records
|
||||
extension Author {
|
||||
/// The request for the author's books
|
||||
var books: QueryInterfaceRequest<Book> {
|
||||
return request(for: Author.books)
|
||||
request(for: Author.books)
|
||||
}
|
||||
}
|
||||
|
||||
extension Book {
|
||||
/// The request for the author of the book
|
||||
var author: QueryInterfaceRequest<Author> {
|
||||
return request(for: Book.author)
|
||||
request(for: Book.author)
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -530,19 +530,19 @@ class ImprovedLibraryManager {
|
||||
}
|
||||
|
||||
func author(id: Int64) throws -> Author? {
|
||||
return try dbQueue.read { db in
|
||||
try dbQueue.read { db in
|
||||
try Author.fetchOne(db, key: id)
|
||||
}
|
||||
}
|
||||
|
||||
func book(id: Int64) throws -> Book? {
|
||||
return try dbQueue.read { db in
|
||||
try dbQueue.read { db in
|
||||
try Book.fetchOne(db, key: id)
|
||||
}
|
||||
}
|
||||
|
||||
func books(writtenBy author: Author) throws -> [Book] {
|
||||
return try dbQueue.read { db in
|
||||
try dbQueue.read { db in
|
||||
try author.books.fetchAll(db)
|
||||
}
|
||||
}
|
||||
@@ -593,7 +593,7 @@ extension LibraryManager {
|
||||
}
|
||||
|
||||
func authorList() throws -> [AuthorListItem] {
|
||||
return try dbQueue.read { db in
|
||||
try dbQueue.read { db in
|
||||
let request = Author
|
||||
.annotated(with: Author.books.count)
|
||||
.orderByName()
|
||||
@@ -610,7 +610,7 @@ extension LibraryManager {
|
||||
}
|
||||
|
||||
func bookInfo(bookId: Int64) throws -> BookInfo? {
|
||||
return try dbQueue.read { db in
|
||||
try dbQueue.read { db in
|
||||
guard let book = try Book.fetchOne(db, key: bookId) else {
|
||||
return nil
|
||||
}
|
||||
@@ -630,7 +630,7 @@ extension LibraryManager {
|
||||
}
|
||||
|
||||
func authorInfo(authorId: Int64) throws -> AuthorInfo? {
|
||||
return try dbQueue.read { db in
|
||||
try dbQueue.read { db in
|
||||
guard let author = try Author.fetchOne(db, key: authorId) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -61,16 +61,12 @@ struct Book: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
|
||||
extension Author {
|
||||
static let books = hasMany(Book.self)
|
||||
var books: QueryInterfaceRequest<Book> {
|
||||
return request(for: Author.books)
|
||||
}
|
||||
var books: QueryInterfaceRequest<Book> { request(for: Author.books) }
|
||||
}
|
||||
|
||||
extension Book {
|
||||
static let author = belongsTo(Author.self)
|
||||
var author: QueryInterfaceRequest<Author> {
|
||||
return request(for: Book.author)
|
||||
}
|
||||
var author: QueryInterfaceRequest<Author> { request(for: Book.author) }
|
||||
}
|
||||
|
||||
//: Populate the database
|
||||
|
||||
@@ -47,13 +47,13 @@ import GRDB
|
||||
//: Everything starts from our class hierarchy:
|
||||
|
||||
class Base {
|
||||
var description: String { return "Base" }
|
||||
var description: String { "Base" }
|
||||
init() { }
|
||||
}
|
||||
|
||||
class Foo: Base {
|
||||
var name: String
|
||||
override var description: String { return "Foo: \(name)" }
|
||||
override var description: String { "Foo: \(name)" }
|
||||
init(name: String) {
|
||||
self.name = name
|
||||
super.init()
|
||||
@@ -62,7 +62,7 @@ class Foo: Base {
|
||||
|
||||
class Bar: Base {
|
||||
var score: Int
|
||||
override var description: String { return "Bar: \(score)" }
|
||||
override var description: String { "Bar: \(score)" }
|
||||
init(score: Int) {
|
||||
self.score = score
|
||||
super.init()
|
||||
@@ -302,15 +302,15 @@ extension FetchRequest where RowDecoder: MyDatabaseDecoder {
|
||||
// MARK: - FetchRequest fetching methods
|
||||
|
||||
func fetchCursor(_ db: Database) throws -> MapCursor<RowCursor, RowDecoder.DecodedType> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
func fetchAll(_ db: Database) throws -> [RowDecoder.DecodedType] {
|
||||
return try RowDecoder.fetchAll(db, self)
|
||||
try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
func fetchOne(_ db: Database) throws -> RowDecoder.DecodedType? {
|
||||
return try RowDecoder.fetchOne(db, self)
|
||||
try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -335,15 +335,15 @@ extension MyDatabaseDecoder where Self: TableRecord {
|
||||
// MARK: - Static fetching methods
|
||||
|
||||
static func fetchCursor(_ db: Database) throws -> MapCursor<RowCursor, DecodedType> {
|
||||
return try all().fetchCursor(db)
|
||||
try all().fetchCursor(db)
|
||||
}
|
||||
|
||||
static func fetchAll(_ db: Database) throws -> [DecodedType] {
|
||||
return try all().fetchAll(db)
|
||||
try all().fetchAll(db)
|
||||
}
|
||||
|
||||
static func fetchOne(_ db: Database) throws -> DecodedType? {
|
||||
return try all().fetchOne(db)
|
||||
try all().fetchOne(db)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -366,15 +366,15 @@ extension MyDatabaseDecoder {
|
||||
// MARK: - Fetch from SQL
|
||||
|
||||
static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
|
||||
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [DecodedType] {
|
||||
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DecodedType? {
|
||||
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -79,7 +79,7 @@ class TestDeleteAll: NSObject {
|
||||
struct MyRecord: FetchableRecord, TableRecord, PersistableRecord {
|
||||
|
||||
static let MyColumn = Column("MyColumn")
|
||||
static var databaseTableName: String { return String(describing: self) }
|
||||
static var databaseTableName: String { String(describing: self) }
|
||||
|
||||
let myColumn: String
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ try dbQueue.inDatabase { db in
|
||||
}
|
||||
|
||||
|
||||
// Define the Player `Codable` that is a `FetchableRecord` and `MutablePersistableRecord`.
|
||||
// Define the Player codable record type
|
||||
struct Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
var id: Int64
|
||||
var name: String
|
||||
@@ -54,40 +54,33 @@ struct Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
}
|
||||
}
|
||||
|
||||
extension Player {
|
||||
static func orderedById() -> QueryInterfaceRequest<Player> {
|
||||
return order(Columns.id)
|
||||
}
|
||||
}
|
||||
|
||||
// This is just the container of our incoming JSON
|
||||
struct PlayersToSync: Codable {
|
||||
let players: [Player]
|
||||
}
|
||||
// Make Player identifiable
|
||||
extension Player: Identifiable { }
|
||||
|
||||
// Synchronizes the players table with a JSON payload
|
||||
func synchronizePlayers(with jsonString: String, in db: Database) throws {
|
||||
struct SyncData: Decodable {
|
||||
let players: [Player]
|
||||
}
|
||||
let jsonData = jsonString.data(using: .utf8)!
|
||||
let dataToSync = try JSONDecoder().decode(PlayersToSync.self, from: jsonData)
|
||||
let syncData = try JSONDecoder().decode(SyncData.self, from: jsonData)
|
||||
|
||||
// Sort new players to sync by id:
|
||||
let playersToSync = dataToSync.players.sorted { $0.id < $1.id }
|
||||
// Sort players to sync by id:
|
||||
let playersToSync = syncData.players.sorted { $0.id < $1.id }
|
||||
|
||||
// Sort database players by id:
|
||||
let players = try Player.orderedById().fetchAll(db)
|
||||
let players = try Player.orderByPrimaryKey().fetchAll(db)
|
||||
|
||||
// Now that both lists are sorted by id, we can compare them with
|
||||
// the sortedMerge() function (see https://gist.github.com/groue/7e8510849ded36f7d770).
|
||||
// SortedDifference (see https://github.com/groue/SortedDifference).
|
||||
//
|
||||
// We'll delete, insert or update players, depending on their presence
|
||||
// in either lists.
|
||||
for mergeStep in sortedMerge(
|
||||
for change in SortedDifference(
|
||||
left: players, // Database players
|
||||
right: playersToSync, // PlayersToSync players (Decoded)
|
||||
leftKey: { $0.id }, // The id of a database player
|
||||
rightKey: { $0.id }) // The id of a PlayersToSync player
|
||||
right: playersToSync) // PlayersToSync players (Decoded)
|
||||
{
|
||||
switch mergeStep {
|
||||
switch change {
|
||||
case .left(let player):
|
||||
// Delete database player without matching JSON player:
|
||||
try player.delete(db)
|
||||
@@ -140,3 +133,20 @@ do {
|
||||
try synchronizePlayers(with: jsonString2, in: db)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let jsonString3 = """
|
||||
{
|
||||
"players": [
|
||||
{ "id": 2, "name": "Barbara", "score": 3000},
|
||||
{ "id": 3, "name": "Craig", "score": 500},
|
||||
{ "id": 4, "name": "Daniel", "score": 1500},
|
||||
]
|
||||
}
|
||||
"""
|
||||
print("---\nImport \(jsonString3)")
|
||||
try dbQueue.inDatabase { db in
|
||||
// SELECT * FROM player ORDER BY id
|
||||
try synchronizePlayers(with: jsonString3, in: db)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
// Copyright (C) 2020 Gwendal Roué
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a
|
||||
// copy of this software and associated documentation files (the
|
||||
// "Software"), to deal in the Software without restriction, including
|
||||
// without limitation the rights to use, copy, modify, merge, publish,
|
||||
// distribute, sublicense, and/or sell copies of the Software, and to
|
||||
// permit persons to whom the Software is furnished to do so, subject to
|
||||
// the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included
|
||||
// in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
||||
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
/// Given two sequences (left and right), this sequence tells whether elements
|
||||
/// are only found on the left, on the right, or on both sides.
|
||||
public struct SortedDifference<LeftSequence, RightSequence, ID>: Sequence where
|
||||
LeftSequence: Sequence,
|
||||
RightSequence: Sequence,
|
||||
ID: Comparable
|
||||
{
|
||||
private let left: LeftSequence
|
||||
private let right: RightSequence
|
||||
private let lID: (LeftSequence.Element) -> ID
|
||||
private let rID: (RightSequence.Element) -> ID
|
||||
|
||||
/// Given two sequences (left and right), returns a sequence which tells
|
||||
/// whether elements are only found on the left, on the right, or on
|
||||
/// both sides.
|
||||
///
|
||||
/// Both input sequences do not have to share the same element type, but
|
||||
/// their elements must share a common comparable id.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // Prints:
|
||||
/// // - common(Left(id: 1), Right(id: 1))
|
||||
/// // - left(Left(id: 2))
|
||||
/// struct Left { var id: Int }
|
||||
/// struct Right { var id: Int }
|
||||
/// for change in SortedDifference(
|
||||
/// left: [Left(id: 1), Left(id: 2)],
|
||||
/// identifiedBy: { $0.id },
|
||||
/// right: [Right(id: 1)],
|
||||
/// identifiedBy: { $0.id })
|
||||
/// {
|
||||
/// print(change)
|
||||
/// }
|
||||
///
|
||||
/// - precondition: Both input sequences must be sorted by id.
|
||||
/// - precondition: Ids must be unique in each sequences.
|
||||
/// - parameters:
|
||||
/// - left: The left sequence.
|
||||
/// - right: The right sequence.
|
||||
/// - leftID: A function that returns the id of a left element.
|
||||
/// - rightID: A function that returns the id of a right element.
|
||||
public init(
|
||||
left: LeftSequence,
|
||||
identifiedBy leftID: @escaping (LeftSequence.Element) -> ID,
|
||||
right: RightSequence,
|
||||
identifiedBy rightID: @escaping (RightSequence.Element) -> ID)
|
||||
{
|
||||
self.left = left
|
||||
self.right = right
|
||||
self.lID = leftID
|
||||
self.rID = rightID
|
||||
}
|
||||
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(
|
||||
lIterator: left.makeIterator(),
|
||||
rIterator: right.makeIterator(),
|
||||
lID: lID,
|
||||
rID: rID)
|
||||
}
|
||||
|
||||
public struct Iterator: IteratorProtocol {
|
||||
private var lIterator: LeftSequence.Iterator
|
||||
private var rIterator: RightSequence.Iterator
|
||||
private var lOpt: LeftSequence.Element?
|
||||
private var rOpt: RightSequence.Element?
|
||||
private let lID: (LeftSequence.Element) -> ID
|
||||
private let rID: (RightSequence.Element) -> ID
|
||||
|
||||
init(
|
||||
lIterator: LeftSequence.Iterator,
|
||||
rIterator: RightSequence.Iterator,
|
||||
lID: @escaping (LeftSequence.Element) -> ID,
|
||||
rID: @escaping (RightSequence.Element) -> ID)
|
||||
{
|
||||
self.lIterator = lIterator
|
||||
self.rIterator = rIterator
|
||||
self.lID = lID
|
||||
self.rID = rID
|
||||
self.lOpt = self.lIterator.next()
|
||||
self.rOpt = self.rIterator.next()
|
||||
}
|
||||
|
||||
public mutating func next() -> SortedDifferenceChange<LeftSequence.Element, RightSequence.Element>? {
|
||||
switch (lOpt, rOpt) {
|
||||
case let (lElem?, rElem?):
|
||||
let (lID, rID) = (self.lID(lElem), self.rID(rElem))
|
||||
if lID > rID {
|
||||
rOpt = rIterator.next()
|
||||
return .right(rElem)
|
||||
} else if lID == rID {
|
||||
(lOpt, rOpt) = (lIterator.next(), rIterator.next())
|
||||
return .common(lElem, rElem)
|
||||
} else {
|
||||
lOpt = lIterator.next()
|
||||
return .left(lElem)
|
||||
}
|
||||
case let (nil, rElem?):
|
||||
rOpt = rIterator.next()
|
||||
return .right(rElem)
|
||||
case let (lElem?, nil):
|
||||
lOpt = lIterator.next()
|
||||
return .left(lElem)
|
||||
case (nil, nil):
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
extension SortedDifference where
|
||||
LeftSequence.Element: Identifiable,
|
||||
RightSequence.Element: Identifiable,
|
||||
LeftSequence.Element.ID == ID,
|
||||
RightSequence.Element.ID == ID
|
||||
{
|
||||
/// Given two sequences (left and right), returns a sequence which tells
|
||||
/// whether elements are only found on the left, on the right, or on
|
||||
/// both sides.
|
||||
///
|
||||
/// Both input sequences do not have to share the same element type, but
|
||||
/// their elements must share a common comparable id.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // Prints:
|
||||
/// // - common(Left(id: 1), Right(id: 1))
|
||||
/// // - left(Left(id: 2))
|
||||
/// struct Left: Identifiable { var id: Int }
|
||||
/// struct Right: Identifiable { var id: Int }
|
||||
/// for change in SortedDifference(
|
||||
/// left: [Left(id: 1), Left(id: 2)],
|
||||
/// right: [Right(id: 1)])
|
||||
/// {
|
||||
/// print(change)
|
||||
/// }
|
||||
///
|
||||
/// - precondition: Both input sequences must be sorted by id.
|
||||
/// - precondition: Ids must be unique in each sequences.
|
||||
/// - parameters:
|
||||
/// - left: The left sequence.
|
||||
/// - right: The right sequence.
|
||||
public init(left: LeftSequence, right: RightSequence) {
|
||||
self.init(
|
||||
left: left,
|
||||
identifiedBy: { $0.id },
|
||||
right: right,
|
||||
identifiedBy: { $0.id })
|
||||
}
|
||||
}
|
||||
|
||||
extension SortedDifference where
|
||||
LeftSequence.Element: Comparable,
|
||||
RightSequence.Element == LeftSequence.Element,
|
||||
LeftSequence.Element == ID
|
||||
{
|
||||
/// Given two sequences (left and right), this sequence tells whether
|
||||
/// elements are only found on the left, on the right, or on both sides.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // Prints:
|
||||
/// // - common(1, 1)
|
||||
/// // - left(2)
|
||||
/// for change in SortedDifference(left: [1, 2], right: [1]) {
|
||||
/// print(change)
|
||||
/// }
|
||||
///
|
||||
/// - precondition: Both input sequences must be sorted.
|
||||
/// - precondition: Both input sequences must contain unique elements.
|
||||
/// - parameters:
|
||||
/// - left: The left sequence.
|
||||
/// - right: The right sequence.
|
||||
public init(left: LeftSequence, right: RightSequence) {
|
||||
self.init(
|
||||
left: left,
|
||||
identifiedBy: { $0 },
|
||||
right: right,
|
||||
identifiedBy: { $0 })
|
||||
}
|
||||
}
|
||||
|
||||
/// An element of the SortedDifference sequence.
|
||||
public enum SortedDifferenceChange<Left, Right> {
|
||||
/// An element only found in the left sequence
|
||||
case left(Left)
|
||||
/// An element only found in the right sequence
|
||||
case right(Right)
|
||||
/// Left and right elements share a common id
|
||||
case common(Left, Right)
|
||||
}
|
||||
|
||||
extension SortedDifferenceChange: CustomStringConvertible {
|
||||
public var description: String {
|
||||
switch self {
|
||||
case let .left(lhs):
|
||||
return "left(\(String(describing: lhs)))"
|
||||
case let .right(rhs):
|
||||
return "right(\(String(describing: rhs)))"
|
||||
case let .common(lhs, rhs):
|
||||
return "common(\(String(describing: lhs)), \(String(describing: rhs)))"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SortedDifferenceChange: CustomDebugStringConvertible {
|
||||
public var debugDescription: String {
|
||||
switch self {
|
||||
case let .left(lhs):
|
||||
return "left(\(String(reflecting: lhs)))"
|
||||
case let .right(rhs):
|
||||
return "right(\(String(reflecting: rhs)))"
|
||||
case let .common(lhs, rhs):
|
||||
return "common(\(String(reflecting: lhs)), \(String(reflecting: rhs)))"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SortedDifferenceChange: Equatable where
|
||||
Left: Equatable,
|
||||
Right: Equatable
|
||||
{ }
|
||||
@@ -1,88 +0,0 @@
|
||||
/// Given two sorted sequences (left and right), this function emits "merge steps"
|
||||
/// which tell whether elements are only found on the left, on the right, or on
|
||||
/// both sides.
|
||||
///
|
||||
/// Both sequences do not have to share the same element type. Yet elements must
|
||||
/// share a common comparable *key*.
|
||||
///
|
||||
/// Both sequences must be sorted by this key.
|
||||
///
|
||||
/// Keys must be unique in both sequences.
|
||||
///
|
||||
/// The example below compare two sequences sorted by integer representation,
|
||||
/// and prints:
|
||||
///
|
||||
/// - Left: 1
|
||||
/// - Common: 2, 2
|
||||
/// - Common: 3, 3
|
||||
/// - Right: 4
|
||||
///
|
||||
/// for mergeStep in sortedMerge(
|
||||
/// left: [1,2,3],
|
||||
/// right: ["2", "3", "4"],
|
||||
/// leftKey: { $0 },
|
||||
/// rightKey: { Int($0)! })
|
||||
/// {
|
||||
/// switch mergeStep {
|
||||
/// case .left(let left):
|
||||
/// print("- Left: \(left)")
|
||||
/// case .right(let right):
|
||||
/// print("- Right: \(right)")
|
||||
/// case .common(let left, let right):
|
||||
/// print("- Common: \(left), \(right)")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// - parameters:
|
||||
/// - left: The left sequence.
|
||||
/// - right: The right sequence.
|
||||
/// - leftKey: A function that returns the key of a left element.
|
||||
/// - rightKey: A function that returns the key of a right element.
|
||||
/// - returns: A sequence of MergeStep
|
||||
public func sortedMerge<LeftSequence: Sequence, RightSequence: Sequence, Key: Comparable>(
|
||||
left lSeq: LeftSequence,
|
||||
right rSeq: RightSequence,
|
||||
leftKey: @escaping (LeftSequence.Element) -> Key,
|
||||
rightKey: @escaping (RightSequence.Element) -> Key) -> AnySequence<MergeStep<LeftSequence.Element, RightSequence.Element>>
|
||||
{
|
||||
return AnySequence { () -> AnyIterator<MergeStep<LeftSequence.Element, RightSequence.Element>> in
|
||||
var (lGen, rGen) = (lSeq.makeIterator(), rSeq.makeIterator())
|
||||
var (lOpt, rOpt) = (lGen.next(), rGen.next())
|
||||
return AnyIterator {
|
||||
switch (lOpt, rOpt) {
|
||||
case (let lElem?, let rElem?):
|
||||
let (lKey, rKey) = (leftKey(lElem), rightKey(rElem))
|
||||
if lKey > rKey {
|
||||
rOpt = rGen.next()
|
||||
return .right(rElem)
|
||||
} else if lKey == rKey {
|
||||
(lOpt, rOpt) = (lGen.next(), rGen.next())
|
||||
return .common(lElem, rElem)
|
||||
} else {
|
||||
lOpt = lGen.next()
|
||||
return .left(lElem)
|
||||
}
|
||||
case (nil, let rElem?):
|
||||
rOpt = rGen.next()
|
||||
return .right(rElem)
|
||||
case (let lElem?, nil):
|
||||
lOpt = lGen.next()
|
||||
return .left(lElem)
|
||||
case (nil, nil):
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Support for sortedMerge()
|
||||
*/
|
||||
public enum MergeStep<LeftElement, RightElement> {
|
||||
/// An element only found in the left sequence:
|
||||
case left(LeftElement)
|
||||
/// An element only found in the right sequence:
|
||||
case right(RightElement)
|
||||
/// Left and right elements share a common key:
|
||||
case common(LeftElement, RightElement)
|
||||
}
|
||||
@@ -34,9 +34,7 @@ try! migrator.migrate(dbQueue)
|
||||
class TableChangeObserver : NSObject, TransactionObserver {
|
||||
private var changedTableNames: Set<String> = []
|
||||
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
return true
|
||||
}
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { true }
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
changedTableNames.insert(event.tableName)
|
||||
|
||||
@@ -22,6 +22,7 @@ SQL Interpolation is an answer to these troubles. It is available in Swift 5.
|
||||
|
||||
- [Introduction]
|
||||
- [SQLLiteral]
|
||||
- [SQL Interpolation and the Query Interface]
|
||||
- [SQL Interpolation and Record Protocols]
|
||||
- [SQL Interpolation Reference]
|
||||
|
||||
@@ -127,6 +128,39 @@ let query = SQLLiteral(
|
||||
SQLLiteral can embed any [value], as we have seen above, but not only. Please keep on reading the next chapter, or jump directly to the [SQL Interpolation Reference].
|
||||
|
||||
|
||||
## SQL Interpolation and the Query Interface
|
||||
|
||||
SQL Interpolation and SQLLiteral let you embed raw SQL snippets in [query interface requests].
|
||||
|
||||
For example:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player WHERE name = 'O''Brien'
|
||||
let request = Player.filter(literal: "name = \("O'Brien")")
|
||||
```
|
||||
|
||||
You can also build literal expressions from other expressions. For example, let's call the `DATE` SQLite function on a query interface column:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23'
|
||||
let createdAt = Column("createdAt")
|
||||
let creationDay = SQLLiteral("DATE(\(createdAt))").sqlExpression
|
||||
let request = Player.filter(creationDay == "2020-01-23")
|
||||
```
|
||||
|
||||
Such literal expressions can be returned by Swift functions:
|
||||
|
||||
```swift
|
||||
func date(_ value: SQLExpressible) -> SQLExpression {
|
||||
SQLLiteral("DATE(\(value))").sqlExpression
|
||||
}
|
||||
|
||||
// SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23'
|
||||
let createdAt = Column("createdAt")
|
||||
let request = Player.filter(date(createdAt) == "2020-01-23")
|
||||
```
|
||||
|
||||
|
||||
## SQL Interpolation and Record Protocols
|
||||
|
||||
The [record protocols] extend your application types with database abilities.
|
||||
@@ -150,25 +184,25 @@ extension Player: Decodable, FetchableRecord, TableRecord {
|
||||
|
||||
/// The player with a given id
|
||||
static func filter(id: Int64) -> SQLRequest<Player> {
|
||||
return "SELECT * FROM \(self) WHERE \(CodingKeys.id) = \(id)"
|
||||
"SELECT * FROM \(self) WHERE \(CodingKeys.id) = \(id)"
|
||||
}
|
||||
|
||||
/// All players with the given ids
|
||||
static func filter(ids: [Int64]) -> SQLRequest<Player> {
|
||||
return "SELECT * FROM \(self) WHERE \(CodingKeys.id) IN \(ids)"
|
||||
"SELECT * FROM \(self) WHERE \(CodingKeys.id) IN \(ids)"
|
||||
}
|
||||
|
||||
/// The maximum score
|
||||
static func maximumScore() -> SQLRequest<Int> {
|
||||
return "SELECT MAX(\(CodingKeys.score)) FROM \(self)"
|
||||
"SELECT MAX(\(CodingKeys.score)) FROM \(self)"
|
||||
}
|
||||
|
||||
/// All players whose score is the maximum score
|
||||
static func leaders() -> SQLRequest<Player> {
|
||||
return """
|
||||
SELECT * FROM \(self)
|
||||
WHERE \(CodingKeys.score) = \(maximumScore())
|
||||
"""
|
||||
"""
|
||||
SELECT * FROM \(self)
|
||||
WHERE \(CodingKeys.score) = \(maximumScore())
|
||||
"""
|
||||
}
|
||||
|
||||
/// A complex request
|
||||
@@ -213,7 +247,7 @@ Let's breakdown each one of those methods.
|
||||
extension Player: Decodable, FetchableRecord, TableRecord {
|
||||
/// The player with a given id
|
||||
static func filter(id: Int64) -> SQLRequest<Player> {
|
||||
return "SELECT * FROM \(self) WHERE \(CodingKeys.id) = \(id)"
|
||||
"SELECT * FROM \(self) WHERE \(CodingKeys.id) = \(id)"
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -237,7 +271,7 @@ Let's breakdown each one of those methods.
|
||||
extension Player: Decodable, FetchableRecord, TableRecord {
|
||||
/// All players with the given ids
|
||||
static func filter(ids: [Int64]) -> SQLRequest<Player> {
|
||||
return "SELECT * FROM \(self) WHERE \(CodingKeys.id) IN \(ids)"
|
||||
"SELECT * FROM \(self) WHERE \(CodingKeys.id) IN \(ids)"
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -259,7 +293,7 @@ Let's breakdown each one of those methods.
|
||||
extension Player: Decodable, FetchableRecord, TableRecord {
|
||||
/// The maximum score
|
||||
static func maximumScore() -> SQLRequest<Int> {
|
||||
return "SELECT MAX(\(CodingKeys.score)) FROM \(self)"
|
||||
"SELECT MAX(\(CodingKeys.score)) FROM \(self)"
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -281,10 +315,10 @@ Let's breakdown each one of those methods.
|
||||
extension Player: Decodable, FetchableRecord, TableRecord {
|
||||
/// All players whose score is the maximum score
|
||||
static func leaders() -> SQLRequest<Player> {
|
||||
return """
|
||||
SELECT * FROM \(self)
|
||||
WHERE \(CodingKeys.score) = \(maximumScore())
|
||||
"""
|
||||
"""
|
||||
SELECT * FROM \(self)
|
||||
WHERE \(CodingKeys.score) = \(maximumScore())
|
||||
"""
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -399,6 +433,7 @@ This chapter lists all kinds of supported interpolations.
|
||||
|
||||
[Introduction]: #introduction
|
||||
[SQLLiteral]: #sqlliteral
|
||||
[SQL Interpolation and the Query Interface]: #sql-interpolation-and-the-query-interface
|
||||
[SQL Interpolation and Record Protocols]: #sql-interpolation-and-record-protocols
|
||||
[SQL Interpolation Reference]: #sql-interpolation-reference
|
||||
[String interpolation]: https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html#ID292
|
||||
@@ -415,4 +450,5 @@ This chapter lists all kinds of supported interpolations.
|
||||
[record]: ../README.md#records
|
||||
[Expressions]: ../README.md#expressions
|
||||
[welcomed]: ../README.md#sqlite-api
|
||||
[query interface requests]: ../README.md#requests
|
||||
[SE-0228 Fix ExpressibleByStringInterpolation]: https://github.com/apple/swift-evolution/blob/master/proposals/0228-fix-expressiblebystringinterpolation.md
|
||||
@@ -115,25 +115,41 @@ 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.
|
||||
**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, or by observing database changes and react accordingly.
|
||||
|
||||
There are several ways to be notified of database changes. You can build on top of the fundamental but low-level [TransactionObserver] protocol. Usually, you'll use [ValueObservation], which notifies fresh values after each database change. And don't forget [GRDBCombine] and [RxGRDB], two sets of reactive extensions based on [Combine] and [RxSwift]:
|
||||
In order to keep your views synchronized with the database content, you can use [ValueObservation]. It notifies fresh values after each database change. The [GRDBCombine] and [RxGRDB] companion libraries provide support for [Combine] and [RxSwift].
|
||||
|
||||
```swift
|
||||
Player.all().rx
|
||||
.fetchAll(in: dbQueue)
|
||||
.subscribe(onNext: { players: [Player] in
|
||||
print("Players have changed")
|
||||
})
|
||||
/// An observation of [Player]
|
||||
let observation = ValueObservation.tracking { db in
|
||||
try Player.fetchAll(db)
|
||||
}
|
||||
|
||||
// Vanilla GRDB
|
||||
let cancellable = observation.start(in: dbQueue,
|
||||
onError: { error in ... },
|
||||
onChange: { (players: [Player]) in print("Fresh players") })
|
||||
|
||||
// GRDBCombine
|
||||
let cancellable = observation.publisher(in: dbQueue).sink(
|
||||
receiveCompletion: { completion in ... },
|
||||
receiveValue: { (players: [Player]) in print("Fresh players") })
|
||||
|
||||
// RxGRDB
|
||||
let disposable = observation.rx.observe(in: dbQueue).subscribe(
|
||||
onNext: { (players: [Player]) in print("Fresh playerss") },
|
||||
onError: { error in ... })
|
||||
```
|
||||
|
||||
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.
|
||||
Next, you choose the dispatch queue on which notifications happen (generally the main queue, by default, as in the examples above). 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. GRDB roots its notification system in the rock-solid SQLite itself, so that high-level requests and raw SQL queries are equally supported.
|
||||
Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, or SQL triggers. GRDB roots its notification system in the rock-solid SQLite itself, so that high-level requests and raw SQL queries are equally supported.
|
||||
|
||||
See [Database Observation](../README.md#database-changes-observation) for further information.
|
||||
|
||||
|
||||
### Non-blocking database reads
|
||||
@@ -231,7 +247,7 @@ try db.execute(literal: "UPDATE player SET score = \(score) WHERE id = \(id)")
|
||||
|
||||
extension Player {
|
||||
static func filter(name: String) -> SQLRequest<Player> {
|
||||
return "SELECT * FROM \(self) WHERE \(CodingKeys.name) = \(name)"
|
||||
"SELECT * FROM player WHERE name = \(name)"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,35 +257,20 @@ let player = try Player.filter(name: "Arthur O'Brien").fetchOne(db)
|
||||
Custom SQL requests as the one above are welcome in database observation tools like the built-in [ValueObservation], or the companion libraries [GRDBCombine] and [RxGRDB]:
|
||||
|
||||
```swift
|
||||
// RxGRDB
|
||||
Player.filter(name: "Arthur O'Brien").rx
|
||||
.fetchOne(in: dbQueue)
|
||||
.subscribe(onNext: { (player: Player?) in
|
||||
print("Player has changed")
|
||||
})
|
||||
```
|
||||
let playerObservation = ValueObservation.tracking { db in
|
||||
try Player.filter(name: "Arthur O'Brien").fetchOne(db)
|
||||
}
|
||||
|
||||
Power users can also consume complex joined SQL queries into handy record values, by *adapting* raw database rows to the decoded records (see [Joined Queries Support](#../README.md#joined-queries-support)):
|
||||
|
||||
```swift
|
||||
let bookInfos: [BookInfo] = SQLRequest<BookInfo>(sql: """
|
||||
SELECT book.*, author.*
|
||||
FROM book
|
||||
LEFT JOIN author ON author.id = book.authorId
|
||||
""")
|
||||
.adapted { db in
|
||||
let adapters = try splittingRowAdapters(columnCounts: [
|
||||
db.columns(in: "book").count,
|
||||
db.columns(in: "author").count])
|
||||
return ScopeAdapter([
|
||||
"book": adapters[0],
|
||||
"author": adapters[1]])
|
||||
}
|
||||
// Observe the SQL request with GRDBCombine
|
||||
let cancellable = playerObservation.publisher(in: dbQueue).sink(
|
||||
receiveCompletion: { completion in ... },
|
||||
receiveValue: { (player: Player?) in print("Player has changed") })
|
||||
```
|
||||
|
||||
In performance-critical sections, you may want to deal with raw database rows, and fetch [lazy cursors](../README.md#cursors) instead of arrays:
|
||||
|
||||
```swift
|
||||
// As close to SQLite metal as possible
|
||||
let rows = try Row.fetchCursor(db, sql: "SELECT id, name, score FROM player")
|
||||
while let row = try rows.next() {
|
||||
let id: Int64 = row[0]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '4.6.2'
|
||||
s.version = '4.14.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
@@ -9,9 +9,9 @@ Pod::Spec.new do |s|
|
||||
s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" }
|
||||
s.module_name = 'GRDB'
|
||||
|
||||
s.swift_versions = ['4.2', '5.0']
|
||||
s.swift_versions = ['5.2']
|
||||
s.ios.deployment_target = '9.0'
|
||||
s.osx.deployment_target = '10.9'
|
||||
s.osx.deployment_target = '10.10'
|
||||
s.watchos.deployment_target = '2.0'
|
||||
s.tvos.deployment_target = '9.0'
|
||||
s.default_subspec = 'standard'
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>IDEDidComputeMac32BitWarning</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1030"
|
||||
LastUpgradeVersion = "1130"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -40,8 +40,17 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
codeCoverageEnabled = "YES"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
codeCoverageEnabled = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "DC3773F219C8CBB3004FCF85"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
@@ -77,17 +86,6 @@
|
||||
</SkippedTests>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "DC3773F219C8CBB3004FCF85"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
@@ -108,8 +106,6 @@
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1030"
|
||||
LastUpgradeVersion = "1130"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -29,8 +29,6 @@
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
@@ -51,8 +49,6 @@
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1030"
|
||||
LastUpgradeVersion = "1130"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -26,8 +26,17 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
codeCoverageEnabled = "YES"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
codeCoverageEnabled = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56E5D7C91B4D3FED00430942"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBiOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
@@ -40,17 +49,6 @@
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56E5D7C91B4D3FED00430942"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBiOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
@@ -71,8 +69,6 @@
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1030"
|
||||
LastUpgradeVersion = "1130"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -26,8 +26,17 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
codeCoverageEnabled = "YES"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
codeCoverageEnabled = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBtvOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
@@ -40,17 +49,6 @@
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBtvOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
@@ -71,8 +69,6 @@
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
|
||||
@@ -1,12 +1,5 @@
|
||||
import Foundation
|
||||
import Dispatch
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// Configuration for a DatabaseQueue or DatabasePool.
|
||||
public struct Configuration {
|
||||
@@ -75,21 +68,41 @@ public struct Configuration {
|
||||
/// Default: nil
|
||||
public var trace: TraceFunction?
|
||||
|
||||
// MARK: - Encryption
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
// TODO: remove when the deprecated passphrase turns unavailable.
|
||||
var _passphrase: String?
|
||||
|
||||
/// The passphrase for the encrypted database.
|
||||
/// If false, SQLite from version 3.29.0 will not interpret a double-quoted
|
||||
/// string as a string literal if it does not match any valid identifier.
|
||||
///
|
||||
/// Default: nil
|
||||
@available(*, deprecated, message: "Use Database.usePassphrase(_:) in Configuration.prepareDatabase instead.")
|
||||
public var passphrase: String? {
|
||||
get { return _passphrase }
|
||||
set { _passphrase = newValue }
|
||||
}
|
||||
#endif
|
||||
/// For example:
|
||||
///
|
||||
/// // Error: no such column: foo
|
||||
/// let name = try String.fetchOne(db, sql: """
|
||||
/// SELECT "foo" FROM "player"
|
||||
/// """)
|
||||
///
|
||||
/// When true, or before version 3.29.0, such strings are interpreted as
|
||||
/// string literals, as in the example below. This is a well known SQLite
|
||||
/// [misfeature](https://sqlite.org/quirks.html#dblquote).
|
||||
///
|
||||
/// // Success: "foo"
|
||||
/// let name = try String.fetchOne(db, sql: """
|
||||
/// SELECT "foo" FROM "player"
|
||||
/// """)
|
||||
///
|
||||
/// - Recommended value: false
|
||||
/// - Default value: false
|
||||
public var acceptsDoubleQuotedStringLiterals = false
|
||||
|
||||
/// When true, the `Database.suspendNotification` and
|
||||
/// `Database.resumeNotification` suspend and resume the database. Database
|
||||
/// suspension helps avoiding the [`0xdead10cc`
|
||||
/// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html).
|
||||
///
|
||||
/// During suspension, all database accesses but reads in WAL mode may throw
|
||||
/// a DatabaseError of code `SQLITE_INTERRUPT`, or `SQLITE_ABORT`. You can
|
||||
/// check for those error codes with the
|
||||
/// `DatabaseError.isInterruptionError` property.
|
||||
///
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public var observesSuspensionNotifications = false
|
||||
|
||||
// MARK: - Managing SQLite Connections
|
||||
|
||||
@@ -161,8 +174,8 @@ public struct Configuration {
|
||||
///
|
||||
/// The quality of service is ignored if you supply a target queue.
|
||||
///
|
||||
/// Default: .default (.unspecified on macOS < 10.10)
|
||||
public var qos: DispatchQoS
|
||||
/// Default: .default
|
||||
public var qos: DispatchQoS = .default
|
||||
|
||||
/// The target queue for all database accesses.
|
||||
///
|
||||
@@ -180,14 +193,7 @@ public struct Configuration {
|
||||
// MARK: - Factory Configuration
|
||||
|
||||
/// Creates a factory configuration
|
||||
public init() {
|
||||
if #available(OSX 10.10, *) {
|
||||
qos = .default
|
||||
} else {
|
||||
qos = .unspecified
|
||||
}
|
||||
}
|
||||
|
||||
public init() { }
|
||||
|
||||
// MARK: - Not Public
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ extension Sequence {
|
||||
_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult)
|
||||
-> FlattenCursor<MapCursor<AnyCursor<Iterator.Element>, SegmentOfResult>>
|
||||
{
|
||||
return AnyCursor(self).flatMap(transform)
|
||||
AnyCursor(self).flatMap(transform)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ extension Cursor {
|
||||
/// Returns a Boolean value indicating whether the cursor contains
|
||||
/// an element.
|
||||
public func isEmpty() throws -> Bool {
|
||||
return try next() == nil
|
||||
try next() == nil
|
||||
}
|
||||
|
||||
/// Returns a Boolean value indicating whether the cursor contains an
|
||||
@@ -123,12 +123,12 @@ extension Cursor {
|
||||
/// // Prints: "0: foo"
|
||||
/// // Prints: "1: bar"
|
||||
public func enumerated() -> EnumeratedCursor<Self> {
|
||||
return EnumeratedCursor(self)
|
||||
EnumeratedCursor(self)
|
||||
}
|
||||
|
||||
/// Returns the elements of the cursor that satisfy the given predicate.
|
||||
public func filter(_ isIncluded: @escaping (Element) throws -> Bool) -> FilterCursor<Self> {
|
||||
return FilterCursor(self, isIncluded)
|
||||
FilterCursor(self, isIncluded)
|
||||
}
|
||||
|
||||
/// Returns the first element of the cursor that satisfies the given
|
||||
@@ -147,7 +147,7 @@ extension Cursor {
|
||||
public func compactMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?)
|
||||
-> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult>
|
||||
{
|
||||
return map(transform).filter { $0 != nil }.map { $0! }
|
||||
map(transform).filter { $0 != nil }.map { $0! }
|
||||
}
|
||||
|
||||
/// Returns a cursor that skips any initial elements that satisfy
|
||||
@@ -158,7 +158,7 @@ extension Cursor {
|
||||
/// `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)
|
||||
DropWhileCursor(self, predicate: predicate)
|
||||
}
|
||||
|
||||
/// Returns a cursor containing all but the given number of initial
|
||||
@@ -178,7 +178,7 @@ extension Cursor {
|
||||
/// - Returns: A cursor starting after the specified number of
|
||||
/// elements.
|
||||
public func dropFirst(_ n: Int) -> DropFirstCursor<Self> {
|
||||
return DropFirstCursor(self, limit: n)
|
||||
DropFirstCursor(self, limit: n)
|
||||
}
|
||||
|
||||
/// Returns a cursor containing all but the first element of the cursor.
|
||||
@@ -193,7 +193,7 @@ extension Cursor {
|
||||
///
|
||||
/// - Returns: A cursor starting after the first element of the cursor.
|
||||
public func dropFirst() -> DropFirstCursor<Self> {
|
||||
return dropFirst(1)
|
||||
dropFirst(1)
|
||||
}
|
||||
|
||||
/// Returns an array containing all but the given number of final
|
||||
@@ -243,7 +243,7 @@ extension Cursor {
|
||||
///
|
||||
/// - Returns: An array leaving off the last element of the cursor.
|
||||
public func dropLast() throws -> [Element] {
|
||||
return try dropLast(1)
|
||||
try dropLast(1)
|
||||
}
|
||||
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
@@ -252,7 +252,7 @@ extension Cursor {
|
||||
-> FlattenCursor<MapCursor<Self, AnyCursor<SegmentOfResult.Element>>>
|
||||
where SegmentOfResult: Sequence
|
||||
{
|
||||
return flatMap { try AnyCursor(transform($0)) }
|
||||
flatMap { try AnyCursor(transform($0)) }
|
||||
}
|
||||
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
@@ -261,7 +261,7 @@ extension Cursor {
|
||||
-> FlattenCursor<MapCursor<Self, SegmentOfResult>>
|
||||
where SegmentOfResult: Cursor
|
||||
{
|
||||
return map(transform).joined()
|
||||
map(transform).joined()
|
||||
}
|
||||
|
||||
/// Calls the given closure on each element in the cursor.
|
||||
@@ -274,7 +274,7 @@ extension Cursor {
|
||||
/// Returns a cursor over the results of the transform function applied to
|
||||
/// this cursor's elements.
|
||||
public func map<T>(_ transform: @escaping (Element) throws -> T) -> MapCursor<Self, T> {
|
||||
return MapCursor(self, transform)
|
||||
MapCursor(self, transform)
|
||||
}
|
||||
|
||||
/// Returns the maximum element in the cursor, using the given predicate as
|
||||
@@ -334,7 +334,7 @@ extension Cursor {
|
||||
/// - 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)
|
||||
PrefixCursor(self, maxLength: maxLength)
|
||||
}
|
||||
|
||||
/// Returns a cursor of the initial consecutive elements that satisfy
|
||||
@@ -345,7 +345,7 @@ extension Cursor {
|
||||
/// `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)
|
||||
PrefixWhileCursor(self, predicate: predicate)
|
||||
}
|
||||
|
||||
/// Returns the result of calling the given combining closure with each
|
||||
@@ -448,7 +448,7 @@ extension Cursor where Element: Comparable {
|
||||
/// `areInIncreasingOrder`. If the cursor has no elements, returns
|
||||
/// `nil`.
|
||||
public func max() throws -> Element? {
|
||||
return try max(by: <)
|
||||
try max(by: <)
|
||||
}
|
||||
|
||||
/// Returns the minimum element in the cursor.
|
||||
@@ -460,7 +460,7 @@ extension Cursor where Element: Comparable {
|
||||
/// `areInIncreasingOrder`. If the cursor has no elements, returns
|
||||
/// `nil`.
|
||||
public func min() throws -> Element? {
|
||||
return try min(by: <)
|
||||
try min(by: <)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -469,7 +469,7 @@ extension Cursor where Element: Comparable {
|
||||
extension Cursor where Element: Cursor {
|
||||
/// Returns the elements of this cursor of cursors, concatenated.
|
||||
public func joined() -> FlattenCursor<Self> {
|
||||
return FlattenCursor(self)
|
||||
FlattenCursor(self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -478,7 +478,7 @@ extension Cursor where Element: Cursor {
|
||||
extension Cursor where Element: Sequence {
|
||||
/// Returns the elements of this cursor of sequences, concatenated.
|
||||
public func joined() -> FlattenCursor<MapCursor<Self, AnyCursor<Element.Element>>> {
|
||||
return flatMap { $0 }
|
||||
flatMap { $0 }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -545,7 +545,7 @@ public final class AnyCursor<Element>: Cursor {
|
||||
/// element exists.
|
||||
/// :nodoc:
|
||||
public func next() throws -> Element? {
|
||||
return try element()
|
||||
try element()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,22 +1,7 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Database Schema
|
||||
|
||||
func withSchemaCache<T>(_ schemaCache: DatabaseSchemaCache, _ block: () throws -> T) rethrows -> T {
|
||||
var oldCache = self.schemaCache
|
||||
defer { self.schemaCache = oldCache }
|
||||
self.schemaCache = schemaCache
|
||||
return try block()
|
||||
}
|
||||
|
||||
/// Clears the database schema cache.
|
||||
///
|
||||
/// You may need to clear the cache manually if the database schema is
|
||||
@@ -35,7 +20,7 @@ extension Database {
|
||||
|
||||
/// Returns whether a table exists.
|
||||
public func tableExists(_ name: String) throws -> Bool {
|
||||
return try exists(type: .table, name: name)
|
||||
try exists(type: .table, name: name)
|
||||
}
|
||||
|
||||
/// Returns whether a table is an internal SQLite table.
|
||||
@@ -57,17 +42,17 @@ extension Database {
|
||||
///
|
||||
/// Those are tables whose name begins with "grdb_".
|
||||
public func isGRDBInternalTable(_ tableName: String) -> Bool {
|
||||
return tableName.starts(with: "grdb_")
|
||||
tableName.starts(with: "grdb_")
|
||||
}
|
||||
|
||||
/// Returns whether a view exists.
|
||||
public func viewExists(_ name: String) throws -> Bool {
|
||||
return try exists(type: .view, name: name)
|
||||
try exists(type: .view, name: name)
|
||||
}
|
||||
|
||||
/// Returns whether a trigger exists.
|
||||
public func triggerExists(_ name: String) throws -> Bool {
|
||||
return try exists(type: .trigger, name: name)
|
||||
try exists(type: .trigger, name: name)
|
||||
}
|
||||
|
||||
private func exists(type: SchemaObjectType, name: String) throws -> Bool {
|
||||
@@ -159,7 +144,7 @@ extension Database {
|
||||
}
|
||||
default:
|
||||
// Multi-columns primary key
|
||||
primaryKey = .regular(pkColumns.map { $0.name })
|
||||
primaryKey = .regular(pkColumns.map(\.name))
|
||||
}
|
||||
|
||||
schemaCache.set(primaryKey: primaryKey, forTable: tableName)
|
||||
@@ -187,10 +172,10 @@ extension Database {
|
||||
let unique: Bool = row[2]
|
||||
let columns = try Row
|
||||
.fetchAll(self, sql: "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))")
|
||||
.map { row -> (Int, String) in
|
||||
.map({ row -> (Int, String) in
|
||||
// [seqno:0 cid:2 name:"column"]
|
||||
(row[0] as Int, row[2] as String)
|
||||
}
|
||||
})
|
||||
.sorted { $0.0 < $1.0 }
|
||||
.map { $0.1 }
|
||||
return IndexInfo(name: indexName, columns: columns, unique: unique)
|
||||
@@ -216,7 +201,7 @@ extension Database {
|
||||
throws -> Bool
|
||||
where T.Iterator.Element == String
|
||||
{
|
||||
return try columnsForUniqueKey(Array(columns), in: tableName) != nil
|
||||
try columnsForUniqueKey(Array(columns), in: tableName) != nil
|
||||
}
|
||||
|
||||
/// The foreign keys defined on table named `tableName`.
|
||||
@@ -360,8 +345,14 @@ extension Database {
|
||||
where T.Iterator.Element == String
|
||||
{
|
||||
// Check primaryKey first, so that we fail early if the table does not exist
|
||||
let primaryKey = try self.primaryKey(tableName)
|
||||
let lowercasedColumns = Set(columns.map { $0.lowercased() })
|
||||
|
||||
// Assume "rowid" is a primary key
|
||||
if lowercasedColumns == ["rowid"] {
|
||||
return ["rowid"]
|
||||
}
|
||||
|
||||
let primaryKey = try self.primaryKey(tableName)
|
||||
if Set(primaryKey.columns.map { $0.lowercased() }) == lowercasedColumns {
|
||||
return primaryKey.columns
|
||||
}
|
||||
@@ -532,7 +523,7 @@ public struct PrimaryKeyInfo {
|
||||
private let impl: Impl
|
||||
|
||||
static func rowID(_ column: String) -> PrimaryKeyInfo {
|
||||
return PrimaryKeyInfo(impl: .rowID(column))
|
||||
PrimaryKeyInfo(impl: .rowID(column))
|
||||
}
|
||||
|
||||
static func regular(_ columns: [String]) -> PrimaryKeyInfo {
|
||||
@@ -590,12 +581,12 @@ public struct ForeignKeyInfo {
|
||||
|
||||
/// The origin columns
|
||||
public var originColumns: [String] {
|
||||
return mapping.map { $0.origin }
|
||||
mapping.map(\.origin)
|
||||
}
|
||||
|
||||
/// The destination columns
|
||||
public var destinationColumns: [String] {
|
||||
return mapping.map { $0.destination }
|
||||
mapping.map(\.destination)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -619,7 +610,7 @@ struct SchemaInfo: Equatable {
|
||||
|
||||
/// All names for a given type
|
||||
func names(ofType type: SchemaObjectType) -> Set<String> {
|
||||
return objects.reduce(into: []) { (set, key) in
|
||||
objects.reduce(into: []) { (set, key) in
|
||||
if key.type == type.rawValue {
|
||||
set.insert(key.name)
|
||||
}
|
||||
|
||||
@@ -1,11 +1,4 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
extension Database {
|
||||
|
||||
@@ -21,7 +14,7 @@ extension Database {
|
||||
/// - 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: sql, prepFlags: 0)
|
||||
try makeSelectStatement(sql: sql, prepFlags: 0)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
@@ -36,7 +29,7 @@ extension Database {
|
||||
/// - 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(self, sql: sql, prepFlags: prepFlags)
|
||||
try SelectStatement.prepare(self, sql: sql, prepFlags: prepFlags)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
@@ -52,12 +45,12 @@ extension Database {
|
||||
/// - 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)
|
||||
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)
|
||||
try internalStatementCache.selectStatement(sql)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
@@ -70,7 +63,7 @@ extension Database {
|
||||
/// - 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: sql, prepFlags: 0)
|
||||
try makeUpdateStatement(sql: sql, prepFlags: 0)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
@@ -85,7 +78,7 @@ extension Database {
|
||||
/// - 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(self, sql: sql, prepFlags: prepFlags)
|
||||
try UpdateStatement.prepare(self, sql: sql, prepFlags: prepFlags)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
@@ -101,12 +94,12 @@ extension Database {
|
||||
/// - 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)
|
||||
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)
|
||||
try internalStatementCache.updateStatement(sql)
|
||||
}
|
||||
|
||||
/// Executes one or several SQL statements, separated by semi-colons.
|
||||
@@ -165,12 +158,14 @@ extension Database {
|
||||
//
|
||||
// And before we return, we'll check that all arguments were consumed.
|
||||
|
||||
var arguments = sqlLiteral.arguments
|
||||
var context = SQLGenerationContext.sqlLiteralContext
|
||||
let sql = sqlLiteral.sql(&context)
|
||||
var arguments = context.arguments
|
||||
let initialValuesCount = arguments.values.count
|
||||
|
||||
// Build a C string (SQLite wants that), and execute SQL statements one
|
||||
// after the other.
|
||||
try sqlLiteral.sql.utf8CString.withUnsafeBufferPointer { buffer in
|
||||
try sql.utf8CString.withUnsafeBufferPointer { buffer in
|
||||
guard let sqlStart = buffer.baseAddress else { return }
|
||||
let sqlEnd = sqlStart + buffer.count // past \0
|
||||
var statementStart = sqlStart
|
||||
@@ -199,7 +194,7 @@ extension Database {
|
||||
// Extract statement arguments
|
||||
let bindings = try arguments.extractBindings(forStatement: statement, allowingRemainingValues: true)
|
||||
// unsafe is OK because we just extracted the correct number of arguments
|
||||
statement.unsafeSetArguments(StatementArguments(bindings))
|
||||
statement.setUncheckedArguments(StatementArguments(bindings))
|
||||
|
||||
// Execute
|
||||
try statement.execute()
|
||||
@@ -220,8 +215,16 @@ extension Database {
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
func executeUpdateStatement(_ statement: UpdateStatement) throws {
|
||||
// Two things must prevent the statement from executing: aborted
|
||||
// transactions, and database suspension.
|
||||
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
|
||||
try checkForSuspensionViolation(from: statement)
|
||||
|
||||
if _isRecordingSelectedRegion {
|
||||
_selectedRegion.formUnion(statement.selectedRegion)
|
||||
}
|
||||
|
||||
let authorizer = observationBroker.updateStatementWillExecute(statement)
|
||||
let sqliteStatement = statement.sqliteStatement
|
||||
var code: Int32 = SQLITE_OK
|
||||
@@ -289,24 +292,14 @@ extension Database {
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
func selectStatementWillExecute(_ statement: SelectStatement) {
|
||||
func selectStatementWillExecute(_ statement: SelectStatement) throws {
|
||||
// Two things must prevent the statement from executing: aborted
|
||||
// transactions, and database suspension.
|
||||
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
|
||||
try checkForSuspensionViolation(from: statement)
|
||||
|
||||
if _isRecordingSelectedRegion {
|
||||
// Don't record schema introspection queries, which may be
|
||||
// run, or not, depending on the state of the schema cache.
|
||||
//
|
||||
// This gives us a quick way to make sure that the observation
|
||||
// below, which runs schema introspection queries as a side effect,
|
||||
// only tracks the "player" table:
|
||||
//
|
||||
// let observation = ValueObservation.tracking { db in
|
||||
// try Player.fetchOne(db, key: 1)
|
||||
// }
|
||||
//
|
||||
// Strictly speaking, this prevents the recording of all schema
|
||||
// queries. But we assume, until proven wrong, that such recording
|
||||
// isn't needed by anyone.
|
||||
let region = statement.databaseRegion.ignoringInternalSQLiteTables()
|
||||
_selectedRegion.formUnion(region)
|
||||
_selectedRegion.formUnion(statement.selectedRegion)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,4 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// A raw SQLite connection, suitable for the SQLite C API.
|
||||
public typealias SQLiteConnection = OpaquePointer
|
||||
@@ -126,10 +119,10 @@ public final class Database {
|
||||
lazy var publicStatementCache = StatementCache(database: self)
|
||||
|
||||
/// The last error code
|
||||
public var lastErrorCode: ResultCode { return ResultCode(rawValue: sqlite3_errcode(sqliteConnection)) }
|
||||
public var lastErrorCode: ResultCode { ResultCode(rawValue: sqlite3_errcode(sqliteConnection)) }
|
||||
|
||||
/// The last error message
|
||||
public var lastErrorMessage: String? { return String(cString: sqlite3_errmsg(sqliteConnection)) }
|
||||
public var lastErrorMessage: String? { String(cString: sqlite3_errmsg(sqliteConnection)) }
|
||||
|
||||
/// Statement authorizer. Use withAuthorizer(_:_:).
|
||||
fileprivate var _authorizer: StatementAuthorizer?
|
||||
@@ -146,7 +139,17 @@ public final class Database {
|
||||
/// Use recordingSelectedRegion(_:), see `selectStatementWillExecute(_:)`
|
||||
var _isRecordingSelectedRegion: Bool = false
|
||||
var _selectedRegion = DatabaseRegion()
|
||||
|
||||
|
||||
/// Support for checkForAbortedTransaction()
|
||||
var isInsideTransactionBlock = false
|
||||
|
||||
/// Support for checkForSuspensionViolation(from:)
|
||||
var isSuspended = LockedBox<Bool>(value: false)
|
||||
|
||||
/// Support for checkForSuspensionViolation(from:)
|
||||
/// This cache is never cleared: we assume journal mode never changes.
|
||||
var journalModeCache: String?
|
||||
|
||||
// MARK: - Private properties
|
||||
|
||||
private var busyCallback: BusyCallback?
|
||||
@@ -167,9 +170,6 @@ public final class Database {
|
||||
deinit {
|
||||
assert(isClosed)
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Database Opening
|
||||
|
||||
@@ -195,9 +195,6 @@ extension Database {
|
||||
}
|
||||
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Database Setup
|
||||
|
||||
@@ -205,6 +202,7 @@ extension Database {
|
||||
func setup() throws {
|
||||
// Setup trace first, so that setup queries are traced.
|
||||
setupTrace()
|
||||
setupDoubleQuotedStringLiterals()
|
||||
try setupForeignKeys()
|
||||
setupBusyMode()
|
||||
setupDefaultFunctions()
|
||||
@@ -215,9 +213,6 @@ extension Database {
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
try validateSQLCipher()
|
||||
if let passphrase = configuration._passphrase {
|
||||
try _usePassphrase(passphrase)
|
||||
}
|
||||
#endif
|
||||
|
||||
// Last step before we can start accessing the database.
|
||||
@@ -290,6 +285,14 @@ extension Database {
|
||||
return SQLITE_OK
|
||||
}
|
||||
|
||||
private func setupDoubleQuotedStringLiterals() {
|
||||
if configuration.acceptsDoubleQuotedStringLiterals {
|
||||
enableDoubleQuotedStringLiterals(sqliteConnection)
|
||||
} else {
|
||||
disableDoubleQuotedStringLiterals(sqliteConnection)
|
||||
}
|
||||
}
|
||||
|
||||
private func setupForeignKeys() throws {
|
||||
// Foreign keys are disabled by default with SQLite3
|
||||
if configuration.foreignKeysEnabled {
|
||||
@@ -361,7 +364,7 @@ extension Database {
|
||||
},
|
||||
dbPointer)
|
||||
}
|
||||
|
||||
|
||||
|
||||
private func activateExtendedCodes() throws {
|
||||
let code = sqlite3_extended_result_codes(sqliteConnection, 1)
|
||||
@@ -396,9 +399,6 @@ extension Database {
|
||||
// another passphrase.
|
||||
try makeSelectStatement(sql: "SELECT * FROM sqlite_master LIMIT 1").makeCursor().next()
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Database Closing
|
||||
|
||||
@@ -416,48 +416,6 @@ extension Database {
|
||||
}
|
||||
|
||||
private static func closeConnection(_ sqliteConnection: SQLiteConnection) {
|
||||
// sqlite3_close_v2 was added in SQLite 3.7.14 http://www.sqlite.org/changes.html#version_3_7_14
|
||||
// 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
|
||||
closeConnection_v2(sqliteConnection, sqlite3_close_v2)
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) {
|
||||
closeConnection_v2(sqliteConnection, sqlite3_close_v2)
|
||||
} else {
|
||||
closeConnection_v1(sqliteConnection)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
private static func closeConnection_v1(_ sqliteConnection: SQLiteConnection) {
|
||||
// https://www.sqlite.org/c3ref/close.html
|
||||
// > If the database connection is associated with unfinalized prepared
|
||||
// > statements or unfinished sqlite3_backup objects then
|
||||
// > sqlite3_close() will leave the database connection open and
|
||||
// > return SQLITE_BUSY.
|
||||
let code = sqlite3_close(sqliteConnection)
|
||||
if code != SQLITE_OK, let log = logError {
|
||||
// A rare situation where GRDB doesn't fatalError on
|
||||
// unprocessed errors.
|
||||
let message = String(cString: sqlite3_errmsg(sqliteConnection))
|
||||
log(ResultCode(rawValue: code), "could not close database: \(message)")
|
||||
if code == SQLITE_BUSY {
|
||||
// Let the user know about unfinalized statements that did
|
||||
// prevent the connection from closing properly.
|
||||
var stmt: SQLiteStatement? = sqlite3_next_stmt(sqliteConnection, nil)
|
||||
while stmt != nil {
|
||||
log(ResultCode(rawValue: code), "unfinalized statement: \(String(cString: sqlite3_sql(stmt)))")
|
||||
stmt = sqlite3_next_stmt(sqliteConnection, stmt)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static func closeConnection_v2(
|
||||
_ sqliteConnection: SQLiteConnection,
|
||||
_ sqlite3_close_v2: @convention(c) (OpaquePointer?) -> Int32)
|
||||
{
|
||||
// https://www.sqlite.org/c3ref/close.html
|
||||
// > If sqlite3_close_v2() is called with unfinalized prepared
|
||||
// > statements and/or unfinished sqlite3_backups, then the database
|
||||
@@ -472,9 +430,6 @@ extension Database {
|
||||
log(ResultCode(rawValue: code), "could not close database: \(message)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
@@ -498,9 +453,6 @@ extension Database {
|
||||
functions.remove(function)
|
||||
function.uninstall(in: self)
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
@@ -538,28 +490,21 @@ extension Database {
|
||||
SQLITE_UTF8,
|
||||
nil, nil, nil)
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Read-Only Access
|
||||
|
||||
func beginReadOnly() throws {
|
||||
_readOnlyDepth += 1
|
||||
if _readOnlyDepth == 1 && configuration.readonly == false {
|
||||
// PRAGMA query_only 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 configuration.readonly { return }
|
||||
if _readOnlyDepth == 0 {
|
||||
try internalCachedUpdateStatement(sql: "PRAGMA query_only = 1").execute()
|
||||
}
|
||||
_readOnlyDepth += 1
|
||||
}
|
||||
|
||||
func endReadOnly() throws {
|
||||
if configuration.readonly { return }
|
||||
_readOnlyDepth -= 1
|
||||
if _readOnlyDepth == 0 && configuration.readonly == false {
|
||||
// PRAGMA query_only 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 _readOnlyDepth == 0 {
|
||||
try internalCachedUpdateStatement(sql: "PRAGMA query_only = 0").execute()
|
||||
}
|
||||
}
|
||||
@@ -567,33 +512,10 @@ extension Database {
|
||||
/// Grants read-only access, starting SQLite 3.8.0
|
||||
func readOnly<T>(_ block: () throws -> T) throws -> T {
|
||||
try beginReadOnly()
|
||||
|
||||
var result: T?
|
||||
var thrownError: Error?
|
||||
|
||||
do {
|
||||
result = try block()
|
||||
} catch {
|
||||
thrownError = error
|
||||
}
|
||||
|
||||
do {
|
||||
try endReadOnly()
|
||||
} catch {
|
||||
if thrownError == nil {
|
||||
thrownError = error
|
||||
}
|
||||
}
|
||||
|
||||
if let error = thrownError {
|
||||
throw error
|
||||
}
|
||||
|
||||
return result!
|
||||
return try throwingFirstError(
|
||||
execute: block,
|
||||
finally: endReadOnly)
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Authorizer
|
||||
|
||||
@@ -604,42 +526,206 @@ extension Database {
|
||||
defer { self._authorizer = old }
|
||||
return try block()
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Recording of the selected region
|
||||
|
||||
func recordingSelectedRegion<T>(_ block: () throws -> T) rethrows -> (T, DatabaseRegion) {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
func recordingSelection<T>(_ region: inout DatabaseRegion, _ block: () throws -> T) rethrows -> T {
|
||||
if region.isFullDatabase {
|
||||
return try block()
|
||||
}
|
||||
|
||||
let oldFlag = self._isRecordingSelectedRegion
|
||||
let oldRegion = self._selectedRegion
|
||||
self._isRecordingSelectedRegion = true
|
||||
self._selectedRegion = DatabaseRegion()
|
||||
_isRecordingSelectedRegion = true
|
||||
_selectedRegion = DatabaseRegion()
|
||||
defer {
|
||||
self._isRecordingSelectedRegion = oldFlag
|
||||
if self._isRecordingSelectedRegion {
|
||||
self._selectedRegion = oldRegion.union(self._selectedRegion)
|
||||
region.formUnion(_selectedRegion)
|
||||
_isRecordingSelectedRegion = oldFlag
|
||||
if _isRecordingSelectedRegion {
|
||||
_selectedRegion = oldRegion.union(_selectedRegion)
|
||||
} else {
|
||||
self._selectedRegion = oldRegion
|
||||
_selectedRegion = oldRegion
|
||||
}
|
||||
}
|
||||
return try (block(), _selectedRegion)
|
||||
return try block()
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Checkpoints
|
||||
|
||||
func checkpoint(_ kind: Database.CheckpointMode) throws {
|
||||
let code = sqlite3_wal_checkpoint_v2(sqliteConnection, nil, kind.rawValue, nil, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: lastErrorMessage)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Interrupt
|
||||
|
||||
// See https://www.sqlite.org/c3ref/interrupt.html
|
||||
func interrupt() {
|
||||
sqlite3_interrupt(sqliteConnection)
|
||||
}
|
||||
|
||||
// MARK: - Database Suspension
|
||||
|
||||
/// When this notification is posted, databases which were opened with the
|
||||
/// `Configuration.observesSuspensionNotifications` flag are suspended.
|
||||
///
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public static let suspendNotification = Notification.Name("GRDB.Database.Suspend")
|
||||
|
||||
/// When this notification is posted, databases which were opened with the
|
||||
/// `Configuration.observesSuspensionNotifications` flag are resumed.
|
||||
///
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public static let resumeNotification = Notification.Name("GRDB.Database.Resume")
|
||||
|
||||
/// Suspends the database. A suspended database prevents database locks in
|
||||
/// order to avoid the [`0xdead10cc`
|
||||
/// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html).
|
||||
///
|
||||
/// This method can be called from any thread.
|
||||
///
|
||||
/// During suspension, any lock is released as soon as possible, and
|
||||
/// lock acquisition is prevented. All database accesses may throw a
|
||||
/// DatabaseError of code `SQLITE_INTERRUPT`, or `SQLITE_ABORT`, except
|
||||
/// reads in WAL mode.
|
||||
///
|
||||
/// Suspension ends with resume().
|
||||
func suspend() {
|
||||
isSuspended.write { isSuspended in
|
||||
if isSuspended {
|
||||
return
|
||||
}
|
||||
|
||||
// Prevent future lock acquisition
|
||||
isSuspended = true
|
||||
|
||||
// Interrupt the database because this may trigger an
|
||||
// SQLITE_INTERRUPT error which may itself abort a transaction and
|
||||
// release a lock. See https://www.sqlite.org/c3ref/interrupt.html
|
||||
interrupt()
|
||||
|
||||
// Now what about the eventual remaining lock? We'll issue a
|
||||
// rollback on next database access which requires a lock, in
|
||||
// checkForSuspensionViolation(from:).
|
||||
}
|
||||
}
|
||||
|
||||
/// Resumes the database. A resumed database stops preventing database locks
|
||||
/// in order to avoid the [`0xdead10cc`
|
||||
/// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html).
|
||||
///
|
||||
/// This method can be called from any thread.
|
||||
///
|
||||
/// See suspend().
|
||||
func resume() {
|
||||
isSuspended.write { isSuspended in
|
||||
isSuspended = false
|
||||
}
|
||||
}
|
||||
|
||||
/// Support for checkForSuspensionViolation(from:)
|
||||
private func journalMode() throws -> String {
|
||||
if let journalMode = journalModeCache {
|
||||
return journalMode
|
||||
}
|
||||
|
||||
// Don't return String.fetchOne(self, sql: "PRAGMA journal_mode"), so
|
||||
// that we don't create an infinite loop in checkForSuspensionViolation(from:)
|
||||
var statement: SQLiteStatement? = nil
|
||||
let sql = "PRAGMA journal_mode"
|
||||
sqlite3_prepare_v2(sqliteConnection, sql, -1, &statement, nil)
|
||||
defer { sqlite3_finalize(statement) }
|
||||
sqlite3_step(statement)
|
||||
guard let cString = sqlite3_column_text(statement, 0) else {
|
||||
throw DatabaseError(resultCode: lastErrorCode, message: lastErrorMessage, sql: sql)
|
||||
}
|
||||
let journalMode = String(cString: cString)
|
||||
journalModeCache = journalMode
|
||||
return journalMode
|
||||
}
|
||||
|
||||
/// Throws SQLITE_ABORT for suspended databases, if statement would lock
|
||||
/// the database, in order to avoid the [`0xdead10cc`
|
||||
/// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html).
|
||||
func checkForSuspensionViolation(from statement: Statement) throws {
|
||||
try isSuspended.read { isSuspended in
|
||||
guard isSuspended else {
|
||||
return
|
||||
}
|
||||
|
||||
if try journalMode() == "wal" && statement.isReadonly {
|
||||
// In WAL mode, accept read-only statements:
|
||||
// - SELECT ...
|
||||
// - BEGIN DEFERRED TRANSACTION
|
||||
//
|
||||
// Those are not read-only:
|
||||
// - INSERT ...
|
||||
// - BEGIN IMMEDIATE TRANSACTION
|
||||
return
|
||||
}
|
||||
|
||||
if
|
||||
let updateStatement = statement as? UpdateStatement,
|
||||
updateStatement.releasesDatabaseLock
|
||||
{
|
||||
// Accept statements that release locks:
|
||||
// - COMMIT
|
||||
// - ROLLBACK
|
||||
// - ROLLBACK TRANSACTION TO SAVEPOINT
|
||||
// - RELEASE SAVEPOINT
|
||||
return
|
||||
}
|
||||
|
||||
// Attempt at releasing an eventual lock with ROLLBACk,
|
||||
// as explained in Database.suspend().
|
||||
//
|
||||
// Use sqlite3_exec instead of `try? rollback()` in order to avoid
|
||||
// an infinite loop in checkForSuspensionViolation(from:)
|
||||
_ = sqlite3_exec(sqliteConnection, "ROLLBACK", nil, nil, nil)
|
||||
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_ABORT,
|
||||
message: "Database is suspended",
|
||||
sql: statement.sql,
|
||||
arguments: statement.arguments)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Transactions & Savepoint
|
||||
|
||||
/// Throws SQLITE_ABORT if called from a transaction-wrapping method and
|
||||
/// transaction has been aborted (for example, by `sqlite3_interrupt`, or a
|
||||
/// `ON CONFLICT ROLLBACK` clause.
|
||||
///
|
||||
/// try db.inTransaction {
|
||||
/// do {
|
||||
/// // Aborted by sqlite3_interrupt or any other
|
||||
/// // SQLite error which leaves transaction
|
||||
/// ...
|
||||
/// } catch { ... }
|
||||
///
|
||||
/// // <- Here we're inside an aborted transaction.
|
||||
/// try checkForAbortedTransaction(...) // throws
|
||||
/// ...
|
||||
///
|
||||
/// return .commit
|
||||
/// }
|
||||
func checkForAbortedTransaction(
|
||||
sql: @autoclosure () -> String? = nil,
|
||||
arguments: @autoclosure () -> StatementArguments? = nil)
|
||||
throws
|
||||
{
|
||||
if isInsideTransactionBlock && !isInsideTransaction {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_ABORT,
|
||||
message: "Transaction was aborted",
|
||||
sql: sql(),
|
||||
arguments: arguments())
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes a block inside a database transaction.
|
||||
///
|
||||
/// try dbQueue.inDatabase do {
|
||||
@@ -666,6 +752,12 @@ extension Database {
|
||||
// Begin transaction
|
||||
try beginTransaction(kind)
|
||||
|
||||
let wasInsideTransactionBlock = isInsideTransactionBlock
|
||||
isInsideTransactionBlock = true
|
||||
defer {
|
||||
isInsideTransactionBlock = wasInsideTransactionBlock
|
||||
}
|
||||
|
||||
// Now that transaction has begun, we'll rollback in case of error.
|
||||
// But we'll throw the first caught error, so that user knows
|
||||
// what happened.
|
||||
@@ -675,6 +767,15 @@ extension Database {
|
||||
let completion = try block()
|
||||
switch completion {
|
||||
case .commit:
|
||||
// In case of aborted transaction, throw SQLITE_ABORT instead
|
||||
// of the generic SQLITE_ERROR "cannot commit - no transaction is active"
|
||||
try checkForAbortedTransaction()
|
||||
|
||||
// Leave transaction block now, so that transaction observers
|
||||
// can execute statements without getting errors from
|
||||
// checkForAbortedTransaction().
|
||||
isInsideTransactionBlock = wasInsideTransactionBlock
|
||||
|
||||
try commit()
|
||||
needsRollback = false
|
||||
case .rollback:
|
||||
@@ -726,7 +827,8 @@ extension Database {
|
||||
// So when the default GRDB transaction kind is not deferred, we open a
|
||||
// transaction instead
|
||||
if !isInsideTransaction && configuration.defaultTransactionKind != .deferred {
|
||||
return try inTransaction(configuration.defaultTransactionKind, block)
|
||||
try inTransaction(configuration.defaultTransactionKind, block)
|
||||
return
|
||||
}
|
||||
|
||||
// If the savepoint is top-level, we'll use ROLLBACK TRANSACTION in
|
||||
@@ -742,6 +844,12 @@ extension Database {
|
||||
// the user uses "grdb" as a savepoint name.
|
||||
try execute(sql: "SAVEPOINT grdb")
|
||||
|
||||
let wasInsideTransactionBlock = isInsideTransactionBlock
|
||||
isInsideTransactionBlock = true
|
||||
defer {
|
||||
isInsideTransactionBlock = wasInsideTransactionBlock
|
||||
}
|
||||
|
||||
// Now that savepoint has begun, we'll rollback in case of error.
|
||||
// But we'll throw the first caught error, so that user knows
|
||||
// what happened.
|
||||
@@ -751,6 +859,15 @@ extension Database {
|
||||
let completion = try block()
|
||||
switch completion {
|
||||
case .commit:
|
||||
// In case of aborted transaction, throw SQLITE_ABORT instead
|
||||
// of the generic SQLITE_ERROR "cannot commit - no transaction is active"
|
||||
try checkForAbortedTransaction()
|
||||
|
||||
// Leave transaction block now, so that transaction observers
|
||||
// can execute statements without getting errors from
|
||||
// checkForAbortedTransaction().
|
||||
isInsideTransactionBlock = wasInsideTransactionBlock
|
||||
|
||||
try execute(sql: "RELEASE SAVEPOINT grdb")
|
||||
assert(!topLevelSavepoint || !isInsideTransaction)
|
||||
needsRollback = false
|
||||
@@ -888,8 +1005,7 @@ extension Database {
|
||||
// The second technique is more robust, because we don't have to guess
|
||||
// which rollback errors should be ignored, and which rollback errors
|
||||
// should be exposed to the library user.
|
||||
SchedulingWatchdog.preconditionValidQueue(self) // guard sqlite3_get_autocommit
|
||||
if sqlite3_get_autocommit(sqliteConnection) == 0 {
|
||||
if isInsideTransaction {
|
||||
try execute(sql: "ROLLBACK TRANSACTION")
|
||||
}
|
||||
assert(!isInsideTransaction)
|
||||
@@ -900,9 +1016,6 @@ extension Database {
|
||||
try execute(sql: "COMMIT TRANSACTION")
|
||||
assert(!isInsideTransaction)
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Memory Management
|
||||
|
||||
@@ -912,20 +1025,54 @@ extension Database {
|
||||
internalStatementCache.clear()
|
||||
publicStatementCache.clear()
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Erasing
|
||||
|
||||
func erase() throws {
|
||||
#if SQLITE_HAS_CODEC
|
||||
// SQLCipher does not support the backup API:
|
||||
// https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631
|
||||
// So we'll drop all database objects one after the other.
|
||||
|
||||
// Prevent foreign keys from messing with drop table statements
|
||||
let foreignKeysEnabled = try Bool.fetchOne(self, sql: "PRAGMA foreign_keys")!
|
||||
if foreignKeysEnabled {
|
||||
try execute(sql: "PRAGMA foreign_keys = OFF")
|
||||
}
|
||||
|
||||
try throwingFirstError(
|
||||
execute: {
|
||||
// Remove all database objects, one after the other
|
||||
try inTransaction {
|
||||
let sql = "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'"
|
||||
while let row = try Row.fetchOne(self, sql: sql) {
|
||||
let type: String = row["type"]
|
||||
let name: String = row["name"]
|
||||
try execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)")
|
||||
}
|
||||
return .commit
|
||||
}
|
||||
},
|
||||
finally: {
|
||||
// Restore foreign keys if needed
|
||||
if foreignKeysEnabled {
|
||||
try execute(sql: "PRAGMA foreign_keys = ON")
|
||||
}
|
||||
})
|
||||
#else
|
||||
try DatabaseQueue().backup(to: self)
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - Backup
|
||||
|
||||
static func backup(
|
||||
from dbFrom: Database,
|
||||
func backup(
|
||||
to dbDest: Database,
|
||||
afterBackupInit: (() -> Void)? = nil,
|
||||
afterBackupStep: (() -> Void)? = nil)
|
||||
throws
|
||||
{
|
||||
guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", dbFrom.sqliteConnection, "main") else {
|
||||
guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", sqliteConnection, "main") else {
|
||||
throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage)
|
||||
}
|
||||
guard Int(bitPattern: backup) != Int(SQLITE_ERROR) else {
|
||||
@@ -977,27 +1124,10 @@ extension Database {
|
||||
/// try db.usePassphrase("secret")
|
||||
/// }
|
||||
public func usePassphrase(_ passphrase: String) throws {
|
||||
// Support for the deprecated method change(passphrase:).
|
||||
// After it has been called, the passphrase used for opening the
|
||||
// database must be ignored.
|
||||
if configuration._passphrase != nil {
|
||||
return
|
||||
}
|
||||
try _usePassphrase(passphrase)
|
||||
}
|
||||
|
||||
/// See usePassphrase(_:)
|
||||
private func _usePassphrase(_ passphrase: String) throws {
|
||||
let data = passphrase.data(using: .utf8)!
|
||||
#if swift(>=5.0)
|
||||
let code = data.withUnsafeBytes {
|
||||
sqlite3_key(sqliteConnection, $0.baseAddress, Int32($0.count))
|
||||
}
|
||||
#else
|
||||
let code = data.withUnsafeBytes {
|
||||
sqlite3_key(sqliteConnection, $0, Int32(data.count))
|
||||
}
|
||||
#endif
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
|
||||
}
|
||||
@@ -1016,15 +1146,9 @@ extension Database {
|
||||
// > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/
|
||||
// swiftlint:disable:previous line_length
|
||||
let data = passphrase.data(using: .utf8)!
|
||||
#if swift(>=5.0)
|
||||
let code = data.withUnsafeBytes {
|
||||
sqlite3_rekey(sqliteConnection, $0.baseAddress, Int32($0.count))
|
||||
}
|
||||
#else
|
||||
let code = data.withUnsafeBytes {
|
||||
sqlite3_rekey(sqliteConnection, $0, Int32(data.count))
|
||||
}
|
||||
#endif
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: lastErrorMessage)
|
||||
}
|
||||
|
||||
@@ -1,11 +1,4 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// A Collation is a string comparison function used by SQLite.
|
||||
public final class DatabaseCollation {
|
||||
|
||||
@@ -1,11 +1,4 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
|
||||
public let rawValue: Int32
|
||||
@@ -20,12 +13,10 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
|
||||
/// let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY
|
||||
/// resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true
|
||||
public var primaryResultCode: ResultCode {
|
||||
return ResultCode(rawValue: rawValue & 0xFF)
|
||||
ResultCode(rawValue: rawValue & 0xFF)
|
||||
}
|
||||
|
||||
var isPrimary: Bool {
|
||||
return self == primaryResultCode
|
||||
}
|
||||
var isPrimary: Bool { self == primaryResultCode }
|
||||
|
||||
/// Returns true if the code on the left matches the code on the right.
|
||||
///
|
||||
@@ -156,21 +147,31 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
|
||||
// swiftlint:enable operator_usage_whitespace line_length
|
||||
}
|
||||
|
||||
extension ResultCode {
|
||||
/// Returns true if the code on the left matches the error on the right.
|
||||
///
|
||||
/// Primary result codes match themselves and their extended result codes,
|
||||
/// while extended result codes match only themselves.
|
||||
///
|
||||
/// do {
|
||||
/// try ...
|
||||
/// } catch ResultCode.SQLITE_CONSTRAINT_FOREIGNKEY {
|
||||
/// // foreign key constraint error
|
||||
/// } catch ResultCode.SQLITE_CONSTRAINT {
|
||||
/// // any other constraint error
|
||||
/// } catch {
|
||||
/// // any other database error
|
||||
/// }
|
||||
public static func ~= (lhs: Self, rhs: Error) -> Bool {
|
||||
guard let error = rhs as? DatabaseError else { return false }
|
||||
return lhs ~= error.extendedResultCode
|
||||
}
|
||||
}
|
||||
|
||||
// CustomStringConvertible
|
||||
extension ResultCode {
|
||||
var errorString: 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 String(cString: sqlite3_errstr(rawValue))
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) {
|
||||
return String(cString: sqlite3_errstr(rawValue))
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
#endif
|
||||
String(cString: sqlite3_errstr(rawValue))
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
@@ -201,7 +202,7 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
///
|
||||
/// See also `extendedResultCode`.
|
||||
public var resultCode: ResultCode {
|
||||
return extendedResultCode.primaryResultCode
|
||||
extendedResultCode.primaryResultCode
|
||||
}
|
||||
|
||||
/// The SQLite extended error code (see
|
||||
@@ -250,6 +251,127 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
let arguments: StatementArguments?
|
||||
}
|
||||
|
||||
// Support for `catch DatabaseError.SQLITE_XXX`
|
||||
extension DatabaseError {
|
||||
public static let SQLITE_OK = ResultCode.SQLITE_OK
|
||||
public static let SQLITE_ERROR = ResultCode.SQLITE_ERROR
|
||||
public static let SQLITE_INTERNAL = ResultCode.SQLITE_INTERNAL
|
||||
public static let SQLITE_PERM = ResultCode.SQLITE_PERM
|
||||
public static let SQLITE_ABORT = ResultCode.SQLITE_ABORT
|
||||
public static let SQLITE_BUSY = ResultCode.SQLITE_BUSY
|
||||
public static let SQLITE_LOCKED = ResultCode.SQLITE_LOCKED
|
||||
public static let SQLITE_NOMEM = ResultCode.SQLITE_NOMEM
|
||||
public static let SQLITE_READONLY = ResultCode.SQLITE_READONLY
|
||||
public static let SQLITE_INTERRUPT = ResultCode.SQLITE_INTERRUPT
|
||||
public static let SQLITE_IOERR = ResultCode.SQLITE_IOERR
|
||||
public static let SQLITE_CORRUPT = ResultCode.SQLITE_CORRUPT
|
||||
public static let SQLITE_NOTFOUND = ResultCode.SQLITE_NOTFOUND
|
||||
public static let SQLITE_FULL = ResultCode.SQLITE_FULL
|
||||
public static let SQLITE_CANTOPEN = ResultCode.SQLITE_CANTOPEN
|
||||
public static let SQLITE_PROTOCOL = ResultCode.SQLITE_PROTOCOL
|
||||
public static let SQLITE_EMPTY = ResultCode.SQLITE_EMPTY
|
||||
public static let SQLITE_SCHEMA = ResultCode.SQLITE_SCHEMA
|
||||
public static let SQLITE_TOOBIG = ResultCode.SQLITE_TOOBIG
|
||||
public static let SQLITE_CONSTRAINT = ResultCode.SQLITE_CONSTRAINT
|
||||
public static let SQLITE_MISMATCH = ResultCode.SQLITE_MISMATCH
|
||||
public static let SQLITE_MISUSE = ResultCode.SQLITE_MISUSE
|
||||
public static let SQLITE_NOLFS = ResultCode.SQLITE_NOLFS
|
||||
public static let SQLITE_AUTH = ResultCode.SQLITE_AUTH
|
||||
public static let SQLITE_FORMAT = ResultCode.SQLITE_FORMAT
|
||||
public static let SQLITE_RANGE = ResultCode.SQLITE_RANGE
|
||||
public static let SQLITE_NOTADB = ResultCode.SQLITE_NOTADB
|
||||
public static let SQLITE_NOTICE = ResultCode.SQLITE_NOTICE
|
||||
public static let SQLITE_WARNING = ResultCode.SQLITE_WARNING
|
||||
public static let SQLITE_ROW = ResultCode.SQLITE_ROW
|
||||
public static let SQLITE_DONE = ResultCode.SQLITE_DONE
|
||||
public static let SQLITE_ERROR_MISSING_COLLSEQ = ResultCode.SQLITE_ERROR_MISSING_COLLSEQ
|
||||
public static let SQLITE_ERROR_RETRY = ResultCode.SQLITE_ERROR_RETRY
|
||||
public static let SQLITE_ERROR_SNAPSHOT = ResultCode.SQLITE_ERROR_SNAPSHOT
|
||||
public static let SQLITE_IOERR_READ = ResultCode.SQLITE_IOERR_READ
|
||||
public static let SQLITE_IOERR_SHORT_READ = ResultCode.SQLITE_IOERR_SHORT_READ
|
||||
public static let SQLITE_IOERR_WRITE = ResultCode.SQLITE_IOERR_WRITE
|
||||
public static let SQLITE_IOERR_FSYNC = ResultCode.SQLITE_IOERR_FSYNC
|
||||
public static let SQLITE_IOERR_DIR_FSYNC = ResultCode.SQLITE_IOERR_DIR_FSYNC
|
||||
public static let SQLITE_IOERR_TRUNCATE = ResultCode.SQLITE_IOERR_TRUNCATE
|
||||
public static let SQLITE_IOERR_FSTAT = ResultCode.SQLITE_IOERR_FSTAT
|
||||
public static let SQLITE_IOERR_UNLOCK = ResultCode.SQLITE_IOERR_UNLOCK
|
||||
public static let SQLITE_IOERR_RDLOCK = ResultCode.SQLITE_IOERR_RDLOCK
|
||||
public static let SQLITE_IOERR_DELETE = ResultCode.SQLITE_IOERR_DELETE
|
||||
public static let SQLITE_IOERR_BLOCKED = ResultCode.SQLITE_IOERR_BLOCKED
|
||||
public static let SQLITE_IOERR_NOMEM = ResultCode.SQLITE_IOERR_NOMEM
|
||||
public static let SQLITE_IOERR_ACCESS = ResultCode.SQLITE_IOERR_ACCESS
|
||||
public static let SQLITE_IOERR_CHECKRESERVEDLOCK = ResultCode.SQLITE_IOERR_CHECKRESERVEDLOCK
|
||||
public static let SQLITE_IOERR_LOCK = ResultCode.SQLITE_IOERR_LOCK
|
||||
public static let SQLITE_IOERR_CLOSE = ResultCode.SQLITE_IOERR_CLOSE
|
||||
public static let SQLITE_IOERR_DIR_CLOSE = ResultCode.SQLITE_IOERR_DIR_CLOSE
|
||||
public static let SQLITE_IOERR_SHMOPEN = ResultCode.SQLITE_IOERR_SHMOPEN
|
||||
public static let SQLITE_IOERR_SHMSIZE = ResultCode.SQLITE_IOERR_SHMSIZE
|
||||
public static let SQLITE_IOERR_SHMLOCK = ResultCode.SQLITE_IOERR_SHMLOCK
|
||||
public static let SQLITE_IOERR_SHMMAP = ResultCode.SQLITE_IOERR_SHMMAP
|
||||
public static let SQLITE_IOERR_SEEK = ResultCode.SQLITE_IOERR_SEEK
|
||||
public static let SQLITE_IOERR_DELETE_NOENT = ResultCode.SQLITE_IOERR_DELETE_NOENT
|
||||
public static let SQLITE_IOERR_MMAP = ResultCode.SQLITE_IOERR_MMAP
|
||||
public static let SQLITE_IOERR_GETTEMPPATH = ResultCode.SQLITE_IOERR_GETTEMPPATH
|
||||
public static let SQLITE_IOERR_CONVPATH = ResultCode.SQLITE_IOERR_CONVPATH
|
||||
public static let SQLITE_IOERR_VNODE = ResultCode.SQLITE_IOERR_VNODE
|
||||
public static let SQLITE_IOERR_AUTH = ResultCode.SQLITE_IOERR_AUTH
|
||||
public static let SQLITE_IOERR_BEGIN_ATOMIC = ResultCode.SQLITE_IOERR_BEGIN_ATOMIC
|
||||
public static let SQLITE_IOERR_COMMIT_ATOMIC = ResultCode.SQLITE_IOERR_COMMIT_ATOMIC
|
||||
public static let SQLITE_IOERR_ROLLBACK_ATOMIC = ResultCode.SQLITE_IOERR_ROLLBACK_ATOMIC
|
||||
public static let SQLITE_LOCKED_SHAREDCACHE = ResultCode.SQLITE_LOCKED_SHAREDCACHE
|
||||
public static let SQLITE_LOCKED_VTAB = ResultCode.SQLITE_LOCKED_VTAB
|
||||
public static let SQLITE_BUSY_RECOVERY = ResultCode.SQLITE_BUSY_RECOVERY
|
||||
public static let SQLITE_BUSY_SNAPSHOT = ResultCode.SQLITE_BUSY_SNAPSHOT
|
||||
public static let SQLITE_CANTOPEN_NOTEMPDIR = ResultCode.SQLITE_CANTOPEN_NOTEMPDIR
|
||||
public static let SQLITE_CANTOPEN_ISDIR = ResultCode.SQLITE_CANTOPEN_ISDIR
|
||||
public static let SQLITE_CANTOPEN_FULLPATH = ResultCode.SQLITE_CANTOPEN_FULLPATH
|
||||
public static let SQLITE_CANTOPEN_CONVPATH = ResultCode.SQLITE_CANTOPEN_CONVPATH
|
||||
public static let SQLITE_CANTOPEN_DIRTYWAL = ResultCode.SQLITE_CANTOPEN_DIRTYWAL
|
||||
public static let SQLITE_CORRUPT_VTAB = ResultCode.SQLITE_CORRUPT_VTAB
|
||||
public static let SQLITE_CORRUPT_SEQUENCE = ResultCode.SQLITE_CORRUPT_SEQUENCE
|
||||
public static let SQLITE_READONLY_RECOVERY = ResultCode.SQLITE_READONLY_RECOVERY
|
||||
public static let SQLITE_READONLY_CANTLOCK = ResultCode.SQLITE_READONLY_CANTLOCK
|
||||
public static let SQLITE_READONLY_ROLLBACK = ResultCode.SQLITE_READONLY_ROLLBACK
|
||||
public static let SQLITE_READONLY_DBMOVED = ResultCode.SQLITE_READONLY_DBMOVED
|
||||
public static let SQLITE_READONLY_CANTINIT = ResultCode.SQLITE_READONLY_CANTINIT
|
||||
public static let SQLITE_READONLY_DIRECTORY = ResultCode.SQLITE_READONLY_DIRECTORY
|
||||
public static let SQLITE_ABORT_ROLLBACK = ResultCode.SQLITE_ABORT_ROLLBACK
|
||||
public static let SQLITE_CONSTRAINT_CHECK = ResultCode.SQLITE_CONSTRAINT_CHECK
|
||||
public static let SQLITE_CONSTRAINT_COMMITHOOK = ResultCode.SQLITE_CONSTRAINT_COMMITHOOK
|
||||
public static let SQLITE_CONSTRAINT_FOREIGNKEY = ResultCode.SQLITE_CONSTRAINT_FOREIGNKEY
|
||||
public static let SQLITE_CONSTRAINT_FUNCTION = ResultCode.SQLITE_CONSTRAINT_FUNCTION
|
||||
public static let SQLITE_CONSTRAINT_NOTNULL = ResultCode.SQLITE_CONSTRAINT_NOTNULL
|
||||
public static let SQLITE_CONSTRAINT_PRIMARYKEY = ResultCode.SQLITE_CONSTRAINT_PRIMARYKEY
|
||||
public static let SQLITE_CONSTRAINT_TRIGGER = ResultCode.SQLITE_CONSTRAINT_TRIGGER
|
||||
public static let SQLITE_CONSTRAINT_UNIQUE = ResultCode.SQLITE_CONSTRAINT_UNIQUE
|
||||
public static let SQLITE_CONSTRAINT_VTAB = ResultCode.SQLITE_CONSTRAINT_VTAB
|
||||
public static let SQLITE_CONSTRAINT_ROWID = ResultCode.SQLITE_CONSTRAINT_ROWID
|
||||
public static let SQLITE_NOTICE_RECOVER_WAL = ResultCode.SQLITE_NOTICE_RECOVER_WAL
|
||||
public static let SQLITE_NOTICE_RECOVER_ROLLBACK = ResultCode.SQLITE_NOTICE_RECOVER_ROLLBACK
|
||||
public static let SQLITE_WARNING_AUTOINDEX = ResultCode.SQLITE_WARNING_AUTOINDEX
|
||||
public static let SQLITE_AUTH_USER = ResultCode.SQLITE_AUTH_USER
|
||||
public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode.SQLITE_OK_LOAD_PERMANENTLY
|
||||
}
|
||||
|
||||
extension DatabaseError {
|
||||
// TODO: test
|
||||
/// Returns true if the error has code `SQLITE_ABORT` or `SQLITE_INTERRUPT`.
|
||||
///
|
||||
/// Such an error can be thrown when a database has been interrupted, or
|
||||
/// when the database is suspended.
|
||||
///
|
||||
/// See `DatabaseReader.interrupt()` and `DatabaseReader.suspend()` for
|
||||
/// more information.
|
||||
public var isInterruptionError: Bool {
|
||||
switch resultCode {
|
||||
case .SQLITE_ABORT, .SQLITE_INTERRUPT:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// CustomStringConvertible
|
||||
extension DatabaseError {
|
||||
/// :nodoc:
|
||||
@@ -273,19 +395,13 @@ extension DatabaseError {
|
||||
|
||||
/// NSError bridging: the domain of the error.
|
||||
/// :nodoc:
|
||||
public static var errorDomain: String {
|
||||
return "GRDB.DatabaseError"
|
||||
}
|
||||
public static var errorDomain: String { "GRDB.DatabaseError" }
|
||||
|
||||
/// NSError bridging: the error code within the given domain.
|
||||
/// :nodoc:
|
||||
public var errorCode: Int {
|
||||
return Int(extendedResultCode.rawValue)
|
||||
}
|
||||
public var errorCode: Int { Int(extendedResultCode.rawValue) }
|
||||
|
||||
/// NSError bridging: the user-info dictionary.
|
||||
/// :nodoc:
|
||||
public var errorUserInfo: [String: Any] {
|
||||
return [NSLocalizedDescriptionKey: description]
|
||||
}
|
||||
public var errorUserInfo: [String: Any] { [NSLocalizedDescriptionKey: description] }
|
||||
}
|
||||
@@ -1,11 +1,3 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// An SQL function or aggregate.
|
||||
public final class DatabaseFunction: Hashable {
|
||||
// SQLite identifies functions by (name + argument count)
|
||||
@@ -14,11 +6,11 @@ public final class DatabaseFunction: Hashable {
|
||||
let nArg: Int32 // -1 for variadic functions
|
||||
}
|
||||
|
||||
public var name: String { return identity.name }
|
||||
public var name: String { identity.name }
|
||||
private let identity: Identity
|
||||
let pure: Bool
|
||||
private let kind: Kind
|
||||
private var eTextRep: Int32 { return (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
|
||||
private var eTextRep: Int32 { (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
|
||||
|
||||
/// Returns an SQL function.
|
||||
///
|
||||
@@ -227,7 +219,7 @@ public final class DatabaseFunction: Hashable {
|
||||
return { (sqliteContext, argc, argv) in
|
||||
let aggregateContextU = DatabaseFunction.unmanagedAggregateContext(sqliteContext)
|
||||
let aggregateContext = aggregateContextU.takeUnretainedValue()
|
||||
assert(!aggregateContext.hasErrored)
|
||||
assert(!aggregateContext.hasErrored) // assert SQLite behavior
|
||||
do {
|
||||
let arguments = (0..<Int(argc)).map { index in
|
||||
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
|
||||
@@ -272,20 +264,24 @@ public final class DatabaseFunction: Hashable {
|
||||
/// See https://sqlite.org/c3ref/context.html
|
||||
/// See https://sqlite.org/c3ref/aggregate_context.html
|
||||
private static func unmanagedAggregateContext(_ sqliteContext: OpaquePointer?) -> Unmanaged<AggregateContext> {
|
||||
// The current aggregate buffer
|
||||
// > The first time the sqlite3_aggregate_context(C,N) routine is called
|
||||
// > for a particular aggregate function, SQLite allocates N of memory,
|
||||
// > zeroes out that memory, and returns a pointer to the new memory.
|
||||
// > On second and subsequent calls to sqlite3_aggregate_context() for
|
||||
// > the same aggregate function instance, the same buffer is returned.
|
||||
let stride = MemoryLayout<Unmanaged<AggregateContext>>.stride
|
||||
let aggregateContextBufferP = UnsafeMutableRawBufferPointer(
|
||||
start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!,
|
||||
count: stride)
|
||||
|
||||
if aggregateContextBufferP.contains(where: { $0 != 0 }) { // TODO: This testt looks weird. Review.
|
||||
// Buffer contains non-null pointer: load aggregate context
|
||||
if aggregateContextBufferP.contains(where: { $0 != 0 }) {
|
||||
// Buffer contains non-zero byte: load aggregate context
|
||||
let aggregateContextP = aggregateContextBufferP
|
||||
.baseAddress!
|
||||
.assumingMemoryBound(to: Unmanaged<AggregateContext>.self)
|
||||
return aggregateContextP.pointee
|
||||
} else {
|
||||
// Buffer contains null pointer: create aggregate context...
|
||||
// Buffer contains null pointer: create aggregate context.
|
||||
let aggregate = Unmanaged<AggregateDefinition>.fromOpaque(sqlite3_user_data(sqliteContext))
|
||||
.takeUnretainedValue()
|
||||
.makeAggregate()
|
||||
@@ -312,15 +308,9 @@ public final class DatabaseFunction: Hashable {
|
||||
case .string(let string):
|
||||
sqlite3_result_text(sqliteContext, string, -1, SQLITE_TRANSIENT)
|
||||
case .blob(let data):
|
||||
#if swift(>=5.0)
|
||||
data.withUnsafeBytes {
|
||||
sqlite3_result_blob(sqliteContext, $0.baseAddress, Int32($0.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
#else
|
||||
data.withUnsafeBytes {
|
||||
sqlite3_result_blob(sqliteContext, $0, Int32(data.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -345,7 +335,7 @@ extension DatabaseFunction {
|
||||
/// Two functions are equal if they share the same name and arity.
|
||||
/// :nodoc:
|
||||
public static func == (lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool {
|
||||
return lhs.identity == rhs.identity
|
||||
lhs.identity == rhs.identity
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,5 @@
|
||||
import Foundation
|
||||
import Dispatch
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
#if os(iOS)
|
||||
import UIKit
|
||||
#endif
|
||||
@@ -15,27 +8,22 @@ import UIKit
|
||||
public final class DatabasePool: DatabaseWriter {
|
||||
private let writer: SerializedDatabase
|
||||
private var readerPool: Pool<SerializedDatabase>!
|
||||
var readerConfiguration: Configuration
|
||||
|
||||
private var functions = Set<DatabaseFunction>()
|
||||
private var collations = Set<DatabaseCollation>()
|
||||
private var tokenizerRegistrations: [(Database) -> Void] = []
|
||||
|
||||
var databaseSnapshotCount = LockedBox(value: 0)
|
||||
|
||||
#if os(iOS)
|
||||
private weak var application: UIApplication?
|
||||
#endif
|
||||
|
||||
// MARK: - Database Information
|
||||
|
||||
/// The database configuration
|
||||
public var configuration: Configuration {
|
||||
writer.configuration
|
||||
}
|
||||
|
||||
/// The path to the database.
|
||||
public var path: String {
|
||||
return writer.path
|
||||
}
|
||||
|
||||
public var configuration: Configuration {
|
||||
return writer.configuration
|
||||
writer.path
|
||||
}
|
||||
|
||||
// MARK: - Initializer
|
||||
@@ -57,27 +45,50 @@ public final class DatabasePool: DatabaseWriter {
|
||||
writer = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
schemaCache: SimpleDatabaseSchemaCache(),
|
||||
schemaCache: DatabaseSchemaCache(),
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "writer")
|
||||
|
||||
// Readers
|
||||
readerConfiguration = configuration
|
||||
var readerConfiguration = configuration
|
||||
readerConfiguration.readonly = true
|
||||
|
||||
// Readers use deferred transactions by default.
|
||||
// Other transaction kinds are forbidden by SQLite in read-only connections.
|
||||
readerConfiguration.defaultTransactionKind = .deferred
|
||||
|
||||
// Readers can't allow dangling transactions because there's no
|
||||
// guarantee that one can get the same reader later in order to close
|
||||
// an opened transaction.
|
||||
readerConfiguration.allowsUnsafeTransactions = false
|
||||
|
||||
// https://www.sqlite.org/wal.html#sometimes_queries_return_sqlite_busy_in_wal_mode
|
||||
// > But there are some obscure cases where a query against a WAL-mode
|
||||
// > database can return SQLITE_BUSY, so applications should be prepared
|
||||
// > for that happenstance.
|
||||
// >
|
||||
// > - If another database connection has the database mode open in
|
||||
// > exclusive locking mode [...]
|
||||
// > - When the last connection to a particular database is closing,
|
||||
// > that connection will acquire an exclusive lock for a short time
|
||||
// > while it cleans up the WAL and shared-memory files [...]
|
||||
// > - If the last connection to a database crashed, then the first new
|
||||
// > connection to open the database will start a recovery process. An
|
||||
// > exclusive lock is held during recovery. [...]
|
||||
//
|
||||
// The whole point of WAL readers is to avoid SQLITE_BUSY, so let's
|
||||
// setup a busy handler for pool readers, in order to workaround those
|
||||
// "obscure cases" that may happen when the database is shared between
|
||||
// multiple processes.
|
||||
readerConfiguration.busyMode = .timeout(10)
|
||||
|
||||
var readerCount = 0
|
||||
readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: { [unowned self] in
|
||||
readerCount += 1 // protected by pool (TODO: documented this protection behavior)
|
||||
let reader = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: self.readerConfiguration,
|
||||
schemaCache: SimpleDatabaseSchemaCache(),
|
||||
configuration: readerConfiguration,
|
||||
schemaCache: DatabaseSchemaCache(),
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "reader.\(readerCount)")
|
||||
reader.sync { self.setupDatabase($0) }
|
||||
@@ -112,9 +123,16 @@ public final class DatabasePool: DatabaseWriter {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setupSuspension()
|
||||
|
||||
// Be a nice iOS citizen, and don't consume too much memory
|
||||
// See https://github.com/groue/GRDB.swift/#memory-management
|
||||
#if os(iOS)
|
||||
setupMemoryManagement()
|
||||
#endif
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
deinit {
|
||||
// Undo job done in setupMemoryManagement()
|
||||
//
|
||||
@@ -122,7 +140,6 @@ public final class DatabasePool: DatabaseWriter {
|
||||
// Explicit unregistration is required before iOS 9 and OS X 10.11.
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
#endif
|
||||
|
||||
private func setupDatabase(_ db: Database) {
|
||||
for function in functions {
|
||||
@@ -170,8 +187,6 @@ extension DatabasePool {
|
||||
///
|
||||
/// This method blocks the current thread until all database accesses
|
||||
/// are completed.
|
||||
///
|
||||
/// See also setupMemoryManagement(application:)
|
||||
public func releaseMemory() {
|
||||
// Release writer memory
|
||||
writer.sync { $0.releaseMemory() }
|
||||
@@ -181,7 +196,6 @@ extension DatabasePool {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#if os(iOS)
|
||||
/// Listens to UIApplicationDidEnterBackgroundNotification and
|
||||
/// UIApplicationDidReceiveMemoryWarningNotification in order to release
|
||||
@@ -190,8 +204,7 @@ extension DatabasePool {
|
||||
/// - param application: The UIApplication that will start a background
|
||||
/// task to let the database pool release its memory when the application
|
||||
/// enters background.
|
||||
public func setupMemoryManagement(in application: UIApplication) {
|
||||
self.application = application
|
||||
private func setupMemoryManagement() {
|
||||
let center = NotificationCenter.default
|
||||
center.addObserver(
|
||||
self,
|
||||
@@ -207,7 +220,7 @@ extension DatabasePool {
|
||||
|
||||
@objc
|
||||
private func applicationDidEnterBackground(_ notification: NSNotification) {
|
||||
guard let application = application else {
|
||||
guard let application = notification.object as? UIApplication else {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -233,24 +246,60 @@ extension DatabasePool {
|
||||
#endif
|
||||
}
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
extension DatabasePool {
|
||||
extension DatabasePool: DatabaseReader {
|
||||
|
||||
// MARK: - Encryption
|
||||
// MARK: - Interrupting Database Operations
|
||||
|
||||
/// Changes the passphrase of an encrypted database
|
||||
@available(*, deprecated, message: "Use Database.changePassphrase(_:) instead")
|
||||
public func change(passphrase: String) throws {
|
||||
try readerPool.barrier {
|
||||
try writer.sync { try $0.changePassphrase(passphrase) }
|
||||
readerPool.removeAll()
|
||||
readerConfiguration._passphrase = passphrase
|
||||
public func interrupt() {
|
||||
writer.interrupt()
|
||||
readerPool.forEach { $0.interrupt() }
|
||||
}
|
||||
|
||||
// MARK: - Database Suspension
|
||||
|
||||
func suspend() {
|
||||
if configuration.readonly {
|
||||
// read-only WAL connections can't acquire locks and do not need to
|
||||
// be suspended.
|
||||
return
|
||||
}
|
||||
writer.suspend()
|
||||
}
|
||||
|
||||
func resume() {
|
||||
if configuration.readonly {
|
||||
// read-only WAL connections can't acquire locks and do not need to
|
||||
// be suspended.
|
||||
return
|
||||
}
|
||||
writer.resume()
|
||||
}
|
||||
|
||||
private func setupSuspension() {
|
||||
if configuration.observesSuspensionNotifications {
|
||||
let center = NotificationCenter.default
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabasePool.suspend(_:)),
|
||||
name: Database.suspendNotification,
|
||||
object: nil)
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabasePool.resume(_:)),
|
||||
name: Database.resumeNotification,
|
||||
object: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
extension DatabasePool: DatabaseReader {
|
||||
|
||||
@objc
|
||||
private func suspend(_ notification: Notification) {
|
||||
suspend()
|
||||
}
|
||||
|
||||
@objc
|
||||
private func resume(_ notification: Notification) {
|
||||
resume()
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
@@ -290,9 +339,8 @@ extension DatabasePool: DatabaseReader {
|
||||
// See DatabasePoolTests.testReadMethodIsolationOfBlock().
|
||||
try db.inTransaction(.deferred) {
|
||||
// Reset the schema cache before running user code in snapshot isolation
|
||||
result = try db.withSchemaCache(SimpleDatabaseSchemaCache()) {
|
||||
try block(db)
|
||||
}
|
||||
db.clearSchemaCache()
|
||||
result = try block(db)
|
||||
return .commit
|
||||
}
|
||||
return result!
|
||||
@@ -300,21 +348,19 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// Asynchronously executes a read-only block in a protected dispatch queue.
|
||||
///
|
||||
/// let players = try dbQueue.asyncRead { result in
|
||||
/// let players = try dbQueue.asyncRead { dbResult in
|
||||
/// do {
|
||||
/// let db = try result.get()
|
||||
/// let db = try dbResult.get()
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // Handle error
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
|
||||
/// SQLCipher), attempts to write in the database from this method throw a
|
||||
/// DatabaseError of resultCode `SQLITE_READONLY`.
|
||||
/// Attempts to write in the database from this method throw a DatabaseError
|
||||
/// of resultCode `SQLITE_READONLY`.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
public func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void) {
|
||||
@@ -338,9 +384,52 @@ extension DatabasePool: DatabaseReader {
|
||||
try db.beginTransaction(.deferred)
|
||||
|
||||
// Reset the schema cache before running user code in snapshot isolation
|
||||
db.withSchemaCache(SimpleDatabaseSchemaCache()) {
|
||||
block(.success(db))
|
||||
}
|
||||
db.clearSchemaCache()
|
||||
block(.success(db))
|
||||
} catch {
|
||||
block(.failure(error))
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
block(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncRead(_ block: @escaping (Result<Database, Error>?) -> Void) {
|
||||
// First async jump in order to grab a reader connection.
|
||||
// Honor configuration dispatching (qos/targetQueue).
|
||||
configuration
|
||||
.makeDispatchQueue(defaultLabel: "GRDB.DatabasePool", purpose: "asyncRead")
|
||||
.async { [weak self] in
|
||||
guard let self = self else {
|
||||
block(nil)
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
let (reader, releaseReader) = try self.readerPool.get()
|
||||
|
||||
// Second async jump because sync could deadlock if
|
||||
// configuration has a serial targetQueue.
|
||||
reader.weakAsync { db in
|
||||
guard let db = db else {
|
||||
block(nil)
|
||||
return
|
||||
}
|
||||
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader()
|
||||
}
|
||||
do {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.beginTransaction(.deferred)
|
||||
|
||||
// Reset the schema cache before running user code in snapshot isolation
|
||||
db.clearSchemaCache()
|
||||
block(.success(db))
|
||||
} catch {
|
||||
block(.failure(error))
|
||||
}
|
||||
@@ -350,7 +439,6 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Synchronously executes a read-only block in a protected dispatch queue,
|
||||
/// and returns its result.
|
||||
@@ -382,10 +470,9 @@ extension DatabasePool: DatabaseReader {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
return try readerPool.get { reader in
|
||||
try reader.sync { db in
|
||||
// No schema cache when snapshot isolation is not established
|
||||
return try db.withSchemaCache(EmptyDatabaseSchemaCache()) {
|
||||
try block(db)
|
||||
}
|
||||
// Reset the schema cache
|
||||
db.clearSchemaCache()
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -423,10 +510,9 @@ extension DatabasePool: DatabaseReader {
|
||||
} else {
|
||||
return try readerPool.get { reader in
|
||||
try reader.sync { db in
|
||||
// No schema cache when snapshot isolation is not established
|
||||
return try db.withSchemaCache(EmptyDatabaseSchemaCache()) {
|
||||
try block(db)
|
||||
}
|
||||
// Reset the schema cache
|
||||
db.clearSchemaCache()
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -435,65 +521,13 @@ extension DatabasePool: DatabaseReader {
|
||||
public func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
// The semaphore that blocks until futureResult is defined:
|
||||
let futureSemaphore = DispatchSemaphore(value: 0)
|
||||
var futureResult: DatabaseResult<T>? = nil
|
||||
var futureResult: Result<T, Error>? = nil
|
||||
|
||||
#if compiler(>=5.0)
|
||||
asyncConcurrentRead { db in
|
||||
asyncConcurrentRead { dbResult in
|
||||
// Fetch and release the future
|
||||
futureResult = DatabaseResult { try block(db.get()) }
|
||||
futureResult = dbResult.flatMap { db in Result { try block(db) } }
|
||||
futureSemaphore.signal()
|
||||
}
|
||||
#else
|
||||
// Check that we're on the writer queue...
|
||||
writer.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
GRDBPrecondition(!db.isInsideTransaction, """
|
||||
must not be called from inside a transaction. \
|
||||
If this error is raised from a DatabasePool.write block, use \
|
||||
DatabasePool.writeWithoutTransaction instead (and use \
|
||||
transactions when needed).
|
||||
""")
|
||||
}
|
||||
|
||||
// The semaphore that blocks the writing dispatch queue until snapshot
|
||||
// isolation has been established:
|
||||
let isolationSemaphore = DispatchSemaphore(value: 0)
|
||||
|
||||
do {
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
reader.async { db in
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader()
|
||||
}
|
||||
do {
|
||||
try db.beginSnapshotTransaction()
|
||||
} catch {
|
||||
futureResult = .failure(error)
|
||||
isolationSemaphore.signal()
|
||||
futureSemaphore.signal()
|
||||
return
|
||||
}
|
||||
|
||||
// Release the writer queue
|
||||
isolationSemaphore.signal()
|
||||
|
||||
// Reset the schema cache before running user code in snapshot isolation
|
||||
db.schemaCache = SimpleDatabaseSchemaCache()
|
||||
|
||||
// Fetch and release the future
|
||||
futureResult = DatabaseResult { try block(db) }
|
||||
futureSemaphore.signal()
|
||||
}
|
||||
} catch {
|
||||
futureResult = .failure(error)
|
||||
isolationSemaphore.signal()
|
||||
futureSemaphore.signal()
|
||||
}
|
||||
|
||||
// Block the writer queue until snapshot isolation success or error
|
||||
_ = isolationSemaphore.wait(timeout: .distantFuture)
|
||||
#endif
|
||||
|
||||
return DatabaseFuture {
|
||||
// Block the future until results are fetched
|
||||
@@ -502,16 +536,13 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// Performs the same job as asyncConcurrentRead.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func spawnConcurrentRead(_ block: @escaping (Result<Database, Error>) -> Void) {
|
||||
asyncConcurrentRead(block)
|
||||
}
|
||||
#endif
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// Asynchronously executes a read-only block in a protected dispatch queue.
|
||||
///
|
||||
/// This method must be called from a writing dispatch queue, outside of any
|
||||
@@ -532,9 +563,9 @@ extension DatabasePool: DatabaseReader {
|
||||
/// try Player.deleteAll()
|
||||
///
|
||||
/// // Count players concurrently
|
||||
/// writer.asyncConcurrentRead { result in
|
||||
/// writer.asyncConcurrentRead { dbResult in
|
||||
/// do {
|
||||
/// let db = try result.get()
|
||||
/// let db = try dbResult.get()
|
||||
/// // Guaranteed to be zero
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
@@ -582,10 +613,9 @@ extension DatabasePool: DatabaseReader {
|
||||
isolationSemaphore.signal()
|
||||
|
||||
// Reset the schema cache before running user code in snapshot isolation
|
||||
db.withSchemaCache(SimpleDatabaseSchemaCache()) {
|
||||
// Fetch and release the future
|
||||
block(.success(db))
|
||||
}
|
||||
db.clearSchemaCache()
|
||||
|
||||
block(.success(db))
|
||||
}
|
||||
} catch {
|
||||
isolationSemaphore.signal()
|
||||
@@ -595,7 +625,6 @@ extension DatabasePool: DatabaseReader {
|
||||
// Block the writer queue until snapshot isolation success or error
|
||||
_ = isolationSemaphore.wait(timeout: .distantFuture)
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Invalidates open read-only SQLite connections.
|
||||
///
|
||||
@@ -646,12 +675,15 @@ extension DatabasePool: DatabaseReader {
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates.
|
||||
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.sync(updates)
|
||||
try writer.sync(updates)
|
||||
}
|
||||
|
||||
/// A barrier write ensures that no database access is executed until all
|
||||
/// previous accesses have completed, and the specified updates have been
|
||||
/// executed.
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, and returns the result.
|
||||
///
|
||||
/// Updates are guaranteed an exclusive access to the database. They wait
|
||||
/// until all pending writes and reads are completed. They postpone all
|
||||
/// other writes and reads until they are completed.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
@@ -660,7 +692,7 @@ extension DatabasePool: DatabaseReader {
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates.
|
||||
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
return try readerPool.barrier {
|
||||
try readerPool.barrier {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
}
|
||||
@@ -717,7 +749,7 @@ extension DatabasePool: DatabaseReader {
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.reentrantSync(updates)
|
||||
try writer.reentrantSync(updates)
|
||||
}
|
||||
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
@@ -729,6 +761,11 @@ extension DatabasePool: DatabaseReader {
|
||||
writer.async(updates)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncWriteWithoutTransaction(_ updates: @escaping (Database?) -> Void) {
|
||||
writer.weakAsync(updates)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
@@ -776,6 +813,125 @@ extension DatabasePool: DatabaseReader {
|
||||
forEachConnection { $0.remove(collation: collation) }
|
||||
}
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// :nodoc:
|
||||
public func _add<Reducer: _ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
return _addReadOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
}
|
||||
|
||||
if observation.requiresWriteAccess {
|
||||
let observer = _addWriteOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
return AnyDatabaseCancellable(cancel: observer.cancel)
|
||||
}
|
||||
|
||||
let observer = _addConcurrent(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
return AnyDatabaseCancellable(cancel: observer.cancel)
|
||||
}
|
||||
|
||||
/// A concurrent observation fetches the initial value without waiting for
|
||||
/// the writer.
|
||||
private func _addConcurrent<Reducer: _ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> ValueObserver<Reducer> // For testability
|
||||
{
|
||||
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
|
||||
assert(!observation.requiresWriteAccess, "Use _addWriteOnly(observation:) instead")
|
||||
|
||||
let observer = ValueObserver<Reducer>(
|
||||
requiresWriteAccess: observation.requiresWriteAccess,
|
||||
writer: self,
|
||||
reducer: observation.makeReducer(),
|
||||
scheduling: scheduler,
|
||||
reduceQueue: configuration.makeDispatchQueue(defaultLabel: "GRDB", purpose: "ValueObservation.reducer"),
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
// Fetch the initial value without waiting for the writer.
|
||||
let initialValue = try unsafeReentrantRead(observer.fetchInitialValue)
|
||||
onChange(initialValue)
|
||||
|
||||
// Now wait for the writer
|
||||
_weakAsyncWriteWithoutTransaction { db in
|
||||
guard let db = db else { return }
|
||||
if observer.isCompleted { return }
|
||||
do {
|
||||
// Don't miss eventual changes between the
|
||||
// initial fetch and the writer access.
|
||||
if let value = try observer.fetchValue(db) {
|
||||
observer.notifyChange(value)
|
||||
}
|
||||
|
||||
// Now we can start observation
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
observer.cancel()
|
||||
onError(error)
|
||||
}
|
||||
} else {
|
||||
// Fetch the initial value without waiting for the writer.
|
||||
_weakAsyncRead { [weak self] dbResult in
|
||||
guard let dbResult = dbResult else { return }
|
||||
guard let self = self else { return }
|
||||
if observer.isCompleted { return }
|
||||
do {
|
||||
let initialValue = try observer.fetchInitialValue(dbResult.get())
|
||||
observer.notifyChange(initialValue)
|
||||
|
||||
// Now wait for the writer
|
||||
self._weakAsyncWriteWithoutTransaction { db in
|
||||
guard let db = db else { return }
|
||||
if observer.isCompleted { return }
|
||||
do {
|
||||
// Don't miss eventual changes between the
|
||||
// initial fetch and the writer access.
|
||||
if let value = try observer.fetchValue(db) {
|
||||
observer.notifyChange(value)
|
||||
}
|
||||
|
||||
// Now we can start observation
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return observer
|
||||
}
|
||||
|
||||
// MARK: - Custom FTS5 Tokenizers
|
||||
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
|
||||
@@ -7,20 +7,17 @@ import UIKit
|
||||
/// A DatabaseQueue serializes access to an SQLite database.
|
||||
public final class DatabaseQueue: DatabaseWriter {
|
||||
private var writer: SerializedDatabase
|
||||
#if os(iOS)
|
||||
private weak var application: UIApplication?
|
||||
#endif
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// The database configuration
|
||||
public var configuration: Configuration {
|
||||
return writer.configuration
|
||||
writer.configuration
|
||||
}
|
||||
|
||||
/// The path to the database file; it is ":memory:" for in-memory databases.
|
||||
public var path: String {
|
||||
return writer.path
|
||||
writer.path
|
||||
}
|
||||
|
||||
// MARK: - Initializers
|
||||
@@ -39,8 +36,16 @@ public final class DatabaseQueue: DatabaseWriter {
|
||||
writer = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
schemaCache: SimpleDatabaseSchemaCache(),
|
||||
schemaCache: DatabaseSchemaCache(),
|
||||
defaultLabel: "GRDB.DatabaseQueue")
|
||||
|
||||
setupSuspension()
|
||||
|
||||
// Be a nice iOS citizen, and don't consume too much memory
|
||||
// See https://github.com/groue/GRDB.swift/#memory-management
|
||||
#if os(iOS)
|
||||
setupMemoryManagement()
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Opens an in-memory SQLite database.
|
||||
@@ -55,11 +60,10 @@ public final class DatabaseQueue: DatabaseWriter {
|
||||
writer = try! SerializedDatabase(
|
||||
path: ":memory:",
|
||||
configuration: configuration,
|
||||
schemaCache: SimpleDatabaseSchemaCache(),
|
||||
schemaCache: DatabaseSchemaCache(),
|
||||
defaultLabel: "GRDB.DatabaseQueue")
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
deinit {
|
||||
// Undo job done in setupMemoryManagement()
|
||||
//
|
||||
@@ -67,7 +71,6 @@ public final class DatabaseQueue: DatabaseWriter {
|
||||
// Explicit unregistration is required before iOS 9 and OS X 10.11.
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
extension DatabaseQueue {
|
||||
@@ -77,8 +80,6 @@ extension DatabaseQueue {
|
||||
/// Free as much memory as possible.
|
||||
///
|
||||
/// This method blocks the current thread until all database accesses are completed.
|
||||
///
|
||||
/// See also setupMemoryManagement(application:)
|
||||
public func releaseMemory() {
|
||||
writer.sync { $0.releaseMemory() }
|
||||
}
|
||||
@@ -91,8 +92,7 @@ extension DatabaseQueue {
|
||||
/// - param application: The UIApplication that will start a background
|
||||
/// task to let the database queue release its memory when the application
|
||||
/// enters background.
|
||||
public func setupMemoryManagement(in application: UIApplication) {
|
||||
self.application = application
|
||||
private func setupMemoryManagement() {
|
||||
let center = NotificationCenter.default
|
||||
center.addObserver(
|
||||
self,
|
||||
@@ -108,7 +108,7 @@ extension DatabaseQueue {
|
||||
|
||||
@objc
|
||||
private func applicationDidEnterBackground(_ notification: NSNotification) {
|
||||
guard let application = application else {
|
||||
guard let application = notification.object as? UIApplication else {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -134,20 +134,49 @@ extension DatabaseQueue {
|
||||
#endif
|
||||
}
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
extension DatabaseQueue {
|
||||
|
||||
// MARK: - Encryption
|
||||
// MARK: - Interrupting Database Operations
|
||||
|
||||
/// Changes the passphrase of an encrypted database
|
||||
@available(*, deprecated, message: "Use Database.changePassphrase(_:) instead")
|
||||
public func change(passphrase: String) throws {
|
||||
try writer.sync { try $0.changePassphrase(passphrase) }
|
||||
public func interrupt() {
|
||||
writer.interrupt()
|
||||
}
|
||||
|
||||
// MARK: - Database Suspension
|
||||
|
||||
func suspend() {
|
||||
writer.suspend()
|
||||
}
|
||||
|
||||
func resume() {
|
||||
writer.resume()
|
||||
}
|
||||
|
||||
private func setupSuspension() {
|
||||
if configuration.observesSuspensionNotifications {
|
||||
let center = NotificationCenter.default
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabaseQueue.suspend(_:)),
|
||||
name: Database.suspendNotification,
|
||||
object: nil)
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabaseQueue.resume(_:)),
|
||||
name: Database.resumeNotification,
|
||||
object: nil)
|
||||
}
|
||||
}
|
||||
|
||||
@objc
|
||||
private func suspend(_ notification: Notification) {
|
||||
suspend()
|
||||
}
|
||||
|
||||
@objc
|
||||
private func resume(_ notification: Notification) {
|
||||
resume()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
extension DatabaseQueue {
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
@@ -160,33 +189,30 @@ extension DatabaseQueue {
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
|
||||
/// SQLCipher), attempts to write in the database from this method throw a
|
||||
/// DatabaseError of resultCode `SQLITE_READONLY`.
|
||||
/// Attempts to write in the database from this method throw a DatabaseError
|
||||
/// of resultCode `SQLITE_READONLY`.
|
||||
///
|
||||
/// - 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 writer.sync { db in
|
||||
try writer.sync { db in
|
||||
try db.readOnly { try block(db) }
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// Asynchronously executes a read-only block in a protected dispatch queue.
|
||||
///
|
||||
/// let players = try dbQueue.asyncRead { result in
|
||||
/// let players = try dbQueue.asyncRead { dbResult in
|
||||
/// do {
|
||||
/// let db = try result.get()
|
||||
/// let db = try dbResult.get()
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // Handle error
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
|
||||
/// SQLCipher), attempts to write in the database from this method throw a
|
||||
/// DatabaseError of resultCode `SQLITE_READONLY`.
|
||||
/// Attempts to write in the database from this method throw a DatabaseError
|
||||
/// of resultCode `SQLITE_READONLY`.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
public func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void) {
|
||||
@@ -204,7 +230,28 @@ extension DatabaseQueue {
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncRead(_ block: @escaping (Result<Database, Error>?) -> Void) {
|
||||
writer.weakAsync { db in
|
||||
guard let db = db else {
|
||||
block(nil)
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
try db.beginReadOnly()
|
||||
} catch {
|
||||
block(.failure(error))
|
||||
return
|
||||
}
|
||||
|
||||
block(.success(db))
|
||||
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
@@ -220,7 +267,7 @@ extension DatabaseQueue {
|
||||
///
|
||||
/// :nodoc:
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.sync(block)
|
||||
try writer.sync(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
@@ -235,13 +282,13 @@ extension DatabaseQueue {
|
||||
///
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.reentrantSync(block)
|
||||
try writer.reentrantSync(block)
|
||||
}
|
||||
|
||||
public func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
// DatabaseQueue can't perform parallel reads.
|
||||
// Perform a blocking read instead.
|
||||
return DatabaseFuture(DatabaseResult {
|
||||
return DatabaseFuture(Result {
|
||||
// Check that we're on the writer queue...
|
||||
try writer.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
@@ -253,7 +300,6 @@ extension DatabaseQueue {
|
||||
})
|
||||
}
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// Performs the same job as asyncConcurrentRead.
|
||||
///
|
||||
/// :nodoc:
|
||||
@@ -276,7 +322,6 @@ extension DatabaseQueue {
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Writing in Database
|
||||
|
||||
@@ -328,7 +373,21 @@ extension DatabaseQueue {
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates.
|
||||
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.sync(updates)
|
||||
try writer.sync(updates)
|
||||
}
|
||||
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, and returns the result.
|
||||
///
|
||||
/// Eventual concurrent database accesses are postponed until the updates
|
||||
/// are completed.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates.
|
||||
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
@@ -344,7 +403,7 @@ extension DatabaseQueue {
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func inDatabase<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.sync(updates)
|
||||
try writer.sync(updates)
|
||||
}
|
||||
|
||||
/// Synchronously executes database updates in a protected dispatch queue, and
|
||||
@@ -358,7 +417,7 @@ extension DatabaseQueue {
|
||||
/// This method is reentrant. It is unsafe because it fosters dangerous
|
||||
/// concurrency practices.
|
||||
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.reentrantSync(updates)
|
||||
try writer.reentrantSync(updates)
|
||||
}
|
||||
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
@@ -367,6 +426,11 @@ extension DatabaseQueue {
|
||||
writer.async(updates)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncWriteWithoutTransaction(_ updates: @escaping (Database?) -> Void) {
|
||||
writer.weakAsync(updates)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
@@ -409,4 +473,30 @@ extension DatabaseQueue {
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
writer.sync { $0.remove(collation: collation) }
|
||||
}
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// :nodoc:
|
||||
public func _add<Reducer: _ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
return _addReadOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
}
|
||||
|
||||
let observer = _addWriteOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
return AnyDatabaseCancellable(cancel: observer.cancel)
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,4 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
import Dispatch
|
||||
|
||||
/// The protocol for all types that can fetch values from a database.
|
||||
///
|
||||
@@ -26,6 +20,67 @@ public protocol DatabaseReader: AnyObject {
|
||||
/// The database configuration
|
||||
var configuration: Configuration { get }
|
||||
|
||||
// MARK: - Interrupting Database Operations
|
||||
|
||||
/// This method causes any pending database operation to abort and return at
|
||||
/// its earliest opportunity.
|
||||
///
|
||||
/// It can be called from any thread.
|
||||
///
|
||||
/// A call to `interrupt()` that occurs when there are no running SQL
|
||||
/// statements is a no-op and has no effect on SQL statements that are
|
||||
/// started after `interrupt()` returns.
|
||||
///
|
||||
/// A database operation that is interrupted will throw a DatabaseError with
|
||||
/// code SQLITE_INTERRUPT. If the interrupted SQL operation is an INSERT,
|
||||
/// UPDATE, or DELETE that is inside an explicit transaction, then the
|
||||
/// entire transaction will be rolled back automatically. If the rolled back
|
||||
/// transaction was started by a transaction-wrapping method such as
|
||||
/// `DatabaseWriter.write` or `Database.inTransaction`, then all database
|
||||
/// accesses will throw a DatabaseError with code SQLITE_ABORT until the
|
||||
/// wrapping method returns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// // interrupted:
|
||||
/// try Player(...).insert(db) // throws SQLITE_INTERRUPT
|
||||
/// // not executed:
|
||||
/// try Player(...).insert(db)
|
||||
/// } // throws SQLITE_INTERRUPT
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// do {
|
||||
/// // interrupted:
|
||||
/// try Player(...).insert(db) // throws SQLITE_INTERRUPT
|
||||
/// } catch { }
|
||||
/// try Player(...).insert(db) // throws SQLITE_ABORT
|
||||
/// } // throws SQLITE_ABORT
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// do {
|
||||
/// // interrupted:
|
||||
/// try Player(...).insert(db) // throws SQLITE_INTERRUPT
|
||||
/// } catch { }
|
||||
/// } // throws SQLITE_ABORT
|
||||
///
|
||||
/// When an application creates transaction without a transaction-wrapping
|
||||
/// method, no SQLITE_ABORT error warns of aborted transactions:
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction
|
||||
/// try db.beginTransaction()
|
||||
/// do {
|
||||
/// // interrupted:
|
||||
/// try Player(...).insert(db) // throws SQLITE_INTERRUPT
|
||||
/// } catch { }
|
||||
/// try Player(...).insert(db) // success
|
||||
/// try db.commit() // throws SQLITE_ERROR "cannot commit - no transaction is active"
|
||||
/// }
|
||||
///
|
||||
/// Both SQLITE_ABORT and SQLITE_INTERRUPT errors can be checked with the
|
||||
/// `DatabaseError.isInterruptionError` property.
|
||||
func interrupt()
|
||||
|
||||
// MARK: - Read From Database
|
||||
|
||||
/// Synchronously executes a read-only block that takes a database
|
||||
@@ -46,8 +101,7 @@ public protocol DatabaseReader: AnyObject {
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds
|
||||
/// and SQLCipher, attempts to write in the database throw a DatabaseError
|
||||
/// Guarantee 2: attempts to write in the database throw a DatabaseError
|
||||
/// whose resultCode is `SQLITE_READONLY`.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
@@ -55,16 +109,15 @@ public protocol DatabaseReader: AnyObject {
|
||||
/// happen while establishing the read access to the database.
|
||||
func read<T>(_ block: (Database) throws -> T) throws -> T
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// Asynchronously executes a read-only block that takes a
|
||||
/// database connection.
|
||||
///
|
||||
/// Guarantee 1: the block argument is isolated. Eventual concurrent
|
||||
/// database updates are not visible inside the block:
|
||||
///
|
||||
/// try reader.asyncRead { result in
|
||||
/// try reader.asyncRead { dbResult in
|
||||
/// do (
|
||||
/// let db = try result.get()
|
||||
/// let db = try dbResult.get()
|
||||
/// // Those two values are guaranteed to be equal, even if the
|
||||
/// // `player` table is modified between the two requests:
|
||||
/// let count1 = try Player.fetchCount(db)
|
||||
@@ -74,13 +127,16 @@ public protocol DatabaseReader: AnyObject {
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds
|
||||
/// and SQLCipher, attempts to write in the database throw a DatabaseError
|
||||
/// Guarantee 2: attempts to write in the database throw a DatabaseError
|
||||
/// whose resultCode is `SQLITE_READONLY`.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void)
|
||||
#endif
|
||||
|
||||
/// Same as asyncRead, but without retaining self
|
||||
///
|
||||
/// :nodoc:
|
||||
func _weakAsyncRead(_ block: @escaping (Result<Database, Error>?) -> Void)
|
||||
|
||||
/// Synchronously executes a read-only block that takes a database
|
||||
/// connection, and returns its result.
|
||||
@@ -194,14 +250,14 @@ public protocol DatabaseReader: AnyObject {
|
||||
/// during observation
|
||||
/// - parameter onChange: a closure that is provided fresh values
|
||||
/// - returns: a TransactionObserver
|
||||
func add<Reducer: ValueReducer>(
|
||||
///
|
||||
/// :nodoc:
|
||||
func _add<Reducer: _ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> TransactionObserver
|
||||
|
||||
/// Remove a transaction observer.
|
||||
func remove(transactionObserver: TransactionObserver)
|
||||
-> DatabaseCancellable
|
||||
}
|
||||
|
||||
extension DatabaseReader {
|
||||
@@ -217,18 +273,67 @@ extension DatabaseReader {
|
||||
/// the backup. Those writes may, or may not, be reflected in the backup,
|
||||
/// but they won't trigger any error.
|
||||
public func backup(to writer: DatabaseWriter) throws {
|
||||
try backup(to: writer, afterBackupInit: nil, afterBackupStep: nil)
|
||||
try writer.writeWithoutTransaction { dbDest in
|
||||
try backup(to: dbDest)
|
||||
}
|
||||
}
|
||||
|
||||
func backup(to writer: DatabaseWriter, afterBackupInit: (() -> Void)?, afterBackupStep: (() -> Void)?) throws {
|
||||
func backup(
|
||||
to dbDest: Database,
|
||||
afterBackupInit: (() -> Void)? = nil,
|
||||
afterBackupStep: (() -> Void)? = nil)
|
||||
throws
|
||||
{
|
||||
try read { dbFrom in
|
||||
try writer.writeWithoutTransaction { dbDest in
|
||||
try Database.backup(
|
||||
from: dbFrom,
|
||||
to: dbDest,
|
||||
afterBackupInit: afterBackupInit,
|
||||
afterBackupStep: afterBackupStep)
|
||||
try dbFrom.backup(
|
||||
to: dbDest,
|
||||
afterBackupInit: afterBackupInit,
|
||||
afterBackupStep: afterBackupStep)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseReader {
|
||||
// MARK: - Value Observation Support
|
||||
|
||||
/// Adding an observation in a read-only database emits only the
|
||||
/// initial value.
|
||||
func _addReadOnly<Reducer: _ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
try onChange(unsafeReentrantRead(observation.fetchValue))
|
||||
} catch {
|
||||
onError(error)
|
||||
}
|
||||
return AnyDatabaseCancellable(cancel: { })
|
||||
} else {
|
||||
var isCancelled = false
|
||||
_weakAsyncRead { dbResult in
|
||||
guard
|
||||
!isCancelled,
|
||||
let dbResult = dbResult
|
||||
else { return }
|
||||
|
||||
let result = dbResult.flatMap { db in
|
||||
Result { try observation.fetchValue(db) }
|
||||
}
|
||||
|
||||
scheduler.schedule {
|
||||
guard !isCancelled else { return }
|
||||
do {
|
||||
try onChange(result.get())
|
||||
} catch {
|
||||
onError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
return AnyDatabaseCancellable(cancel: { isCancelled = true })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -247,31 +352,41 @@ public final class AnyDatabaseReader: DatabaseReader {
|
||||
|
||||
/// :nodoc:
|
||||
public var configuration: Configuration {
|
||||
return base.configuration
|
||||
base.configuration
|
||||
}
|
||||
|
||||
// MARK: - Interrupting Database Operations
|
||||
|
||||
/// :nodoc:
|
||||
public func interrupt() {
|
||||
base.interrupt()
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// :nodoc:
|
||||
public func read<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.read(block)
|
||||
try base.read(block)
|
||||
}
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// :nodoc:
|
||||
public func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void) {
|
||||
base.asyncRead(block)
|
||||
}
|
||||
#endif
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncRead(_ block: @escaping (Result<Database, Error>?) -> Void) {
|
||||
base._weakAsyncRead(block)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeRead(block)
|
||||
try base.unsafeRead(block)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeReentrantRead(block)
|
||||
try base.unsafeReentrantRead(block)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
@@ -301,17 +416,17 @@ public final class AnyDatabaseReader: DatabaseReader {
|
||||
// MARK: - Value Observation
|
||||
|
||||
/// :nodoc:
|
||||
public func add<Reducer: ValueReducer>(
|
||||
public func _add<Reducer: _ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> TransactionObserver
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
return base.add(observation: observation, onError: onError, onChange: onChange)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func remove(transactionObserver: TransactionObserver) {
|
||||
base.remove(transactionObserver: transactionObserver)
|
||||
base._add(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,12 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
return tableRegions.isEmpty
|
||||
}
|
||||
|
||||
/// Returns whether the region covers the full database: all columns and all
|
||||
/// rows from all tables.
|
||||
public var isFullDatabase: Bool {
|
||||
tableRegions == nil
|
||||
}
|
||||
|
||||
/// The region that covers the full database: all columns and all rows
|
||||
/// from all tables.
|
||||
public static let fullDatabase = DatabaseRegion(tableRegions: nil)
|
||||
@@ -170,7 +176,7 @@ extension DatabaseRegion {
|
||||
/// 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 == false
|
||||
intersection(eventKind.modifiedRegion).isEmpty == false
|
||||
}
|
||||
|
||||
/// Returns whether the content in the region is impacted by this event.
|
||||
@@ -233,7 +239,7 @@ extension DatabaseRegion {
|
||||
}
|
||||
return tableRegions
|
||||
.sorted(by: { (l, r) in l.key < r.key })
|
||||
.map { (table, tableRegion) in
|
||||
.map({ (table, tableRegion) in
|
||||
var desc = table
|
||||
if let columns = tableRegion.columns {
|
||||
desc += "(" + columns.sorted().joined(separator: ",") + ")"
|
||||
@@ -244,7 +250,7 @@ extension DatabaseRegion {
|
||||
desc += "[" + rowIds.sorted().map { "\($0)" }.joined(separator: ",") + "]"
|
||||
}
|
||||
return desc
|
||||
}
|
||||
})
|
||||
.joined(separator: ",")
|
||||
}
|
||||
}
|
||||
@@ -319,7 +325,7 @@ public protocol DatabaseRegionConvertible {
|
||||
extension DatabaseRegion: DatabaseRegionConvertible {
|
||||
/// :nodoc:
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return self
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
@@ -337,7 +343,7 @@ public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
|
||||
|
||||
/// :nodoc:
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try _region(db)
|
||||
try _region(db)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -345,7 +351,7 @@ public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
|
||||
|
||||
extension DatabaseRegion {
|
||||
static func union(_ regions: DatabaseRegion...) -> DatabaseRegion {
|
||||
return regions.reduce(into: DatabaseRegion()) { union, region in
|
||||
regions.reduce(into: DatabaseRegion()) { union, region in
|
||||
union.formUnion(region)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,7 +105,7 @@ private class DatabaseRegionObserver: TransactionObserver {
|
||||
}
|
||||
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
return region.isModified(byEventsOfKind: eventKind)
|
||||
region.isModified(byEventsOfKind: eventKind)
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
|
||||
@@ -1,24 +1,5 @@
|
||||
/// The protocol for database schema cache.
|
||||
protocol DatabaseSchemaCache {
|
||||
mutating func clear()
|
||||
|
||||
var schemaInfo: SchemaInfo? { get set }
|
||||
|
||||
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)
|
||||
|
||||
func indexes(on table: String) -> [IndexInfo]?
|
||||
mutating func set(indexes: [IndexInfo], forTable table: String)
|
||||
|
||||
func foreignKeys(on table: String) -> [ForeignKeyInfo]?
|
||||
mutating func set(foreignKeys: [ForeignKeyInfo], forTable table: String)
|
||||
}
|
||||
|
||||
/// A thread-unsafe database schema cache
|
||||
struct SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
struct DatabaseSchemaCache {
|
||||
var schemaInfo: SchemaInfo?
|
||||
private var primaryKeys: [String: PrimaryKeyInfo] = [:]
|
||||
private var columns: [String: [ColumnInfo]] = [:]
|
||||
@@ -34,7 +15,7 @@ struct SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
}
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
|
||||
return primaryKeys[table]
|
||||
primaryKeys[table]
|
||||
}
|
||||
|
||||
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
|
||||
@@ -42,7 +23,7 @@ struct SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
}
|
||||
|
||||
func columns(in table: String) -> [ColumnInfo]? {
|
||||
return columns[table]
|
||||
columns[table]
|
||||
}
|
||||
|
||||
mutating func set(columns: [ColumnInfo], forTable table: String) {
|
||||
@@ -50,7 +31,7 @@ struct SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
}
|
||||
|
||||
func indexes(on table: String) -> [IndexInfo]? {
|
||||
return indexes[table]
|
||||
indexes[table]
|
||||
}
|
||||
|
||||
mutating func set(indexes: [IndexInfo], forTable table: String) {
|
||||
@@ -58,32 +39,10 @@ struct SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
}
|
||||
|
||||
func foreignKeys(on table: String) -> [ForeignKeyInfo]? {
|
||||
return foreignKeys[table]
|
||||
foreignKeys[table]
|
||||
}
|
||||
|
||||
mutating func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
|
||||
self.foreignKeys[table] = foreignKeys
|
||||
}
|
||||
}
|
||||
|
||||
/// An always empty database schema cache
|
||||
struct EmptyDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
func clear() { }
|
||||
|
||||
var schemaInfo: SchemaInfo? {
|
||||
get { return nil }
|
||||
set { }
|
||||
}
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo? { return nil }
|
||||
func set(primaryKey: PrimaryKeyInfo, forTable table: String) { }
|
||||
|
||||
func columns(in table: String) -> [ColumnInfo]? { return nil }
|
||||
func set(columns: [ColumnInfo], forTable table: String) { }
|
||||
|
||||
func indexes(on table: String) -> [IndexInfo]? { return nil }
|
||||
func set(indexes: [IndexInfo], forTable table: String) { }
|
||||
|
||||
func foreignKeys(on table: String) -> [ForeignKeyInfo]? { return nil }
|
||||
func set(foreignKeys: [ForeignKeyInfo], forTable table: String) { }
|
||||
}
|
||||
@@ -11,7 +11,7 @@ public class DatabaseSnapshot: DatabaseReader {
|
||||
|
||||
/// The database configuration
|
||||
public var configuration: Configuration {
|
||||
return serializedDatabase.configuration
|
||||
serializedDatabase.configuration
|
||||
}
|
||||
|
||||
init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws {
|
||||
@@ -22,7 +22,7 @@ public class DatabaseSnapshot: DatabaseReader {
|
||||
serializedDatabase = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
schemaCache: SimpleDatabaseSchemaCache(),
|
||||
schemaCache: DatabaseSchemaCache(),
|
||||
defaultLabel: defaultLabel,
|
||||
purpose: purpose)
|
||||
|
||||
@@ -47,6 +47,12 @@ public class DatabaseSnapshot: DatabaseReader {
|
||||
// DatabaseReader
|
||||
extension DatabaseSnapshot {
|
||||
|
||||
// MARK: - Interrupting Database Operations
|
||||
|
||||
public func interrupt() {
|
||||
serializedDatabase.interrupt()
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// Synchronously executes a read-only block that takes a database
|
||||
@@ -59,15 +65,14 @@ extension DatabaseSnapshot {
|
||||
/// - 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)
|
||||
try serializedDatabase.sync(block)
|
||||
}
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// Asynchronously executes a read-only block in a protected dispatch queue.
|
||||
///
|
||||
/// let players = try snapshot.asyncRead { result in
|
||||
/// let players = try snapshot.asyncRead { dbResult in
|
||||
/// do {
|
||||
/// let db = try result.get()
|
||||
/// let db = try dbResult.get()
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // Handle error
|
||||
@@ -78,16 +83,20 @@ extension DatabaseSnapshot {
|
||||
public func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void) {
|
||||
serializedDatabase.async { block(.success($0)) }
|
||||
}
|
||||
#endif
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncRead(_ block: @escaping (Result<Database, Error>?) -> Void) {
|
||||
serializedDatabase.weakAsync { block($0.map { .success($0) }) }
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.sync(block)
|
||||
try serializedDatabase.sync(block)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try serializedDatabase.reentrantSync(block)
|
||||
try serializedDatabase.reentrantSync(block)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
@@ -110,61 +119,20 @@ extension DatabaseSnapshot {
|
||||
serializedDatabase.sync { $0.remove(collation: collation) }
|
||||
}
|
||||
|
||||
// MARK: - Value Observation
|
||||
// MARK: - Database Observation
|
||||
|
||||
public func add<Reducer: ValueReducer>(
|
||||
/// :nodoc:
|
||||
public func _add<Reducer: _ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> TransactionObserver
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
// TODO: fetch asynchronously when possible
|
||||
do {
|
||||
// Deal with initial value
|
||||
switch observation.scheduling {
|
||||
case .mainQueue:
|
||||
if let value = try unsafeReentrantRead(observation.fetchFirst) {
|
||||
if DispatchQueue.isMain {
|
||||
onChange(value)
|
||||
} else {
|
||||
DispatchQueue.main.async {
|
||||
onChange(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
case let .async(onQueue: queue, startImmediately: startImmediately):
|
||||
if startImmediately {
|
||||
if let value = try unsafeReentrantRead(observation.fetchFirst) {
|
||||
queue.async {
|
||||
onChange(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
case let .unsafe(startImmediately: startImmediately):
|
||||
if startImmediately {
|
||||
if let value = try unsafeReentrantRead(observation.fetchFirst) {
|
||||
onChange(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
onError(error)
|
||||
}
|
||||
|
||||
// Return a dummy observer, because snapshots never change
|
||||
return SnapshotValueObserver()
|
||||
}
|
||||
|
||||
public func remove(transactionObserver: TransactionObserver) {
|
||||
// Can't remove an observer which could not be added :-)
|
||||
_addReadOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
}
|
||||
}
|
||||
|
||||
/// An observer that does nothing, support for
|
||||
/// `DatabaseSnapshot.add(observation:onError:onChange:)`.
|
||||
private class SnapshotValueObserver: TransactionObserver {
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { return false }
|
||||
func databaseDidChange(with event: DatabaseEvent) { }
|
||||
func databaseDidCommit(_ db: Database) { }
|
||||
func databaseDidRollback(_ db: Database) { }
|
||||
}
|
||||
@@ -1,11 +1,4 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
// MARK: - DatabaseValue
|
||||
|
||||
@@ -209,12 +202,12 @@ extension DatabaseValue {
|
||||
extension DatabaseValue {
|
||||
/// Returns self
|
||||
public var databaseValue: DatabaseValue {
|
||||
return self
|
||||
self
|
||||
}
|
||||
|
||||
/// Returns the database value
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> DatabaseValue? {
|
||||
return dbValue
|
||||
dbValue
|
||||
}
|
||||
}
|
||||
|
||||
@@ -223,7 +216,7 @@ extension DatabaseValue {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public var sqlExpression: SQLExpression {
|
||||
return self
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
@@ -277,7 +270,7 @@ extension DatabaseValue {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
return self
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,7 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
// MARK: - Conversion Context and Errors
|
||||
|
||||
/// A type that helps the user understanding value conversion errors
|
||||
struct ValueConversionContext {
|
||||
struct ValueConversionContext: Refinable {
|
||||
private enum Column {
|
||||
case columnIndex(Int)
|
||||
case columnName(String)
|
||||
@@ -20,16 +12,12 @@ struct ValueConversionContext {
|
||||
var arguments: StatementArguments?
|
||||
private var column: Column?
|
||||
|
||||
func atColumn(_ columnIndex: Int) -> ValueConversionContext {
|
||||
var result = self
|
||||
result.column = .columnIndex(columnIndex)
|
||||
return result
|
||||
func atColumn(_ columnIndex: Int) -> Self {
|
||||
with(\.column, .columnIndex(columnIndex))
|
||||
}
|
||||
|
||||
func atColumn(_ columnName: String) -> ValueConversionContext {
|
||||
var result = self
|
||||
result.column = .columnName(columnName)
|
||||
return result
|
||||
func atColumn(_ columnName: String) -> Self {
|
||||
with(\.column, .columnName(columnName))
|
||||
}
|
||||
|
||||
var columnIndex: Int? {
|
||||
@@ -228,7 +216,7 @@ extension DatabaseValueConvertible {
|
||||
|
||||
@usableFromInline
|
||||
static func decode(from row: Row, atUncheckedIndex index: Int) -> Self {
|
||||
return decode(
|
||||
decode(
|
||||
from: row.impl.databaseValue(atUncheckedIndex: index),
|
||||
conversionContext: ValueConversionContext(row).atColumn(index))
|
||||
}
|
||||
@@ -262,7 +250,7 @@ extension DatabaseValueConvertible {
|
||||
|
||||
@usableFromInline
|
||||
static func decodeIfPresent(from row: Row, atUncheckedIndex index: Int) -> Self? {
|
||||
return decodeIfPresent(
|
||||
decodeIfPresent(
|
||||
from: row.impl.databaseValue(atUncheckedIndex: index),
|
||||
conversionContext: ValueConversionContext(row).atColumn(index))
|
||||
}
|
||||
@@ -313,7 +301,7 @@ extension Row {
|
||||
atUncheckedIndex index: Int)
|
||||
-> Value
|
||||
{
|
||||
return impl.fastDecode(type, atUncheckedIndex: index)
|
||||
impl.fastDecode(type, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
@@ -322,6 +310,6 @@ extension Row {
|
||||
atUncheckedIndex index: Int)
|
||||
-> Value?
|
||||
{
|
||||
return impl.fastDecodeIfPresent(type, atUncheckedIndex: index)
|
||||
impl.fastDecodeIfPresent(type, atUncheckedIndex: index)
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,3 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
// MARK: - DatabaseValueConvertible
|
||||
|
||||
/// Types that adopt DatabaseValueConvertible can be initialized from
|
||||
/// database values.
|
||||
///
|
||||
@@ -36,7 +26,7 @@ extension DatabaseValueConvertible {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public var sqlExpression: SQLExpression {
|
||||
return databaseValue
|
||||
databaseValue
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,7 +57,7 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor
|
||||
_statement.reset(withArguments: arguments)
|
||||
|
||||
// Assume cursor is created for iteration
|
||||
statement.database.selectStatementWillExecute(statement)
|
||||
try statement.database.selectStatementWillExecute(statement)
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -123,7 +113,7 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>:
|
||||
_statement.reset(withArguments: arguments)
|
||||
|
||||
// Assume cursor is created for iteration
|
||||
statement.database.selectStatementWillExecute(statement)
|
||||
try statement.database.selectStatementWillExecute(statement)
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -194,7 +184,7 @@ extension DatabaseValueConvertible {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> DatabaseValueCursor<Self>
|
||||
{
|
||||
return try DatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
try DatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from a prepared statement.
|
||||
@@ -214,7 +204,7 @@ extension DatabaseValueConvertible {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Self]
|
||||
{
|
||||
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from a prepared statement.
|
||||
@@ -273,7 +263,7 @@ extension DatabaseValueConvertible {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> DatabaseValueCursor<Self>
|
||||
{
|
||||
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from an SQL query.
|
||||
@@ -294,7 +284,7 @@ extension DatabaseValueConvertible {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Self]
|
||||
{
|
||||
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from an SQL query.
|
||||
@@ -318,7 +308,7 @@ extension DatabaseValueConvertible {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Self?
|
||||
{
|
||||
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -404,7 +394,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched values.
|
||||
@@ -416,7 +406,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
return try RowDecoder.fetchAll(db, self)
|
||||
try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched value.
|
||||
@@ -431,7 +421,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
return try RowDecoder.fetchOne(db, self)
|
||||
try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -475,7 +465,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
{
|
||||
return try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a prepared statement.
|
||||
@@ -495,7 +485,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Wrapped?]
|
||||
{
|
||||
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -529,7 +519,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
{
|
||||
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from an SQL query.
|
||||
@@ -550,7 +540,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Wrapped?]
|
||||
{
|
||||
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -599,7 +589,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible {
|
||||
extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder.Wrapped: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching Optional values
|
||||
|
||||
@@ -619,8 +609,8 @@ extension FetchRequest 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 -> NullableDatabaseValueCursor<RowDecoder._Wrapped> {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
|
||||
public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor<RowDecoder.Wrapped> {
|
||||
try Optional<RowDecoder.Wrapped>.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched optional values.
|
||||
@@ -631,7 +621,22 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped:
|
||||
/// - 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)
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder.Wrapped?] {
|
||||
try Optional<RowDecoder.Wrapped>.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched value.
|
||||
///
|
||||
/// The result is nil if the request returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches String?
|
||||
/// let string = try request.fetchOne(db) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder.Wrapped? {
|
||||
try RowDecoder.Wrapped.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,19 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// - throws: The error thrown by the updates.
|
||||
func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, and returns the result.
|
||||
///
|
||||
/// Updates are guaranteed an exclusive access to the database. They wait
|
||||
/// until all pending writes and reads are completed. They postpone all
|
||||
/// other writes and reads until they are completed.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates.
|
||||
func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T
|
||||
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
/// wrapped inside a transaction.
|
||||
///
|
||||
@@ -79,7 +91,6 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
func asyncWrite<T>(
|
||||
_ updates: @escaping (Database) throws -> T,
|
||||
completion: @escaping (Database, Result<T, Error>) -> Void)
|
||||
#endif
|
||||
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction.
|
||||
@@ -88,6 +99,12 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// in a transaction.
|
||||
func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
|
||||
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, without retaining self.
|
||||
///
|
||||
/// :nodoc:
|
||||
func _weakAsyncWriteWithoutTransaction(_ updates: @escaping (Database?) -> Void)
|
||||
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, and returns the result.
|
||||
///
|
||||
@@ -135,7 +152,6 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// }
|
||||
func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> DatabaseFuture<T>
|
||||
|
||||
#if compiler(>=5.0)
|
||||
// Exposed for RxGRDB and GRBCombine. Naming is not stabilized.
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -156,9 +172,9 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// try Player.deleteAll()
|
||||
///
|
||||
/// // Count players concurrently
|
||||
/// writer.asyncConcurrentRead { result in
|
||||
/// writer.asyncConcurrentRead { dbResult in
|
||||
/// do {
|
||||
/// let db = try result.get()
|
||||
/// let db = try dbResult.get()
|
||||
/// // Guaranteed to be zero
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
@@ -173,7 +189,6 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// :nodoc:
|
||||
func spawnConcurrentRead(_ block: @escaping (Result<Database, Error>) -> Void)
|
||||
#endif
|
||||
}
|
||||
|
||||
extension DatabaseWriter {
|
||||
@@ -196,7 +211,7 @@ extension DatabaseWriter {
|
||||
/// - throws: The error thrown by the updates, or by the
|
||||
/// wrapping transaction.
|
||||
public func write<T>(_ updates: (Database) throws -> T) throws -> T {
|
||||
return try writeWithoutTransaction { db in
|
||||
try writeWithoutTransaction { db in
|
||||
var result: T?
|
||||
try db.inTransaction {
|
||||
result = try updates(db)
|
||||
@@ -206,7 +221,6 @@ extension DatabaseWriter {
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
/// wrapped inside a transaction.
|
||||
///
|
||||
@@ -247,7 +261,6 @@ extension DatabaseWriter {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Transaction Observers
|
||||
|
||||
@@ -267,10 +280,10 @@ extension DatabaseWriter {
|
||||
writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) }
|
||||
}
|
||||
|
||||
/// Default implementation for the DatabaseReader requirement.
|
||||
/// :nodoc:
|
||||
public func remove(transactionObserver: TransactionObserver) {
|
||||
writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) }
|
||||
_weakAsyncWriteWithoutTransaction {
|
||||
$0?.remove(transactionObserver: transactionObserver)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Erasing the content of the database
|
||||
@@ -280,44 +293,7 @@ extension DatabaseWriter {
|
||||
/// - precondition: database is not accessed concurrently during the
|
||||
/// execution of this method.
|
||||
public func erase() throws {
|
||||
#if SQLITE_HAS_CODEC
|
||||
// SQLCipher does not support the backup API:
|
||||
// https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631
|
||||
// So we'll drop all database objects one after the other.
|
||||
try writeWithoutTransaction { db in
|
||||
// Prevent foreign keys from messing with drop table statements
|
||||
let foreignKeysEnabled = try Bool.fetchOne(db, sql: "PRAGMA foreign_keys")!
|
||||
if foreignKeysEnabled {
|
||||
try db.execute(sql: "PRAGMA foreign_keys = OFF")
|
||||
}
|
||||
|
||||
// Remove all database objects, one after the other
|
||||
do {
|
||||
try db.inTransaction {
|
||||
let sql = "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'"
|
||||
while let row = try Row.fetchOne(db, sql: sql) {
|
||||
let type: String = row["type"]
|
||||
let name: String = row["name"]
|
||||
try db.execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)")
|
||||
}
|
||||
return .commit
|
||||
}
|
||||
|
||||
// Restore foreign keys if needed
|
||||
if foreignKeysEnabled {
|
||||
try db.execute(sql: "PRAGMA foreign_keys = ON")
|
||||
}
|
||||
} catch {
|
||||
// Restore foreign keys if needed
|
||||
if foreignKeysEnabled {
|
||||
try? db.execute(sql: "PRAGMA foreign_keys = ON")
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
#else
|
||||
try DatabaseQueue().backup(to: self)
|
||||
#endif
|
||||
try writeWithoutTransaction { try $0.erase() }
|
||||
}
|
||||
|
||||
// MARK: - Claiming Disk Space
|
||||
@@ -330,218 +306,54 @@ extension DatabaseWriter {
|
||||
try writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
|
||||
}
|
||||
|
||||
// MARK: - Value Observation
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// Default implementation for the DatabaseReader requirement.
|
||||
/// :nodoc:
|
||||
public func add<Reducer: ValueReducer>(
|
||||
/// A write-only observation only uses the serialized writer
|
||||
func _addWriteOnly<Reducer: _ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> TransactionObserver
|
||||
-> ValueObserver<Reducer> // For testability
|
||||
{
|
||||
let requiresWriteAccess = observation.requiresWriteAccess
|
||||
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
|
||||
|
||||
let observer = ValueObserver<Reducer>(
|
||||
requiresWriteAccess: requiresWriteAccess,
|
||||
observesSelectedRegion: observation.observesSelectedRegion,
|
||||
requiresWriteAccess: observation.requiresWriteAccess,
|
||||
writer: self,
|
||||
reducer: observation.makeReducer(),
|
||||
scheduling: scheduler,
|
||||
reduceQueue: configuration.makeDispatchQueue(defaultLabel: "GRDB", purpose: "ValueObservation.reducer"),
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
|
||||
switch observation.scheduling {
|
||||
case .mainQueue:
|
||||
if DispatchQueue.isMain {
|
||||
// Use case: observation starts on the main queue and wants
|
||||
// a synchronous initial fetch. Typically, this helps avoiding
|
||||
// flashes of missing content.
|
||||
var startValue: Reducer.Value? = nil
|
||||
defer {
|
||||
if let startValue = startValue {
|
||||
onChange(startValue)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
try unsafeReentrantWrite { db in
|
||||
observer.notificationQueue = DispatchQueue.main
|
||||
observer.baseRegion = try observation.baseRegion(db).ignoringViews(db)
|
||||
observer.reducer = try observation.makeReducer(db)
|
||||
|
||||
// Initial value & selected region
|
||||
let fetchedValue: Reducer.Fetched
|
||||
if observation.observesSelectedRegion {
|
||||
(fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion {
|
||||
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
} else {
|
||||
fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
if let value = observer.reducer.value(fetchedValue) {
|
||||
startValue = value
|
||||
}
|
||||
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
}
|
||||
} catch {
|
||||
onError(error)
|
||||
}
|
||||
} else {
|
||||
// Use case: observation does not start on the main queue, but
|
||||
// has the default scheduling .mainQueue
|
||||
asyncWriteWithoutTransaction { db in
|
||||
do {
|
||||
observer.notificationQueue = DispatchQueue.main
|
||||
observer.baseRegion = try observation.baseRegion(db).ignoringViews(db)
|
||||
observer.reducer = try observation.makeReducer(db)
|
||||
|
||||
// Initial value & selected region
|
||||
let fetchedValue: Reducer.Fetched
|
||||
if observation.observesSelectedRegion {
|
||||
(fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion {
|
||||
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
} else {
|
||||
fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
if let value = observer.reducer.value(fetchedValue) {
|
||||
DispatchQueue.main.async {
|
||||
onChange(value)
|
||||
}
|
||||
}
|
||||
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
} catch {
|
||||
DispatchQueue.main.async {
|
||||
onError(error)
|
||||
}
|
||||
}
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
let initialValue: Reducer.Value = try unsafeReentrantWrite { db in
|
||||
let initialValue = try observer.fetchInitialValue(db)
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
return initialValue
|
||||
}
|
||||
onChange(initialValue)
|
||||
} catch {
|
||||
observer.cancel()
|
||||
onError(error)
|
||||
}
|
||||
|
||||
case let .async(onQueue: queue, startImmediately: startImmediately):
|
||||
// Use case: observation must not block the target queue
|
||||
asyncWriteWithoutTransaction { db in
|
||||
} else {
|
||||
_weakAsyncWriteWithoutTransaction { db in
|
||||
guard let db = db else { return }
|
||||
if observer.isCompleted { return }
|
||||
do {
|
||||
observer.notificationQueue = queue
|
||||
observer.baseRegion = try observation.baseRegion(db).ignoringViews(db)
|
||||
observer.reducer = try observation.makeReducer(db)
|
||||
|
||||
// Initial value & selected region
|
||||
if startImmediately {
|
||||
let fetchedValue: Reducer.Fetched
|
||||
if observation.observesSelectedRegion {
|
||||
(fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion {
|
||||
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
} else {
|
||||
fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
if let value = observer.reducer.value(fetchedValue) {
|
||||
queue.async {
|
||||
onChange(value)
|
||||
}
|
||||
}
|
||||
} else if observation.observesSelectedRegion {
|
||||
(_, observer.selectedRegion) = try db.recordingSelectedRegion {
|
||||
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
}
|
||||
|
||||
let initialValue = try observer.fetchInitialValue(db)
|
||||
observer.notifyChange(initialValue)
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
} catch {
|
||||
queue.async {
|
||||
onError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
case let .unsafe(startImmediately: startImmediately):
|
||||
if startImmediately {
|
||||
// Use case: third-party integration (RxSwift, Combine, ...) that
|
||||
// need a synchronous initial fetch.
|
||||
//
|
||||
// This is really super extra unsafe.
|
||||
//
|
||||
// If the observation is started on one dispatch queue, then
|
||||
// the onChange and onError callbacks must be asynchronously
|
||||
// dispatched on the *same* queue.
|
||||
//
|
||||
// A failure to follow this rule may mess with the ordering of
|
||||
// initial values.
|
||||
var startValue: Reducer.Value? = nil
|
||||
defer {
|
||||
if let startValue = startValue {
|
||||
onChange(startValue)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
try unsafeReentrantWrite { db in
|
||||
observer.notificationQueue = nil
|
||||
observer.baseRegion = try observation.baseRegion(db).ignoringViews(db)
|
||||
observer.reducer = try observation.makeReducer(db)
|
||||
|
||||
// Initial value & selected region
|
||||
if startImmediately {
|
||||
let fetchedValue: Reducer.Fetched
|
||||
if observation.observesSelectedRegion {
|
||||
(fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion {
|
||||
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
} else {
|
||||
fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
if let value = observer.reducer.value(fetchedValue) {
|
||||
startValue = value
|
||||
}
|
||||
} else if observation.observesSelectedRegion {
|
||||
(_, observer.selectedRegion) = try db.recordingSelectedRegion {
|
||||
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
}
|
||||
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
}
|
||||
} catch {
|
||||
onError(error)
|
||||
}
|
||||
} else {
|
||||
// Use case: ?
|
||||
//
|
||||
// This is unsafe because no promise is made on the dispatch
|
||||
// queue on which the onChange and onError callbacks are called.
|
||||
asyncWriteWithoutTransaction { db in
|
||||
do {
|
||||
observer.notificationQueue = nil
|
||||
observer.baseRegion = try observation.baseRegion(db).ignoringViews(db)
|
||||
observer.reducer = try observation.makeReducer(db)
|
||||
|
||||
// Selected region
|
||||
if observation.observesSelectedRegion {
|
||||
(_, observer.selectedRegion) = try db.recordingSelectedRegion {
|
||||
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
}
|
||||
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
} catch {
|
||||
onError(error)
|
||||
}
|
||||
observer.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO
|
||||
//
|
||||
// We promise that observation stops when the returned observer is
|
||||
// deallocated. But the real observer may have not started observing
|
||||
// the database, because some observations start asynchronously.
|
||||
// Well... This forces us to return a "token" that cancels any
|
||||
// observation started asynchronously.
|
||||
//
|
||||
// We'll eventually return a proper Cancellable. In GRDB 5?
|
||||
return ValueObserverToken(writer: self, observer: observer)
|
||||
return observer
|
||||
}
|
||||
}
|
||||
|
||||
@@ -566,7 +378,7 @@ public class DatabaseFuture<Value> {
|
||||
_wait = wait
|
||||
}
|
||||
|
||||
init(_ result: DatabaseResult<Value>) {
|
||||
init(_ result: Result<Value, Error>) {
|
||||
_wait = result.get
|
||||
}
|
||||
|
||||
@@ -598,58 +410,70 @@ public final class AnyDatabaseWriter: DatabaseWriter {
|
||||
|
||||
/// :nodoc:
|
||||
public var configuration: Configuration {
|
||||
return base.configuration
|
||||
base.configuration
|
||||
}
|
||||
|
||||
// MARK: - Interrupting Database Operations
|
||||
|
||||
/// :nodoc:
|
||||
public func interrupt() {
|
||||
base.interrupt()
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// :nodoc:
|
||||
public func read<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.read(block)
|
||||
try base.read(block)
|
||||
}
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// :nodoc:
|
||||
public func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void) {
|
||||
base.asyncRead(block)
|
||||
}
|
||||
#endif
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncRead(_ block: @escaping (Result<Database, Error>?) -> Void) {
|
||||
base._weakAsyncRead(block)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeRead(block)
|
||||
try base.unsafeRead(block)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeReentrantRead(block)
|
||||
try base.unsafeReentrantRead(block)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
return base.concurrentRead(block)
|
||||
base.concurrentRead(block)
|
||||
}
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// :nodoc:
|
||||
public func spawnConcurrentRead(_ block: @escaping (Result<Database, Error>) -> Void) {
|
||||
base.spawnConcurrentRead(block)
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Writing in Database
|
||||
|
||||
/// :nodoc:
|
||||
public func write<T>(_ updates: (Database) throws -> T) throws -> T {
|
||||
return try base.write(updates)
|
||||
try base.write(updates)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
return try base.writeWithoutTransaction(updates)
|
||||
try base.writeWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try base.barrierWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// :nodoc:
|
||||
public func asyncWrite<T>(
|
||||
_ updates: @escaping (Database) throws -> T,
|
||||
@@ -657,16 +481,20 @@ public final class AnyDatabaseWriter: DatabaseWriter {
|
||||
{
|
||||
base.asyncWrite(updates, completion: completion)
|
||||
}
|
||||
#endif
|
||||
|
||||
/// :nodoc:
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
base.asyncWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncWriteWithoutTransaction(_ updates: @escaping (Database?) -> Void) {
|
||||
base._weakAsyncWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
return try base.unsafeReentrantWrite(updates)
|
||||
try base.unsafeReentrantWrite(updates)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
@@ -692,4 +520,21 @@ public final class AnyDatabaseWriter: DatabaseWriter {
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
base.remove(collation: collation)
|
||||
}
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// :nodoc:
|
||||
public func _add<Reducer: _ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
base._add(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
}
|
||||
}
|
||||
@@ -49,20 +49,6 @@ public protocol FetchRequest: DatabaseRegionConvertible {
|
||||
/// The type that tells how fetched database rows should be interpreted.
|
||||
associatedtype RowDecoder
|
||||
|
||||
// TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method
|
||||
/// This method is deprecated. Use
|
||||
/// `makePreparedRequest(_:forSingleResult:)` instead.
|
||||
///
|
||||
/// Returns a tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter singleResult: A hint that a single result row will be
|
||||
/// consumed. Implementations can optionally use this to optimize the
|
||||
/// prepared statement.
|
||||
/// - returns: A prepared statement and an eventual row adapter.
|
||||
func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
|
||||
|
||||
/// Returns a PreparedRequest that is ready to be executed.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -89,7 +75,7 @@ extension FetchRequest {
|
||||
|
||||
/// Returns an adapted request.
|
||||
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest<Self> {
|
||||
return AdaptedFetchRequest(self, adapter)
|
||||
AdaptedFetchRequest(self, adapter)
|
||||
}
|
||||
|
||||
/// Returns the number of rows fetched by the request.
|
||||
@@ -112,22 +98,7 @@ extension FetchRequest {
|
||||
/// - parameter db: A database connection.
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
let request = try makePreparedRequest(db, forSingleResult: false)
|
||||
return request.statement.databaseRegion
|
||||
}
|
||||
|
||||
// Support for legacy requests which only define prepare(_:forSingleResult:)
|
||||
// TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method
|
||||
/// :nodoc:
|
||||
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
|
||||
let (statement, adapter) = try prepare(db, forSingleResult: singleResult)
|
||||
return PreparedRequest(statement: statement, adapter: adapter)
|
||||
}
|
||||
|
||||
// TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) {
|
||||
let request = try makePreparedRequest(db, forSingleResult: singleResult)
|
||||
return (request.statement, request.adapter)
|
||||
return request.statement.selectedRegion
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,12 +131,12 @@ public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
|
||||
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try base.fetchCount(db)
|
||||
try base.fetchCount(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try base.databaseRegion(db)
|
||||
try base.databaseRegion(db)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -189,39 +160,18 @@ public struct AnyFetchRequest<T>: FetchRequest {
|
||||
_databaseRegion = request.databaseRegion
|
||||
}
|
||||
|
||||
/// Creates a request whose `prepare()` method wraps and forwards
|
||||
/// operations the argument closure.
|
||||
@available(*, deprecated, message: "Define your own FetchRequest type instead.")
|
||||
public init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?)) {
|
||||
_preparedRequest = { db, singleResult in
|
||||
let (statement, adapter) = try prepare(db, singleResult)
|
||||
return PreparedRequest(statement: statement, adapter: adapter)
|
||||
}
|
||||
|
||||
_fetchCount = { db in
|
||||
let (statement, _) = try prepare(db, false)
|
||||
let sql = "SELECT COUNT(*) FROM (\(statement.sql))"
|
||||
return try Int.fetchOne(db, sql: sql, arguments: statement.arguments)!
|
||||
}
|
||||
|
||||
_databaseRegion = { db in
|
||||
let (statement, _) = try prepare(db, false)
|
||||
return statement.databaseRegion
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
|
||||
return try _preparedRequest(db, singleResult)
|
||||
try _preparedRequest(db, singleResult)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try _fetchCount(db)
|
||||
try _fetchCount(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try _databaseRegion(db)
|
||||
try _databaseRegion(db)
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,4 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// A database row.
|
||||
public final class Row: Equatable, Hashable, RandomAccessCollection,
|
||||
@@ -78,15 +71,13 @@ public final class Row: Equatable, Hashable, RandomAccessCollection,
|
||||
/// the iteration of a query: make sure to make a copy of it whenever you
|
||||
/// want to keep a specific one: `row.copy()`.
|
||||
public func copy() -> Row {
|
||||
return impl.copiedRow(self)
|
||||
impl.copiedRow(self)
|
||||
}
|
||||
|
||||
// MARK: - Not Public
|
||||
|
||||
/// Returns true if and only if the row was fetched from a database.
|
||||
var isFetched: Bool {
|
||||
return impl.isFetched
|
||||
}
|
||||
var isFetched: Bool { impl.isFetched }
|
||||
|
||||
/// Creates a row that maps an SQLite statement. Further calls to
|
||||
/// sqlite3_step() modify the row.
|
||||
@@ -142,19 +133,19 @@ extension Row {
|
||||
/// Columns appear in the same order as they occur as the `.0` member
|
||||
/// of column-value pairs in `self`.
|
||||
public var columnNames: LazyMapCollection<Row, String> {
|
||||
return lazy.map { $0.0 }
|
||||
lazy.map { $0.0 }
|
||||
}
|
||||
|
||||
/// Returns true if and only if the row has that column.
|
||||
///
|
||||
/// This method is case-insensitive.
|
||||
public func hasColumn(_ columnName: String) -> Bool {
|
||||
return index(ofColumn: columnName) != nil
|
||||
index(ofColumn: columnName) != nil
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func index(ofColumn name: String) -> Int? {
|
||||
return impl.index(ofColumn: name)
|
||||
impl.index(ofColumn: name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -382,7 +373,7 @@ extension Row {
|
||||
/// The result is nil if the row does not contain the column.
|
||||
@inlinable
|
||||
public subscript<Column: ColumnExpression>(_ column: Column) -> DatabaseValueConvertible? {
|
||||
return self[column.name]
|
||||
self[column.name]
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -395,7 +386,7 @@ extension Row {
|
||||
/// `Value`. Should this conversion fail, a fatal error is raised.
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible, Column: ColumnExpression>(_ column: Column) -> Value? {
|
||||
return self[column.name]
|
||||
self[column.name]
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -417,7 +408,7 @@ extension Row {
|
||||
Value: DatabaseValueConvertible & StatementColumnConvertible,
|
||||
Column: ColumnExpression
|
||||
{
|
||||
return self[column.name]
|
||||
self[column.name]
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -431,7 +422,7 @@ extension Row {
|
||||
/// SQLite value can not be converted to `Value`.
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible, Column: ColumnExpression>(_ column: Column) -> Value {
|
||||
return self[column.name]
|
||||
self[column.name]
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -454,7 +445,7 @@ extension Row {
|
||||
Value: DatabaseValueConvertible & StatementColumnConvertible,
|
||||
Column: ColumnExpression
|
||||
{
|
||||
return self[column.name]
|
||||
self[column.name]
|
||||
}
|
||||
|
||||
/// Returns the optional Data at given index.
|
||||
@@ -502,7 +493,7 @@ extension Row {
|
||||
/// The returned data does not owns its bytes: it must not be used longer
|
||||
/// than the row's lifetime.
|
||||
public func dataNoCopy<Column: ColumnExpression>(_ column: Column) -> Data? {
|
||||
return dataNoCopy(named: column.name)
|
||||
dataNoCopy(named: column.name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -515,7 +506,7 @@ extension Row {
|
||||
/// Values appear in the same order as they occur as the `.1` member
|
||||
/// of column-value pairs in `self`.
|
||||
public var databaseValues: LazyMapCollection<Row, DatabaseValue> {
|
||||
return lazy.map { $0.1 }
|
||||
lazy.map { $0.1 }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -701,7 +692,7 @@ extension Row {
|
||||
/// row.scopes["bar"] // [bar:2]
|
||||
/// row.scopes["baz"] // nil
|
||||
public var scopes: ScopesView {
|
||||
return impl.scopes(prefetchedRows: prefetchedRows)
|
||||
impl.scopes(prefetchedRows: prefetchedRows)
|
||||
}
|
||||
|
||||
/// Returns a view on the scopes tree defined by row adapters.
|
||||
@@ -724,7 +715,7 @@ extension Row {
|
||||
/// row.scopesTree["bar"] // [bar:2]
|
||||
/// row.scopesTree["baz"] // [baz:3]
|
||||
public var scopesTree: ScopesTreeView {
|
||||
return ScopesTreeView(scopes: scopes)
|
||||
ScopesTreeView(scopes: scopes)
|
||||
}
|
||||
|
||||
/// Returns a copy of the row, without any scopes.
|
||||
@@ -755,7 +746,7 @@ extension Row {
|
||||
/// This property can turn out useful when you debug the consumption of
|
||||
/// adapted rows, such as rows fetched from joined requests.
|
||||
public var unadapted: Row {
|
||||
return impl.unadaptedRow(self)
|
||||
impl.unadaptedRow(self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -779,7 +770,7 @@ public final class RowCursor: Cursor {
|
||||
statement.reset(withArguments: arguments)
|
||||
|
||||
// Assume cursor is created for iteration
|
||||
statement.database.selectStatementWillExecute(statement)
|
||||
try statement.database.selectStatementWillExecute(statement)
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -847,7 +838,7 @@ extension Row {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> RowCursor
|
||||
{
|
||||
return try RowCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
try RowCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of rows fetched from a prepared statement.
|
||||
@@ -935,7 +926,7 @@ extension Row {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> RowCursor
|
||||
{
|
||||
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of rows fetched from an SQL query.
|
||||
@@ -960,7 +951,7 @@ extension Row {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Row]
|
||||
{
|
||||
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns a single row fetched from an SQL query.
|
||||
@@ -985,7 +976,7 @@ extension Row {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Row?
|
||||
{
|
||||
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1093,7 +1084,7 @@ extension FetchRequest where RowDecoder == Row {
|
||||
/// - returns: A cursor over fetched rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> RowCursor {
|
||||
return try Row.fetchCursor(db, self)
|
||||
try Row.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched rows.
|
||||
@@ -1105,7 +1096,7 @@ extension FetchRequest where RowDecoder == Row {
|
||||
/// - returns: An array of fetched rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [Row] {
|
||||
return try Row.fetchAll(db, self)
|
||||
try Row.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched row.
|
||||
@@ -1117,7 +1108,7 @@ extension FetchRequest where RowDecoder == Row {
|
||||
/// - returns: An optional row.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> Row? {
|
||||
return try Row.fetchOne(db, self)
|
||||
try Row.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1142,16 +1133,12 @@ extension Row {
|
||||
|
||||
/// The index of the first (ColumnName, DatabaseValue) pair.
|
||||
/// :nodoc:
|
||||
public var startIndex: RowIndex {
|
||||
return Index(0)
|
||||
}
|
||||
public var startIndex: RowIndex { RowIndex(0) }
|
||||
|
||||
/// The "past-the-end" index, successor of the index of the last
|
||||
/// (ColumnName, DatabaseValue) pair.
|
||||
/// :nodoc:
|
||||
public var endIndex: RowIndex {
|
||||
return Index(count)
|
||||
}
|
||||
public var endIndex: RowIndex { RowIndex(count) }
|
||||
|
||||
/// Accesses the (ColumnName, DatabaseValue) pair at given index.
|
||||
public subscript(position: RowIndex) -> (String, DatabaseValue) {
|
||||
@@ -1225,14 +1212,14 @@ extension Row {
|
||||
extension Row {
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
return "["
|
||||
"["
|
||||
+ map { (column, dbValue) in "\(column):\(dbValue)" }.joined(separator: " ")
|
||||
+ "]"
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public var debugDescription: String {
|
||||
return debugDescription(level: 0)
|
||||
debugDescription(level: 0)
|
||||
}
|
||||
|
||||
private func debugDescription(level: Int) -> String {
|
||||
@@ -1284,12 +1271,12 @@ public struct RowIndex: Comparable, Strideable {
|
||||
extension RowIndex {
|
||||
/// :nodoc:
|
||||
public static func == (lhs: RowIndex, rhs: RowIndex) -> Bool {
|
||||
return lhs.index == rhs.index
|
||||
lhs.index == rhs.index
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public static func < (lhs: RowIndex, rhs: RowIndex) -> Bool {
|
||||
return lhs.index < rhs.index
|
||||
lhs.index < rhs.index
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1297,12 +1284,12 @@ extension RowIndex {
|
||||
extension RowIndex {
|
||||
/// :nodoc:
|
||||
public func distance(to other: RowIndex) -> Int {
|
||||
return other.index - index
|
||||
other.index - index
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func advanced(by n: Int) -> RowIndex {
|
||||
return RowIndex(index + n)
|
||||
RowIndex(index + n)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1339,7 +1326,7 @@ extension Row {
|
||||
|
||||
/// The scopes defined on this row.
|
||||
public var names: Dictionary<String, LayoutedRowAdapter>.Keys {
|
||||
return scopes.keys
|
||||
scopes.keys
|
||||
}
|
||||
|
||||
init() {
|
||||
@@ -1354,17 +1341,17 @@ extension Row {
|
||||
|
||||
/// :nodoc:
|
||||
public var startIndex: Index {
|
||||
return scopes.startIndex
|
||||
scopes.startIndex
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public var endIndex: Index {
|
||||
return scopes.endIndex
|
||||
scopes.endIndex
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func index(after i: Index) -> Index {
|
||||
return scopes.index(after: i)
|
||||
scopes.index(after: i)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
@@ -1387,7 +1374,7 @@ extension Row {
|
||||
/// Returns the row associated with the given scope, or nil if the
|
||||
/// scope is not defined.
|
||||
public subscript(_ name: String) -> Row? {
|
||||
return scopes.index(forKey: name).map { self[$0].row }
|
||||
scopes.index(forKey: name).map { self[$0].row }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1500,7 +1487,7 @@ extension Row {
|
||||
|
||||
/// True if there is no prefetched associated rows.
|
||||
public var isEmpty: Bool {
|
||||
return prefetches.isEmpty
|
||||
prefetches.isEmpty
|
||||
}
|
||||
|
||||
/// The keys for available prefetched rows
|
||||
@@ -1666,20 +1653,16 @@ private struct ArrayRowImpl: RowImpl {
|
||||
self.columns = columns
|
||||
}
|
||||
|
||||
var count: Int {
|
||||
return columns.count
|
||||
}
|
||||
var count: Int { columns.count }
|
||||
|
||||
var isFetched: Bool {
|
||||
return false
|
||||
}
|
||||
var isFetched: Bool { false }
|
||||
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
|
||||
return columns[index].1
|
||||
columns[index].1
|
||||
}
|
||||
|
||||
func columnName(atUncheckedIndex index: Int) -> String {
|
||||
return columns[index].0
|
||||
columns[index].0
|
||||
}
|
||||
|
||||
func index(ofColumn name: String) -> Int? {
|
||||
@@ -1688,7 +1671,7 @@ private struct ArrayRowImpl: RowImpl {
|
||||
}
|
||||
|
||||
func copiedRow(_ row: Row) -> Row {
|
||||
return row
|
||||
row
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1708,20 +1691,16 @@ private struct StatementCopyRowImpl: RowImpl {
|
||||
self.columnNames = columnNames
|
||||
}
|
||||
|
||||
var count: Int {
|
||||
return columnNames.count
|
||||
}
|
||||
var count: Int { columnNames.count }
|
||||
|
||||
var isFetched: Bool {
|
||||
return true
|
||||
}
|
||||
var isFetched: Bool { true }
|
||||
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
|
||||
return dbValues[index]
|
||||
dbValues[index]
|
||||
}
|
||||
|
||||
func columnName(atUncheckedIndex index: Int) -> String {
|
||||
return columnNames[index]
|
||||
columnNames[index]
|
||||
}
|
||||
|
||||
func index(ofColumn name: String) -> Int? {
|
||||
@@ -1730,7 +1709,7 @@ private struct StatementCopyRowImpl: RowImpl {
|
||||
}
|
||||
|
||||
func copiedRow(_ row: Row) -> Row {
|
||||
return row
|
||||
row
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1755,12 +1734,10 @@ private struct StatementRowImpl: RowImpl {
|
||||
}
|
||||
|
||||
var count: Int {
|
||||
return Int(sqlite3_column_count(sqliteStatement))
|
||||
Int(sqlite3_column_count(sqliteStatement))
|
||||
}
|
||||
|
||||
var isFetched: Bool {
|
||||
return true
|
||||
}
|
||||
var isFetched: Bool { true }
|
||||
|
||||
func hasNull(atUncheckedIndex index: Int) -> Bool {
|
||||
// Avoid extracting values, because this modifies the SQLite statement.
|
||||
@@ -1779,25 +1756,25 @@ private struct StatementRowImpl: RowImpl {
|
||||
}
|
||||
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
|
||||
return DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
}
|
||||
|
||||
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int) -> Value
|
||||
{
|
||||
return Value.fastDecode(from: sqliteStatement, atUncheckedIndex: Int32(index))
|
||||
Value.fastDecode(from: sqliteStatement, atUncheckedIndex: Int32(index))
|
||||
}
|
||||
|
||||
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int) -> Value?
|
||||
{
|
||||
return Value.fastDecodeIfPresent(from: sqliteStatement, atUncheckedIndex: Int32(index))
|
||||
Value.fastDecodeIfPresent(from: sqliteStatement, atUncheckedIndex: Int32(index))
|
||||
}
|
||||
|
||||
func columnName(atUncheckedIndex index: Int) -> String {
|
||||
return statement.columnNames[index]
|
||||
statement.columnNames[index]
|
||||
}
|
||||
|
||||
func index(ofColumn name: String) -> Int? {
|
||||
@@ -1808,22 +1785,22 @@ private struct StatementRowImpl: RowImpl {
|
||||
}
|
||||
|
||||
func copiedRow(_ row: Row) -> Row {
|
||||
return Row(copiedFromSQLiteStatement: sqliteStatement, statement: statement)
|
||||
Row(copiedFromSQLiteStatement: sqliteStatement, statement: statement)
|
||||
}
|
||||
}
|
||||
|
||||
// This one is not optimized at all, since it is only used in fatal conversion errors, so far
|
||||
private struct SQLiteStatementRowImpl: RowImpl {
|
||||
let sqliteStatement: SQLiteStatement
|
||||
var count: Int { return Int(sqlite3_column_count(sqliteStatement)) }
|
||||
var isFetched: Bool { return true }
|
||||
var count: Int { Int(sqlite3_column_count(sqliteStatement)) }
|
||||
var isFetched: Bool { true }
|
||||
|
||||
func columnName(atUncheckedIndex index: Int) -> String {
|
||||
return String(cString: sqlite3_column_name(sqliteStatement, Int32(index)))
|
||||
String(cString: sqlite3_column_name(sqliteStatement, Int32(index)))
|
||||
}
|
||||
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
|
||||
return DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
}
|
||||
|
||||
func dataNoCopy(atUncheckedIndex index: Int) -> Data? {
|
||||
@@ -1848,13 +1825,9 @@ private struct SQLiteStatementRowImpl: RowImpl {
|
||||
|
||||
/// See Row.init()
|
||||
private struct EmptyRowImpl: RowImpl {
|
||||
var count: Int {
|
||||
return 0
|
||||
}
|
||||
var count: Int { 0 }
|
||||
|
||||
var isFetched: Bool {
|
||||
return false
|
||||
}
|
||||
var isFetched: Bool { false }
|
||||
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
|
||||
// Programmer error
|
||||
@@ -1866,11 +1839,7 @@ private struct EmptyRowImpl: RowImpl {
|
||||
fatalError("row index out of range")
|
||||
}
|
||||
|
||||
func index(ofColumn name: String) -> Int? {
|
||||
return nil
|
||||
}
|
||||
func index(ofColumn name: String) -> Int? { nil }
|
||||
|
||||
func copiedRow(_ row: Row) -> Row {
|
||||
return row
|
||||
}
|
||||
func copiedRow(_ row: Row) -> Row { row }
|
||||
}
|
||||
@@ -89,11 +89,11 @@ public struct LayoutedColumnMapping {
|
||||
}
|
||||
|
||||
func baseColumnIndex(atMappingIndex index: Int) -> Int {
|
||||
return layoutColumns[index].0
|
||||
layoutColumns[index].0
|
||||
}
|
||||
|
||||
func columnName(atMappingIndex index: Int) -> String {
|
||||
return layoutColumns[index].1
|
||||
layoutColumns[index].1
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,16 +104,12 @@ extension LayoutedColumnMapping: LayoutedRowAdapter {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns self.
|
||||
public var mapping: LayoutedColumnMapping {
|
||||
return self
|
||||
}
|
||||
public var mapping: LayoutedColumnMapping { self }
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns the empty dictionary.
|
||||
public var scopes: [String: LayoutedRowAdapter] {
|
||||
return [:]
|
||||
}
|
||||
public var scopes: [String: LayoutedRowAdapter] { [:] }
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
@@ -175,13 +171,13 @@ extension SelectStatement: RowLayout {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public var layoutColumns: [(Int, String)] {
|
||||
return Array(columnNames.enumerated())
|
||||
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)
|
||||
index(ofColumn: name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,7 +243,7 @@ extension RowAdapter {
|
||||
|
||||
extension RowAdapter {
|
||||
func baseColumnIndex(atIndex index: Int, layout: RowLayout) throws -> Int {
|
||||
return try layoutedAdapter(from: layout).mapping.baseColumnIndex(atMappingIndex: index)
|
||||
try layoutedAdapter(from: layout).mapping.baseColumnIndex(atMappingIndex: index)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -259,7 +255,7 @@ public struct EmptyRowAdapter: RowAdapter {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
return LayoutedColumnMapping(layoutColumns: [])
|
||||
LayoutedColumnMapping(layoutColumns: [])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -325,7 +321,7 @@ 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))
|
||||
LayoutedColumnMapping(layoutColumns: layout.layoutColumns.suffix(from: index))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -355,7 +351,7 @@ 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])
|
||||
LayoutedColumnMapping(layoutColumns: layout.layoutColumns[range])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -454,7 +450,7 @@ struct ChainedAdapter: RowAdapter {
|
||||
let second: RowAdapter
|
||||
|
||||
func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
return try second.layoutedAdapter(from: first.layoutedAdapter(from: layout).mapping)
|
||||
try second.layoutedAdapter(from: first.layoutedAdapter(from: layout).mapping)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -484,16 +480,12 @@ struct AdaptedRowImpl: RowImpl {
|
||||
self.mapping = adapter.mapping
|
||||
}
|
||||
|
||||
var count: Int {
|
||||
return mapping.layoutColumns.count
|
||||
}
|
||||
var count: Int { mapping.layoutColumns.count }
|
||||
|
||||
var isFetched: Bool {
|
||||
return base.isFetched
|
||||
}
|
||||
var isFetched: Bool { base.isFetched }
|
||||
|
||||
func scopes(prefetchedRows: Row.PrefetchedRowsView) -> Row.ScopesView {
|
||||
return Row.ScopesView(row: base, scopes: adapter.scopes, prefetchedRows: prefetchedRows)
|
||||
Row.ScopesView(row: base, scopes: adapter.scopes, prefetchedRows: prefetchedRows)
|
||||
}
|
||||
|
||||
func hasNull(atUncheckedIndex index: Int) -> Bool {
|
||||
@@ -528,15 +520,15 @@ struct AdaptedRowImpl: RowImpl {
|
||||
}
|
||||
|
||||
func columnName(atUncheckedIndex index: Int) -> String {
|
||||
return mapping.columnName(atMappingIndex: index)
|
||||
mapping.columnName(atMappingIndex: index)
|
||||
}
|
||||
|
||||
func index(ofColumn name: String) -> Int? {
|
||||
return mapping.layoutIndex(ofColumn: name)
|
||||
mapping.layoutIndex(ofColumn: name)
|
||||
}
|
||||
|
||||
func copiedRow(_ row: Row) -> Row {
|
||||
return Row(base: base.copy(), adapter: adapter)
|
||||
Row(base: base.copy(), adapter: adapter)
|
||||
}
|
||||
|
||||
func unscopedRow(_ row: Row) -> Row {
|
||||
@@ -545,6 +537,6 @@ struct AdaptedRowImpl: RowImpl {
|
||||
}
|
||||
|
||||
func unadaptedRow(_ row: Row) -> Row {
|
||||
return base.unadapted
|
||||
base.unadapted
|
||||
}
|
||||
}
|
||||
@@ -1,33 +1,24 @@
|
||||
#if swift(>=5.0)
|
||||
/// :nodoc:
|
||||
public struct SQLInterpolation: StringInterpolationProtocol {
|
||||
var context = SQLGenerationContext.literalGenerationContext(withArguments: true)
|
||||
var sql: String
|
||||
var arguments: StatementArguments {
|
||||
get { return context.arguments! }
|
||||
set { context.arguments = newValue }
|
||||
}
|
||||
var elements: [SQLLiteral.Element]
|
||||
|
||||
public init(literalCapacity: Int, interpolationCount: Int) {
|
||||
sql = ""
|
||||
sql.reserveCapacity(literalCapacity + interpolationCount)
|
||||
elements = []
|
||||
elements.reserveCapacity(interpolationCount + 1)
|
||||
}
|
||||
|
||||
/// "SELECT * FROM player"
|
||||
public mutating func appendLiteral(_ sql: String) {
|
||||
self.sql += sql
|
||||
elements.append(.sql(sql))
|
||||
}
|
||||
|
||||
/// "SELECT * FROM \(sql: "player")"
|
||||
public mutating func appendInterpolation(sql: String, arguments: StatementArguments = StatementArguments()) {
|
||||
self.sql += sql
|
||||
self.arguments += arguments
|
||||
elements.append(.sql(sql, arguments))
|
||||
}
|
||||
|
||||
/// "SELECT * FROM player WHERE \(literal: condition)"
|
||||
public mutating func appendInterpolation(literal sqlLiteral: SQLLiteral) {
|
||||
sql += sqlLiteral.sql
|
||||
arguments += sqlLiteral.arguments
|
||||
elements.append(contentsOf: sqlLiteral.elements)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -10,8 +10,68 @@
|
||||
/// try db.execute(literal: query)
|
||||
/// }
|
||||
public struct SQLLiteral {
|
||||
public private(set) var sql: String
|
||||
public private(set) var arguments: StatementArguments
|
||||
/// SQLLiteral is an array of elements which can be qualified with
|
||||
/// table aliases.
|
||||
enum Element {
|
||||
case sql(String, StatementArguments = StatementArguments())
|
||||
case expression(SQLExpression)
|
||||
case selectable(SQLSelectable)
|
||||
case orderingTerm(SQLOrderingTerm)
|
||||
case subQuery(SQLLiteral)
|
||||
|
||||
fileprivate func sql(_ context: inout SQLGenerationContext) -> String {
|
||||
switch self {
|
||||
case let .sql(sql, arguments):
|
||||
if context.append(arguments: arguments) == false {
|
||||
// GRDB limitation: we don't know how to look for `?` in sql and
|
||||
// replace them with literals.
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
return sql
|
||||
case let .expression(expression):
|
||||
return expression.expressionSQL(&context, wrappedInParenthesis: false)
|
||||
case let .selectable(selectable):
|
||||
return selectable.resultColumnSQL(&context)
|
||||
case let .orderingTerm(orderingTerm):
|
||||
return orderingTerm.orderingTermSQL(&context)
|
||||
case let .subQuery(sqlLiteral):
|
||||
return "(" + sqlLiteral.sql(&context) + ")"
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func qualified(with alias: TableAlias) -> Element {
|
||||
switch self {
|
||||
case .sql:
|
||||
return self
|
||||
case let .expression(expression):
|
||||
return .expression(expression.qualifiedExpression(with: alias))
|
||||
case let .selectable(selectable):
|
||||
return .selectable(selectable.qualifiedSelectable(with: alias))
|
||||
case let .orderingTerm(orderingTerm):
|
||||
return .orderingTerm(orderingTerm.qualifiedOrdering(with: alias))
|
||||
case .subQuery:
|
||||
// subqueries are not requalified
|
||||
return self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public var sql: String {
|
||||
var context = SQLGenerationContext.sqlLiteralContext
|
||||
return sql(&context)
|
||||
}
|
||||
|
||||
public var arguments: StatementArguments {
|
||||
var context = SQLGenerationContext.sqlLiteralContext
|
||||
_ = sql(&context)
|
||||
return context.arguments
|
||||
}
|
||||
|
||||
private(set) var elements: [Element]
|
||||
|
||||
init(elements: [Element]) {
|
||||
self.elements = elements
|
||||
}
|
||||
|
||||
/// Creates an SQLLiteral from a plain SQL string, and eventual arguments.
|
||||
///
|
||||
@@ -21,15 +81,28 @@ public struct SQLLiteral {
|
||||
/// sql: "UPDATE player SET name = ? WHERE id = ?",
|
||||
/// arguments: [name, id])
|
||||
public init(sql: String, arguments: StatementArguments = StatementArguments()) {
|
||||
self.sql = sql
|
||||
self.arguments = arguments
|
||||
self.init(elements: [.sql(sql, arguments)])
|
||||
}
|
||||
|
||||
/// Returns a literal whose SQL is transformed by the given closure.
|
||||
public func mapSQL(_ transform: (String) throws -> String) rethrows -> SQLLiteral {
|
||||
var result = self
|
||||
result.sql = try transform(sql)
|
||||
return result
|
||||
/// Creates an SQLLiteral from an SQL expression.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let columnLiteral = SQLLiteral(Column("username"))
|
||||
/// let suffixLiteral = SQLLiteral("@example.com".databaseValue)
|
||||
/// let emailLiteral = [columnLiteral, suffixLiteral].joined(separator: " || ")
|
||||
/// let request = User.select(emailLiteral.sqlExpression)
|
||||
/// let emails = try String.fetchAll(db, request)
|
||||
public init(_ expression: SQLExpression) {
|
||||
self.init(elements: [.expression(expression)])
|
||||
}
|
||||
|
||||
func sql(_ context: inout SQLGenerationContext) -> String {
|
||||
elements.map { $0.sql(&context) }.joined()
|
||||
}
|
||||
|
||||
fileprivate func qualified(with alias: TableAlias) -> SQLLiteral {
|
||||
SQLLiteral(elements: elements.map { $0.qualified(with: alias) })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,8 +125,7 @@ extension SQLLiteral {
|
||||
/// var query: SQLLiteral = "SELECT * FROM player "
|
||||
/// query += "WHERE name = \(name)"
|
||||
public static func += (lhs: inout SQLLiteral, rhs: SQLLiteral) {
|
||||
lhs.sql += rhs.sql
|
||||
lhs.arguments += rhs.arguments
|
||||
lhs.elements += rhs.elements
|
||||
}
|
||||
|
||||
/// Appends an SQLLiteral to the receiver.
|
||||
@@ -75,6 +147,25 @@ extension SQLLiteral {
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLLiteral {
|
||||
/// Creates a literal SQL expression.
|
||||
///
|
||||
/// SQLLiteral(sql: "1 + 2").sqlExpression
|
||||
/// SQLLiteral(sql: "? + ?", arguments: [1, 2]).sqlExpression
|
||||
/// SQLLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]).sqlExpression
|
||||
public var sqlExpression: SQLExpression {
|
||||
_SQLExpressionLiteral(sqlLiteral: self)
|
||||
}
|
||||
|
||||
var sqlSelectable: SQLSelectable {
|
||||
_SQLSelectionLiteral(sqlLiteral: self)
|
||||
}
|
||||
|
||||
var sqlOrderingTerm: SQLOrderingTerm {
|
||||
_SQLOrderingLiteral(sqlLiteral: self)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence where Element == SQLLiteral {
|
||||
/// Returns the concatenated SQLLiteral of this sequence of literals,
|
||||
/// inserting the given separator between each element.
|
||||
@@ -86,25 +177,17 @@ extension Sequence where Element == SQLLiteral {
|
||||
/// ]
|
||||
/// let query = components.joined(separator: " ")
|
||||
public func joined(separator: String = "") -> SQLLiteral {
|
||||
var sql = ""
|
||||
var arguments = StatementArguments()
|
||||
var first = true
|
||||
for literal in self {
|
||||
if first {
|
||||
first = false
|
||||
} else {
|
||||
sql += separator
|
||||
}
|
||||
sql += literal.sql
|
||||
arguments += literal.arguments
|
||||
if separator.isEmpty {
|
||||
return SQLLiteral(elements: flatMap(\.elements))
|
||||
} else {
|
||||
return SQLLiteral(elements: Array(map(\.elements).joined(separator: CollectionOfOne(.sql(separator)))))
|
||||
}
|
||||
return SQLLiteral(sql: sql, arguments: arguments)
|
||||
}
|
||||
}
|
||||
|
||||
extension Collection where Element == SQLLiteral {
|
||||
/// Returns the concatenated SQLLiteral of this collection of literals,
|
||||
/// inserting the given separator between each element.
|
||||
/// inserting the given SQL separator between each element.
|
||||
///
|
||||
/// let components: [SQLLiteral] = [
|
||||
/// "UPDATE player",
|
||||
@@ -113,15 +196,16 @@ extension Collection where Element == SQLLiteral {
|
||||
/// ]
|
||||
/// let query = components.joined(separator: " ")
|
||||
public func joined(separator: String = "") -> SQLLiteral {
|
||||
let sql = map { $0.sql }.joined(separator: separator)
|
||||
let arguments = reduce(into: StatementArguments()) { $0 += $1.arguments }
|
||||
return SQLLiteral(sql: sql, arguments: arguments)
|
||||
if separator.isEmpty {
|
||||
return SQLLiteral(elements: flatMap(\.elements))
|
||||
} else {
|
||||
return SQLLiteral(elements: Array(map(\.elements).joined(separator: CollectionOfOne(.sql(separator)))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ExpressibleByStringInterpolation
|
||||
|
||||
#if swift(>=5.0)
|
||||
extension SQLLiteral: ExpressibleByStringInterpolation {
|
||||
/// :nodoc
|
||||
public init(unicodeScalarLiteral: String) {
|
||||
@@ -140,7 +224,111 @@ extension SQLLiteral: ExpressibleByStringInterpolation {
|
||||
|
||||
/// :nodoc:
|
||||
public init(stringInterpolation sqlInterpolation: SQLInterpolation) {
|
||||
self.init(sql: sqlInterpolation.sql, arguments: sqlInterpolation.arguments)
|
||||
self.init(elements: sqlInterpolation.elements)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - _SQLExpressionLiteral
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// SQLExpressionLiteral is an expression built from a raw SQL snippet.
|
||||
///
|
||||
/// SQLExpressionLiteral(sql: "1 + 2")
|
||||
///
|
||||
/// The SQL literal may contain `?` and colon-prefixed arguments:
|
||||
///
|
||||
/// SQLExpressionLiteral(sql: "? + ?", arguments: [1, 2])
|
||||
/// SQLExpressionLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2])
|
||||
private struct _SQLExpressionLiteral: SQLExpression {
|
||||
private let sqlLiteral: SQLLiteral
|
||||
|
||||
// Prefer SQLLiteral.sqlExpression
|
||||
init(sqlLiteral: SQLLiteral) {
|
||||
self.sqlLiteral = sqlLiteral
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
|
||||
if wrappedInParenthesis {
|
||||
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
|
||||
}
|
||||
return sqlLiteral.sql(&context)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
sqlLiteral.qualified(with: alias).sqlExpression
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - _SQLSelectionLiteral
|
||||
|
||||
private struct _SQLSelectionLiteral: SQLSelectable {
|
||||
private let sqlLiteral: SQLLiteral
|
||||
|
||||
// Prefer SQLLiteral.sqlSelectable
|
||||
fileprivate init(sqlLiteral: SQLLiteral) {
|
||||
self.sqlLiteral = sqlLiteral
|
||||
}
|
||||
|
||||
func resultColumnSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
sqlLiteral.sql(&context)
|
||||
}
|
||||
|
||||
func countedSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
fatalError("""
|
||||
Selection literals can't be counted. \
|
||||
To resolve this error, select one or several literal expressions instead. \
|
||||
See SQLLiteral.sqlExpression.
|
||||
""")
|
||||
}
|
||||
|
||||
func count(distinct: Bool) -> SQLCount? {
|
||||
fatalError("""
|
||||
Selection literals can't be counted. \
|
||||
To resolve this error, select one or several literal expressions instead. \
|
||||
See SQLLiteral.sqlExpression.
|
||||
""")
|
||||
}
|
||||
|
||||
func columnCount(_ db: Database) throws -> Int {
|
||||
fatalError("""
|
||||
Selection literals don't known how many columns they contain. \
|
||||
To resolve this error, select one or several literal expressions instead. \
|
||||
See SQLLiteral.sqlExpression.
|
||||
""")
|
||||
}
|
||||
|
||||
func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable {
|
||||
sqlLiteral.qualified(with: alias).sqlSelectable
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - _SQLOrderingLiteral
|
||||
|
||||
private struct _SQLOrderingLiteral: SQLOrderingTerm {
|
||||
private let sqlLiteral: SQLLiteral
|
||||
|
||||
// Prefer SQLLiteral.sqlOrderingTerm
|
||||
fileprivate init(sqlLiteral: SQLLiteral) {
|
||||
self.sqlLiteral = sqlLiteral
|
||||
}
|
||||
|
||||
var reversed: SQLOrderingTerm {
|
||||
fatalError("""
|
||||
Ordering literals can't be reversed. \
|
||||
To resolve this error, order by expression literals instead.
|
||||
""")
|
||||
}
|
||||
|
||||
func orderingTermSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
sqlLiteral.sql(&context)
|
||||
}
|
||||
|
||||
func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm {
|
||||
sqlLiteral.qualified(with: alias).sqlOrderingTerm
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -19,19 +19,19 @@ public struct SQLRequest<T>: FetchRequest {
|
||||
/// let id = 42
|
||||
/// let request: SQLRequest<Player> = "SELECT * FROM player WHERE id = \(id)"
|
||||
/// request.sql // "SELECT * FROM player WHERE id = ?"
|
||||
public var sql: String { return sqlLiteral.sql }
|
||||
public var sql: String { sqlLiteral.sql }
|
||||
|
||||
/// The request argument
|
||||
///
|
||||
/// let id = 42
|
||||
/// let request: SQLRequest<Player> = "SELECT * FROM player WHERE id = \(id)"
|
||||
/// request.arguments // [42]
|
||||
public var arguments: StatementArguments { return sqlLiteral.arguments }
|
||||
public var arguments: StatementArguments { sqlLiteral.arguments }
|
||||
|
||||
/// The request adapter
|
||||
public var adapter: RowAdapter?
|
||||
|
||||
private var sqlLiteral: SQLLiteral
|
||||
private(set) var sqlLiteral: SQLLiteral
|
||||
private let cache: Cache?
|
||||
|
||||
/// Creates a request from an SQL string, optional arguments, and
|
||||
@@ -146,21 +146,22 @@ public struct SQLRequest<T>: FetchRequest {
|
||||
///
|
||||
/// :nodoc:
|
||||
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
|
||||
var context = SQLGenerationContext.sqlLiteralContext
|
||||
let sql = sqlLiteral.sql(&context)
|
||||
let statement: SelectStatement
|
||||
switch cache {
|
||||
case .none:
|
||||
statement = try db.makeSelectStatement(sql: sqlLiteral.sql)
|
||||
statement = try db.makeSelectStatement(sql: sql)
|
||||
case .public?:
|
||||
statement = try db.cachedSelectStatement(sql: sqlLiteral.sql)
|
||||
statement = try db.cachedSelectStatement(sql: sql)
|
||||
case .internal?:
|
||||
statement = try db.internalCachedSelectStatement(sql: sqlLiteral.sql)
|
||||
statement = try db.internalCachedSelectStatement(sql: sql)
|
||||
}
|
||||
try statement.setArgumentsWithValidation(sqlLiteral.arguments)
|
||||
try statement.setArguments(context.arguments)
|
||||
return PreparedRequest(statement: statement, adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
#if swift(>=5.0)
|
||||
extension SQLRequest: ExpressibleByStringInterpolation {
|
||||
/// :nodoc
|
||||
public init(unicodeScalarLiteral: String) {
|
||||
@@ -182,4 +183,3 @@ extension SQLRequest: ExpressibleByStringInterpolation {
|
||||
self.init(literal: SQLLiteral(stringInterpolation: sqlInterpolation))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -53,10 +53,10 @@ final class SchedulingWatchdog {
|
||||
}
|
||||
|
||||
static var current: SchedulingWatchdog? {
|
||||
return DispatchQueue.getSpecific(key: watchDogKey)
|
||||
DispatchQueue.getSpecific(key: watchDogKey)
|
||||
}
|
||||
|
||||
func allows(_ db: Database) -> Bool {
|
||||
return allowedDatabases.contains { $0 === db }
|
||||
allowedDatabases.contains { $0 === db }
|
||||
}
|
||||
}
|
||||
@@ -6,9 +6,7 @@ final class SerializedDatabase {
|
||||
private let db: Database
|
||||
|
||||
/// The database configuration
|
||||
var configuration: Configuration {
|
||||
return db.configuration
|
||||
}
|
||||
var configuration: Configuration { db.configuration }
|
||||
|
||||
/// The path to the database file
|
||||
var path: String
|
||||
@@ -186,9 +184,22 @@ final class SerializedDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Asynchronously executes a block in the serialized dispatch queue,
|
||||
/// without retaining self.
|
||||
func weakAsync(_ block: @escaping (Database?) -> Void) {
|
||||
queue.async { [weak self] in
|
||||
if let self = self {
|
||||
block(self.db)
|
||||
self.preconditionNoUnsafeTransactionLeft(self.db)
|
||||
} else {
|
||||
block(nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if any only if the current dispatch queue is valid.
|
||||
var onValidQueue: Bool {
|
||||
return SchedulingWatchdog.current?.allows(db) ?? false
|
||||
SchedulingWatchdog.current?.allows(db) ?? false
|
||||
}
|
||||
|
||||
/// Executes the block in the current queue.
|
||||
@@ -199,6 +210,21 @@ final class SerializedDatabase {
|
||||
return try block(db)
|
||||
}
|
||||
|
||||
func interrupt() {
|
||||
// Intentionally not scheduled in our serial queue
|
||||
db.interrupt()
|
||||
}
|
||||
|
||||
func suspend() {
|
||||
// Intentionally not scheduled in our serial queue
|
||||
db.suspend()
|
||||
}
|
||||
|
||||
func resume() {
|
||||
// Intentionally not scheduled in our serial queue
|
||||
db.resume()
|
||||
}
|
||||
|
||||
/// Fatal error if current dispatch queue is not valid.
|
||||
func preconditionValidQueue(
|
||||
_ message: @autoclosure() -> String = "Database was not used on the correct thread.",
|
||||
|
||||
@@ -1,11 +1,4 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// A raw SQLite statement, suitable for the SQLite C API.
|
||||
public typealias SQLiteStatement = OpaquePointer
|
||||
@@ -31,6 +24,16 @@ public class Statement {
|
||||
.trimmingCharacters(in: .sqlStatementSeparators)
|
||||
}
|
||||
|
||||
// Selected region is computed during statement compilation, and maybe
|
||||
// optimized for select statements compiled by QueryInterfaceRequest, in
|
||||
// order to perform focused database observation. See
|
||||
// SQLQueryGenerator.optimizedSelectedRegion(_:_:)
|
||||
var selectedRegion = DatabaseRegion()
|
||||
|
||||
var isReadonly: Bool {
|
||||
sqlite3_stmt_readonly(sqliteStatement) != 0
|
||||
}
|
||||
|
||||
unowned let database: Database
|
||||
|
||||
/// Creates a prepared statement. Returns nil if the compiled string is
|
||||
@@ -84,6 +87,7 @@ public class Statement {
|
||||
|
||||
self.database = database
|
||||
self.sqliteStatement = statement
|
||||
self.selectedRegion = authorizer.selectedRegion
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -120,23 +124,57 @@ public class Statement {
|
||||
|
||||
/// The statement arguments.
|
||||
public var arguments: StatementArguments {
|
||||
get { return _arguments }
|
||||
get { _arguments }
|
||||
set {
|
||||
// Force arguments validity: it is a programmer error to provide
|
||||
// arguments that do not match the statement.
|
||||
try! setArgumentsWithValidation(newValue)
|
||||
try! setArguments(newValue)
|
||||
}
|
||||
}
|
||||
|
||||
/// Throws a DatabaseError of code SQLITE_ERROR if arguments don't fill all
|
||||
/// statement arguments.
|
||||
public func validate(arguments: StatementArguments) throws {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let statement = try db.makeUpdateArgument(sql: """
|
||||
/// INSERT INTO player (id, name) VALUES (?, ?)
|
||||
/// """)
|
||||
///
|
||||
/// // OK
|
||||
/// statement.validateArguments([1, "Arthur"])
|
||||
///
|
||||
/// // Throws
|
||||
/// statement.validateArguments([1])
|
||||
///
|
||||
/// See also setArguments(_:)
|
||||
public func validateArguments(_ arguments: StatementArguments) throws {
|
||||
var arguments = arguments
|
||||
_ = try arguments.extractBindings(forStatement: self, allowingRemainingValues: false)
|
||||
}
|
||||
|
||||
/// Set arguments without any validation. Trades safety for performance.
|
||||
public func unsafeSetArguments(_ arguments: StatementArguments) {
|
||||
///
|
||||
/// Only call this method if you are sure input arguments match all expected
|
||||
/// arguments of the statement.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let statement = try db.makeUpdateArgument(sql: """
|
||||
/// INSERT INTO player (id, name) VALUES (?, ?)
|
||||
/// """)
|
||||
///
|
||||
/// // OK
|
||||
/// statement.setUncheckedArguments([1, "Arthur"])
|
||||
///
|
||||
/// // OK
|
||||
/// let arguments: StatementArguments = ... // some untrusted arguments
|
||||
/// try statement.validateArguments(arguments)
|
||||
/// statement.setUncheckedArguments(arguments)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// statement.setUncheckedArguments([1])
|
||||
public func setUncheckedArguments(_ arguments: StatementArguments) {
|
||||
_arguments = arguments
|
||||
argumentsNeedValidation = false
|
||||
|
||||
@@ -155,14 +193,28 @@ public class Statement {
|
||||
}
|
||||
}
|
||||
|
||||
func setArgumentsWithValidation(_ arguments: StatementArguments) throws {
|
||||
/// Set the statement arguments, or throws a DatabaseError of code
|
||||
/// SQLITE_ERROR if arguments don't fill all statement arguments.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let statement = try db.makeUpdateArgument(sql: """
|
||||
/// INSERT INTO player (id, name) VALUES (?, ?)
|
||||
/// """)
|
||||
///
|
||||
/// // OK
|
||||
/// try statement.setArguments([1, "Arthur"])
|
||||
///
|
||||
/// // Throws an error
|
||||
/// try statement.setArguments([1])
|
||||
public func setArguments(_ arguments: StatementArguments) throws {
|
||||
// Validate
|
||||
_arguments = arguments
|
||||
var arguments = arguments
|
||||
let bindings = try arguments.extractBindings(forStatement: self, allowingRemainingValues: false)
|
||||
argumentsNeedValidation = false
|
||||
var consumedArguments = arguments
|
||||
let bindings = try consumedArguments.extractBindings(forStatement: self, allowingRemainingValues: false)
|
||||
|
||||
// Apply
|
||||
_arguments = arguments
|
||||
argumentsNeedValidation = false
|
||||
try reset()
|
||||
clearBindings()
|
||||
for (index, dbValue) in zip(Int32(1)..., bindings) {
|
||||
@@ -183,15 +235,9 @@ public class Statement {
|
||||
case .string(let string):
|
||||
code = sqlite3_bind_text(sqliteStatement, index, string, -1, SQLITE_TRANSIENT)
|
||||
case .blob(let data):
|
||||
#if swift(>=5.0)
|
||||
code = data.withUnsafeBytes {
|
||||
sqlite3_bind_blob(sqliteStatement, index, $0.baseAddress, Int32($0.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
#else
|
||||
code = data.withUnsafeBytes {
|
||||
sqlite3_bind_blob(sqliteStatement, index, $0, Int32(data.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// It looks like sqlite3_bind_xxx() functions do not access the file system.
|
||||
@@ -216,9 +262,9 @@ public class Statement {
|
||||
// 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! setArguments(arguments)
|
||||
} else if argumentsNeedValidation {
|
||||
try! validate(arguments: self.arguments)
|
||||
try! validateArguments(self.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -276,13 +322,6 @@ extension Statement {
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
/// }
|
||||
public final class SelectStatement: Statement {
|
||||
// Database region is computed during statement compilation, and maybe
|
||||
// optimized when statement is compiled for a QueryInterfaceRequest, in
|
||||
// order to perform focused database observation. See
|
||||
// SQLQueryGenerator.optimizedDatabaseRegion(_:_:)
|
||||
/// The database region that the statement looks into.
|
||||
public internal(set) var databaseRegion = DatabaseRegion()
|
||||
|
||||
/// Creates a prepared statement. Returns nil if the compiled string is
|
||||
/// blank or empty.
|
||||
///
|
||||
@@ -315,13 +354,14 @@ public final class SelectStatement: Statement {
|
||||
GRDBPrecondition(
|
||||
authorizer.transactionEffect == nil,
|
||||
"Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
|
||||
|
||||
self.databaseRegion = authorizer.databaseRegion
|
||||
}
|
||||
|
||||
/// The database region that the statement looks into.
|
||||
public var databaseRegion: DatabaseRegion { selectedRegion }
|
||||
|
||||
/// The number of columns in the resulting rows.
|
||||
public var columnCount: Int {
|
||||
return Int(sqlite3_column_count(self.sqliteStatement))
|
||||
Int(sqlite3_column_count(self.sqliteStatement))
|
||||
}
|
||||
|
||||
/// The column names, ordered from left to right.
|
||||
@@ -340,14 +380,14 @@ public final class SelectStatement: Statement {
|
||||
/// Returns the index of the leftmost column named `name`, in a
|
||||
/// case-insensitive way.
|
||||
public func index(ofColumn name: String) -> Int? {
|
||||
return columnIndexes[name.lowercased()]
|
||||
columnIndexes[name.lowercased()]
|
||||
}
|
||||
|
||||
/// Creates a cursor over the statement which does not produce any
|
||||
/// value. Each call to the next() cursor method calls the sqlite3_step()
|
||||
/// C function.
|
||||
func makeCursor(arguments: StatementArguments? = nil) -> StatementCursor {
|
||||
return StatementCursor(statement: self, arguments: arguments)
|
||||
func makeCursor(arguments: StatementArguments? = nil) throws -> StatementCursor {
|
||||
try StatementCursor(statement: self, arguments: arguments)
|
||||
}
|
||||
|
||||
/// Utility function for cursors
|
||||
@@ -384,13 +424,13 @@ final class StatementCursor: Cursor {
|
||||
var _done = false
|
||||
|
||||
// Use SelectStatement.makeCursor() instead
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil) {
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil) throws {
|
||||
_statement = statement
|
||||
_sqliteStatement = statement.sqliteStatement
|
||||
_statement.reset(withArguments: arguments)
|
||||
|
||||
// Assume cursor is created for iteration
|
||||
statement.database.selectStatementWillExecute(statement)
|
||||
try statement.database.selectStatementWillExecute(statement)
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -449,6 +489,25 @@ public final class UpdateStatement: Statement {
|
||||
private(set) var transactionEffect: TransactionEffect?
|
||||
private(set) var databaseEventKinds: [DatabaseEventKind] = []
|
||||
|
||||
var releasesDatabaseLock: Bool {
|
||||
guard let transactionEffect = transactionEffect else {
|
||||
return false
|
||||
}
|
||||
|
||||
switch transactionEffect {
|
||||
case .commitTransaction, .rollbackTransaction,
|
||||
.releaseSavepoint, .rollbackSavepoint:
|
||||
// Not technically correct:
|
||||
// - ROLLBACK TRANSACTION TO SAVEPOINT does not release any lock
|
||||
// - RELEASE SAVEPOINT does not always release lock
|
||||
//
|
||||
// But both move in the direction of releasing locks :-)
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a prepared statement. Returns nil if the compiled string is
|
||||
/// blank or empty.
|
||||
///
|
||||
@@ -583,7 +642,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
private(set) var namedValues: [String: DatabaseValue] = [:]
|
||||
|
||||
public var isEmpty: Bool {
|
||||
return values.isEmpty && namedValues.isEmpty
|
||||
values.isEmpty && namedValues.isEmpty
|
||||
}
|
||||
|
||||
|
||||
@@ -614,7 +673,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
/// - parameter sequence: A sequence of DatabaseValueConvertible values.
|
||||
/// - returns: A StatementArguments.
|
||||
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Element: DatabaseValueConvertible {
|
||||
values = sequence.map { $0.databaseValue }
|
||||
values = sequence.map(\.databaseValue)
|
||||
}
|
||||
|
||||
/// Creates statement arguments from any array. The result is nil unless all
|
||||
@@ -911,7 +970,7 @@ extension StatementArguments {
|
||||
extension StatementArguments {
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
let valuesDescriptions = values.map { $0.description }
|
||||
let valuesDescriptions = values.map(\.description)
|
||||
let namedValuesDescriptions = namedValues.map { (key, value) -> String in
|
||||
"\(String(reflecting: key)): \(value)"
|
||||
}
|
||||
|
||||
@@ -1,13 +1,6 @@
|
||||
#if os(Linux)
|
||||
import Glibc
|
||||
#endif
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// A protocol around sqlite3_set_authorizer
|
||||
protocol StatementAuthorizer: AnyObject {
|
||||
@@ -23,7 +16,7 @@ protocol StatementAuthorizer: AnyObject {
|
||||
/// A class that gathers information about one statement during its compilation.
|
||||
final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
/// What this statements reads
|
||||
var databaseRegion = DatabaseRegion()
|
||||
var selectedRegion = DatabaseRegion()
|
||||
|
||||
/// What this statements writes
|
||||
var databaseEventKinds: [DatabaseEventKind] = []
|
||||
@@ -66,7 +59,8 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
SQLITE_CREATE_INDEX, SQLITE_CREATE_TABLE,
|
||||
SQLITE_CREATE_TEMP_INDEX, SQLITE_CREATE_TEMP_TABLE,
|
||||
SQLITE_CREATE_TEMP_TRIGGER, SQLITE_CREATE_TEMP_VIEW,
|
||||
SQLITE_CREATE_TRIGGER, SQLITE_CREATE_VIEW:
|
||||
SQLITE_CREATE_TRIGGER, SQLITE_CREATE_VIEW,
|
||||
SQLITE_CREATE_VTABLE:
|
||||
invalidatesDatabaseSchemaCache = true
|
||||
return SQLITE_OK
|
||||
|
||||
@@ -75,10 +69,10 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
guard let columnName = cString2.map(String.init) else { return SQLITE_OK }
|
||||
if columnName.isEmpty {
|
||||
// SELECT COUNT(*) FROM table
|
||||
databaseRegion.formUnion(DatabaseRegion(table: tableName))
|
||||
selectedRegion.formUnion(DatabaseRegion(table: tableName))
|
||||
} else {
|
||||
// SELECT column FROM table
|
||||
databaseRegion.formUnion(DatabaseRegion(table: tableName, columns: [columnName]))
|
||||
selectedRegion.formUnion(DatabaseRegion(table: tableName, columns: [columnName]))
|
||||
}
|
||||
return SQLITE_OK
|
||||
|
||||
@@ -144,7 +138,7 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
guard sqlite3_libversion_number() < 3019000 else { return SQLITE_OK }
|
||||
guard let cString2 = cString2 else { return SQLITE_OK }
|
||||
if sqlite3_stricmp(cString2, "COUNT") == 0 {
|
||||
databaseRegion = .fullDatabase
|
||||
selectedRegion = .fullDatabase
|
||||
}
|
||||
return SQLITE_OK
|
||||
|
||||
@@ -192,9 +186,6 @@ final class TruncateOptimizationBlocker: StatementAuthorizer {
|
||||
|
||||
private struct AuthorizerActionCode: RawRepresentable, CustomStringConvertible {
|
||||
let rawValue: Int32
|
||||
init(rawValue: Int32) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
var description: String {
|
||||
switch rawValue {
|
||||
|
||||
@@ -1,11 +1,3 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// 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
|
||||
@@ -79,7 +71,7 @@ public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & Sta
|
||||
_statement.reset(withArguments: arguments)
|
||||
|
||||
// Assume cursor is created for iteration
|
||||
statement.database.selectStatementWillExecute(statement)
|
||||
try statement.database.selectStatementWillExecute(statement)
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -138,7 +130,7 @@ public final class FastNullableDatabaseValueCursor<Value>: Cursor
|
||||
_statement.reset(withArguments: arguments)
|
||||
|
||||
// Assume cursor is created for iteration
|
||||
statement.database.selectStatementWillExecute(statement)
|
||||
try statement.database.selectStatementWillExecute(statement)
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -202,7 +194,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> FastDatabaseValueCursor<Self>
|
||||
{
|
||||
return try FastDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
try FastDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from a prepared statement.
|
||||
@@ -222,7 +214,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Self]
|
||||
{
|
||||
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from a prepared statement.
|
||||
@@ -281,7 +273,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> FastDatabaseValueCursor<Self>
|
||||
{
|
||||
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from an SQL query.
|
||||
@@ -302,7 +294,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Self]
|
||||
{
|
||||
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from an SQL query.
|
||||
@@ -323,7 +315,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Self?
|
||||
{
|
||||
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -408,7 +400,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> FastDatabaseValueCursor<RowDecoder> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched values.
|
||||
@@ -420,7 +412,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
return try RowDecoder.fetchAll(db, self)
|
||||
try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched value.
|
||||
@@ -435,7 +427,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
return try RowDecoder.fetchOne(db, self)
|
||||
try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -479,7 +471,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> FastNullableDatabaseValueCursor<Wrapped>
|
||||
{
|
||||
return try FastNullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
try FastNullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a prepared statement.
|
||||
@@ -499,7 +491,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Wrapped?]
|
||||
{
|
||||
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -533,7 +525,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> FastNullableDatabaseValueCursor<Wrapped>
|
||||
{
|
||||
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from an SQL query.
|
||||
@@ -554,7 +546,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Wrapped?]
|
||||
{
|
||||
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -606,7 +598,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
extension FetchRequest
|
||||
where
|
||||
RowDecoder: _OptionalProtocol,
|
||||
RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible
|
||||
RowDecoder.Wrapped: DatabaseValueConvertible & StatementColumnConvertible
|
||||
{
|
||||
|
||||
// MARK: Fetching Optional values
|
||||
@@ -627,8 +619,8 @@ extension FetchRequest
|
||||
/// - 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 -> FastNullableDatabaseValueCursor<RowDecoder._Wrapped> {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
|
||||
public func fetchCursor(_ db: Database) throws -> FastNullableDatabaseValueCursor<RowDecoder.Wrapped> {
|
||||
try Optional<RowDecoder.Wrapped>.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched optional values.
|
||||
@@ -639,7 +631,22 @@ extension FetchRequest
|
||||
/// - 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)
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder.Wrapped?] {
|
||||
try Optional<RowDecoder.Wrapped>.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched value.
|
||||
///
|
||||
/// The result is nil if the request returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches String?
|
||||
/// let string = try request.fetchOne(db) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder.Wrapped? {
|
||||
try RowDecoder.Wrapped.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ extension CGFloat: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return Double(self).databaseValue
|
||||
Double(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a CGFloat initialized from *dbValue*, if possible.
|
||||
|
||||
@@ -1,11 +1,4 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// Data is convertible to and from DatabaseValue.
|
||||
extension Data: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
@@ -21,7 +14,7 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return DatabaseValue(storage: .blob(self))
|
||||
DatabaseValue(storage: .blob(self))
|
||||
}
|
||||
|
||||
/// Returns a Data initialized from *dbValue*, if it contains
|
||||
|
||||
@@ -1,14 +1,7 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// DatabaseDateComponents reads and stores DateComponents in the database.
|
||||
public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnConvertible, Codable {
|
||||
|
||||
/// The available formats for reading and storing date components.
|
||||
public enum Format: String {
|
||||
@@ -159,4 +152,30 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC
|
||||
|
||||
return SQLiteDateParser().components(from: string)
|
||||
}
|
||||
|
||||
// MARK: - Codable adoption
|
||||
|
||||
|
||||
/// Creates a new instance by decoding from the given decoder.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - decoder: The decoder to read data from.
|
||||
public init(from decoder: Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
let stringValue = try container.decode(String.self)
|
||||
guard let decodedValue = DatabaseDateComponents.fromDatabaseValue(stringValue.databaseValue) else {
|
||||
throw DecodingError.dataCorruptedError(in: container,
|
||||
debugDescription: "Unable to initialise databaseDateComponent")
|
||||
}
|
||||
self = decodedValue
|
||||
}
|
||||
|
||||
/// Encodes this value into the given encoder.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - encoder: The encoder to write data to.
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(String.fromDatabaseValue(databaseValue)!)
|
||||
}
|
||||
}
|
||||
@@ -17,12 +17,12 @@ extension DatabaseValueConvertible where Self: ReferenceConvertible, Self.Refere
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return (self as! ReferenceType).databaseValue
|
||||
(self as! ReferenceType).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a value initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
return ReferenceType.fromDatabaseValue(dbValue).flatMap { cast($0) }
|
||||
ReferenceType.fromDatabaseValue(dbValue).flatMap { cast($0) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,4 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
#if !os(Linux)
|
||||
/// NSDate is stored in the database using the format
|
||||
@@ -14,7 +7,7 @@ extension NSDate: 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 (self as Date).databaseValue
|
||||
(self as Date).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a date initialized from dbValue, if possible.
|
||||
@@ -42,7 +35,7 @@ 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
|
||||
storageDateFormatter.string(from: self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a date initialized from dbValue, if possible.
|
||||
|
||||
@@ -6,7 +6,7 @@ extension NSData: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return (self as Data).databaseValue
|
||||
(self as Data).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an NSData initialized from *dbValue*, if it contains
|
||||
|
||||
@@ -4,12 +4,8 @@ import Foundation
|
||||
extension NSNull: DatabaseValueConvertible {
|
||||
|
||||
/// Returns DatabaseValue.null.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return .null
|
||||
}
|
||||
public var databaseValue: DatabaseValue { .null }
|
||||
|
||||
/// Returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
return nil
|
||||
}
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { nil }
|
||||
}
|
||||
@@ -6,7 +6,7 @@ extension NSString: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return (self as String).databaseValue
|
||||
(self as String).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an NSString initialized from *dbValue*, if possible.
|
||||
|
||||