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 | ||
|
|
a67070dd9a | ||
|
|
f257fb7a4e | ||
|
|
3f79892fdb | ||
|
|
cd6d46e349 | ||
|
|
9ea160b116 | ||
|
|
8f03b5c8f3 | ||
|
|
3ce3f2fa71 | ||
|
|
d9c26a40b4 | ||
|
|
09e271de77 | ||
|
|
205dea122f | ||
|
|
2eb10aa19a | ||
|
|
63fc59fd7c | ||
|
|
bf6ee31491 | ||
|
|
146151ffd7 | ||
|
|
5b24f598a5 | ||
|
|
51a1c418a6 | ||
|
|
e1ff862ffc | ||
|
|
630a2c358a | ||
|
|
e0ea30041f | ||
|
|
58263e9b60 | ||
|
|
1e80aecfbd | ||
|
|
d5c6dde3d9 | ||
|
|
7819c9026a | ||
|
|
e6617c8e12 | ||
|
|
d03a01a84a | ||
|
|
90735fb3a7 | ||
|
|
264906221e | ||
|
|
be21704633 | ||
|
|
b68bb00033 | ||
|
|
1dd5c17bc7 | ||
|
|
c8a2c68728 | ||
|
|
f40c6511ef | ||
|
|
60aa6c2bf2 | ||
|
|
fe7446431b | ||
|
|
abe2a62d47 | ||
|
|
65d0f1edcc | ||
|
|
c09615bab0 | ||
|
|
218afa72c3 | ||
|
|
cb77fe2ed3 | ||
|
|
7345c5f2dd | ||
|
|
efdebf59d3 | ||
|
|
35d7490092 | ||
|
|
dd4a2c5d9c | ||
|
|
eae70f426e | ||
|
|
c7a6ca964c | ||
|
|
acb0004cea | ||
|
|
995d1b851a | ||
|
|
beab493dd5 | ||
|
|
1c76eb7e9f | ||
|
|
205398b65a | ||
|
|
61a6c5785f | ||
|
|
d983c6407c | ||
|
|
7cb78a4c86 | ||
|
|
733f6883d0 | ||
|
|
594874656a | ||
|
|
6142020c50 | ||
|
|
6f5b18854d | ||
|
|
b39c678a3d | ||
|
|
a8a85d9a1f | ||
|
|
182b92f010 | ||
|
|
a78f3699eb | ||
|
|
89bc509170 | ||
|
|
cfa615444e | ||
|
|
35389ed978 | ||
|
|
caacecfd83 | ||
|
|
924b460c7a | ||
|
|
60a9cf4942 | ||
|
|
f9f3080819 | ||
|
|
02c024e819 | ||
|
|
10249675ff | ||
|
|
b6553c0b59 | ||
|
|
dfd3e50b9c | ||
|
|
79b8f7ed1d | ||
|
|
f184c626e0 | ||
|
|
24ba40a77e | ||
|
|
66326d79a2 | ||
|
|
fcd6c100ee | ||
|
|
95b7879e33 | ||
|
|
404532f6f0 | ||
|
|
751262cdb3 | ||
|
|
0ac0d31796 | ||
|
|
9d5d7f0216 | ||
|
|
b59521e247 | ||
|
|
7dd90c4af3 | ||
|
|
b06e4ad298 | ||
|
|
ff21f86341 | ||
|
|
c89d41adbb | ||
|
|
b3e1bf6f05 | ||
|
|
fc57a69672 | ||
|
|
fdbc0c8ec8 | ||
|
|
e3edf6daec | ||
|
|
1b8f7b95f4 | ||
|
|
f756f39772 | ||
|
|
836f34297d | ||
|
|
cd6d2579a5 | ||
|
|
2892424006 | ||
|
|
856792d688 | ||
|
|
00115ba60c | ||
|
|
1cdddd35c8 | ||
|
|
ccaf4c942f | ||
|
|
9f9fcb1a8e | ||
|
|
b6955377c9 | ||
|
|
5f085f2df8 | ||
|
|
3cc5bb7c98 | ||
|
|
3dc4567233 | ||
|
|
37477adada | ||
|
|
a44afd79e0 | ||
|
|
61088ee2e7 | ||
|
|
a721917d95 | ||
|
|
a08b078c3e | ||
|
|
aa1cfb9020 | ||
|
|
0d961ce48e | ||
|
|
1b753802dd | ||
|
|
3f3bdde10c | ||
|
|
b2ea9e51d2 | ||
|
|
27a05028db | ||
|
|
725e16390b | ||
|
|
6b83ba3585 | ||
|
|
62e50b1a73 | ||
|
|
bf7192cef1 | ||
|
|
18d634b171 | ||
|
|
a5b5bccc61 | ||
|
|
988852a438 | ||
|
|
2313713603 | ||
|
|
6a5ce71c12 | ||
|
|
9872e945ba | ||
|
|
b3341cc552 | ||
|
|
0a1e3afa82 | ||
|
|
483728bfbf | ||
|
|
b459536b66 | ||
|
|
d990b47814 | ||
|
|
aa157a77d2 | ||
|
|
254f3760b4 | ||
|
|
896ec284e1 | ||
|
|
036178a55a | ||
|
|
3ff94c7607 | ||
|
|
5c125fae8b | ||
|
|
642089f41a | ||
|
|
6285a59926 | ||
|
|
4ba199f0aa | ||
|
|
75f3540b8f | ||
|
|
bfa1689d7d | ||
|
|
a1c96f9093 | ||
|
|
32842c22f0 | ||
|
|
8e764aadd2 | ||
|
|
ad9b32f9a2 | ||
|
|
cb9323480c | ||
|
|
cc7d19d925 | ||
|
|
c2e68d95fe | ||
|
|
7b3275ce45 | ||
|
|
9a69dbd8a1 | ||
|
|
f2198f5af7 | ||
|
|
8150dda951 | ||
|
|
d4928eff99 | ||
|
|
1f48405b5c | ||
|
|
55d4a9c029 | ||
|
|
e6bc1c40fe | ||
|
|
b9e2f35728 | ||
|
|
6fc7794e64 | ||
|
|
1d71b9f311 | ||
|
|
9f26777cc3 | ||
|
|
0b9fe9ae92 | ||
|
|
1ba4e8c771 | ||
|
|
aded6d206d | ||
|
|
d644f01557 | ||
|
|
eb112c912c | ||
|
|
d8b0b95842 | ||
|
|
8f66114042 | ||
|
|
943eca10a6 | ||
|
|
82f56ee596 | ||
|
|
00e2c2a626 | ||
|
|
c7e4492846 | ||
|
|
04a6e969a5 | ||
|
|
5b4a225dc3 | ||
|
|
e3efcc0d87 | ||
|
|
8580023eda | ||
|
|
473f6ff0d8 | ||
|
|
e495df0114 | ||
|
|
06d6c3866b | ||
|
|
da459386a0 | ||
|
|
1023f260b7 | ||
|
|
a6fa76a954 | ||
|
|
3e48eb703e | ||
|
|
7cf10bfb67 | ||
|
|
055e33b381 | ||
|
|
7fffc2791e | ||
|
|
4d3f0bd88b | ||
|
|
881d4c6bfc | ||
|
|
ba02713d78 | ||
|
|
6f6e382948 | ||
|
|
b7c7892a74 | ||
|
|
a6112a5ca2 | ||
|
|
d219f5589e | ||
|
|
01a1a7c962 | ||
|
|
8e38af9aae | ||
|
|
d28847bf3d | ||
|
|
24c25dfd04 | ||
|
|
18e09cda11 | ||
|
|
fb54c2ae45 | ||
|
|
a08e8f0ef6 | ||
|
|
bd81f6e7a6 | ||
|
|
eea8f7b1e9 | ||
|
|
c734eba245 | ||
|
|
71bf6fdbcf | ||
|
|
226410caf8 | ||
|
|
82d80d4120 | ||
|
|
80baa798d6 | ||
|
|
ba1142ac58 | ||
|
|
e279d287b9 | ||
|
|
87b474029e | ||
|
|
8af3b58e54 | ||
|
|
a770d46843 | ||
|
|
efaa387ee2 | ||
|
|
f849c38f43 | ||
|
|
ea43468a6f | ||
|
|
fd18a7b75d | ||
|
|
fe9c4381e0 | ||
|
|
0f2c5cd8a0 | ||
|
|
9c864bc768 | ||
|
|
dc146a431c | ||
|
|
c718889418 | ||
|
|
d61522ee5f | ||
|
|
c4481f4e79 | ||
|
|
731a83908d | ||
|
|
62a12d94ce | ||
|
|
4f025e59af | ||
|
|
2039cd4874 | ||
|
|
1b94c38b4f | ||
|
|
f556fc39ab | ||
|
|
a5c8f23ba4 | ||
|
|
af0ac156aa | ||
|
|
8d5cddd293 | ||
|
|
38599b007f | ||
|
|
5908c26a79 | ||
|
|
d32b5271bd | ||
|
|
55803b29b0 | ||
|
|
870d22fd95 | ||
|
|
c6cb92d757 | ||
|
|
3ab8a34d58 | ||
|
|
bd9104d29f | ||
|
|
e351b79526 | ||
|
|
a59f4ef096 | ||
|
|
bb959fa5c3 | ||
|
|
2b3e5a06db | ||
|
|
e58b652970 | ||
|
|
62f5bd1940 | ||
|
|
63cb9f2ad2 | ||
|
|
19cf569036 | ||
|
|
e23cb4ed76 | ||
|
|
bdf802ab34 | ||
|
|
507ae0dfdc | ||
|
|
56af3ceff6 | ||
|
|
4ffb59719a | ||
|
|
bb0c11f7d5 | ||
|
|
82c8958c44 | ||
|
|
e8ad3871f7 | ||
|
|
53aaca480e | ||
|
|
23678ab9da | ||
|
|
2996a24de9 | ||
|
|
dba8d636bb | ||
|
|
faa7bf7e53 | ||
|
|
05fdf5cfdd | ||
|
|
b4ef6a3dad | ||
|
|
0c709294a0 | ||
|
|
d15bb190eb | ||
|
|
ede4572da3 | ||
|
|
b4929bb638 | ||
|
|
52cd98547d | ||
|
|
5cced46a61 | ||
|
|
3f8e994501 | ||
|
|
ae60bc6e18 | ||
|
|
462e5eee24 | ||
|
|
c1a0b7f9e2 | ||
|
|
89001f11c3 | ||
|
|
026db8f19a | ||
|
|
2d1f218ec5 | ||
|
|
4d558488c0 | ||
|
|
bf73f0ded2 | ||
|
|
b8cc4c30f9 | ||
|
|
cf2a6763b5 | ||
|
|
e65e2a3bd1 | ||
|
|
56d355c903 | ||
|
|
35ceeebb3d | ||
|
|
d9e1a04cc2 | ||
|
|
d7a51c39ca | ||
|
|
756f1b9387 | ||
|
|
df6bb8761c | ||
|
|
b3215cc471 | ||
|
|
7defc8ea07 | ||
|
|
2b401fe745 | ||
|
|
3e4c6fd102 | ||
|
|
9946880c5e | ||
|
|
738ea4ed10 | ||
|
|
498c65a64c | ||
|
|
fbc50dd2d1 | ||
|
|
7802eb356d | ||
|
|
036e236dc0 | ||
|
|
ff2f8bd88e | ||
|
|
1d47fb16be | ||
|
|
5345ccd53e | ||
|
|
e1ee2afba1 | ||
|
|
d290102d9c | ||
|
|
de3f32b6ad | ||
|
|
cb517dc5c9 | ||
|
|
49d098eb7b | ||
|
|
caa624f56b | ||
|
|
c190b1355e | ||
|
|
335850c5fe | ||
|
|
2730f8f806 | ||
|
|
dc2871d5eb | ||
|
|
cdccac8c86 | ||
|
|
173c8af3ef | ||
|
|
3cea3db2b4 | ||
|
|
7526276f98 | ||
|
|
b9925d1620 | ||
|
|
68d4889864 | ||
|
|
c5cb8f44f3 | ||
|
|
309fa97606 | ||
|
|
a2ba53ab26 | ||
|
|
3a98f337bd | ||
|
|
8663a1bf3f | ||
|
|
fc13454f29 | ||
|
|
8cadb97b2f | ||
|
|
278e4190db | ||
|
|
d3fe40127c | ||
|
|
3f9b94f95e | ||
|
|
02e1793cc9 | ||
|
|
e40e37bd04 | ||
|
|
65de31a335 | ||
|
|
66552ebc77 | ||
|
|
4a79a20116 | ||
|
|
f03fd276f1 | ||
|
|
0e031cd5a9 | ||
|
|
cd3c84d19e | ||
|
|
29cfebdec0 | ||
|
|
d0e839c2b4 | ||
|
|
d18c65fbe5 | ||
|
|
07ade5ee75 | ||
|
|
3897e9824c | ||
|
|
0c2875a310 | ||
|
|
f7946834f1 | ||
|
|
0ad819902d | ||
|
|
b715ca5eb8 | ||
|
|
bc7c3e5eb1 | ||
|
|
9650783ea4 | ||
|
|
4b0e43f884 | ||
|
|
f120632e36 | ||
|
|
d42b515fb6 | ||
|
|
47b813057a | ||
|
|
1db76a9d85 | ||
|
|
a59546203f | ||
|
|
085f4c9597 | ||
|
|
bec731d763 | ||
|
|
b0be32be71 | ||
|
|
d774d353e7 | ||
|
|
44138c433f | ||
|
|
f502db40b0 | ||
|
|
86f7ab74a7 | ||
|
|
cea22f261e | ||
|
|
da34694663 | ||
|
|
085fd13ef6 | ||
|
|
50c9792eb2 | ||
|
|
795056a3b6 | ||
|
|
aca4db2c96 | ||
|
|
cdec1a4318 | ||
|
|
3971058dd8 | ||
|
|
b6f988194c | ||
|
|
ad24bd8021 | ||
|
|
096096684e | ||
|
|
038a8d2d88 | ||
|
|
5abd21fa4a | ||
|
|
a80d6731a8 | ||
|
|
e7ed67d41d | ||
|
|
da042eaae9 | ||
|
|
416d2cae1e | ||
|
|
ac85ffff84 | ||
|
|
e3d2559b9d | ||
|
|
c1a926e6dc | ||
|
|
b31f46cbc0 | ||
|
|
6b236ceb5c | ||
|
|
30812792df | ||
|
|
c1cbe51747 | ||
|
|
1416c6e179 | ||
|
|
91ff9ce0b8 | ||
|
|
5099305257 | ||
|
|
92c13c3ea8 | ||
|
|
872f394339 | ||
|
|
deaf60263d | ||
|
|
7e53901544 | ||
|
|
ce95590b8a | ||
|
|
c42cf38fc2 | ||
|
|
dc4a66fe2c | ||
|
|
c9ab5eb551 | ||
|
|
4e33b06f0b | ||
|
|
ff45864454 | ||
|
|
fb3c722724 | ||
|
|
6c93e1509d | ||
|
|
0680e5abd7 | ||
|
|
aefaa86302 | ||
|
|
ed509c5349 | ||
|
|
0232c8e792 | ||
|
|
cba1113a03 | ||
|
|
1b4c3808d1 | ||
|
|
ac583e8fdf | ||
|
|
fff7d1c49e | ||
|
|
0fe96619bf | ||
|
|
0440736f3b | ||
|
|
35e1aeb7a8 | ||
|
|
8fe3b18121 | ||
|
|
26259ef0f9 | ||
|
|
fb9244e5bb | ||
|
|
03d9727f61 | ||
|
|
e7a590b82b | ||
|
|
1b5e94a050 | ||
|
|
3669fadecb | ||
|
|
7ed4b799b7 | ||
|
|
bba9d42433 | ||
|
|
6a5d3fe85b | ||
|
|
957d7b4c86 | ||
|
|
2dd5058878 | ||
|
|
a02bbc5748 | ||
|
|
bef13a7d0e | ||
|
|
b0e140d4bb | ||
|
|
ca9ecd7f66 | ||
|
|
4729405625 | ||
|
|
7d92c665f0 | ||
|
|
4f4a5d92c7 | ||
|
|
5bb54f0049 | ||
|
|
543dfe9e69 | ||
|
|
8b8722f376 | ||
|
|
1d75863c9a | ||
|
|
6fa452b68c | ||
|
|
ab000d7a4f | ||
|
|
680f3ad20c | ||
|
|
b6b1f9b3e8 | ||
|
|
05a547f2df | ||
|
|
1602a37d08 | ||
|
|
49a7b2091c | ||
|
|
bf94fc168e | ||
|
|
d2aea2e3a7 | ||
|
|
0159d75b38 | ||
|
|
c8755a91e8 | ||
|
|
b0e4f286cb | ||
|
|
f641e2fc39 | ||
|
|
1402100d26 | ||
|
|
eda36829d0 | ||
|
|
48017b2de2 | ||
|
|
862886fa0a | ||
|
|
68221af5c3 | ||
|
|
b3e547a347 | ||
|
|
498c153be1 | ||
|
|
7ed8168f11 | ||
|
|
547fc98358 | ||
|
|
6397d5757e | ||
|
|
6d71f8b17c | ||
|
|
cafb329d6e | ||
|
|
071fdd3711 | ||
|
|
0cca73cdfc | ||
|
|
31e59f3968 | ||
|
|
d6e0dcafcb | ||
|
|
203130da31 | ||
|
|
af4a83115b | ||
|
|
0ad7d5e894 | ||
|
|
6e7a923d6e | ||
|
|
490a124cbf |
No files matched your search
@@ -2,4 +2,4 @@ source 'https://rubygems.org'
|
||||
|
||||
gem 'xcpretty'
|
||||
gem 'xcpretty-travis-formatter'
|
||||
gem 'cocoapods', '~> 1.6'
|
||||
gem 'cocoapods', '~> 1.7'
|
||||
@@ -0,0 +1 @@
|
||||
github: [groue]
|
||||
@@ -102,10 +102,12 @@ SQLiteCustom/GRDBCustomSQLite-USER.xcconfig
|
||||
|
||||
# CocoaPods test
|
||||
Pods
|
||||
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 +0,0 @@
|
||||
4.2
|
||||
@@ -0,0 +1,63 @@
|
||||
included:
|
||||
- GRDB
|
||||
|
||||
disabled_rules:
|
||||
- cyclomatic_complexity
|
||||
- file_length
|
||||
- force_cast
|
||||
- force_try
|
||||
- function_body_length
|
||||
- function_parameter_count
|
||||
- identifier_name
|
||||
- is_disjoint
|
||||
- nesting
|
||||
- opening_brace
|
||||
- redundant_optional_initialization
|
||||
- syntactic_sugar
|
||||
- todo
|
||||
- trailing_comma
|
||||
- trailing_whitespace
|
||||
- type_body_length
|
||||
- type_name
|
||||
- unused_setter_value
|
||||
|
||||
opt_in_rules:
|
||||
- anyobject_protocol
|
||||
- array_init
|
||||
- attributes
|
||||
- closure_spacing
|
||||
- collection_alignment
|
||||
- contains_over_filter_count
|
||||
- contains_over_filter_is_empty
|
||||
- contains_over_first_not_nil
|
||||
- contains_over_range_nil_comparison
|
||||
- convenience_type
|
||||
- empty_collection_literal
|
||||
- empty_count
|
||||
- empty_string
|
||||
- explicit_init
|
||||
- fatal_error_message
|
||||
- first_where
|
||||
- flatmap_over_map_reduce
|
||||
- identical_operands
|
||||
- joined_default_parameter
|
||||
- last_where
|
||||
- legacy_multiple
|
||||
- legacy_random
|
||||
- lower_acl_than_parent
|
||||
- modifier_order
|
||||
- no_extension_access_modifier
|
||||
- overridden_super_call
|
||||
- pattern_matching_keywords
|
||||
- prohibited_super_call
|
||||
- reduce_into
|
||||
- redundant_type_annotation
|
||||
- sorted_first_last
|
||||
- toggle_bool
|
||||
- unused_declaration
|
||||
- unused_import
|
||||
- yoda_condition
|
||||
|
||||
vertical_whitespace:
|
||||
max_empty_lines: 2
|
||||
|
||||
@@ -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,312 +28,181 @@ jobs:
|
||||
include:
|
||||
|
||||
###########################################
|
||||
## Test GRDB Xcode 10.2
|
||||
## Test GRDB Xcode 11.4
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBOSX (Swift 5, macOS)
|
||||
- TID=GRDBOSX (Swift 5.1, macOS)
|
||||
script: make test_framework_GRDBOSX_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBOSX (Swift 4.2, macOS)
|
||||
script: make test_framework_GRDBOSX_minSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBWatchOS (watchOS)
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 5, iOS <MAX>)
|
||||
- TID=GRDBiOS (Swift 5.1, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget_minSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 5, iOS <MIN>)
|
||||
- TID=GRDBiOS (Swift 5.1, iOS <MIN>)
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 5.1, tvOS <MAX>)
|
||||
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 4.2, tvOS <MAX>)
|
||||
script: make test_framework_GRDBtvOS_maxTarget_minSwift
|
||||
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
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 10.2
|
||||
## Test GRDBCustom Xcode 11.4
|
||||
|
||||
- stage: Test GRDBCustom Xcode 10.2
|
||||
- stage: Test GRDBCustom Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBOSX (Swift 5, macOS)
|
||||
- TID=GRDBOSX (Swift 5.1, macOS)
|
||||
script: make test_framework_GRDBCustomSQLiteOSX
|
||||
|
||||
- stage: Test GRDBCustom Xcode 10.2
|
||||
- stage: Test GRDBCustom Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 5, iOS <MAX>)
|
||||
- TID=GRDBiOS (Swift 5.1, iOS <MAX>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDBCustom Xcode 10.2
|
||||
- stage: Test GRDBCustom Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_minSwift
|
||||
|
||||
- stage: Test GRDBCustom Xcode 10.2
|
||||
- stage: Test GRDBCustom Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 5, iOS <MIN>)
|
||||
- TID=GRDBiOS (Swift 5.1, iOS <MIN>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
|
||||
|
||||
###########################################
|
||||
## Test SQLCipher Xcode 10.2
|
||||
## Test SQLCipher Xcode 11.4
|
||||
|
||||
- stage: Test SQLCipher Xcode 10.2
|
||||
- stage: Test SQLCipher Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=SQLCipher 3
|
||||
script: make test_framework_SQLCipher3
|
||||
|
||||
- stage: Test SQLCipher Xcode 10.2
|
||||
- stage: Test SQLCipher Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=SQLCipher 4
|
||||
script: make test_framework_SQLCipher4
|
||||
|
||||
###########################################
|
||||
## Test Installation Xcode 10.2
|
||||
## Test Installation Xcode 11.4
|
||||
|
||||
# Manual Install
|
||||
- stage: Test Installation Xcode 10.2
|
||||
- stage: Test Installation Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=Manual Install
|
||||
script: make test_install_manual
|
||||
|
||||
# CocoaPods Lint
|
||||
- stage: Test Installation Xcode 10.2
|
||||
- stage: Test Installation Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=CocoaPods Lint
|
||||
script: make test_CocoaPodsLint_GRDB
|
||||
|
||||
# CocoaPods Install GRDB
|
||||
- stage: Test Installation Xcode 10.2
|
||||
- stage: Test Installation Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=CocoaPods GRDB
|
||||
script: make test_install_GRDB_CocoaPods
|
||||
- TID=CocoaPods GRDB (framework)
|
||||
script: make test_install_GRDB_CocoaPods_framework
|
||||
|
||||
# CocoaPods Install GRDB
|
||||
- stage: Test Installation Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=CocoaPods GRDB (static)
|
||||
script: make test_install_GRDB_CocoaPods_static
|
||||
|
||||
# SPM Install
|
||||
- stage: Test Installation Xcode 10.2
|
||||
- stage: Test Installation Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=SPM
|
||||
script: make test_install_SPM
|
||||
- TID=SPM Package
|
||||
script: make test_install_SPM_Package
|
||||
|
||||
###########################################
|
||||
## Test GRDB Xcode 10.1
|
||||
|
||||
- stage: Test GRDB Xcode 10.1
|
||||
# SPM Install
|
||||
- stage: Test Installation Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.1
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBOSX (Swift 4.2, macOS)
|
||||
script: make test_framework_GRDBOSX_maxSwift
|
||||
- TID=SPM Package in Xcode Project
|
||||
script: make test_install_SPM_Project
|
||||
|
||||
- stage: Test GRDB Xcode 10.1
|
||||
# Custom SQLite Install
|
||||
- stage: Test Installation Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.1
|
||||
osx_image: xcode11.4
|
||||
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=GRDB [SPM] (macOS)
|
||||
script: make test_SPM
|
||||
|
||||
# ###########################################
|
||||
# ## Test GRDBCustom Xcode 10.1
|
||||
#
|
||||
# - stage: Test GRDBCustom Xcode 10.1
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode10.1
|
||||
# env:
|
||||
# - TID=GRDBOSX (Swift 4.2, macOS)
|
||||
# script: make test_framework_GRDBCustomSQLiteOSX
|
||||
#
|
||||
# - stage: Test GRDBCustom Xcode 10.1
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode10.1
|
||||
# env:
|
||||
# - TID=GRDBiOS (Swift 4.2, iOS <MAX>)
|
||||
# script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
|
||||
#
|
||||
# - stage: Test GRDBCustom Xcode 10.1
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode10.1
|
||||
# env:
|
||||
# - TID=GRDBiOS (Swift 4.2, iOS <MIN>)
|
||||
# script: make test_framework_GRDBCustomSQLiteiOS_minTarget
|
||||
|
||||
###########################################
|
||||
## 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=GRDB [SPM] (macOS)
|
||||
script: make test_SPM
|
||||
|
||||
# ###########################################
|
||||
# ## Test GRDBCustom Xcode 10
|
||||
#
|
||||
# - stage: Test GRDBCustom Xcode 10
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode10
|
||||
# env:
|
||||
# - TID=GRDBOSX (Swift 4.2, macOS)
|
||||
# script: make test_framework_GRDBCustomSQLiteOSX
|
||||
#
|
||||
# - stage: Test GRDBCustom Xcode 10
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode10
|
||||
# env:
|
||||
# - TID=GRDBiOS (Swift 4.2, iOS <MAX>)
|
||||
# script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
|
||||
#
|
||||
# - stage: Test GRDBCustom Xcode 10
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode10
|
||||
# env:
|
||||
# - TID=GRDBiOS (Swift 4.2, iOS <MIN>)
|
||||
# script: make test_framework_GRDBCustomSQLiteiOS_minTarget
|
||||
#
|
||||
# ###########################################
|
||||
# ## Test SQLCipher Xcode 10
|
||||
#
|
||||
# - stage: Test SQLCipher Xcode 10
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode10
|
||||
# env:
|
||||
# - TID=SQLCipher 3
|
||||
# script: make test_framework_SQLCipher3
|
||||
#
|
||||
# - stage: Test SQLCipher Xcode 10
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode10
|
||||
# env:
|
||||
# - TID=SQLCipher 4
|
||||
# script: make test_framework_SQLCipher4
|
||||
#
|
||||
# ###########################################
|
||||
# ## Test Installation Xcode 10
|
||||
#
|
||||
# # Manual Install
|
||||
# - stage: Test Installation Xcode 10
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode10
|
||||
# env:
|
||||
# - TID=Manual Install
|
||||
# script: make test_install_manual
|
||||
#
|
||||
# # CocoaPods Lint
|
||||
# - stage: Test Installation Xcode 10
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode10
|
||||
# env:
|
||||
# - TID=CocoaPods Lint
|
||||
# script: make test_CocoaPodsLint_GRDB
|
||||
#
|
||||
# # CocoaPods Install GRDB
|
||||
# - stage: Test Installation Xcode 10
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode10
|
||||
# env:
|
||||
# - TID=CocoaPods GRDB
|
||||
# script: make test_install_GRDB_CocoaPods
|
||||
#
|
||||
# # SPM Install
|
||||
# - stage: Test Installation Xcode 10
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode10
|
||||
# env:
|
||||
# - TID=SPM
|
||||
# script: make test_install_SPM
|
||||
- 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.
|
||||
|
||||
@@ -3,11 +3,36 @@ Release Notes
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library.
|
||||
GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library.
|
||||
|
||||
|
||||
<!--
|
||||
[Next Release](#next-release)
|
||||
-->
|
||||
|
||||
|
||||
#### 5.x Releases
|
||||
|
||||
- `5.0.x` Development - [GRDB5 Branch](#grdb5-branch)
|
||||
|
||||
|
||||
#### 4.x Releases
|
||||
|
||||
- `4.0.x` Releases - [4.0.0](#400)
|
||||
- `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)
|
||||
- `4.3.x` Releases - [4.3.0](#430)
|
||||
- `4.2.x` Releases - [4.2.0](#420) | [4.2.1](#421)
|
||||
- `4.1.x` Releases - [4.1.0](#410) | [4.1.1](#411)
|
||||
- `4.0.x` Releases - [4.0.0](#400) | [4.0.1](#401)
|
||||
|
||||
#### 3.x Releases
|
||||
|
||||
@@ -47,6 +72,632 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection:
|
||||
- [0.110.0](#01100), ...
|
||||
|
||||
|
||||
<!--
|
||||
## 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
|
||||
|
||||
Released November 20, 2019 • [diff](https://github.com/groue/GRDB.swift/compare/v4.6.1...v4.6.2)
|
||||
|
||||
**Fixed**
|
||||
|
||||
- [#653](https://github.com/groue/GRDB.swift/pull/653) by [@michaelkirk-signal](https://github.com/michaelkirk-signal): Fix DatabaseMigrator.appliedMigrations() error on empty database
|
||||
|
||||
|
||||
## 4.6.1
|
||||
|
||||
Released November 10, 2019 • [diff](https://github.com/groue/GRDB.swift/compare/v4.6.0...v4.6.1)
|
||||
|
||||
**Fixed**
|
||||
|
||||
- [#647](https://github.com/groue/GRDB.swift/pull/647): Honor conflict resolution for batch updates
|
||||
|
||||
|
||||
## 4.6.0
|
||||
|
||||
Released November 9, 2019 • [diff](https://github.com/groue/GRDB.swift/compare/v4.5.0...v4.6.0)
|
||||
|
||||
**New**
|
||||
|
||||
- [#646](https://github.com/groue/GRDB.swift/pull/646): Batch updates
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
The [Update Requests](README.md#update-requests) chapter documents the new support for batch updates introduced in the [query interface](README.md#the-query-interface).
|
||||
|
||||
The [Associations Guide](Documentation/AssociationsBasics.md) has gained a new [Ordered Associations](Documentation/AssociationsBasics.md#ordered-associations) chapter which explains how to define ordered HasMany and HasManyThrough associations.
|
||||
|
||||
|
||||
## 4.5.0
|
||||
|
||||
Released October 15, 2019 • [diff](https://github.com/groue/GRDB.swift/compare/v4.4.0...v4.5.0)
|
||||
|
||||
**Fixed**
|
||||
|
||||
- The `DatabaseMigrator.eraseDatabaseOnSchemaChange` option no longer fails when migrations depend on database configuration.
|
||||
- Fixed `DatabasePool.reentrantRead` which was not actually reentrant.
|
||||
- [#631](https://github.com/groue/GRDB.swift/pull/631): Fix custom SQLite builds
|
||||
- [#632](https://github.com/groue/GRDB.swift/pull/632) by [@runhum](https://github.com/runhum): Fix documentation typo
|
||||
|
||||
**New**
|
||||
|
||||
- [#622](https://github.com/groue/GRDB.swift/pull/622): Allow observation of FTS4 virtual tables
|
||||
- [#627](https://github.com/groue/GRDB.swift/pull/627): Swift Package Manager: define SQLite as a system library target
|
||||
- [#633](https://github.com/groue/GRDB.swift/pull/633): SQLITE_ENABLE_PREUPDATE_HOOK support with CocoaPods
|
||||
- [#635](https://github.com/groue/GRDB.swift/pull/635): Sunset FetchedRecordsController
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
The [Support for SQLite Pre-Update Hooks](README.md#support-for-sqlite-pre-update-hooks) chapter has been updated with a way to enable extra GRDB APIs for the SQLITE_ENABLE_PREUPDATE_HOOK option with CocoaPods.
|
||||
|
||||
The [Demo Application](Documentation/DemoApps/GRDBDemoiOS) no longer uses [FetchedRecordsController](Documentation/FetchedRecordsController.md), which has been sunsetted. Instead, it tracks database changes with [ValueObservation](README.md#valueobservation), and animates its table view with the Swift built-in [difference(from:)](https://developer.apple.com/documentation/swift/bidirectionalcollection/3200721-difference) method.
|
||||
|
||||
|
||||
## 4.4.0
|
||||
|
||||
Released September 6, 2019 • [diff](https://github.com/groue/GRDB.swift/compare/v4.3.0...v4.4.0)
|
||||
|
||||
|
||||
### New
|
||||
|
||||
- [#602](https://github.com/groue/GRDB.swift/pull/602): Don't keep the sqlCipher passphrase in memory longer than necessary
|
||||
- [#603](https://github.com/groue/GRDB.swift/pull/603): DatabasePool write barrier
|
||||
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
SQLCipher passphrase management has been refactored: you will get deprecation warnings. Check out the rewritten [Encryption](README.md#encryption) chapter in order to migrate your code and remove those warnings.
|
||||
|
||||
The [Advanced DatabasePool](README.md#advanced-databasepool) chapter has been extended for the new `barrierWriteWithoutTransaction` method.
|
||||
|
||||
|
||||
### API Diff
|
||||
|
||||
**Deprecations**
|
||||
|
||||
```diff
|
||||
class DatabaseQueue {
|
||||
+ @available(*, deprecated)
|
||||
func change(passphrase: String) throws
|
||||
}
|
||||
|
||||
class DatabasePool {
|
||||
+ @available(*, deprecated)
|
||||
func change(passphrase: String) throws
|
||||
}
|
||||
|
||||
struct Configuration {
|
||||
+ @available(*, deprecated)
|
||||
var passphrase: String?
|
||||
}
|
||||
```
|
||||
|
||||
**New Methods**
|
||||
|
||||
```diff
|
||||
class DatabasePool {
|
||||
+ func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T
|
||||
+ func invalidateReadOnlyConnections()
|
||||
}
|
||||
|
||||
class Database {
|
||||
+ func usePassphrase(_ passphrase: String) throws
|
||||
+ func changePassphrase(_ passphrase: String) throws
|
||||
+ var lastErrorCode: ResultCode
|
||||
+ var lastErrorMessage: String?
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 4.3.0
|
||||
|
||||
Released August 28, 2019 • [diff](https://github.com/groue/GRDB.swift/compare/v4.2.1...v4.3.0)
|
||||
|
||||
**New**
|
||||
|
||||
- [#600](https://github.com/groue/GRDB.swift/pull/600) by [@kdubb](https://github.com/kdubb): Add support for tvOS
|
||||
|
||||
|
||||
## 4.2.1
|
||||
|
||||
Released August 13, 2019 • [diff](https://github.com/groue/GRDB.swift/compare/v4.2.0...v4.2.1)
|
||||
|
||||
**Fixed**
|
||||
|
||||
- [#592](https://github.com/groue/GRDB.swift/pull/592): Fix Data interpolation
|
||||
|
||||
|
||||
## 4.2.0
|
||||
|
||||
Released August 6, 2019 • [diff](https://github.com/groue/GRDB.swift/compare/v4.1.1...v4.2.0)
|
||||
|
||||
**New**
|
||||
|
||||
- [#570](https://github.com/groue/GRDB.swift/pull/570) by [@chrisballinger](https://github.com/chrisballinger): Allow Swift static library integration via CocoaPods
|
||||
- [#576](https://github.com/groue/GRDB.swift/pull/576): Expose table name and full-text filtering methods to DerivableRequest
|
||||
- [#586](https://github.com/groue/GRDB.swift/pull/586): Automatic region tracking for ValueObservation
|
||||
|
||||
**Fixed**
|
||||
|
||||
- [#560](https://github.com/groue/GRDB.swift/pull/560) by [@bellebethcooper](https://github.com/bellebethcooper): Minor typo fix
|
||||
- [#562](https://github.com/groue/GRDB.swift/pull/562): Fix crash when using more than one DatabaseCollation
|
||||
- [#577](https://github.com/groue/GRDB.swift/pull/577): Rename `aliased(_:)` methods to `forKey(_:)`
|
||||
- [#585](https://github.com/groue/GRDB.swift/pull/585): Fix use of SQLite authorizers
|
||||
|
||||
**Other**
|
||||
|
||||
- [#563](https://github.com/groue/GRDB.swift/pull/563): More tests for eager loading of hasMany associations
|
||||
- [#574](https://github.com/groue/GRDB.swift/pull/574): SwiftLint
|
||||
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
The [ValueObservation](README.md#valueobservation) chapter has been updated so that it fosters the new `ValueObservation.tracking(value:)` method. Other ways to define observations are now described as optimizations.
|
||||
|
||||
|
||||
### API Diff
|
||||
|
||||
```diff
|
||||
-protocol DerivableRequest: FilteredRequest, JoinableRequest, OrderedRequest, SelectionRequest { }
|
||||
+protocol DerivableRequest: FilteredRequest, JoinableRequest, OrderedRequest, SelectionRequest, TableRequest { }
|
||||
|
||||
-extension QueryInterfaceRequest {
|
||||
- func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<T>
|
||||
-}
|
||||
-extension QueryInterfaceRequest {
|
||||
- func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest<T>
|
||||
-}
|
||||
+extension TableRequest where Self: FilteredRequest {
|
||||
+ func matching(_ pattern: FTS3Pattern?) -> Self
|
||||
+}
|
||||
+extension TableRequest where Self: FilteredRequest {
|
||||
+ func matching(_ pattern: FTS5Pattern?) -> Self
|
||||
+}
|
||||
|
||||
protocol Association: DerivableRequest {
|
||||
- associatedtype OriginRowDecoder
|
||||
+ associatedtype OriginRowDecoder: TableRecord
|
||||
}
|
||||
|
||||
-struct BelongsToAssociation<Origin, Destination>: AssociationToOne { }
|
||||
-struct HasManyAssociation<Origin, Destination>: AssociationToMany { }
|
||||
-struct HasManyThroughAssociation<Origin, Destination>: AssociationToMany { }
|
||||
-struct HasOneAssociation<Origin, Destination>: AssociationToOne { }
|
||||
-struct HasOneThroughAssociation<Origin, Destination>: AssociationToOne { }
|
||||
+struct BelongsToAssociation<Origin: TableRecord, Destination: TableRecord>: AssociationToOne { }
|
||||
+struct HasManyAssociation<Origin: TableRecord, Destination: TableRecord>: AssociationToMany { }
|
||||
+struct HasManyThroughAssociation<Origin: TableRecord, Destination: TableRecord>: AssociationToMany { }
|
||||
+struct HasOneAssociation<Origin: TableRecord, Destination: TableRecord>: AssociationToOne { }
|
||||
+struct HasOneThroughAssociation<Origin: TableRecord, Destination: TableRecord>: AssociationToOne { }
|
||||
|
||||
-struct QueryInterfaceRequest<T>: DerivableRequest { }
|
||||
+struct QueryInterfaceRequest<T>: FilteredRequest, OrderedRequest, SelectionRequest, TableRequuest { }
|
||||
+extension QueryInterfaceRequest: JoinableRequest where T: TableRecord { }
|
||||
+extension QueryInterfaceRequest: DerivableRequest where T: TableRecord { }
|
||||
|
||||
extension AssociationAggregate {
|
||||
+ @available(*, deprecated, renamed: "forKey(_:)")
|
||||
func aliased(_ name: String) -> AssociationAggregate<RowDecoder>
|
||||
+ func forKey(_ name: String) -> AssociationAggregate<RowDecoder>
|
||||
|
||||
+ @available(*, deprecated, renamed: "forKey(_:)")
|
||||
func aliased(_ key: CodingKey) -> AssociationAggregate<RowDecoder>
|
||||
+ func forKey(_ key: CodingKey) -> AssociationAggregate<RowDecoder>
|
||||
}
|
||||
|
||||
extension SQLSpecificExpressible {
|
||||
+ @available(*, deprecated, renamed: "forKey(_:)")
|
||||
func aliased(_ name: String) -> SQLSelectable
|
||||
+ func forKey(_ name: String) -> SQLSelectable
|
||||
|
||||
+ @available(*, deprecated, renamed: "forKey(_:)")
|
||||
func aliased(_ key: CodingKey) -> SQLSelectable
|
||||
+ func forKey(_ key: CodingKey) -> SQLSelectable
|
||||
}
|
||||
|
||||
extension ValueObservation where Reducer == Void {
|
||||
+ static func tracking<Value>(fetch: @escaping (Database) throws -> Value) -> ValueObservation<ValueReducers.Fetch<Value>>
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 4.1.1
|
||||
|
||||
Released June 22, 2019 • [diff](https://github.com/groue/GRDB.swift/compare/v4.1.0...v4.1.1)
|
||||
|
||||
This version is identical to 4.1.0.
|
||||
|
||||
## 4.1.0
|
||||
|
||||
Released June 20, 2019 • [diff](https://github.com/groue/GRDB.swift/compare/v4.0.1...v4.1.0)
|
||||
|
||||
- [#537](https://github.com/groue/GRDB.swift/pull/537): Remove useless parenthesis from generated SQL
|
||||
- [#538](https://github.com/groue/GRDB.swift/pull/538) by [@Timac](https://github.com/Timac): Add FAQ to clarify "Wrong number of statement arguments" error with "like '%?%'"
|
||||
- [#539](https://github.com/groue/GRDB.swift/pull/539): Expose joining methods on both requests and associations
|
||||
- [#540](https://github.com/groue/GRDB.swift/pull/540): Update SQLite to 3.28.0 (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib))
|
||||
- [#542](https://github.com/groue/GRDB.swift/pull/542): Move eager loading of hasMany associations to FetchRequest
|
||||
- [#546](https://github.com/groue/GRDB.swift/pull/546) by [@robcas3](https://github.com/robcas3): Fix SPM errors with Xcode 11 beta
|
||||
- [#549](https://github.com/groue/GRDB.swift/pull/549) Support for Combine
|
||||
- [#550](https://github.com/groue/GRDB.swift/pull/550) Asynchronous Database Access Methods
|
||||
- [#555](https://github.com/groue/GRDB.swift/pull/555) Avoid a crash when read-only access can't be established
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
Good practices evolve: the [Define Record Requests](Documentation/GoodPracticesForDesigningRecordTypes.md#define-record-requests) chapter of the The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) has been rewritten.
|
||||
|
||||
The [Examples of Record Definitions](README.md#examples-of-record-definitions) has been extended with a sample record optimized for fetching performance.
|
||||
|
||||
The [ValueObservation](README.md#valueobservation) chapter has been updated with new APIs for building observation, and combining observations together in order to avoid data races.
|
||||
|
||||
The [ValueObservation Error Handling](README.md#valueobservation-error-handling) chapter explains with more details how to deal with observation errors.
|
||||
|
||||
### API Diff
|
||||
|
||||
<details>
|
||||
<summary>Asynchronous database access methods</summary>
|
||||
|
||||
```diff
|
||||
protocol DatabaseReader {
|
||||
+ var configuration: Configuration { get }
|
||||
+
|
||||
+ #if compiler(>=5.0)
|
||||
+ func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void)
|
||||
+ #endif
|
||||
}
|
||||
|
||||
protocol DatabaseWriter {
|
||||
+ func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
|
||||
+
|
||||
+ #if compiler(>=5.0)
|
||||
+ func asyncWrite<T>(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result<T, Error>) -> Void)
|
||||
+ #endif
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>ValueObservation changes</summary>
|
||||
|
||||
```diff
|
||||
+extension FetchRequest {
|
||||
+ func observationForCount() -> ValueObservation<...>
|
||||
+}
|
||||
+extension FetchRequest where RowDecoder: ... {
|
||||
+ func observationForAll() -> ValueObservation<...>
|
||||
+ func observationForFirst() -> ValueObservation<...>
|
||||
+)
|
||||
+extension TableRecord {
|
||||
+ static func observationForCount() -> ValueObservation<...>
|
||||
+ static func observationForAll() -> ValueObservation<...>
|
||||
+ static func observationForFirst() -> ValueObservation<...>
|
||||
+}
|
||||
extension ValueObservation where ... {
|
||||
+ @available(*, deprecated)
|
||||
static func trackingCount<Request: FetchRequest>(_ request: Request) -> ValueObservation<...>
|
||||
+ @available(*, deprecated)
|
||||
static func trackingAll<Request: FetchRequest>(_ request: Request) -> ValueObservation<...>
|
||||
+ @available(*, deprecated)
|
||||
static func trackingOne<Request: FetchRequest>(_ request: Request) -> ValueObservation<...>
|
||||
}
|
||||
extension ValueObservation where Reducer: ValueReducer {
|
||||
- func start(in reader: DatabaseReader, onError: ((Error) -> Void)? = nil, onChange: @escaping (Reducer.Value) -> Void) throws -> TransactionObserver
|
||||
+ func start(in reader: DatabaseReader, onChange: @escaping (Reducer.Value) -> Void) throws -> TransactionObserver
|
||||
+ func start(in reader: DatabaseReader, onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver
|
||||
+ func combine<..., Combined>(..., transform: @escaping (...) -> Combined) -> ValueObservation<...>
|
||||
}
|
||||
extension ValueObservation where Reducer: ValueReducer, Reducer.Value: Equatable {
|
||||
+ @available(*, deprecated)
|
||||
func distinctUntilChanged() -> ValueObservation<...>
|
||||
+ func removeDuplicates() -> ValueObservation<...>
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Joining methods on both requests and associations</summary>
|
||||
|
||||
```diff
|
||||
+protocol JoinableRequest {
|
||||
+ associatedtype RowDecoder
|
||||
+}
|
||||
+
|
||||
+extension JoinableRequest {
|
||||
+ func including<A: AssociationToMany>(all association: A) -> Self where A.OriginRowDecoder == RowDecoder
|
||||
+ func including<A: Association>(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder
|
||||
+ func including<A: Association>(required association: A) -> Self where A.OriginRowDecoder == RowDecoder
|
||||
+ func joining<A: Association>(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder
|
||||
+ func joining<A: Association>(required association: A) -> Self where A.OriginRowDecoder == RowDecoder
|
||||
+}
|
||||
|
||||
-protocol DerivableRequest: SelectionRequest, FilteredRequest, OrderedRequest { }
|
||||
+protocol DerivableRequest: SelectionRequest, FilteredRequest, OrderedRequest, JoinableRequest { }
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>FetchRequest changes</summary>
|
||||
|
||||
```diff
|
||||
+struct PreparedRequest {
|
||||
+ var statement: SelectStatement
|
||||
+ var adapter: RowAdapter?
|
||||
+ init(statement: SelectStatement, adapter: RowAdapter? = nil)
|
||||
+}
|
||||
|
||||
protocol FetchRequest {
|
||||
+ // deprecated
|
||||
func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
|
||||
+ func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
|
||||
}
|
||||
```
|
||||
|
||||
The core FetchRequest preparation method is now `makePreparedRequest(_:forSingleResult:)`. The former core method `prepare(_:forSingleResult:)` will remain a requirement of the FetchRequest protocol until GRDB 5 due to semantic versioning constraints. Both methods are provided with a default implementation which makes each one depend on the other: this creates an infinite loop unless you provide at least one of them. If you have a choice, implement only `makePreparedRequest(_:forSingleResult:)`.
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
## 4.0.1
|
||||
|
||||
Released May 25, 2019 • [diff](https://github.com/groue/GRDB.swift/compare/v4.0.0...v4.0.1)
|
||||
|
||||
- [#533](https://github.com/groue/GRDB.swift/pull/533): Fix eager loading of HasManyThrough associations
|
||||
- [#534](https://github.com/groue/GRDB.swift/pull/534): Support for CocoaPods 1.7.0
|
||||
- [#535](https://github.com/groue/GRDB.swift/pull/535): Update the Good Practices for Designing Record Types
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) have been enhanced and completed with a whole new section about "database managers".
|
||||
|
||||
|
||||
## 4.0.0
|
||||
|
||||
Released May 23, 2019 • [diff](https://github.com/groue/GRDB.swift/compare/v3.7.0...v4.0.0)
|
||||
@@ -898,7 +1549,7 @@ Released September 23, 2018 • [diff](https://github.com/groue/GRDB.swift/co
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
- Enhanced visibility of the [Demo Application](DemoApps/GRDBDemoiOS)
|
||||
- Enhanced visibility of the [Demo Application](Documentation/DemoApps/GRDBDemoiOS)
|
||||
|
||||
|
||||
## 3.3.0
|
||||
@@ -1604,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)
|
||||
|
||||
|
||||
@@ -78,9 +78,6 @@ The ideas, in alphabetical order:
|
||||
- [Date and Time Functions]
|
||||
- [Decode NSDecimalNumber from Text Columns]
|
||||
- [Documentation]
|
||||
- [FetchedRecordsController Diffing Algorithm]
|
||||
- [FetchedRecordsController Support for Any Request]
|
||||
- [FetchedRecordsController Support for Sections]
|
||||
- [Full Text Search Demo Application]
|
||||
- [JSON]
|
||||
- [Linux]
|
||||
@@ -88,7 +85,6 @@ The ideas, in alphabetical order:
|
||||
- [Reactive Database Observation]
|
||||
- [SQL Console in the Debugger]
|
||||
- [SQLCipher in a Shared App Container]
|
||||
- [Static Library]
|
||||
- [Typed Expressions]
|
||||
|
||||
|
||||
@@ -206,50 +202,6 @@ Inline documentation, the one which is embedded right into the source code and i
|
||||
If you are a good writer, your help will be very warmly welcomed.
|
||||
|
||||
|
||||
### FetchedRecordsController Diffing Algorithm
|
||||
|
||||
:muscle: Hard
|
||||
|
||||
[FetchedRecordsController] uses a Levenshtein-based diffing algorithm which has a terrible algorithmic complexity. This makes this very useful class unable to deal with more than hundreds of elements.
|
||||
|
||||
There exists much more efficient O(n) diffing algorithms that would lift this limitation.
|
||||
|
||||
Starting points:
|
||||
|
||||
- [RxSwiftCommunity/RxDataSources](https://github.com/RxSwiftCommunity/RxDataSources)
|
||||
- [ra1028/DifferenceKit](https://github.com/ra1028/DifferenceKit)
|
||||
- [tonyarnold/Differ](https://github.com/tonyarnold/Differ)
|
||||
- [onmyway133/DeepDiff](https://github.com/onmyway133/DeepDiff)
|
||||
- [mcudich/HeckelDiff](https://github.com/mcudich/HeckelDiff)
|
||||
|
||||
|
||||
### FetchedRecordsController Support for Any Request
|
||||
|
||||
:muscle: Hard
|
||||
|
||||
[FetchedRecordsController] is able to deal with records, but not with raw rows or values:
|
||||
|
||||
```swift
|
||||
// Supported by FetchedRecordsController
|
||||
let recordRequest = Player.all()
|
||||
|
||||
// Not supported by FetchedRecordsController
|
||||
let stringRequest = Player.select(Column("name"), as: String.self)
|
||||
let rowRequest = SQLRequest<Row>("SELECT ...")
|
||||
```
|
||||
|
||||
This limitation does not apply to [ValueObservation] and [RxGRDB]. It would be nice if FetchedRecordsController would become just as versatile.
|
||||
|
||||
|
||||
### FetchedRecordsController Support for Sections
|
||||
|
||||
:muscle: Hard
|
||||
|
||||
[FetchedRecordsController] mimics the API of Core Data's [NSFetchedResultsController](https://developer.apple.com/documentation/coredata/nsfetchedresultscontroller), but does not yet support table and collection view sections.
|
||||
|
||||
This improvement most certainly depends on a refreshing of the [FetchedRecordsController Diffing Algorithm].
|
||||
|
||||
|
||||
### Full Text Search Demo Application
|
||||
|
||||
:baby: Starter Task :pencil: Documentation
|
||||
@@ -292,14 +244,16 @@ There are several SQLite features that GRDB could natively support:
|
||||
- [Windows Functions](https://www.sqlite.org/windowfunctions.html)
|
||||
- [More ideas](https://www.sqlite.org/lang.html)
|
||||
|
||||
See [issue #575](https://github.com/groue/GRDB.swift/issues/575) for more information and guidance about the implementation of extra table alterations.
|
||||
|
||||
|
||||
### Reactive Database Observation
|
||||
|
||||
:baby: Starter Task
|
||||
|
||||
We already have the [RxGRDB] companion library, which offers [RxSwift](https://github.com/ReactiveX/RxSwift) bindings.
|
||||
We already have the [GRDBCombine](http://github.com/groue/GRDBCombine) and [RxGRDB] companion libraries.
|
||||
|
||||
We need more choices of reactive engines.
|
||||
More choices of reactive engines would help more developers enjoy GRDB.
|
||||
|
||||
|
||||
### SQL Console in the Debugger
|
||||
@@ -316,13 +270,6 @@ Sometimes one needs, in lldb, a console similar to the [Command Line Shell For S
|
||||
See issue [#302](https://github.com/groue/GRDB.swift/issues/302).
|
||||
|
||||
|
||||
### Static Library
|
||||
|
||||
:question: Unknown Difficulty :hammer: Tooling
|
||||
|
||||
It would be nice to be able to integrate GRDB as a static library.
|
||||
|
||||
|
||||
### Typed Expressions
|
||||
|
||||
:bowtie: Public API Challenge :muscle: Hard :fire: Experimental
|
||||
@@ -366,22 +313,18 @@ Features that blur this focus are non-goals:
|
||||
[Date and Time Functions]: #date-and-time-functions
|
||||
[Decode NSDecimalNumber from Text Columns]: #decode-nsdecimalnumber-from-text-columns
|
||||
[Documentation]: #documentation
|
||||
[FetchedRecordsController]: README.md#fetchedrecordscontroller
|
||||
[FetchedRecordsController Diffing Algorithm]: #fetchedrecordscontroller-diffing-algorithm
|
||||
[FetchedRecordsController Support for Any Request]: #fetchedrecordscontroller-support-for-any-request
|
||||
[FetchedRecordsController Support for Sections]: #fetchedrecordscontroller-support-for-sections
|
||||
[Full Text Search Demo Application]: #full-text-search-demo-application
|
||||
[How is the Library Organized?]: Documentation/LibraryOrganization.md
|
||||
[How is the Repository Organized?]: Documentation/RepositoryOrganization.md
|
||||
[JSON]: #json
|
||||
[Linux]: #linux
|
||||
[More SQL Generation]: #more-sql-generation
|
||||
[Reactive Database Observation]: #reactive-database-observation
|
||||
[Records: Splitting Database Encoding from Ability to Write in the Database]: #records-splitting-database-encoding-from-ability-to-write-in-the-database
|
||||
[Non-Goals]: #non-goals
|
||||
[Report Bugs]: #report-bugs
|
||||
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
|
||||
[Concurrency]: #concurrency
|
||||
[Static Library]: #static-library
|
||||
[Sponsoring and Professional Support]: #sponsoring-and-professional-support
|
||||
[SQL Console in the Debugger]: #sql-console-in-the-debugger
|
||||
[SQLCipher in a Shared App Container]: #sqlcipher-in-a-shared-app-container
|
||||
|
||||
|
Before Width: | Height: | Size: 3.8 KiB |
|
Before Width: | Height: | Size: 5.7 KiB |
@@ -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
|
||||
@@ -23,6 +23,7 @@ GRDB Associations
|
||||
- [Combining Associations]
|
||||
- [Filtering Associations]
|
||||
- [Sorting Associations]
|
||||
- [Ordered Associations]
|
||||
- [Columns Selected by an Association]
|
||||
- [Table Aliases]
|
||||
- [Refining Association Requests]
|
||||
@@ -90,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)
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -164,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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,7 +194,7 @@ GRDB handles five types of associations:
|
||||
|
||||
An association declares a link from a record type to another, as in "one book **belongs to** its author". It instructs GRDB to use the foreign keys declared in the database as support for Swift methods.
|
||||
|
||||
Each one of the three types of associations is appropriate for a particular database situation.
|
||||
Each one of these associations is appropriate for a particular database situation.
|
||||
|
||||
- [BelongsTo]
|
||||
- [HasMany]
|
||||
@@ -282,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)
|
||||
...
|
||||
@@ -293,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)
|
||||
...
|
||||
@@ -326,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))
|
||||
...
|
||||
@@ -341,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)
|
||||
...
|
||||
}
|
||||
|
||||
@@ -765,6 +766,7 @@ Fetch requests do not visit the database until you fetch values from them. This
|
||||
- [Combining Associations]
|
||||
- [Filtering Associations]
|
||||
- [Sorting Associations]
|
||||
- [Ordered Associations]
|
||||
- [Columns Selected by an Association]
|
||||
- [Table Aliases]
|
||||
- [Refining Association Requests]
|
||||
@@ -783,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)
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -804,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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -822,18 +824,6 @@ let novels = try author
|
||||
.fetchAll(db) // [Book]
|
||||
```
|
||||
|
||||
Those requests can also turn out useful when you want to track their changes with [database observation tools] like [ValueObservation]:
|
||||
|
||||
```swift
|
||||
// Track changes in the author's books:
|
||||
let author: Author = ...
|
||||
ValueObservation
|
||||
.trackingAll(author.books)
|
||||
.start(in: dbQueue) { (books: [Book]) in
|
||||
print("Author's book have changed")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Joining And Prefetching Associated Records
|
||||
|
||||
@@ -1121,6 +1111,104 @@ let request = Book
|
||||
Those extra sorting options require **[Table Aliases]**, introduced below.
|
||||
|
||||
|
||||
## Ordered Associations
|
||||
|
||||
By default, **[HasMany]** or **[HasManyThrough]** associations are unordered: the order of associated records is undefined unless [explicitly specified](#sorting-associations) on each request.
|
||||
|
||||
But you can build an ordering right into the definition of an association, so that it becomes the default ordering for this association. For example, let's model soccer teams and players, ordered by the number printed on their shirt.
|
||||
|
||||
Let's start with a **HasMany** association. Each player knows its position in its team:
|
||||
|
||||
```swift
|
||||
struct Team: FetchableRecord, TableRecord {
|
||||
var id: Int64
|
||||
var name: String
|
||||
}
|
||||
|
||||
struct Player: FetchableRecord, TableRecord {
|
||||
var id: Int64
|
||||
var teamId: Int64
|
||||
var name: String
|
||||
var position: Int
|
||||
}
|
||||
```
|
||||
|
||||
The `Team.players` association is ordered by position, so that all team players are loaded well-sorted by default:
|
||||
|
||||
```swift
|
||||
extension Team {
|
||||
static let players = hasMany(Player.self).order(Column("position"))
|
||||
|
||||
var players: QueryInterfaceRequest<Player> {
|
||||
request(for: Team.players)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Things are very similar for **HasManyThrough** associations. Now each player knows its position in the teams it belongs to:
|
||||
|
||||
```swift
|
||||
struct Team: FetchableRecord, TableRecord {
|
||||
var id: Int64
|
||||
var name: String
|
||||
}
|
||||
|
||||
struct PlayerRole: FetchableRecord, TableRecord {
|
||||
var teamId: Int64
|
||||
var playerId: Int64
|
||||
var position: Int
|
||||
}
|
||||
|
||||
struct Player: FetchableRecord, TableRecord {
|
||||
var id: Int64
|
||||
var name: String
|
||||
}
|
||||
```
|
||||
|
||||
Again, the `Team.players` association is ordered by position, so that all team players are loaded well-sorted by default:
|
||||
|
||||
```swift
|
||||
extension Team {
|
||||
static let playerRoles = hasMany(PlayerRole.self).order(Column("position"))
|
||||
|
||||
static let players = hasMany(Player.self, through: playerRoles, using: PlayerRole.player)
|
||||
|
||||
var players: QueryInterfaceRequest<Player> {
|
||||
request(for: Team.players)
|
||||
}
|
||||
}
|
||||
|
||||
extension PlayerRole {
|
||||
static let player = belongsTo(Player.self)
|
||||
}
|
||||
```
|
||||
|
||||
In both cases, you can escape the default ordering when you need it:
|
||||
|
||||
```swift
|
||||
struct TeamInfo: Decodable, FetchableRecord {
|
||||
var team: Team
|
||||
var players: [Player]
|
||||
}
|
||||
|
||||
// Default ordering by position
|
||||
let team: Team = ...
|
||||
let players = try team.players.fetchAll(db)
|
||||
let teamInfos = try Team
|
||||
.including(all: Team.players)
|
||||
.asRequest(of: TeamInfo.self)
|
||||
.fetchAll(db)
|
||||
|
||||
// Custom ordering
|
||||
let team: Team = ...
|
||||
let players = try team.players.order(Column("name")).fetchAll(db)
|
||||
let teamInfos = try Team
|
||||
.including(all: Team.players.order(Column("name")))
|
||||
.asRequest(of: TeamInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
|
||||
## Columns Selected by an Association
|
||||
|
||||
By default, associated records include all their columns:
|
||||
@@ -1239,63 +1327,6 @@ let request = Book.aliased(bookAlias)
|
||||
|
||||
## Refining Association Requests
|
||||
|
||||
You can join and include an association several times in a single request. This can help you craft complex requests in a modular way.
|
||||
|
||||
Let's say, for example, that your application needs all books, along with their Spanish authors, sorted by author name and then by title. That's already pretty complex.
|
||||
|
||||
This request can be built in a single shot:
|
||||
|
||||
```swift
|
||||
let authorAlias = TableAlias()
|
||||
let request = Book
|
||||
.including(required: Book.author
|
||||
.filter(Column("countryCode") == "ES")
|
||||
.aliased(authorAlias))
|
||||
.order(authorAlias[Column("name")], Column("title"))
|
||||
```
|
||||
|
||||
The same request can also be built in three distinct steps, as below:
|
||||
|
||||
```swift
|
||||
// 1. include author
|
||||
var request = Book.including(required: Book.author)
|
||||
|
||||
// 2. filter by author country
|
||||
request = request.joining(required: Book.author.filter(Column("countryCode") == "ES"))
|
||||
|
||||
// 3. sort by author name and then title
|
||||
let authorAlias = TableAlias()
|
||||
request = request
|
||||
.joining(optional: Book.author.aliased(authorAlias))
|
||||
.order(authorAlias[Column("name")], Column("title"))
|
||||
```
|
||||
|
||||
See how the `Book.author` has been joined or included, on each step, independently, for a different purpose. We can wrap those steps in an extension to the `QueryInterfaceRequest<Book>` type:
|
||||
|
||||
```swift
|
||||
extension QueryInterfaceRequest where T == Book {
|
||||
func filter(authorCountryCode: String) -> QueryInterfaceRequest<Book> {
|
||||
let filteredAuthor = Book.author.filter(Column("countryCode") == countryCode)
|
||||
return joining(required: filteredAuthor)
|
||||
}
|
||||
|
||||
func orderedByAuthorNameAndTitle() -> QueryInterfaceRequest<Book> {
|
||||
let authorAlias = TableAlias()
|
||||
return joining(optional: Book.author.aliased(authorAlias))
|
||||
.order(authorAlias[Column("name")], Column("title"))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And now our complex request looks much simpler:
|
||||
|
||||
```swift
|
||||
let request = Book
|
||||
.including(required: Book.author)
|
||||
.filter(authorCountryCode: "ES")
|
||||
.orderedByAuthorNameAndTitle()
|
||||
```
|
||||
|
||||
When you join or include an association several times, with the same **[association key](#the-structure-of-a-joined-request)**, GRDB will apply the following rules:
|
||||
|
||||
- `including` wins over `joining`:
|
||||
@@ -1343,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
|
||||
=================================
|
||||
@@ -1355,31 +1440,14 @@ Often, you'll also make it adopt the standard Decodable protocol, because the co
|
||||
|
||||
Each association included in the request can feed a property of the decoded record:
|
||||
|
||||
- `including(all:)` feeds an Array or Set property:
|
||||
|
||||
```swift
|
||||
// All authors with their books
|
||||
let request = Author.including(all: Author.books)
|
||||
|
||||
struct AuthorInfo: FetchableRecord, Decodable {
|
||||
var author: Author
|
||||
var books: [Book] // all associated books
|
||||
}
|
||||
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
- `including(optional:)` feeds an optional property:
|
||||
|
||||
```swift
|
||||
// All employees with their manager and subordinate
|
||||
let request = Employee
|
||||
.including(optional: Employee.manager)
|
||||
.including(all: Employee.subordinates)
|
||||
let request = Employee.including(optional: Employee.manager)
|
||||
|
||||
struct EmployeeInfo: FetchableRecord, Decodable {
|
||||
var employee: Employee
|
||||
var manager: Employee? // the optional manager
|
||||
var subordinates: Set<Employee>
|
||||
var manager: Employee? // the optional associated manager
|
||||
}
|
||||
let employeeInfos: [EmployeeInfo] = try EmployeeInfo.fetchAll(db, request)
|
||||
```
|
||||
@@ -1387,22 +1455,28 @@ Each association included in the request can feed a property of the decoded reco
|
||||
- `including(required:)` feeds an non-optional property:
|
||||
|
||||
```swift
|
||||
// All books with information about their author, country, and cover image:
|
||||
let request = Book
|
||||
.including(required: Book.author
|
||||
.including(optional: Author.country))
|
||||
.including(optional: Book.coverImage)
|
||||
let request = Book.including(required: Book.author)
|
||||
|
||||
struct BookInfo: FetchableRecord, Decodable {
|
||||
var book: Book
|
||||
var author: Author // the required author
|
||||
var country: Country?
|
||||
var coverImage: CoverImage?
|
||||
var author: Author // the required associated author
|
||||
}
|
||||
|
||||
let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
- `including(all:)` feeds an Array or Set property:
|
||||
|
||||
```swift
|
||||
let request = Author.including(all: Author.books)
|
||||
|
||||
struct AuthorInfo: FetchableRecord, Decodable {
|
||||
var author: Author
|
||||
var books: [Book] // all associated books
|
||||
}
|
||||
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
- [The Structure of a Joined Request]
|
||||
- [Decoding a Joined Request with a Decodable Record]
|
||||
- [Decoding a Joined Request with FetchableRecord]
|
||||
@@ -1536,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))
|
||||
@@ -1557,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:
|
||||
|
||||
@@ -1684,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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1790,14 +1863,14 @@ The default name is built from the aggregating method, the **[association key](#
|
||||
|
||||
Those default names are lost whenever an aggregate is modified (negated, added, multiplied, whatever).
|
||||
|
||||
You can name or rename aggregates with the `aliased` method:
|
||||
You can name or rename aggregates with the `forKey` method:
|
||||
|
||||
```swift
|
||||
struct AuthorInfo: Decodable, FetchableRecord {
|
||||
var author: Author
|
||||
var numberOfBooks: Int
|
||||
}
|
||||
let numberOfBooks = Author.books.count.aliased("numberOfBooks") // <--
|
||||
let numberOfBooks = Author.books.count.forKey("numberOfBooks") // <--
|
||||
let request = Author.annotated(with: numberOfBooks)
|
||||
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
|
||||
|
||||
@@ -1805,7 +1878,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
|
||||
var author: Author
|
||||
var hasBooks: Bool
|
||||
}
|
||||
let hasBooks = (Author.books.isEmpty == false).aliased("hasBooks") // <--
|
||||
let hasBooks = (Author.books.isEmpty == false).forKey("hasBooks") // <--
|
||||
let request = Author.annotated(with: hasBooks)
|
||||
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
|
||||
|
||||
@@ -1813,7 +1886,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
|
||||
var author: Author
|
||||
var workCount: Int
|
||||
}
|
||||
let workCount = (Author.books.count + Author.paintings.count).aliased("workCount") // <--
|
||||
let workCount = (Author.books.count + Author.paintings.count).forKey("workCount") // <--
|
||||
let request = Author.annotated(with: workCount)
|
||||
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
|
||||
```
|
||||
@@ -1826,7 +1899,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
|
||||
var numberOfBooks: Int
|
||||
|
||||
static func all() -> QueryInterfaceRequest<AuthorInfo> {
|
||||
let numberOfBooks = Author.books.count.aliased(CodingKey.numberOfBooks) // <--
|
||||
let numberOfBooks = Author.books.count.forKey(CodingKey.numberOfBooks) // <--
|
||||
return Author
|
||||
.annotated(with: numberOfBooks)
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
@@ -2040,7 +2113,7 @@ Aggregates can be modified and combined with Swift operators:
|
||||
|
||||
```swift
|
||||
let workCount = Author.books.count + Author.paintings.count)
|
||||
let request = Author.annotated(with: workCount.aliased("workCount"))
|
||||
let request = Author.annotated(with: workCount.forKey("workCount"))
|
||||
```
|
||||
|
||||
- IFNULL operator `??`
|
||||
@@ -2132,7 +2205,7 @@ In this other example, the `Author.books` and `Author.paintings` have the distin
|
||||
|
||||
let aggregate = Author.books.count + // association key "books"
|
||||
Author.paintings.count // association key "paintings"
|
||||
let request = Author.annotated(with: aggregate.aliased("workCount"))
|
||||
let request = Author.annotated(with: aggregate.forKey("workCount"))
|
||||
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
@@ -2200,11 +2273,11 @@ But in the following example, we use the same association `Author.books` twice,
|
||||
let novelCount = Author.books // association key "books"
|
||||
.filter(Column("kind") == "novel")
|
||||
.count
|
||||
.aliased("novelCount")
|
||||
.forKey("novelCount")
|
||||
let theatrePlayCount = Author.books // association key "books"
|
||||
.filter(Column("kind") == "theatrePlay")
|
||||
.count
|
||||
.aliased("theatrePlayCount")
|
||||
.forKey("theatrePlayCount")
|
||||
let request = Author.annotated(with: novelCount, theatrePlayCount)
|
||||
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
|
||||
```
|
||||
@@ -2214,35 +2287,40 @@ But in the following example, we use the same association `Author.books` twice,
|
||||
|
||||
The `DerivableRequest` protocol is adopted by both [query interface requests] such as `Author.all()` and associations such as `Book.author`. It is intended for you to use as a customization point when you want to extend the built-in GRDB apis.
|
||||
|
||||
For example:
|
||||
For example, we may want to define `orderedByName()` and `filter(country:)` request methods that make our requests easier to read:
|
||||
|
||||
```swift
|
||||
// Authors sorted by name
|
||||
let request = Author.all().orderedByName()
|
||||
|
||||
// French authors ordered by name
|
||||
let request = Author.all().filter(country: "FR").orderedByName()
|
||||
|
||||
// Spanish books
|
||||
let request = Book.all().filter(country: "ES")
|
||||
```
|
||||
|
||||
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 orderByFullName() -> Self {
|
||||
return order(
|
||||
Column("lastName").collating(.localizedCaseInsensitiveCompare),
|
||||
Column("firstName").collating(.localizedCaseInsensitiveCompare))
|
||||
func orderedByName() -> Self {
|
||||
order(Column("name").collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
}
|
||||
|
||||
extension DerivableRequest where RowDecoder == Book {
|
||||
func filter(country: String) -> Self {
|
||||
joining(required: Book.author.filter(country: country))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Thanks to DerivableRequest, both the `filter(country:)` and `orderByFullName()` methods are now available for both Author-based requests and associations:
|
||||
|
||||
```swift
|
||||
// French authors sorted by full name:
|
||||
let request = Author.all()
|
||||
.filter(country: "FR")
|
||||
.orderByFullName()
|
||||
|
||||
// French books, sorted by full name of author:
|
||||
let request = Book.joining(required: Book.author
|
||||
.filter(country: "FR")
|
||||
.orderByFullName())
|
||||
```
|
||||
See [Good Practices for Designing Record Types] for more information.
|
||||
|
||||
|
||||
## Known Issues
|
||||
@@ -2301,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:
|
||||
|
||||
@@ -2341,6 +2419,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
[HasOneThrough]: #hasonethrough
|
||||
[Choosing Between BelongsTo and HasOne]: #choosing-between-belongsto-and-hasone
|
||||
[Self Joins]: #self-joins
|
||||
[Ordered Associations]: #ordered-associations
|
||||
[The Types of Associations]: #the-types-of-associations
|
||||
[FetchableRecord]: ../README.md#fetchablerecord-protocols
|
||||
[migration]: ../README.md#migrations
|
||||
|
||||
@@ -3,7 +3,7 @@ Custom SQLite Builds
|
||||
|
||||
By default, GRDB uses the version of SQLite that ships with the target operating system.
|
||||
|
||||
**You can build GRDB with a custom build of [SQLite 3.27.2](https://www.sqlite.org/changes.html).**
|
||||
**You can build GRDB with a custom build of [SQLite 3.28.0](https://www.sqlite.org/changes.html).**
|
||||
|
||||
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](../../../#support-for-sqlite-pre-update-hooks).
|
||||
|
||||
@@ -11,13 +11,13 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
|
||||
**To install GRDB with a custom SQLite build:**
|
||||
|
||||
1. Clone the GRDB git repository, checkout the latest tagged version, and download SQLite sources:
|
||||
1. Clone the GRDB git repository, checkout the latest tagged version:
|
||||
|
||||
```sh
|
||||
cd [GRDB directory]
|
||||
git checkout v4.0.0
|
||||
git checkout [latest tag]
|
||||
git submodule update --init SQLiteCustom/src
|
||||
````
|
||||
```
|
||||
|
||||
2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5` and `SQLITE_ENABLE_PREUPDATE_HOOK`.
|
||||
|
||||
@@ -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**:
|
||||
|
||||
@@ -120,13 +120,15 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
```
|
||||
|
||||
The path should be the path to your `GRDBCustomSQLite-INSTALL.sh` file.
|
||||
|
||||
Select your application target in the "Provide build settings from" menu.
|
||||
|
||||
9. Check the "Shared" checkbox of your application scheme (this lets you commit the pre-action in your Version Control System).
|
||||
|
||||
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 {
|
||||
|
||||
@@ -7,6 +7,10 @@
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
56606D202355938A00185962 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D142355931F00185962 /* GRDB.framework */; };
|
||||
56606D212355938A00185962 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D142355931F00185962 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
|
||||
56606D24235593AB00185962 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D182355931F00185962 /* GRDB.framework */; };
|
||||
56606D25235593AB00185962 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D182355931F00185962 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
|
||||
568E5FC31E926430002582E0 /* Interface.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FC11E926430002582E0 /* Interface.storyboard */; };
|
||||
568E5FC51E926430002582E0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FC41E926430002582E0 /* Assets.xcassets */; };
|
||||
568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = 568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
|
||||
@@ -14,8 +18,6 @@
|
||||
568E5FD31E926430002582E0 /* ExtensionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568E5FD21E926430002582E0 /* ExtensionDelegate.swift */; };
|
||||
568E5FD51E926430002582E0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FD41E926430002582E0 /* Assets.xcassets */; };
|
||||
568E5FD91E926430002582E0 /* GRDBDemoWatchOS.app in Embed Watch Content */ = {isa = PBXBuildFile; fileRef = 568E5FBF1E926430002582E0 /* GRDBDemoWatchOS.app */; };
|
||||
568E5FE41E926547002582E0 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0365B1E8D9F79003B6DA4 /* GRDB.framework */; };
|
||||
568E5FE51E926547002582E0 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0365B1E8D9F79003B6DA4 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
|
||||
56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */; };
|
||||
56B0360C1E8D9EBE003B6DA4 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */; };
|
||||
56B0360E1E8D9EBE003B6DA4 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */; };
|
||||
@@ -24,17 +26,78 @@
|
||||
56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Player.swift */; };
|
||||
56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */; };
|
||||
56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */; };
|
||||
56B0365E1E8D9FB1003B6DA4 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0364D1E8D9F79003B6DA4 /* GRDB.framework */; };
|
||||
56B0365F1E8D9FB1003B6DA4 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0364D1E8D9F79003B6DA4 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
563BD2F01F8364C1006A5390 /* PBXContainerItemProxy */ = {
|
||||
56606D092355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56439B501F4CA1DC0066043F;
|
||||
remoteInfo = GRDBOSXPerformanceComparisonTests;
|
||||
remoteGlobalIDString = DC3773F319C8CBB3004FCF85;
|
||||
remoteInfo = GRDBOSX;
|
||||
};
|
||||
56606D0B2355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56E5D7F91B4D422D00430942;
|
||||
remoteInfo = GRDBOSXTests;
|
||||
};
|
||||
56606D112355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56553C181C3E906C00522B5C;
|
||||
remoteInfo = GRDBOSXCrashTests;
|
||||
};
|
||||
56606D132355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56E5D7CA1B4D3FED00430942;
|
||||
remoteInfo = GRDBiOS;
|
||||
};
|
||||
56606D152355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56E5D7D31B4D3FEE00430942;
|
||||
remoteInfo = GRDBiOSTests;
|
||||
};
|
||||
56606D172355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 565490A01D5A4798005622CB;
|
||||
remoteInfo = GRDBWatchOS;
|
||||
};
|
||||
56606D192355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = AAA4DCFE230F1E0600C74B15;
|
||||
remoteInfo = GRDBtvOS;
|
||||
};
|
||||
56606D1B2355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = AAA4DDD4230F262000C74B15;
|
||||
remoteInfo = GRDBtvOSTests;
|
||||
};
|
||||
56606D1D2355937900185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 56E5D7C91B4D3FED00430942;
|
||||
remoteInfo = GRDBiOS;
|
||||
};
|
||||
56606D22235593A300185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 5654909F1D5A4798005622CB;
|
||||
remoteInfo = GRDBWatchOS;
|
||||
};
|
||||
568E5FCD1E926430002582E0 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
@@ -50,83 +113,6 @@
|
||||
remoteGlobalIDString = 568E5FBE1E926430002582E0;
|
||||
remoteInfo = GRDBDemoWatchOS;
|
||||
};
|
||||
568E5FE21E926535002582E0 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 5654909F1D5A4798005622CB;
|
||||
remoteInfo = GRDBWatchOS;
|
||||
};
|
||||
568E5FE61E926547002582E0 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 5654909F1D5A4798005622CB;
|
||||
remoteInfo = GRDBWatchOS;
|
||||
};
|
||||
56B0363A1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = DC3773F319C8CBB3004FCF85;
|
||||
remoteInfo = GRDBOSX;
|
||||
};
|
||||
56B0363C1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56E5D7F91B4D422D00430942;
|
||||
remoteInfo = GRDBOSXTests;
|
||||
};
|
||||
56B0363E1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 560C981A1C0E22D300BF8471;
|
||||
remoteInfo = GRDBOSXPerformanceTests;
|
||||
};
|
||||
56B036401E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56553C181C3E906C00522B5C;
|
||||
remoteInfo = GRDBOSXCrashTests;
|
||||
};
|
||||
56B0364C1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56E5D7CA1B4D3FED00430942;
|
||||
remoteInfo = GRDBiOS;
|
||||
};
|
||||
56B0364E1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56E5D7D31B4D3FEE00430942;
|
||||
remoteInfo = GRDBiOSTests;
|
||||
};
|
||||
56B0365A1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 565490A01D5A4798005622CB;
|
||||
remoteInfo = GRDBWatchOS;
|
||||
};
|
||||
56B0365C1E8D9F8F003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 56E5D7C91B4D3FED00430942;
|
||||
remoteInfo = GRDBiOS;
|
||||
};
|
||||
56B036601E8D9FB1003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 56E5D7C91B4D3FED00430942;
|
||||
remoteInfo = GRDBiOS;
|
||||
};
|
||||
/* End PBXContainerItemProxy section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
@@ -158,7 +144,7 @@
|
||||
dstPath = "";
|
||||
dstSubfolderSpec = 10;
|
||||
files = (
|
||||
568E5FE51E926547002582E0 /* GRDB.framework in Embed Frameworks */,
|
||||
56606D25235593AB00185962 /* GRDB.framework in Embed Frameworks */,
|
||||
);
|
||||
name = "Embed Frameworks";
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
@@ -169,7 +155,7 @@
|
||||
dstPath = "";
|
||||
dstSubfolderSpec = 10;
|
||||
files = (
|
||||
56B0365F1E8D9FB1003B6DA4 /* GRDB.framework in Embed Frameworks */,
|
||||
56606D212355938A00185962 /* GRDB.framework in Embed Frameworks */,
|
||||
);
|
||||
name = "Embed Frameworks";
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
@@ -196,7 +182,7 @@
|
||||
56B0361A1E8D9F38003B6DA4 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = "<group>"; };
|
||||
56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionViewController.swift; sourceTree = "<group>"; };
|
||||
56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayersViewController.swift; sourceTree = "<group>"; };
|
||||
56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../GRDB.xcodeproj; sourceTree = "<group>"; };
|
||||
56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
@@ -204,7 +190,7 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
568E5FE41E926547002582E0 /* GRDB.framework in Frameworks */,
|
||||
56606D24235593AB00185962 /* GRDB.framework in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -212,13 +198,35 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
56B0365E1E8D9FB1003B6DA4 /* GRDB.framework in Frameworks */,
|
||||
56606D202355938A00185962 /* GRDB.framework in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
56606CFD2355931F00185962 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56606D0A2355931F00185962 /* GRDB.framework */,
|
||||
56606D0C2355931F00185962 /* GRDBOSXTests.xctest */,
|
||||
56606D122355931F00185962 /* GRDBOSXCrashTests.xctest */,
|
||||
56606D142355931F00185962 /* GRDB.framework */,
|
||||
56606D162355931F00185962 /* GRDBiOSTests.xctest */,
|
||||
56606D182355931F00185962 /* GRDB.framework */,
|
||||
56606D1A2355931F00185962 /* GRDB.framework */,
|
||||
56606D1C2355931F00185962 /* GRDBtvOSTests.xctest */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56606D1F2355938A00185962 /* Frameworks */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
);
|
||||
name = Frameworks;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
568E5FC01E926430002582E0 /* GRDBDemoWatchOS */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -248,6 +256,7 @@
|
||||
568E5FC01E926430002582E0 /* GRDBDemoWatchOS */,
|
||||
568E5FCF1E926430002582E0 /* GRDBDemoWatchOS Extension */,
|
||||
56B036041E8D9EBE003B6DA4 /* Products */,
|
||||
56606D1F2355938A00185962 /* Frameworks */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
@@ -277,21 +286,6 @@
|
||||
path = GRDBDemoiOS;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56B036271E8D9F79003B6DA4 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56B0363B1E8D9F79003B6DA4 /* GRDB.framework */,
|
||||
56B0363D1E8D9F79003B6DA4 /* GRDBOSXTests.xctest */,
|
||||
56B0363F1E8D9F79003B6DA4 /* GRDBOSXPerformanceTests.xctest */,
|
||||
563BD2F11F8364C1006A5390 /* GRDBOSXPerformanceComparisonTests.xctest */,
|
||||
56B036411E8D9F79003B6DA4 /* GRDBOSXCrashTests.xctest */,
|
||||
56B0364D1E8D9F79003B6DA4 /* GRDB.framework */,
|
||||
56B0364F1E8D9F79003B6DA4 /* GRDBiOSTests.xctest */,
|
||||
56B0365B1E8D9F79003B6DA4 /* GRDB.framework */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
@@ -324,8 +318,7 @@
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
568E5FE31E926535002582E0 /* PBXTargetDependency */,
|
||||
568E5FE71E926547002582E0 /* PBXTargetDependency */,
|
||||
56606D23235593A300185962 /* PBXTargetDependency */,
|
||||
);
|
||||
name = "GRDBDemoWatchOS Extension";
|
||||
productName = "GRDBDemoWatchOS Extension";
|
||||
@@ -345,8 +338,7 @@
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
56B0365D1E8D9F8F003B6DA4 /* PBXTargetDependency */,
|
||||
56B036611E8D9FB1003B6DA4 /* PBXTargetDependency */,
|
||||
56606D1E2355937900185962 /* PBXTargetDependency */,
|
||||
568E5FD81E926430002582E0 /* PBXTargetDependency */,
|
||||
);
|
||||
name = GRDBDemoiOS;
|
||||
@@ -372,11 +364,13 @@
|
||||
568E5FCA1E926430002582E0 = {
|
||||
CreatedOnToolsVersion = 8.3;
|
||||
DevelopmentTeam = AMD8W895CT;
|
||||
LastSwiftMigration = 1020;
|
||||
ProvisioningStyle = Automatic;
|
||||
};
|
||||
56B036021E8D9EBE003B6DA4 = {
|
||||
CreatedOnToolsVersion = 8.3;
|
||||
DevelopmentTeam = AMD8W895CT;
|
||||
LastSwiftMigration = 1020;
|
||||
ProvisioningStyle = Automatic;
|
||||
};
|
||||
};
|
||||
@@ -394,7 +388,7 @@
|
||||
projectDirPath = "";
|
||||
projectReferences = (
|
||||
{
|
||||
ProductGroup = 56B036271E8D9F79003B6DA4 /* Products */;
|
||||
ProductGroup = 56606CFD2355931F00185962 /* Products */;
|
||||
ProjectRef = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
},
|
||||
);
|
||||
@@ -408,60 +402,60 @@
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXReferenceProxy section */
|
||||
563BD2F11F8364C1006A5390 /* GRDBOSXPerformanceComparisonTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBOSXPerformanceComparisonTests.xctest;
|
||||
remoteRef = 563BD2F01F8364C1006A5390 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B0363B1E8D9F79003B6DA4 /* GRDB.framework */ = {
|
||||
56606D0A2355931F00185962 /* GRDB.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDB.framework;
|
||||
remoteRef = 56B0363A1E8D9F79003B6DA4 /* PBXContainerItemProxy */;
|
||||
remoteRef = 56606D092355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B0363D1E8D9F79003B6DA4 /* GRDBOSXTests.xctest */ = {
|
||||
56606D0C2355931F00185962 /* GRDBOSXTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBOSXTests.xctest;
|
||||
remoteRef = 56B0363C1E8D9F79003B6DA4 /* PBXContainerItemProxy */;
|
||||
remoteRef = 56606D0B2355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B0363F1E8D9F79003B6DA4 /* GRDBOSXPerformanceTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBOSXPerformanceTests.xctest;
|
||||
remoteRef = 56B0363E1E8D9F79003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B036411E8D9F79003B6DA4 /* GRDBOSXCrashTests.xctest */ = {
|
||||
56606D122355931F00185962 /* GRDBOSXCrashTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBOSXCrashTests.xctest;
|
||||
remoteRef = 56B036401E8D9F79003B6DA4 /* PBXContainerItemProxy */;
|
||||
remoteRef = 56606D112355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B0364D1E8D9F79003B6DA4 /* GRDB.framework */ = {
|
||||
56606D142355931F00185962 /* GRDB.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDB.framework;
|
||||
remoteRef = 56B0364C1E8D9F79003B6DA4 /* PBXContainerItemProxy */;
|
||||
remoteRef = 56606D132355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B0364F1E8D9F79003B6DA4 /* GRDBiOSTests.xctest */ = {
|
||||
56606D162355931F00185962 /* GRDBiOSTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBiOSTests.xctest;
|
||||
remoteRef = 56B0364E1E8D9F79003B6DA4 /* PBXContainerItemProxy */;
|
||||
remoteRef = 56606D152355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B0365B1E8D9F79003B6DA4 /* GRDB.framework */ = {
|
||||
56606D182355931F00185962 /* GRDB.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDB.framework;
|
||||
remoteRef = 56B0365A1E8D9F79003B6DA4 /* PBXContainerItemProxy */;
|
||||
remoteRef = 56606D172355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56606D1A2355931F00185962 /* GRDB.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDB.framework;
|
||||
remoteRef = 56606D192355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56606D1C2355931F00185962 /* GRDBtvOSTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBtvOSTests.xctest;
|
||||
remoteRef = 56606D1B2355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
/* End PBXReferenceProxy section */
|
||||
@@ -521,6 +515,16 @@
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXTargetDependency section */
|
||||
56606D1E2355937900185962 /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = GRDBiOS;
|
||||
targetProxy = 56606D1D2355937900185962 /* PBXContainerItemProxy */;
|
||||
};
|
||||
56606D23235593A300185962 /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = GRDBWatchOS;
|
||||
targetProxy = 56606D22235593A300185962 /* PBXContainerItemProxy */;
|
||||
};
|
||||
568E5FCE1E926430002582E0 /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
target = 568E5FCA1E926430002582E0 /* GRDBDemoWatchOS Extension */;
|
||||
@@ -531,26 +535,6 @@
|
||||
target = 568E5FBE1E926430002582E0 /* GRDBDemoWatchOS */;
|
||||
targetProxy = 568E5FD71E926430002582E0 /* PBXContainerItemProxy */;
|
||||
};
|
||||
568E5FE31E926535002582E0 /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = GRDBWatchOS;
|
||||
targetProxy = 568E5FE21E926535002582E0 /* PBXContainerItemProxy */;
|
||||
};
|
||||
568E5FE71E926547002582E0 /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = GRDBWatchOS;
|
||||
targetProxy = 568E5FE61E926547002582E0 /* PBXContainerItemProxy */;
|
||||
};
|
||||
56B0365D1E8D9F8F003B6DA4 /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = GRDBiOS;
|
||||
targetProxy = 56B0365C1E8D9F8F003B6DA4 /* PBXContainerItemProxy */;
|
||||
};
|
||||
56B036611E8D9FB1003B6DA4 /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = GRDBiOS;
|
||||
targetProxy = 56B036601E8D9FB1003B6DA4 /* PBXContainerItemProxy */;
|
||||
};
|
||||
/* End PBXTargetDependency section */
|
||||
|
||||
/* Begin PBXVariantGroup section */
|
||||
@@ -594,7 +578,6 @@
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
TARGETED_DEVICE_FAMILY = 4;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 3.2;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -611,7 +594,6 @@
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
TARGETED_DEVICE_FAMILY = 4;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 3.2;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
@@ -629,7 +611,6 @@
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
TARGETED_DEVICE_FAMILY = 4;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 3.2;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -647,7 +628,6 @@
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
TARGETED_DEVICE_FAMILY = 4;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 3.2;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
@@ -701,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 = 4.2;
|
||||
SWIFT_VERSION = 5.0;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 2.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -754,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 = 4.2;
|
||||
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 = "1020"
|
||||
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 = "1020"
|
||||
LastUpgradeVersion = "1130"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -27,8 +27,6 @@
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
@@ -38,8 +36,8 @@
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
<Testables>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Release"
|
||||
@@ -61,8 +59,6 @@
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
@@ -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" : {
|
||||
|
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>
|
||||
@@ -8,6 +8,9 @@ struct Player {
|
||||
var score: Int
|
||||
}
|
||||
|
||||
// Hashable conformance supports tableView diffing
|
||||
extension Player: Hashable { }
|
||||
|
||||
// MARK: - Persistence
|
||||
|
||||
// Turn Player into a Codable Record.
|
||||
@@ -32,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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,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)
|
||||
}
|
||||
}
|
||||
@@ -9,12 +9,13 @@ class PlayersViewController: UITableViewController {
|
||||
}
|
||||
|
||||
@IBOutlet private weak var newPlayerButtonItem: UIBarButtonItem!
|
||||
private var playersController: FetchedRecordsController<Player>!
|
||||
private var playerCountObserver: TransactionObserver?
|
||||
private var players: [Player] = []
|
||||
private var playersCancellable: DatabaseCancellable?
|
||||
private var playerCountCancellable: DatabaseCancellable?
|
||||
private var playerOrdering: PlayerOrdering = .byScore {
|
||||
didSet {
|
||||
try! playersController.setRequest(playersRequest)
|
||||
configureOrderingBarButtonItem()
|
||||
configureTableView()
|
||||
}
|
||||
}
|
||||
private var playersRequest: QueryInterfaceRequest<Player> {
|
||||
@@ -58,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))
|
||||
}
|
||||
@@ -71,58 +72,69 @@ class PlayersViewController: UITableViewController {
|
||||
|
||||
private func configureTitle() {
|
||||
// Track changes in the number of players
|
||||
playerCountObserver = try! ValueObservation
|
||||
.trackingCount(playersRequest)
|
||||
.start(in: dbQueue) { [unowned self] count in
|
||||
let observation = ValueObservation.tracking { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
playerCountCancellable = observation.start(
|
||||
in: dbQueue,
|
||||
scheduling: .immediate,
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] count in
|
||||
guard let self = self else { return }
|
||||
switch count {
|
||||
case 0: self.navigationItem.title = "No Player"
|
||||
case 1: self.navigationItem.title = "1 Player"
|
||||
default: self.navigationItem.title = "\(count) Players"
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private func configureTableView() {
|
||||
// Track changes in the database players
|
||||
playersController = try! FetchedRecordsController(dbQueue, request: playersRequest)
|
||||
|
||||
// Animate changes in the table view
|
||||
playersController.trackChanges(
|
||||
willChange: { [unowned self] _ in
|
||||
self.tableView.beginUpdates()
|
||||
},
|
||||
onChange: { [unowned self] (controller, record, change) in
|
||||
switch change {
|
||||
case .insertion(let indexPath):
|
||||
self.tableView.insertRows(at: [indexPath], with: .fade)
|
||||
|
||||
case .deletion(let indexPath):
|
||||
self.tableView.deleteRows(at: [indexPath], with: .fade)
|
||||
|
||||
case .update(let indexPath, _):
|
||||
if let cell = self.tableView.cellForRow(at: indexPath) {
|
||||
self.configure(cell, at: indexPath)
|
||||
}
|
||||
|
||||
case .move(let indexPath, let newIndexPath, _):
|
||||
// Actually move cells around for more demo effect :-)
|
||||
let cell = self.tableView.cellForRow(at: indexPath)
|
||||
self.tableView.moveRow(at: indexPath, to: newIndexPath)
|
||||
if let cell = cell {
|
||||
self.configure(cell, at: newIndexPath)
|
||||
}
|
||||
|
||||
// A quieter animation:
|
||||
// self.tableView.deleteRows(at: [indexPath], with: .fade)
|
||||
// self.tableView.insertRows(at: [newIndexPath], with: .fade)
|
||||
}
|
||||
},
|
||||
didChange: { [unowned self] _ in
|
||||
self.tableView.endUpdates()
|
||||
// Track changes in the list of players
|
||||
let request = self.playersRequest
|
||||
let observation = ValueObservation.tracking { db in
|
||||
try request.fetchAll(db)
|
||||
}
|
||||
playersCancellable = observation.start(
|
||||
in: dbQueue,
|
||||
scheduling: .immediate,
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
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()
|
||||
|
||||
// Initial fetch
|
||||
try! playersController.performFetch()
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,7 +145,7 @@ extension PlayersViewController {
|
||||
|
||||
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
|
||||
if segue.identifier == "Edit" {
|
||||
let player = playersController.record(at: tableView.indexPathForSelectedRow!)
|
||||
let player = players[tableView.indexPathForSelectedRow!.row]
|
||||
let controller = segue.destination as! PlayerEditionViewController
|
||||
controller.title = player.name
|
||||
controller.player = player
|
||||
@@ -162,12 +174,8 @@ extension PlayersViewController {
|
||||
// MARK: - UITableViewDataSource
|
||||
|
||||
extension PlayersViewController {
|
||||
override func numberOfSections(in tableView: UITableView) -> Int {
|
||||
return playersController.sections.count
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
||||
return playersController.sections[section].numberOfRecords
|
||||
players.count
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
||||
@@ -178,14 +186,14 @@ extension PlayersViewController {
|
||||
|
||||
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
|
||||
// Delete the player
|
||||
let player = playersController.record(at: indexPath)
|
||||
let player = players[indexPath.row]
|
||||
try! dbQueue.write { db in
|
||||
_ = try player.delete(db)
|
||||
}
|
||||
}
|
||||
|
||||
private func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
|
||||
let player = playersController.record(at: indexPath)
|
||||
let player = players[indexPath.row]
|
||||
if player.name.isEmpty {
|
||||
cell.textLabel?.text = "-"
|
||||
} else {
|
||||
@@ -7,7 +7,7 @@ Demo Application
|
||||
|
||||
- how to setup a database in an iOS app
|
||||
- how to define a simple [Codable Record](../../README.md#codable-records)
|
||||
- how to track database changes and animate a table view with [FetchedRecordsController](../../README.md#fetchedrecordscontroller).
|
||||
- how to track database changes and animate a table view with [ValueObservation](../../README.md#valueobservation).
|
||||
|
||||
**Files of interest:**
|
||||
|
||||
@@ -25,7 +25,7 @@ Demo Application
|
||||
|
||||
- [PlayersViewController.swift](GRDBDemoiOS/PlayersViewController.swift)
|
||||
|
||||
`PlayersViewController` displays a list of players. It keeps its title up-to-date with [ValueObservation](../../README.md#valueobservation), and animates its table view according to database changes with [FetchedRecordsController](../../README.md#fetchedrecordscontroller).
|
||||
`PlayersViewController` displays a list of players. It keeps its view up-to-date with [ValueObservation](../../README.md#valueobservation).
|
||||
|
||||
- [PlayerEditionViewController.swift](GRDBDemoiOS/PlayerEditionViewController.swift)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
# FetchedRecordsController
|
||||
|
||||
**FetchedRecordsController is a sunsetted GRDB API.**
|
||||
|
||||
It is not deprecated. But FetchedRecordsController has known limitations which are not planned to be lifted.
|
||||
|
||||
You are advised to use [ValueObservation] instead of FetchedRecordsController.
|
||||
|
||||
---
|
||||
|
||||
**FetchedRecordsController tracks changes in the results of a request, feeds table views and collection views, and animates cells when the results of the request change.**
|
||||
|
||||
It looks and behaves very much like [Core Data's NSFetchedResultsController](https://developer.apple.com/library/ios/documentation/CoreData/Reference/NSFetchedResultsController_Class/).
|
||||
|
||||
Given a fetch request, and a type that adopts the [FetchableRecord] protocol, such as a subclass of the [Record](../README.md#record-class) class, a FetchedRecordsController is able to track changes in the results of the fetch request, notify of those changes, and return the results of the request in a form that is suitable for a table view or a collection view, with one cell per fetched record.
|
||||
|
||||
- [Creating the Fetched Records Controller](#creating-the-fetched-records-controller)
|
||||
- [Responding to Changes](#responding-to-changes)
|
||||
- [The Changes Notifications](#the-changes-notifications)
|
||||
- [Modifying the Fetch Request](#modifying-the-fetch-request)
|
||||
- [Table and Collection Views](#table-and-collection-views)
|
||||
- [Implementing the Table View Datasource Methods](#implementing-the-table-view-datasource-methods)
|
||||
- [Implementing Table View Updates](#implementing-table-view-updates)
|
||||
- [FetchedRecordsController Concurrency](#fetchedrecordscontroller-concurrency)
|
||||
|
||||
|
||||
## Creating the Fetched Records Controller
|
||||
|
||||
When you initialize a fetched records controller, you provide the following mandatory information:
|
||||
|
||||
- A [database connection](../README.md#database-connections)
|
||||
- The type of the fetched records. It must be a type that adopts the [FetchableRecord] protocol, such as a subclass of the [Record](../README.md#record-class) class
|
||||
- A fetch request
|
||||
|
||||
```swift
|
||||
class Player : Record { ... }
|
||||
let dbQueue = DatabaseQueue(...) // or DatabasePool
|
||||
|
||||
// Using a Request from the Query Interface:
|
||||
let controller = FetchedRecordsController(
|
||||
dbQueue,
|
||||
request: Player.order(Column("name")))
|
||||
|
||||
// Using SQL, and eventual arguments:
|
||||
let controller = FetchedRecordsController<Player>(
|
||||
dbQueue,
|
||||
sql: "SELECT * FROM player ORDER BY name WHERE countryCode = ?",
|
||||
arguments: ["FR"])
|
||||
```
|
||||
|
||||
The fetch request can involve several database tables. The fetched records controller will only track changes in the columns and tables used by the fetch request.
|
||||
|
||||
```swift
|
||||
let controller = FetchedRecordsController<Author>(
|
||||
dbQueue,
|
||||
sql: """
|
||||
SELECT author.name, COUNT(book.id) AS bookCount
|
||||
FROM author
|
||||
LEFT JOIN book ON book.authorId = author.id
|
||||
GROUP BY author.id
|
||||
ORDER BY author.name
|
||||
""")
|
||||
```
|
||||
|
||||
|
||||
After creating an instance, you invoke `performFetch()` to actually execute
|
||||
the fetch.
|
||||
|
||||
```swift
|
||||
try controller.performFetch()
|
||||
```
|
||||
|
||||
|
||||
## Responding to Changes
|
||||
|
||||
In general, FetchedRecordsController is designed to respond to changes at *the database layer*, by [notifying](#the-changes-notifications) when *database rows* change location or values.
|
||||
|
||||
Changes are not reflected until they are applied in the database by a successful [transaction](../README.md#transactions-and-savepoints):
|
||||
|
||||
```swift
|
||||
// One transaction
|
||||
try dbQueue.write { db in // or dbPool.write
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
}
|
||||
|
||||
// One transaction
|
||||
try dbQueue.inTransaction { db in // or dbPool.writeInTransaction
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
return .commit
|
||||
}
|
||||
|
||||
// Two transactions
|
||||
try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
}
|
||||
```
|
||||
|
||||
When you apply several changes to the database, you should group them in a single explicit transaction. The controller will then notify of all changes together.
|
||||
|
||||
|
||||
## The Changes Notifications
|
||||
|
||||
An instance of FetchedRecordsController notifies that the controller’s fetched records have been changed by the mean of *callbacks*:
|
||||
|
||||
```swift
|
||||
let controller = try FetchedRecordsController(...)
|
||||
|
||||
controller.trackChanges(
|
||||
// controller's records are about to change:
|
||||
willChange: { controller in ... },
|
||||
|
||||
// notification of individual record changes:
|
||||
onChange: { (controller, record, change) in ... },
|
||||
|
||||
// controller's records have changed:
|
||||
didChange: { controller in ... })
|
||||
|
||||
try controller.performFetch()
|
||||
```
|
||||
|
||||
See [Implementing Table View Updates](#implementing-table-view-updates) for more detail on table view updates.
|
||||
|
||||
**All callbacks are optional.** When you only need to grab the latest results, you can omit the `didChange` argument name:
|
||||
|
||||
```swift
|
||||
controller.trackChanges { controller in
|
||||
let newPlayers = controller.fetchedRecords // [Player]
|
||||
}
|
||||
```
|
||||
|
||||
> :warning: **Warning**: notification of individual record changes (the `onChange` callback) has FetchedRecordsController use a diffing algorithm that has a high complexity, a high memory consumption, and is thus **not suited for large result sets**. One hundred rows is probably OK, but one thousand is probably not. If your application experiences problems with large lists, see [Issue 263](https://github.com/groue/GRDB.swift/issues/263) for more information.
|
||||
|
||||
Callbacks have the fetched record controller itself as an argument: use it in order to avoid memory leaks:
|
||||
|
||||
```swift
|
||||
// BAD: memory leak
|
||||
controller.trackChanges { _ in
|
||||
let newPlayers = controller.fetchedRecords
|
||||
}
|
||||
|
||||
// GOOD
|
||||
controller.trackChanges { controller in
|
||||
let newPlayers = controller.fetchedRecords
|
||||
}
|
||||
```
|
||||
|
||||
**Callbacks are invoked asynchronously.** See [FetchedRecordsController Concurrency](#fetchedrecordscontroller-concurrency) for more information.
|
||||
|
||||
**Values fetched from inside callbacks may be inconsistent with the controller's records.** This is because after database has changed, and before the controller had the opportunity to invoke callbacks in the main thread, other database changes can happen.
|
||||
|
||||
To avoid inconsistencies, provide a `fetchAlongside` argument to the `trackChanges` method, as below:
|
||||
|
||||
```swift
|
||||
controller.trackChanges(
|
||||
fetchAlongside: { db in
|
||||
// Fetch any extra value, for example the number of fetched records:
|
||||
return try Player.fetchCount(db)
|
||||
},
|
||||
didChange: { (controller, count) in
|
||||
// The extra value is the second argument.
|
||||
let recordsCount = controller.fetchedRecords.count
|
||||
assert(count == recordsCount) // guaranteed
|
||||
})
|
||||
```
|
||||
|
||||
Whenever the fetched records controller can not look for changes after a transaction has potentially modified the tracked request, an error handler is called. The request observation is not stopped, though: future transactions may successfully be handled, and the notified changes will then be based on the last successful fetch.
|
||||
|
||||
```swift
|
||||
controller.trackErrors { (controller, error) in
|
||||
print("Missed a transaction because \(error)")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Modifying the Fetch Request
|
||||
|
||||
You can change a fetched records controller's fetch request or SQL query.
|
||||
|
||||
```swift
|
||||
controller.setRequest(Player.order(Column("name")))
|
||||
controller.setRequest(sql: "SELECT ...", arguments: ...)
|
||||
```
|
||||
|
||||
The [notification callbacks](#the-changes-notifications) are notified of eventual changes if the new request fetches a different set of records.
|
||||
|
||||
> :point_up: **Note**: This behavior differs from Core Data's NSFetchedResultsController, which does not notify of record changes when the fetch request is replaced.
|
||||
|
||||
**Change callbacks are invoked asynchronously.** This means that modifying the request from the main thread does *not* immediately triggers callbacks. When you need to take immediate action, force the controller to refresh immediately with its `performFetch` method. In this case, changes callbacks are *not* called:
|
||||
|
||||
```swift
|
||||
// Change request on the main thread:
|
||||
controller.setRequest(Player.order(Column("name")))
|
||||
// Here callbacks have not been called yet.
|
||||
// You can cancel them, and refresh records immediately:
|
||||
try controller.performFetch()
|
||||
```
|
||||
|
||||
## Table and Collection Views
|
||||
|
||||
FetchedRecordsController let you feed table and collection views, and keep them up-to-date with the database content.
|
||||
|
||||
For nice animated updates, a fetched records controller needs to recognize identical records between two different result sets. When records adopt the [TableRecord] protocol, they are automatically compared according to their primary key:
|
||||
|
||||
```swift
|
||||
class Player : TableRecord { ... }
|
||||
let controller = FetchedRecordsController(
|
||||
dbQueue,
|
||||
request: Player.all())
|
||||
```
|
||||
|
||||
For other types, the fetched records controller needs you to be more explicit:
|
||||
|
||||
```swift
|
||||
let controller = FetchedRecordsController(
|
||||
dbQueue,
|
||||
request: ...,
|
||||
isSameRecord: { (player1, player2) in player1.id == player2.id })
|
||||
```
|
||||
|
||||
|
||||
### Implementing the Table View Datasource Methods
|
||||
|
||||
The table view data source asks the fetched records controller to provide relevant information:
|
||||
|
||||
```swift
|
||||
func numberOfSections(in tableView: UITableView) -> Int {
|
||||
fetchedRecordsController.sections.count
|
||||
}
|
||||
|
||||
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
||||
fetchedRecordsController.sections[section].numberOfRecords
|
||||
}
|
||||
|
||||
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
||||
let cell = ...
|
||||
let record = fetchedRecordsController.record(at: indexPath)
|
||||
// Configure the cell
|
||||
return cell
|
||||
}
|
||||
```
|
||||
|
||||
> :point_up: **Note**: In its current state, FetchedRecordsController does not support grouping table view rows into custom sections: it generates a unique section.
|
||||
|
||||
|
||||
### Implementing Table View Updates
|
||||
|
||||
When changes in the fetched records should reload the whole table view, you can simply tell so:
|
||||
|
||||
```swift
|
||||
controller.trackChanges { [unowned self] _ in
|
||||
self.tableView.reloadData()
|
||||
}
|
||||
```
|
||||
|
||||
Yet, FetchedRecordsController can notify that the controller’s fetched records have been changed due to some add, remove, move, or update operations, and help applying animated changes to a UITableView.
|
||||
|
||||
|
||||
#### Typical Table View Updates
|
||||
|
||||
For animated table view updates, use the `willChange` and `didChange` callbacks to bracket events provided by the fetched records controller, as illustrated in the following example:
|
||||
|
||||
```swift
|
||||
// Assume self has a tableView property, and a cell configuration
|
||||
// method named configure(_:at:).
|
||||
|
||||
controller.trackChanges(
|
||||
// controller's records are about to change:
|
||||
willChange: { [unowned self] _ in
|
||||
self.tableView.beginUpdates()
|
||||
},
|
||||
|
||||
// notification of individual record changes:
|
||||
onChange: { [unowned self] (controller, record, change) in
|
||||
switch change {
|
||||
case .insertion(let indexPath):
|
||||
self.tableView.insertRows(at: [indexPath], with: .fade)
|
||||
|
||||
case .deletion(let indexPath):
|
||||
self.tableView.deleteRows(at: [indexPath], with: .fade)
|
||||
|
||||
case .update(let indexPath, _):
|
||||
if let cell = self.tableView.cellForRow(at: indexPath) {
|
||||
self.configure(cell, at: indexPath)
|
||||
}
|
||||
|
||||
case .move(let indexPath, let newIndexPath, _):
|
||||
self.tableView.deleteRows(at: [indexPath], with: .fade)
|
||||
self.tableView.insertRows(at: [newIndexPath], with: .fade)
|
||||
|
||||
// // Alternate technique which actually moves cells around:
|
||||
// let cell = self.tableView.cellForRow(at: indexPath)
|
||||
// self.tableView.moveRow(at: indexPath, to: newIndexPath)
|
||||
// if let cell = cell {
|
||||
// self.configure(cell, at: newIndexPath)
|
||||
// }
|
||||
}
|
||||
},
|
||||
|
||||
// controller's records have changed:
|
||||
didChange: { [unowned self] _ in
|
||||
self.tableView.endUpdates()
|
||||
})
|
||||
```
|
||||
|
||||
> :warning: **Warning**: notification of individual record changes (the `onChange` callback) has FetchedRecordsController use a diffing algorithm that has a high complexity, a high memory consumption, and is thus **not suited for large result sets**. One hundred rows is probably OK, but one thousand is probably not. If your application experiences problems with large lists, see [Issue 263](https://github.com/groue/GRDB.swift/issues/263) for more information.
|
||||
>
|
||||
> :point_up: **Note**: our sample code above uses `unowned` references to the table view controller. This is a safe pattern as long as the table view controller owns the fetched records controller, and is deallocated from the main thread (this is usually the case). In other situations, prefer weak references.
|
||||
|
||||
|
||||
## FetchedRecordsController Concurrency
|
||||
|
||||
**A fetched records controller *can not* be used from any thread.**
|
||||
|
||||
When the database itself can be read and modified from [any thread](../README.md#database-connections), fetched records controllers **must** be used from the main thread. Record changes are also [notified](#the-changes-notifications) on the main thread.
|
||||
|
||||
**Change callbacks are invoked asynchronously.** This means that changes made from the main thread are *not* immediately notified. When you need to take immediate action, force the controller to refresh immediately with its `performFetch` method. In this case, changes callbacks are *not* called:
|
||||
|
||||
```swift
|
||||
// Change database on the main thread:
|
||||
try dbQueue.write { db in
|
||||
try Player(...).insert(db)
|
||||
}
|
||||
// Here callbacks have not been called yet.
|
||||
// You can cancel them, and refresh records immediately:
|
||||
try controller.performFetch()
|
||||
```
|
||||
|
||||
> :point_up: **Note**: when the main thread does not fit your needs, give a serial dispatch queue to the controller initializer: the controller must then be used from this queue, and record changes are notified on this queue as well.
|
||||
>
|
||||
> ```swift
|
||||
> let queue = DispatchQueue()
|
||||
> queue.async {
|
||||
> let controller = try FetchedRecordsController(..., queue: queue)
|
||||
> controller.trackChanges { /* in queue */ }
|
||||
> try controller.performFetch()
|
||||
> }
|
||||
> ```
|
||||
|
||||
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[GRDBCombine]: http://github.com/groue/GRDBCombine
|
||||
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
|
||||
[FetchableRecord]: ../README.md#fetchablerecord-protocol
|
||||
[TableRecord]: ../README.md#tablerecord-protocol
|
||||
@@ -0,0 +1,688 @@
|
||||
Full-Text Search
|
||||
================
|
||||
|
||||
**Full-Text Search is an efficient way to search a corpus of textual documents.**
|
||||
|
||||
```swift
|
||||
// Create full-text tables
|
||||
try db.create(virtualTable: "book", using: FTS4()) { t in // or FTS3(), or FTS5()
|
||||
t.column("author")
|
||||
t.column("title")
|
||||
t.column("body")
|
||||
}
|
||||
|
||||
// Populate full-text table with records or SQL
|
||||
try Book(...).insert(db)
|
||||
try db.execute(
|
||||
sql: "INSERT INTO book (author, title, body) VALUES (?, ?, ?)",
|
||||
arguments: [...])
|
||||
|
||||
// Build search patterns
|
||||
let pattern = FTS3Pattern(matchingPhrase: "Moby-Dick")
|
||||
|
||||
// Search with the query interface or SQL
|
||||
let books = try Book.matching(pattern).fetchAll(db)
|
||||
let books = try Book.fetchAll(db,
|
||||
sql: "SELECT * FROM book WHERE book MATCH ?",
|
||||
arguments: [pattern])
|
||||
```
|
||||
|
||||
- **[Choosing the Full-Text Engine](#choosing-the-full-text-engine)**
|
||||
- **[Enabling FTS5 Support](#enabling-fts5-support)**
|
||||
- **Create Full-Text Virtual Tables**: [FTS3/4](#create-fts3-and-fts4-virtual-tables), [FTS5](#create-fts5-virtual-tables)
|
||||
- **Choosing a Tokenizer**: [FTS3/4](#fts3-and-fts4-tokenizers), [FTS5](#fts5-tokenizers)
|
||||
- **Search Patterns**: [FTS3/4](#fts3pattern), [FTS5](#fts5pattern)
|
||||
- **Sorting by Relevance**: [FTS5](#fts5-sorting-by-relevance)
|
||||
- **External Content Full-Text Tables**: [FTS4/5](#external-content-full-text-tables)
|
||||
- **Full-Text Record**s: [FTS3/4/5](#full-text-records)
|
||||
- **Unicode Full-Text Gotchas**: [FTS3/4/5](#unicode-full-text-gotchas). Unicorns don't exist.
|
||||
- **Custom Tokenizers**: [FTS5](FTS5Tokenizers.md). Leverage extra full-text features such as synonyms or stop words. Avoid [unicode gotchas](#unicode-full-text-gotchas).
|
||||
- **Sample Code**: [WWDC Companion](https://github.com/groue/WWDCCompanion), an iOS app that stores, displays, and lets the user search the WWDC 2016 sessions.
|
||||
|
||||
|
||||
## Choosing the Full-Text Engine
|
||||
|
||||
**SQLite supports three full-text engines: [FTS3, FTS4](https://www.sqlite.org/fts3.html) and [FTS5](https://www.sqlite.org/fts5.html).**
|
||||
|
||||
Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this does not really tell which engine to choose for your application. Instead, make your choice depend on:
|
||||
|
||||
- **The full-text features needed by the application**:
|
||||
|
||||
| Full-Text Needs | FTS3 | FTS4 | FTS5 |
|
||||
| -------------------------------------------------------------------------- | :--: | :--: | :--: |
|
||||
| :question: Queries | | | |
|
||||
| **Words searches** (documents that contain "database") | X | X | X |
|
||||
| **Prefix searches** (documents that contain a word starting with "data") | X | X | X |
|
||||
| **Phrases searches** (documents that contain the phrase "SQLite database") | X | X | X |
|
||||
| **Boolean searches** (documents that contain "SQLite" or "database") | X | X | X |
|
||||
| **Proximity search** (documents that contain "SQLite" near "database") | X | X | X |
|
||||
| :scissors: Tokenization | | | |
|
||||
| **Ascii case insensitivity** (have "DATABASE" match "database") | X | X | X |
|
||||
| **Unicode case insensitivity** (have "ÉLÉGANCE" match "élégance") | X | X | X |
|
||||
| **Latin diacritics insensitivity** (have "elegance" match "élégance") | X | X | X |
|
||||
| **English Stemming** (have "frustration" match "frustrated") | X | X | X |
|
||||
| **English Stemming and Ascii case insensitivity** | X | X | X |
|
||||
| **English Stemming and Unicode case insensitivity** | | | X |
|
||||
| **English Stemming and Latin diacritics insensitivity** | | | X |
|
||||
| **Synonyms** (have "1st" match "first") | ¹ | ¹ | X ² |
|
||||
| **Pinyin and Romaji** (have "romaji" match "ローマ字") | ¹ | ¹ | X ² |
|
||||
| **Stop words** (don't index, and don't match words like "and" and "the") | ¹ | ¹ | X ² |
|
||||
| **Spell checking** (have "alamaba" match "alabama") | ¹ | ¹ | ¹ |
|
||||
| :bowtie: Other Features | | | |
|
||||
| **Ranking** (sort results by relevance) | ¹ | ¹ | X |
|
||||
| **Snippets** (display a few words around a match) | X | X | X |
|
||||
|
||||
¹ Requires extra setup, possibly hard to implement.
|
||||
|
||||
² Requires a [custom tokenizer](FTS5Tokenizers.md).
|
||||
|
||||
For a full feature list, read the SQLite documentation. Some missing features can be achieved with extra application code.
|
||||
|
||||
- **The speed versus disk space constraints.** Roughly speaking, FTS4 and FTS5 are faster than FTS3, but use more space. FTS4 only supports content compression.
|
||||
|
||||
- **The location of the indexed text in your database schema.** Only FTS4 and FTS5 support "contentless" and "external content" tables.
|
||||
|
||||
- **The SQLite library integrated in your application.** The version of SQLite that ships with iOS, macOS, tvOS and watchOS supports FTS3 and FTS4 out of the box, but not always FTS5. To use FTS5, see [Enabling FTS5 Support](#enabling-fts5-support).
|
||||
|
||||
- See [FST3 vs. FTS4](https://www.sqlite.org/fts3.html#differences_between_fts3_and_fts4) and [FTS5 vs. FTS3/4](https://www.sqlite.org/fts5.html#appendix_a) for more differences.
|
||||
|
||||
> :point_up: **Note**: In case you were still wondering, it is recommended to read the SQLite documentation: [FTS3 & FTS4](https://www.sqlite.org/fts3.html) and [FTS5](https://www.sqlite.org/fts5.html).
|
||||
|
||||
|
||||
## Create FTS3 and FTS4 Virtual Tables
|
||||
|
||||
**FTS3 and FTS4 full-text tables store and index textual content.**
|
||||
|
||||
Create tables with the `create(virtualTable:using:)` method:
|
||||
|
||||
```swift
|
||||
// CREATE VIRTUAL TABLE document USING fts3(content)
|
||||
try db.create(virtualTable: "document", using: FTS3()) { t in
|
||||
t.column("content")
|
||||
}
|
||||
|
||||
// CREATE VIRTUAL TABLE document USING fts4(content)
|
||||
try db.create(virtualTable: "document", using: FTS4()) { t in
|
||||
t.column("content")
|
||||
}
|
||||
```
|
||||
|
||||
**All columns in a full-text table contain text.** If you need to index a table that contains other kinds of values, you need an ["external content" full-text table](#external-content-full-text-tables).
|
||||
|
||||
You can specify a [tokenizer](#fts3-and-fts4-tokenizers):
|
||||
|
||||
```swift
|
||||
// CREATE VIRTUAL TABLE book USING fts4(
|
||||
// tokenize=porter,
|
||||
// author,
|
||||
// title,
|
||||
// body
|
||||
// )
|
||||
try db.create(virtualTable: "book", using: FTS4()) { t in
|
||||
t.tokenizer = .porter
|
||||
t.column("author")
|
||||
t.column("title")
|
||||
t.column("body")
|
||||
}
|
||||
```
|
||||
|
||||
FTS4 supports [options](https://www.sqlite.org/fts3.html#fts4_options):
|
||||
|
||||
```swift
|
||||
// CREATE VIRTUAL TABLE book USING fts4(
|
||||
// content,
|
||||
// uuid,
|
||||
// content="",
|
||||
// compress=zip,
|
||||
// uncompress=unzip,
|
||||
// prefix="2,4",
|
||||
// notindexed=uuid,
|
||||
// languageid=lid
|
||||
// )
|
||||
try db.create(virtualTable: "document", using: FTS4()) { t in
|
||||
t.content = ""
|
||||
t.compress = "zip"
|
||||
t.uncompress = "unzip"
|
||||
t.prefixes = [2, 4]
|
||||
t.column("content")
|
||||
t.column("uuid").notIndexed()
|
||||
t.column("lid").asLanguageId()
|
||||
}
|
||||
```
|
||||
|
||||
The `content` option is involved in "contentless" and "external content" full-text tables. GRDB can help you defining full-text tables that automatically synchronize with their content table. See [External Content Full-Text Tables](#external-content-full-text-tables).
|
||||
|
||||
|
||||
See [SQLite documentation](https://www.sqlite.org/fts3.html) for more information.
|
||||
|
||||
|
||||
## FTS3 and FTS4 Tokenizers
|
||||
|
||||
**A tokenizer defines what "matching" means.** Depending on the tokenizer you choose, full-text searches won't return the same results.
|
||||
|
||||
SQLite ships with three built-in FTS3/4 tokenizers: `simple`, `porter` and `unicode61` that use different algorithms to match queries with indexed content:
|
||||
|
||||
```swift
|
||||
try db.create(virtualTable: "book", using: FTS4()) { t in
|
||||
// Pick one:
|
||||
t.tokenizer = .simple // default
|
||||
t.tokenizer = .porter
|
||||
t.tokenizer = .unicode61(...)
|
||||
}
|
||||
```
|
||||
|
||||
See below some examples of matches:
|
||||
|
||||
| content | query | simple | porter | unicode61 |
|
||||
| ----------- | ---------- | :----: | :----: | :-------: |
|
||||
| Foo | Foo | X | X | X |
|
||||
| Foo | FOO | X | X | X |
|
||||
| Jérôme | Jérôme | X ¹ | X ¹ | X ¹ |
|
||||
| Jérôme | JÉRÔME | | | X ¹ |
|
||||
| Jérôme | Jerome | | | X ¹ |
|
||||
| Database | Databases | | X | |
|
||||
| Frustration | Frustrated | | X | |
|
||||
|
||||
¹ Don't miss [Unicode Full-Text Gotchas](#unicode-full-text-gotchas)
|
||||
|
||||
- **simple**
|
||||
|
||||
```swift
|
||||
try db.create(virtualTable: "book", using: FTS4()) { t in
|
||||
t.tokenizer = .simple // default
|
||||
}
|
||||
```
|
||||
|
||||
The default "simple" tokenizer is case-insensitive for ASCII characters. It matches "foo" with "FOO", but not "Jérôme" with "JÉRÔME".
|
||||
|
||||
It does not provide stemming, and won't match "databases" with "database".
|
||||
|
||||
It does not strip diacritics from latin script characters, and won't match "jérôme" with "jerome".
|
||||
|
||||
- **porter**
|
||||
|
||||
```swift
|
||||
try db.create(virtualTable: "book", using: FTS4()) { t in
|
||||
t.tokenizer = .porter
|
||||
}
|
||||
```
|
||||
|
||||
The "porter" tokenizer compares English words according to their roots: it matches "database" with "databases", and "frustration" with "frustrated".
|
||||
|
||||
It does not strip diacritics from latin script characters, and won't match "jérôme" with "jerome".
|
||||
|
||||
- **unicode61**
|
||||
|
||||
```swift
|
||||
try db.create(virtualTable: "book", using: FTS4()) { t in
|
||||
t.tokenizer = .unicode61()
|
||||
t.tokenizer = .unicode61(diacritics: .keep)
|
||||
}
|
||||
```
|
||||
|
||||
The "unicode61" tokenizer is case-insensitive for unicode characters. It matches "Jérôme" with "JÉRÔME".
|
||||
|
||||
It strips diacritics from latin script characters by default, and matches "jérôme" with "jerome". This behavior can be disabled, as in the example above.
|
||||
|
||||
It does not provide stemming, and won't match "databases" with "database".
|
||||
|
||||
See [SQLite tokenizers](https://www.sqlite.org/fts3.html#tokenizer) for more information.
|
||||
|
||||
|
||||
## FTS3Pattern
|
||||
|
||||
**Full-text search in FTS3 and FTS4 tables is performed with search patterns:**
|
||||
|
||||
- `database` matches all documents that contain "database"
|
||||
- `data*` matches all documents that contain a word starting with "data"
|
||||
- `SQLite database` matches all documents that contain both "SQLite" and "database"
|
||||
- `SQLite OR database` matches all documents that contain "SQLite" or "database"
|
||||
- `"SQLite database"` matches all documents that contain the "SQLite database" phrase
|
||||
|
||||
**Not all search patterns are valid**: they must follow the [Full-Text Index Queries Grammar](https://www.sqlite.org/fts3.html#full_text_index_queries).
|
||||
|
||||
The FTS3Pattern type helps you validating patterns, and building valid patterns from untrusted strings (such as strings typed by users):
|
||||
|
||||
```swift
|
||||
struct FTS3Pattern {
|
||||
init(rawPattern: String) throws
|
||||
init?(matchingAnyTokenIn string: String)
|
||||
init?(matchingAllTokensIn string: String)
|
||||
init?(matchingPhrase string: String)
|
||||
}
|
||||
```
|
||||
|
||||
The first initializer validates your raw patterns against the query grammar, and may throw a [DatabaseError](../README.md#databaseerror):
|
||||
|
||||
```swift
|
||||
// OK: FTS3Pattern
|
||||
let pattern = try FTS3Pattern(rawPattern: "sqlite AND database")
|
||||
// DatabaseError: malformed MATCH expression: [AND]
|
||||
let pattern = try FTS3Pattern(rawPattern: "AND")
|
||||
```
|
||||
|
||||
The three other initializers don't throw. They build a valid pattern from any string, **including strings provided by users of your application**. They let you find documents that match all given words, any given word, or a full phrase, depending on the needs of your application:
|
||||
|
||||
```swift
|
||||
let query = "SQLite database"
|
||||
// Matches documents that contain "SQLite" or "database"
|
||||
let pattern = FTS3Pattern(matchingAnyTokenIn: query)
|
||||
// Matches documents that contain both "SQLite" and "database"
|
||||
let pattern = FTS3Pattern(matchingAllTokensIn: query)
|
||||
// Matches documents that contain "SQLite database"
|
||||
let pattern = FTS3Pattern(matchingPhrase: query)
|
||||
```
|
||||
|
||||
They return nil when no pattern could be built from the input string:
|
||||
|
||||
```swift
|
||||
let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.5/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
sql: "SELECT * FROM document WHERE content MATCH ?",
|
||||
arguments: [pattern])
|
||||
```
|
||||
|
||||
Use them in the [query interface](../README.md#the-query-interface):
|
||||
|
||||
```swift
|
||||
// Search in all columns
|
||||
let documents = try Document.matching(pattern).fetchAll(db)
|
||||
|
||||
// Search in a specific column:
|
||||
let documents = try Document.filter(Column("content").match(pattern)).fetchAll(db)
|
||||
```
|
||||
|
||||
|
||||
## Enabling FTS5 Support
|
||||
|
||||
When the FTS3 and FTS4 full-text engines don't suit your needs, you may want to use FTS5. See [Choosing the Full-Text Engine](#choosing-the-full-text-engine) to help you make a decision.
|
||||
|
||||
The version of SQLite that ships with iOS, macOS, tvOS and watchOS does not always support the FTS5 engine. To enable FTS5 support, you'll need to install GRDB with one of those installation techniques:
|
||||
|
||||
1. Use the GRDB.swift CocoaPod with a custom compilation option, as below. It uses the system SQLite, which is compiled with FTS5 support, but only on iOS 11.4+ / macOS 10.13+ / tvOS 11.4+ / watchOS 4.3+:
|
||||
|
||||
```ruby
|
||||
pod 'GRDB.swift'
|
||||
platform :ios, '11.4' # or above
|
||||
|
||||
post_install do |installer|
|
||||
installer.pods_project.targets.select { |target| target.name == "GRDB.swift" }.each do |target|
|
||||
target.build_configurations.each do |config|
|
||||
config.build_settings['OTHER_SWIFT_FLAGS'] = "$(inherited) -D SQLITE_ENABLE_FTS5"
|
||||
end
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
> :warning: **Warning**: make sure you use the right platform version! You will get runtime errors on devices with a lower version.
|
||||
|
||||
> :point_up: **Note**: there used to be a GRDBPlus CocoaPod with pre-enabled FTS5 support. This CocoaPod is deprecated: please switch to the above technique.
|
||||
|
||||
2. Use the GRDB.swift/SQLCipher CocoaPod subspec (see [encryption](../README.md#encryption)):
|
||||
|
||||
```ruby
|
||||
pod 'GRDB.swift/SQLCipher'
|
||||
```
|
||||
|
||||
3. Use a [custom SQLite build] and activate the `SQLITE_ENABLE_FTS5` compilation option.
|
||||
|
||||
|
||||
## Create FTS5 Virtual Tables
|
||||
|
||||
**FTS5 full-text tables store and index textual content.**
|
||||
|
||||
To use FTS5, you'll need a [custom SQLite build] that activates the `SQLITE_ENABLE_FTS5` compilation option.
|
||||
|
||||
Create FTS5 tables with the `create(virtualTable:using:)` method:
|
||||
|
||||
```swift
|
||||
// CREATE VIRTUAL TABLE document USING fts5(content)
|
||||
try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
t.column("content")
|
||||
}
|
||||
```
|
||||
|
||||
**All columns in a full-text table contain text.** If you need to index a table that contains other kinds of values, you need an ["external content" full-text table](#external-content-full-text-tables).
|
||||
|
||||
You can specify a [tokenizer](#fts5-tokenizers):
|
||||
|
||||
```swift
|
||||
// CREATE VIRTUAL TABLE book USING fts5(
|
||||
// tokenize='porter',
|
||||
// author,
|
||||
// title,
|
||||
// body
|
||||
// )
|
||||
try db.create(virtualTable: "book", using: FTS5()) { t in
|
||||
t.tokenizer = .porter()
|
||||
t.column("author")
|
||||
t.column("title")
|
||||
t.column("body")
|
||||
}
|
||||
```
|
||||
|
||||
FTS5 supports [options](https://www.sqlite.org/fts5.html#fts5_table_creation_and_initialization):
|
||||
|
||||
```swift
|
||||
// CREATE VIRTUAL TABLE book USING fts5(
|
||||
// content,
|
||||
// uuid UNINDEXED,
|
||||
// content='table',
|
||||
// content_rowid='id',
|
||||
// prefix='2 4',
|
||||
// columnsize=0,
|
||||
// detail=column
|
||||
// )
|
||||
try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
t.column("content")
|
||||
t.column("uuid").notIndexed()
|
||||
t.content = "table"
|
||||
t.contentRowID = "id"
|
||||
t.prefixes = [2, 4]
|
||||
t.columnSize = 0
|
||||
t.detail = "column"
|
||||
}
|
||||
```
|
||||
|
||||
The `content` and `contentRowID` options are involved in "contentless" and "external content" full-text tables. GRDB can help you defining full-text tables that automatically synchronize with their content table. See [External Content Full-Text Tables](#external-content-full-text-tables).
|
||||
|
||||
See [SQLite documentation](https://www.sqlite.org/fts5.html) for more information.
|
||||
|
||||
|
||||
## FTS5 Tokenizers
|
||||
|
||||
**A tokenizer defines what "matching" means.** Depending on the tokenizer you choose, full-text searches won't return the same results.
|
||||
|
||||
SQLite ships with three built-in FTS5 tokenizers: `ascii`, `porter` and `unicode61` that use different algorithms to match queries with indexed content.
|
||||
|
||||
```swift
|
||||
try db.create(virtualTable: "book", using: FTS5()) { t in
|
||||
// Pick one:
|
||||
t.tokenizer = .unicode61() // default
|
||||
t.tokenizer = .unicode61(...)
|
||||
t.tokenizer = .ascii
|
||||
t.tokenizer = .porter(...)
|
||||
}
|
||||
```
|
||||
|
||||
See below some examples of matches:
|
||||
|
||||
| content | query | ascii | unicode61 | porter on ascii | porter on unicode61 |
|
||||
| ----------- | ---------- | :----: | :-------: | :-------------: | :-----------------: |
|
||||
| Foo | Foo | X | X | X | X |
|
||||
| Foo | FOO | X | X | X | X |
|
||||
| Jérôme | Jérôme | X ¹ | X ¹ | X ¹ | X ¹ |
|
||||
| Jérôme | JÉRÔME | | X ¹ | | X ¹ |
|
||||
| Jérôme | Jerome | | X ¹ | | X ¹ |
|
||||
| Database | Databases | | | X | X |
|
||||
| Frustration | Frustrated | | | X | X |
|
||||
|
||||
¹ Don't miss [Unicode Full-Text Gotchas](#unicode-full-text-gotchas)
|
||||
|
||||
- **unicode61**
|
||||
|
||||
```swift
|
||||
try db.create(virtualTable: "book", using: FTS5()) { t in
|
||||
t.tokenizer = .unicode61()
|
||||
t.tokenizer = .unicode61(diacritics: .keep)
|
||||
}
|
||||
```
|
||||
|
||||
The default "unicode61" tokenizer is case-insensitive for unicode characters. It matches "Jérôme" with "JÉRÔME".
|
||||
|
||||
It strips diacritics from latin script characters by default, and matches "jérôme" with "jerome". This behavior can be disabled, as in the example above.
|
||||
|
||||
It does not provide stemming, and won't match "databases" with "database".
|
||||
|
||||
- **ascii**
|
||||
|
||||
```swift
|
||||
try db.create(virtualTable: "book", using: FTS5()) { t in
|
||||
t.tokenizer = .ascii
|
||||
}
|
||||
```
|
||||
|
||||
The "ascii" tokenizer is case-insensitive for ASCII characters. It matches "foo" with "FOO", but not "Jérôme" with "JÉRÔME".
|
||||
|
||||
It does not provide stemming, and won't match "databases" with "database".
|
||||
|
||||
It does not strip diacritics from latin script characters, and won't match "jérôme" with "jerome".
|
||||
|
||||
- **porter**
|
||||
|
||||
```swift
|
||||
try db.create(virtualTable: "book", using: FTS5()) { t in
|
||||
t.tokenizer = .porter() // porter wrapping unicode61 (the default)
|
||||
t.tokenizer = .porter(.ascii) // porter wrapping ascii
|
||||
t.tokenizer = .porter(.unicode61(diacritics: .keep)) // porter wrapping unicode61 without diacritics stripping
|
||||
}
|
||||
```
|
||||
|
||||
The porter tokenizer is a wrapper tokenizer which compares English words according to their roots: it matches "database" with "databases", and "frustration" with "frustrated".
|
||||
|
||||
It strips diacritics from latin script characters if it wraps unicode61, and does not if it wraps ascii (see the example above).
|
||||
|
||||
See [SQLite tokenizers](https://www.sqlite.org/fts5.html#tokenizers) for more information, and [custom FTS5 tokenizers](FTS5Tokenizers.md) in order to add your own tokenizers.
|
||||
|
||||
|
||||
## FTS5Pattern
|
||||
|
||||
**Full-text search in FTS5 tables is performed with search patterns:**
|
||||
|
||||
- `database` matches all documents that contain "database"
|
||||
- `data*` matches all documents that contain a word starting with "data"
|
||||
- `SQLite database` matches all documents that contain both "SQLite" and "database"
|
||||
- `SQLite OR database` matches all documents that contain "SQLite" or "database"
|
||||
- `"SQLite database"` matches all documents that contain the "SQLite database" phrase
|
||||
|
||||
**Not all search patterns are valid**: they must follow the [Full-Text Query Syntax](https://www.sqlite.org/fts5.html#full_text_query_syntax).
|
||||
|
||||
The FTS5Pattern type helps you validating patterns, and building valid patterns from untrusted strings (such as strings typed by users):
|
||||
|
||||
```swift
|
||||
extension Database {
|
||||
func makeFTS5Pattern(rawPattern: String, forTable table: String) throws -> FTS5Pattern
|
||||
}
|
||||
|
||||
struct FTS5Pattern {
|
||||
init?(matchingAnyTokenIn string: String)
|
||||
init?(matchingAllTokensIn string: String)
|
||||
init?(matchingPhrase string: String)
|
||||
}
|
||||
```
|
||||
|
||||
The `Database.makeFTS5Pattern(rawPattern:forTable:)` method validates your raw patterns against the query grammar and the columns of the targeted table, and may throw a [DatabaseError](../README.md#databaseerror):
|
||||
|
||||
```swift
|
||||
// OK: FTS5Pattern
|
||||
try db.makeFTS5Pattern(rawPattern: "sqlite", forTable: "book")
|
||||
// DatabaseError: syntax error near \"AND\"
|
||||
try db.makeFTS5Pattern(rawPattern: "AND", forTable: "book")
|
||||
// DatabaseError: no such column: missing
|
||||
try db.makeFTS5Pattern(rawPattern: "missing: sqlite", forTable: "book")
|
||||
```
|
||||
|
||||
The FTS5Pattern initializers don't throw. They build a valid pattern from any string, **including strings provided by users of your application**. They let you find documents that match all given words, any given word, or a full phrase, depending on the needs of your application:
|
||||
|
||||
```swift
|
||||
let query = "SQLite database"
|
||||
// Matches documents that contain "SQLite" or "database"
|
||||
let pattern = FTS5Pattern(matchingAnyTokenIn: query)
|
||||
// Matches documents that contain both "SQLite" and "database"
|
||||
let pattern = FTS5Pattern(matchingAllTokensIn: query)
|
||||
// Matches documents that contain "SQLite database"
|
||||
let pattern = FTS5Pattern(matchingPhrase: query)
|
||||
// Matches documents that start with "SQLite database"
|
||||
let pattern = FTS5Pattern(matchingPrefixPhrase: query)
|
||||
```
|
||||
|
||||
They return nil when no pattern could be built from the input string:
|
||||
|
||||
```swift
|
||||
let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.5/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
sql: "SELECT * FROM document WHERE document MATCH ?",
|
||||
arguments: [pattern])
|
||||
```
|
||||
|
||||
Use them in the [query interface](../README.md#the-query-interface):
|
||||
|
||||
```swift
|
||||
let documents = try Document.matching(pattern).fetchAll(db)
|
||||
```
|
||||
|
||||
|
||||
## FTS5: Sorting by Relevance
|
||||
|
||||
**FTS5 can sort results by relevance** (most to least relevant):
|
||||
|
||||
```swift
|
||||
// SQL
|
||||
let documents = try Document.fetchAll(db,
|
||||
sql: "SELECT * FROM document WHERE document MATCH ? ORDER BY rank",
|
||||
arguments: [pattern])
|
||||
|
||||
// Query Interface
|
||||
let documents = try Document.matching(pattern).order(Column.rank).fetchAll(db)
|
||||
```
|
||||
|
||||
For more information about the ranking algorithm, as well as extra options, read [Sorting by Auxiliary Function Results](https://www.sqlite.org/fts5.html#sorting_by_auxiliary_function_results)
|
||||
|
||||
GRDB does not provide any ranking for FTS3 and FTS4. See SQLite's [Search Application Tips](https://www.sqlite.org/fts3.html#appendix_a) if you really need it.
|
||||
|
||||
|
||||
## External Content Full-Text Tables
|
||||
|
||||
**An external content table does not store the indexed text.** Instead, it indexes the text stored in another table.
|
||||
|
||||
This is very handy when you want to index a table that can not be declared as a full-text table (because it contains non-textual values, for example). You just have to define an external content full-text table that refers to the regular table.
|
||||
|
||||
The two tables must be kept up-to-date, so that the full-text index matches the content of the regular table. This synchronization happens automatically if you use the `synchronize(withTable:)` method in your full-text table definition:
|
||||
|
||||
```swift
|
||||
// A regular table
|
||||
try db.create(table: "book") { t in
|
||||
t.column("author", .text)
|
||||
t.column("title", .text)
|
||||
t.column("content", .text)
|
||||
...
|
||||
}
|
||||
|
||||
// A full-text table synchronized with the regular table
|
||||
try db.create(virtualTable: "book_ft", using: FTS4()) { t in // or FTS5()
|
||||
t.synchronize(withTable: "book")
|
||||
t.column("author")
|
||||
t.column("title")
|
||||
t.column("content")
|
||||
}
|
||||
```
|
||||
|
||||
The eventual content already present in the regular table is indexed, and every insert, update or delete that happens in the regular table is automatically applied to the full-text index.
|
||||
|
||||
For more information, see the SQLite documentation about external content tables: [FTS4](https://www.sqlite.org/fts3.html#_external_content_fts4_tables_), [FTS5](https://sqlite.org/fts5.html#external_content_tables).
|
||||
|
||||
See also [WWDC Companion](https://github.com/groue/WWDCCompanion), a sample app that uses external content tables to store, display, and let the user search the WWDC sessions.
|
||||
|
||||
|
||||
### Deleting Synchronized Full-Text Tables
|
||||
|
||||
Synchronization of full-text tables with their content table happens by the mean of SQL triggers.
|
||||
|
||||
SQLite automatically deletes those triggers when the content (not full-text) table is dropped.
|
||||
|
||||
However, those triggers remain after the full-text table has been dropped. Unless they are dropped too, they will prevent future insertion, updates, and deletions in the content table, and the creation of a new full-text table.
|
||||
|
||||
To drop those triggers, use the `dropFTS4SynchronizationTriggers` or `dropFTS5SynchronizationTriggers` methods:
|
||||
|
||||
```swift
|
||||
// Create tables
|
||||
try db.create(table: "book") { t in
|
||||
...
|
||||
}
|
||||
try db.create(virtualTable: "book_ft", using: FTS4()) { t in
|
||||
t.synchronize(withTable: "book")
|
||||
...
|
||||
}
|
||||
|
||||
// Drop full-text table
|
||||
try db.drop(table: "book_ft")
|
||||
try db.dropFTS4SynchronizationTriggers(forTable: "book_ft")
|
||||
```
|
||||
|
||||
> :warning: **Warning**: there was a bug in GRDB up to version 2.3.1 included, which created triggers with a wrong name. If it is possible that the full-text table was created by an old version of GRDB, then delete the synchronization triggers **twice**: once with the name of the deleted full-text table, and once with the name of the content table:
|
||||
>
|
||||
> ```swift
|
||||
> // Drop full-text table
|
||||
> try db.drop(table: "book_ft")
|
||||
> try db.dropFTS4SynchronizationTriggers(forTable: "book_ft")
|
||||
> try db.dropFTS4SynchronizationTriggers(forTable: "book") // Support for GRDB <= 2.3.1
|
||||
> ```
|
||||
|
||||
|
||||
|
||||
### Querying External Content Full-Text Tables
|
||||
|
||||
When you need to perform a full-text search, and the external content table contains all the data you need, you can simply query the full-text table.
|
||||
|
||||
But if you need to load columns from the regular table, and in the same time perform a full-text search, then you will need to query both tables at the same time.
|
||||
|
||||
That is because SQLite will throw an error when you try to perform a full-text search on a regular table:
|
||||
|
||||
```swift
|
||||
// SQLite error 1: unable to use function MATCH in the requested context
|
||||
// SELECT * FROM book WHERE book MATCH '...'
|
||||
let books = Book.matching(pattern).fetchAll(db)
|
||||
```
|
||||
|
||||
The solution is to perform a joined request, using raw SQL:
|
||||
|
||||
```swift
|
||||
let sql = """
|
||||
SELECT book.*
|
||||
FROM book
|
||||
JOIN book_ft
|
||||
ON book_ft.rowid = book.rowid
|
||||
AND book_ft MATCH ?
|
||||
"""
|
||||
let books = Book.fetchAll(db, sql: sql, arguments: [pattern])
|
||||
```
|
||||
|
||||
|
||||
## Full-Text Records
|
||||
|
||||
**You can define [record](../README.md#records) types around the full-text virtual tables.**
|
||||
|
||||
However these tables don't have any explicit primary key. Instead, they use the [implicit rowid primary key](../README.md#the-implicit-rowid-primary-key): a special hidden column named `rowid`.
|
||||
|
||||
You will have to [expose this hidden column](../README.md#exposing-the-rowid-column) in order to fetch, delete, and update full-text records by primary key.
|
||||
|
||||
|
||||
## Unicode Full-Text Gotchas
|
||||
|
||||
The SQLite built-in tokenizers for [FTS3, FTS4](#fts3-and-fts4-tokenizers) and [FTS5](#fts5-tokenizers) are generally unicode-aware, with a few caveats, and limitations.
|
||||
|
||||
Generally speaking, matches may fail when content and query don't use the same [unicode normalization](http://unicode.org/reports/tr15/). SQLite actually exhibits inconsistent behavior in this regard.
|
||||
|
||||
For example, for "aimé" to match "aimé", they better have the same normalization: the NFC "aim\u{00E9}" form may not match its NFD "aime\u{0301}" equivalent. Most strings that you get from Swift, UIKit and Cocoa use NFC, so be careful with NFD inputs (such as strings from the HFS+ file system, or strings that you can't trust like network inputs). Use [String.precomposedStringWithCanonicalMapping](https://developer.apple.com/reference/swift/string/1407210-precomposedstringwithcanonicalma) to turn a string into NFC.
|
||||
|
||||
Besides, if you want "fi" to match the ligature "fi" (U+FB01), then you need to normalize your indexed contents and inputs to NFKC or NFKD. Use [String.precomposedStringWithCompatibilityMapping](https://developer.apple.com/reference/swift/string/1407834-precomposedstringwithcompatibili) to turn a string into NFKC.
|
||||
|
||||
Unicode normalization is not the end of the story, because it won't help "Encyclopaedia" match "Encyclopædia", "Mueller", "Müller", "Grossmann", "Großmann", or "Diyarbakır", "DIYARBAKIR". The [String.applyingTransform](https://developer.apple.com/reference/swift/string/1643133-applyingtransform) method can help.
|
||||
|
||||
GRDB lets you write [custom FTS5 tokenizers](FTS5Tokenizers.md) that can transparently deal with all these issues. For FTS3 and FTS4, you'll need to pre-process your strings before injecting them in the full-text engine.
|
||||
|
||||
Happy indexing!
|
||||
|
||||
|
||||
@@ -1,523 +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
|
||||
[FetchedRecordsController]: ../README.md#fetchedrecordscontroller
|
||||
[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,183 +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)
|
||||
- [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 = ValueObservation.trackingAll(Player.all())
|
||||
observation.scheduling = .async(onQueue: .main, startImmediately: true)
|
||||
let observer = try observation.start(in: dbQueue) { (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
|
||||
@@ -5,20 +5,25 @@ This guide aims at helping you leverage the best of GRDB [records] and [associat
|
||||
|
||||
Since GRDB sits right between low-level libraries like SQLite itself or [FMDB], and high-level ORM like [Core Data] or [Realm], you may face questions when designing the model layer of your application.
|
||||
|
||||
To support this guide, we'll design a simply library application that lets the user crawl through books and their authors.
|
||||
To support this guide, we'll design a simple library application that lets the user crawl through books and their authors.
|
||||
|
||||
- [Trust SQLite More Than Yourself]
|
||||
- [Record Types are Responsible for Their Tables]
|
||||
- [Persistable Record Types are Responsible for Their Tables]
|
||||
- [Define Record Requests]
|
||||
- [Compose Records]
|
||||
- [Fetch In Time]
|
||||
- [How to Design Database Managers]
|
||||
- [Observe the Database and Refetch when Needed]
|
||||
|
||||
|
||||
## Trust SQLite More Than Yourself
|
||||
|
||||
SQLite is a robust database. Even if you don't know it well, and aren't familiar with the SQL language, you are able to take profit from its solid foundation. It is very difficult to corrupt an SQLite database file. And it can make sure that only valid information is persisted on disk.
|
||||
It is important to put things in the right order. An SQLite database stored on one of your user's device is more important than the Swift code that accesses it. When a user installs a new version of your application, all the code may change, but the database remains the same.
|
||||
|
||||
This is important because we developers write bugs, and some of them will ship in the wild, affecting your application users. But thanks to SQLite, those bugs will be unable to corrupt your precious users' data. All it takes is a robust **database schema**.
|
||||
This is why we recommend defining a **robust database schema** even before playing with record types.
|
||||
|
||||
SQLite is a battle-tested database. Even if you don't know it well, and aren't familiar with the SQL language, you are able to take profit from its solid foundation. It is very difficult to corrupt an SQLite database file. And it can make sure that only valid information is persisted on disk.
|
||||
|
||||
This is important because we developers write bugs, and some of them will ship in the wild, affecting the users of our applications. But SQLite will prevent many of those bugs from corrupting our precious users' data.
|
||||
|
||||
For example, if we were to define a [migration] that sets up our library database, made of books and their authors, we could write:
|
||||
|
||||
@@ -29,31 +34,33 @@ migrator.registerMigration("createLibrary") { db in
|
||||
try db.create(table: "author") { t in // (1)
|
||||
t.autoIncrementedPrimaryKey("id") // (2)
|
||||
t.column("name", .text).notNull() // (3)
|
||||
t.column("country", .text) // (4)
|
||||
}
|
||||
|
||||
try db.create(table: "book") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("title", .text).notNull() // (4)
|
||||
t.column("authorId", .integer) // (5)
|
||||
.notNull() // (6)
|
||||
.indexed() // (7)
|
||||
.references("author", onDelete: .cascade) // (8)
|
||||
t.column("title", .text).notNull() // (5)
|
||||
t.column("authorId", .integer) // (6)
|
||||
.notNull() // (7)
|
||||
.indexed() // (8)
|
||||
.references("author", onDelete: .cascade) // (9)
|
||||
}
|
||||
}
|
||||
|
||||
try migrator.migrate(dbQueue)
|
||||
```
|
||||
|
||||
1. Our database table names follow the GRDB 3 recommendation: generally speaking they should be singular, and camel-cased. Make them look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`.
|
||||
1. Our database table names follow the [recommended convention]: they are English, singular, and camelCased. They look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`.
|
||||
2. Each author has a unique id.
|
||||
3. An author must have a name.
|
||||
4. A book must have a title.
|
||||
5. The `book.authorId` column is used to link a book to the author it belongs to.
|
||||
6. The `book.authorId` column is not null so that SQLite guarantees that all books have an author.
|
||||
7. The `book.authorId` column is indexed in order to ease the selection of an author's books.
|
||||
8. We define a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book can refer to a missing author. On top of that, the `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
|
||||
4. The country of an author is not always known.
|
||||
5. A book must have a title.
|
||||
6. The `book.authorId` column is used to link a book to the author it belongs to.
|
||||
7. The `book.authorId` column is not null so that SQLite guarantees that all books have an author.
|
||||
8. The `book.authorId` column is indexed in order to ease the selection of an author's books.
|
||||
9. We define a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book can refer to a missing author. On top of that, the `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
|
||||
|
||||
Thanks to this database schema, you can be confident so no matter how wrong our application goes, it will always process *consistent data*. Even after a hard crash, application will always find the author of any book, all books will have a non-nil title, etc.
|
||||
Thanks to this database schema, you can be confident that no matter how wrong our application goes, it will always process *consistent data*. Even after a hard crash, application will always find the author of any book, all books will have a non-nil title, etc.
|
||||
|
||||
> :bulb: **Tip**: Don't look at your local SQLite database as you look at the JSON you load from a remote server. You can't control the JSON, its format and content: your application must defend itself against wacky servers. But you can control the database. Put the database on your side, make it trustable. Learn about relational databases, and how they can help you guarantee the quality of your application data. Put as much energy as you can in the proper definition of your database schema.
|
||||
>
|
||||
@@ -82,27 +89,36 @@ Thanks to this database schema, you can be confident so no matter how wrong our
|
||||
> So make sure that migrations don't use application types and values: migrations should talk to the database, only to the database, and use the database language: **strings**.
|
||||
|
||||
|
||||
## Record Types are Responsible for Their Tables
|
||||
## Persistable Record Types are Responsible for Their Tables
|
||||
|
||||
Define one record type per database table.
|
||||
Define one record type per database table, and make it adopt a [PersistableRecord] protocol.
|
||||
|
||||
In this sample code, we'll use codable structs, but there are [other ways](../README.md#examples-of-record-definitions) to define records.
|
||||
In this sample code, we'll use Codable structs, but there are [other ways](../README.md#examples-of-record-definitions) to define records.
|
||||
|
||||
```swift
|
||||
struct Author: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
struct Author: Codable {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
|
||||
var country: String?
|
||||
}
|
||||
|
||||
struct Book: Codable {
|
||||
var id: Int64?
|
||||
var authorId: Int64
|
||||
var title: String
|
||||
}
|
||||
|
||||
// Add Database access
|
||||
|
||||
extension Author: FetchableRecord, MutablePersistableRecord {
|
||||
// Update auto-incremented id upon successful insertion
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
}
|
||||
}
|
||||
|
||||
struct Book: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
var id: Int64?
|
||||
var authorId: Int64
|
||||
var title: String
|
||||
|
||||
extension Book: FetchableRecord, MutablePersistableRecord {
|
||||
// Update auto-incremented id upon successful insertion
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
}
|
||||
@@ -116,9 +132,11 @@ That's it. The `Author` type can read and write in the `author` database table.
|
||||
> :bulb: **Tip**: When a database table uses an auto-incremented identifier, make the `id` property optional (so that you can instantiate a record before it gets inserted and gains an id), and implement the `didInsert(with:for:)` method:
|
||||
>
|
||||
> ```swift
|
||||
> var author = Author(id: nil, name: "Hermann Melville")
|
||||
> try author.insert(db)
|
||||
> print(author.id) // Some non-nil id
|
||||
> try dbQueue.write { db in
|
||||
> var author = Author(id: nil, name: "Hermann Melville", country: "United States")
|
||||
> try author.insert(db)
|
||||
> print(author.id!) // Guaranteed non-nil id
|
||||
> }
|
||||
> ```
|
||||
|
||||
Since `Author` and `Book` can insert, update, and delete rows in the `author` and `book` database tables, they are *responsible for modifying those database tables*.
|
||||
@@ -128,87 +146,221 @@ Applying the **[Single Responsibility Principle]** has a consequence: don't even
|
||||
> :bulb: **Tip**: Make sure each record type deals with one database table, and only one database table.
|
||||
|
||||
|
||||
## Compose Records
|
||||
## Define Record Requests
|
||||
|
||||
Now that we have two types for authors and books, we'd like to navigate from books to authors and vice-versa: we may want to know an author's books, or a book's author.
|
||||
Now that we have record types that are able to read and write in the database, we'd like to put them to good use.
|
||||
|
||||
GRDB can help you do this with [associations]. In our case, each author **has many** books, and each book **belongs to** its author. Here is how you define those associations, along with their companion properties:
|
||||
> :bulb: **Tip**: Define an enumeration of columns that you will use in order to filter, sort, etc.
|
||||
|
||||
When your record type is a [Codable Record], derive columns from the [CodingKeys] enum:
|
||||
|
||||
```swift
|
||||
// For a codable record
|
||||
extension Author {
|
||||
static let books = hasMany(Book.self)
|
||||
var books: QueryInterfaceRequest<Book> {
|
||||
return request(for: Author.books)
|
||||
}
|
||||
}
|
||||
|
||||
extension Book {
|
||||
static let author = belongsTo(Author.self)
|
||||
var author: QueryInterfaceRequest<Author> {
|
||||
return request(for: Book.author)
|
||||
// Define database columns from CodingKeys
|
||||
enum Columns {
|
||||
static let id = Column(CodingKeys.id)
|
||||
static let name = Column(CodingKeys.name)
|
||||
static let country = Column(CodingKeys.country)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Thanks to this setup, you can fetch associated records:
|
||||
Otherwise, declare a plain String enum that conforms to the ColumnExpression protocol:
|
||||
|
||||
```swift
|
||||
// Fetch an author and its books
|
||||
struct AuthorInfo {
|
||||
var author: Author
|
||||
var books: [Book]
|
||||
// For a non-codable record
|
||||
extension Author {
|
||||
// Define database columns as an enum
|
||||
enum Columns: String, ColumnExpression {
|
||||
case id, name, country
|
||||
}
|
||||
}
|
||||
let authorInfo: AuthorInfo? = try dbQueue.read { db in
|
||||
guard let author = try Author.fetchOne(db, key: 123) else { return nil }
|
||||
let books = try author.books.fetchAll(db)
|
||||
return AuthorInfo(author: author, books: books)
|
||||
```
|
||||
|
||||
> :bulb: **Tip**: Define commonly used requests in a constrained extension of the `DerivableRequest` protocol.
|
||||
|
||||
The `DerivableRequest` protocol generally lets you filter, sort, and join or include associations (we'll talk about associations in the [Compose Records] chapter below).
|
||||
|
||||
Here is how you define those requests:
|
||||
|
||||
```swift
|
||||
// Some requests of Author --------------------v
|
||||
extension DerivableRequest where RowDecoder == Author {
|
||||
|
||||
/// Returns a request for all authors ordered by name, in a localized
|
||||
/// case-insensitive fashion
|
||||
func orderByName() -> Self {
|
||||
let name = Author.Columns.name
|
||||
return order(name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
|
||||
/// Returns a request for all authors from a country
|
||||
func filter(country: String) -> Self {
|
||||
filter(Author.Columns.country == country)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Those methods defined on the `DerivableRequest` protocol hide intimate database details. They allow you to compose database requests in a fluent style:
|
||||
|
||||
```swift
|
||||
try dbQueue.read { db in
|
||||
let sortedAuthors: [Author] = try Author.all()
|
||||
.orderByName()
|
||||
.fetchAll(db)
|
||||
|
||||
let frenchAuthors: [Author] = try Author.all()
|
||||
.filter(country: "France")
|
||||
.fetchAll(db)
|
||||
|
||||
let sortedSpanishAuthors: [Author] = try Author.all()
|
||||
.filter(country: "Spain")
|
||||
.orderByName()
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
Those customized request methods are also available on record associations, because associations conform to the `DerivableRequest` protocol:
|
||||
|
||||
```swift
|
||||
// Some requests of Book
|
||||
extension DerivableRequest where RowDecoder == Book {
|
||||
/// Returns a request for all books from a country
|
||||
func filter(authorCountry: String) -> Self {
|
||||
// A book is from a country if it can be
|
||||
// joined with an author from that country:
|
||||
// ---------------------------v
|
||||
joining(required: Book.author.filter(country: authorCountry))
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch all authorships
|
||||
try dbQueue.read { db in
|
||||
let italianBooks = try Book.all()
|
||||
.filter(authorCountry: "Italy")
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
Not *every requests* can be expressed on `DerivableRequest`. For example, [Association Aggregates] are out of scope. When this happens, define your requests in a constrained extension to `QueryInterfaceRequest`:
|
||||
|
||||
```swift
|
||||
// More requests of Author -------------------------v
|
||||
extension QueryInterfaceRequest where RowDecoder == Author {
|
||||
/// Returns a request for all authors with at least one book
|
||||
func havingBooks() -> QueryInterfaceRequest<Author> {
|
||||
having(Author.books.isEmpty == false)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Those requests defined on `QueryInterfaceRequest` still compose fluently:
|
||||
|
||||
```swift
|
||||
try dbQueue.read { db in
|
||||
let sortedFrenchAuthorsHavingBooks = try Author.all()
|
||||
.filter(country: "France")
|
||||
.havingBooks() // <-
|
||||
.orderByName()
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
Finally, when it happens that a request only makes sense when defined on the Record type itself, just go ahead and define a static method or property of your Record type:
|
||||
|
||||
```swift
|
||||
extension MySingletonRecord {
|
||||
/// The one any only record stored in the database
|
||||
static let shared = all().limit(1)
|
||||
}
|
||||
|
||||
let singleton = try dbQueue.read { db
|
||||
try MySingletonRecord.shared.fetchOne(db)
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Compose Records
|
||||
|
||||
We'd like to navigate from books to authors and vice-versa: we may want to know an author's books, or a book's author.
|
||||
|
||||
GRDB can help you do this with [associations]. In our case, each author **has many** books, and each book **belongs to** its author. Here is how you define those associations:
|
||||
|
||||
```swift
|
||||
extension Author {
|
||||
static let books = hasMany(Book.self)
|
||||
}
|
||||
|
||||
extension Book {
|
||||
static let author = belongsTo(Author.self)
|
||||
}
|
||||
```
|
||||
|
||||
Thanks to this setup, you can fetch associated records, or compute aggregated values from associated records. For example:
|
||||
|
||||
```swift
|
||||
// Fetch all authors and their number of books
|
||||
struct AuthorInfo: Decodable, FetchableRecord {
|
||||
var author: Author
|
||||
var bookCount: Int
|
||||
}
|
||||
let authorInfos: [AuthorInfo] = try dbQueue.read { db in
|
||||
let request = Author.annotated(with: Author.books.count)
|
||||
return try AuthorInfo.fetchAll(db, request)
|
||||
}
|
||||
|
||||
// Fetch all Colombian books and their authors:
|
||||
struct Authorship: Decodable, FetchableRecord {
|
||||
var book: Book
|
||||
var author: Author
|
||||
}
|
||||
let authorships: [Authorship] = try dbQueue.read { db in
|
||||
let request = Book.including(required: Book.author)
|
||||
let request = Book.including(required: Book.author.filter(country: "Colombia"))
|
||||
return try Authorship.fetchAll(db, request)
|
||||
}
|
||||
```
|
||||
|
||||
The example `AuthorInfo` and `Authorship` types above may look superfluous to you. After all, other ORMs out there are able to navigate in complex graphs of records without much fuss, aren't they?
|
||||
As in the sample code above, requests which feed from several associated records will often have you define extra record types, such as `AuthorInfo` and `Authorship`. Those extra record types are designed to be able to decode database requests. The names and types of their properties follow the conventions defined by [associations]. Make them conform to the Decodable and FetchableRecord protocols so that they can decode database rows in a breeze.
|
||||
|
||||
That is because other ORMs perform lazy loading:
|
||||
Unlike the primitive persistable record types `Author` and `Book`, those records can not write in the database. They are simple data types, passive views on the database content. Remember, only [Persistable Record Types are Responsible for Their Tables].
|
||||
|
||||
```ruby
|
||||
# Ruby's Active Record
|
||||
author = Author.find(123) # fetch author
|
||||
books = author.books # lazily fetches books on demand
|
||||
```
|
||||
> :question: **Note**: The example `AuthorInfo` and `Authorship` types above may look superfluous to you. After all, other ORMs out there are able to navigate in complex graphs of records without much fuss, aren't they?
|
||||
>
|
||||
> That is because other ORMs perform lazy loading:
|
||||
>
|
||||
> ```ruby
|
||||
> # Ruby's Active Record
|
||||
> author = Author.find(123) # fetch author
|
||||
> book_count = author.books.count # lazily counts books on demand
|
||||
> ```
|
||||
>
|
||||
> GRDB does not perform lazy loading. Lazy loading either requires records to be *managed* (as in [Core Data] and [Realm]), or that all data processing happens in a *single function* (think of an HTTP request handled with a web-oriented ORM like [Active Record] and [Django]). The underlying issue is *data consistency*: you always want your memory objects to accurately represent your application data, without any glitch, ever. This involves the subtle database concept of [isolation] against concurrent changes. In a GUI application, this can't be achieved without a very complex record management, and non-trivial pain points for the application developer.
|
||||
>
|
||||
> This is why GRDB has removed lazy loading from the list of desirable features. Instead, it provides the tooling needed to fetch data, even complex ones, in a single and safe stroke. See the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more information.
|
||||
|
||||
GRDB does not perform lazy loading. Lazy loading either requires record to be *managed* (as in [Core Data] and [Realm]), or that all data processing happens in a *single function* (think of an HTTP request handled with a web-oriented ORM like [Active Record] and [Django]). The underlying issue is *data consistency*: you always want your memory objects to accurately represent your application data, without any glitch, ever. This involves the subtle database concept of [isolation] against concurrent changes. In a GUI application, this can't be achieved without a very complex record management, and non-trivial pain points for the application developer. This is why GRDB has removed lazy loading from the list of desirable features. See the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more information.
|
||||
|
||||
The consequence is that each part of your application will load the data it needs, at the moment it needs it, as below:
|
||||
Granted with primitive and derived record types, your application will load the data it needs, at the moment it needs it, as below:
|
||||
|
||||
1. Prepare the application screen that lists all authors:
|
||||
|
||||
```swift
|
||||
let authors: [Author] = dbQueue.read { db in
|
||||
Author.order(Colum("name")).fetchAll(db)
|
||||
let authors: [Author] = try dbQueue.read { db in
|
||||
try Author.all().orderByName().fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
2. Prepare the application screen that displays an author and her books:
|
||||
|
||||
```swift
|
||||
struct AuthorInfo {
|
||||
struct AuthorInfo: Codable, FetchableRecord {
|
||||
var author: Author
|
||||
var books: [Book]
|
||||
}
|
||||
let authorId = 123
|
||||
let authorInfo: AuthorInfo? = try dbQueue.read { db in
|
||||
guard let author = try Author.fetchOne(db, key: authorId) else { return nil }
|
||||
let books = try author.books.fetchAll(db)
|
||||
return AuthorInfo(author: author, books: books)
|
||||
let request = Author
|
||||
.filter(key: authorId)
|
||||
.including(all: Author.books)
|
||||
return try AuthorInfo.fetchOne(db, request)
|
||||
}
|
||||
```
|
||||
|
||||
@@ -228,79 +380,296 @@ The consequence is that each part of your application will load the data it need
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: **Tip**: Identify the various **graph of objects** needed by the various parts of your application. Design them independently, by composing the basic record types. Fetch the data your application needs, at the moment it needs it, no more, no less.
|
||||
> :bulb: **Tip**: Identify the various **graph of objects** needed by the various parts of your application. Design them independently, by composing primitive record types linked by associations. Fetch the data your application needs, at the moment it needs it, no more, no less.
|
||||
|
||||
|
||||
## Fetch In Time
|
||||
|
||||
> :bulb: **Tip**: Make sure you fetch all the data your application needs in a **single database read**.
|
||||
A last extension on your record types will further help navigation from records to associated ones:
|
||||
|
||||
```swift
|
||||
// NOT RECOMMENDED
|
||||
let bookId = 123
|
||||
// Two fetches not grouped in a single `read` block:
|
||||
if let book = databaseManager.getBook(id: bookId) {
|
||||
let author = databaseManager.getAuthor(id: book.authorId)!
|
||||
// use book and author
|
||||
}
|
||||
|
||||
// RECOMMENDED (without associations)
|
||||
let bookId = 123
|
||||
let bookInfo: BookInfo? = try dbQueue.read { db in
|
||||
// All fetches are grouped in a single `read` block:
|
||||
if let book = try Book.fetchOne(db, key: bookId) {
|
||||
let author = try Author.fetchOne(db, key: book.authorId)!
|
||||
return BookInfo(book: book, author: author)
|
||||
} else {}
|
||||
return nil
|
||||
extension Author {
|
||||
/// The request for the author's books
|
||||
var books: QueryInterfaceRequest<Book> {
|
||||
request(for: Author.books)
|
||||
}
|
||||
}
|
||||
if let bookInfo = bookInfo {
|
||||
// use bookInfo
|
||||
}
|
||||
|
||||
// RECOMMENDED (with associations)
|
||||
let bookId = 123
|
||||
let bookInfo: BookInfo? = try dbQueue.read { db in
|
||||
// All fetches are grouped in a single `read` block:
|
||||
let request = Book
|
||||
.filter(key: bookId)
|
||||
.including(required: Book.author)
|
||||
return try BookInfo.fetchOne(db, request)
|
||||
}
|
||||
if let bookInfo = bookInfo {
|
||||
// use bookInfo
|
||||
extension Book {
|
||||
/// The request for the author of the book
|
||||
var author: QueryInterfaceRequest<Author> {
|
||||
request(for: Book.author)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This tip is paramount, and deserves an explanation because too many database libraries out there tend to completely disregard multi-threading gotchas.
|
||||
Those properties provide an alternative way to feed our application:
|
||||
|
||||
When you do not fetch your data in a single database access block, other threads of your application may modify the database in the background, and have you fetch inconsistent data. This leads to hard-to-reproduce bugs, from funny values on screen to data loss.
|
||||
1. Prepare the application screen that displays an author and her books:
|
||||
|
||||
```swift
|
||||
struct AuthorInfo {
|
||||
var author: Author
|
||||
var books: [Book]
|
||||
}
|
||||
let authorId = 123
|
||||
let authorInfo: AuthorInfo? = try dbQueue.read { db in
|
||||
guard let author = try Author.fetchOne(db, key: authorId) else {
|
||||
return nil
|
||||
}
|
||||
let books = try author.books.fetchAll(db)
|
||||
return AuthorInfo(
|
||||
author: author,
|
||||
books: books)
|
||||
}
|
||||
```
|
||||
|
||||
Wrapping all fetches in a `read` method may look like an inconvenience to you. After all, other ORMs don't require that much ceremony:
|
||||
2. Prepare the application screen that displays a book information:
|
||||
|
||||
```swift
|
||||
struct BookInfo {
|
||||
var book: Book
|
||||
var author: Author
|
||||
}
|
||||
let bookId = 123
|
||||
let bookInfo: BookInfo? = try dbQueue.read { db in
|
||||
guard let book = try Book.fetchOne(db, key: bookId) else {
|
||||
return nil
|
||||
}
|
||||
guard let author = try book.author.fetchOne(db) else {
|
||||
return nil
|
||||
}
|
||||
return BookInfo(book: book, author: author)
|
||||
}
|
||||
```
|
||||
|
||||
```ruby
|
||||
# Ruby's Active Record
|
||||
if book = Book.find(123) # fetch book
|
||||
author = book.author # fetch author
|
||||
# use book and author
|
||||
end
|
||||
|
||||
## How to Design Database Managers
|
||||
|
||||
Many developpers want to hide GRDB database queues and pools inside "database managers":
|
||||
|
||||
```swift
|
||||
// LibraryManager grants access to the library database.
|
||||
class LibraryManager {
|
||||
private let dbQueue: DatabaseQueue
|
||||
init(dbQueue: DatabaseQueue) {
|
||||
self.dbQueue = dbQueue
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The problem is that it is very hard to guarantee that you will surely fetch an author after you have fetched a book, despite the constraints of the database schema. One has to perform subsequent fetches in the proper [isolation] level, so that eventual concurrent writes that modify the database are unable to mess with subsequent requests.
|
||||
> :bulb: **Tip**: Don't let your database managers create their own databases. Instead, give them a database created by, say, the ApplicationDelegate. This will allow you to efficiently test the database manager with an in-memory database, for example.
|
||||
|
||||
This isolation can be achieved with record management, as in [Core Data] or [Realm], that target long-running multi-threaded applications. On the other side, most web-oriented ORMs rely on short-lived database transactions, so that each HTTP request can be processed independently of others.
|
||||
Design your database managers with the [GRDB concurrency rules] in mind.
|
||||
|
||||
GRDB is not a managed ORM. It thus has to use the same isolation techniques as web-oriented ORMs. But unlike web-oriented ORMs, GRDB can't provide implicit isolation: the application must decide when it wants to safely read information in the database, and this decision is made explicit with database access methods such as `dbQueue.read`.
|
||||
Practically, let's start with a naive example, and gradually improve it:
|
||||
|
||||
Do not overlook this advice, or your application will exhibit weird concurrency-related bugs. Read the [Concurrency Guide] for detailed information, and the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more rationale.
|
||||
```swift
|
||||
// A naive manager that we will improve
|
||||
class NaiveLibraryManager {
|
||||
private let dbQueue: DatabaseQueue
|
||||
init(dbQueue: DatabaseQueue) {
|
||||
self.dbQueue = dbQueue
|
||||
}
|
||||
|
||||
func author(id: Int64) -> Author? {
|
||||
do {
|
||||
return try dbQueue.read { db in
|
||||
try Author.fetchOne(db, key: id)
|
||||
}
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func book(id: Int64) -> Book? {
|
||||
do {
|
||||
return try dbQueue.read { db in
|
||||
try Book.fetchOne(db, key: id)
|
||||
}
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func books(writtenBy author: Author) -> [Book] {
|
||||
do {
|
||||
return try dbQueue.read { db in
|
||||
try author.books.fetchAll(db)
|
||||
}
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**This manager can be improved in two ways.**
|
||||
|
||||
- [Embrace Errors]
|
||||
- [Thread-Safety is also an Application Concern]
|
||||
|
||||
### Embrace Errors
|
||||
|
||||
Have database managers throw database errors instead of catching them.
|
||||
|
||||
Consider Apple's [CNContactStore](https://developer.apple.com/documentation/contacts/cncontactstore), for example. Does it hide errors when you fetch or save address book contacts? No it does not. Keychain, Media assets, File system, Core Data? No they do not hide errors either. Follow the practices of Apple engineers: do not hide errors :muscle:
|
||||
|
||||
Exposing errors will help you building your application:
|
||||
|
||||
- You will be able to inspect errors during development, and fix bugs. `do { ... } catch { print(error) }` will save you hours of clueless questioning.
|
||||
- You will be able to opt in for advanced OS features like [data protection].
|
||||
|
||||
> :bulb: **Tip**: Don't hide database errors. Let the application handle them, because only application can decide how to handle them.
|
||||
|
||||
This gives the improved manager below. And it has less code, which means less bugs :bowtie:
|
||||
|
||||
```swift
|
||||
// An improved manager that does not hide errors
|
||||
class ImprovedLibraryManager {
|
||||
private let dbQueue: DatabaseQueue
|
||||
init(dbQueue: DatabaseQueue) {
|
||||
self.dbQueue = dbQueue
|
||||
}
|
||||
|
||||
func author(id: Int64) throws -> Author? {
|
||||
try dbQueue.read { db in
|
||||
try Author.fetchOne(db, key: id)
|
||||
}
|
||||
}
|
||||
|
||||
func book(id: Int64) throws -> Book? {
|
||||
try dbQueue.read { db in
|
||||
try Book.fetchOne(db, key: id)
|
||||
}
|
||||
}
|
||||
|
||||
func books(writtenBy author: Author) throws -> [Book] {
|
||||
try dbQueue.read { db in
|
||||
try author.books.fetchAll(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Thread-Safety is also an Application Concern
|
||||
|
||||
Now, let's make our database manager **thread-safe**.
|
||||
|
||||
This one is more subtle. In order to understand what is wrong in our naive manager, one has to consider how it is used by the application.
|
||||
|
||||
For example, in the screen that displays an author and her books, we would write:
|
||||
|
||||
```swift
|
||||
let authorId = 123
|
||||
if let author = libraryManager.author(id: authorId) {
|
||||
let books = libraryManager.books(writtenBy: author)
|
||||
// Use author and books
|
||||
}
|
||||
```
|
||||
|
||||
This code is not thread-safe, because other application threads may have modified the database between the two database accesses. You may end up with an author without any book, and this sure does not make a pretty application screen.
|
||||
|
||||
Such bugs are uneasy to reproduce. Sometimes your application will refresh the library content from the network, and delete an author right at the wrong time. The more users your application has, the more users will see weird screens. And of course, you'll be bitten right on the day of the demo in front of the boss.
|
||||
|
||||
Fortunately, GRDB has all the tools you need to prevent such nasty data races:
|
||||
|
||||
> :bulb: **Tip**: Make sure you fetch all the data your application needs at a given moment of time, in a **single database read**.
|
||||
|
||||
This gives a much safer manager:
|
||||
|
||||
```swift
|
||||
// A manager that actually manages
|
||||
class LibraryManager {
|
||||
private let dbQueue: DatabaseQueue
|
||||
init(dbQueue: DatabaseQueue) {
|
||||
self.dbQueue = dbQueue
|
||||
}
|
||||
}
|
||||
|
||||
// Feeds the list of authors
|
||||
extension LibraryManager {
|
||||
struct AuthorListItem: Decodable, FetchableRecord {
|
||||
let author: Author
|
||||
let bookCount: Int
|
||||
}
|
||||
|
||||
func authorList() throws -> [AuthorListItem] {
|
||||
try dbQueue.read { db in
|
||||
let request = Author
|
||||
.annotated(with: Author.books.count)
|
||||
.orderByName()
|
||||
return try AuthorListItem.fetchAll(db, request)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Feeds a book screen
|
||||
extension LibraryManager {
|
||||
struct BookInfo {
|
||||
var book: Book
|
||||
var author: Author
|
||||
}
|
||||
|
||||
func bookInfo(bookId: Int64) throws -> BookInfo? {
|
||||
try dbQueue.read { db in
|
||||
guard let book = try Book.fetchOne(db, key: bookId) else {
|
||||
return nil
|
||||
}
|
||||
guard let author = try book.author.fetchOne(db) else {
|
||||
return nil
|
||||
}
|
||||
return BookInfo(book: book, author: author)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Feeds an author screen
|
||||
extension LibraryManager {
|
||||
struct AuthorInfo {
|
||||
var author: Author
|
||||
var books: [Book]
|
||||
}
|
||||
|
||||
func authorInfo(authorId: Int64) throws -> AuthorInfo? {
|
||||
try dbQueue.read { db in
|
||||
guard let author = try Author.fetchOne(db, key: authorId) else {
|
||||
return nil
|
||||
}
|
||||
let books = try author.books.fetchAll(db)
|
||||
return AuthorInfo(author: author, books: books)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The `AuthorListItem`, `BookInfo`, `AuthorInfo` types returned by the manager are designed to feed your views.
|
||||
|
||||
When a new screen is added to your application, and you want to make sure it displays **consistent data** free from any data race, make sure you update the manager if needed. The rule is very simple: consumed data must come from a **single** database access method (`dbQueue.read`, `write`, etc.), or [ValueObservation].
|
||||
|
||||
In other words: since GRDB is an unmanaged ORM, some amount of management must be imported into your application in order to make it fully thread-safe.
|
||||
|
||||
> :question: **Note**: Wrapping several fetches in a single `read` method may look like an inconvenience to you. After all, other ORMs don't require that much ceremony:
|
||||
>
|
||||
> ```ruby
|
||||
> # Ruby's Active Record
|
||||
> book = Book.find(123) # fetch book
|
||||
> author = book.author # fetch author
|
||||
> # use book and author
|
||||
> ```
|
||||
>
|
||||
> The problem is that it is very hard to guarantee that you will surely fetch an author after you have fetched a book, despite the constraints of the database schema. One has to perform subsequent fetches in the proper [isolation] level, so that eventual concurrent writes that modify the database are unable to mess with subsequent requests.
|
||||
>
|
||||
> This isolation can be achieved with record management, as in [Core Data] or [Realm], that target long-running multi-threaded applications. On the other side, most web-oriented ORMs rely on short-lived database transactions, so that each HTTP request can be processed independently of others.
|
||||
>
|
||||
> GRDB is not a managed ORM. It thus has to use the same isolation techniques as web-oriented ORMs. But unlike web-oriented ORMs, GRDB can't provide implicit isolation: the application must decide when it wants to safely read information in the database, and this decision is made explicit, in your application code, with database access methods such as `dbQueue.read`.
|
||||
>
|
||||
> See the [Concurrency Guide] for detailed information, and the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more rationale.
|
||||
|
||||
|
||||
## Observe the Database and Refetch when Needed
|
||||
|
||||
We have seen above that the Author and Book record types are [responsible](#record-types-are-responsible-for-their-tables) for their own dedicated database tables. Later we [composed](#compose-records) them into more complex types such as `BookInfo` or `AuthorInfo`. We advised the application to fetch database information [right on time](#fetch-in-time), when it needs to process it.
|
||||
We have seen above that the primitive Author and Book record types are [responsible](#persistable-record-types-are-responsible-for-their-tables) for their own database tables. Later we built [requests](#define-record-requests) and [composed](#compose-records) records into more complex ones such as BookInfo or AuthorInfo. We have shown how [database managers](#how-to-design-database-managers) should expose database content to the rest of the application.
|
||||
|
||||
Fetched information eventually becomes obsoleted, as the application modifies the database content.
|
||||
Database content which has been fetched into memory eventually becomes obsoleted, as the application modifies the database content.
|
||||
|
||||
It is up to the application to decide how long it should keep fetched information in memory. Very often though, the application will want to keep memory information synchronized with the database content.
|
||||
|
||||
@@ -310,7 +679,7 @@ Instead, have a look at [Database Observation]:
|
||||
|
||||
> :bulb: **Tip**: [ValueObservation] performs automated tracking of database changes.
|
||||
>
|
||||
> :bulb: **Tip**: [FetchedRecordsController] performs automated tracking of database changes, and can animate the cells of a table or collection view.
|
||||
> :bulb: **Tip**: [GRDBCombine] performs automated tracking of database changes, in the [Combine](https://developer.apple.com/documentation/combine) way.
|
||||
>
|
||||
> :bulb: **Tip**: [RxGRDB] performs automated tracking of database changes, in the [RxSwift](https://github.com/ReactiveX/RxSwift) way.
|
||||
>
|
||||
@@ -318,7 +687,6 @@ Instead, have a look at [Database Observation]:
|
||||
>
|
||||
> :bulb: **Tip**: Don't try to write complex methods that both modify the database and the values in memory at the same time. Instead, modify the database with plain record types, and rely on database observation for automatically refreshing values, even complex ones.
|
||||
|
||||
|
||||
[records]: ../README.md#records
|
||||
[associations]: AssociationsBasics.md
|
||||
[FMDB]: https://github.com/ccgus/fmdb
|
||||
@@ -337,14 +705,25 @@ Instead, have a look at [Database Observation]:
|
||||
[migration]: ../README.md#migrations
|
||||
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
|
||||
[Concurrency Guide]: ../README.md#concurrency
|
||||
[GRDB concurrency rules]: ../README.md#concurrency
|
||||
[PersistableRecord]: ../README.md#persistablerecord-protocol
|
||||
[Database Observation]: ../README.md#database-changes-observation
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[FetchedRecordsController]: ../README.md#fetchedrecordscontroller
|
||||
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
|
||||
[GRDBCombine]: http://github.com/groue/GRDBCombine
|
||||
[TransactionObserver]: ../README.md#transactionobserver-protocol
|
||||
[Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself
|
||||
[Record Types are Responsible for Their Tables]: #record-types-are-responsible-for-their-tables
|
||||
[Persistable Record Types are Responsible for Their Tables]: #persistable-record-types-are-responsible-for-their-tables
|
||||
[Define Record Requests]: #define-record-requests
|
||||
[Compose Records]: #compose-records
|
||||
[Fetch In Time]: #fetch-in-time
|
||||
[How to Design Database Managers]: #how-to-design-database-managers
|
||||
[Observe the Database and Refetch when Needed]: #observe-the-database-and-refetch-when-needed
|
||||
[query interface]: ../README.md#the-query-interface
|
||||
[observe database changes]: ../README.md#database-changes-observation
|
||||
[data protection]: ../README.md#data-protection
|
||||
[Embrace Errors]: #embrace-errors
|
||||
[Thread-Safety is also an Application Concern]: #thread-safety-is-also-an-application-concern
|
||||
[recommended convention]: AssociationsBasics.md#associations-and-the-database-schema
|
||||
[Association Aggregates]: AssociationsBasics.md#association-aggregates
|
||||
[Codable Record]: ../README.md#codable-records
|
||||
[CodingKeys]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
|
||||
@@ -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
|
||||
{ }
|
||||
@@ -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)
|
||||
@@ -15,7 +15,6 @@ To release a new GRDB version:
|
||||
- Update GRDB version number and release date in:
|
||||
- Makefile
|
||||
- CHANGELOG.md
|
||||
- Documentation/CustomSQLiteBuilds.md
|
||||
- GRDB.swift.podspec
|
||||
- README.md
|
||||
- Support/Info.plist
|
||||
|
||||
@@ -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
|
||||
@@ -90,6 +90,8 @@ For your convenience, those record protocols can be derived from the [Decodable
|
||||
|
||||
Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with **database change notifications**, with many advantages.
|
||||
|
||||
See [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md) for some practical advice.
|
||||
|
||||
|
||||
### Allow database records to cross threads
|
||||
|
||||
@@ -113,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, or [FetchedRecordsController], which animates table and collection views. And don't forget [RxGRDB], a set of reactive extensions based on [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
|
||||
@@ -170,7 +188,9 @@ We can see that the threat of conflicts is *always* left to the application. Cor
|
||||
|
||||
Finally, raw FMDatabase, SQLite.swift, and Core Data are the hardest tools, and you'd better be a very skilled developer in order to use them properly.
|
||||
|
||||
For further information about GRDB concurrency, check its detailed [Concurrency Guide].
|
||||
For detailed information about GRDB concurrency, check the [Concurrency Guide].
|
||||
|
||||
For practical advice on designing the database access layer of your application, see the [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md).
|
||||
|
||||
|
||||
### Never pay for using raw SQL
|
||||
@@ -227,44 +247,30 @@ 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)"
|
||||
}
|
||||
}
|
||||
|
||||
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 [ValueObservation] and [RxGRDB]:
|
||||
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
|
||||
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]
|
||||
@@ -287,7 +293,6 @@ Happy GRDB! :gift:
|
||||
[Diesel]: http://diesel.rs
|
||||
[FCModel]: https://github.com/marcoarment/FCModel
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[FetchedRecordsController]: ../README.md#fetchedrecordscontroller
|
||||
[Fluent]: https://github.com/vapor/fluent
|
||||
[FMDB]: http://github.com/ccgus/fmdb
|
||||
[GRDB]: http://github.com/groue/GRDB.swift
|
||||
@@ -297,6 +302,8 @@ Happy GRDB! :gift:
|
||||
[FetchableRecord]: ../README.md#records
|
||||
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
|
||||
[RxSwift]: https://github.com/ReactiveX/RxSwift
|
||||
[GRDBCombine]: http://github.com/groue/GRDBCombine
|
||||
[Combine]: https://developer.apple.com/documentation/combine
|
||||
[SQLite.swift]: http://github.com/stephencelis/SQLite.swift
|
||||
[StORM]: https://www.perfect.org/docs/StORM.html
|
||||
[Swift-Kuery]: http://github.com/IBM-Swift/Swift-Kuery
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '4.0.0'
|
||||
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,20 +9,21 @@ 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 = ['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.module_map = 'Support/module.modulemap'
|
||||
s.tvos.deployment_target = '9.0'
|
||||
s.default_subspec = 'standard'
|
||||
|
||||
s.subspec 'standard' do |ss|
|
||||
ss.source_files = 'GRDB/**/*.swift', 'Support/*.h'
|
||||
ss.source_files = 'GRDB/**/*.swift', 'Support/grdb_config.h'
|
||||
ss.framework = 'Foundation'
|
||||
ss.library = 'sqlite3'
|
||||
end
|
||||
|
||||
s.subspec 'SQLCipher' do |ss|
|
||||
ss.source_files = 'GRDB/**/*.swift', 'Support/*.h'
|
||||
ss.source_files = 'GRDB/**/*.swift', 'Support/grdb_config.h'
|
||||
ss.framework = 'Foundation'
|
||||
ss.dependency 'SQLCipher', '>= 3.4.0'
|
||||
ss.xcconfig = {
|
||||
|
||||
@@ -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 = "1020"
|
||||
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 = "1020"
|
||||
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 = "1020"
|
||||
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"
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1130"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBtvOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
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">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "AAA4DD07230F262000C74B15"
|
||||
BuildableName = "GRDBtvOSTests.xctest"
|
||||
BlueprintName = "GRDBtvOSTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBtvOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBtvOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -2,7 +2,7 @@
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
<Group
|
||||
location = "group:Playgrounds"
|
||||
location = "group:Documentation/Playgrounds"
|
||||
name = "Playgrounds">
|
||||
<FileRef
|
||||
location = "group:Tour.playground">
|
||||
@@ -51,6 +51,6 @@
|
||||
location = "group:Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj">
|
||||
location = "group:Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
@@ -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,23 +68,46 @@ public struct Configuration {
|
||||
/// Default: nil
|
||||
public var trace: TraceFunction?
|
||||
|
||||
|
||||
// MARK: - Encryption
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
/// 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
|
||||
public var passphrase: String?
|
||||
|
||||
#endif
|
||||
|
||||
/// If set, allows custom configuration to be run every time
|
||||
/// a new connection is opened.
|
||||
/// For example:
|
||||
///
|
||||
/// This block is run after the Database's connection has opened, but
|
||||
/// before that connection has been made available to any read/write
|
||||
/// API's.
|
||||
/// // 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
|
||||
|
||||
/// A function that is run when an SQLite connection is opened, before the
|
||||
/// connection is made available for database access methods.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -158,10 +174,18 @@ 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 the work performed by the database.
|
||||
/// The target queue for all database accesses.
|
||||
///
|
||||
/// When you use a database pool, make sure the queue is concurrent. If
|
||||
/// it is serial, no concurrent database access can happen, and you may
|
||||
/// experience deadlocks.
|
||||
///
|
||||
/// If the queue is nil, all database accesses happen in unspecified
|
||||
/// dispatch queues whose quality of service and label are determined by the
|
||||
/// `qos` and `label` Configuration properties.
|
||||
///
|
||||
/// Default: nil
|
||||
public var targetQueue: DispatchQueue? = nil
|
||||
@@ -169,21 +193,14 @@ 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
|
||||
|
||||
var threadingMode: Database.ThreadingMode = .`default`
|
||||
var SQLiteConnectionDidOpen: (() -> ())?
|
||||
var SQLiteConnectionWillClose: ((SQLiteConnection) -> ())?
|
||||
var SQLiteConnectionDidClose: (() -> ())?
|
||||
var SQLiteConnectionDidOpen: (() -> Void)?
|
||||
var SQLiteConnectionWillClose: ((SQLiteConnection) -> Void)?
|
||||
var SQLiteConnectionDidClose: (() -> Void)?
|
||||
var SQLiteOpenFlags: Int32 {
|
||||
let readWriteFlags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE)
|
||||
return threadingMode.SQLiteOpenFlags | readWriteFlags
|
||||
|
||||
@@ -29,8 +29,11 @@ extension Sequence {
|
||||
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<AnyCursor<Iterator.Element>, SegmentOfResult>> {
|
||||
return AnyCursor(self).flatMap(transform)
|
||||
public func flatMap<SegmentOfResult: Cursor>(
|
||||
_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult)
|
||||
-> FlattenCursor<MapCursor<AnyCursor<Iterator.Element>, SegmentOfResult>>
|
||||
{
|
||||
AnyCursor(self).flatMap(transform)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,7 +79,7 @@ extension Set {
|
||||
/// `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`,
|
||||
/// `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`,
|
||||
/// `suffix`.
|
||||
public protocol Cursor : class {
|
||||
public protocol Cursor: AnyObject {
|
||||
/// The type of element traversed by the cursor.
|
||||
associatedtype Element
|
||||
|
||||
@@ -89,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
|
||||
@@ -120,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
|
||||
@@ -141,8 +144,10 @@ extension Cursor {
|
||||
|
||||
/// Returns a cursor over the concatenated non-nil results of mapping
|
||||
/// transform over this cursor.
|
||||
public func compactMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult> {
|
||||
return map(transform).filter { $0 != nil }.map { $0! }
|
||||
public func compactMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?)
|
||||
-> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult>
|
||||
{
|
||||
map(transform).filter { $0 != nil }.map { $0! }
|
||||
}
|
||||
|
||||
/// Returns a cursor that skips any initial elements that satisfy
|
||||
@@ -153,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
|
||||
@@ -173,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.
|
||||
@@ -188,9 +193,9 @@ 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
|
||||
/// elements.
|
||||
///
|
||||
@@ -238,19 +243,25 @@ 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
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult: Sequence>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, AnyCursor<SegmentOfResult.Element>>> {
|
||||
return flatMap { try AnyCursor(transform($0)) }
|
||||
public func flatMap<SegmentOfResult>(_ transform: @escaping (Element) throws -> SegmentOfResult)
|
||||
-> FlattenCursor<MapCursor<Self, AnyCursor<SegmentOfResult.Element>>>
|
||||
where SegmentOfResult: Sequence
|
||||
{
|
||||
flatMap { try AnyCursor(transform($0)) }
|
||||
}
|
||||
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, SegmentOfResult>> {
|
||||
return map(transform).joined()
|
||||
public func flatMap<SegmentOfResult>(_ transform: @escaping (Element) throws -> SegmentOfResult)
|
||||
-> FlattenCursor<MapCursor<Self, SegmentOfResult>>
|
||||
where SegmentOfResult: Cursor
|
||||
{
|
||||
map(transform).joined()
|
||||
}
|
||||
|
||||
/// Calls the given closure on each element in the cursor.
|
||||
@@ -263,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
|
||||
@@ -323,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
|
||||
@@ -334,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
|
||||
@@ -437,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.
|
||||
@@ -449,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: <)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -458,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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -467,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 }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -503,7 +514,7 @@ extension Cursor where Element: StringProtocol {
|
||||
/// This cursor forwards its next() method to an arbitrary underlying cursor
|
||||
/// having the same Element type, hiding the specifics of the underlying
|
||||
/// cursor.
|
||||
public final class AnyCursor<Element> : Cursor {
|
||||
public final class AnyCursor<Element>: Cursor {
|
||||
private let element: () throws -> Element?
|
||||
|
||||
/// Creates a cursor that wraps a base cursor but whose type depends only on
|
||||
@@ -534,16 +545,16 @@ public final class AnyCursor<Element> : Cursor {
|
||||
/// element exists.
|
||||
/// :nodoc:
|
||||
public func next() throws -> Element? {
|
||||
return try element()
|
||||
try element()
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public final class DropFirstCursor<Base: Cursor> : Cursor {
|
||||
public final class DropFirstCursor<Base: Cursor>: Cursor {
|
||||
private let base: Base
|
||||
private let limit: Int
|
||||
private var dropped: Int = 0
|
||||
|
||||
|
||||
init(_ base: Base, limit: Int) {
|
||||
GRDBPrecondition(limit >= 0, "Can't drop a negative number of elements from a cursor")
|
||||
self.base = base
|
||||
@@ -566,7 +577,7 @@ public final class DropFirstCursor<Base: Cursor> : Cursor {
|
||||
/// consecutive elements of some base cursor that satisfy a given predicate.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class DropWhileCursor<Base: Cursor> : Cursor {
|
||||
public final class DropWhileCursor<Base: Cursor>: Cursor {
|
||||
private let base: Base
|
||||
private let predicate: (Base.Element) throws -> Bool
|
||||
private var predicateHasFailed = false
|
||||
@@ -605,7 +616,7 @@ public final class DropWhileCursor<Base: Cursor> : Cursor {
|
||||
/// // Prints: "1: bar"
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class EnumeratedCursor<Base: Cursor> : Cursor {
|
||||
public final class EnumeratedCursor<Base: Cursor>: Cursor {
|
||||
private let base: Base
|
||||
private var index: Int
|
||||
|
||||
@@ -628,7 +639,7 @@ public final class EnumeratedCursor<Base: Cursor> : Cursor {
|
||||
/// also satisfy a given predicate.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class FilterCursor<Base: Cursor> : Cursor {
|
||||
public final class FilterCursor<Base: Cursor>: Cursor {
|
||||
private let base: Base
|
||||
private let isIncluded: (Base.Element) throws -> Bool
|
||||
|
||||
@@ -656,7 +667,7 @@ public final class FilterCursor<Base: Cursor> : Cursor {
|
||||
/// See Cursor.joined(), Cursor.flatMap(_:), Sequence.flatMap(_:)
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Cursor {
|
||||
public final class FlattenCursor<Base: Cursor>: Cursor where Base.Element: Cursor {
|
||||
private let base: Base
|
||||
private var inner: Base.Element?
|
||||
|
||||
@@ -686,7 +697,7 @@ public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Curs
|
||||
/// See Cursor.map(_:)
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class MapCursor<Base: Cursor, Element> : Cursor {
|
||||
public final class MapCursor<Base: Cursor, Element>: Cursor {
|
||||
private let base: Base
|
||||
private let transform: (Base.Element) throws -> Element
|
||||
|
||||
@@ -708,7 +719,7 @@ public final class MapCursor<Base: Cursor, Element> : Cursor {
|
||||
/// `Base` cursor.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class PrefixCursor<Base: Cursor> : Cursor {
|
||||
public final class PrefixCursor<Base: Cursor>: Cursor {
|
||||
private let base: Base
|
||||
private let maxLength: Int
|
||||
private var taken = 0
|
||||
@@ -735,7 +746,7 @@ public final class PrefixCursor<Base: Cursor> : Cursor {
|
||||
/// some base cursor that satisfy a given predicate.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class PrefixWhileCursor<Base: Cursor> : Cursor {
|
||||
public final class PrefixWhileCursor<Base: Cursor>: Cursor {
|
||||
private let base: Base
|
||||
private let predicate: (Base.Element) throws -> Bool
|
||||
private var predicateHasFailed = false
|
||||
|
||||
@@ -1,15 +1,7 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
extension Database {
|
||||
|
||||
|
||||
// MARK: - Database Schema
|
||||
|
||||
|
||||
/// Clears the database schema cache.
|
||||
///
|
||||
/// You may need to clear the cache manually if the database schema is
|
||||
@@ -28,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.
|
||||
@@ -50,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 {
|
||||
@@ -71,7 +63,7 @@ extension Database {
|
||||
.names(ofType: type)
|
||||
.contains { $0.lowercased() == name }
|
||||
}
|
||||
|
||||
|
||||
/// The primary key for table named `tableName`.
|
||||
///
|
||||
/// All tables have a primary key, even when it is not explicit. When a
|
||||
@@ -152,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)
|
||||
@@ -180,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)
|
||||
@@ -203,8 +195,13 @@ extension Database {
|
||||
|
||||
/// True if a sequence of columns uniquely identifies a row, that is to say
|
||||
/// if the columns are the primary key, or if there is a unique index on them.
|
||||
public func table<T: Sequence>(_ tableName: String, hasUniqueKey columns: T) throws -> Bool where T.Iterator.Element == String {
|
||||
return try columnsForUniqueKey(Array(columns), in: tableName) != nil
|
||||
public func table<T: Sequence>(
|
||||
_ tableName: String,
|
||||
hasUniqueKey columns: T)
|
||||
throws -> Bool
|
||||
where T.Iterator.Element == String
|
||||
{
|
||||
try columnsForUniqueKey(Array(columns), in: tableName) != nil
|
||||
}
|
||||
|
||||
/// The foreign keys defined on table named `tableName`.
|
||||
@@ -213,7 +210,9 @@ extension Database {
|
||||
return foreignKeys
|
||||
}
|
||||
|
||||
var rawForeignKeys: [(destinationTable: String, mapping: [(origin: String, destination: String?, seq: Int)])] = []
|
||||
var rawForeignKeys: [(
|
||||
destinationTable: String,
|
||||
mapping: [(origin: String, destination: String?, seq: Int)])] = []
|
||||
var previousId: Int? = nil
|
||||
for row in try Row.fetchAll(self, sql: "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") {
|
||||
// row = [id:0 seq:0 table:"parents" from:"parentId" to:"id" on_update:"..." on_delete:"..." match:"..."]
|
||||
@@ -224,9 +223,13 @@ extension Database {
|
||||
let destination: String? = row[4]
|
||||
|
||||
if previousId == id {
|
||||
rawForeignKeys[rawForeignKeys.count - 1].mapping.append((origin: origin, destination: destination, seq: seq))
|
||||
rawForeignKeys[rawForeignKeys.count - 1]
|
||||
.mapping
|
||||
.append((origin: origin, destination: destination, seq: seq))
|
||||
} else {
|
||||
rawForeignKeys.append((destinationTable: table, mapping: [(origin: origin, destination: destination, seq: seq)]))
|
||||
rawForeignKeys.append((
|
||||
destinationTable: table,
|
||||
mapping: [(origin: origin, destination: destination, seq: seq)]))
|
||||
previousId = id
|
||||
}
|
||||
}
|
||||
@@ -281,7 +284,7 @@ extension Database {
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
|
||||
/// The columns in the table named `tableName`
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
@@ -313,7 +316,7 @@ extension Database {
|
||||
// 0 | id | INTEGER | 0 | NULL | 1 |
|
||||
// 1 | name | TEXT | 0 | NULL | 0 |
|
||||
// 2 | score | INTEGER | 0 | NULL | 0 |
|
||||
|
||||
|
||||
if sqlite3_libversion_number() < 3008005 {
|
||||
// Work around a bug in SQLite where PRAGMA table_info would
|
||||
// return a result even after the table was deleted.
|
||||
@@ -324,7 +327,7 @@ extension Database {
|
||||
let columns = try ColumnInfo
|
||||
.fetchAll(self, sql: "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
|
||||
.sorted(by: { $0.cid < $1.cid })
|
||||
guard columns.count > 0 else {
|
||||
if columns.isEmpty {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
}
|
||||
|
||||
@@ -335,14 +338,31 @@ extension Database {
|
||||
/// If there exists a unique key on columns, return the columns
|
||||
/// ordered as the matching index (or primay key). Case of returned columns
|
||||
/// is not guaranteed.
|
||||
func columnsForUniqueKey<T: Sequence>(_ columns: T, in tableName: String) throws -> [String]? where T.Iterator.Element == String {
|
||||
let primaryKey = try self.primaryKey(tableName) // first, so that we fail early and consistently should the table not exist
|
||||
func columnsForUniqueKey<T: Sequence>(
|
||||
_ columns: T,
|
||||
in tableName: String)
|
||||
throws -> [String]?
|
||||
where T.Iterator.Element == String
|
||||
{
|
||||
// Check primaryKey first, so that we fail early if the table does not exist
|
||||
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
|
||||
}
|
||||
if let index = try indexes(on: tableName).first(where: { index in index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns }) {
|
||||
// There is an explicit unique index on the columns
|
||||
|
||||
// Is there is an explicit unique index on the columns?
|
||||
let indexes = try self.indexes(on: tableName)
|
||||
let matchingIndex = indexes.first { index in
|
||||
index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns
|
||||
}
|
||||
if let index = matchingIndex {
|
||||
return index.columns
|
||||
}
|
||||
return nil
|
||||
@@ -366,7 +386,7 @@ extension Database {
|
||||
/// 2 score INTEGER 0 NULL 0
|
||||
///
|
||||
/// See `Database.columns(in:)` and https://www.sqlite.org/pragma.html#pragma_table_info
|
||||
public struct ColumnInfo : FetchableRecord {
|
||||
public struct ColumnInfo: FetchableRecord {
|
||||
let cid: Int
|
||||
|
||||
/// The column name
|
||||
@@ -503,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 {
|
||||
@@ -561,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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -590,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(sql: sql, prepFlags: prepFlags, in: self)
|
||||
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(sql: sql, prepFlags: prepFlags, in: self)
|
||||
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
|
||||
@@ -180,16 +175,15 @@ extension Database {
|
||||
|
||||
// Compile
|
||||
do {
|
||||
let statementCompilationAuthorizer = StatementCompilationAuthorizer()
|
||||
authorizer = statementCompilationAuthorizer
|
||||
defer { authorizer = nil }
|
||||
|
||||
nextStatement = try UpdateStatement(
|
||||
database: self,
|
||||
statementStart: statementStart,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: 0,
|
||||
authorizer: statementCompilationAuthorizer)
|
||||
let authorizer = StatementCompilationAuthorizer()
|
||||
nextStatement = try withAuthorizer(authorizer) {
|
||||
try UpdateStatement(
|
||||
database: self,
|
||||
statementStart: statementStart,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: 0,
|
||||
authorizer: authorizer)
|
||||
}
|
||||
}
|
||||
|
||||
guard let statement = nextStatement else {
|
||||
@@ -200,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()
|
||||
@@ -213,18 +207,71 @@ extension Database {
|
||||
// Check that all arguments were consumed: it is a programmer error to
|
||||
// provide arguments that do not match the statement.
|
||||
if arguments.values.isEmpty == false {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)")
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: "wrong number of statement arguments: \(initialValuesCount)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
func updateStatementWillExecute(_ statement: UpdateStatement) {
|
||||
observationBroker.updateStatementWillExecute(statement)
|
||||
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
|
||||
withAuthorizer(authorizer) {
|
||||
while true {
|
||||
code = sqlite3_step(sqliteStatement)
|
||||
if code == SQLITE_ROW {
|
||||
// Statement returns a row, but the user ignores the
|
||||
// content of this row:
|
||||
//
|
||||
// try db.execute(sql: "SELECT ...")
|
||||
//
|
||||
// That's OK: maybe the selected rows perform side effects.
|
||||
// For example:
|
||||
//
|
||||
// try db.execute(sql: "SELECT sqlcipher_export(...)")
|
||||
//
|
||||
// Or maybe the user doesn't know that the executed statement
|
||||
// return rows (https://github.com/groue/GRDB.swift/issues/15);
|
||||
//
|
||||
// try db.execute(sql: "PRAGMA journal_mode=WAL")
|
||||
//
|
||||
// It is thus important that we consume *all* rows.
|
||||
continue
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Statement has been fully executed, and authorizer has been reset.
|
||||
// We can now move on further tasks.
|
||||
|
||||
if code == SQLITE_DONE {
|
||||
try updateStatementDidExecute(statement)
|
||||
} else {
|
||||
assert(code != SQLITE_ROW)
|
||||
try updateStatementDidFail(statement)
|
||||
throw DatabaseError(
|
||||
resultCode: code,
|
||||
message: lastErrorMessage,
|
||||
sql: statement.sql,
|
||||
arguments: statement.arguments)
|
||||
}
|
||||
}
|
||||
|
||||
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
|
||||
private func updateStatementDidExecute(_ statement: UpdateStatement) throws {
|
||||
if statement.invalidatesDatabaseSchemaCache {
|
||||
clearSchemaCache()
|
||||
}
|
||||
@@ -232,7 +279,7 @@ extension Database {
|
||||
try observationBroker.updateStatementDidExecute(statement)
|
||||
}
|
||||
|
||||
func updateStatementDidFail(_ statement: UpdateStatement) throws {
|
||||
private func updateStatementDidFail(_ statement: UpdateStatement) throws {
|
||||
// Failed statements can not be reused, because sqlite3_reset won't
|
||||
// be able to restore the statement to its initial state:
|
||||
// https://www.sqlite.org/c3ref/reset.html
|
||||
@@ -244,6 +291,18 @@ extension Database {
|
||||
try observationBroker.updateStatementDidFail(statement)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
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 {
|
||||
_selectedRegion.formUnion(statement.selectedRegion)
|
||||
}
|
||||
}
|
||||
|
||||
func selectStatementDidFail(_ statement: SelectStatement) {
|
||||
// Failed statements can not be reused, because sqlite3_reset won't
|
||||
// be able to restore the statement to its initial state:
|
||||
@@ -294,7 +353,7 @@ struct StatementCache {
|
||||
selectStatements[sql] = statement
|
||||
return statement
|
||||
}
|
||||
|
||||
|
||||
mutating func updateStatement(_ sql: String) throws -> UpdateStatement {
|
||||
if let statement = updateStatements[sql] {
|
||||
return statement
|
||||
|
||||
@@ -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
|
||||
@@ -36,7 +29,7 @@ public final class Database {
|
||||
public let sqliteConnection: SQLiteConnection
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
|
||||
/// The error logging function.
|
||||
///
|
||||
/// Quoting https://www.sqlite.org/errlog.html:
|
||||
@@ -53,7 +46,7 @@ public final class Database {
|
||||
if logError != nil {
|
||||
registerErrorLogCallback { (_, code, message) in
|
||||
guard let logError = Database.logError else { return }
|
||||
guard let message = message.map({ String(cString: $0) }) else { return }
|
||||
guard let message = message.map(String.init) else { return }
|
||||
let resultCode = ResultCode(rawValue: code)
|
||||
logError(resultCode, message)
|
||||
}
|
||||
@@ -114,7 +107,7 @@ public final class Database {
|
||||
// > connection while this routine is running, then the return value
|
||||
// > is undefined.
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
if isClosed { return false } // Support for SerializedDatabasae.deinit
|
||||
if isClosed { return false } // Support for SerializedDatabase.deinit
|
||||
return sqlite3_get_autocommit(sqliteConnection) == 0
|
||||
}
|
||||
|
||||
@@ -125,28 +118,14 @@ public final class Database {
|
||||
lazy var internalStatementCache = StatementCache(database: self)
|
||||
lazy var publicStatementCache = StatementCache(database: self)
|
||||
|
||||
// Errors
|
||||
var lastErrorCode: ResultCode { return ResultCode(rawValue: sqlite3_errcode(sqliteConnection)) }
|
||||
var lastErrorMessage: String? { return String(cString: sqlite3_errmsg(sqliteConnection)) }
|
||||
/// The last error code
|
||||
public var lastErrorCode: ResultCode { ResultCode(rawValue: sqlite3_errcode(sqliteConnection)) }
|
||||
|
||||
// Statement authorizer
|
||||
var authorizer: StatementAuthorizer? {
|
||||
didSet {
|
||||
switch (oldValue, authorizer) {
|
||||
case (.some, nil):
|
||||
sqlite3_set_authorizer(sqliteConnection, nil, nil)
|
||||
case (nil, .some):
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
sqlite3_set_authorizer(sqliteConnection, { (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in
|
||||
guard let dbPointer = dbPointer else { return SQLITE_OK }
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer).takeUnretainedValue()
|
||||
return db.authorizer!.authorize(actionCode, cString1, cString2, cString3, cString4)
|
||||
}, dbPointer)
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The last error message
|
||||
public var lastErrorMessage: String? { String(cString: sqlite3_errmsg(sqliteConnection)) }
|
||||
|
||||
/// Statement authorizer. Use withAuthorizer(_:_:).
|
||||
fileprivate var _authorizer: StatementAuthorizer?
|
||||
|
||||
// Transaction observers management
|
||||
lazy var observationBroker = DatabaseObservationBroker(self)
|
||||
@@ -156,17 +135,32 @@ public final class Database {
|
||||
try! Set(String.fetchCursor($0, sql: "PRAGMA COMPILE_OPTIONS"))
|
||||
}
|
||||
|
||||
/// If true, select statement execution is recorded.
|
||||
/// 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?
|
||||
|
||||
private var functions = Set<DatabaseFunction>()
|
||||
private var collations = Set<DatabaseCollation>()
|
||||
|
||||
private var _readOnlyDepth = 0 // Modify with beginReadOnly/endReadOnly
|
||||
private var isClosed: Bool = false
|
||||
|
||||
|
||||
// MARK: - Initializer
|
||||
|
||||
|
||||
init(path: String, configuration: Configuration, schemaCache: DatabaseSchemaCache) throws {
|
||||
self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
|
||||
self.configuration = configuration
|
||||
@@ -176,10 +170,7 @@ public final class Database {
|
||||
deinit {
|
||||
assert(isClosed)
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
|
||||
// MARK: - Database Opening
|
||||
|
||||
private static func openConnection(path: String, flags: Int32) throws -> SQLiteConnection {
|
||||
@@ -204,34 +195,29 @@ extension Database {
|
||||
}
|
||||
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
|
||||
// MARK: - Database Setup
|
||||
|
||||
/// This method must be called after database initialization
|
||||
func setup() throws {
|
||||
// Setup trace first, so that setup queries are traced.
|
||||
setupTrace()
|
||||
setupDoubleQuotedStringLiterals()
|
||||
try setupForeignKeys()
|
||||
setupBusyMode()
|
||||
setupDefaultFunctions()
|
||||
setupDefaultCollations()
|
||||
setupAuthorizer()
|
||||
observationBroker.installCommitAndRollbackHooks()
|
||||
try activateExtendedCodes()
|
||||
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
try validateSQLCipher()
|
||||
if let passphrase = configuration.passphrase {
|
||||
try setCipherPassphrase(passphrase)
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// Last step before we can start accessing the database.
|
||||
// This is the opportunity to run SQLCipher configuration
|
||||
// pragmas such as cipher_page_size, for example.
|
||||
try configuration.prepareDatabase?(self)
|
||||
|
||||
try validateFormat()
|
||||
configuration.SQLiteConnectionDidOpen?()
|
||||
}
|
||||
@@ -240,24 +226,34 @@ extension Database {
|
||||
guard configuration.trace != nil else {
|
||||
return
|
||||
}
|
||||
// sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0 http://www.sqlite.org/changes.html#version_3_14
|
||||
// It is available from iOS 10.0 and OS X 10.12 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
// sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0
|
||||
// http://www.sqlite.org/changes.html#version_3_14
|
||||
// It is available from iOS 10.0 and OS X 10.12
|
||||
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
sqlite3_trace_v2(sqliteConnection, UInt32(SQLITE_TRACE_STMT), { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in
|
||||
return Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql)
|
||||
}, dbPointer)
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
sqlite3_trace_v2(
|
||||
sqliteConnection,
|
||||
UInt32(SQLITE_TRACE_STMT),
|
||||
{ (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in
|
||||
Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql)
|
||||
},
|
||||
dbPointer)
|
||||
#elseif os(Linux)
|
||||
setupTrace_v1()
|
||||
setupTrace_v1()
|
||||
#else
|
||||
if #available(iOS 10.0, OSX 10.12, watchOS 3.0, *) {
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
sqlite3_trace_v2(sqliteConnection, UInt32(SQLITE_TRACE_STMT), { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in
|
||||
return Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql)
|
||||
}, dbPointer)
|
||||
} else {
|
||||
setupTrace_v1()
|
||||
}
|
||||
if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
sqlite3_trace_v2(
|
||||
sqliteConnection,
|
||||
UInt32(SQLITE_TRACE_STMT),
|
||||
{ (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in
|
||||
Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql)
|
||||
},
|
||||
dbPointer)
|
||||
} else {
|
||||
setupTrace_v1()
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -265,7 +261,7 @@ extension Database {
|
||||
private func setupTrace_v1() {
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
|
||||
guard let sql = sql.map({ String(cString: $0) }) else { return }
|
||||
guard let sql = sql.map(String.init) else { return }
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
|
||||
db.configuration.trace!(sql)
|
||||
}, dbPointer)
|
||||
@@ -289,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 {
|
||||
@@ -324,7 +328,7 @@ extension Database {
|
||||
add(function: .lowercase)
|
||||
add(function: .uppercase)
|
||||
|
||||
if #available(OSX 10.11, watchOS 3.0, *) {
|
||||
if #available(iOS 9.0, OSX 10.11, watchOS 3.0, *) {
|
||||
add(function: .localizedCapitalize)
|
||||
add(function: .localizedLowercase)
|
||||
add(function: .localizedUppercase)
|
||||
@@ -339,6 +343,29 @@ extension Database {
|
||||
add(collation: .localizedStandardCompare)
|
||||
}
|
||||
|
||||
private func setupAuthorizer() {
|
||||
// SQLite authorizer is set only once per database connection.
|
||||
//
|
||||
// This is because authorizer changes have SQLite invalidate statements,
|
||||
// with undesired side effects. See:
|
||||
//
|
||||
// - DatabaseCursorTests.testIssue583()
|
||||
// - http://sqlite.1065341.n5.nabble.com/Issue-report-sqlite3-set-authorizer-triggers-error-4-516-SQLITE-ABORT-ROLLBACK-during-statement-itern-td107972.html
|
||||
// swiftlint:disable:previous line_length
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
sqlite3_set_authorizer(
|
||||
sqliteConnection,
|
||||
{ (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer.unsafelyUnwrapped).takeUnretainedValue()
|
||||
guard let authorizer = db._authorizer else {
|
||||
return SQLITE_OK
|
||||
}
|
||||
return authorizer.authorize(actionCode, cString1, cString2, cString3, cString4)
|
||||
},
|
||||
dbPointer)
|
||||
}
|
||||
|
||||
|
||||
private func activateExtendedCodes() throws {
|
||||
let code = sqlite3_extended_result_codes(sqliteConnection, 1)
|
||||
guard code == SQLITE_OK else {
|
||||
@@ -362,22 +389,6 @@ extension Database {
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
private func setCipherPassphrase(_ 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)))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
private func validateFormat() throws {
|
||||
@@ -388,10 +399,7 @@ extension Database {
|
||||
// another passphrase.
|
||||
try makeSelectStatement(sql: "SELECT * FROM sqlite_master LIMIT 1").makeCursor().next()
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
|
||||
// MARK: - Database Closing
|
||||
|
||||
/// This method must be called before database deallocation
|
||||
@@ -408,47 +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(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
|
||||
@@ -463,10 +430,7 @@ extension Database {
|
||||
log(ResultCode(rawValue: code), "could not close database: \(message)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
@@ -489,10 +453,7 @@ extension Database {
|
||||
functions.remove(function)
|
||||
function.uninstall(in: self)
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// Add or redefine a collation.
|
||||
@@ -529,31 +490,242 @@ extension Database {
|
||||
SQLITE_UTF8,
|
||||
nil, nil, nil)
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Read-Only Access
|
||||
|
||||
func beginReadOnly() throws {
|
||||
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 {
|
||||
try internalCachedUpdateStatement(sql: "PRAGMA query_only = 0").execute()
|
||||
}
|
||||
}
|
||||
|
||||
/// Grants read-only access, starting SQLite 3.8.0
|
||||
func readOnly<T>(_ block: () throws -> T) rethrows -> T {
|
||||
if configuration.readonly {
|
||||
func readOnly<T>(_ block: () throws -> T) throws -> T {
|
||||
try beginReadOnly()
|
||||
return try throwingFirstError(
|
||||
execute: block,
|
||||
finally: endReadOnly)
|
||||
}
|
||||
|
||||
// MARK: - Authorizer
|
||||
|
||||
func withAuthorizer<T>(_ authorizer: StatementAuthorizer?, _ block: () throws -> T) rethrows -> T {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
let old = self._authorizer
|
||||
self._authorizer = authorizer
|
||||
defer { self._authorizer = old }
|
||||
return try block()
|
||||
}
|
||||
|
||||
// MARK: - Recording of the selected region
|
||||
|
||||
func recordingSelection<T>(_ region: inout DatabaseRegion, _ block: () throws -> T) rethrows -> T {
|
||||
if region.isFullDatabase {
|
||||
return try block()
|
||||
}
|
||||
|
||||
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
// Assume those pragmas never fail
|
||||
try! internalCachedUpdateStatement(sql: "PRAGMA query_only = 1").execute()
|
||||
defer { try! internalCachedUpdateStatement(sql: "PRAGMA query_only = 0").execute() }
|
||||
let oldFlag = self._isRecordingSelectedRegion
|
||||
let oldRegion = self._selectedRegion
|
||||
_isRecordingSelectedRegion = true
|
||||
_selectedRegion = DatabaseRegion()
|
||||
defer {
|
||||
region.formUnion(_selectedRegion)
|
||||
_isRecordingSelectedRegion = oldFlag
|
||||
if _isRecordingSelectedRegion {
|
||||
_selectedRegion = oldRegion.union(_selectedRegion)
|
||||
} else {
|
||||
_selectedRegion = oldRegion
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// 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 {
|
||||
@@ -580,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.
|
||||
@@ -589,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:
|
||||
@@ -608,7 +795,7 @@ extension Database {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if let firstError = firstError {
|
||||
throw firstError
|
||||
}
|
||||
@@ -640,9 +827,10 @@ 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
|
||||
// order to perform the special error handling of rollbacks (see
|
||||
// the rollback method).
|
||||
@@ -656,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.
|
||||
@@ -665,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
|
||||
@@ -714,7 +917,7 @@ extension Database {
|
||||
|
||||
/// Begins a database transaction and take a snapshot of the last committed
|
||||
/// database state.
|
||||
func beginSnapshotIsolation() throws {
|
||||
func beginSnapshotTransaction() throws {
|
||||
// https://www.sqlite.org/isolation.html
|
||||
//
|
||||
// > In WAL mode, SQLite exhibits "snapshot isolation". When a read
|
||||
@@ -802,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)
|
||||
@@ -814,10 +1016,7 @@ extension Database {
|
||||
try execute(sql: "COMMIT TRANSACTION")
|
||||
assert(!isInsideTransaction)
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
|
||||
// MARK: - Memory Management
|
||||
|
||||
func releaseMemory() {
|
||||
@@ -826,18 +1025,58 @@ 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, to dbDest: Database, afterBackupInit: (() -> ())? = nil, afterBackupStep: (() -> ())? = nil) throws {
|
||||
guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", dbFrom.sqliteConnection, "main") else {
|
||||
func backup(
|
||||
to dbDest: Database,
|
||||
afterBackupInit: (() -> Void)? = nil,
|
||||
afterBackupStep: (() -> Void)? = nil)
|
||||
throws
|
||||
{
|
||||
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 {
|
||||
throw DatabaseError(resultCode: .SQLITE_ERROR)
|
||||
throw DatabaseError()
|
||||
}
|
||||
|
||||
afterBackupInit?()
|
||||
@@ -872,35 +1111,49 @@ extension Database {
|
||||
}
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
extension Database {
|
||||
|
||||
// MARK: - Encryption
|
||||
|
||||
func change(passphrase: String) throws {
|
||||
// FIXME: sqlite3_rekey is discouraged.
|
||||
//
|
||||
// https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320
|
||||
//
|
||||
// > We (Zetetic) have been discouraging the use of sqlite3_rekey in
|
||||
// > favor of attaching a new database with the desired encryption
|
||||
// > options and using sqlcipher_export() to migrate the contents and
|
||||
// > schema of the original db into the new one:
|
||||
// > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/
|
||||
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)
|
||||
}
|
||||
extension Database {
|
||||
|
||||
// MARK: - Encryption
|
||||
|
||||
/// Sets the passphrase used to crypt and decrypt an SQLCipher database.
|
||||
///
|
||||
/// Call this method from Configuration.prepareDatabase, as in the example below:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase = { db in
|
||||
/// try db.usePassphrase("secret")
|
||||
/// }
|
||||
public func usePassphrase(_ passphrase: String) throws {
|
||||
let data = passphrase.data(using: .utf8)!
|
||||
let code = data.withUnsafeBytes {
|
||||
sqlite3_key(sqliteConnection, $0.baseAddress, Int32($0.count))
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Changes the passphrase used by an SQLCipher encrypted database.
|
||||
public func changePassphrase(_ passphrase: String) throws {
|
||||
// FIXME: sqlite3_rekey is discouraged.
|
||||
//
|
||||
// https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320
|
||||
//
|
||||
// > We (Zetetic) have been discouraging the use of sqlite3_rekey in
|
||||
// > favor of attaching a new database with the desired encryption
|
||||
// > options and using sqlcipher_export() to migrate the contents and
|
||||
// > schema of the original db into the new one:
|
||||
// > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/
|
||||
// swiftlint:disable:previous line_length
|
||||
let data = passphrase.data(using: .utf8)!
|
||||
let code = data.withUnsafeBytes {
|
||||
sqlite3_rekey(sqliteConnection, $0.baseAddress, Int32($0.count))
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: lastErrorMessage)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
extension Database {
|
||||
@@ -959,7 +1212,7 @@ extension Database {
|
||||
/// A built-in SQLite collation.
|
||||
///
|
||||
/// See https://www.sqlite.org/datatype3.html#collation
|
||||
public struct CollationName : RawRepresentable, Hashable {
|
||||
public struct CollationName: RawRepresentable, Hashable {
|
||||
/// :nodoc:
|
||||
public let rawValue: String
|
||||
|
||||
@@ -990,7 +1243,7 @@ extension Database {
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/datatype3.html
|
||||
public struct ColumnType : RawRepresentable, Hashable {
|
||||
public struct ColumnType: RawRepresentable, Hashable {
|
||||
/// :nodoc:
|
||||
public let rawValue: String
|
||||
|
||||
@@ -1031,7 +1284,7 @@ extension Database {
|
||||
/// An SQLite conflict resolution.
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_conflict.html.
|
||||
public enum ConflictResolution : String {
|
||||
public enum ConflictResolution: String {
|
||||
case rollback = "ROLLBACK"
|
||||
case abort = "ABORT"
|
||||
case fail = "FAIL"
|
||||
@@ -1042,7 +1295,7 @@ extension Database {
|
||||
/// A foreign key action.
|
||||
///
|
||||
/// See https://www.sqlite.org/foreignkeys.html
|
||||
public enum ForeignKeyAction : String {
|
||||
public enum ForeignKeyAction: String {
|
||||
case cascade = "CASCADE"
|
||||
case restrict = "RESTRICT"
|
||||
case setNull = "SET NULL"
|
||||
@@ -1059,7 +1312,7 @@ extension Database {
|
||||
}
|
||||
|
||||
/// An SQLite transaction kind. See https://www.sqlite.org/lang_transaction.html
|
||||
public enum TransactionKind : String {
|
||||
public enum TransactionKind: String {
|
||||
case deferred = "DEFERRED"
|
||||
case immediate = "IMMEDIATE"
|
||||
case exclusive = "EXCLUSIVE"
|
||||
|
||||
@@ -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 {
|
||||
@@ -27,8 +20,16 @@ public final class DatabaseCollation {
|
||||
self.name = name
|
||||
self.function = { (length1, buffer1, length2, buffer2) in
|
||||
// Buffers are not C strings: they do not end with \0.
|
||||
let string1 = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped), length: Int(length1), encoding: .utf8, freeWhenDone: false)!
|
||||
let string2 = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped), length: Int(length2), encoding: .utf8, freeWhenDone: false)!
|
||||
let string1 = String(
|
||||
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped),
|
||||
length: Int(length1),
|
||||
encoding: .utf8,
|
||||
freeWhenDone: false)!
|
||||
let string2 = String(
|
||||
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped),
|
||||
length: Int(length2),
|
||||
encoding: .utf8,
|
||||
freeWhenDone: false)!
|
||||
return function(string1, string2)
|
||||
}
|
||||
}
|
||||
@@ -50,6 +51,6 @@ extension DatabaseCollation: Hashable {
|
||||
/// :nodoc:
|
||||
public static func == (lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool {
|
||||
// See https://www.sqlite.org/c3ref/create_collation.html
|
||||
return sqlite3_stricmp(lhs.name, lhs.name) == 0
|
||||
return sqlite3_stricmp(lhs.name, rhs.name) == 0
|
||||
}
|
||||
}
|
||||