Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
d7d3f87921 | ||
|
|
3e7df8c774 | ||
|
|
db4598d881 | ||
|
|
60312f63d7 | ||
|
|
f54297d488 | ||
|
|
4368c529fa | ||
|
|
bf40e77d9c | ||
|
|
4ce4b2e0d1 | ||
|
|
a3c86e343b | ||
|
|
962ab13da9 | ||
|
|
4085050e96 | ||
|
|
a80a2571f6 | ||
|
|
2a43377079 | ||
|
|
2a0bd93795 | ||
|
|
05747a62ea | ||
|
|
e201dd21ac | ||
|
|
c04f3c7faa | ||
|
|
83409e3dec | ||
|
|
def9997698 | ||
|
|
bb7f4b2f86 | ||
|
|
ee703142ce | ||
|
|
324db50668 | ||
|
|
2e84e11bfa | ||
|
|
6062beb9f4 | ||
|
|
1d8c924c4e | ||
|
|
8b35343f3d | ||
|
|
35ead1d4c1 | ||
|
|
2c3e639f39 | ||
|
|
0f9fb9a3e0 | ||
|
|
567547a205 | ||
|
|
9a28c0ae03 | ||
|
|
82ccc121dd | ||
|
|
472063c7c1 | ||
|
|
f23e41a866 | ||
|
|
faae864699 | ||
|
|
d2b9137548 | ||
|
|
dec80ac300 | ||
|
|
b471488a83 | ||
|
|
21d2df9ade | ||
|
|
7461342089 | ||
|
|
e4498b2784 | ||
|
|
2734bd1266 | ||
|
|
77a677296b | ||
|
|
c90560fda9 | ||
|
|
f5be0e176d | ||
|
|
9691adc0bb | ||
|
|
b1c953c536 | ||
|
|
059ae19974 | ||
|
|
65c6360d0c | ||
|
|
25526472b3 | ||
|
|
a4a26e01e7 | ||
|
|
e163b91cf0 | ||
|
|
c19b3ad305 | ||
|
|
6628c09db7 | ||
|
|
7674f2f522 | ||
|
|
c841120d3b | ||
|
|
81476e58b8 | ||
|
|
69baff31ef | ||
|
|
6f6a8e3c3b | ||
|
|
403e5ab058 | ||
|
|
bc1e74a73e | ||
|
|
1fdd0bc428 | ||
|
|
940e9c3871 | ||
|
|
844fb3ca8b | ||
|
|
721fd52d12 | ||
|
|
85a86424c9 | ||
|
|
7d4306d383 | ||
|
|
96780419e9 | ||
|
|
332f42bba3 | ||
|
|
bab21d4c59 | ||
|
|
2c7b3e7667 | ||
|
|
30839bd19d | ||
|
|
304fdabd88 | ||
|
|
fde53b13c6 | ||
|
|
62557343a1 | ||
|
|
4b565ae262 | ||
|
|
64bcbde1ab | ||
|
|
76891a351d | ||
|
|
b29b5215b9 | ||
|
|
507d603a4e | ||
|
|
a38850ab00 | ||
|
|
6af4b180df | ||
|
|
8f3036b090 | ||
|
|
8fd4108463 | ||
|
|
40260c2316 | ||
|
|
7268085692 | ||
|
|
5f3b879efd | ||
|
|
5b15a88974 | ||
|
|
95c7c10f35 | ||
|
|
d5943962b3 | ||
|
|
ada6002c91 | ||
|
|
09afd2fadf | ||
|
|
4f17444a7e | ||
|
|
87b77768ec | ||
|
|
fe0198f453 | ||
|
|
ae6a224122 | ||
|
|
73773358c9 | ||
|
|
8e2a8fe9d8 | ||
|
|
a1b0baaca9 | ||
|
|
15dd4fc477 | ||
|
|
52add837e5 | ||
|
|
637c94b265 | ||
|
|
ca76032b8b | ||
|
|
35027a825f | ||
|
|
98a7f94248 | ||
|
|
cdcaaa4b77 | ||
|
|
d2c33715d0 | ||
|
|
5113d08ce3 | ||
|
|
cd53e0102b | ||
|
|
c95e9fafb1 | ||
|
|
1a368d30b0 | ||
|
|
ebd393f52a | ||
|
|
27cbe18c51 | ||
|
|
670bca00b0 | ||
|
|
2a85d89364 | ||
|
|
c5ac0ea941 | ||
|
|
d23f4c3ac7 | ||
|
|
604a51bb79 | ||
|
|
3786482368 | ||
|
|
f98502a136 | ||
|
|
7703741f25 | ||
|
|
5f36b43441 | ||
|
|
eb977e9391 | ||
|
|
ad1bdd7f01 | ||
|
|
c1ed3aa094 | ||
|
|
901015368c | ||
|
|
ae18041861 | ||
|
|
a6d348fc57 | ||
|
|
70b948b1c8 | ||
|
|
8038a9db05 | ||
|
|
3337e49f64 | ||
|
|
67ec70a117 | ||
|
|
c4be3e527d | ||
|
|
f5177a5612 | ||
|
|
d18c00231e | ||
|
|
644064aa08 | ||
|
|
881bb45fae | ||
|
|
46b7618f38 | ||
|
|
490a124cbf | ||
|
|
a7ea0913fa | ||
|
|
c0616c6a26 | ||
|
|
9fc5cda92b | ||
|
|
1c47f01e9a | ||
|
|
04ffc71dbb | ||
|
|
2634a0918d | ||
|
|
c7fed1c0b3 | ||
|
|
17e8df2d25 | ||
|
|
8786a60d31 | ||
|
|
acb7432610 | ||
|
|
560676a4bb | ||
|
|
a45065c340 | ||
|
|
bd0884503e | ||
|
|
f6b2c7e9f3 | ||
|
|
814ed0e4f1 | ||
|
|
5eff7755fe | ||
|
|
b1bcf637ab | ||
|
|
f199dc3cbe | ||
|
|
40b11f9f2f | ||
|
|
8f678c94cc | ||
|
|
171cdcb36e | ||
|
|
1dce152f95 | ||
|
|
90dd8d19bc | ||
|
|
efe89f000d | ||
|
|
590f6c2b2a | ||
|
|
623f2eaf43 | ||
|
|
8d759898d3 | ||
|
|
5fb6c40036 | ||
|
|
91ec3bada3 | ||
|
|
217b7eee9f | ||
|
|
f1522c09b5 | ||
|
|
b00271ad80 | ||
|
|
d7b4cf364d | ||
|
|
7ef5669710 | ||
|
|
73d622a074 | ||
|
|
ce782cecac | ||
|
|
a7431403a5 | ||
|
|
4b82656d3a | ||
|
|
2ca2f11883 | ||
|
|
1fbe7cfecf | ||
|
|
331938c647 | ||
|
|
995657108d | ||
|
|
f6a5279ac9 | ||
|
|
a88f20fb50 | ||
|
|
cfb1b2fc4d | ||
|
|
0e2daff329 | ||
|
|
18bd025e1c | ||
|
|
dd87a8d42c | ||
|
|
96c10f017e | ||
|
|
95ccb511db | ||
|
|
820db3f07d | ||
|
|
1317dc5db0 | ||
|
|
76971c44f6 | ||
|
|
708538bcf0 | ||
|
|
1e3de49251 | ||
|
|
73f4a9fb23 | ||
|
|
aec26c66be | ||
|
|
8fcabb5b73 | ||
|
|
9090c54c93 | ||
|
|
425debd0db | ||
|
|
f335005efd | ||
|
|
8084e83760 | ||
|
|
bdbcf682c4 | ||
|
|
29188a0606 | ||
|
|
fba553bbb9 | ||
|
|
2932b72200 | ||
|
|
e6bbdeab2c | ||
|
|
c37ccb6448 | ||
|
|
330005596a | ||
|
|
a336cf6ca4 | ||
|
|
801e8bb23c | ||
|
|
235ce0aba2 | ||
|
|
2a72d08334 | ||
|
|
6b04996290 | ||
|
|
d2b65d9fb8 | ||
|
|
1b9a1d3e30 | ||
|
|
5730dd5414 | ||
|
|
322039d490 | ||
|
|
c0c2a40c22 | ||
|
|
7d50825bff | ||
|
|
da55d09960 | ||
|
|
f9b0af5f7b | ||
|
|
d1fa479b31 | ||
|
|
6b3f2e844c | ||
|
|
9370036baf | ||
|
|
95274c57dd | ||
|
|
e55a5bd1d0 | ||
|
|
97173dea60 | ||
|
|
7e3e91ac99 | ||
|
|
1c1ee4e92a | ||
|
|
1e06ff24ec | ||
|
|
ba91a79798 | ||
|
|
3c977d7bf8 | ||
|
|
261e9481b2 | ||
|
|
1f50b4fefe | ||
|
|
cbb1b27830 | ||
|
|
bdf8d0bcd5 | ||
|
|
5af1686677 | ||
|
|
2711b9bb04 | ||
|
|
a172473e37 | ||
|
|
3f8047fc0e | ||
|
|
a12830050b | ||
|
|
21c0175a71 | ||
|
|
65fe2bb50c | ||
|
|
e3a0935914 | ||
|
|
693e6da773 | ||
|
|
4716f91d8b | ||
|
|
46791c8f74 | ||
|
|
1b3f0e8ece | ||
|
|
e2211aca21 | ||
|
|
235a612ce0 | ||
|
|
7070dedf1a | ||
|
|
20aecd5328 | ||
|
|
1af55653d3 | ||
|
|
9efc20fa51 | ||
|
|
f847be98f5 | ||
|
|
ff00dabcd1 | ||
|
|
72f00ccd9a | ||
|
|
5995f468e3 | ||
|
|
023afce21b | ||
|
|
9b24671043 | ||
|
|
088f6c92c7 | ||
|
|
207b90f1b5 | ||
|
|
dd139b6268 | ||
|
|
072fa2583a | ||
|
|
af1fd6b90c | ||
|
|
f9868bd8b5 | ||
|
|
00ae2de14e | ||
|
|
a6cbd242e6 | ||
|
|
be950162d0 | ||
|
|
db34d9537b | ||
|
|
1682df5c4e | ||
|
|
3ca7647110 | ||
|
|
2c4a449c5b | ||
|
|
49d92dc6ce | ||
|
|
d52fcbe0c9 | ||
|
|
5bf54dc5c9 | ||
|
|
0a814ee1e7 | ||
|
|
94316540de | ||
|
|
b67a53e645 | ||
|
|
a0f37c6e85 | ||
|
|
82dc51c554 | ||
|
|
6115078e95 | ||
|
|
8d35330e12 | ||
|
|
e0e07a7454 | ||
|
|
7a42bb42f5 | ||
|
|
212290bbf9 | ||
|
|
6f20d8b406 | ||
|
|
0561b7de5d | ||
|
|
9f41277bd4 | ||
|
|
9f4cad4134 | ||
|
|
bf012614bc | ||
|
|
aeeb59601a | ||
|
|
747a6352d6 | ||
|
|
325b376f4c | ||
|
|
dcc3db2730 | ||
|
|
29c1c5481c | ||
|
|
ebc7a9d8e0 | ||
|
|
99065a4faf | ||
|
|
26b8682e63 | ||
|
|
d41f6b4466 | ||
|
|
bfa5fbe8ce | ||
|
|
900134729a | ||
|
|
d888423676 | ||
|
|
eac38be34b | ||
|
|
f42a184401 | ||
|
|
5fbf56c373 | ||
|
|
784ebcc8e9 | ||
|
|
df84654554 | ||
|
|
53e513f1f8 | ||
|
|
0074adc023 | ||
|
|
ca8987ad98 | ||
|
|
6460f639ee | ||
|
|
41d93f546c | ||
|
|
80a642260f | ||
|
|
39800b1257 | ||
|
|
d04fc07337 | ||
|
|
11fd8d6b87 | ||
|
|
7183457217 | ||
|
|
cf4e512894 | ||
|
|
cf837855f2 | ||
|
|
916d3931aa | ||
|
|
9d9bbc5f5d | ||
|
|
153233ace4 | ||
|
|
4bae8e9ac5 | ||
|
|
1e617381a8 | ||
|
|
6d5215c8cb | ||
|
|
4ce6271f6d | ||
|
|
10c75d1e5e | ||
|
|
05258b1098 | ||
|
|
1a513e8e6e | ||
|
|
4ae1fb11cc | ||
|
|
9500a74744 | ||
|
|
973e82b139 | ||
|
|
d88fb4d96f | ||
|
|
cd6c4a4232 | ||
|
|
aeb41dc1eb | ||
|
|
d2b2e12a10 | ||
|
|
9040970c8d | ||
|
|
211ac7aada | ||
|
|
d60b68ab8a | ||
|
|
82423c41f2 | ||
|
|
2b460083af | ||
|
|
bad862ba16 | ||
|
|
adc4aa7c41 | ||
|
|
53d2e6b895 | ||
|
|
c46dbdd97e | ||
|
|
6543d75f6d | ||
|
|
32f6a45e8f | ||
|
|
519fa9a41a | ||
|
|
7d0b5cf03c | ||
|
|
35ffe9a9fd | ||
|
|
b063870739 | ||
|
|
8ca9839433 | ||
|
|
47f9b0f4a9 | ||
|
|
349ef328c7 | ||
|
|
8415e8c2a0 | ||
|
|
d4eb7ba27b | ||
|
|
090eea9923 | ||
|
|
d566838dc5 | ||
|
|
5bed0ac58e | ||
|
|
ee481b2327 | ||
|
|
8fbc3ca875 | ||
|
|
4aecad3649 | ||
|
|
cf128ac800 | ||
|
|
1a51eb6b52 | ||
|
|
a355b9eb03 | ||
|
|
a3c2cb7f1c | ||
|
|
4ba16067d0 | ||
|
|
605b6f7593 | ||
|
|
43fff32156 | ||
|
|
9f776a119f | ||
|
|
658c9d34cb | ||
|
|
2f447cc237 | ||
|
|
403c4a894f | ||
|
|
ccf339d6ef | ||
|
|
7ff21981f0 | ||
|
|
5d9fa76754 | ||
|
|
bd633e25ee | ||
|
|
87cd76a468 | ||
|
|
fca6420053 | ||
|
|
ec51f4dbdf | ||
|
|
916311a851 | ||
|
|
d6b6028e42 | ||
|
|
c756d27808 | ||
|
|
13985d0553 | ||
|
|
0363ca406d | ||
|
|
c20b7e5799 | ||
|
|
7642eb054b | ||
|
|
f3c68420a0 | ||
|
|
223ed4c73c | ||
|
|
99d010cded | ||
|
|
5bf1e6f818 | ||
|
|
06f0961b13 | ||
|
|
addfa45d3a | ||
|
|
6489c80846 | ||
|
|
9e8e00ff99 | ||
|
|
9ee25fdec1 | ||
|
|
4d5e5e1de3 | ||
|
|
1188969144 | ||
|
|
66c72e7bd2 | ||
|
|
eed30c0954 | ||
|
|
8dd9f5fd40 | ||
|
|
7cab5dbf2b | ||
|
|
6fd14d0a70 | ||
|
|
51c0b7a2f8 | ||
|
|
679f989e96 | ||
|
|
1a24f61723 | ||
|
|
1ff5552d5e | ||
|
|
4815807f09 | ||
|
|
8fc23e1771 | ||
|
|
5cf2d4920d | ||
|
|
3d6d1c89b2 | ||
|
|
08451dfced | ||
|
|
b506838519 | ||
|
|
1511981dc7 | ||
|
|
661cca9f80 | ||
|
|
4ee2523d59 | ||
|
|
997be18718 | ||
|
|
e966544aeb | ||
|
|
4935c6f258 | ||
|
|
03fafa437c | ||
|
|
0fe7db2694 | ||
|
|
22edb91796 | ||
|
|
5ffc35a955 | ||
|
|
1084fe0425 | ||
|
|
8d867320b0 | ||
|
|
34dd011e90 | ||
|
|
8fce4faeea | ||
|
|
8faff704d5 | ||
|
|
2d71679476 | ||
|
|
715b7a7867 | ||
|
|
8ef28b0683 | ||
|
|
31bdb2eeaa | ||
|
|
63192e2b75 | ||
|
|
fcbbe17909 | ||
|
|
a1e809cbc7 | ||
|
|
93b429cca4 | ||
|
|
3aaa5e74ec | ||
|
|
27156fd215 | ||
|
|
bcac197910 | ||
|
|
336081a78a | ||
|
|
6306bd31e3 | ||
|
|
690e980018 | ||
|
|
f9fbd42962 | ||
|
|
919f6095c6 | ||
|
|
83f62eed79 | ||
|
|
96b971b0da | ||
|
|
05fe018fed | ||
|
|
921c5d636a | ||
|
|
61ae460525 | ||
|
|
caaf2365e0 | ||
|
|
bed9164bcd | ||
|
|
f3621da329 | ||
|
|
2c75582c22 | ||
|
|
aa4f7c3d78 | ||
|
|
9906cf799c | ||
|
|
304937161c | ||
|
|
789497da75 | ||
|
|
14371cd7c6 | ||
|
|
b9dbce47a2 | ||
|
|
eb1672dec3 | ||
|
|
dd0926ebfb | ||
|
|
e80f3639af | ||
|
|
944b3ac07d | ||
|
|
746c22e950 | ||
|
|
a0c85f093c | ||
|
|
728c3b28ed | ||
|
|
03b8df2fe1 | ||
|
|
dae55e4105 | ||
|
|
f8a1ecb644 | ||
|
|
22c2cfb4ea | ||
|
|
b15eaa826b | ||
|
|
32b8d87a64 | ||
|
|
62ba97f517 | ||
|
|
e81a514f29 | ||
|
|
e36ca9f645 | ||
|
|
d9dc21a073 | ||
|
|
59cc1fef67 | ||
|
|
8df8129743 | ||
|
|
b6481e8a68 | ||
|
|
65b65f4d70 | ||
|
|
870ef6bac8 | ||
|
|
f7f0810c17 | ||
|
|
17c3ac1911 | ||
|
|
d74340a317 | ||
|
|
e54410b608 | ||
|
|
58dc1c67d6 | ||
|
|
7e9e50e52d | ||
|
|
df05e940e8 | ||
|
|
8d6a2fb4f1 | ||
|
|
afa8360397 | ||
|
|
50f8bcec34 | ||
|
|
d13968b753 | ||
|
|
086e3e918e | ||
|
|
e986f0d6e5 | ||
|
|
36ce78bd37 | ||
|
|
e2a11eeb05 | ||
|
|
2d40b86a50 | ||
|
|
4f350631ff | ||
|
|
db67d3840b | ||
|
|
2cd20b79f7 | ||
|
|
b296e9824a | ||
|
|
b0d9c519e1 | ||
|
|
6937193d28 | ||
|
|
500a5eea28 | ||
|
|
9758e1783e | ||
|
|
a57aa2e346 | ||
|
|
4bd5ace2ee | ||
|
|
85f618e16e | ||
|
|
e7995b9cd4 | ||
|
|
6e80c748d2 | ||
|
|
c546c578ce | ||
|
|
59162d93de | ||
|
|
354d22d70d | ||
|
|
f15b2e12d6 | ||
|
|
4ecef0ea11 | ||
|
|
637de8b6fa | ||
|
|
aa6f55d72f | ||
|
|
f018c7f823 | ||
|
|
98e2d009c6 | ||
|
|
09e85ba341 | ||
|
|
f27a1e9504 | ||
|
|
86409687a4 | ||
|
|
ff439c2dbc | ||
|
|
9b6c9b421a | ||
|
|
b5bcdd9df4 | ||
|
|
b36cf84b23 | ||
|
|
fb89b540cd | ||
|
|
86b8c35c04 | ||
|
|
e7497e707e | ||
|
|
b7089bb025 | ||
|
|
612bd70710 | ||
|
|
8affc8abe4 | ||
|
|
d9cf760a25 | ||
|
|
5b6d882d67 | ||
|
|
87ee00c2c5 | ||
|
|
e100287bd8 | ||
|
|
323b8de3dc | ||
|
|
06ec4580be | ||
|
|
efd69a628a | ||
|
|
cc80daec99 | ||
|
|
fd398aa434 | ||
|
|
4b8ea08f4f | ||
|
|
e57cf49dc4 | ||
|
|
111dcbcad4 | ||
|
|
4174896225 | ||
|
|
5738edc1bb | ||
|
|
192bd71c12 | ||
|
|
5ee3b9c878 | ||
|
|
d3020dbd8f | ||
|
|
493575a47b | ||
|
|
fa4febfa93 | ||
|
|
8cd49082ec | ||
|
|
0dbfe7d9e3 | ||
|
|
bbc64e38c7 | ||
|
|
d7188f4b93 | ||
|
|
bb045235bf | ||
|
|
ca4879c496 | ||
|
|
a466a8b253 | ||
|
|
5cd66c1be8 | ||
|
|
4489106bd6 | ||
|
|
485d42373b | ||
|
|
249484a21f | ||
|
|
fb8946254d | ||
|
|
b8a2592737 | ||
|
|
3029949731 | ||
|
|
91061ee669 | ||
|
|
90a9aa3523 | ||
|
|
ad04ccc094 | ||
|
|
a230fe400d | ||
|
|
62ef344a6c | ||
|
|
3eb36768c6 | ||
|
|
b6f79f176c | ||
|
|
e2d151e748 | ||
|
|
54ddd3e025 | ||
|
|
2d7857f45b | ||
|
|
81892491f2 | ||
|
|
0493a9646f | ||
|
|
e99823dbcc | ||
|
|
a1c99425cc | ||
|
|
dc6db13134 | ||
|
|
699c63e913 | ||
|
|
e924587236 | ||
|
|
c776801c4a | ||
|
|
73782d5e9d | ||
|
|
659171902e | ||
|
|
4a209fcbc4 | ||
|
|
91b68ffa4f | ||
|
|
5ea914ce0a | ||
|
|
950fa607a1 | ||
|
|
c9ff5a53a1 | ||
|
|
f42d5f202d | ||
|
|
27c6390635 | ||
|
|
e62cfe086c | ||
|
|
40f6b351ea | ||
|
|
89dda44364 | ||
|
|
9addac6f54 | ||
|
|
5a942d7213 | ||
|
|
bb972a351a | ||
|
|
5f037c7e4e | ||
|
|
9d391badc0 | ||
|
|
f309a0c5f3 | ||
|
|
d9530433f2 | ||
|
|
20d067c826 | ||
|
|
1e7840f0e4 | ||
|
|
77fd2b8411 | ||
|
|
b180fc37bb | ||
|
|
4e4d591109 | ||
|
|
7745e92a1f | ||
|
|
b70de2033a | ||
|
|
134bc670ef | ||
|
|
d265e2d77b | ||
|
|
ac40b63262 | ||
|
|
bac9d8e425 | ||
|
|
bf0c9b5c27 | ||
|
|
f70d04c76a | ||
|
|
85aa899c7b | ||
|
|
19fa05aecc | ||
|
|
9c4a8fb0b2 | ||
|
|
e19f02b77e | ||
|
|
b34030fc39 | ||
|
|
40a5fb1195 | ||
|
|
d9dd880d6d | ||
|
|
c51b0ba862 | ||
|
|
197f922e7e | ||
|
|
25f6bd9673 | ||
|
|
909821f4e5 | ||
|
|
b211dc55c4 | ||
|
|
863a762eca | ||
|
|
bb01da7635 | ||
|
|
558cdacb5b | ||
|
|
eff7dbd798 | ||
|
|
1d3935baaf | ||
|
|
b40e4e58e1 | ||
|
|
36d3607565 | ||
|
|
d55807e2a2 | ||
|
|
6447eeca17 | ||
|
|
1fea9c06e8 | ||
|
|
11d3dd9538 | ||
|
|
f6f236512b | ||
|
|
343816ed7b | ||
|
|
59a65bf81e | ||
|
|
a5b06b5cb0 | ||
|
|
802575c505 | ||
|
|
c433a130e5 | ||
|
|
ca4a867803 | ||
|
|
37ac126d26 | ||
|
|
5badd62515 | ||
|
|
37983b8581 | ||
|
|
815a3697da | ||
|
|
32acfb2cf4 | ||
|
|
9fd802b3ea | ||
|
|
21d243fc33 | ||
|
|
97936c3fad | ||
|
|
03934041c2 | ||
|
|
862563fdaa | ||
|
|
73935dfa9d | ||
|
|
9a3e6f0b97 | ||
|
|
bc5899543f | ||
|
|
fd79a53a96 | ||
|
|
194624212e | ||
|
|
1472385242 | ||
|
|
78bb086f69 | ||
|
|
e3681fdde5 | ||
|
|
6ec4556c2c | ||
|
|
1e72731c07 | ||
|
|
82329c899e | ||
|
|
8ab6e67f07 | ||
|
|
643bbc7076 | ||
|
|
61f2544afe | ||
|
|
546289bc88 | ||
|
|
d3d5b1d24c | ||
|
|
dd59186887 | ||
|
|
88d7c58522 | ||
|
|
c711ca1e8f | ||
|
|
56d49dd385 | ||
|
|
7b97d75a80 | ||
|
|
a8d9f2d82b | ||
|
|
c7d28de386 | ||
|
|
ce61d27a9e | ||
|
|
b8e3994858 | ||
|
|
7c6c615969 | ||
|
|
8c543f5078 | ||
|
|
3884141fc2 | ||
|
|
2c3776d372 | ||
|
|
c1d8dcb105 | ||
|
|
c89540683f | ||
|
|
3687e11958 | ||
|
|
90c588a9f5 | ||
|
|
838d9204ab | ||
|
|
2488007b9c | ||
|
|
5b3412e9f7 | ||
|
|
f07eee3ca7 | ||
|
|
769b247da9 | ||
|
|
ef54efcb75 | ||
|
|
f41112c071 | ||
|
|
e8ad816de5 | ||
|
|
32f1a7ae0f | ||
|
|
3dcae6d409 | ||
|
|
550c016a98 | ||
|
|
e092e8b3ec | ||
|
|
1b53bf9ea2 | ||
|
|
3f001ba04d | ||
|
|
87c4775421 | ||
|
|
2e3f2f9d61 | ||
|
|
798b727d7f | ||
|
|
54361617fe | ||
|
|
417b830b61 | ||
|
|
b757a44a77 | ||
|
|
6b78be51e2 | ||
|
|
466140e699 | ||
|
|
4e1eea5743 | ||
|
|
267b4f958d | ||
|
|
9c71061629 | ||
|
|
40ba0a7e8f | ||
|
|
bf6a101338 | ||
|
|
736db6a546 | ||
|
|
6a10ad0e11 | ||
|
|
a521c89962 | ||
|
|
b155ab742a | ||
|
|
4376e7519f | ||
|
|
42f13a621a | ||
|
|
8a9ccccf93 | ||
|
|
e3a8bfda6f | ||
|
|
a5c291e7a8 | ||
|
|
71b75ee265 | ||
|
|
3f1db5aa10 | ||
|
|
5ff519afcb | ||
|
|
41d814b540 | ||
|
|
326ef19fe9 | ||
|
|
796644edda | ||
|
|
03b51ee899 | ||
|
|
a2af4fb99a | ||
|
|
e95119130c | ||
|
|
9735d8b74e | ||
|
|
f4c0eaa912 | ||
|
|
d6e7d74a12 | ||
|
|
771c85581c | ||
|
|
1baca23500 | ||
|
|
cc2a2a3545 | ||
|
|
72a2408fce | ||
|
|
0cd1ca11ef | ||
|
|
c04e6ad86d | ||
|
|
3e67a1a021 | ||
|
|
a3e62d8734 | ||
|
|
f5bfb9df95 | ||
|
|
d45ed56b64 | ||
|
|
59175a6b4d | ||
|
|
f4e77c7700 | ||
|
|
cbc3467e2d | ||
|
|
65cc0bb2b3 | ||
|
|
7e548aee13 | ||
|
|
8d18b06e5d | ||
|
|
55c8d350b8 | ||
|
|
064f1005e5 | ||
|
|
53adad16e5 | ||
|
|
466a1ad4d5 | ||
|
|
f80f59cc38 | ||
|
|
ead2b13362 | ||
|
|
0ea9a1ce0d | ||
|
|
3b7801efff | ||
|
|
5efbbe9f0c | ||
|
|
d868b7e1ce | ||
|
|
60358ba0c0 | ||
|
|
b6eb5ab399 | ||
|
|
b9ab74cb1d | ||
|
|
d3fd838c6c | ||
|
|
1108ba4bf2 | ||
|
|
49de0e0f49 | ||
|
|
d56b62a65f | ||
|
|
c28a4d4061 | ||
|
|
3971b43894 | ||
|
|
9fc5c2680b | ||
|
|
0f8156afed | ||
|
|
da3f14c29a | ||
|
|
dbacf3acf0 | ||
|
|
961138b09b | ||
|
|
6c6e46b8d6 | ||
|
|
0cbf259ed1 | ||
|
|
07bf5882fe | ||
|
|
b3c7fec676 | ||
|
|
296a1d5b12 | ||
|
|
8c5e3df546 | ||
|
|
50213c925f | ||
|
|
a1a5165bd2 | ||
|
|
7d9e87088d | ||
|
|
c300cf2a38 | ||
|
|
c48d2e484a | ||
|
|
2bc8f33249 | ||
|
|
257fc8b66a | ||
|
|
bc274a603c | ||
|
|
ab7970d470 | ||
|
|
087a899f13 | ||
|
|
842eaf0816 | ||
|
|
f7b79e05f6 | ||
|
|
1867ee91de | ||
|
|
d53412d404 | ||
|
|
74ca85e52c | ||
|
|
51942046b9 | ||
|
|
38e1cc9a27 | ||
|
|
7e8ebed7a8 | ||
|
|
eb95562b73 | ||
|
|
44af4e62a6 | ||
|
|
30363b4a5b | ||
|
|
bb02d9d857 | ||
|
|
9babbcbcb3 | ||
|
|
04de6193c0 | ||
|
|
6fa72ebea1 | ||
|
|
0e51a0ff65 | ||
|
|
a276a49a26 | ||
|
|
741f0b2a43 | ||
|
|
3d21773496 | ||
|
|
cca716e1ab | ||
|
|
8e13cb4e6c | ||
|
|
c4d328783f | ||
|
|
22b5990669 | ||
|
|
d3838d1d73 | ||
|
|
cdd7579104 | ||
|
|
4e3b7c14a9 | ||
|
|
b4b824c360 | ||
|
|
6f86cbf0c4 | ||
|
|
f68b1cd2c3 | ||
|
|
53f98a7bf6 | ||
|
|
77de519fcc | ||
|
|
739c325079 | ||
|
|
10650704b5 | ||
|
|
735394669d | ||
|
|
4e40d755f4 | ||
|
|
e5f43e341b | ||
|
|
72c5769e8b | ||
|
|
669b9c4e91 | ||
|
|
a489959780 | ||
|
|
1985b9129a | ||
|
|
f7712473aa | ||
|
|
f582683f20 | ||
|
|
a4b35729df | ||
|
|
191607fc13 | ||
|
|
5a540e8850 | ||
|
|
f59dba711c | ||
|
|
93326307fa | ||
|
|
8d6ec6297a | ||
|
|
1d47853abe | ||
|
|
38e4027599 | ||
|
|
29b54dd37d | ||
|
|
03d2bc43ac | ||
|
|
22ed0fb1a1 | ||
|
|
489454b0d4 | ||
|
|
840f8358b5 | ||
|
|
470e1534dc | ||
|
|
158177364b | ||
|
|
de2823b613 | ||
|
|
0d5adfe5a9 | ||
|
|
0010be4e56 | ||
|
|
62f6cfe6b5 | ||
|
|
31e6ddeac3 | ||
|
|
f2c3c213cc | ||
|
|
f303664808 | ||
|
|
471808fa3b | ||
|
|
cbe505f4a4 | ||
|
|
087989fc89 | ||
|
|
a519a4ab86 | ||
|
|
627e8ec969 | ||
|
|
2b78479a5e | ||
|
|
e0a9cced4a | ||
|
|
26ba5768b2 | ||
|
|
09581c6ae0 | ||
|
|
fc3aca792f | ||
|
|
a043c4c29e | ||
|
|
ec5451ee70 | ||
|
|
7c4462641e | ||
|
|
82efe7ca23 | ||
|
|
052d2e3008 | ||
|
|
de227bdce1 | ||
|
|
697b2af61d | ||
|
|
ff4f6f3b12 | ||
|
|
31b688d801 | ||
|
|
f694437f5b | ||
|
|
69853d7901 | ||
|
|
abe6957c85 | ||
|
|
08b103f5f5 | ||
|
|
9c71356e3d | ||
|
|
2341523c41 | ||
|
|
0df4815086 | ||
|
|
fe0f238f32 | ||
|
|
fda04a105d | ||
|
|
e5d97c15ad | ||
|
|
ce95ff7278 | ||
|
|
33927e7f4d | ||
|
|
6a4d9fb8fc | ||
|
|
cf33d78f49 | ||
|
|
0d89aa911b | ||
|
|
d521a99d87 | ||
|
|
a848d864ce | ||
|
|
759c1088a1 | ||
|
|
2d004a1a26 | ||
|
|
35e1de495e | ||
|
|
697709c82f | ||
|
|
9ad476235d | ||
|
|
dadc5c3c58 | ||
|
|
3be3a51cdc | ||
|
|
7bdbfb77dd | ||
|
|
8e0c01ef70 | ||
|
|
1c5cecf568 | ||
|
|
9330468f92 | ||
|
|
fcbea047cc | ||
|
|
619b73ea76 | ||
|
|
597d745e37 | ||
|
|
52ffb4a02c | ||
|
|
c007c04afb | ||
|
|
4b92968912 | ||
|
|
2938a95270 | ||
|
|
5b2e9cdaa5 | ||
|
|
5736cd2740 | ||
|
|
6b05617d8d | ||
|
|
58470fa959 | ||
|
|
43c04268ee | ||
|
|
3ba8d7ae60 | ||
|
|
97c22cde40 | ||
|
|
8a983274af | ||
|
|
445ec18d6e | ||
|
|
a441b1d24d | ||
|
|
23743680d2 | ||
|
|
afaabfe872 | ||
|
|
53114ea491 | ||
|
|
12745b2882 | ||
|
|
19291e2501 | ||
|
|
3890d2659f | ||
|
|
68a8592bcd | ||
|
|
445187c276 | ||
|
|
55707e67d4 | ||
|
|
82435db722 | ||
|
|
a47a0c9d2d | ||
|
|
5a24726cf1 | ||
|
|
7ecacaaccc | ||
|
|
704da35576 | ||
|
|
2774aaf292 | ||
|
|
8ffeb28b02 | ||
|
|
5f92209c59 | ||
|
|
4f8e97a07c | ||
|
|
39bc140dc8 | ||
|
|
0838d5903e | ||
|
|
a0cd603c61 | ||
|
|
3ef8083043 | ||
|
|
35ed13c940 | ||
|
|
1da41c7fe5 | ||
|
|
01069ee998 | ||
|
|
ebbf858da4 | ||
|
|
047a95f2c9 | ||
|
|
7508811e40 | ||
|
|
2ae8e236c0 | ||
|
|
a13903e7a1 | ||
|
|
c25bc1d5fa | ||
|
|
d004372b63 | ||
|
|
789248e369 | ||
|
|
3404cc574b | ||
|
|
2ca049c2e4 | ||
|
|
89054c8165 | ||
|
|
24e8ee2d00 | ||
|
|
f69c79bc1a | ||
|
|
82765aba1d | ||
|
|
bcc177ff7d | ||
|
|
3bfef630f9 | ||
|
|
6a6d58da6c | ||
|
|
6e7065de36 | ||
|
|
f60152ed2e | ||
|
|
f6b0c0cc65 | ||
|
|
c16b2bcb57 | ||
|
|
5d70ef93c8 | ||
|
|
68d76eca01 | ||
|
|
83453e1b11 | ||
|
|
903694d095 | ||
|
|
168d2850ab | ||
|
|
fc692bdb8a | ||
|
|
d963e688be | ||
|
|
6157ab0583 | ||
|
|
ad61c72988 | ||
|
|
dd4b651938 | ||
|
|
7cd50872cf | ||
|
|
fc5e92954b | ||
|
|
6c7ac25fb8 | ||
|
|
86cff20f99 | ||
|
|
7a628bf23f | ||
|
|
9e8d08f579 | ||
|
|
8c3606fe4b | ||
|
|
01c9e9e1e1 | ||
|
|
ff28c02f21 | ||
|
|
1426c7fd38 | ||
|
|
366460bc62 | ||
|
|
16c62999fa | ||
|
|
2cd3a7e0c9 | ||
|
|
9958e7b96c | ||
|
|
8319c70315 | ||
|
|
45ff5f2fa1 | ||
|
|
df51d2887a | ||
|
|
9c37237f7b | ||
|
|
6ecb7a40d0 | ||
|
|
52ec6c6cd2 | ||
|
|
ba11d7be66 | ||
|
|
4c58fd5111 | ||
|
|
4bde81db4f | ||
|
|
37a9999b35 | ||
|
|
33b40637a8 | ||
|
|
e7fd075936 | ||
|
|
cc4a9fa2e2 | ||
|
|
56f3bdc390 | ||
|
|
ba5537692f | ||
|
|
5595046341 | ||
|
|
ad844f6ba5 | ||
|
|
baf8dbc881 | ||
|
|
ad672395de | ||
|
|
923fab769f | ||
|
|
4e3dc03422 | ||
|
|
d96212ca59 | ||
|
|
d16022a33a | ||
|
|
5cb22125aa | ||
|
|
6ee77df2dd | ||
|
|
ea54b06e28 | ||
|
|
6b33c08b26 | ||
|
|
cb16bf549f | ||
|
|
9a8b60a8a7 | ||
|
|
dec965d610 | ||
|
|
adf3e65971 | ||
|
|
c437e4a2ef | ||
|
|
4dd9d2e1fe | ||
|
|
185c3cbbf9 | ||
|
|
ffbf4d2c87 | ||
|
|
464cd0db7d | ||
|
|
e2e00f9b40 | ||
|
|
2c2c75b0f4 | ||
|
|
8ef7547c8e | ||
|
|
d82daaa398 | ||
|
|
a5a8b2ac40 | ||
|
|
bdcbee37f4 | ||
|
|
70508f5daa | ||
|
|
3c44180c47 | ||
|
|
3d179acc00 | ||
|
|
dd9ca2317c | ||
|
|
c71d4903a0 | ||
|
|
d118a775ac | ||
|
|
e92c0c9aed | ||
|
|
b826789349 | ||
|
|
a09099bb02 | ||
|
|
914781cd7f | ||
|
|
de84b084ec | ||
|
|
2b6e69404e | ||
|
|
aaca651a2e | ||
|
|
138289b646 | ||
|
|
d4157db4b1 | ||
|
|
3bf32564a4 | ||
|
|
7186cd98c8 | ||
|
|
b9a878bb20 | ||
|
|
8c479a863a | ||
|
|
58a48b73ae | ||
|
|
2e6ed9d8f9 | ||
|
|
df406341c1 | ||
|
|
41629ec9aa | ||
|
|
47b42f38e3 | ||
|
|
21209fb107 | ||
|
|
106812c02c | ||
|
|
da58e228c0 | ||
|
|
9bfe893908 | ||
|
|
03a781075e | ||
|
|
60afc9ee06 | ||
|
|
22165984c3 | ||
|
|
eebb013d06 | ||
|
|
0e0ebdb2d6 | ||
|
|
be15f89e28 | ||
|
|
5d2f063c93 | ||
|
|
e49c190288 | ||
|
|
d3ddf1c1bc | ||
|
|
04fc14d557 | ||
|
|
603115c9a4 | ||
|
|
6b60fbe50e | ||
|
|
2a43869e45 | ||
|
|
bd52dbcec0 | ||
|
|
c9dace3089 | ||
|
|
9184cbe324 | ||
|
|
2216573acb | ||
|
|
2b331e3c03 | ||
|
|
875e7779c3 | ||
|
|
743a56e0e4 | ||
|
|
6e1ef92a38 | ||
|
|
e3ca4e42a3 | ||
|
|
6db4c38c74 | ||
|
|
8a16f0ba42 | ||
|
|
81cd30bb38 | ||
|
|
d26145e59e | ||
|
|
2b664d5485 | ||
|
|
27f8103e79 | ||
|
|
a5c2c618e4 | ||
|
|
9d4a083193 | ||
|
|
9d00f63358 | ||
|
|
0ae85eed24 | ||
|
|
41050094af | ||
|
|
7d339edd6e | ||
|
|
23d7d3f8ed | ||
|
|
7bd9703540 | ||
|
|
8a6e7b70ef | ||
|
|
5a8c3cdafc | ||
|
|
16a1cecc57 | ||
|
|
e367d55940 | ||
|
|
b45b6cd0cf | ||
|
|
c2535d19e9 | ||
|
|
fa4ca12903 | ||
|
|
c5444fa99d | ||
|
|
468eaf8642 | ||
|
|
d9d0f62f71 | ||
|
|
8b4eb55568 | ||
|
|
132ba89427 | ||
|
|
1c26b7748e | ||
|
|
3354b22cd0 | ||
|
|
e5cd3a8994 | ||
|
|
1c09a3d31f | ||
|
|
83c257822b | ||
|
|
e82c92a002 | ||
|
|
d58586a18e | ||
|
|
066889e0d7 | ||
|
|
ff595eeaef | ||
|
|
80956ee2c7 | ||
|
|
95ef76e839 | ||
|
|
bcdf9d8c58 | ||
|
|
c44a1518cc | ||
|
|
8056a0e3c9 | ||
|
|
47275d0bf0 | ||
|
|
af8e17c753 | ||
|
|
6b6f80b818 | ||
|
|
eaf25161a5 | ||
|
|
870d6e6966 | ||
|
|
cd2697e34b | ||
|
|
2083c3b41c | ||
|
|
d65d547b23 | ||
|
|
0593832d10 | ||
|
|
056db7ff6f | ||
|
|
3c01f0f1c0 | ||
|
|
05dc1a5bea | ||
|
|
2174beb396 | ||
|
|
d9989fc442 | ||
|
|
566f42e8d0 | ||
|
|
f159927724 | ||
|
|
21b8690e07 | ||
|
|
bb91a7ca0b | ||
|
|
5819419f3b | ||
|
|
2c59f838aa | ||
|
|
cbbc12adc0 | ||
|
|
d4d0aed3ae | ||
|
|
588d7ac4ca | ||
|
|
ab98081e7b | ||
|
|
a8a3ec8259 | ||
|
|
4fcc1f81d5 | ||
|
|
4572e493e6 | ||
|
|
1928c84b80 | ||
|
|
b4d99dc738 | ||
|
|
8abf815045 | ||
|
|
7610eebb3f | ||
|
|
c43800f40d | ||
|
|
a511772562 | ||
|
|
e916f577f1 | ||
|
|
da14fd2f87 | ||
|
|
052e615de0 | ||
|
|
5a2f713775 | ||
|
|
ae66563654 | ||
|
|
26df5aa516 | ||
|
|
d3a9667f10 | ||
|
|
adf5695c20 | ||
|
|
aa8cb60fad | ||
|
|
65d99879a8 | ||
|
|
b14f1b9fdc | ||
|
|
46511e507e | ||
|
|
8f5eee0130 | ||
|
|
7f8d59b7b1 | ||
|
|
0932e92fb4 | ||
|
|
5a8381b282 | ||
|
|
8493984949 | ||
|
|
a386fb6580 | ||
|
|
baee699591 | ||
|
|
ad11affd21 | ||
|
|
209b3d0d37 | ||
|
|
edca38470e | ||
|
|
e9b76bb196 | ||
|
|
f70e9b3e39 | ||
|
|
13f3e5ec0d | ||
|
|
fb209d8805 | ||
|
|
c6b1872291 | ||
|
|
8fa405452d | ||
|
|
34c7b0b40c | ||
|
|
f583ef0d2a | ||
|
|
e438d580b4 | ||
|
|
2c9a4b6968 | ||
|
|
ba984427a4 | ||
|
|
1e34128213 | ||
|
|
319ac27b15 | ||
|
|
8ea13dc5fd | ||
|
|
ad6f1f4a37 | ||
|
|
063fe70766 | ||
|
|
1c9ce6781b | ||
|
|
81e777a323 | ||
|
|
b7273e0a7e | ||
|
|
bb90ea0259 | ||
|
|
f925d7e3d4 | ||
|
|
bbf7eb0b73 | ||
|
|
140c590c49 | ||
|
|
ff306c21e2 | ||
|
|
d1892c649c | ||
|
|
f5d0e4db12 | ||
|
|
fc914470f5 | ||
|
|
d03b76b7e7 | ||
|
|
d45afb921a | ||
|
|
e1f80494a8 | ||
|
|
982dee5b77 | ||
|
|
9815b310b6 | ||
|
|
7bb0718bae | ||
|
|
da60a5004e | ||
|
|
8af33c4fc9 | ||
|
|
1fba575c18 | ||
|
|
1e25debefc | ||
|
|
97d77e871b | ||
|
|
7cb58cfffc | ||
|
|
950940dedf | ||
|
|
c32af15fdd | ||
|
|
3d285dfc81 | ||
|
|
76d3ac42ff | ||
|
|
e9b7a67c73 | ||
|
|
ba7cd4f61d | ||
|
|
7a3321a5ed | ||
|
|
5cb9d19b1e | ||
|
|
9e3da1a1a9 | ||
|
|
35e202eb13 | ||
|
|
812975ee7d | ||
|
|
934ee8e5f4 | ||
|
|
47c424cb69 | ||
|
|
b35fb6e315 | ||
|
|
fdc191bbb4 | ||
|
|
a8ec0530b1 | ||
|
|
b7b8594176 | ||
|
|
eee433fefe | ||
|
|
513a5a3fb7 | ||
|
|
1a3638c0ef | ||
|
|
ef123824c3 | ||
|
|
2bc56255b2 | ||
|
|
a94711ad77 | ||
|
|
0ab84aff52 | ||
|
|
e415db248a | ||
|
|
c3a15bc2fc | ||
|
|
7a18b7c948 | ||
|
|
df1f9b92a1 | ||
|
|
4110f890da | ||
|
|
44061f0d31 | ||
|
|
7be6386689 | ||
|
|
4d7d5e8429 | ||
|
|
b933917f34 | ||
|
|
d7f7a57129 | ||
|
|
d5008283d4 | ||
|
|
e51f27403d | ||
|
|
e5b2710151 | ||
|
|
bdca768900 | ||
|
|
b9b7ab2902 | ||
|
|
30bc15afb6 | ||
|
|
7ea15dcce2 | ||
|
|
44b998c08f | ||
|
|
2b8c8389fe | ||
|
|
dfb9421bd7 | ||
|
|
02db2a8dc6 | ||
|
|
9bb4ff86f1 | ||
|
|
2eb0955420 | ||
|
|
659db4fdd9 | ||
|
|
d00421abe0 | ||
|
|
4d343e893e | ||
|
|
eba21d3371 | ||
|
|
b47f5864ac | ||
|
|
e8dacb31cc | ||
|
|
0b77d0d745 | ||
|
|
de4f57c2aa | ||
|
|
2d6140a805 | ||
|
|
b2234b46a2 | ||
|
|
358225b462 | ||
|
|
820673b78b | ||
|
|
1c66ad4aad | ||
|
|
5f41c57c45 | ||
|
|
0cdc7d81d4 | ||
|
|
942b32e5d5 | ||
|
|
aa8bc0fae3 | ||
|
|
275098084d | ||
|
|
05fda18a56 | ||
|
|
4b7f17dbfa | ||
|
|
c52b59f1bc | ||
|
|
76f5adf944 | ||
|
|
d81475adc4 | ||
|
|
a08974ffa4 | ||
|
|
8c06e7bff5 | ||
|
|
7f16e357d0 | ||
|
|
6262d10794 | ||
|
|
d9dd293d7f | ||
|
|
e49e2db571 | ||
|
|
7da5ff95a0 | ||
|
|
8eee52dad5 | ||
|
|
9bc68cd10e | ||
|
|
e415a93d7e | ||
|
|
46bba98f0f | ||
|
|
6a21e97a12 | ||
|
|
1ae8e39dab | ||
|
|
b99b14eb4d | ||
|
|
5579dd651a | ||
|
|
66541922a4 | ||
|
|
80fe7f87b1 | ||
|
|
bf5420de26 | ||
|
|
ef10e2e8ed | ||
|
|
1dcb42c540 | ||
|
|
897fd32725 | ||
|
|
e46902c845 | ||
|
|
d836fffd08 | ||
|
|
c480e07f08 | ||
|
|
9f2058f6d9 | ||
|
|
7d4ebce70a | ||
|
|
cbda1f9211 | ||
|
|
cef5d25228 | ||
|
|
220ce379e1 | ||
|
|
2826472c19 | ||
|
|
bcc45dc076 | ||
|
|
7def60c3c0 | ||
|
|
74aae3dd59 | ||
|
|
89d5bd7945 | ||
|
|
feeedcb92d | ||
|
|
78a6f7251b | ||
|
|
b307e907cb | ||
|
|
9f2ba7245b | ||
|
|
e9e1fa85c6 | ||
|
|
f8de01779c | ||
|
|
84c53ef6b9 | ||
|
|
a8f6ed6d61 | ||
|
|
1c811a61ca | ||
|
|
566dae0574 | ||
|
|
f0ec9925d2 | ||
|
|
481dc79c85 | ||
|
|
0b1a24184b | ||
|
|
b473d07b3c | ||
|
|
5538977911 | ||
|
|
9815b0b480 | ||
|
|
9ed01719b7 | ||
|
|
0e40b6bda2 | ||
|
|
dd18323a36 | ||
|
|
06e5dc5dfd | ||
|
|
b916bca1f6 | ||
|
|
4186d2e5c4 | ||
|
|
33a5decfdc | ||
|
|
2c35ca5ac7 | ||
|
|
4d2e230633 | ||
|
|
66d7f37643 | ||
|
|
fd00cd613e | ||
|
|
c5c4508bfe | ||
|
|
d21a9b90b2 | ||
|
|
0eeb72a89b | ||
|
|
1cd211bd89 | ||
|
|
1d04376493 | ||
|
|
fa396a2d86 | ||
|
|
06150b5e58 | ||
|
|
4f0b5eb7b9 | ||
|
|
79fd17faec | ||
|
|
59da551b66 | ||
|
|
89d95f6a7c | ||
|
|
1db18b818a | ||
|
|
37be51ec37 | ||
|
|
6fb5bb8ffd | ||
|
|
d82b539942 | ||
|
|
dc8406d732 | ||
|
|
328d1fcd30 | ||
|
|
d4590ff91f | ||
|
|
5bcc95ce87 |
No files matched your search
@@ -1,4 +1,5 @@
|
||||
source 'https://rubygems.org'
|
||||
|
||||
gem 'xcpretty'
|
||||
gem 'xcpretty-travis-formatter'
|
||||
gem 'xcpretty-travis-formatter'
|
||||
gem 'cocoapods', '~> 1.7'
|
||||
@@ -18,7 +18,7 @@ Please fill out this template when filing an issue.
|
||||
|
||||
### Environment
|
||||
|
||||
**GRDB flavor(s):** (GRDB, GRDBCipher, GRDBCustom?)
|
||||
**GRDB flavor(s):** (GRDB, SQLCipher, Custom SQLite build?)
|
||||
**GRDB version:**
|
||||
**Installation method:** (CocoaPods, SPM, manual?)
|
||||
**Xcode version:**
|
||||
|
||||
@@ -1,18 +1,12 @@
|
||||
<!-- Please describe your pull request here. -->
|
||||
|
||||
### One more thing…
|
||||
### Pull Request Checklist
|
||||
|
||||
<!--
|
||||
When relevant, please check as many checkboxes in this list as possible.
|
||||
|
||||
Documentation makes sure that you are not the only one who knows about the changes. Tests make sure your changes will be supported in the future.
|
||||
|
||||
Write documentation and tests if you can, because if nobody else has the time to do it, the pull request will simply be rejected.
|
||||
|
||||
Ask for help and guidance when needed.
|
||||
Please verify that your pull request checks those boxes:
|
||||
-->
|
||||
|
||||
- [ ] This pull request is submitted against the `develop` branch.
|
||||
- [ ] This pull request is submitted against the `development` branch.
|
||||
- [ ] Inline documentation has been updated.
|
||||
- [ ] README.md or another dedicated guide has been updated.
|
||||
- [ ] Changes are tested, for all flavors of GRDB, GRDBCipher, and GRDBCustomSQLite.
|
||||
- [ ] Updated CHANGELOG.md
|
||||
- [ ] Changes are tested.
|
||||
@@ -101,8 +101,8 @@ SQLiteCustom/GRDBCustomSQLite-USER.h
|
||||
SQLiteCustom/GRDBCustomSQLite-USER.xcconfig
|
||||
|
||||
# CocoaPods test
|
||||
Podfile.lock
|
||||
Pods
|
||||
Podfile.lock
|
||||
|
||||
# SPM
|
||||
.build
|
||||
|
||||
@@ -7,9 +7,6 @@
|
||||
[submodule "Tests/Performance/Realm"]
|
||||
path = Tests/Performance/Realm
|
||||
url = https://github.com/realm/realm-cocoa.git
|
||||
[submodule "SQLCipher/src"]
|
||||
path = SQLCipher/src
|
||||
url = https://github.com/groue/sqlcipher.git
|
||||
[submodule "SQLiteCustom/src"]
|
||||
path = SQLiteCustom/src
|
||||
url = https://github.com/swiftlyfalling/SQLiteLib
|
||||
url = https://github.com/swiftlyfalling/SQLiteLib.git
|
||||
@@ -1 +0,0 @@
|
||||
4.1
|
||||
@@ -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,9 +1,19 @@
|
||||
# The OS X Build Environment
|
||||
# https://docs.travis-ci.com/user/reference/osx/#Xcode-version
|
||||
# https://docs.travis-ci.com/user/reference/osx/#xcode-version
|
||||
|
||||
language: objective-c
|
||||
xcode_project: GRDB.xcodeproj
|
||||
|
||||
# Caches
|
||||
cache:
|
||||
- bundler
|
||||
- cocoapods
|
||||
|
||||
# Custom CocoaPods installation so that Podfile.lock is honored
|
||||
install:
|
||||
- bundle install
|
||||
- bundle exec pod repo update
|
||||
|
||||
# Disable the default Travis-CI submodule logic
|
||||
# The various make commands ensure that the appropriate submodules are retrieved
|
||||
git:
|
||||
@@ -13,145 +23,413 @@ jobs:
|
||||
include:
|
||||
|
||||
###########################################
|
||||
## Test GRDB
|
||||
|
||||
# Test GRDBOSX (Xcode 9.4)
|
||||
- stage: Test GRDB
|
||||
## Test GRDB Xcode 11
|
||||
|
||||
- stage: Test GRDB Xcode 11
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.4
|
||||
osx_image: xcode11
|
||||
env:
|
||||
- TID=GRDBOSX (Xcode 9.4, macOS)
|
||||
script: make test_framework_GRDBOSX
|
||||
|
||||
# Test GRDBWatchOS (Xcode 9.4)
|
||||
- stage: Test GRDB
|
||||
- TID=GRDBOSX (Swift 5.1, macOS)
|
||||
script: make test_framework_GRDBOSX_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 11
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.4
|
||||
osx_image: xcode11
|
||||
env:
|
||||
- TID=GRDBWatchOS (Xcode 9.4, watchOS)
|
||||
- TID=GRDBOSX (Swift 4.2, macOS)
|
||||
script: make test_framework_GRDBOSX_minSwift
|
||||
|
||||
- stage: Test GRDB Xcode 11
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
env:
|
||||
- TID=GRDBWatchOS (watchOS)
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
# Test GRDBiOS (Xcode 9.4, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB
|
||||
|
||||
- stage: Test GRDB Xcode 11
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.4
|
||||
osx_image: xcode11
|
||||
env:
|
||||
- TID=GRDBiOS (Xcode 9.4, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget
|
||||
|
||||
# Test GRDBiOS (Xcode 9.3, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB
|
||||
- TID=GRDBiOS (Swift 5.1, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 11
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.3
|
||||
osx_image: xcode11
|
||||
env:
|
||||
- TID=GRDBiOS (Xcode 9.3, iOS <MIN>)
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
# Test GRDB [SPM] (Xcode 9.4, macOS)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.4
|
||||
env:
|
||||
- TID=GRDB [SPM] (Xcode 9.4, macOS)
|
||||
script: make test_SPM
|
||||
|
||||
###########################################
|
||||
## Test GRDB (Custom SQLite)
|
||||
|
||||
# Test GRDBCustomSQLiteOSX (Xcode 9.4)
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.4
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteOSX (Xcode 9.4, macOS)
|
||||
script: make test_framework_GRDBCustomSQLiteOSX
|
||||
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 9.4, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.4
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 9.4, iOS <MAX>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget
|
||||
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 9.3, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.3
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 9.3, iOS <MIN>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
|
||||
|
||||
###########################################
|
||||
## Test GRDB (SQLCipher)
|
||||
|
||||
# Test GRDBCipherOSX (Xcode 9.4)
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.4
|
||||
env:
|
||||
- TID=GRDBCipherOSX (Xcode 9.4, macOS)
|
||||
script: make test_framework_GRDBCipherOSX
|
||||
|
||||
# Test GRDBCipheriOS (Xcode 9.4, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.4
|
||||
env:
|
||||
- TID=GRDBCipheriOS (Xcode 9.4, iOS <MAX>)
|
||||
script: make test_framework_GRDBCipheriOS_maxTarget
|
||||
|
||||
# Test GRDBCipheriOS (Xcode 9.3, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.3
|
||||
env:
|
||||
- TID=GRDBCipheriOS (Xcode 9.3, iOS <MIN>)
|
||||
script: make test_framework_GRDBCipheriOS_minTarget
|
||||
|
||||
###########################################
|
||||
## Test Installation Methods
|
||||
|
||||
# Manual Install (Xcode 9.4)
|
||||
- stage: Test Installation
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.4
|
||||
env:
|
||||
- TID=Manual Install (Xcode 9.4)
|
||||
script: make test_install_manual
|
||||
|
||||
# Manual Install (GRDBCipher, Xcode 9.4)
|
||||
- stage: Test Installation
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.4
|
||||
env:
|
||||
- TID=Manual Install (GRDBCipher, Xcode 9.4)
|
||||
script: make test_install_GRDBCipher
|
||||
|
||||
# Cocoapods Lint (Xcode 9.4)
|
||||
- stage: Test Installation
|
||||
osx_image: xcode9.4
|
||||
install:
|
||||
- gem install cocoapods # Since Travis is not always on latest version
|
||||
env:
|
||||
- TID=Cocoapods (Xcode 9.4)
|
||||
script: make test_CocoaPodsLint
|
||||
|
||||
# SPM Install (Xcode 9.4)
|
||||
- stage: Test Installation
|
||||
osx_image: xcode9.4
|
||||
env:
|
||||
- TID=SPM (Xcode 9.4)
|
||||
script: make test_install_SPM
|
||||
|
||||
## Carthage Build
|
||||
## Commented out until `make test_CarthageBuild` performs *reliably*.
|
||||
## See https://github.com/groue/GRDB.swift/pull/262
|
||||
# - stage: Test Installation
|
||||
# osx_image: xcode9.4
|
||||
# before_install:
|
||||
# - brew update
|
||||
# - brew outdated carthage || brew upgrade carthage
|
||||
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget_minSwift
|
||||
|
||||
# - stage: Test GRDB Xcode 11
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode11
|
||||
# env:
|
||||
# - TID=Carthages
|
||||
# script: make test_CarthageBuild
|
||||
# - TID=GRDBiOS (Swift 5.1, iOS <MIN>)
|
||||
# script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 11
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 5.1, tvOS <MAX>)
|
||||
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 11
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 4.2, tvOS <MAX>)
|
||||
script: make test_framework_GRDBtvOS_maxTarget_minSwift
|
||||
|
||||
# - stage: Test GRDB Xcode 11
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode11
|
||||
# env:
|
||||
# - TID=GRDBtvOS (Swift 5.1, tvOS <MIN>)
|
||||
# script: make test_framework_GRDBtvOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 11
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
env:
|
||||
- TID=GRDB [SPM] (macOS)
|
||||
script: make test_SPM
|
||||
|
||||
###########################################
|
||||
## Test GRDBCustom Xcode 11
|
||||
|
||||
- stage: Test GRDBCustom Xcode 11
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
env:
|
||||
- TID=GRDBOSX (Swift 5.1, macOS)
|
||||
script: make test_framework_GRDBCustomSQLiteOSX
|
||||
|
||||
- stage: Test GRDBCustom Xcode 11
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 5.1, iOS <MAX>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDBCustom Xcode 11
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_minSwift
|
||||
|
||||
# - stage: Test GRDBCustom Xcode 11
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode11
|
||||
# env:
|
||||
# - TID=GRDBiOS (Swift 5.1, iOS <MIN>)
|
||||
# script: make test_framework_GRDBCustomSQLiteiOS_minTarget
|
||||
|
||||
###########################################
|
||||
## Test SQLCipher Xcode 11
|
||||
|
||||
- stage: Test SQLCipher Xcode 11
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
env:
|
||||
- TID=SQLCipher 3
|
||||
script: make test_framework_SQLCipher3
|
||||
|
||||
- stage: Test SQLCipher Xcode 11
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
env:
|
||||
- TID=SQLCipher 4
|
||||
script: make test_framework_SQLCipher4
|
||||
|
||||
###########################################
|
||||
## Test Installation Xcode 11
|
||||
|
||||
# Manual Install
|
||||
- stage: Test Installation Xcode 11
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
env:
|
||||
- TID=Manual Install
|
||||
script: make test_install_manual
|
||||
|
||||
# CocoaPods Lint
|
||||
- stage: Test Installation Xcode 11
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
env:
|
||||
- TID=CocoaPods Lint
|
||||
script: make test_CocoaPodsLint_GRDB
|
||||
|
||||
# CocoaPods Install GRDB
|
||||
- stage: Test Installation Xcode 11
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
env:
|
||||
- TID=CocoaPods GRDB (framework)
|
||||
script: make test_install_GRDB_CocoaPods_framework
|
||||
|
||||
# CocoaPods Install GRDB
|
||||
- stage: Test Installation Xcode 11
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
env:
|
||||
- TID=CocoaPods GRDB (static)
|
||||
script: make test_install_GRDB_CocoaPods_static
|
||||
|
||||
# SPM Install
|
||||
- stage: Test Installation Xcode 11
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
env:
|
||||
- TID=SPM Package
|
||||
script: make test_install_SPM_Package
|
||||
|
||||
# SPM Install
|
||||
- stage: Test Installation Xcode 11
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
env:
|
||||
- TID=SPM Package in Xcode Project
|
||||
script: make test_install_SPM_Project
|
||||
|
||||
# Custom SQLite Install
|
||||
- stage: Test Installation Xcode 11
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11
|
||||
env:
|
||||
- TID=Custom SQLite
|
||||
script: make test_install_customSQLite
|
||||
|
||||
###########################################
|
||||
## Test GRDB Xcode 10.3
|
||||
|
||||
- stage: Test GRDB Xcode 10.3
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.3
|
||||
env:
|
||||
- TID=GRDBOSX (Swift 5, macOS)
|
||||
script: make test_framework_GRDBOSX_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.3
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.3
|
||||
env:
|
||||
- TID=GRDBWatchOS (watchOS)
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
- stage: Test GRDB Xcode 10.3
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.3
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 5, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.3
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.3
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 5, iOS <MIN>)
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 10.3
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.3
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 5, tvOS <MAX>)
|
||||
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.3
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.3
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 5, tvOS <MIN>)
|
||||
script: make test_framework_GRDBtvOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 10.3
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.3
|
||||
env:
|
||||
- TID=GRDB [SPM] (macOS)
|
||||
script: make test_SPM
|
||||
|
||||
###########################################
|
||||
## Test GRDB Xcode 10.2
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDBOSX (Swift 5, macOS)
|
||||
script: make test_framework_GRDBOSX_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDBWatchOS (watchOS)
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 5, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 5, iOS <MIN>)
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 5, tvOS <MAX>)
|
||||
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 5, tvOS <MIN>)
|
||||
script: make test_framework_GRDBtvOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDB [SPM] (macOS)
|
||||
script: make test_SPM
|
||||
|
||||
###########################################
|
||||
## Test GRDB Xcode 10.1
|
||||
|
||||
- stage: Test GRDB Xcode 10.1
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.1
|
||||
env:
|
||||
- TID=GRDBOSX (Swift 4.2, macOS)
|
||||
script: make test_framework_GRDBOSX_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.1
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.1
|
||||
env:
|
||||
- TID=GRDBWatchOS (watchOS)
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
- stage: Test GRDB Xcode 10.1
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.1
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.1
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.1
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 4.2, iOS <MIN>)
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 10.1
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.1
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 4.2, tvOS <MAX>)
|
||||
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.1
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.1
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 4.2, tvOS <MIN>)
|
||||
script: make test_framework_GRDBtvOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 10.1
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.1
|
||||
env:
|
||||
- TID=GRDB [SPM] (macOS)
|
||||
script: make test_SPM
|
||||
|
||||
###########################################
|
||||
## Test GRDB Xcode 10
|
||||
|
||||
- stage: Test GRDB Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=GRDBOSX (Swift 4.2, macOS)
|
||||
script: make test_framework_GRDBOSX_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=GRDBWatchOS (watchOS)
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
- stage: Test GRDB Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 4.2, iOS <MIN>)
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 4.2, tvOS <MAX>)
|
||||
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 4.2, tvOS <MIN>)
|
||||
script: make test_framework_GRDBtvOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=GRDB [SPM] (macOS)
|
||||
script: make test_SPM
|
||||
|
||||
# CocoaPods Install GRDB
|
||||
- stage: Test Installation Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=CocoaPods GRDB (framework)
|
||||
script: make test_install_GRDB_CocoaPods_framework
|
||||
|
||||
# CocoaPods Install GRDB
|
||||
- stage: Test Installation Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=CocoaPods GRDB (static)
|
||||
script: make test_install_GRDB_CocoaPods_static
|
||||
|
||||
# Custom SQLite Install
|
||||
- stage: Test Installation Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=Custom SQLite
|
||||
script: make test_install_customSQLite
|
||||
@@ -0,0 +1,50 @@
|
||||
# Contributor Code of Conduct
|
||||
|
||||
As contributors and maintainers of this project, and in the interest of
|
||||
fostering an open and welcoming community, we pledge to respect all people who
|
||||
contribute through reporting issues, posting feature requests, updating
|
||||
documentation, submitting pull requests or patches, and other activities.
|
||||
|
||||
We are committed to making participation in this project a harassment-free
|
||||
experience for everyone, regardless of level of experience, gender, gender
|
||||
identity and expression, sexual orientation, disability, personal appearance,
|
||||
body size, race, ethnicity, age, religion, or nationality.
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
- The use of sexualized language or imagery
|
||||
- Personal attacks
|
||||
- Trolling or insulting/derogatory comments
|
||||
- Public or private harassment
|
||||
- Publishing other's private information, such as physical or electronic
|
||||
addresses, without explicit permission
|
||||
- Other unethical or unprofessional conduct
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or
|
||||
reject comments, commits, code, wiki edits, issues, and other contributions
|
||||
that are not aligned to this Code of Conduct, or to ban temporarily or
|
||||
permanently any contributor for other behaviors that they deem inappropriate,
|
||||
threatening, offensive, or harmful.
|
||||
|
||||
By adopting this Code of Conduct, project maintainers commit themselves to
|
||||
fairly and consistently applying these principles to every aspect of managing
|
||||
this project. Project maintainers who do not follow or enforce the Code of
|
||||
Conduct may be permanently removed from the project team.
|
||||
|
||||
This code of conduct applies both within project spaces and in public spaces
|
||||
when an individual is representing the project or its community.
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported by contacting a project maintainer at [gr@pierlis.com](mailto:gr@pierlis.com).
|
||||
|
||||
All complaints will be reviewed and investigated and will result in a response that
|
||||
is deemed necessary and appropriate to the circumstances. Maintainers are
|
||||
obligated to maintain confidentiality with regard to the reporter of an
|
||||
incident.
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||
version 1.3.0, available at
|
||||
[http://contributor-covenant.org/version/1/3/0/][version]
|
||||
|
||||
[homepage]: http://contributor-covenant.org
|
||||
[version]: http://contributor-covenant.org/version/1/3/0/
|
||||
@@ -0,0 +1,339 @@
|
||||
Contributing to GRDB
|
||||
====================
|
||||
|
||||
**Thank you for coming!**
|
||||
|
||||
This guide is a set of tips and guidelines for contributing to the GitHub repository [groue/GRDB.swift](https://github.com/groue/GRDB.swift).
|
||||
|
||||
- [Report Bugs]
|
||||
- [Ask Questions]
|
||||
- [Suggest an Enhancement]
|
||||
- [Submit a Pull Request]
|
||||
- [Sponsoring and Professional Support]
|
||||
- [Suggested Contributions]
|
||||
- [Non-Goals]
|
||||
|
||||
|
||||
### Report Bugs
|
||||
|
||||
Please make sure the bug is not already reported by searching existing [issues](https://github.com/groue/GRDB.swift/issues).
|
||||
|
||||
If you're unable to find an existing issue addressing the problem, [open a new one](https://github.com/groue/GRDB.swift/issues/new). Be sure to include a title and clear description, as much relevant information as possible, and a code sample or an executable test case demonstrating the expected behavior that is not occurring.
|
||||
|
||||
|
||||
### Ask Questions
|
||||
|
||||
The information you are looking for is maybe already available. Check out:
|
||||
|
||||
- the [FAQ](README.md#faq)
|
||||
- the [general documentation](README.md#documentation)
|
||||
- the [answered questions](https://github.com/groue/GRDB.swift/issues?utf8=✓&q=label%3Aquestion+)
|
||||
|
||||
If not, your questions are welcome in the [GRDB forums](https://forums.swift.org/c/related-projects/grdb), or in a new [GitHub issue](https://github.com/groue/GRDB.swift/issues/new).
|
||||
|
||||
|
||||
### Suggest an Enhancement
|
||||
|
||||
Your idea may already be listed in [Suggested Contributions], waiting for someone to pick it up.
|
||||
|
||||
If not, contact [@groue](http://twitter.com/groue) on Twitter, or [open a new issue](https://github.com/groue/GRDB.swift/issues/new).
|
||||
|
||||
|
||||
### Submit a Pull Request
|
||||
|
||||
Discuss your idea first, so that your changes have a good chance of being merged in.
|
||||
|
||||
Submit your pull request against the `development` branch.
|
||||
|
||||
Pull requests that include tests for modified and new functionalities, inline documentation, and relevant updates to the main README.md are merged faster, because you won't have to wait for somebody else to complete your contribution.
|
||||
|
||||
|
||||
### Sponsoring and Professional Support
|
||||
|
||||
GRDB is free. It is openly developed by its contributors, on their free time, according to their will, needs, and availability. It is not controlled by any company.
|
||||
|
||||
When you have specific development or support needs, and are willing to financially contribute to GRDB, please send an email to [Gwendal Roué](mailto:gr@pierlis.com) so that we can enter a regular business relationship through the [Pierlis](http://pierlis.com/) company, based in Paris, France.
|
||||
|
||||
|
||||
## Suggested Contributions
|
||||
|
||||
You'll find below various ideas for enhancing and extending GRDB, in various areas. Your ideas can be added to this list: [Suggest an Enhancement].
|
||||
|
||||
Legend:
|
||||
|
||||
- :baby: **Starter Task**: get familiar with GRDB internals
|
||||
- :muscle: **Hard**: there are implementation challenges
|
||||
- :pencil: **Documentation**
|
||||
- :fire: **Experimental**: let's invent the future!
|
||||
- :bowtie: **Public API Challenge**: we'll need a very good public API
|
||||
- :hammer: **Tooling**: GRDB and its environment
|
||||
- :question: **Unknown Difficulty**
|
||||
|
||||
The ideas, in alphabetical order:
|
||||
|
||||
- [Associations]
|
||||
- [CloudKit]
|
||||
- [Concurrency]
|
||||
- [Custom FTS5 Auxiliary Functions]
|
||||
- [Date and Time Functions]
|
||||
- [Decode NSDecimalNumber from Text Columns]
|
||||
- [Documentation]
|
||||
- [Full Text Search Demo Application]
|
||||
- [JSON]
|
||||
- [Linux]
|
||||
- [More SQL Generation]
|
||||
- [Reactive Database Observation]
|
||||
- [SQL Console in the Debugger]
|
||||
- [SQLCipher in a Shared App Container]
|
||||
- [Typed Expressions]
|
||||
|
||||
|
||||
### Associations
|
||||
|
||||
:bowtie: Public API Challenge :muscle: Hard :fire: Experimental
|
||||
|
||||
Associations can be enhanced in several ways. See the "Known Issues" chapter of the [Associations Guide](Documentation/AssociationsBasics.md)
|
||||
|
||||
|
||||
### CloudKit
|
||||
|
||||
:bowtie: Public API Challenge :question: Unknown Difficulty :fire: Experimental
|
||||
|
||||
Integration with [CloudKit](https://developer.apple.com/icloud/cloudkit/) is a rich, interesting, and useful topic.
|
||||
|
||||
It is likely that CloudKit support would exist in a separate companion library.
|
||||
|
||||
Starting points:
|
||||
|
||||
- [caiyue1993/IceCream](https://github.com/caiyue1993/IceCream)
|
||||
- [mentrena/SyncKit](https://github.com/mentrena/SyncKit)
|
||||
- [nofelmahmood/Seam](https://github.com/nofelmahmood/Seam)
|
||||
- [Sorix/CloudCore](https://github.com/Sorix/CloudCore)
|
||||
- [Synchronizing data with CloudKit](https://medium.com/@guilhermerambo/synchronizing-data-with-cloudkit-94c6246a3fda)
|
||||
- WWDC CloudKit sessions, including [CloudKit Best Practices](https://developer.apple.com/videos/play/wwdc2016/231/)
|
||||
|
||||
|
||||
### Concurrency
|
||||
|
||||
:bowtie: Public API Challenge :muscle: Hard :pencil: Documentation
|
||||
|
||||
GRDB has a strong focus on safe concurrency. Not only safe as "does not crash", but safe as "actively protects your application data". The topic is discussed in (too) many places:
|
||||
|
||||
- [Concurrency Guide](README.md#concurrency)
|
||||
- [Why Adopt GRDB?](https://github.com/groue/GRDB.swift/blob/master/Documentation/WhyAdoptGRDB.md#strong-and-clear-multi-threading-guarantees)
|
||||
- [Four different ways to handle SQLite concurrency](https://medium.com/@gwendal.roue/four-different-ways-to-handle-sqlite-concurrency-db3bcc74d00e)
|
||||
- [Good Practices for Designing Record Types](https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md#fetch-in-time)
|
||||
- [Comparison between GRDB and Core Data concurrency](https://github.com/groue/GRDB.swift/issues/405)
|
||||
|
||||
Despite this abundant documention, I regularly meet developers who don't think about eventual multi-threading gotchas, and don't design their application against them.
|
||||
|
||||
This can be explained:
|
||||
|
||||
- Some developers disregard potential multi-threading bugs such as data races, even if the fix is "easy". Such bugs may never happen during the development of an application. They may only impact a few users in production. It is always easier not to think about them.
|
||||
|
||||
- Databases are often seen as plain CRUD tools, and some developers are not familiar with topics like isolation or transactions. This is especially true for developers who have experience in a managed ORM such as Core Data or Realm, or web frameworks like Rails or Django: switching to an unmanaged relational database is not an easy task.
|
||||
|
||||
- Not all applications need to be multi-threaded.
|
||||
|
||||
And this creates improvement opportunities:
|
||||
|
||||
- Better documentation of GRDB concurrency
|
||||
|
||||
- The introduction of an "ultra-safe" concurrency mode. Maybe something that restricts all database accesses to the main thread, like [FCModel](https://github.com/marcoarment/FCModel). Maybe in a separate companion library.
|
||||
|
||||
|
||||
### Custom FTS5 Auxiliary Functions
|
||||
|
||||
:question: Unknown Difficulty
|
||||
|
||||
The SQLite documentation provides [this description](https://www.sqlite.org/fts5.html) of FTS5 auxiliary functions:
|
||||
|
||||
> An application may use FTS5 auxiliary functions to retrieve extra information regarding the matched row. For example, an auxiliary function may be used to retrieve a copy of a column value for a matched row with all instances of the matched term surrounded by html <b></b> tags.
|
||||
|
||||
Applications can define their own [custom FTS5 auxiliary functions](https://www.sqlite.org/fts5.html#custom_auxiliary_functions) with SQLite, but GRDB does not yet provide any Swift API for that.
|
||||
|
||||
See issue [#421](https://github.com/groue/GRDB.swift/issues/421) for more information.
|
||||
|
||||
|
||||
### Date and Time Functions
|
||||
|
||||
:baby: Starter Task
|
||||
|
||||
Believe it or not, no one has ever asked support for SQLite [Date And Time Functions](https://www.sqlite.org/lang_datefunc.html). There is surely room for a nice Swift API that makes them available.
|
||||
|
||||
For more ideas, see:
|
||||
|
||||
- [SQLite Core Functions](https://www.sqlite.org/lang_corefunc.html)
|
||||
- [SQLite Aggregate Functions](https://www.sqlite.org/lang_aggfunc.html)
|
||||
- [SQLite JSON functions](https://www.sqlite.org/json1.html) and [JSON], below.
|
||||
|
||||
Functions are defined in [GRDB/QueryInterface/Support/SQLFunctions.swift](https://github.com/groue/GRDB.swift/blob/master/GRDB/QueryInterface/Support/SQLFunctions.swift).
|
||||
|
||||
|
||||
### Decode NSDecimalNumber from Text Columns
|
||||
|
||||
:baby: Starter Task
|
||||
|
||||
NSDecimalNumber currently only decodes integer and float decimal values. It would be nice if NSDecimalNumber would decode text values as well:
|
||||
|
||||
```swift
|
||||
let number = try NSDecimalNumber.fetchOne(db, "SELECT '12.3'")!
|
||||
print(number) // prints 12.3
|
||||
```
|
||||
|
||||
NSNumber and NSDecimalNumber support is found in [GRDB/Core/Support/Foundation/NSNumber.swift](https://github.com/groue/GRDB.swift/blob/master/GRDB/Core/Support/Foundation/NSNumber.swift)
|
||||
|
||||
|
||||
### Documentation
|
||||
|
||||
:baby: Starter Task :pencil: Documentation
|
||||
|
||||
General documentation can always be improved so that it reaches its goal: helping developers building applications.
|
||||
|
||||
- English: the documentation has mostly been written by [@groue](http://github.com/groue) who is not a native English speaker.
|
||||
- Clarity: any chapter that is not crystal clear should be enhanced.
|
||||
- Audience: documentation should talk to several populations of developers, from beginners who need positive guidance, to SQLite experts who need to build trust.
|
||||
- Typos
|
||||
- Inaccuracies
|
||||
- etc.
|
||||
|
||||
Inline documentation, the one which is embedded right into the source code and is displayed by Xcode when one alt-clicks an identifier, deserves the same care.
|
||||
|
||||
If you are a good writer, your help will be very warmly welcomed.
|
||||
|
||||
|
||||
### Full Text Search Demo Application
|
||||
|
||||
:baby: Starter Task :pencil: Documentation
|
||||
|
||||
There exists a GRDB demo app for the FTS5 full-text engine: [WWDCCompanion](https://github.com/groue/WWDCCompanion).
|
||||
|
||||
This application downloads the transcripts of WWDC sessions, and lets its user type keywords and find matching sessions, sorted by relevance.
|
||||
|
||||
The problem is that this demo app breaks every year :sweat_smile:
|
||||
|
||||
We'd need instead to index a stable corpus, in order to ease the maintenance of this demo app.
|
||||
|
||||
|
||||
### JSON
|
||||
|
||||
:bowtie: Public API Challenge :baby: Starter Task
|
||||
|
||||
[Codable Records] are granted with automatic JSON encoding and decoding of their complex properties. But there is still room for improvements. For example, could we put the [SQLite JSON1 extension](https://www.sqlite.org/json1.html) to some good use?
|
||||
|
||||
|
||||
### Linux
|
||||
|
||||
:muscle: Hard :hammer: Tooling
|
||||
|
||||
Swift on Linux is currently focused on the server (Vapor, Perfect, Kitura). While general server support is a [non-goal](#non-goals) of GRDB, there exists read-only servers, and Linux GUI applications, too. Linux is thus a desired platform.
|
||||
|
||||
|
||||
### More SQL Generation
|
||||
|
||||
:bowtie: Public API Challenge :question: Unknown Difficulty
|
||||
|
||||
There are several SQLite features that GRDB could natively support:
|
||||
|
||||
- [ALTER TABLE ... RENAME COLUMN ... TO ...](https://www.sqlite.org/lang_altertable.html)
|
||||
- [ATTACH DATABASE](https://www.sqlite.org/lang_attach.html)
|
||||
- [UPSERT](https://www.sqlite.org/lang_UPSERT.html)
|
||||
- [INSERT INTO ... SELECT ...](https://www.sqlite.org/lang_insert.html)
|
||||
- [WITH RECURSIVE ...](https://www.sqlite.org/lang_with.html)
|
||||
- [RTree](https://sqlite.org/rtree.html)
|
||||
- [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 [GRDBCombine](http://github.com/groue/GRDBCombine) and [RxGRDB] companion libraries.
|
||||
|
||||
More choices of reactive engines would help more developers enjoy GRDB.
|
||||
|
||||
|
||||
### SQL Console in the Debugger
|
||||
|
||||
:question: Unknown Difficulty :hammer: Tooling
|
||||
|
||||
Sometimes one needs, in lldb, a console similar to the [Command Line Shell For SQLite](https://www.sqlite.org/cli.html).
|
||||
|
||||
|
||||
### SQLCipher in a Shared App Container
|
||||
|
||||
:question: Unknown Difficulty
|
||||
|
||||
See issue [#302](https://github.com/groue/GRDB.swift/issues/302).
|
||||
|
||||
|
||||
### Typed Expressions
|
||||
|
||||
:bowtie: Public API Challenge :muscle: Hard :fire: Experimental
|
||||
|
||||
The compiler currently does not spot type mistakes in query interface requests:
|
||||
|
||||
```swift
|
||||
Player.filter(Column("name") == "Arthur") // OK
|
||||
Player.filter(Column("name") == 1) // Sure
|
||||
Player.filter(Column("name") == Date()) // Legit
|
||||
```
|
||||
|
||||
This weak typing also prevents natural-looking Swift code from producing the expected results:
|
||||
|
||||
```swift
|
||||
// Performs arithmetic additions instead of string concatenation
|
||||
Player.select(Column("firstName") + " " + Column("lastName"))
|
||||
```
|
||||
|
||||
It would be interesting to see what typed expressions could bring to GRDB.
|
||||
|
||||
|
||||
## Non-Goals
|
||||
|
||||
GRDB is a "toolkit for SQLite databases, with a focus on application development".
|
||||
|
||||
This definition is the reason why GRDB can provide key features such as sharp multi-threading, database observation, and first-class support for raw SQL.
|
||||
|
||||
Features that blur this focus are non-goals:
|
||||
|
||||
- Support for MySQL, PostgreSQL, or other database engines
|
||||
- Support for Servers
|
||||
|
||||
|
||||
[Ask Questions]: #ask-questions
|
||||
[Associations]: #associations
|
||||
[CloudKit]: #cloudkit
|
||||
[Codable Records]: README.md#codable-records
|
||||
[Custom FTS5 Auxiliary Functions]: #custom-fts5-auxiliary-functions
|
||||
[Database Observation]: #database-observation
|
||||
[Date and Time Functions]: #date-and-time-functions
|
||||
[Decode NSDecimalNumber from Text Columns]: #decode-nsdecimalnumber-from-text-columns
|
||||
[Documentation]: #documentation
|
||||
[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
|
||||
[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
|
||||
[Submit a Pull Request]: #submit-a-pull-request
|
||||
[Suggest an Enhancement]: #suggest-an-enhancement
|
||||
[Suggested Contributions]: #suggested-contributions
|
||||
[Typed Expressions]: #typed-expressions
|
||||
[persistence methods]: README.md#persistence-methods
|
||||
[PersistableRecord]: README.md#persistablerecord-protocol
|
||||
[Record Comparison]: README.md#record-comparison
|
||||
[Requesting Associated Records]: Documentation/AssociationsBasics.md#requesting-associated-records
|
||||
[ValueObservation]: README.md#valueobservation
|
||||
@@ -1,28 +0,0 @@
|
||||
import GRDB
|
||||
|
||||
struct Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
var score: Int
|
||||
|
||||
enum Columns: String, ColumnExpression {
|
||||
case id, name, score
|
||||
}
|
||||
|
||||
/// Update player id after successful insertion
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
}
|
||||
}
|
||||
|
||||
extension Player {
|
||||
private static let names = ["Arthur", "Anita", "Barbara", "Bernard", "Craig", "Chiara", "David", "Dean", "Éric", "Elena", "Fatima", "Frederik", "Gilbert", "Georgette", "Henriette", "Hassan", "Ignacio", "Irene", "Julie", "Jack", "Karl", "Kristel", "Louis", "Liz", "Masashi", "Mary", "Noam", "Nicole", "Ophelie", "Oleg", "Pascal", "Patricia", "Quentin", "Quinn", "Raoul", "Rachel", "Stephan", "Susie", "Tristan", "Tatiana", "Ursule", "Urbain", "Victor", "Violette", "Wilfried", "Wilhelmina", "Yvon", "Yann", "Zazie", "Zoé"]
|
||||
|
||||
static func randomName() -> String {
|
||||
return names[Int(arc4random_uniform(UInt32(names.count)))]
|
||||
}
|
||||
|
||||
static func randomScore() -> Int {
|
||||
return 10 * Int(arc4random_uniform(101))
|
||||
}
|
||||
}
|
||||
@@ -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.24.0](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 v3.2.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`.
|
||||
|
||||
@@ -120,6 +120,8 @@ 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).
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
<key>NSExtensionAttributes</key>
|
||||
<dict>
|
||||
<key>WKAppBundleIdentifier</key>
|
||||
<string>com.github.groue.GRDBDemoiOS.watchkitapp</string>
|
||||
<string>com.github.groue.GRDBDemoiOS2.watchkitapp</string>
|
||||
</dict>
|
||||
<key>NSExtensionPointIdentifier</key>
|
||||
<string>com.apple.watchkit</string>
|
||||
@@ -26,7 +26,7 @@
|
||||
<string>UIInterfaceOrientationPortraitUpsideDown</string>
|
||||
</array>
|
||||
<key>WKCompanionAppBundleIdentifier</key>
|
||||
<string>com.github.groue.GRDBDemoiOS</string>
|
||||
<string>com.github.groue.GRDBDemoiOS2</string>
|
||||
<key>WKWatchKitApp</key>
|
||||
<true/>
|
||||
</dict>
|
||||
@@ -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,18 +26,93 @@
|
||||
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 = DC3773F319C8CBB3004FCF85;
|
||||
remoteInfo = GRDBOSX;
|
||||
};
|
||||
56606D0B2355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56E5D7F91B4D422D00430942;
|
||||
remoteInfo = GRDBOSXTests;
|
||||
};
|
||||
56606D0D2355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 560C981A1C0E22D300BF8471;
|
||||
remoteInfo = GRDBOSXPerformanceTests;
|
||||
};
|
||||
56606D0F2355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56439B501F4CA1DC0066043F;
|
||||
remoteInfo = GRDBOSXPerformanceComparisonTests;
|
||||
};
|
||||
56606D112355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
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;
|
||||
containerPortal = 56B035FB1E8D9EBE003B6DA4 /* Project object */;
|
||||
@@ -50,83 +127,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 +158,7 @@
|
||||
dstPath = "";
|
||||
dstSubfolderSpec = 10;
|
||||
files = (
|
||||
568E5FE51E926547002582E0 /* GRDB.framework in Embed Frameworks */,
|
||||
56606D25235593AB00185962 /* GRDB.framework in Embed Frameworks */,
|
||||
);
|
||||
name = "Embed Frameworks";
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
@@ -169,7 +169,7 @@
|
||||
dstPath = "";
|
||||
dstSubfolderSpec = 10;
|
||||
files = (
|
||||
56B0365F1E8D9FB1003B6DA4 /* GRDB.framework in Embed Frameworks */,
|
||||
56606D212355938A00185962 /* GRDB.framework in Embed Frameworks */,
|
||||
);
|
||||
name = "Embed Frameworks";
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
@@ -196,7 +196,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 +204,7 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
568E5FE41E926547002582E0 /* GRDB.framework in Frameworks */,
|
||||
56606D24235593AB00185962 /* GRDB.framework in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -212,13 +212,37 @@
|
||||
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 */,
|
||||
56606D0E2355931F00185962 /* GRDBOSXPerformanceTests.xctest */,
|
||||
56606D102355931F00185962 /* GRDBOSXPerformanceComparisonTests.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 +272,7 @@
|
||||
568E5FC01E926430002582E0 /* GRDBDemoWatchOS */,
|
||||
568E5FCF1E926430002582E0 /* GRDBDemoWatchOS Extension */,
|
||||
56B036041E8D9EBE003B6DA4 /* Products */,
|
||||
56606D1F2355938A00185962 /* Frameworks */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
@@ -277,21 +302,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 +334,7 @@
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
568E5FE31E926535002582E0 /* PBXTargetDependency */,
|
||||
568E5FE71E926547002582E0 /* PBXTargetDependency */,
|
||||
56606D23235593A300185962 /* PBXTargetDependency */,
|
||||
);
|
||||
name = "GRDBDemoWatchOS Extension";
|
||||
productName = "GRDBDemoWatchOS Extension";
|
||||
@@ -345,8 +354,7 @@
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
56B0365D1E8D9F8F003B6DA4 /* PBXTargetDependency */,
|
||||
56B036611E8D9FB1003B6DA4 /* PBXTargetDependency */,
|
||||
56606D1E2355937900185962 /* PBXTargetDependency */,
|
||||
568E5FD81E926430002582E0 /* PBXTargetDependency */,
|
||||
);
|
||||
name = GRDBDemoiOS;
|
||||
@@ -361,7 +369,7 @@
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastSwiftUpdateCheck = 0830;
|
||||
LastUpgradeCheck = 0930;
|
||||
LastUpgradeCheck = 1020;
|
||||
ORGANIZATIONNAME = "Gwendal Roué";
|
||||
TargetAttributes = {
|
||||
568E5FBE1E926430002582E0 = {
|
||||
@@ -372,18 +380,20 @@
|
||||
568E5FCA1E926430002582E0 = {
|
||||
CreatedOnToolsVersion = 8.3;
|
||||
DevelopmentTeam = AMD8W895CT;
|
||||
LastSwiftMigration = 1020;
|
||||
ProvisioningStyle = Automatic;
|
||||
};
|
||||
56B036021E8D9EBE003B6DA4 = {
|
||||
CreatedOnToolsVersion = 8.3;
|
||||
DevelopmentTeam = AMD8W895CT;
|
||||
LastSwiftMigration = 1020;
|
||||
ProvisioningStyle = Automatic;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = 56B035FE1E8D9EBE003B6DA4 /* Build configuration list for PBXProject "GRDBDemoiOS" */;
|
||||
compatibilityVersion = "Xcode 3.2";
|
||||
developmentRegion = English;
|
||||
developmentRegion = en;
|
||||
hasScannedForEncodings = 0;
|
||||
knownRegions = (
|
||||
en,
|
||||
@@ -394,7 +404,7 @@
|
||||
projectDirPath = "";
|
||||
projectReferences = (
|
||||
{
|
||||
ProductGroup = 56B036271E8D9F79003B6DA4 /* Products */;
|
||||
ProductGroup = 56606CFD2355931F00185962 /* Products */;
|
||||
ProjectRef = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
},
|
||||
);
|
||||
@@ -408,60 +418,74 @@
|
||||
/* 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 */ = {
|
||||
56606D0E2355931F00185962 /* GRDBOSXPerformanceTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBOSXPerformanceTests.xctest;
|
||||
remoteRef = 56B0363E1E8D9F79003B6DA4 /* PBXContainerItemProxy */;
|
||||
remoteRef = 56606D0D2355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B036411E8D9F79003B6DA4 /* GRDBOSXCrashTests.xctest */ = {
|
||||
56606D102355931F00185962 /* GRDBOSXPerformanceComparisonTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBOSXPerformanceComparisonTests.xctest;
|
||||
remoteRef = 56606D0F2355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56606D122355931F00185962 /* GRDBOSXCrashTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
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 +545,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 +565,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 */
|
||||
@@ -589,7 +603,7 @@
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
INFOPLIST_FILE = "GRDBDemoWatchOS Extension/Info.plist";
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
|
||||
PRODUCT_NAME = "${TARGET_NAME}";
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
@@ -606,7 +620,7 @@
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
INFOPLIST_FILE = "GRDBDemoWatchOS Extension/Info.plist";
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
|
||||
PRODUCT_NAME = "${TARGET_NAME}";
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
@@ -624,7 +638,7 @@
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
IBSC_MODULE = GRDBDemoWatchOS_Extension;
|
||||
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
@@ -642,7 +656,7 @@
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
IBSC_MODULE = GRDBDemoWatchOS_Extension;
|
||||
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
@@ -655,6 +669,7 @@
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
|
||||
CLANG_ANALYZER_NONNULL = YES;
|
||||
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
|
||||
@@ -705,7 +720,7 @@
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 4.0;
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -713,6 +728,7 @@
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
|
||||
CLANG_ANALYZER_NONNULL = YES;
|
||||
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
|
||||
@@ -755,7 +771,7 @@
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
|
||||
SWIFT_VERSION = 4.0;
|
||||
SWIFT_VERSION = 5.0;
|
||||
VALIDATE_PRODUCT = YES;
|
||||
};
|
||||
name = Release;
|
||||
@@ -769,7 +785,7 @@
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
};
|
||||
name = Debug;
|
||||
@@ -783,7 +799,7 @@
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
};
|
||||
name = Release;
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
</Workspace>
|
||||
@@ -2,7 +2,7 @@
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded</key>
|
||||
<false/>
|
||||
<key>IDEDidComputeMac32BitWarning</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0930"
|
||||
LastUpgradeVersion = "1030"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0930"
|
||||
LastUpgradeVersion = "1030"
|
||||
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"
|
||||
@@ -8,11 +8,10 @@ struct AppDatabase {
|
||||
/// Creates a fully initialized database at path
|
||||
static func openDatabase(atPath path: String) throws -> DatabaseQueue {
|
||||
// Connect to the database
|
||||
// See https://github.com/groue/GRDB.swift/#database-connections
|
||||
dbQueue = try DatabaseQueue(path: path)
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
let dbQueue = try DatabaseQueue(path: path)
|
||||
|
||||
// Use DatabaseMigrator to define the database schema
|
||||
// See https://github.com/groue/GRDB.swift/#migrations
|
||||
// Define the database schema
|
||||
try migrator.migrate(dbQueue)
|
||||
|
||||
return dbQueue
|
||||
@@ -20,8 +19,7 @@ struct AppDatabase {
|
||||
|
||||
/// The DatabaseMigrator that defines the database schema.
|
||||
///
|
||||
/// This migrator is exposed so that migrations can be tested.
|
||||
// See https://github.com/groue/GRDB.swift/#migrations
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#migrations
|
||||
static var migrator: DatabaseMigrator {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
@@ -29,11 +27,10 @@ struct AppDatabase {
|
||||
// Create a table
|
||||
// See https://github.com/groue/GRDB.swift#create-tables
|
||||
try db.create(table: "player") { t in
|
||||
// An integer primary key auto-generates unique IDs
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
|
||||
// Sort player names in a localized case insensitive fashion by default
|
||||
// See https://github.com/groue/GRDB.swift/#unicode
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#unicode
|
||||
t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare)
|
||||
|
||||
t.column("score", .integer).notNull()
|
||||
@@ -8,7 +8,7 @@ var dbQueue: DatabaseQueue!
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
var window: UIWindow?
|
||||
|
||||
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
|
||||
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
|
||||
try! setupDatabase(application)
|
||||
return true
|
||||
}
|
||||
@@ -20,7 +20,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
dbQueue = try AppDatabase.openDatabase(atPath: databaseURL.path)
|
||||
|
||||
// Be a nice iOS citizen, and don't consume too much memory
|
||||
// See https://github.com/groue/GRDB.swift/#memory-management
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#memory-management
|
||||
dbQueue.setupMemoryManagement(in: application)
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 3.8 KiB After Width: | Height: | Size: 3.8 KiB |
|
Before Width: | Height: | Size: 5.7 KiB After Width: | Height: | Size: 5.7 KiB |
@@ -1,12 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14113" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
|
||||
<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>
|
||||
<dependencies>
|
||||
<deployment identifier="iOS"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14088"/>
|
||||
<capability name="Constraints to layout margins" minToolsVersion="6.0"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14283.14"/>
|
||||
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
|
||||
</dependencies>
|
||||
<scenes>
|
||||
@@ -14,7 +12,7 @@
|
||||
<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" alwaysBounceVertical="YES" dataMode="static" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="vlV-lc-eQA">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" dataMode="static" style="plain" separatorStyle="none" rowHeight="44" 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"/>
|
||||
@@ -25,11 +23,11 @@
|
||||
<rect key="frame" x="0.0" y="0.0" 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="43.5"/>
|
||||
<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="26" y="12" width="333" height="20"/>
|
||||
<rect key="frame" x="16" y="12" width="343" height="20"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<textInputTraits key="textInputTraits" autocapitalizationType="words" autocorrectionType="no" spellCheckingType="no" returnKeyType="next"/>
|
||||
<connections>
|
||||
@@ -38,7 +36,7 @@
|
||||
</textField>
|
||||
</subviews>
|
||||
<constraints>
|
||||
<constraint firstItem="m5m-Zs-j0z" firstAttribute="leading" secondItem="iyM-TJ-JB4" secondAttribute="leadingMargin" constant="10" id="9cK-nj-70V"/>
|
||||
<constraint firstItem="m5m-Zs-j0z" firstAttribute="leading" secondItem="iyM-TJ-JB4" secondAttribute="leadingMargin" id="9cK-nj-70V"/>
|
||||
<constraint firstAttribute="trailingMargin" secondItem="m5m-Zs-j0z" secondAttribute="trailing" id="JsE-8v-XAS"/>
|
||||
<constraint firstItem="m5m-Zs-j0z" firstAttribute="centerY" secondItem="iyM-TJ-JB4" secondAttribute="centerY" id="psG-tW-QrM"/>
|
||||
</constraints>
|
||||
@@ -48,11 +46,11 @@
|
||||
<rect key="frame" x="0.0" y="44" 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="43.5"/>
|
||||
<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="26" y="12" width="333" height="20"/>
|
||||
<rect key="frame" x="16" y="12" width="343" height="20"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<textInputTraits key="textInputTraits" autocorrectionType="no" spellCheckingType="no" keyboardType="numberPad" returnKeyType="done"/>
|
||||
</textField>
|
||||
@@ -60,7 +58,7 @@
|
||||
<constraints>
|
||||
<constraint firstAttribute="trailingMargin" secondItem="rZ9-Fa-cyr" secondAttribute="trailing" id="Gso-FU-Ct1"/>
|
||||
<constraint firstItem="rZ9-Fa-cyr" firstAttribute="centerY" secondItem="ccO-0O-u72" secondAttribute="centerY" id="UqA-ea-emb"/>
|
||||
<constraint firstItem="rZ9-Fa-cyr" firstAttribute="leading" secondItem="ccO-0O-u72" secondAttribute="leadingMargin" constant="10" id="WrY-St-72v"/>
|
||||
<constraint firstItem="rZ9-Fa-cyr" firstAttribute="leading" secondItem="ccO-0O-u72" secondAttribute="leadingMargin" id="WrY-St-72v"/>
|
||||
</constraints>
|
||||
</tableViewCellContentView>
|
||||
</tableViewCell>
|
||||
@@ -0,0 +1,66 @@
|
||||
import GRDB
|
||||
|
||||
// A plain Player struct
|
||||
struct Player {
|
||||
// Prefer Int64 for auto-incremented database ids
|
||||
var id: Int64?
|
||||
var name: String
|
||||
var score: Int
|
||||
}
|
||||
|
||||
// Hashable conformance supports tableView diffing
|
||||
extension Player: Hashable { }
|
||||
|
||||
// MARK: - Persistence
|
||||
|
||||
// Turn Player into a Codable Record.
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#records
|
||||
extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
// Define database columns from CodingKeys
|
||||
private enum Columns {
|
||||
static let id = Column(CodingKeys.id)
|
||||
static let name = Column(CodingKeys.name)
|
||||
static let score = Column(CodingKeys.score)
|
||||
}
|
||||
|
||||
// Update a player id after it has been inserted in the database.
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Database access
|
||||
|
||||
// Define some useful player requests.
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
|
||||
extension Player {
|
||||
static func orderedByName() -> QueryInterfaceRequest<Player> {
|
||||
return Player.order(Columns.name)
|
||||
}
|
||||
|
||||
static func orderedByScore() -> QueryInterfaceRequest<Player> {
|
||||
return Player.order(Columns.score.desc, Columns.name)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Player Randomization
|
||||
|
||||
extension Player {
|
||||
private static let names = [
|
||||
"Arthur", "Anita", "Barbara", "Bernard", "Craig", "Chiara", "David",
|
||||
"Dean", "Éric", "Elena", "Fatima", "Frederik", "Gilbert", "Georgette",
|
||||
"Henriette", "Hassan", "Ignacio", "Irene", "Julie", "Jack", "Karl",
|
||||
"Kristel", "Louis", "Liz", "Masashi", "Mary", "Noam", "Nicole",
|
||||
"Ophelie", "Oleg", "Pascal", "Patricia", "Quentin", "Quinn", "Raoul",
|
||||
"Rachel", "Stephan", "Susie", "Tristan", "Tatiana", "Ursule", "Urbain",
|
||||
"Victor", "Violette", "Wilfried", "Wilhelmina", "Yvon", "Yann",
|
||||
"Zazie", "Zoé"]
|
||||
|
||||
static func randomName() -> String {
|
||||
return names.randomElement()!
|
||||
}
|
||||
|
||||
static func randomScore() -> Int {
|
||||
return 10 * Int.random(in: 0...100)
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,16 @@
|
||||
import UIKit
|
||||
|
||||
protocol PlayerEditionViewControllerDelegate: class {
|
||||
func playerEditionControllerDidComplete(_ controller: PlayerEditionViewController)
|
||||
}
|
||||
|
||||
class PlayerEditionViewController: UITableViewController {
|
||||
weak var delegate: PlayerEditionViewControllerDelegate?
|
||||
enum Presentation {
|
||||
/// Modal presentation: edition ends with the "Commit" segue.
|
||||
case modal
|
||||
|
||||
/// Push presentation: edition ends when user hits the back button.
|
||||
case push
|
||||
}
|
||||
|
||||
var player: Player! { didSet { configureView() } }
|
||||
var commitButtonHidden: Bool = false { didSet { configureView() } }
|
||||
var presentation: Presentation! { didSet { configureView() } }
|
||||
|
||||
@IBOutlet fileprivate weak var cancelBarButtonItem: UIBarButtonItem!
|
||||
@IBOutlet fileprivate weak var commitBarButtonItem: UIBarButtonItem!
|
||||
@@ -31,13 +34,14 @@ class PlayerEditionViewController: UITableViewController {
|
||||
} else {
|
||||
scoreTextField.text = "\(player.score)"
|
||||
}
|
||||
|
||||
if commitButtonHidden {
|
||||
navigationItem.leftBarButtonItem = nil
|
||||
navigationItem.rightBarButtonItem = nil
|
||||
} else {
|
||||
|
||||
switch presentation! {
|
||||
case .modal:
|
||||
navigationItem.leftBarButtonItem = cancelBarButtonItem
|
||||
navigationItem.rightBarButtonItem = commitBarButtonItem
|
||||
case .push:
|
||||
navigationItem.leftBarButtonItem = nil
|
||||
navigationItem.rightBarButtonItem = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -55,17 +59,21 @@ extension PlayerEditionViewController {
|
||||
|
||||
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
|
||||
if segue.identifier == "Commit" {
|
||||
applyChanges()
|
||||
saveChanges()
|
||||
}
|
||||
}
|
||||
|
||||
override func willMove(toParentViewController parent: UIViewController?) {
|
||||
super.willMove(toParentViewController: parent)
|
||||
override func willMove(toParent parent: UIViewController?) {
|
||||
super.willMove(toParent: parent)
|
||||
|
||||
if parent == nil {
|
||||
// Self is popping from its navigation controller
|
||||
applyChanges()
|
||||
delegate?.playerEditionControllerDidComplete(self)
|
||||
switch presentation! {
|
||||
case .modal:
|
||||
break
|
||||
case .push:
|
||||
if parent == nil {
|
||||
// Self is popping from its navigation controller
|
||||
saveChanges()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,12 +106,16 @@ extension PlayerEditionViewController: UITextFieldDelegate {
|
||||
return false
|
||||
}
|
||||
|
||||
private func applyChanges() {
|
||||
private func saveChanges() {
|
||||
guard var player = self.player else {
|
||||
return
|
||||
}
|
||||
player.name = nameTextField.text ?? ""
|
||||
player.score = scoreTextField.text.flatMap { Int($0) } ?? 0
|
||||
self.player = player
|
||||
|
||||
try! dbQueue.inDatabase { db in
|
||||
try player.save(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,171 +1,61 @@
|
||||
import UIKit
|
||||
import GRDB
|
||||
|
||||
/// PlayersViewController displays the list of players.
|
||||
class PlayersViewController: UITableViewController {
|
||||
enum PlayerOrdering {
|
||||
private enum PlayerOrdering {
|
||||
case byName
|
||||
case byScore
|
||||
|
||||
var request: QueryInterfaceRequest<Player> {
|
||||
switch self {
|
||||
case .byName:
|
||||
return Player.order(Player.Columns.name)
|
||||
case .byScore:
|
||||
return Player.order(Player.Columns.score.desc, Player.Columns.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var playersController: FetchedRecordsController<Player>!
|
||||
var playerOrdering: PlayerOrdering = .byScore {
|
||||
@IBOutlet private weak var newPlayerButtonItem: UIBarButtonItem!
|
||||
private var players: [Player] = []
|
||||
private var playersObserver: TransactionObserver?
|
||||
private var playerCountObserver: TransactionObserver?
|
||||
private var playerOrdering: PlayerOrdering = .byScore {
|
||||
didSet {
|
||||
try! playersController.setRequest(playerOrdering.request)
|
||||
configureNavigationItem()
|
||||
configureOrderingBarButtonItem()
|
||||
configureTableView()
|
||||
}
|
||||
}
|
||||
private var playersRequest: QueryInterfaceRequest<Player> {
|
||||
switch playerOrdering {
|
||||
case .byName:
|
||||
return Player.orderedByName()
|
||||
case .byScore:
|
||||
return Player.orderedByScore()
|
||||
}
|
||||
}
|
||||
|
||||
@IBOutlet weak var newPlayerButtonItem: UIBarButtonItem!
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
configureTableView()
|
||||
configureToolbar()
|
||||
configureNavigationItem()
|
||||
configureTableView()
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
navigationController?.isToolbarHidden = false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Navigation
|
||||
|
||||
extension PlayersViewController : PlayerEditionViewControllerDelegate {
|
||||
|
||||
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
|
||||
if segue.identifier == "Edit" {
|
||||
let player = playersController.record(at: tableView.indexPathForSelectedRow!)
|
||||
let controller = segue.destination as! PlayerEditionViewController
|
||||
controller.title = player.name
|
||||
controller.player = player
|
||||
controller.delegate = self // See playerEditionControllerDidComplete
|
||||
controller.commitButtonHidden = true
|
||||
}
|
||||
else if segue.identifier == "New" {
|
||||
setEditing(false, animated: true)
|
||||
let navigationController = segue.destination as! UINavigationController
|
||||
let controller = navigationController.viewControllers.first as! PlayerEditionViewController
|
||||
controller.title = "New Player"
|
||||
controller.player = Player(id: nil, name: "", score: 0)
|
||||
}
|
||||
private func configureToolbar() {
|
||||
toolbarItems = [
|
||||
UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deletePlayers)),
|
||||
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
|
||||
UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refresh)),
|
||||
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
|
||||
UIBarButtonItem(title: "💣", style: .plain, target: self, action: #selector(stressTest)),
|
||||
]
|
||||
}
|
||||
|
||||
@IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) {
|
||||
// Player creation: cancel button was tapped
|
||||
}
|
||||
|
||||
@IBAction func commitPlayerEdition(_ segue: UIStoryboardSegue) {
|
||||
// Player creation: commit button was tapped
|
||||
let controller = segue.source as! PlayerEditionViewController
|
||||
try! dbQueue.write { db in
|
||||
try controller.player.save(db)
|
||||
}
|
||||
}
|
||||
|
||||
func playerEditionControllerDidComplete(_ controller: PlayerEditionViewController) {
|
||||
// Player edition: user has finished editing the player
|
||||
try! dbQueue.write { db in
|
||||
try controller.player.save(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - UITableViewDataSource
|
||||
|
||||
extension PlayersViewController {
|
||||
private func configureTableView() {
|
||||
playersController = try! FetchedRecordsController(dbQueue, request: playerOrdering.request)
|
||||
|
||||
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()
|
||||
})
|
||||
|
||||
try! playersController.performFetch()
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
||||
let cell = tableView.dequeueReusableCell(withIdentifier: "Player", for: indexPath)
|
||||
configure(cell, at: indexPath)
|
||||
return cell
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
|
||||
// Delete the player
|
||||
let player = playersController.record(at: indexPath)
|
||||
try! dbQueue.write { db in
|
||||
_ = try player.delete(db)
|
||||
}
|
||||
}
|
||||
|
||||
private func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
|
||||
let player = playersController.record(at: indexPath)
|
||||
if player.name.isEmpty {
|
||||
cell.textLabel?.text = "(anonymous)"
|
||||
} else {
|
||||
cell.textLabel?.text = player.name
|
||||
}
|
||||
cell.detailTextLabel?.text = abs(player.score) > 1 ? "\(player.score) points" : "0 point"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Actions
|
||||
|
||||
extension PlayersViewController {
|
||||
private func configureNavigationItem() {
|
||||
navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem]
|
||||
|
||||
configureOrderingBarButtonItem()
|
||||
configureTitle()
|
||||
}
|
||||
|
||||
private func configureOrderingBarButtonItem() {
|
||||
switch playerOrdering {
|
||||
case .byScore:
|
||||
navigationItem.rightBarButtonItem = UIBarButtonItem(
|
||||
@@ -180,16 +70,142 @@ extension PlayersViewController {
|
||||
}
|
||||
}
|
||||
|
||||
private func configureToolbar() {
|
||||
toolbarItems = [
|
||||
UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deletePlayers)),
|
||||
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
|
||||
UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refresh)),
|
||||
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
|
||||
UIBarButtonItem(title: "💣", style: .plain, target: self, action: #selector(stressTest)),
|
||||
]
|
||||
private func configureTitle() {
|
||||
// Track changes in the number of players
|
||||
let observation = ValueObservation.tracking { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
playerCountObserver = observation.start(
|
||||
in: dbQueue,
|
||||
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 list of players
|
||||
let request = self.playersRequest
|
||||
let observation = ValueObservation.tracking { db in
|
||||
try request.fetchAll(db)
|
||||
}
|
||||
playersObserver = observation.start(
|
||||
in: dbQueue,
|
||||
onError: { error in
|
||||
fatalError("Unexpected error: \(error)")
|
||||
},
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
|
||||
// Compute difference between current and new list of players
|
||||
let difference = players
|
||||
.difference(from: self.players)
|
||||
.inferringMoves()
|
||||
|
||||
// Apply those changes to the table view
|
||||
self.tableView.performBatchUpdates({
|
||||
self.players = players
|
||||
for change in difference {
|
||||
switch change {
|
||||
case let .remove(offset, _, associatedWith):
|
||||
if let associatedWith = associatedWith {
|
||||
self.tableView.moveRow(
|
||||
at: IndexPath(row: offset, section: 0),
|
||||
to: IndexPath(row: associatedWith, section: 0))
|
||||
} else {
|
||||
self.tableView.deleteRows(
|
||||
at: [IndexPath(row: offset, section: 0)],
|
||||
with: .fade)
|
||||
}
|
||||
case let .insert(offset, _, associatedWith):
|
||||
if associatedWith == nil {
|
||||
self.tableView.insertRows(
|
||||
at: [IndexPath(row: offset, section: 0)],
|
||||
with: .fade)
|
||||
}
|
||||
}
|
||||
}
|
||||
}, completion: nil)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Navigation
|
||||
|
||||
extension PlayersViewController {
|
||||
|
||||
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
|
||||
if segue.identifier == "Edit" {
|
||||
let player = players[tableView.indexPathForSelectedRow!.row]
|
||||
let controller = segue.destination as! PlayerEditionViewController
|
||||
controller.title = player.name
|
||||
controller.player = player
|
||||
controller.presentation = .push
|
||||
}
|
||||
else if segue.identifier == "New" {
|
||||
setEditing(false, animated: true)
|
||||
let navigationController = segue.destination as! UINavigationController
|
||||
let controller = navigationController.viewControllers.first as! PlayerEditionViewController
|
||||
controller.title = "New Player"
|
||||
controller.player = Player(id: nil, name: "", score: 0)
|
||||
controller.presentation = .modal
|
||||
}
|
||||
}
|
||||
|
||||
@IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) {
|
||||
// Player creation cancelled
|
||||
}
|
||||
|
||||
@IBAction func commitPlayerEdition(_ segue: UIStoryboardSegue) {
|
||||
// Player creation committed
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - UITableViewDataSource
|
||||
|
||||
extension PlayersViewController {
|
||||
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
||||
return players.count
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
||||
let cell = tableView.dequeueReusableCell(withIdentifier: "Player", for: indexPath)
|
||||
configure(cell, at: indexPath)
|
||||
return cell
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
|
||||
// Delete the player
|
||||
let player = players[indexPath.row]
|
||||
try! dbQueue.write { db in
|
||||
_ = try player.delete(db)
|
||||
}
|
||||
}
|
||||
|
||||
private func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
|
||||
let player = players[indexPath.row]
|
||||
if player.name.isEmpty {
|
||||
cell.textLabel?.text = "-"
|
||||
} else {
|
||||
cell.textLabel?.text = player.name
|
||||
}
|
||||
cell.detailTextLabel?.text = abs(player.score) > 1 ? "\(player.score) points" : "0 point"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Actions
|
||||
|
||||
extension PlayersViewController {
|
||||
@IBAction func sortByName() {
|
||||
setEditing(false, animated: true)
|
||||
playerOrdering = .byName
|
||||
@@ -231,16 +247,16 @@ extension PlayersViewController {
|
||||
}
|
||||
} else {
|
||||
// Insert a player
|
||||
if arc4random_uniform(2) == 0 {
|
||||
if Bool.random() {
|
||||
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
|
||||
try player.insert(db)
|
||||
}
|
||||
// Delete a random player
|
||||
if arc4random_uniform(2) == 0 {
|
||||
if Bool.random() {
|
||||
try Player.order(sql: "RANDOM()").limit(1).deleteAll(db)
|
||||
}
|
||||
// Update some players
|
||||
for var player in try Player.fetchAll(db) where arc4random_uniform(2) == 0 {
|
||||
for var player in try Player.fetchAll(db) where Bool.random() {
|
||||
player.score = Player.randomScore()
|
||||
try player.update(db)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
Demo Application
|
||||
================
|
||||
|
||||
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/Images/GRDBDemoScreenshot.png" width="50%">
|
||||
|
||||
**This demo application shows you:**
|
||||
|
||||
- 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 [ValueObservation](../../README.md#valueobservation).
|
||||
|
||||
**Files of interest:**
|
||||
|
||||
- [AppDelegate.swift](GRDBDemoiOS/AppDelegate.swift)
|
||||
|
||||
`AppDelegate` creates, on application startup, a unique instance of [DatabaseQueue](../../README.md#database-queues) available for the whole application.
|
||||
|
||||
- [AppDatabase.swift](GRDBDemoiOS/AppDatabase.swift)
|
||||
|
||||
`AppDatabase` defines the database for the whole application. It uses [DatabaseMigrator](../../README.md#migrations) in order to setup the database schema.
|
||||
|
||||
- [Player.swift](GRDBDemoiOS/Player.swift)
|
||||
|
||||
`Player` is a [Record](../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../README.md#codable-records).
|
||||
|
||||
- [PlayersViewController.swift](GRDBDemoiOS/PlayersViewController.swift)
|
||||
|
||||
`PlayersViewController` displays a list of players. It keeps its view up-to-date with [ValueObservation](../../README.md#valueobservation).
|
||||
|
||||
- [PlayerEditionViewController.swift](GRDBDemoiOS/PlayerEditionViewController.swift)
|
||||
|
||||
`PlayerEditionViewController` can create or edit a player, and save it in the database.
|
||||
@@ -81,7 +81,7 @@ try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
The full-text table can be fed and queried in [a regular way](../../../#full-text-search):
|
||||
|
||||
```swift
|
||||
try db.execute("INSERT INTO documents VALUES (?)", arguments: ["..."])
|
||||
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["..."])
|
||||
try Document(content: "...").insert(db)
|
||||
|
||||
let pattern = FTS5Pattern(matchingAnyTokenIn:"...")
|
||||
|
||||
@@ -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 {
|
||||
return fetchedRecordsController.sections.count
|
||||
}
|
||||
|
||||
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
||||
return 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!
|
||||
|
||||
|
||||
@@ -160,17 +160,43 @@ struct Player: FetchableRecord, TableRecord {
|
||||
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)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
GRDB can apply additional optimizations on expressions that adopt ColumnExpression, so conform to this protocol when you define a custom column type:
|
||||
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
|
||||
struct TypedColumn: ColumnExpression {
|
||||
// GRDB 3
|
||||
struct Player: Codable {
|
||||
var id: Int64
|
||||
var name: String
|
||||
var sqlType: 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)
|
||||
}
|
||||
}
|
||||
let nameColumn = TypedColumn(name: "name", sqlType: "VARCHAR")
|
||||
let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db)
|
||||
```
|
||||
|
||||
|
||||
@@ -410,14 +436,16 @@ Now you'll write instead:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
dbQueue.rx
|
||||
.fetch(from: [request, ...]) { db in try fetchResult(db) }
|
||||
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.
|
||||
|
||||
RxGRDB for GRDB 3 also introduces a new protocol, [DatabaseRegionConvertible], that allows a better encapsulation of complex requests, and a streamlined observable definition.
|
||||
GRDB 3.6 also introduces a new protocol, [DatabaseRegionConvertible], that allows a better encapsulation of complex requests, and a streamlined observable definition.
|
||||
|
||||
For example:
|
||||
|
||||
@@ -442,8 +470,9 @@ dbQueue.rx
|
||||
// GRDB 3: Track a team and its players
|
||||
struct TeamInfoRequest: DatabaseRegionConvertible { ... }
|
||||
let request = TeamInfoRequest(teamId: 1)
|
||||
dbQueue.rx
|
||||
.fetch(from: [request]) { try request.fetchOne($0) }
|
||||
ValueObservation.tracking(request, fetch: { try request.fetchOne($0) })
|
||||
.rx
|
||||
.fetch(in: dbQueue)
|
||||
.subscribe(onNext: { teamInfo: TeamInfo? in
|
||||
...
|
||||
})
|
||||
@@ -476,7 +505,6 @@ If you have time, you may dig deeper in GRDB 3 with those updated documentation
|
||||
[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
|
||||
@@ -490,5 +518,5 @@ If you have time, you may dig deeper in GRDB 3 with those updated documentation
|
||||
[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/RxGRDB/blob/master/README.md#databaseregionconvertible-protocol
|
||||
[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
|
||||
@@ -0,0 +1,187 @@
|
||||
Migrating From GRDB 3 to GRDB 4
|
||||
===============================
|
||||
|
||||
GRDB 4 comes with new features, but also a few breaking changes. This guide aims at helping you upgrading your applications.
|
||||
|
||||
- [New requirements](#new-requirements)
|
||||
- [Raw SQL](#raw-sql)
|
||||
- [ValueObservation](#valueobservation)
|
||||
- [Associations](#associations)
|
||||
- [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md)
|
||||
- [SQLCipher](#sqlcipher)
|
||||
- [PersistenceError.recordNotFound](#persistenceerrorrecordnotfound)
|
||||
|
||||
|
||||
### New requirements
|
||||
|
||||
GRDB now requires Swift 4.2+ and Xcode 10+. Swift 4.0 and 4.1 are no longer supported. Xcode 9 is no longer supported.
|
||||
|
||||
iOS 8 is no longer supported. The minimum iOS target is now iOS 9.
|
||||
|
||||
|
||||
### Raw SQL
|
||||
|
||||
Whenever your application uses raw SQL queries or snippets, you will now always have to use the `sql` argument label:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
try db.execute("INSERT INTO player (name) VALUES (?)", arguments: ["Arthur"])
|
||||
let playerCount = try Int.fetchOne(db, "SELECT COUNT(*) FROM player")
|
||||
|
||||
// GRDB 4
|
||||
try db.execute(sql: "INSERT INTO player (name) VALUES (?)", arguments: ["Arthur"])
|
||||
let playerCount = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM player")
|
||||
```
|
||||
|
||||
This change was made necessary by the introduction of [SQL Interpolation].
|
||||
|
||||
|
||||
### ValueObservation
|
||||
|
||||
[ValueObservation] has been refreshed in GRDB 4.
|
||||
|
||||
To guarantee asynchronous notifications, and never ever block your main thread, use the `.async(onQueue:startImmediately:)` scheduling:
|
||||
|
||||
```swift
|
||||
// On main queue
|
||||
var observation = Player.observationForAll()
|
||||
observation.scheduling = .async(onQueue: .main, startImmediately: true)
|
||||
let observer = try observation.start(
|
||||
in: dbQueue,
|
||||
onError: { error in ... },
|
||||
onChange: { (players: [Player]) in
|
||||
// On main queue
|
||||
print("fresh players: \(players)")s
|
||||
})
|
||||
// <- here "fresh players" is not printed yet.
|
||||
```
|
||||
|
||||
In GRDB 3, this scheduling used to be named `.queue(_: startImmediately:)`.
|
||||
|
||||
The second breaking change is `ValueObservation.extent`, which was removed in GRDB 4. Now all observations last until the observer returned by the `start` method is deallocated.
|
||||
|
||||
|
||||
### Associations
|
||||
|
||||
GRDB 4 brought a few new [associations] features:
|
||||
|
||||
- **Indirect associations** [HasOneThrough] and [HasManyThrough] let you define associations from a record to another through a third one. For example, they let you easily express many-to-many relations such as "a country has many citizens through its passports":
|
||||
|
||||
```swift
|
||||
struct Country: TableRecord, EncodableRecord {
|
||||
static let passports = hasMany(Passport.self)
|
||||
// New!
|
||||
static let citizens = hasMany(Citizen.self, through: passports, using: Passport.citizen)
|
||||
var citizens: QueryInterfaceRequest<Citizen> {
|
||||
return request(for: Country.citizens)
|
||||
}
|
||||
}
|
||||
|
||||
struct Passport: TableRecord {
|
||||
static let citizen = belongsTo(Citizen.self)
|
||||
}
|
||||
|
||||
struct Citizen: TableRecord {
|
||||
}
|
||||
|
||||
let country: Country = ...
|
||||
let citizens: [Citizen] = try dbQueue.read { db in
|
||||
try country.citizens.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||

|
||||
|
||||
- **Eager loading of HasMany associations**: The new `including(all:)` method lets you load arrays or sets of associated records in a single request:
|
||||
|
||||
```swift
|
||||
// All authors with their respective books
|
||||
let request = Author.including(all: Author.books)
|
||||
|
||||
// This request can feed the following record:
|
||||
struct AuthorInfo: FetchableRecord, Decodable {
|
||||
var author: Author
|
||||
var books: [Book] // all associated books
|
||||
}
|
||||
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
See [Joining And Prefetching Associated Records] for more information.
|
||||
|
||||
- **Automatic pluralization and singularization** of association identifiers.
|
||||
|
||||
GRDB will automatically **pluralize** or **singularize** names in order to help you easily associate records.
|
||||
|
||||
For example, the Book and Author records will automatically feed properties named `books`, `author`, or `bookCount` in your decoded records, without any explicit configuration, as long as the names of the backing database tables are "book" and "author".
|
||||
|
||||
The GRDB pluralization mechanisms are very powerful, being capable of pluralizing and singularizing both regular and irregular words (it's directly inspired from the battle-tested [Ruby on Rails inflections](https://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-pluralize)).
|
||||
|
||||
However, this change may have introduced some incompatibilities with GRDB 3 associations. Check [The Structure of a Joined Request] for more information.
|
||||
|
||||
|
||||
### SQLCipher
|
||||
|
||||
The integration of GRDB with SQLCipher has changed.
|
||||
|
||||
1. With GRDB 3, it was possible to perform a manual installation, or to use CocoaPods and the GRDBCipher pod.
|
||||
|
||||
With GRDB 4, CocoaPods is the only supported installation method. And the GRDBCipher pod is discontinued, replaced with GRDB.swift/SQLCipher:
|
||||
|
||||
```diff
|
||||
-pod 'GRDBCipher'
|
||||
+pod 'GRDB.swift/SQLCipher'
|
||||
```
|
||||
|
||||
In your Swift code, you no longer import the GRDBCipher module, but GRDB:
|
||||
|
||||
```diff
|
||||
-import GRDBCipher
|
||||
+import GRDB
|
||||
```
|
||||
|
||||
2. The default SQLCipher version which comes with GRDB 4 is now SQLCipher 4, which is incompatible with SQLCipher 3. SQLCipher 3 is still supported, though. See [Encryption] for more details.
|
||||
|
||||
3. The `cipherPageSize` and `kdfIterations` configuration properties are discontinued. With GRDB 4, run sql pragmas in the `prepareDatabase` property of the configuration:
|
||||
|
||||
```swift
|
||||
var configuration = Configuration()
|
||||
configuration.passphrase = "secret"
|
||||
configuration.prepareDatabase = { db in
|
||||
try db.execute(sql: "PRAGMA cipher_page_size = 4096")
|
||||
try db.execute(sql: "PRAGMA kdf_iter = 128000")
|
||||
}
|
||||
let dbQueue = try DatabaseQueue(path: "...", configuration: configuration)
|
||||
```
|
||||
|
||||
|
||||
### PersistenceError.recordNotFound
|
||||
|
||||
PersistenceError.recordNotFound is thrown whenever a record update method does not find any database row to update. It was refactored in GRDB 4:
|
||||
|
||||
```swift
|
||||
public enum PersistenceError: Error {
|
||||
case recordNotFound(databaseTableName: String, key: [String: DatabaseValue])
|
||||
}
|
||||
|
||||
do {
|
||||
try player.updateChanges {
|
||||
$0.score += 1000
|
||||
}
|
||||
} catch let error as PersistenceError.recordNotFound {
|
||||
// Update failed because player does not exist in the database
|
||||
print(error)
|
||||
// prints "Key not found in table player: [id:42]"
|
||||
}
|
||||
```
|
||||
|
||||
[SQL Interpolation]: SQLInterpolation.md
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[Encryption]: ../README.md#encryption
|
||||
[HasOneThrough]: AssociationsBasics.md#hasonethrough
|
||||
[HasManyThrough]: AssociationsBasics.md#hasmanythrough
|
||||
[PersistableRecord]: ../README.md#persistablerecord-protocol
|
||||
[associations]: AssociationsBasics.md
|
||||
[EncodableRecord]: ../README.md#persistablerecord-protocol
|
||||
[The Structure of a Joined Request]: AssociationsBasics.md#the-structure-of-a-joined-request
|
||||
[Joining And Prefetching Associated Records]: AssociationsBasics.md#joining-and-prefetching-associated-records
|
||||
|
||||
@@ -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 {
|
||||
return 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
|
||||
return 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> {
|
||||
return 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> {
|
||||
return 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> {
|
||||
return 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? {
|
||||
return try dbQueue.read { db in
|
||||
try Author.fetchOne(db, key: id)
|
||||
}
|
||||
}
|
||||
|
||||
func book(id: Int64) throws -> Book? {
|
||||
return try dbQueue.read { db in
|
||||
try Book.fetchOne(db, key: id)
|
||||
}
|
||||
}
|
||||
|
||||
func books(writtenBy author: Author) throws -> [Book] {
|
||||
return try dbQueue.read { db in
|
||||
try 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] {
|
||||
return 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? {
|
||||
return 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? {
|
||||
return 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.
|
||||
|
||||
@@ -308,15 +677,16 @@ This synchronization is not automatic with GRDB: records do not "auto-update". T
|
||||
|
||||
Instead, have a look at [Database Observation]:
|
||||
|
||||
> :bulb: **Tip**: Use [FetchedRecordsController] when a table or collection views should remained synchronized with the database, in an animated way.
|
||||
> :bulb: **Tip**: [ValueObservation] performs automated tracking of database changes.
|
||||
>
|
||||
> :bulb: **Tip**: Use [RxGRDB] when your application needs to react to all changes in the results of a database request.
|
||||
> :bulb: **Tip**: [GRDBCombine] performs automated tracking of database changes, in the [Combine](https://developer.apple.com/documentation/combine) way.
|
||||
>
|
||||
> :bulb: **Tip**: Use [TransactionObserver], the low-level protocol for database observation, for your most advanced needs.
|
||||
> :bulb: **Tip**: [RxGRDB] performs automated tracking of database changes, in the [RxSwift](https://github.com/ReactiveX/RxSwift) way.
|
||||
>
|
||||
> :bulb: **Tip**: [TransactionObserver] provides low-level database observation, for your most advanced needs.
|
||||
>
|
||||
> :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
|
||||
@@ -335,13 +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
|
||||
[FetchedRecordsController]: ../README.md#fetchedrecordscontroller
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[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
|
||||
|
Before Width: | Height: | Size: 47 KiB |
@@ -0,0 +1,173 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="489px" height="362px" viewBox="0 0 489 362" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<!-- Generator: Sketch 51.2 (57519) - http://www.bohemiancoding.com/sketch -->
|
||||
<title>DatabasePoolScheduling</title>
|
||||
<desc>Created with Sketch.</desc>
|
||||
<defs>
|
||||
<linearGradient x1="50%" y1="100%" x2="50%" y2="1.41638472e-14%" id="linearGradient-1">
|
||||
<stop stop-color="#FFFFFF" stop-opacity="0.9" offset="0%"></stop>
|
||||
<stop stop-color="#FFFFFF" offset="100%"></stop>
|
||||
</linearGradient>
|
||||
<rect id="path-2" x="0" y="0" width="120" height="88" rx="10"></rect>
|
||||
<filter x="-12.1%" y="-13.1%" width="124.2%" height="133.0%" filterUnits="objectBoundingBox" id="filter-4">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<rect id="path-5" x="0" y="0" width="120" height="250" rx="10"></rect>
|
||||
<filter x="-12.1%" y="-4.6%" width="124.2%" height="111.6%" filterUnits="objectBoundingBox" id="filter-7">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<rect id="path-8" x="0" y="0" width="120" height="94" rx="10"></rect>
|
||||
<filter x="-12.1%" y="-12.2%" width="124.2%" height="130.9%" filterUnits="objectBoundingBox" id="filter-10">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<rect id="path-11" x="0" y="0" width="120" height="44" rx="10"></rect>
|
||||
<filter x="-12.1%" y="-26.1%" width="124.2%" height="165.9%" filterUnits="objectBoundingBox" id="filter-13">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<rect id="path-14" x="0" y="0" width="120" height="44" rx="10"></rect>
|
||||
<filter x="-12.1%" y="-26.1%" width="124.2%" height="165.9%" filterUnits="objectBoundingBox" id="filter-16">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<rect id="path-17" x="0" y="0" width="120" height="44" rx="10"></rect>
|
||||
<filter x="-12.1%" y="-26.1%" width="124.2%" height="165.9%" filterUnits="objectBoundingBox" id="filter-19">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
</defs>
|
||||
<g id="Page-3" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<g id="DatabasePoolScheduling">
|
||||
<g id="Group-2" transform="translate(44.000000, 0.000000)" stroke="#D7D7D7">
|
||||
<rect id="Rectangle-2" x="0.5" y="0.5" width="444" height="361" rx="6"></rect>
|
||||
<rect id="Rectangle-2-Copy" fill-opacity="0.02" fill="#000000" x="148.5" y="0.5" width="148" height="361"></rect>
|
||||
</g>
|
||||
<text id="Thread-1" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal" fill="#000000">
|
||||
<tspan x="89.9428711" y="26">Thread 1</tspan>
|
||||
</text>
|
||||
<text id="Thread-2" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal" fill="#000000">
|
||||
<tspan x="236.979004" y="26">Thread 2</tspan>
|
||||
</text>
|
||||
<text id="Thread-3" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal" fill="#000000">
|
||||
<tspan x="384.818359" y="26">Thread 3</tspan>
|
||||
</text>
|
||||
<g id="BlueBox" transform="translate(58.000000, 44.000000)">
|
||||
<g id="Group">
|
||||
<mask id="mask-3" fill="white">
|
||||
<use xlink:href="#path-2"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-4)" xlink:href="#path-2"></use>
|
||||
<use fill="#005CC5" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" fill="url(#linearGradient-1)" fill-rule="evenodd" x="-0.5" y="-0.5" width="121" height="89" rx="10"></rect>
|
||||
</g>
|
||||
<text id="Label" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="15.7509766" y="49">Read State A</tspan>
|
||||
</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="BlueBox" transform="translate(355.000000, 94.000000)">
|
||||
<g id="Group">
|
||||
<mask id="mask-6" fill="white">
|
||||
<use xlink:href="#path-5"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-7)" xlink:href="#path-5"></use>
|
||||
<use fill="#005CC5" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" fill="url(#linearGradient-1)" fill-rule="evenodd" x="-0.5" y="-0.5" width="121" height="251" rx="10"></rect>
|
||||
</g>
|
||||
<text id="Label" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="15.7509766" y="130">Read State A</tspan>
|
||||
</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="GreenBox" transform="translate(207.000000, 60.000000)">
|
||||
<g id="Group">
|
||||
<mask id="mask-9" fill="white">
|
||||
<use xlink:href="#path-8"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-10)" xlink:href="#path-8"></use>
|
||||
<use fill="#366500" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" fill="url(#linearGradient-1)" fill-rule="evenodd" x="-0.5" y="-0.5" width="121" height="95" rx="10"></rect>
|
||||
</g>
|
||||
<text id="Label" mask="url(#mask-9)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="14.7802734" y="52">Write State B</tspan>
|
||||
</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="GreenBox" transform="translate(58.000000, 172.000000)">
|
||||
<g id="Group">
|
||||
<mask id="mask-12" fill="white">
|
||||
<use xlink:href="#path-11"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-13)" xlink:href="#path-11"></use>
|
||||
<use fill="#366500" fill-rule="evenodd" xlink:href="#path-11"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" fill="url(#linearGradient-1)" fill-rule="evenodd" x="-0.5" y="-0.5" width="121" height="45" rx="10"></rect>
|
||||
</g>
|
||||
<text id="Label" mask="url(#mask-12)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="15.9663086" y="27">Read State B</tspan>
|
||||
</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="OrangeBox" transform="translate(58.000000, 231.000000)">
|
||||
<g id="Group">
|
||||
<mask id="mask-15" fill="white">
|
||||
<use xlink:href="#path-14"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-16)" xlink:href="#path-14"></use>
|
||||
<use fill="#CD7F00" fill-rule="evenodd" xlink:href="#path-14"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" fill="url(#linearGradient-1)" fill-rule="evenodd" x="-0.5" y="-0.5" width="121" height="45" rx="10"></rect>
|
||||
</g>
|
||||
<text id="Label" mask="url(#mask-15)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="14.4179688" y="27">Write State C</tspan>
|
||||
</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="OrangeBox" transform="translate(207.000000, 300.000000)">
|
||||
<g id="Group">
|
||||
<mask id="mask-18" fill="white">
|
||||
<use xlink:href="#path-17"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-19)" xlink:href="#path-17"></use>
|
||||
<use fill="#CD7F00" fill-rule="evenodd" xlink:href="#path-17"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" fill="url(#linearGradient-1)" fill-rule="evenodd" x="-0.5" y="-0.5" width="121" height="45" rx="10"></rect>
|
||||
</g>
|
||||
<text id="Label" mask="url(#mask-18)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="15.6040039" y="27">Read State C</tspan>
|
||||
</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Group-4" transform="translate(0.000000, 13.000000)" fill="#000000">
|
||||
<text id="Time" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="0.501953125" y="13">Time</tspan>
|
||||
</text>
|
||||
<path id="Line" d="M16.5,340 L21,331 L12,331 L16.5,340 Z M16,22.5 L16,331.5 L16,332 L17,332 L17,331.5 L17,22.5 L17,22 L16,22 L16,22.5 Z" fill-rule="nonzero"></path>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 39 KiB |
@@ -0,0 +1,150 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="489px" height="362px" viewBox="0 0 489 362" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<!-- Generator: Sketch 51.2 (57519) - http://www.bohemiancoding.com/sketch -->
|
||||
<title>DatabaseQueueScheduling</title>
|
||||
<desc>Created with Sketch.</desc>
|
||||
<defs>
|
||||
<linearGradient x1="50%" y1="100%" x2="50%" y2="1.41638472e-14%" id="linearGradient-1">
|
||||
<stop stop-color="#FFFFFF" stop-opacity="0.9" offset="0%"></stop>
|
||||
<stop stop-color="#FFFFFF" offset="100%"></stop>
|
||||
</linearGradient>
|
||||
<rect id="path-2" x="0" y="0" width="120" height="44" rx="10"></rect>
|
||||
<filter x="-12.1%" y="-26.1%" width="124.2%" height="165.9%" filterUnits="objectBoundingBox" id="filter-4">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<rect id="path-5" x="0" y="0" width="120" height="44" rx="10"></rect>
|
||||
<filter x="-12.1%" y="-26.1%" width="124.2%" height="165.9%" filterUnits="objectBoundingBox" id="filter-7">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<rect id="path-8" x="0" y="0" width="120" height="44" rx="10"></rect>
|
||||
<filter x="-12.1%" y="-26.1%" width="124.2%" height="165.9%" filterUnits="objectBoundingBox" id="filter-10">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<rect id="path-11" x="0" y="0" width="120" height="44" rx="10"></rect>
|
||||
<filter x="-12.1%" y="-26.1%" width="124.2%" height="165.9%" filterUnits="objectBoundingBox" id="filter-13">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<rect id="path-14" x="0" y="0" width="120" height="44" rx="10"></rect>
|
||||
<filter x="-12.1%" y="-26.1%" width="124.2%" height="165.9%" filterUnits="objectBoundingBox" id="filter-16">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
</defs>
|
||||
<g id="Page-3" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<g id="DatabaseQueueScheduling">
|
||||
<g id="Group-2" transform="translate(44.000000, 0.000000)" stroke="#D7D7D7">
|
||||
<rect id="Rectangle-2" x="0.5" y="0.5" width="444" height="361" rx="6"></rect>
|
||||
<rect id="Rectangle-2-Copy" fill-opacity="0.02" fill="#000000" x="148.5" y="0.5" width="148" height="361"></rect>
|
||||
</g>
|
||||
<text id="Thread-1" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal" fill="#000000">
|
||||
<tspan x="89.9428711" y="26">Thread 1</tspan>
|
||||
</text>
|
||||
<text id="Thread-2" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal" fill="#000000">
|
||||
<tspan x="236.979004" y="26">Thread 2</tspan>
|
||||
</text>
|
||||
<text id="Thread-3" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal" fill="#000000">
|
||||
<tspan x="384.818359" y="26">Thread 3</tspan>
|
||||
</text>
|
||||
<g id="Group-4" transform="translate(0.000000, 13.000000)" fill="#000000">
|
||||
<text id="Time" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="0.501953125" y="13">Time</tspan>
|
||||
</text>
|
||||
<path id="Line" d="M16.5,340 L21,331 L12,331 L16.5,340 Z M16,22.5 L16,331.5 L16,332 L17,332 L17,331.5 L17,22.5 L17,22 L16,22 L16,22.5 Z" fill-rule="nonzero"></path>
|
||||
</g>
|
||||
<g id="BlueBox" transform="translate(58.000000, 44.000000)">
|
||||
<g id="Group">
|
||||
<mask id="mask-3" fill="white">
|
||||
<use xlink:href="#path-2"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-4)" xlink:href="#path-2"></use>
|
||||
<use fill="#005CC5" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" fill="url(#linearGradient-1)" fill-rule="evenodd" x="-0.5" y="-0.5" width="121" height="45" rx="10"></rect>
|
||||
</g>
|
||||
<text id="Label" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="15.7509766" y="27">Read State A</tspan>
|
||||
</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="GreenBox" transform="translate(207.000000, 110.000000)">
|
||||
<g id="Group">
|
||||
<mask id="mask-6" fill="white">
|
||||
<use xlink:href="#path-5"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-7)" xlink:href="#path-5"></use>
|
||||
<use fill="#366500" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" fill="url(#linearGradient-1)" fill-rule="evenodd" x="-0.5" y="-0.5" width="121" height="45" rx="10"></rect>
|
||||
</g>
|
||||
<text id="Label" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="14.7802734" y="27">Write State B</tspan>
|
||||
</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="GreenBox" transform="translate(355.000000, 159.000000)">
|
||||
<g id="Group">
|
||||
<mask id="mask-9" fill="white">
|
||||
<use xlink:href="#path-8"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-10)" xlink:href="#path-8"></use>
|
||||
<use fill="#366500" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" fill="url(#linearGradient-1)" fill-rule="evenodd" x="-0.5" y="-0.5" width="121" height="45" rx="10"></rect>
|
||||
</g>
|
||||
<text id="Label" mask="url(#mask-9)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="15.9663086" y="27">Read State B</tspan>
|
||||
</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="OrangeBox" transform="translate(355.000000, 297.000000)">
|
||||
<g id="Group">
|
||||
<mask id="mask-12" fill="white">
|
||||
<use xlink:href="#path-11"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-13)" xlink:href="#path-11"></use>
|
||||
<use fill="#CD7F00" fill-rule="evenodd" xlink:href="#path-11"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" fill="url(#linearGradient-1)" fill-rule="evenodd" x="-0.5" y="-0.5" width="121" height="45" rx="10"></rect>
|
||||
</g>
|
||||
<text id="Label" mask="url(#mask-12)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="15.6040039" y="27">Read State C</tspan>
|
||||
</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="OrangeBox" transform="translate(58.000000, 231.000000)">
|
||||
<g id="Group">
|
||||
<mask id="mask-15" fill="white">
|
||||
<use xlink:href="#path-14"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-16)" xlink:href="#path-14"></use>
|
||||
<use fill="#CD7F00" fill-rule="evenodd" xlink:href="#path-14"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" fill="url(#linearGradient-1)" fill-rule="evenodd" x="-0.5" y="-0.5" width="121" height="45" rx="10"></rect>
|
||||
</g>
|
||||
<text id="Label" mask="url(#mask-15)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="14.4179688" y="27">Write State C</tspan>
|
||||
</text>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 285 KiB |
@@ -0,0 +1,3 @@
|
||||
fixfonts:
|
||||
sed -i '' -- 's/SFUIText-Regular, SF UI Text/-apple-system,sans-serif/g' *.svg
|
||||
sed -i '' -- 's/SFUIText-Semibold, SF UI Text/-apple-system,sans-serif/g' *.svg
|
||||
@@ -83,15 +83,17 @@ try dbQueue.write { db in
|
||||
}
|
||||
|
||||
// Demo values: two Foo and one Bar
|
||||
try db.execute("""
|
||||
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
|
||||
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
|
||||
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
|
||||
""", arguments: [
|
||||
try db.execute(
|
||||
sql: """
|
||||
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
|
||||
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
|
||||
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
|
||||
""",
|
||||
arguments: [
|
||||
"Foo", "Arthur", nil,
|
||||
"Bar", nil, 100,
|
||||
"Foo", "Barbara", nil,
|
||||
])
|
||||
])
|
||||
}
|
||||
|
||||
//: We also need a method that decodes database rows into `Foo` or `Bar`
|
||||
@@ -140,7 +142,7 @@ extension Base {
|
||||
|
||||
try dbQueue.read { db in
|
||||
print("> KISS: Fetch from SQL")
|
||||
let rows = try Row.fetchAll(db, "SELECT * FROM base") // Fetch database rows
|
||||
let rows = try Row.fetchAll(db, sql: "SELECT * FROM base") // Fetch database rows
|
||||
let bases = rows.map { row in // Decode database rows
|
||||
Base.decode(row: row)
|
||||
}
|
||||
@@ -210,13 +212,15 @@ extension Base: MyDatabaseDecoder {
|
||||
//: **prepared statement**:
|
||||
//:
|
||||
//: try dbQueue.read { db in
|
||||
//: let statement = try db.makeSelectStatement("SELECT ...")
|
||||
//: let statement = try db.makeSelectStatement(sql: "SELECT ...")
|
||||
//: try Base.fetchCursor(statement) // Cursor of Base
|
||||
//: try Base.fetchAll(statement) // [Base]
|
||||
//: try Base.fetchOne(statement) // Base?
|
||||
//: }
|
||||
|
||||
extension MyDatabaseDecoder {
|
||||
// MARK: - Fetch from SelectStatement
|
||||
|
||||
// SelectStatement, StatementArguments, and RowAdapter are the fundamental
|
||||
// fetching parameters of GRDB. Make sure to accept them all:
|
||||
static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
|
||||
@@ -239,7 +243,7 @@ extension MyDatabaseDecoder {
|
||||
|
||||
try dbQueue.read { db in
|
||||
print("> Fetch from prepared statement")
|
||||
let statement = try db.makeSelectStatement("SELECT * FROM base")
|
||||
let statement = try db.makeSelectStatement(sql: "SELECT * FROM base")
|
||||
let bases = try Base.fetchAll(statement)
|
||||
for base in bases {
|
||||
print(base.description)
|
||||
@@ -258,6 +262,8 @@ try dbQueue.read { db in
|
||||
//: try Base.fetchOne(db, request) // Base?
|
||||
//: }
|
||||
extension MyDatabaseDecoder {
|
||||
// MARK: - Fetch from FetchRequest
|
||||
|
||||
static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> MapCursor<RowCursor, DecodedType> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
@@ -293,6 +299,8 @@ try dbQueue.read { db in
|
||||
//: try request.fetchOne(db) // Base?
|
||||
//: }
|
||||
extension FetchRequest where RowDecoder: MyDatabaseDecoder {
|
||||
// MARK: - FetchRequest fetching methods
|
||||
|
||||
func fetchCursor(_ db: Database) throws -> MapCursor<RowCursor, RowDecoder.DecodedType> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
@@ -324,6 +332,8 @@ try dbQueue.read { db in
|
||||
//: try Base.fetchOne(db) // Base?
|
||||
//: }
|
||||
extension MyDatabaseDecoder where Self: TableRecord {
|
||||
// MARK: - Static fetching methods
|
||||
|
||||
static func fetchCursor(_ db: Database) throws -> MapCursor<RowCursor, DecodedType> {
|
||||
return try all().fetchCursor(db)
|
||||
}
|
||||
@@ -345,31 +355,32 @@ try dbQueue.read { db in
|
||||
}
|
||||
}
|
||||
|
||||
//: Finally, you don't have a true GRDB record unless it allows fetching from
|
||||
//: raw SQL:
|
||||
//: Finally, you can support raw SQL as well:
|
||||
//:
|
||||
//: try dbQueue.read { db in
|
||||
//: try Base.fetchCursor(db, "SELECT ...") // Cursor of Base
|
||||
//: try Base.fetchAll(db, "SELECT ...") // [Base]
|
||||
//: try Base.fetchOne(db, "SELECT ...") // Base?
|
||||
//: try Base.fetchAll(db,
|
||||
//: sql: "SELECT ... WHERE name = ?",
|
||||
//: arguments: ["O'Brien"]) // [Base]
|
||||
//: }
|
||||
extension MyDatabaseDecoder {
|
||||
static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
|
||||
return try fetchCursor(db, SQLRequest<Self>(sql, arguments: arguments, adapter: adapter))
|
||||
// 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))
|
||||
}
|
||||
|
||||
static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [DecodedType] {
|
||||
return try fetchAll(db, SQLRequest<Self>(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))
|
||||
}
|
||||
|
||||
static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DecodedType? {
|
||||
return try fetchOne(db, SQLRequest<Self>(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 dbQueue.read { db in
|
||||
print("> Fetch from SQL")
|
||||
let bases = try Base.fetchAll(db, "SELECT * FROM base")
|
||||
let bases = try Base.fetchAll(db, sql: "SELECT * FROM base")
|
||||
for base in bases {
|
||||
print(base.description)
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
//: To run this playground:
|
||||
//:
|
||||
//: - Open GRDB.xcworkspace
|
||||
//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX
|
||||
//: - Build: menu Product > Build
|
||||
//: - Select the playground in the Playgrounds Group
|
||||
//: - Run the playground
|
||||
//:
|
||||
//: This sample code shows how to use GRDB to synchronize a database table
|
||||
//: with a JSON payload. We use as few SQL queries as possible:
|
||||
//:
|
||||
//: - Only one SELECT query.
|
||||
//: - One query per insert, delete, and update.
|
||||
//: - Useless UPDATE statements are avoided.
|
||||
|
||||
import Foundation
|
||||
import GRDB
|
||||
|
||||
|
||||
// Open an in-memory database that logs all its SQL statements
|
||||
|
||||
var configuration = Configuration()
|
||||
configuration.trace = { print($0) }
|
||||
let dbQueue = DatabaseQueue(configuration: configuration)
|
||||
|
||||
|
||||
// Create the database table to store the players
|
||||
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.column("name", .text)
|
||||
t.column("score", .integer)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Define the Player `Codable` that is a `FetchableRecord` and `MutablePersistableRecord`.
|
||||
struct Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
var id: Int64
|
||||
var name: String
|
||||
var score: Int
|
||||
|
||||
// Define database columns from CodingKeys
|
||||
private enum Columns {
|
||||
static let id = Column(CodingKeys.id)
|
||||
static let name = Column(CodingKeys.name)
|
||||
static let score = Column(CodingKeys.score)
|
||||
}
|
||||
|
||||
// Update a player id after it has been inserted in the database.
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
}
|
||||
}
|
||||
|
||||
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]
|
||||
}
|
||||
|
||||
// Synchronizes the players table with a JSON payload
|
||||
func synchronizePlayers(with jsonString: String, in db: Database) throws {
|
||||
let jsonData = jsonString.data(using: .utf8)!
|
||||
let dataToSync = try JSONDecoder().decode(PlayersToSync.self, from: jsonData)
|
||||
|
||||
// Sort new players to sync by id:
|
||||
let playersToSync = dataToSync.players.sorted { $0.id < $1.id }
|
||||
|
||||
// Sort database players by id:
|
||||
let players = try Player.orderedById().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).
|
||||
//
|
||||
// We'll delete, insert or update players, depending on their presence
|
||||
// in either lists.
|
||||
for mergeStep in sortedMerge(
|
||||
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
|
||||
{
|
||||
switch mergeStep {
|
||||
case .left(let player):
|
||||
// Delete database player without matching JSON player:
|
||||
try player.delete(db)
|
||||
case .right(var playerToSync):
|
||||
// Insert the Codable player without matching database player:
|
||||
try playerToSync.insert(db)
|
||||
case .common(let player, let playerToSync):
|
||||
// Update database player with its JSON counterpart:
|
||||
try playerToSync.updateChanges(db, from: player)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let jsonString1 = """
|
||||
{
|
||||
"players": [
|
||||
{ "id": 1, "name": "Arthur", "score": 1000},
|
||||
{ "id": 2, "name": "Barbara", "score": 2000},
|
||||
{ "id": 3, "name": "Craig", "score": 500},
|
||||
]
|
||||
}
|
||||
"""
|
||||
print("---\nImport \(jsonString1)")
|
||||
try dbQueue.inDatabase { db in
|
||||
// SELECT * FROM player ORDER BY id
|
||||
// INSERT INTO "player" ("id", "name", "score") VALUES (1,'Arthur',1000)
|
||||
// INSERT INTO "player" ("id", "name", "score") VALUES (2,'Barbara',2000)
|
||||
// INSERT INTO "player" ("id", "name", "score") VALUES (3,'Craig',500)
|
||||
try synchronizePlayers(with: jsonString1, in: db)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let jsonString2 = """
|
||||
{
|
||||
"players": [
|
||||
{ "id": 2, "name": "Barbara", "score": 3000},
|
||||
{ "id": 3, "name": "Craig", "score": 500},
|
||||
{ "id": 4, "name": "Daniel", "score": 1500},
|
||||
]
|
||||
}
|
||||
"""
|
||||
print("---\nImport \(jsonString2)")
|
||||
try dbQueue.inDatabase { db in
|
||||
// SELECT * FROM player ORDER BY id
|
||||
// DELETE FROM "player" WHERE "id"=1
|
||||
// UPDATE "player" SET "score"=3000 WHERE "id"=2
|
||||
// INSERT INTO "player" ("id", "name", "score") VALUES (4,'Daniel',1500)
|
||||
try synchronizePlayers(with: jsonString2, in: db)
|
||||
}
|
||||
}
|
||||
@@ -13,9 +13,9 @@ try! dbQueue.inDatabase { db in
|
||||
t.column("name", .text)
|
||||
}
|
||||
|
||||
try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Arthur"])
|
||||
try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Barbara"])
|
||||
try db.execute(sql: "INSERT INTO persons (name) VALUES (?)", arguments: ["Arthur"])
|
||||
try db.execute(sql: "INSERT INTO persons (name) VALUES (?)", arguments: ["Barbara"])
|
||||
|
||||
let names = try String.fetchAll(db, "SELECT name FROM persons")
|
||||
let names = try String.fetchAll(db, sql: "SELECT name FROM persons")
|
||||
print(names)
|
||||
}
|
||||
@@ -9,7 +9,7 @@
|
||||
//: Tour
|
||||
//: ======
|
||||
//:
|
||||
//: This playground is a tour of GRDB.
|
||||
//: This playground is a quick tour of GRDB.
|
||||
|
||||
import GRDB
|
||||
import CoreLocation
|
||||
@@ -26,44 +26,45 @@ let dbQueue = DatabaseQueue(configuration: configuration)
|
||||
//: Execute SQL queries
|
||||
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(
|
||||
"CREATE TABLE pointOfInterests (" +
|
||||
"id INTEGER PRIMARY KEY, " +
|
||||
"title TEXT, " +
|
||||
"favorite BOOLEAN NOT NULL, " +
|
||||
"latitude DOUBLE NOT NULL, " +
|
||||
"longitude DOUBLE NOT NULL" +
|
||||
")")
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE place (
|
||||
id INTEGER PRIMARY KEY,
|
||||
title TEXT,
|
||||
favorite BOOLEAN NOT NULL,
|
||||
latitude DOUBLE NOT NULL,
|
||||
longitude DOUBLE NOT NULL
|
||||
)
|
||||
""")
|
||||
|
||||
try db.execute(
|
||||
"INSERT INTO pointOfInterests (title, favorite, latitude, longitude) " +
|
||||
"VALUES (?, ?, ?, ?)",
|
||||
arguments: ["Paris", true, 48.85341, 2.3488])
|
||||
try db.execute(sql: """
|
||||
INSERT INTO place (title, favorite, latitude, longitude)
|
||||
VALUES (?, ?, ?, ?)
|
||||
""", arguments: ["Paris", true, 48.85341, 2.3488])
|
||||
let parisId = db.lastInsertedRowID
|
||||
}
|
||||
|
||||
|
||||
//: Fetch database rows and values
|
||||
|
||||
try dbQueue.inDatabase { db in
|
||||
let rows = try Row.fetchCursor(db, "SELECT * FROM pointOfInterests")
|
||||
try! dbQueue.inDatabase { db in
|
||||
let rows = try Row.fetchCursor(db, sql: "SELECT * FROM place")
|
||||
while let row = try rows.next() {
|
||||
let title: String = row["title"]
|
||||
let favorite: Bool = row["favorite"]
|
||||
let coordinate = CLLocationCoordinate2DMake(
|
||||
row["latitude"],
|
||||
row["longitude"])
|
||||
let coordinate = CLLocationCoordinate2D(
|
||||
latitude: row["latitude"],
|
||||
longitude: row["longitude"])
|
||||
print("Fetched", title, favorite, coordinate)
|
||||
}
|
||||
|
||||
let poiCount = try Int.fetchOne(db, "SELECT COUNT(*) FROM pointOfInterests")! // Int
|
||||
let poiTitles = try String.fetchAll(db, "SELECT title FROM pointOfInterests") // [String]
|
||||
let placeCount = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM place")! // Int
|
||||
let placeTitles = try String.fetchAll(db, sql: "SELECT title FROM place") // [String]
|
||||
}
|
||||
|
||||
|
||||
//: Insert and fetch records
|
||||
|
||||
struct PointOfInterest {
|
||||
struct Place {
|
||||
var id: Int64?
|
||||
var title: String?
|
||||
var favorite: Bool
|
||||
@@ -71,7 +72,7 @@ struct PointOfInterest {
|
||||
}
|
||||
|
||||
// Adopt FetchableRecord
|
||||
extension PointOfInterest : FetchableRecord {
|
||||
extension Place : FetchableRecord {
|
||||
init(row: Row) {
|
||||
id = row["id"]
|
||||
title = row["title"]
|
||||
@@ -83,12 +84,12 @@ extension PointOfInterest : FetchableRecord {
|
||||
}
|
||||
|
||||
// Adopt TableRecord
|
||||
extension PointOfInterest : TableRecord {
|
||||
static let databaseTableName = "pointOfInterests"
|
||||
extension Place : TableRecord {
|
||||
static let databaseTableName = "place"
|
||||
}
|
||||
|
||||
// Adopt MutablePersistableRecord
|
||||
extension PointOfInterest : MutablePersistableRecord {
|
||||
extension Place : MutablePersistableRecord {
|
||||
func encode(to container: inout PersistenceContainer) {
|
||||
container["id"] = id
|
||||
container["title"] = title
|
||||
@@ -103,7 +104,7 @@ extension PointOfInterest : MutablePersistableRecord {
|
||||
}
|
||||
|
||||
try dbQueue.inDatabase { db in
|
||||
var berlin = PointOfInterest(
|
||||
var berlin = Place(
|
||||
id: nil,
|
||||
title: "Berlin",
|
||||
favorite: false,
|
||||
@@ -116,7 +117,7 @@ try dbQueue.inDatabase { db in
|
||||
try berlin.update(db)
|
||||
|
||||
// Fetch from SQL
|
||||
let pois = try PointOfInterest.fetchAll(db, "SELECT * FROM pointOfInterests") // [PointOfInterest]
|
||||
let places = try Place.fetchAll(db, sql: "SELECT * FROM place") // [Place]
|
||||
|
||||
|
||||
//: Avoid SQL with the query interface:
|
||||
@@ -124,10 +125,10 @@ try dbQueue.inDatabase { db in
|
||||
let title = Column("title")
|
||||
let favorite = Column("favorite")
|
||||
|
||||
berlin = try PointOfInterest.filter(title == "Berlin").fetchOne(db)! // PointOfInterest
|
||||
let paris = try PointOfInterest.fetchOne(db, key: 1) // PointOfInterest?
|
||||
let favoritePois = try PointOfInterest // [PointOfInterest]
|
||||
.filter(favorite)
|
||||
berlin = try Place.filter(title == "Berlin").fetchOne(db)! // Place
|
||||
let paris = try Place.fetchOne(db, key: 1) // Place?
|
||||
let favoritePlaces = try Place // [Place]
|
||||
.filter(favorite == true)
|
||||
.order(title)
|
||||
.fetchAll(db)
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
//: To run this playground:
|
||||
//:
|
||||
//: - Open GRDB.xcworkspace
|
||||
//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX
|
||||
//: - Build: menu Product > Build
|
||||
//: - Select the playground in the Playgrounds Group
|
||||
//: - Run the playground
|
||||
|
||||
import GRDB
|
||||
|
||||
|
||||
// Create the databsae
|
||||
|
||||
let dbQueue = DatabaseQueue() // Memory database
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.registerMigration("createPerson") { db in
|
||||
try db.create(table: "person") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
}
|
||||
migrator.registerMigration("createPet") { db in
|
||||
try db.create(table: "pet") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
t.column("ownerId", .integer).references("person", onDelete: .cascade)
|
||||
}
|
||||
}
|
||||
try! migrator.migrate(dbQueue)
|
||||
|
||||
|
||||
//
|
||||
|
||||
class TableChangeObserver : NSObject, TransactionObserver {
|
||||
private var changedTableNames: Set<String> = []
|
||||
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
changedTableNames.insert(event.tableName)
|
||||
}
|
||||
|
||||
func databaseDidCommit(_ db: Database) {
|
||||
print("Changed table(s): \(changedTableNames.joined(separator: ", "))")
|
||||
changedTableNames = []
|
||||
}
|
||||
|
||||
func databaseDidRollback(_ db: Database) {
|
||||
changedTableNames = []
|
||||
}
|
||||
}
|
||||
|
||||
let observer = TableChangeObserver()
|
||||
dbQueue.add(transactionObserver: observer)
|
||||
|
||||
|
||||
//
|
||||
|
||||
print("-- Changes without transaction")
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: "INSERT INTO person (name) VALUES (?)", arguments: ["Arthur"])
|
||||
let arthurId = db.lastInsertedRowID
|
||||
try db.execute(sql: "INSERT INTO person (name) VALUES (?)", arguments: ["Barbara"])
|
||||
try db.execute(sql: "INSERT INTO pet (ownerId, name) VALUES (?, ?)", arguments: [arthurId, "Barbara"])
|
||||
try db.execute(sql: "DELETE FROM person WHERE id = ?", arguments: [arthurId])
|
||||
}
|
||||
|
||||
print("-- Rollbacked changes")
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute(sql: "INSERT INTO person (name) VALUES ('Arthur')")
|
||||
try db.execute(sql: "INSERT INTO person (name) VALUES ('Barbara')")
|
||||
return .rollback
|
||||
}
|
||||
|
||||
|
||||
print("-- Changes wrapped in a transaction")
|
||||
try dbQueue.write { db in
|
||||
try db.execute(sql: "DELETE FROM person")
|
||||
try db.execute(sql: "INSERT INTO person (name) VALUES (?)", arguments: ["Arthur"])
|
||||
let arthurId = db.lastInsertedRowID
|
||||
try db.execute(sql: "INSERT INTO person (name) VALUES (?)", arguments: ["Barbara"])
|
||||
try db.execute(sql: "INSERT INTO pet (ownerId, name) VALUES (?, ?)", arguments: [arthurId, "Barbara"])
|
||||
try db.execute(sql: "DELETE FROM person WHERE id = ?", arguments: [arthurId])
|
||||
}
|
||||
@@ -15,18 +15,14 @@ To release a new GRDB version:
|
||||
- Update GRDB version number and release date in:
|
||||
- Makefile
|
||||
- CHANGELOG.md
|
||||
- Documentation/CustomSQLiteBuilds.md
|
||||
- GRDB.swift.podspec
|
||||
- GRDBCipher.podspec
|
||||
- README.md
|
||||
- Support/Info.plist
|
||||
- Commit and tag
|
||||
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
|
||||
- Push to the master branch
|
||||
- `pod trunk push --allow-warnings GRDB.swift.podspec`
|
||||
- `pod trunk push --allow-warnings GRDBCipher.podspec`
|
||||
- `make doc`, and update index.html in the `gh-pages` branch
|
||||
- Update http://github.com/groue/GRDBDemo
|
||||
- Update http://github.com/groue/WWDCCompanion
|
||||
- Update [performance comparison](https://github.com/groue/GRDB.swift/wiki/Performance):
|
||||
|
||||
|
||||
@@ -0,0 +1,418 @@
|
||||
SQL Interpolation
|
||||
=================
|
||||
|
||||
Your SQL skills are [welcomed] throughout GRDB. Yet writing raw SQL presents commonplace challenges. For example, you want to make sure your queries don't break whenever the database schema changes as you ship new versions of your application. When you inject user values in the database, you have to use statement arguments, and it is easy to make a mistake in the process.
|
||||
|
||||
The query below exemplifies this situation. It even contains a bug that is not quite easy to spot:
|
||||
|
||||
```swift
|
||||
try db.execute(
|
||||
sql: """
|
||||
UPDATE student
|
||||
SET firstName = ?, lastName = ?, department = ?, birthDate = ?,
|
||||
registrationDate = ?, mainTeacherId = ?
|
||||
WHERE id = ?
|
||||
""",
|
||||
arguments: [firstName, lastName, department, birthDate,
|
||||
registrationDate, mainTeacherId])
|
||||
|
||||
```
|
||||
|
||||
SQL Interpolation is an answer to these troubles. It is available in Swift 5.
|
||||
|
||||
- [Introduction]
|
||||
- [SQLLiteral]
|
||||
- [SQL Interpolation and Record Protocols]
|
||||
- [SQL Interpolation Reference]
|
||||
|
||||
|
||||
## Introduction
|
||||
|
||||
**SQL Interpolation** lets you embed values in your SQL queries by wrapping them inside `\(` and `)`:
|
||||
|
||||
```swift
|
||||
let name: String = ...
|
||||
let id: Int64 = ...
|
||||
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
|
||||
```
|
||||
|
||||
SQL interpolation looks and feel just like regular [String interpolation]:
|
||||
|
||||
```swift
|
||||
let name = "World"
|
||||
print("Hello \(name)!") // prints "Hello World!"
|
||||
```
|
||||
|
||||
The difference is that it generates valid SQL which does not suffer from syntax errors or [SQL injection]. For example, you do not need to validate input or process single quotes:
|
||||
|
||||
```swift
|
||||
// Executes `UPDATE player SET name = 'O''Brien' WHERE id = 42`
|
||||
let name = "O'Brien"
|
||||
let id = 42
|
||||
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
|
||||
```
|
||||
|
||||
Under the hood, SQL interpolation generates a plain SQL string. It runs exactly as below:
|
||||
|
||||
```swift
|
||||
try db.execute(sql: "UPDATE player SET name = ? WHERE id = ?", arguments: [name, id])
|
||||
```
|
||||
|
||||
Plain SQL strings are indeed still available, and SQL interpolation only kicks in when you ask for it. There is a simple rule to remember:
|
||||
|
||||
- For plain SQL strings, use the `sql` argument label:
|
||||
|
||||
```swift
|
||||
try db.execute(sql: "UPDATE player SET name = ? WHERE id = ?", arguments: [name, id])
|
||||
```
|
||||
|
||||
- For SQL interpolation, use the `literal` argument label:
|
||||
|
||||
```swift
|
||||
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
|
||||
```
|
||||
|
||||
|
||||
## SQLLiteral
|
||||
|
||||
**SQLLiteral** is the type that looks like a plain String, but profits from SQL interpolation:
|
||||
|
||||
```swift
|
||||
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
try db.execute(literal: query)
|
||||
```
|
||||
|
||||
**SQLLiteral is not a Swift String.** You can not use the `execute(literal:)` method with a String argument:
|
||||
|
||||
```swift
|
||||
// Compiler error:
|
||||
// Cannot convert value of type 'String' to expected argument type 'SQLLiteral'
|
||||
let query = "UPDATE player SET name = \(name) WHERE id = \(id)" // a String
|
||||
try db.execute(literal: query)
|
||||
```
|
||||
|
||||
SQLLiteral can build your queries step by step, with regular operators and methods:
|
||||
|
||||
```swift
|
||||
// +, +=, append
|
||||
var query: SQLLiteral = "UPDATE player "
|
||||
query += "SET name = \(name) "
|
||||
query.append(literal: "WHERE id = \(id)")
|
||||
|
||||
// joined(), joined(separator:)
|
||||
let components: [SQLLiteral] = [
|
||||
"UPDATE player",
|
||||
"SET name = \(name)",
|
||||
"WHERE id = \(id)"
|
||||
]
|
||||
let query = components.joined(separator: " ")
|
||||
```
|
||||
|
||||
Extract the plain SQL string from a literal:
|
||||
|
||||
```swift
|
||||
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
print(query.sql) // prints "UPDATE player SET name = ? WHERE id = ?"
|
||||
print(query.arguments) // prints ["O'Brien", 42]
|
||||
```
|
||||
|
||||
Build a literal from a plain SQL string:
|
||||
|
||||
```swift
|
||||
let query = SQLLiteral(
|
||||
sql: "UPDATE player SET name = ? WHERE id = ?",
|
||||
arguments: [name, id])
|
||||
```
|
||||
|
||||
SQLLiteral can embed any [value], as we have seen above, but not only. Please keep on reading the next chapter, or jump directly to the [SQL Interpolation Reference].
|
||||
|
||||
|
||||
## SQL Interpolation and Record Protocols
|
||||
|
||||
The [record protocols] extend your application types with database abilities.
|
||||
|
||||
**A record type knows everything about the schema of its underlying database table**. With the [TableRecord] protocol, the `databaseTableName` property contains the table name. With the [Decodable] protocol, the [CodingKeys] enum contain the column names. And with [FetchableRecord], you can decode raw database rows.
|
||||
|
||||
SQL Interpolation puts this knowledge to good use, so that you can build robust queries that consistently use correct table and column names:
|
||||
|
||||
```swift
|
||||
struct Player {
|
||||
var id: Int64
|
||||
var name: String
|
||||
var score: Int?
|
||||
}
|
||||
|
||||
extension Player: Decodable, FetchableRecord, TableRecord {
|
||||
/// Deletes all player with no score
|
||||
static func deleteAllWithoutScore(_ db: Database) throws {
|
||||
try db.execute(literal: "DELETE FROM \(self) WHERE \(CodingKeys.score) IS NULL")
|
||||
}
|
||||
|
||||
/// The player with a given id
|
||||
static func filter(id: Int64) -> SQLRequest<Player> {
|
||||
return "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)"
|
||||
}
|
||||
|
||||
/// The maximum score
|
||||
static func maximumScore() -> SQLRequest<Int> {
|
||||
return "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())
|
||||
"""
|
||||
}
|
||||
|
||||
/// A complex request
|
||||
static func complexRequest() -> SQLRequest<Player> {
|
||||
let query: SQLLiteral = "SELECT * FROM \(self) "
|
||||
query += "JOIN \(Team.self) ON ..."
|
||||
query += "GROUP BY ..."
|
||||
return SQLRequest(literal: query)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Let's breakdown each one of those methods.
|
||||
|
||||
- `deleteAllWithoutScore(_:)`
|
||||
|
||||
```swift
|
||||
extension Player: Decodable, FetchableRecord, TableRecord {
|
||||
/// Deletes all player with no score
|
||||
static func deleteAllWithoutScore(_ db: Database) throws {
|
||||
try db.execute(literal: "DELETE FROM \(self) WHERE \(CodingKeys.score) IS NULL")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Usage:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// DELETE FROM player WHERE score IS NULL
|
||||
try Player.deleteAllWithoutScore(db)
|
||||
}
|
||||
```
|
||||
|
||||
`DELETE FROM \(self) ...` embeds the Player type itself. Since Player adopts the [TableRecord] protocol, this embeds `Player.databaseTableName` in the SQL query.
|
||||
|
||||
`... \(CodingKeys.score) IS NULL` embeds CodingKeys.score. This one has been synthesized by the Swift compiler because Player adopts the Decodable protocol. It embeds the column name in the SQL query.
|
||||
|
||||
- `filter(id:)`
|
||||
|
||||
```swift
|
||||
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)"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Usage:
|
||||
|
||||
```swift
|
||||
let player = try dbQueue.read { db in
|
||||
// SELECT * player WHERE id = 42
|
||||
try Player.filter(id: 42).fetchOne(db) // Player?
|
||||
}
|
||||
```
|
||||
|
||||
The return type of this method is `SQLRequest<Player>`. It is one of the GRDB [request types]. And it profits from SQL interpolation: this is why this method can simply return an "SQL literal"".
|
||||
|
||||
It embeds `\(self)` (the Player type which adopts the TableRecord protocol) and `\(CodingKeys.id)` (the coding key synthesized by the Decodable protocol), and `\(id)` (a [value]).
|
||||
|
||||
- `filter(ids:)`
|
||||
|
||||
```swift
|
||||
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)"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Usage:
|
||||
|
||||
```swift
|
||||
let players = try dbQueue.read { db in
|
||||
// SELECT * player WHERE id IN (1, 2, 3)
|
||||
try Player.filter(ids: [1, 2, 3]).fetchAll(db) // [Player]
|
||||
}
|
||||
```
|
||||
|
||||
It embeds `\(ids)`, an array of ids. All [value] sequences are supported (arrays, sets, etc.) Empty sequences are supported as well, with both `IN` and `NOT IN` SQL operators.
|
||||
|
||||
- `maximumScore()`
|
||||
|
||||
```swift
|
||||
extension Player: Decodable, FetchableRecord, TableRecord {
|
||||
/// The maximum score
|
||||
static func maximumScore() -> SQLRequest<Int> {
|
||||
return "SELECT MAX(\(CodingKeys.score)) FROM \(self)"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Usage:
|
||||
|
||||
```swift
|
||||
let maximumScore = try dbQueue.read { db in
|
||||
// SELECT MAX(score) FROM player
|
||||
try Player.maximumScore().fetchOne(db) // Int?
|
||||
}
|
||||
```
|
||||
|
||||
The result is `SQLRequest<Int>`, unlike previous requests of type `SQLRequest<Player>`. SQLRequest accepts any fetchable type (database [row], simple [value], or custom [record]).
|
||||
|
||||
- `leaders()`
|
||||
|
||||
```swift
|
||||
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())
|
||||
"""
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Usage:
|
||||
|
||||
```swift
|
||||
let leaders = try dbQueue.read { db in
|
||||
// SELECT * FROM player
|
||||
// WHERE score = (SELECT MAX(score) FROM player)
|
||||
try Player.leaders().fetchAll(db) // [Player]
|
||||
}
|
||||
```
|
||||
|
||||
This request embeds `\(maximumScore())`, the `SQLRequest<Int>` returned by the `maximumScore` method. After values, coding keys, and types that adopt the TableRecord protocol, this ends our quick tour of things you can embed between `\(` and `)`. Check out the [SQL Interpolation Reference] for the full list of supported interpolations.
|
||||
|
||||
- `complexRequest()`
|
||||
|
||||
```swift
|
||||
extension Player: Decodable, FetchableRecord, TableRecord {
|
||||
/// A complex request
|
||||
static func complexRequest() -> SQLRequest<Player> {
|
||||
let query: SQLLiteral = "SELECT * FROM \(self) "
|
||||
query += "JOIN \(Team.self) ON ..."
|
||||
query += "GROUP BY ..."
|
||||
return SQLRequest(literal: query)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This last request shows how to build an SQLRequest from an [SQLLiteral]. You will need SQLLiteral when the request can not be expressed in a single "SQL literal".
|
||||
|
||||
|
||||
|
||||
## SQL Interpolation Reference
|
||||
|
||||
This chapter lists all kinds of supported interpolations.
|
||||
|
||||
- Types adopting the [TableRecord] protocol:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player
|
||||
extension Player: TableRecord { }
|
||||
"SELECT * FROM \(Player.self)"
|
||||
|
||||
// INSERT INTO player ...
|
||||
let player: Player = ...
|
||||
"INSERT INTO \(tableOf: player) ..."
|
||||
```
|
||||
|
||||
- [Expressions] and [values]:
|
||||
|
||||
```swift
|
||||
// SELECT name FROM player
|
||||
"SELECT \(Column("name")) FROM player"
|
||||
|
||||
// SELECT (score + 100) AS points FROM player
|
||||
let bonus = 100
|
||||
"SELECT \(Column("score") + bonus) AS points FROM player"
|
||||
|
||||
// SELECT (score + 100) AS points FROM player
|
||||
"SELECT (score + \(bonus)) AS points FROM player"
|
||||
```
|
||||
|
||||
- Coding keys:
|
||||
|
||||
```swift
|
||||
// SELECT name FROM player
|
||||
"SELECT \(CodingKeys.name) FROM player"
|
||||
```
|
||||
|
||||
- Sequences:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player WHERE id IN (1, 2, 3)
|
||||
let ids = [1, 2, 3]
|
||||
"SELECT * FROM player WHERE id IN \(ids)"
|
||||
```
|
||||
|
||||
- Orderings:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player ORDER BY name DESC
|
||||
"SELECT * FROM player WHERE id IN \(Column("name").desc)"
|
||||
```
|
||||
|
||||
- SQLRequest:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player WHERE score = (SELECT MAX(score) FROM player)
|
||||
let subQuery: SQLRequest<Int> = "SELECT MAX(score) FROM player"
|
||||
"SELECT * FROM player WHERE score = \(subQuery)"
|
||||
```
|
||||
|
||||
- SQLLiteral:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player WHERE name = 'O''Brien'
|
||||
let condition: SQLLiteral = "name = \("O'Brien")"
|
||||
"SELECT * FROM player WHERE \(literal: condition)"
|
||||
```
|
||||
|
||||
- Plain SQL strings and eventual arguments:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player
|
||||
"SELECT * FROM \(sql: "player")"
|
||||
|
||||
// SELECT * FROM player WHERE name = 'O''Brien'
|
||||
"SELECT * FROM player WHERE \(sql: "name = ?", arguments: ["O'Brien"])"
|
||||
```
|
||||
|
||||
[Introduction]: #introduction
|
||||
[SQLLiteral]: #sqlliteral
|
||||
[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
|
||||
[SQL injection]: ../README.md#avoiding-sql-injection
|
||||
[record protocols]: ../README.md#record-protocols-overview
|
||||
[FetchableRecord]: ../README.md#fetchablerecord-protocol
|
||||
[TableRecord]: ../README.md#tablerecord-protocol
|
||||
[Decodable]: ../README.md#codable-records
|
||||
[CodingKeys]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
|
||||
[value]: ../README.md#values
|
||||
[values]: ../README.md#values
|
||||
[request types]: ../README.md#custom-requests
|
||||
[row]: ../README.md#row-queries
|
||||
[record]: ../README.md#records
|
||||
[Expressions]: ../README.md#expressions
|
||||
[welcomed]: ../README.md#sqlite-api
|
||||
[SE-0228 Fix ExpressibleByStringInterpolation]: https://github.com/apple/swift-evolution/blob/master/proposals/0228-fix-expressiblebystringinterpolation.md
|
||||
@@ -69,7 +69,7 @@ By adopting the [FetchableRecord] protocol, places can be loaded from SQL reques
|
||||
|
||||
```swift
|
||||
extension Place: FetchableRecord { ... }
|
||||
let places = try Place.fetchAll(db, "SELECT * FROM place") // [Place]
|
||||
let places = try Place.fetchAll(db, sql: "SELECT * FROM place") // [Place]
|
||||
```
|
||||
|
||||
Add the [TableRecord] protocol, and SQL requests are generated for you:
|
||||
@@ -86,8 +86,12 @@ extension Place: PersistableRecord { ... }
|
||||
try place.delete(db)
|
||||
```
|
||||
|
||||
For your convenience, those record protocols can be derived from the [Decodable and Encodable](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types) protocols of the standard library. [Codable records] are even given free support for JSON columns and other niceties.
|
||||
|
||||
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,7 +117,7 @@ let players = try Player.fetchAll(db)
|
||||
|
||||
**Fetched records behave just like an in-memory cache of the database content.** Your application is free to decide, on its own, how it should handle the lifetime of those cached values: by ignoring future database changes, by observing database changes and react accordingly, or in any way deemed relevant.
|
||||
|
||||
There are several ways to be notified of database changes. You can build on top of the low-level [TransactionObserver] protocol. Or you can use [FetchedRecordsController], which looks a lot like Core Data's NSFetchedResultsController, and is able to animate table and collection views. And don't forget [RxGRDB], a set of reactive extensions based on [RxSwift]:
|
||||
There are several ways to be notified of database changes. You can build on top of the fundamental but low-level [TransactionObserver] protocol. Usually, you'll use [ValueObservation], which notifies fresh values after each database change. And don't forget [GRDBCombine] and [RxGRDB], two sets of reactive extensions based on [Combine] and [RxSwift]:
|
||||
|
||||
```swift
|
||||
Player.all().rx
|
||||
@@ -168,16 +172,23 @@ 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
|
||||
|
||||
SQL is a weird language. Born in the 70s, easy to [misuse](https://xkcd.com/327/), feared by some developers, despised by others, and yet wonderfully concise and powerful.
|
||||
|
||||
GRDB [query interface] and [associations] can generate SQL for you:
|
||||
GRDB [records], [query interface] and [associations] can generate SQL for you:
|
||||
|
||||
```swift
|
||||
// UPDATE player SET score = 950 WHERE id = 42
|
||||
try player.updateChanges {
|
||||
$0.score += 10
|
||||
}
|
||||
|
||||
// SELECT * FROM player ORDER BY score DESC LIMIT 10
|
||||
let bestPlayers: [Player] = try Player
|
||||
.order(scoreColumn.desc)
|
||||
@@ -200,19 +211,48 @@ let bookInfos: [BookInfo] = BookInfo.fetchAll(db, request)
|
||||
But you can always switch to SQL when you want to:
|
||||
|
||||
```swift
|
||||
let bestPlayers: [Player] = try Player.fetchAll(db, """
|
||||
try db.execute(
|
||||
sql: "UPDATE player SET score = ? WHERE id = ?",
|
||||
arguments: [950, 42])
|
||||
|
||||
let bestPlayers: [Player] = try Player.fetchAll(db, sql: """
|
||||
SELECT * FROM player ORDER BY score DESC LIMIT 10
|
||||
""")
|
||||
|
||||
let maximumScore: Int? = try Int.fetchOne(db, """
|
||||
let maximumScore: Int? = try Int.fetchOne(db, sql: """
|
||||
SELECT MAX(score) FROM player
|
||||
""")
|
||||
```
|
||||
|
||||
With Swift 5, you can profit from **SQL interpolation**. It lets you build SQL queries from natural looking strings, but without any risk of syntax error or [SQL injection](https://xkcd.com/327/):
|
||||
|
||||
```swift
|
||||
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)"
|
||||
}
|
||||
}
|
||||
|
||||
let player = try Player.filter(name: "Arthur O'Brien").fetchOne(db)
|
||||
```
|
||||
|
||||
Custom SQL requests as the one above are welcome in database observation tools like the built-in [ValueObservation], or the companion libraries [GRDBCombine] and [RxGRDB]:
|
||||
|
||||
```swift
|
||||
// RxGRDB
|
||||
Player.filter(name: "Arthur O'Brien").rx
|
||||
.fetchOne(in: dbQueue)
|
||||
.subscribe(onNext: { (player: Player?) in
|
||||
print("Player has changed")
|
||||
})
|
||||
```
|
||||
|
||||
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>("""
|
||||
let bookInfos: [BookInfo] = SQLRequest<BookInfo>(sql: """
|
||||
SELECT book.*, author.*
|
||||
FROM book
|
||||
LEFT JOIN author ON author.id = book.authorId
|
||||
@@ -230,7 +270,7 @@ let bookInfos: [BookInfo] = SQLRequest<BookInfo>("""
|
||||
In performance-critical sections, you may want to deal with raw database rows, and fetch [lazy cursors](../README.md#cursors) instead of arrays:
|
||||
|
||||
```swift
|
||||
let rows = try Row.fetchCursor(db, "SELECT id, name, score FROM player")
|
||||
let rows = try Row.fetchCursor(db, sql: "SELECT id, name, score FROM player")
|
||||
while let row = try rows.next() {
|
||||
let id: Int64 = row[0]
|
||||
let name: String = row[1]
|
||||
@@ -238,28 +278,6 @@ while let row = try rows.next() {
|
||||
}
|
||||
```
|
||||
|
||||
When you feel like your code clarity would be enhanced by hiding your custom SQL in a dedicated method, you can build [custom requests](../README.md#custom-requests):
|
||||
|
||||
```swift
|
||||
extension Player {
|
||||
static func customRequest(...) -> SQLRequest<Player> {
|
||||
return SQLRequest<Player>("SELECT ...", arguments: ...)
|
||||
}
|
||||
}
|
||||
|
||||
let players = try Player.customRequest(...).fetchAll(db)
|
||||
```
|
||||
|
||||
Those custom requests are welcome in database observation tools like [FetchedRecordsController] and [RxGRDB]:
|
||||
|
||||
```swift
|
||||
Player.customRequest(...).rx
|
||||
.fetchAll(in: dbQueue)
|
||||
.subscribe(onNext: { players: [Player] in
|
||||
print("Players have changed")
|
||||
})
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
If this little tour of GRDB has convinced you, the real trip starts here: [GRDB].
|
||||
@@ -273,7 +291,7 @@ Happy GRDB! :gift:
|
||||
[DatabasePool]: ../README.md#database-pools
|
||||
[Diesel]: http://diesel.rs
|
||||
[FCModel]: https://github.com/marcoarment/FCModel
|
||||
[FetchedRecordsController]: ../README.md#fetchedrecordscontroller
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[Fluent]: https://github.com/vapor/fluent
|
||||
[FMDB]: http://github.com/ccgus/fmdb
|
||||
[GRDB]: http://github.com/groue/GRDB.swift
|
||||
@@ -283,6 +301,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
|
||||
@@ -290,3 +310,5 @@ Happy GRDB! :gift:
|
||||
[TransactionObserver]: ../README.md#transactionobserver-protocol
|
||||
[query interface]: ../README.md#the-query-interface
|
||||
[associations]: AssociationsBasics.md
|
||||
[Codable records]: ../README.md#codable-records
|
||||
[records]: ../README.md#records
|
||||
@@ -1,20 +1,35 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '3.2.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
s.homepage = 'https://github.com/groue/GRDB.swift'
|
||||
s.author = { 'Gwendal Roué' => 'gr@pierlis.com' }
|
||||
s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" }
|
||||
s.module_name = 'GRDB'
|
||||
|
||||
s.ios.deployment_target = '8.0'
|
||||
s.osx.deployment_target = '10.9'
|
||||
s.watchos.deployment_target = '2.0'
|
||||
|
||||
s.source_files = 'GRDB/**/*.swift', 'Support/*.h'
|
||||
s.module_map = 'Support/module.modulemap'
|
||||
s.framework = 'Foundation'
|
||||
s.library = 'sqlite3'
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '4.6.2'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
s.homepage = 'https://github.com/groue/GRDB.swift'
|
||||
s.author = { 'Gwendal Roué' => 'gr@pierlis.com' }
|
||||
s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" }
|
||||
s.module_name = 'GRDB'
|
||||
|
||||
s.swift_versions = ['4.2', '5.0']
|
||||
s.ios.deployment_target = '9.0'
|
||||
s.osx.deployment_target = '10.9'
|
||||
s.watchos.deployment_target = '2.0'
|
||||
s.tvos.deployment_target = '9.0'
|
||||
s.default_subspec = 'standard'
|
||||
|
||||
s.subspec 'standard' do |ss|
|
||||
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/grdb_config.h'
|
||||
ss.framework = 'Foundation'
|
||||
ss.dependency 'SQLCipher', '>= 3.4.0'
|
||||
ss.xcconfig = {
|
||||
'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_HAS_CODEC -D GRDBCIPHER -D SQLITE_ENABLE_FTS5',
|
||||
'OTHER_CFLAGS' => '$(inherited) -DSQLITE_HAS_CODEC -DGRDBCIPHER -DSQLITE_ENABLE_FTS5',
|
||||
'GCC_PREPROCESSOR_DEFINITIONS' => '$(inherited) SQLITE_HAS_CODEC=1 GRDBCIPHER=1 SQLITE_ENABLE_FTS5=1'
|
||||
}
|
||||
end
|
||||
end
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0930"
|
||||
LastUpgradeVersion = "1030"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0930"
|
||||
LastUpgradeVersion = "1030"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0930"
|
||||
LastUpgradeVersion = "1030"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -10,7 +10,6 @@
|
||||
buildConfiguration = "Release"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
@@ -31,7 +30,6 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0930"
|
||||
LastUpgradeVersion = "1030"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0930"
|
||||
LastUpgradeVersion = "1030"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0910"
|
||||
LastUpgradeVersion = "1030"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -14,10 +14,10 @@
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56B037261E8E31D0003B6DA4"
|
||||
BuildableName = "GRDBiOS.app"
|
||||
BlueprintName = "GRDBiOS"
|
||||
ReferencedContainer = "container:GRDBiOS.xcodeproj">
|
||||
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBtvOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
@@ -26,17 +26,27 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
codeCoverageEnabled = "YES"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "AAA4DD07230F262000C74B15"
|
||||
BuildableName = "GRDBtvOSTests.xctest"
|
||||
BlueprintName = "GRDBtvOSTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56B037261E8E31D0003B6DA4"
|
||||
BuildableName = "GRDBiOS.app"
|
||||
BlueprintName = "GRDBiOS"
|
||||
ReferencedContainer = "container:GRDBiOS.xcodeproj">
|
||||
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBtvOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
@@ -46,23 +56,21 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56B037261E8E31D0003B6DA4"
|
||||
BuildableName = "GRDBiOS.app"
|
||||
BlueprintName = "GRDBiOS"
|
||||
ReferencedContainer = "container:GRDBiOS.xcodeproj">
|
||||
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBtvOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
@@ -72,16 +80,15 @@
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56B037261E8E31D0003B6DA4"
|
||||
BuildableName = "GRDBiOS.app"
|
||||
BlueprintName = "GRDBiOS"
|
||||
ReferencedContainer = "container:GRDBiOS.xcodeproj">
|
||||
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBtvOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
@@ -2,7 +2,7 @@
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
<Group
|
||||
location = "group:Playgrounds"
|
||||
location = "group:Documentation/Playgrounds"
|
||||
name = "Playgrounds">
|
||||
<FileRef
|
||||
location = "group:Tour.playground">
|
||||
@@ -10,9 +10,6 @@
|
||||
<FileRef
|
||||
location = "group:JSONSynchronization.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Record.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:TransactionObserver.playground">
|
||||
</FileRef>
|
||||
@@ -20,7 +17,7 @@
|
||||
location = "group:Issue156.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:/Users/groue/Documents/git/groue/GRDB.swift/Playgrounds/CustomizedDecodingOfDatabaseRows.playground">
|
||||
location = "group:CustomizedDecodingOfDatabaseRows.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Associations.playground">
|
||||
@@ -50,13 +47,10 @@
|
||||
<FileRef
|
||||
location = "group:GRDBCustom.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:GRDBCipher.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
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,8 +1,11 @@
|
||||
import Foundation
|
||||
import Dispatch
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// Configuration for a DatabaseQueue or DatabasePool.
|
||||
@@ -72,16 +75,34 @@ public struct Configuration {
|
||||
/// Default: nil
|
||||
public var trace: TraceFunction?
|
||||
|
||||
|
||||
// MARK: - Encryption
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
/// The passphrase for encrypted database.
|
||||
// TODO: remove when the deprecated passphrase turns unavailable.
|
||||
var _passphrase: String?
|
||||
|
||||
/// The passphrase for the encrypted database.
|
||||
///
|
||||
/// Default: nil
|
||||
public var passphrase: String?
|
||||
@available(*, deprecated, message: "Use Database.usePassphrase(_:) in Configuration.prepareDatabase instead.")
|
||||
public var passphrase: String? {
|
||||
get { return _passphrase }
|
||||
set { _passphrase = newValue }
|
||||
}
|
||||
#endif
|
||||
|
||||
// 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:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase = { db in
|
||||
/// try db.execute(sql: "PRAGMA kdf_iter = 10000")
|
||||
/// }
|
||||
public var prepareDatabase: ((Database) throws -> Void)?
|
||||
|
||||
// MARK: - Transactions
|
||||
|
||||
@@ -136,23 +157,57 @@ public struct Configuration {
|
||||
/// Default: 5
|
||||
public var maximumReaderCount: Int = 5
|
||||
|
||||
/// The quality of service class for the work performed by the database.
|
||||
///
|
||||
/// The quality of service is ignored if you supply a target queue.
|
||||
///
|
||||
/// Default: .default (.unspecified on macOS < 10.10)
|
||||
public var qos: DispatchQoS
|
||||
|
||||
/// 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
|
||||
|
||||
// MARK: - Factory Configuration
|
||||
|
||||
/// Creates a factory configuration
|
||||
public init() { }
|
||||
public init() {
|
||||
if #available(OSX 10.10, *) {
|
||||
qos = .default
|
||||
} else {
|
||||
qos = .unspecified
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
func makeDispatchQueue(defaultLabel: String, purpose: String? = nil) -> DispatchQueue {
|
||||
let label = (self.label ?? defaultLabel) + (purpose.map { "." + $0 } ?? "")
|
||||
if let targetQueue = targetQueue {
|
||||
return DispatchQueue(label: label, target: targetQueue)
|
||||
} else {
|
||||
return DispatchQueue(label: label, qos: qos)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A tracing function that takes an SQL string.
|
||||
|
||||
@@ -14,8 +14,9 @@
|
||||
extension Array {
|
||||
/// Creates an array containing the elements of a cursor.
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'bar'")
|
||||
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
|
||||
/// let strings = try Array(cursor) // ["foo", "bar"]
|
||||
@inlinable
|
||||
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
|
||||
self.init()
|
||||
while let element = try cursor.next() {
|
||||
@@ -28,7 +29,10 @@ 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>> {
|
||||
public func flatMap<SegmentOfResult: Cursor>(
|
||||
_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult)
|
||||
-> FlattenCursor<MapCursor<AnyCursor<Iterator.Element>, SegmentOfResult>>
|
||||
{
|
||||
return AnyCursor(self).flatMap(transform)
|
||||
}
|
||||
}
|
||||
@@ -36,7 +40,7 @@ extension Sequence {
|
||||
extension Set {
|
||||
/// Creates a set containing the elements of a cursor.
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'foo'")
|
||||
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'foo'")
|
||||
/// let strings = try Set(cursor) // ["foo"]
|
||||
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
|
||||
self.init()
|
||||
@@ -75,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
|
||||
|
||||
@@ -85,6 +89,12 @@ public protocol Cursor : class {
|
||||
}
|
||||
|
||||
extension Cursor {
|
||||
/// Returns a Boolean value indicating whether the cursor contains
|
||||
/// an element.
|
||||
public func isEmpty() throws -> Bool {
|
||||
return try next() == nil
|
||||
}
|
||||
|
||||
/// Returns a Boolean value indicating whether the cursor contains an
|
||||
/// element that satisfies the given predicate.
|
||||
///
|
||||
@@ -105,7 +115,7 @@ extension Cursor {
|
||||
/// Returns a cursor of pairs (n, x), where n represents a consecutive
|
||||
/// integer starting at zero, and x represents an element of the cursor.
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'bar'")
|
||||
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
|
||||
/// let c = cursor.enumerated()
|
||||
/// while let (n, x) = c.next() {
|
||||
/// print("\(n): \(x)")
|
||||
@@ -134,15 +144,12 @@ 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> {
|
||||
public func compactMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?)
|
||||
-> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult>
|
||||
{
|
||||
return map(transform).filter { $0 != nil }.map { $0! }
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "compactMap")
|
||||
public func flatMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult> {
|
||||
return compactMap(transform)
|
||||
}
|
||||
|
||||
/// Returns a cursor that skips any initial elements that satisfy
|
||||
/// `predicate`.
|
||||
///
|
||||
@@ -188,7 +195,7 @@ extension Cursor {
|
||||
public func dropFirst() -> DropFirstCursor<Self> {
|
||||
return dropFirst(1)
|
||||
}
|
||||
|
||||
|
||||
/// Returns an array containing all but the given number of final
|
||||
/// elements.
|
||||
///
|
||||
@@ -241,13 +248,19 @@ extension Cursor {
|
||||
|
||||
/// 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>>> {
|
||||
public func flatMap<SegmentOfResult>(_ transform: @escaping (Element) throws -> SegmentOfResult)
|
||||
-> FlattenCursor<MapCursor<Self, AnyCursor<SegmentOfResult.Element>>>
|
||||
where SegmentOfResult: Sequence
|
||||
{
|
||||
return 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>> {
|
||||
public func flatMap<SegmentOfResult>(_ transform: @escaping (Element) throws -> SegmentOfResult)
|
||||
-> FlattenCursor<MapCursor<Self, SegmentOfResult>>
|
||||
where SegmentOfResult: Cursor
|
||||
{
|
||||
return map(transform).joined()
|
||||
}
|
||||
|
||||
@@ -501,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
|
||||
@@ -537,11 +550,11 @@ public final class AnyCursor<Element> : Cursor {
|
||||
}
|
||||
|
||||
/// :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
|
||||
@@ -564,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
|
||||
@@ -594,7 +607,7 @@ public final class DropWhileCursor<Base: Cursor> : Cursor {
|
||||
/// To create an instance of `EnumeratedCursor`, call the `enumerated()` method
|
||||
/// on a cursor:
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'bar'")
|
||||
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
|
||||
/// let c = cursor.enumerated()
|
||||
/// while let (n, x) = c.next() {
|
||||
/// print("\(n): \(x)")
|
||||
@@ -603,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
|
||||
|
||||
@@ -626,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
|
||||
|
||||
@@ -654,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?
|
||||
|
||||
@@ -684,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
|
||||
|
||||
@@ -706,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
|
||||
@@ -733,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,13 +1,22 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
extension Database {
|
||||
|
||||
|
||||
// MARK: - Database Schema
|
||||
|
||||
|
||||
func withSchemaCache<T>(_ schemaCache: DatabaseSchemaCache, _ block: () throws -> T) rethrows -> T {
|
||||
var oldCache = self.schemaCache
|
||||
defer { self.schemaCache = oldCache }
|
||||
self.schemaCache = schemaCache
|
||||
return try block()
|
||||
}
|
||||
|
||||
/// Clears the database schema cache.
|
||||
///
|
||||
/// You may need to clear the cache manually if the database schema is
|
||||
@@ -25,9 +34,8 @@ extension Database {
|
||||
}
|
||||
|
||||
/// Returns whether a table exists.
|
||||
public func tableExists(_ tableName: String) throws -> Bool {
|
||||
// SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html)
|
||||
return try Row.fetchOne(self, "SELECT 1 FROM (SELECT sql, type, name FROM sqlite_master UNION SELECT sql, type, name FROM sqlite_temp_master) WHERE type = 'table' AND LOWER(name) = ?", arguments: [tableName.lowercased()]) != nil
|
||||
public func tableExists(_ name: String) throws -> Bool {
|
||||
return try exists(type: .table, name: name)
|
||||
}
|
||||
|
||||
/// Returns whether a table is an internal SQLite table.
|
||||
@@ -53,17 +61,24 @@ extension Database {
|
||||
}
|
||||
|
||||
/// Returns whether a view exists.
|
||||
public func viewExists(_ viewName: String) throws -> Bool {
|
||||
// SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html)
|
||||
return try Row.fetchOne(self, "SELECT 1 FROM (SELECT sql, type, name FROM sqlite_master UNION SELECT sql, type, name FROM sqlite_temp_master) WHERE type = 'view' AND LOWER(name) = ?", arguments: [viewName.lowercased()]) != nil
|
||||
public func viewExists(_ name: String) throws -> Bool {
|
||||
return try exists(type: .view, name: name)
|
||||
}
|
||||
|
||||
/// Returns whether a trigger exists.
|
||||
public func triggerExists(_ triggerName: String) throws -> Bool {
|
||||
// SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html)
|
||||
return try Row.fetchOne(self, "SELECT 1 FROM (SELECT sql, type, name FROM sqlite_master UNION SELECT sql, type, name FROM sqlite_temp_master) WHERE type = 'trigger' AND LOWER(name) = ?", arguments: [triggerName.lowercased()]) != nil
|
||||
public func triggerExists(_ name: String) throws -> Bool {
|
||||
return try exists(type: .trigger, name: name)
|
||||
}
|
||||
|
||||
|
||||
private func exists(type: SchemaObjectType, name: String) throws -> Bool {
|
||||
// SQlite identifiers are case-insensitive, case-preserving:
|
||||
// http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html
|
||||
let name = name.lowercased()
|
||||
return try schema()
|
||||
.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
|
||||
@@ -164,14 +179,21 @@ extension Database {
|
||||
return indexes
|
||||
}
|
||||
|
||||
let indexes = try Row.fetchAll(self, "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))").map { row -> IndexInfo in
|
||||
let indexName: String = row[1]
|
||||
let unique: Bool = row[2]
|
||||
let columns = try Row.fetchAll(self, "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))")
|
||||
.map { ($0[0] as Int, $0[2] as String) }
|
||||
.sorted { $0.0 < $1.0 }
|
||||
.map { $0.1 }
|
||||
return IndexInfo(name: indexName, columns: columns, unique: unique)
|
||||
let indexes = try Row
|
||||
.fetchAll(self, sql: "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))")
|
||||
.map { row -> IndexInfo in
|
||||
// [seq:0 name:"index" unique:0 origin:"c" partial:0]
|
||||
let indexName: String = row[1]
|
||||
let unique: Bool = row[2]
|
||||
let columns = try Row
|
||||
.fetchAll(self, sql: "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))")
|
||||
.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)
|
||||
}
|
||||
|
||||
if indexes.isEmpty {
|
||||
@@ -188,7 +210,12 @@ 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 {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -198,9 +225,11 @@ 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, "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") {
|
||||
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:"..."]
|
||||
let id: Int = row[0]
|
||||
let seq: Int = row[1]
|
||||
@@ -209,9 +238,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
|
||||
}
|
||||
}
|
||||
@@ -249,32 +282,24 @@ extension Database {
|
||||
|
||||
/// Returns the actual name of the database table
|
||||
func canonicalTableName(_ tableName: String) throws -> String {
|
||||
if let canonicalTableName = schemaCache.canonicalTableName(tableName) {
|
||||
return canonicalTableName
|
||||
}
|
||||
|
||||
guard let canonicalTableName = try String.fetchOne(self, """
|
||||
SELECT name FROM (
|
||||
SELECT name, type FROM sqlite_master
|
||||
UNION
|
||||
SELECT name, type FROM sqlite_temp_master)
|
||||
WHERE type = 'table' AND LOWER(name) = ?
|
||||
""", arguments: [tableName.lowercased()])
|
||||
else {
|
||||
guard let name = try schema().canonicalName(tableName, ofType: .table) else {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
}
|
||||
|
||||
schemaCache.set(canonicalTableName: canonicalTableName, forTable: tableName)
|
||||
return canonicalTableName
|
||||
return name
|
||||
}
|
||||
|
||||
func schema() throws -> SchemaInfo {
|
||||
return try SchemaInfo(self)
|
||||
if let schemaInfo = schemaCache.schemaInfo {
|
||||
return schemaInfo
|
||||
}
|
||||
let schemaInfo = try SchemaInfo(self)
|
||||
schemaCache.schemaInfo = schemaInfo
|
||||
return schemaInfo
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
|
||||
/// The columns in the table named `tableName`
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
@@ -306,7 +331,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.
|
||||
@@ -315,9 +340,9 @@ extension Database {
|
||||
}
|
||||
}
|
||||
let columns = try ColumnInfo
|
||||
.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
|
||||
.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)")
|
||||
}
|
||||
|
||||
@@ -328,14 +353,25 @@ 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 primaryKey = try self.primaryKey(tableName)
|
||||
let lowercasedColumns = Set(columns.map { $0.lowercased() })
|
||||
if Set(primaryKey.columns.map { $0.lowercased() }) == lowercasedColumns {
|
||||
return primaryKey.columns
|
||||
}
|
||||
if let index = try indexes(on: tableName).first(where: { index in index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns }) {
|
||||
// There is an explicit unique index on the columns
|
||||
|
||||
// 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
|
||||
@@ -359,7 +395,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
|
||||
@@ -381,7 +417,7 @@ public struct ColumnInfo : FetchableRecord {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try db.execute("""
|
||||
/// try db.execute(sql: """
|
||||
/// CREATE TABLE player(
|
||||
/// id INTEGER PRIMARY KEY,
|
||||
/// name TEXT DEFAULT 'Anonymous',
|
||||
@@ -563,23 +599,47 @@ public struct ForeignKeyInfo {
|
||||
}
|
||||
}
|
||||
|
||||
enum SchemaObjectType: String {
|
||||
case index
|
||||
case table
|
||||
case trigger
|
||||
case view
|
||||
}
|
||||
|
||||
struct SchemaInfo: Equatable {
|
||||
var objects: [SchemaKey: String?]
|
||||
private var objects: Set<SchemaObject>
|
||||
|
||||
init(_ db: Database) throws {
|
||||
objects = try Dictionary(uniqueKeysWithValues: Row
|
||||
.fetchAll(db, "SELECT type, name, tbl_name, sql FROM sqlite_master")
|
||||
.map { row in (SchemaKey(row: row), row["sql"]) })
|
||||
objects = try Set(SchemaObject.fetchCursor(db, sql: """
|
||||
SELECT type, name, tbl_name, sql, 0 AS isTemporary FROM sqlite_master \
|
||||
UNION \
|
||||
SELECT type, name, tbl_name, sql, 1 FROM sqlite_temp_master
|
||||
"""))
|
||||
}
|
||||
|
||||
struct SchemaKey: Codable, Hashable, FetchableRecord {
|
||||
/// All names for a given type
|
||||
func names(ofType type: SchemaObjectType) -> Set<String> {
|
||||
return objects.reduce(into: []) { (set, key) in
|
||||
if key.type == type.rawValue {
|
||||
set.insert(key.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the canonical name of the object:
|
||||
///
|
||||
/// try db.execute(sql: "CREATE TABLE FooBar (...)")
|
||||
/// try db.schema().canonicalName("foobar", ofType: .table) // "FooBar"
|
||||
func canonicalName(_ name: String, ofType type: SchemaObjectType) -> String? {
|
||||
let name = name.lowercased()
|
||||
return objects.first { $0.name.lowercased() == name }?.name
|
||||
}
|
||||
|
||||
private struct SchemaObject: Codable, Hashable, FetchableRecord {
|
||||
var type: String
|
||||
var name: String
|
||||
var tbl_name: String?
|
||||
|
||||
// TODO: remove when Hashable conformance is synthesized
|
||||
var hashValue: Int {
|
||||
return type.hashValue ^ name.hashValue ^ (tbl_name?.hashValue ?? 0)
|
||||
}
|
||||
var sql: String?
|
||||
var isTemporary: Bool
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,11 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
extension Database {
|
||||
|
||||
@@ -6,20 +13,20 @@ extension Database {
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?")
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: A SelectStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func makeSelectStatement(_ sql: String) throws -> SelectStatement {
|
||||
return try makeSelectStatement(sql, prepFlags: 0)
|
||||
public func makeSelectStatement(sql: String) throws -> SelectStatement {
|
||||
return try makeSelectStatement(sql: sql, prepFlags: 0)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0)
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0)
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
///
|
||||
@@ -28,13 +35,13 @@ extension Database {
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
/// - returns: A SelectStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
func makeSelectStatement(_ sql: String, prepFlags: Int32) throws -> SelectStatement {
|
||||
return try SelectStatement.prepare(sql: sql, prepFlags: prepFlags, in: self)
|
||||
func makeSelectStatement(sql: String, prepFlags: Int32) throws -> SelectStatement {
|
||||
return try SelectStatement.prepare(self, sql: sql, prepFlags: prepFlags)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
|
||||
/// let statement = try db.cachedSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?")
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
///
|
||||
@@ -44,31 +51,31 @@ extension Database {
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func cachedSelectStatement(_ sql: String) throws -> SelectStatement {
|
||||
public func cachedSelectStatement(sql: String) throws -> SelectStatement {
|
||||
return try publicStatementCache.selectStatement(sql)
|
||||
}
|
||||
|
||||
/// Returns a cached statement that does not conflict with user's cached statements.
|
||||
func internalCachedSelectStatement(_ sql: String) throws -> SelectStatement {
|
||||
func internalCachedSelectStatement(sql: String) throws -> SelectStatement {
|
||||
return try internalStatementCache.selectStatement(sql)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)")
|
||||
/// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func makeUpdateStatement(_ sql: String) throws -> UpdateStatement {
|
||||
return try makeUpdateStatement(sql, prepFlags: 0)
|
||||
public func makeUpdateStatement(sql: String) throws -> UpdateStatement {
|
||||
return try makeUpdateStatement(sql: sql, prepFlags: 0)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)", prepFlags: 0)
|
||||
/// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)", prepFlags: 0)
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
@@ -77,13 +84,13 @@ extension Database {
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
func makeUpdateStatement(_ sql: String, prepFlags: Int32) throws -> UpdateStatement {
|
||||
return try UpdateStatement.prepare(sql: sql, prepFlags: prepFlags, in: self)
|
||||
func makeUpdateStatement(sql: String, prepFlags: Int32) throws -> UpdateStatement {
|
||||
return try UpdateStatement.prepare(self, sql: sql, prepFlags: prepFlags)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedUpdateStatement("INSERT INTO player (name) VALUES (?)")
|
||||
/// let statement = try db.cachedUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
@@ -93,107 +100,175 @@ extension Database {
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func cachedUpdateStatement(_ sql: String) throws -> UpdateStatement {
|
||||
public func cachedUpdateStatement(sql: String) throws -> UpdateStatement {
|
||||
return try publicStatementCache.updateStatement(sql)
|
||||
}
|
||||
|
||||
/// Returns a cached statement that does not conflict with user's cached statements.
|
||||
func internalCachedUpdateStatement(_ sql: String) throws -> UpdateStatement {
|
||||
func internalCachedUpdateStatement(sql: String) throws -> UpdateStatement {
|
||||
return try internalStatementCache.updateStatement(sql)
|
||||
}
|
||||
|
||||
/// Executes one or several SQL statements, separated by semi-colons.
|
||||
///
|
||||
/// try db.execute(
|
||||
/// "INSERT INTO player (name) VALUES (:name)",
|
||||
/// sql: "INSERT INTO player (name) VALUES (:name)",
|
||||
/// arguments: ["name": "Arthur"])
|
||||
///
|
||||
/// try db.execute("""
|
||||
/// try db.execute(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// """, arguments; ['Arthur', 'Barbara', 'Craig'])
|
||||
/// """, arguments: ["Arthur", "Barbara", "O'Brien"])
|
||||
///
|
||||
/// This method may throw a DatabaseError.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func execute(_ sql: String, arguments: StatementArguments? = nil) throws {
|
||||
public func execute(sql: String, arguments: StatementArguments = StatementArguments()) throws {
|
||||
try execute(literal: SQLLiteral(sql: sql, arguments: arguments))
|
||||
}
|
||||
|
||||
/// Executes one or several SQL statements, separated by semi-colons.
|
||||
///
|
||||
/// try db.execute(literal: SQLLiteral(
|
||||
/// sql: "INSERT INTO player (name) VALUES (:name)",
|
||||
/// arguments: ["name": "Arthur"]))
|
||||
///
|
||||
/// try db.execute(literal: SQLLiteral(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// """, arguments: ["Arthur", "Barbara", "O'Brien"]))
|
||||
///
|
||||
/// With Swift 5, you can safely embed raw values in your SQL queries,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// try db.execute(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"));
|
||||
/// INSERT INTO player (name) VALUES (\("Barbara"));
|
||||
/// INSERT INTO player (name) VALUES (\("O'Brien"));
|
||||
/// """)
|
||||
///
|
||||
/// This method may throw a DatabaseError.
|
||||
///
|
||||
/// - parameter sqlLiteral: An SQLLiteral.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func execute(literal sqlLiteral: SQLLiteral) throws {
|
||||
// This method is like sqlite3_exec (https://www.sqlite.org/c3ref/exec.html)
|
||||
// It adds support for arguments, and the tricky part is to consume
|
||||
// arguments as statements are executed.
|
||||
//
|
||||
// Here we build two functions:
|
||||
// - consumeArguments returns arguments for a statement
|
||||
// - validateRemainingArguments validates the remaining arguments, after
|
||||
// all statements have been executed, in the same way
|
||||
// as Statement.validate(arguments:)
|
||||
// This job is performed by StatementArguments.extractBindings(forStatement:allowingRemainingValues:)
|
||||
//
|
||||
// And before we return, we'll check that all arguments were consumed.
|
||||
|
||||
var arguments = arguments ?? StatementArguments()
|
||||
var arguments = sqlLiteral.arguments
|
||||
let initialValuesCount = arguments.values.count
|
||||
let consumeArguments = { (statement: UpdateStatement) throws -> StatementArguments in
|
||||
let bindings = try arguments.consume(statement, allowingRemainingValues: true)
|
||||
return StatementArguments(bindings)
|
||||
}
|
||||
let validateRemainingArguments = {
|
||||
if !arguments.values.isEmpty {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)")
|
||||
}
|
||||
}
|
||||
|
||||
// Iterate SQL statements
|
||||
let sqlCodeUnits = sql.utf8CString
|
||||
try sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
|
||||
let sqlStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
|
||||
let sqlEnd = sqlStart + sqlCodeUnits.count
|
||||
// Build a C string (SQLite wants that), and execute SQL statements one
|
||||
// after the other.
|
||||
try sqlLiteral.sql.utf8CString.withUnsafeBufferPointer { buffer in
|
||||
guard let sqlStart = buffer.baseAddress else { return }
|
||||
let sqlEnd = sqlStart + buffer.count // past \0
|
||||
var statementStart = sqlStart
|
||||
while statementStart < sqlEnd - 1 {
|
||||
while statementStart < sqlEnd {
|
||||
var statementEnd: UnsafePointer<Int8>? = nil
|
||||
let nextStatement: UpdateStatement?
|
||||
|
||||
// Compile
|
||||
do {
|
||||
let statement: UpdateStatement
|
||||
// Compile
|
||||
do {
|
||||
let statementCompilationAuthorizer = StatementCompilationAuthorizer()
|
||||
authorizer = statementCompilationAuthorizer
|
||||
defer { authorizer = nil }
|
||||
|
||||
statement = try UpdateStatement(
|
||||
let authorizer = StatementCompilationAuthorizer()
|
||||
nextStatement = try withAuthorizer(authorizer) {
|
||||
try UpdateStatement(
|
||||
database: self,
|
||||
statementStart: statementStart,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: 0,
|
||||
authorizer: statementCompilationAuthorizer)
|
||||
authorizer: authorizer)
|
||||
}
|
||||
|
||||
// Execute
|
||||
let arguments = try consumeArguments(statement)
|
||||
statement.unsafeSetArguments(arguments)
|
||||
try statement.execute()
|
||||
|
||||
// Next
|
||||
statementStart = statementEnd!
|
||||
} catch is EmptyStatementError {
|
||||
// End
|
||||
}
|
||||
|
||||
guard let statement = nextStatement else {
|
||||
// End of SQL string
|
||||
break
|
||||
}
|
||||
|
||||
// Extract statement arguments
|
||||
let bindings = try arguments.extractBindings(forStatement: statement, allowingRemainingValues: true)
|
||||
// unsafe is OK because we just extracted the correct number of arguments
|
||||
statement.unsafeSetArguments(StatementArguments(bindings))
|
||||
|
||||
// Execute
|
||||
try statement.execute()
|
||||
|
||||
// Next
|
||||
statementStart = statementEnd!
|
||||
}
|
||||
}
|
||||
|
||||
// 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)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
func executeUpdateStatement(_ statement: UpdateStatement) throws {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Force arguments validity: it is a programmer error to provide
|
||||
// arguments that do not match the statement.
|
||||
try! validateRemainingArguments() // throws if there are remaining arguments.
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
func updateStatementWillExecute(_ statement: UpdateStatement) {
|
||||
observationBroker.updateStatementWillExecute(statement)
|
||||
// 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()
|
||||
}
|
||||
@@ -201,7 +276,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
|
||||
@@ -213,6 +288,28 @@ extension Database {
|
||||
try observationBroker.updateStatementDidFail(statement)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
func selectStatementWillExecute(_ statement: SelectStatement) {
|
||||
if _isRecordingSelectedRegion {
|
||||
// Don't record schema introspection queries, which may be
|
||||
// run, or not, depending on the state of the schema cache.
|
||||
//
|
||||
// This gives us a quick way to make sure that the observation
|
||||
// below, which runs schema introspection queries as a side effect,
|
||||
// only tracks the "player" table:
|
||||
//
|
||||
// let observation = ValueObservation.tracking { db in
|
||||
// try Player.fetchOne(db, key: 1)
|
||||
// }
|
||||
//
|
||||
// Strictly speaking, this prevents the recording of all schema
|
||||
// queries. But we assume, until proven wrong, that such recording
|
||||
// isn't needed by anyone.
|
||||
let region = statement.databaseRegion.ignoringInternalSQLiteTables()
|
||||
_selectedRegion.formUnion(region)
|
||||
}
|
||||
}
|
||||
|
||||
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:
|
||||
@@ -223,3 +320,87 @@ extension Database {
|
||||
publicStatementCache.remove(statement)
|
||||
}
|
||||
}
|
||||
|
||||
/// A thread-unsafe statement cache
|
||||
struct StatementCache {
|
||||
unowned let db: Database
|
||||
private var selectStatements: [String: SelectStatement] = [:]
|
||||
private var updateStatements: [String: UpdateStatement] = [:]
|
||||
|
||||
init(database: Database) {
|
||||
self.db = database
|
||||
}
|
||||
|
||||
mutating func selectStatement(_ sql: String) throws -> SelectStatement {
|
||||
if let statement = selectStatements[sql] {
|
||||
return statement
|
||||
}
|
||||
|
||||
// http://www.sqlite.org/c3ref/c_prepare_persistent.html#sqlitepreparepersistent
|
||||
// > The SQLITE_PREPARE_PERSISTENT flag is a hint to the query
|
||||
// > planner that the prepared statement will be retained for a long
|
||||
// > time and probably reused many times.
|
||||
//
|
||||
// This looks like a perfect match for cached statements.
|
||||
//
|
||||
// However SQLITE_PREPARE_PERSISTENT was only introduced in
|
||||
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
let statement = try db.makeSelectStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
|
||||
#else
|
||||
let statement: SelectStatement
|
||||
if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) {
|
||||
// SQLite 3.24.0 or more
|
||||
statement = try db.makeSelectStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
|
||||
} else {
|
||||
// SQLite 3.19.3 or less
|
||||
statement = try db.makeSelectStatement(sql: sql)
|
||||
}
|
||||
#endif
|
||||
selectStatements[sql] = statement
|
||||
return statement
|
||||
}
|
||||
|
||||
mutating func updateStatement(_ sql: String) throws -> UpdateStatement {
|
||||
if let statement = updateStatements[sql] {
|
||||
return statement
|
||||
}
|
||||
|
||||
// http://www.sqlite.org/c3ref/c_prepare_persistent.html#sqlitepreparepersistent
|
||||
// > The SQLITE_PREPARE_PERSISTENT flag is a hint to the query
|
||||
// > planner that the prepared statement will be retained for a long
|
||||
// > time and probably reused many times.
|
||||
//
|
||||
// This looks like a perfect match for cached statements.
|
||||
//
|
||||
// However SQLITE_PREPARE_PERSISTENT was only introduced in
|
||||
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
let statement = try db.makeUpdateStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
|
||||
#else
|
||||
let statement: UpdateStatement
|
||||
if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) {
|
||||
// SQLite 3.24.0 or more
|
||||
statement = try db.makeUpdateStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
|
||||
} else {
|
||||
// SQLite 3.19.3 or less
|
||||
statement = try db.makeUpdateStatement(sql: sql)
|
||||
}
|
||||
#endif
|
||||
updateStatements[sql] = statement
|
||||
return statement
|
||||
}
|
||||
|
||||
mutating func clear() {
|
||||
updateStatements = [:]
|
||||
selectStatements = [:]
|
||||
}
|
||||
|
||||
mutating func remove(_ statement: SelectStatement) {
|
||||
selectStatements.removeFirst { $0.value === statement }
|
||||
}
|
||||
|
||||
mutating func remove(_ statement: UpdateStatement) {
|
||||
updateStatements.removeFirst { $0.value === statement }
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// A raw SQLite connection, suitable for the SQLite C API.
|
||||
@@ -34,7 +36,7 @@ public final class Database {
|
||||
public let sqliteConnection: SQLiteConnection
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
|
||||
/// The error logging function.
|
||||
///
|
||||
/// Quoting https://www.sqlite.org/errlog.html:
|
||||
@@ -51,7 +53,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)
|
||||
}
|
||||
@@ -112,7 +114,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
|
||||
}
|
||||
|
||||
@@ -123,69 +125,43 @@ 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 { return 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? { return String(cString: sqlite3_errmsg(sqliteConnection)) }
|
||||
|
||||
/// Statement authorizer. Use withAuthorizer(_:_:).
|
||||
fileprivate var _authorizer: StatementAuthorizer?
|
||||
|
||||
// Transaction observers management
|
||||
lazy var observationBroker = DatabaseObservationBroker(self)
|
||||
|
||||
/// The list of compile options used when building SQLite
|
||||
static let sqliteCompileOptions: Set<String> = DatabaseQueue().inDatabase {
|
||||
try! Set(String.fetchCursor($0, "PRAGMA COMPILE_OPTIONS"))
|
||||
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()
|
||||
|
||||
// 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 {
|
||||
let sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
|
||||
do {
|
||||
try Database.activateExtendedCodes(sqliteConnection)
|
||||
#if SQLITE_HAS_CODEC
|
||||
try Database.validateSQLCipher(sqliteConnection)
|
||||
if let passphrase = configuration.passphrase {
|
||||
try Database.set(passphrase: passphrase, forConnection: sqliteConnection)
|
||||
}
|
||||
#endif
|
||||
try Database.validateDatabaseFormat(sqliteConnection)
|
||||
} catch {
|
||||
Database.closeConnection(sqliteConnection)
|
||||
throw error
|
||||
}
|
||||
|
||||
self.sqliteConnection = sqliteConnection
|
||||
self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
|
||||
self.configuration = configuration
|
||||
self.schemaCache = schemaCache
|
||||
|
||||
configuration.SQLiteConnectionDidOpen?()
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -194,7 +170,7 @@ public final class Database {
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
|
||||
// MARK: - Database Opening
|
||||
|
||||
private static func openConnection(path: String, flags: Int32) throws -> SQLiteConnection {
|
||||
@@ -202,6 +178,16 @@ extension Database {
|
||||
var sqliteConnection: SQLiteConnection? = nil
|
||||
let code = sqlite3_open_v2(path, &sqliteConnection, flags, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
// https://www.sqlite.org/c3ref/open.html
|
||||
// > Whether or not an error occurs when it is opened, resources
|
||||
// > associated with the database connection handle should be
|
||||
// > released by passing it to sqlite3_close() when it is no
|
||||
// > longer required.
|
||||
//
|
||||
// https://www.sqlite.org/c3ref/close.html
|
||||
// > Calling sqlite3_close() or sqlite3_close_v2() with a NULL
|
||||
// > pointer argument is a harmless no-op.
|
||||
sqlite3_close(sqliteConnection)
|
||||
throw DatabaseError(resultCode: code)
|
||||
}
|
||||
if let sqliteConnection = sqliteConnection {
|
||||
@@ -209,65 +195,10 @@ extension Database {
|
||||
}
|
||||
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
|
||||
}
|
||||
|
||||
private static func activateExtendedCodes(_ sqliteConnection: SQLiteConnection) throws {
|
||||
let code = sqlite3_extended_result_codes(sqliteConnection, 1)
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
|
||||
}
|
||||
}
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
private static func validateSQLCipher(_ sqliteConnection: SQLiteConnection) throws {
|
||||
// https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688
|
||||
//
|
||||
// > In order to avoid situations where SQLite might be used
|
||||
// > improperly at runtime, we strongly recommend that
|
||||
// > applications institute a runtime test to ensure that the
|
||||
// > application is actually using SQLCipher on the active
|
||||
// > connection.
|
||||
var sqliteStatement: SQLiteStatement? = nil
|
||||
let code = sqlite3_prepare_v2(sqliteConnection, "PRAGMA cipher_version", -1, &sqliteStatement, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
|
||||
}
|
||||
defer {
|
||||
sqlite3_finalize(sqliteStatement)
|
||||
}
|
||||
if sqlite3_step(sqliteStatement) != SQLITE_ROW || (sqlite3_column_text(sqliteStatement, 0) == nil) {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: """
|
||||
GRDB is not linked against SQLCipher. \
|
||||
Check https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
private static func set(passphrase: String, forConnection sqliteConnection: SQLiteConnection) throws {
|
||||
let data = passphrase.data(using: .utf8)!
|
||||
let code = data.withUnsafeBytes { bytes in
|
||||
sqlite3_key(sqliteConnection, bytes, Int32(data.count))
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
private static func validateDatabaseFormat(_ sqliteConnection: SQLiteConnection) throws {
|
||||
// Users are surprised when they open a picture as a database and
|
||||
// see no error (https://github.com/groue/GRDB.swift/issues/54).
|
||||
//
|
||||
// So let's fail early if file is not a database, or encrypted with
|
||||
// another passphrase.
|
||||
let code = sqlite3_exec(sqliteConnection, "SELECT * FROM sqlite_master LIMIT 1", nil, nil, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
|
||||
// MARK: - Database Setup
|
||||
|
||||
/// This method must be called after database initialization
|
||||
@@ -278,63 +209,91 @@ extension Database {
|
||||
setupBusyMode()
|
||||
setupDefaultFunctions()
|
||||
setupDefaultCollations()
|
||||
setupAuthorizer()
|
||||
observationBroker.installCommitAndRollbackHooks()
|
||||
try activateExtendedCodes()
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
try validateSQLCipher()
|
||||
if let passphrase = configuration._passphrase {
|
||||
try _usePassphrase(passphrase)
|
||||
}
|
||||
#endif
|
||||
|
||||
// Last step before we can start accessing the database.
|
||||
try configuration.prepareDatabase?(self)
|
||||
|
||||
try validateFormat()
|
||||
configuration.SQLiteConnectionDidOpen?()
|
||||
}
|
||||
|
||||
private func setupTrace() {
|
||||
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)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
// 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
|
||||
sqlite3_trace_v2(sqliteConnection, UInt32(SQLITE_TRACE_STMT), { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in
|
||||
guard let stmt = stmt else { return SQLITE_OK }
|
||||
guard let expandedSQLCString = sqlite3_expanded_sql(OpaquePointer(stmt)) else { return SQLITE_OK }
|
||||
let sql = String(cString: expandedSQLCString)
|
||||
sqlite3_free(expandedSQLCString)
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
|
||||
db.configuration.trace!(sql)
|
||||
return SQLITE_OK
|
||||
}, dbPointer)
|
||||
#elseif GRDBCIPHER
|
||||
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
|
||||
guard let sql = sql.map({ String(cString: $0) }) else { return }
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
|
||||
db.configuration.trace!(sql)
|
||||
}, dbPointer)
|
||||
#elseif !os(Linux)
|
||||
if #available(iOS 10.0, OSX 10.12, watchOS 3.0, *) {
|
||||
sqlite3_trace_v2(sqliteConnection, UInt32(SQLITE_TRACE_STMT), { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in
|
||||
guard let stmt = stmt else { return SQLITE_OK }
|
||||
guard let expandedSQLCString = sqlite3_expanded_sql(OpaquePointer(stmt)) else { return SQLITE_OK }
|
||||
let sql = String(cString: expandedSQLCString)
|
||||
sqlite3_free(expandedSQLCString)
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
|
||||
db.configuration.trace!(sql)
|
||||
return SQLITE_OK
|
||||
}, dbPointer)
|
||||
} else {
|
||||
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
|
||||
guard let sql = sql.map({ String(cString: $0) }) else { return }
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
|
||||
db.configuration.trace!(sql)
|
||||
}, dbPointer)
|
||||
}
|
||||
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()
|
||||
#else
|
||||
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
|
||||
guard let sql = sql.map({ String(cString: $0) }) else { return }
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
|
||||
db.configuration.trace!(sql)
|
||||
}, dbPointer)
|
||||
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
|
||||
}
|
||||
|
||||
// Precondition: configuration.trace != nil
|
||||
private func setupTrace_v1() {
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
|
||||
guard let sql = sql.map(String.init) else { return }
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
|
||||
db.configuration.trace!(sql)
|
||||
}, dbPointer)
|
||||
}
|
||||
|
||||
// Precondition: configuration.trace != nil
|
||||
private static func trace_v2(
|
||||
_ mask: UInt32,
|
||||
_ dbPointer: UnsafeMutableRawPointer?,
|
||||
_ stmt: UnsafeMutableRawPointer?,
|
||||
_ unexpandedSQL: UnsafeMutableRawPointer?,
|
||||
_ sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
|
||||
-> Int32
|
||||
{
|
||||
guard let stmt = stmt else { return SQLITE_OK }
|
||||
guard let expandedSQLCString = sqlite3_expanded_sql(OpaquePointer(stmt)) else { return SQLITE_OK }
|
||||
let sql = String(cString: expandedSQLCString)
|
||||
sqlite3_free(expandedSQLCString)
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
|
||||
db.configuration.trace!(sql)
|
||||
return SQLITE_OK
|
||||
}
|
||||
|
||||
private func setupForeignKeys() throws {
|
||||
// Foreign keys are disabled by default with SQLite3
|
||||
if configuration.foreignKeysEnabled {
|
||||
try execute("PRAGMA foreign_keys = ON")
|
||||
try execute(sql: "PRAGMA foreign_keys = ON")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -380,10 +339,67 @@ extension Database {
|
||||
add(collation: .localizedCompare)
|
||||
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 {
|
||||
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
|
||||
}
|
||||
}
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
private func validateSQLCipher() throws {
|
||||
// https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688
|
||||
//
|
||||
// > In order to avoid situations where SQLite might be used
|
||||
// > improperly at runtime, we strongly recommend that
|
||||
// > applications institute a runtime test to ensure that the
|
||||
// > application is actually using SQLCipher on the active
|
||||
// > connection.
|
||||
if try String.fetchOne(self, sql: "PRAGMA cipher_version") == nil {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: """
|
||||
GRDB is not linked against SQLCipher. \
|
||||
Check https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688
|
||||
""")
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
private func validateFormat() throws {
|
||||
// Users are surprised when they open a picture as a database and
|
||||
// see no error (https://github.com/groue/GRDB.swift/issues/54).
|
||||
//
|
||||
// So let's fail early if file is not a database, or encrypted with
|
||||
// another passphrase.
|
||||
try makeSelectStatement(sql: "SELECT * FROM sqlite_master LIMIT 1").makeCursor().next()
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
|
||||
// MARK: - Database Closing
|
||||
|
||||
/// This method must be called before database deallocation
|
||||
@@ -400,41 +416,48 @@ 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
|
||||
close_v2(connection: sqliteConnection)
|
||||
closeConnection_v2(sqliteConnection, sqlite3_close_v2)
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) {
|
||||
close_v2(connection: sqliteConnection)
|
||||
} else {
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) {
|
||||
closeConnection_v2(sqliteConnection, sqlite3_close_v2)
|
||||
} else {
|
||||
closeConnection_v1(sqliteConnection)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// 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
|
||||
private static func close_v2(connection sqliteConnection: SQLiteConnection) {
|
||||
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
|
||||
@@ -449,28 +472,10 @@ extension Database {
|
||||
log(ResultCode(rawValue: code), "could not close database: \(message)")
|
||||
}
|
||||
}
|
||||
#else
|
||||
@available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *)
|
||||
private static func close_v2(connection sqliteConnection: SQLiteConnection) {
|
||||
// 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
|
||||
// > connection becomes an unusable "zombie" which will automatically
|
||||
// > be deallocated when the last prepared statement is finalized or the
|
||||
// > last sqlite3_backup is finished.
|
||||
let code = sqlite3_close_v2(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)")
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
@@ -482,7 +487,7 @@ extension Database {
|
||||
/// return int + 1
|
||||
/// }
|
||||
/// db.add(function: fn)
|
||||
/// try Int.fetchOne(db, "SELECT succ(1)")! // 2
|
||||
/// try Int.fetchOne(db, sql: "SELECT succ(1)")! // 2
|
||||
public func add(function: DatabaseFunction) {
|
||||
functions.update(with: function)
|
||||
function.install(in: self)
|
||||
@@ -496,7 +501,7 @@ extension Database {
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// Add or redefine a collation.
|
||||
@@ -505,7 +510,7 @@ extension Database {
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// db.add(collation: collation)
|
||||
/// try db.execute("CREATE TABLE files (name TEXT COLLATE localized_standard")
|
||||
/// try db.execute(sql: "CREATE TABLE files (name TEXT COLLATE localized_standard")
|
||||
public func add(collation: DatabaseCollation) {
|
||||
collations.update(with: collation)
|
||||
let collationPointer = Unmanaged.passUnretained(collation).toOpaque()
|
||||
@@ -539,30 +544,107 @@ extension Database {
|
||||
|
||||
// MARK: - Read-Only Access
|
||||
|
||||
func beginReadOnly() throws {
|
||||
_readOnlyDepth += 1
|
||||
if _readOnlyDepth == 1 && configuration.readonly == false {
|
||||
// PRAGMA query_only was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
|
||||
// It is available from iOS 8.2 and OS X 10.10
|
||||
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
try internalCachedUpdateStatement(sql: "PRAGMA query_only = 1").execute()
|
||||
}
|
||||
}
|
||||
|
||||
func endReadOnly() throws {
|
||||
_readOnlyDepth -= 1
|
||||
if _readOnlyDepth == 0 && configuration.readonly == false {
|
||||
// PRAGMA query_only was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
|
||||
// It is available from iOS 8.2 and OS X 10.10
|
||||
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
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 {
|
||||
return try block()
|
||||
func readOnly<T>(_ block: () throws -> T) throws -> T {
|
||||
try beginReadOnly()
|
||||
|
||||
var result: T?
|
||||
var thrownError: Error?
|
||||
|
||||
do {
|
||||
result = try block()
|
||||
} catch {
|
||||
thrownError = error
|
||||
}
|
||||
|
||||
// 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! execute("PRAGMA query_only = 1")
|
||||
defer { try! execute("PRAGMA query_only = 0") }
|
||||
do {
|
||||
try endReadOnly()
|
||||
} catch {
|
||||
if thrownError == nil {
|
||||
thrownError = error
|
||||
}
|
||||
}
|
||||
|
||||
if let error = thrownError {
|
||||
throw error
|
||||
}
|
||||
|
||||
return result!
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// 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()
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Recording of the selected region
|
||||
|
||||
func recordingSelectedRegion<T>(_ block: () throws -> T) rethrows -> (T, DatabaseRegion) {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
let oldFlag = self._isRecordingSelectedRegion
|
||||
let oldRegion = self._selectedRegion
|
||||
self._isRecordingSelectedRegion = true
|
||||
self._selectedRegion = DatabaseRegion()
|
||||
defer {
|
||||
self._isRecordingSelectedRegion = oldFlag
|
||||
if self._isRecordingSelectedRegion {
|
||||
self._selectedRegion = oldRegion.union(self._selectedRegion)
|
||||
} else {
|
||||
self._selectedRegion = oldRegion
|
||||
}
|
||||
}
|
||||
return try (block(), _selectedRegion)
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
func checkpoint(_ kind: Database.CheckpointMode) throws {
|
||||
let code = sqlite3_wal_checkpoint_v2(sqliteConnection, nil, kind.rawValue, nil, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: lastErrorMessage)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
// MARK: - Transactions & Savepoint
|
||||
|
||||
/// Executes a block inside a database transaction.
|
||||
///
|
||||
/// try dbQueue.inDatabase do {
|
||||
/// try db.inTransaction {
|
||||
/// try db.execute("INSERT ...")
|
||||
/// try db.execute(sql: "INSERT ...")
|
||||
/// return .commit
|
||||
/// }
|
||||
/// }
|
||||
@@ -612,7 +694,7 @@ extension Database {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if let firstError = firstError {
|
||||
throw firstError
|
||||
}
|
||||
@@ -622,7 +704,7 @@ extension Database {
|
||||
///
|
||||
/// try dbQueue.inDatabase do {
|
||||
/// try db.inSavepoint {
|
||||
/// try db.execute("INSERT ...")
|
||||
/// try db.execute(sql: "INSERT ...")
|
||||
/// return .commit
|
||||
/// }
|
||||
/// }
|
||||
@@ -646,7 +728,7 @@ extension Database {
|
||||
if !isInsideTransaction && configuration.defaultTransactionKind != .deferred {
|
||||
return try inTransaction(configuration.defaultTransactionKind, block)
|
||||
}
|
||||
|
||||
|
||||
// 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).
|
||||
@@ -658,7 +740,7 @@ extension Database {
|
||||
// using unique savepoint names. User could still mess with them
|
||||
// with raw SQL queries, but let's assume that it is unlikely that
|
||||
// the user uses "grdb" as a savepoint name.
|
||||
try execute("SAVEPOINT grdb")
|
||||
try execute(sql: "SAVEPOINT grdb")
|
||||
|
||||
// Now that savepoint has begun, we'll rollback in case of error.
|
||||
// But we'll throw the first caught error, so that user knows
|
||||
@@ -669,7 +751,7 @@ extension Database {
|
||||
let completion = try block()
|
||||
switch completion {
|
||||
case .commit:
|
||||
try execute("RELEASE SAVEPOINT grdb")
|
||||
try execute(sql: "RELEASE SAVEPOINT grdb")
|
||||
assert(!topLevelSavepoint || !isInsideTransaction)
|
||||
needsRollback = false
|
||||
case .rollback:
|
||||
@@ -688,8 +770,8 @@ extension Database {
|
||||
// Rollback, and release the savepoint.
|
||||
// Rollback alone is not enough to clear the savepoint from
|
||||
// the SQLite savepoint stack.
|
||||
try execute("ROLLBACK TRANSACTION TO SAVEPOINT grdb")
|
||||
try execute("RELEASE SAVEPOINT grdb")
|
||||
try execute(sql: "ROLLBACK TRANSACTION TO SAVEPOINT grdb")
|
||||
try execute(sql: "RELEASE SAVEPOINT grdb")
|
||||
}
|
||||
} catch {
|
||||
if firstError == nil {
|
||||
@@ -712,7 +794,57 @@ extension Database {
|
||||
/// - throws: The error thrown by the block.
|
||||
public func beginTransaction(_ kind: TransactionKind? = nil) throws {
|
||||
let kind = kind ?? configuration.defaultTransactionKind
|
||||
try execute("BEGIN \(kind.rawValue) TRANSACTION")
|
||||
try execute(sql: "BEGIN \(kind.rawValue) TRANSACTION")
|
||||
assert(isInsideTransaction)
|
||||
}
|
||||
|
||||
/// Begins a database transaction and take a snapshot of the last committed
|
||||
/// database state.
|
||||
func beginSnapshotTransaction() throws {
|
||||
// https://www.sqlite.org/isolation.html
|
||||
//
|
||||
// > In WAL mode, SQLite exhibits "snapshot isolation". When a read
|
||||
// > transaction starts, that reader continues to see an unchanging
|
||||
// > "snapshot" of the database file as it existed at the moment in time
|
||||
// > when the read transaction started. Any write transactions that
|
||||
// > commit while the read transaction is active are still invisible to
|
||||
// > the read transaction, because the reader is seeing a snapshot of
|
||||
// > database file from a prior moment in time.
|
||||
//
|
||||
// That's exactly what we need. But what does "when read transaction
|
||||
// starts" mean?
|
||||
//
|
||||
// http://www.sqlite.org/lang_transaction.html
|
||||
//
|
||||
// > Deferred [transaction] means that no locks are acquired on the
|
||||
// > database until the database is first accessed. [...] Locks are not
|
||||
// > acquired until the first read or write operation. [...] Because the
|
||||
// > acquisition of locks is deferred until they are needed, it is
|
||||
// > possible that another thread or process could create a separate
|
||||
// > transaction and write to the database after the BEGIN on the
|
||||
// > current thread has executed.
|
||||
//
|
||||
// Now that's precise enough: SQLite defers "snapshot isolation" until
|
||||
// the first SELECT:
|
||||
//
|
||||
// Reader Writer
|
||||
// BEGIN DEFERRED TRANSACTION
|
||||
// UPDATE ... (1)
|
||||
// Here the change (1) is visible
|
||||
// SELECT ...
|
||||
// UPDATE ... (2)
|
||||
// Here the change (2) is not visible
|
||||
//
|
||||
// We thus have to perform a select that establishes the
|
||||
// snapshot isolation before we release the writer queue:
|
||||
//
|
||||
// Reader Writer
|
||||
// BEGIN DEFERRED TRANSACTION
|
||||
// SELECT anything
|
||||
// UPDATE ...
|
||||
// Here the change is not visible by GRDB user
|
||||
try beginTransaction(.deferred)
|
||||
try internalCachedSelectStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next()
|
||||
}
|
||||
|
||||
/// Rollbacks a database transaction.
|
||||
@@ -758,20 +890,20 @@ extension Database {
|
||||
// should be exposed to the library user.
|
||||
SchedulingWatchdog.preconditionValidQueue(self) // guard sqlite3_get_autocommit
|
||||
if sqlite3_get_autocommit(sqliteConnection) == 0 {
|
||||
try execute("ROLLBACK TRANSACTION")
|
||||
try execute(sql: "ROLLBACK TRANSACTION")
|
||||
}
|
||||
assert(!isInsideTransaction)
|
||||
}
|
||||
|
||||
/// Commits a database transaction.
|
||||
public func commit() throws {
|
||||
try execute("COMMIT TRANSACTION")
|
||||
try execute(sql: "COMMIT TRANSACTION")
|
||||
assert(!isInsideTransaction)
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
|
||||
// MARK: - Memory Management
|
||||
|
||||
func releaseMemory() {
|
||||
@@ -786,12 +918,18 @@ extension Database {
|
||||
|
||||
// MARK: - Backup
|
||||
|
||||
static func backup(from dbFrom: Database, to dbDest: Database, afterBackupInit: (() -> ())? = nil, afterBackupStep: (() -> ())? = nil) throws {
|
||||
static func backup(
|
||||
from dbFrom: Database,
|
||||
to dbDest: Database,
|
||||
afterBackupInit: (() -> Void)? = nil,
|
||||
afterBackupStep: (() -> Void)? = nil)
|
||||
throws
|
||||
{
|
||||
guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", dbFrom.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?()
|
||||
@@ -820,34 +958,78 @@ extension Database {
|
||||
throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage)
|
||||
}
|
||||
|
||||
// The schema of the destination database has changed:
|
||||
dbDest.clearSchemaCache()
|
||||
}
|
||||
}
|
||||
|
||||
#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)!
|
||||
let code = data.withUnsafeBytes { bytes in
|
||||
sqlite3_rekey(sqliteConnection, bytes, Int32(data.count))
|
||||
}
|
||||
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 {
|
||||
// Support for the deprecated method change(passphrase:).
|
||||
// After it has been called, the passphrase used for opening the
|
||||
// database must be ignored.
|
||||
if configuration._passphrase != nil {
|
||||
return
|
||||
}
|
||||
try _usePassphrase(passphrase)
|
||||
}
|
||||
|
||||
/// See usePassphrase(_:)
|
||||
private func _usePassphrase(_ passphrase: String) throws {
|
||||
let data = passphrase.data(using: .utf8)!
|
||||
#if swift(>=5.0)
|
||||
let code = data.withUnsafeBytes {
|
||||
sqlite3_key(sqliteConnection, $0.baseAddress, Int32($0.count))
|
||||
}
|
||||
#else
|
||||
let code = data.withUnsafeBytes {
|
||||
sqlite3_key(sqliteConnection, $0, Int32(data.count))
|
||||
}
|
||||
#endif
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)!
|
||||
#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)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
extension Database {
|
||||
@@ -871,6 +1053,7 @@ extension Database {
|
||||
///
|
||||
/// To set the busy mode of a database, use Configuration:
|
||||
///
|
||||
/// // Wait 1 second before failing with SQLITE_BUSY
|
||||
/// let configuration = Configuration(busyMode: .timeout(1))
|
||||
/// let dbQueue = DatabaseQueue(path: "...", configuration: configuration)
|
||||
///
|
||||
@@ -886,7 +1069,7 @@ extension Database {
|
||||
case immediateError
|
||||
|
||||
/// The SQLITE_BUSY error will be returned only if the database remains
|
||||
/// locked for more than the specified duration.
|
||||
/// locked for more than the specified duration (in seconds).
|
||||
case timeout(TimeInterval)
|
||||
|
||||
/// A custom callback that is called when a database is locked.
|
||||
@@ -905,7 +1088,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
|
||||
|
||||
@@ -936,7 +1119,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
|
||||
|
||||
@@ -977,7 +1160,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"
|
||||
@@ -988,7 +1171,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"
|
||||
@@ -1005,7 +1188,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,8 +1,10 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// A Collation is a string comparison function used by SQLite.
|
||||
@@ -16,7 +18,7 @@ public final class DatabaseCollation {
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// db.add(collation: collation)
|
||||
/// try db.execute("CREATE TABLE file (name TEXT COLLATE localized_standard")
|
||||
/// try db.execute(sql: "CREATE TABLE file (name TEXT COLLATE localized_standard")
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The function name.
|
||||
@@ -25,29 +27,37 @@ 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseCollation : Hashable {
|
||||
extension DatabaseCollation: Hashable {
|
||||
// Collation equality is based on the sqlite3_strnicmp SQLite function.
|
||||
// (see https://www.sqlite.org/c3ref/create_collation.html). Computing
|
||||
// a hash value that honors the Swift Hashable contract (value equality
|
||||
// implies hash equality) is thus non trivial. But it's not that
|
||||
// important, since this hashValue is only used when one adds
|
||||
// or removes a collation from a database connection.
|
||||
/// :nodoc:
|
||||
public var hashValue: Int {
|
||||
// Collation equality is based on the sqlite3_strnicmp SQLite function.
|
||||
// (see https://www.sqlite.org/c3ref/create_collation.html). Computing
|
||||
// a hash value that honors the Swift Hashable contract (value equality
|
||||
// implies hash equality) is thus non trivial. But it's not that
|
||||
// important, since this hashValue is only used when one adds
|
||||
// or removes a collation from a database connection.
|
||||
return 0
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(0)
|
||||
}
|
||||
|
||||
/// Two collations are equal if they share the same name (case insensitive)
|
||||
/// :nodoc:
|
||||
public static func == (lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool {
|
||||
// See https://www.sqlite.org/c3ref/create_collation.html
|
||||
return sqlite3_stricmp(lhs.name, lhs.name) == 0
|
||||
return sqlite3_stricmp(lhs.name, rhs.name) == 0
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible {
|
||||
public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
|
||||
public let rawValue: Int32
|
||||
|
||||
public init(rawValue: Int32) {
|
||||
@@ -46,6 +48,7 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
|
||||
// Primary Result codes
|
||||
// https://www.sqlite.org/rescode.html#primary_result_code_list
|
||||
|
||||
// swiftlint:disable operator_usage_whitespace
|
||||
public static let SQLITE_OK = ResultCode(rawValue: 0) // Successful result
|
||||
public static let SQLITE_ERROR = ResultCode(rawValue: 1) // SQL error or missing database
|
||||
public static let SQLITE_INTERNAL = ResultCode(rawValue: 2) // Internal logic error in SQLite
|
||||
@@ -77,10 +80,15 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
|
||||
public static let SQLITE_WARNING = ResultCode(rawValue: 28) // Warnings from sqlite3_log()
|
||||
public static let SQLITE_ROW = ResultCode(rawValue: 100) // sqlite3_step() has another row ready
|
||||
public static let SQLITE_DONE = ResultCode(rawValue: 101) // sqlite3_step() has finished executing
|
||||
// swiftlint:enable operator_usage_whitespace
|
||||
|
||||
// Extended Result Code
|
||||
// https://www.sqlite.org/rescode.html#extended_result_code_list
|
||||
|
||||
// swiftlint:disable operator_usage_whitespace line_length
|
||||
public static let SQLITE_ERROR_MISSING_COLLSEQ = ResultCode(rawValue: (SQLITE_ERROR.rawValue | (1<<8)))
|
||||
public static let SQLITE_ERROR_RETRY = ResultCode(rawValue: (SQLITE_ERROR.rawValue | (2<<8)))
|
||||
public static let SQLITE_ERROR_SNAPSHOT = ResultCode(rawValue: (SQLITE_ERROR.rawValue | (3<<8)))
|
||||
public static let SQLITE_IOERR_READ = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (1<<8)))
|
||||
public static let SQLITE_IOERR_SHORT_READ = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (2<<8)))
|
||||
public static let SQLITE_IOERR_WRITE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (3<<8)))
|
||||
@@ -109,18 +117,26 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
|
||||
public static let SQLITE_IOERR_CONVPATH = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (26<<8)))
|
||||
public static let SQLITE_IOERR_VNODE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (27<<8)))
|
||||
public static let SQLITE_IOERR_AUTH = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (28<<8)))
|
||||
public static let SQLITE_IOERR_BEGIN_ATOMIC = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (29<<8)))
|
||||
public static let SQLITE_IOERR_COMMIT_ATOMIC = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (30<<8)))
|
||||
public static let SQLITE_IOERR_ROLLBACK_ATOMIC = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (31<<8)))
|
||||
public static let SQLITE_LOCKED_SHAREDCACHE = ResultCode(rawValue: (SQLITE_LOCKED.rawValue | (1<<8)))
|
||||
public static let SQLITE_LOCKED_VTAB = ResultCode(rawValue: (SQLITE_LOCKED.rawValue | (2<<8)))
|
||||
public static let SQLITE_BUSY_RECOVERY = ResultCode(rawValue: (SQLITE_BUSY.rawValue | (1<<8)))
|
||||
public static let SQLITE_BUSY_SNAPSHOT = ResultCode(rawValue: (SQLITE_BUSY.rawValue | (2<<8)))
|
||||
public static let SQLITE_CANTOPEN_NOTEMPDIR = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (1<<8)))
|
||||
public static let SQLITE_CANTOPEN_ISDIR = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (2<<8)))
|
||||
public static let SQLITE_CANTOPEN_FULLPATH = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (3<<8)))
|
||||
public static let SQLITE_CANTOPEN_CONVPATH = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (4<<8)))
|
||||
public static let SQLITE_CANTOPEN_DIRTYWAL = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (5<<8))) /* Not Used */
|
||||
public static let SQLITE_CORRUPT_VTAB = ResultCode(rawValue: (SQLITE_CORRUPT.rawValue | (1<<8)))
|
||||
public static let SQLITE_CORRUPT_SEQUENCE = ResultCode(rawValue: (SQLITE_CORRUPT.rawValue | (2<<8)))
|
||||
public static let SQLITE_READONLY_RECOVERY = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (1<<8)))
|
||||
public static let SQLITE_READONLY_CANTLOCK = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (2<<8)))
|
||||
public static let SQLITE_READONLY_ROLLBACK = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (3<<8)))
|
||||
public static let SQLITE_READONLY_DBMOVED = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (4<<8)))
|
||||
public static let SQLITE_READONLY_CANTINIT = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (5<<8)))
|
||||
public static let SQLITE_READONLY_DIRECTORY = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (6<<8)))
|
||||
public static let SQLITE_ABORT_ROLLBACK = ResultCode(rawValue: (SQLITE_ABORT.rawValue | (2<<8)))
|
||||
public static let SQLITE_CONSTRAINT_CHECK = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (1<<8)))
|
||||
public static let SQLITE_CONSTRAINT_COMMITHOOK = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (2<<8)))
|
||||
@@ -137,28 +153,38 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
|
||||
public static let SQLITE_WARNING_AUTOINDEX = ResultCode(rawValue: (SQLITE_WARNING.rawValue | (1<<8)))
|
||||
public static let SQLITE_AUTH_USER = ResultCode(rawValue: (SQLITE_AUTH.rawValue | (1<<8)))
|
||||
public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8)))
|
||||
// swiftlint:enable operator_usage_whitespace line_length
|
||||
}
|
||||
|
||||
// CustomStringConvertible
|
||||
extension ResultCode {
|
||||
var errorString: String? {
|
||||
// sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15
|
||||
// It is available from iOS 8.2 and OS X 10.10
|
||||
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
return String(cString: sqlite3_errstr(rawValue))
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) {
|
||||
return String(cString: sqlite3_errstr(rawValue))
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
// sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, iOSApplicationExtension 8.2, *) {
|
||||
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
|
||||
} else {
|
||||
return "\(rawValue)"
|
||||
}
|
||||
#endif
|
||||
if let errorString = errorString {
|
||||
return "\(rawValue) (\(errorString))"
|
||||
} else {
|
||||
return "\(rawValue)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// DatabaseError wraps an SQLite error.
|
||||
public struct DatabaseError : Error, CustomStringConvertible, CustomNSError {
|
||||
public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
|
||||
/// The SQLite error code (see
|
||||
/// https://www.sqlite.org/rescode.html#primary_result_code_list).
|
||||
@@ -197,9 +223,14 @@ public struct DatabaseError : Error, CustomStringConvertible, CustomNSError {
|
||||
public let sql: String?
|
||||
|
||||
/// Creates a Database Error
|
||||
public init(resultCode: ResultCode = .SQLITE_ERROR, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
|
||||
public init(
|
||||
resultCode: ResultCode = .SQLITE_ERROR,
|
||||
message: String? = nil,
|
||||
sql: String? = nil,
|
||||
arguments: StatementArguments? = nil)
|
||||
{
|
||||
self.extendedResultCode = resultCode
|
||||
self.message = message
|
||||
self.message = message ?? resultCode.errorString
|
||||
self.sql = sql
|
||||
self.arguments = arguments
|
||||
}
|
||||
@@ -254,7 +285,7 @@ extension DatabaseError {
|
||||
|
||||
/// NSError bridging: the user-info dictionary.
|
||||
/// :nodoc:
|
||||
public var errorUserInfo: [String : Any] {
|
||||
public var errorUserInfo: [String: Any] {
|
||||
return [NSLocalizedDescriptionKey: description]
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// An SQL function or aggregate.
|
||||
@@ -27,7 +29,7 @@ public final class DatabaseFunction: Hashable {
|
||||
/// return int + 1
|
||||
/// }
|
||||
/// db.add(function: fn)
|
||||
/// try Int.fetchOne(db, "SELECT succ(1)")! // 2
|
||||
/// try Int.fetchOne(db, sql: "SELECT succ(1)")! // 2
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The function name.
|
||||
@@ -42,7 +44,12 @@ public final class DatabaseFunction: Hashable {
|
||||
/// as Int, String, NSDate, etc. The array is guaranteed to have
|
||||
/// exactly *argumentCount* elements, provided *argumentCount* is
|
||||
/// not nil.
|
||||
public init(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?) {
|
||||
public init(
|
||||
_ name: String,
|
||||
argumentCount: Int32? = nil,
|
||||
pure: Bool = false,
|
||||
function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?)
|
||||
{
|
||||
self.identity = Identity(name: name, nArg: argumentCount ?? -1)
|
||||
self.pure = pure
|
||||
self.kind = .function{ (argc, argv) in
|
||||
@@ -73,10 +80,10 @@ public final class DatabaseFunction: Hashable {
|
||||
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// dbQueue.add(function: fn)
|
||||
/// try dbQueue.write { db in
|
||||
/// try db.execute("CREATE TABLE test(i)")
|
||||
/// try db.execute("INSERT INTO test(i) VALUES (1)")
|
||||
/// try db.execute("INSERT INTO test(i) VALUES (2)")
|
||||
/// try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
|
||||
/// try db.execute(sql: "CREATE TABLE test(i)")
|
||||
/// try db.execute(sql: "INSERT INTO test(i) VALUES (1)")
|
||||
/// try db.execute(sql: "INSERT INTO test(i) VALUES (2)")
|
||||
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
|
||||
/// }
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -92,10 +99,15 @@ public final class DatabaseFunction: Hashable {
|
||||
/// an array of DatabaseValue arguments. The array is guaranteed to
|
||||
/// have exactly *argumentCount* elements, provided *argumentCount* is
|
||||
/// not nil.
|
||||
public init<Aggregate: DatabaseAggregate>(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, aggregate: Aggregate.Type) {
|
||||
public init<Aggregate: DatabaseAggregate>(
|
||||
_ name: String,
|
||||
argumentCount: Int32? = nil,
|
||||
pure: Bool = false,
|
||||
aggregate: Aggregate.Type)
|
||||
{
|
||||
self.identity = Identity(name: name, nArg: argumentCount ?? -1)
|
||||
self.pure = pure
|
||||
self.kind = .aggregate { return Aggregate() }
|
||||
self.kind = .aggregate { Aggregate() }
|
||||
}
|
||||
|
||||
/// Calls sqlite3_create_function_v2
|
||||
@@ -195,7 +207,9 @@ public final class DatabaseFunction: Hashable {
|
||||
var xFunc: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
|
||||
guard case .function = self else { return nil }
|
||||
return { (sqliteContext, argc, argv) in
|
||||
let definition = Unmanaged<FunctionDefinition>.fromOpaque(sqlite3_user_data(sqliteContext)).takeUnretainedValue()
|
||||
let definition = Unmanaged<FunctionDefinition>
|
||||
.fromOpaque(sqlite3_user_data(sqliteContext))
|
||||
.takeUnretainedValue()
|
||||
do {
|
||||
try DatabaseFunction.report(
|
||||
result: definition.compute(argc, argv),
|
||||
@@ -260,11 +274,15 @@ public final class DatabaseFunction: Hashable {
|
||||
private static func unmanagedAggregateContext(_ sqliteContext: OpaquePointer?) -> Unmanaged<AggregateContext> {
|
||||
// The current aggregate buffer
|
||||
let stride = MemoryLayout<Unmanaged<AggregateContext>>.stride
|
||||
let aggregateContextBufferP = UnsafeMutableRawBufferPointer(start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!, count: stride)
|
||||
let aggregateContextBufferP = UnsafeMutableRawBufferPointer(
|
||||
start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!,
|
||||
count: stride)
|
||||
|
||||
if aggregateContextBufferP.contains(where: { $0 != 0 }) {
|
||||
if aggregateContextBufferP.contains(where: { $0 != 0 }) { // TODO: This testt looks weird. Review.
|
||||
// Buffer contains non-null pointer: load aggregate context
|
||||
let aggregateContextP = aggregateContextBufferP.baseAddress!.assumingMemoryBound(to: Unmanaged<AggregateContext>.self)
|
||||
let aggregateContextP = aggregateContextBufferP
|
||||
.baseAddress!
|
||||
.assumingMemoryBound(to: Unmanaged<AggregateContext>.self)
|
||||
return aggregateContextP.pointee
|
||||
} else {
|
||||
// Buffer contains null pointer: create aggregate context...
|
||||
@@ -275,8 +293,8 @@ public final class DatabaseFunction: Hashable {
|
||||
|
||||
// retain and store in SQLite's buffer
|
||||
let aggregateContextU = Unmanaged.passRetained(aggregateContext)
|
||||
var aggregateContextP = aggregateContextU.toOpaque()
|
||||
withUnsafeBytes(of: &aggregateContextP) {
|
||||
let aggregateContextP = aggregateContextU.toOpaque()
|
||||
withUnsafeBytes(of: aggregateContextP) {
|
||||
aggregateContextBufferP.copyMemory(from: $0)
|
||||
}
|
||||
return aggregateContextU
|
||||
@@ -294,9 +312,15 @@ public final class DatabaseFunction: Hashable {
|
||||
case .string(let string):
|
||||
sqlite3_result_text(sqliteContext, string, -1, SQLITE_TRANSIENT)
|
||||
case .blob(let data):
|
||||
data.withUnsafeBytes { bytes in
|
||||
sqlite3_result_blob(sqliteContext, bytes, Int32(data.count), SQLITE_TRANSIENT)
|
||||
#if swift(>=5.0)
|
||||
data.withUnsafeBytes {
|
||||
sqlite3_result_blob(sqliteContext, $0.baseAddress, Int32($0.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
#else
|
||||
data.withUnsafeBytes {
|
||||
sqlite3_result_blob(sqliteContext, $0, Int32(data.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -313,10 +337,9 @@ public final class DatabaseFunction: Hashable {
|
||||
}
|
||||
|
||||
extension DatabaseFunction {
|
||||
/// The hash value
|
||||
/// :nodoc:
|
||||
public var hashValue: Int {
|
||||
return identity.hashValue
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(identity)
|
||||
}
|
||||
|
||||
/// Two functions are equal if they share the same name and arity.
|
||||
@@ -348,10 +371,10 @@ extension DatabaseFunction {
|
||||
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// dbQueue.add(function: fn)
|
||||
/// try dbQueue.write { db in
|
||||
/// try db.execute("CREATE TABLE test(i)")
|
||||
/// try db.execute("INSERT INTO test(i) VALUES (1)")
|
||||
/// try db.execute("INSERT INTO test(i) VALUES (2)")
|
||||
/// try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
|
||||
/// try db.execute(sql: "CREATE TABLE test(i)")
|
||||
/// try db.execute(sql: "INSERT INTO test(i) VALUES (1)")
|
||||
/// try db.execute(sql: "INSERT INTO test(i) VALUES (2)")
|
||||
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
|
||||
/// }
|
||||
public protocol DatabaseAggregate {
|
||||
/// Creates an aggregate.
|
||||
|
||||
@@ -1,23 +1,27 @@
|
||||
import Foundation
|
||||
import Dispatch
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
import SQLite3
|
||||
#endif
|
||||
#if os(iOS)
|
||||
import UIKit
|
||||
import UIKit
|
||||
#endif
|
||||
|
||||
/// A DatabasePool grants concurrent accesses to an SQLite database.
|
||||
public final class DatabasePool: DatabaseWriter {
|
||||
private let writer: SerializedDatabase
|
||||
private var readerConfig: Configuration
|
||||
private var readerPool: Pool<SerializedDatabase>!
|
||||
var readerConfiguration: Configuration
|
||||
|
||||
private var functions = Set<DatabaseFunction>()
|
||||
private var collations = Set<DatabaseCollation>()
|
||||
private var tokenizerRegistrations: [(Database) -> Void] = []
|
||||
|
||||
var snapshotCount = ReadWriteBox(0)
|
||||
var databaseSnapshotCount = LockedBox(value: 0)
|
||||
|
||||
#if os(iOS)
|
||||
private weak var application: UIApplication?
|
||||
@@ -30,6 +34,10 @@ public final class DatabasePool: DatabaseWriter {
|
||||
return writer.path
|
||||
}
|
||||
|
||||
public var configuration: Configuration {
|
||||
return writer.configuration
|
||||
}
|
||||
|
||||
// MARK: - Initializer
|
||||
|
||||
/// Opens the SQLite database at path *path*.
|
||||
@@ -50,19 +58,43 @@ public final class DatabasePool: DatabaseWriter {
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
schemaCache: SimpleDatabaseSchemaCache(),
|
||||
label: (configuration.label ?? "GRDB.DatabasePool") + ".writer")
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "writer")
|
||||
|
||||
// Readers
|
||||
readerConfiguration = configuration
|
||||
readerConfiguration.readonly = true
|
||||
// Readers use deferred transactions by default.
|
||||
// Other transaction kinds are forbidden by SQLite in read-only connections.
|
||||
readerConfiguration.defaultTransactionKind = .deferred
|
||||
// Readers can't allow dangling transactions because there's no
|
||||
// guarantee that one can get the same reader later in order to close
|
||||
// an opened transaction.
|
||||
readerConfiguration.allowsUnsafeTransactions = false
|
||||
var readerCount = 0
|
||||
readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: { [unowned self] in
|
||||
readerCount += 1 // protected by pool (TODO: documented this protection behavior)
|
||||
let reader = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: self.readerConfiguration,
|
||||
schemaCache: SimpleDatabaseSchemaCache(),
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "reader.\(readerCount)")
|
||||
reader.sync { self.setupDatabase($0) }
|
||||
return reader
|
||||
})
|
||||
|
||||
// Activate WAL Mode unless readonly
|
||||
if !configuration.readonly {
|
||||
try writer.sync { db in
|
||||
let journalMode = try String.fetchOne(db, "PRAGMA journal_mode = WAL")
|
||||
let journalMode = try String.fetchOne(db, sql: "PRAGMA journal_mode = WAL")
|
||||
guard journalMode == "wal" else {
|
||||
throw DatabaseError(message: "could not activate WAL Mode at path: \(path)")
|
||||
}
|
||||
|
||||
// https://www.sqlite.org/pragma.html#pragma_synchronous
|
||||
// > Many applications choose NORMAL when in WAL mode
|
||||
try db.execute("PRAGMA synchronous = NORMAL")
|
||||
try db.execute(sql: "PRAGMA synchronous = NORMAL")
|
||||
|
||||
if !FileManager.default.fileExists(atPath: path + "-wal") {
|
||||
// Create the -wal file if it does not exist yet. This
|
||||
@@ -70,27 +102,16 @@ public final class DatabasePool: DatabaseWriter {
|
||||
// opens a pool to an existing non-WAL database, and
|
||||
// attempts to read from it.
|
||||
// See https://github.com/groue/GRDB.swift/issues/102
|
||||
try db.execute("CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY); DROP TABLE grdb_issue_102;")
|
||||
try db.inSavepoint {
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY);
|
||||
DROP TABLE grdb_issue_102;
|
||||
""")
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Readers
|
||||
readerConfig = configuration
|
||||
readerConfig.readonly = true
|
||||
readerConfig.defaultTransactionKind = .deferred // Make it the default for readers. Other transaction kinds are forbidden by SQLite in read-only connections.
|
||||
readerConfig.allowsUnsafeTransactions = false // Because there's no guarantee that one can get the same reader in order to close its opened transaction.
|
||||
var readerCount = 0
|
||||
readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: { [unowned self] in
|
||||
readerCount += 1 // protected by pool's ReadWriteBox (undocumented behavior and protection)
|
||||
let reader = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: self.readerConfig,
|
||||
schemaCache: SimpleDatabaseSchemaCache(),
|
||||
label: (self.readerConfig.label ?? "GRDB.DatabasePool") + ".reader.\(readerCount)")
|
||||
reader.sync { self.setupDatabase($0) }
|
||||
return reader
|
||||
})
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
@@ -104,19 +125,29 @@ public final class DatabasePool: DatabaseWriter {
|
||||
#endif
|
||||
|
||||
private func setupDatabase(_ db: Database) {
|
||||
for function in self.functions {
|
||||
for function in functions {
|
||||
db.add(function: function)
|
||||
}
|
||||
for collation in self.collations {
|
||||
for collation in collations {
|
||||
db.add(collation: collation)
|
||||
}
|
||||
for registration in tokenizerRegistrations {
|
||||
registration(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocks the current thread until all database connections have
|
||||
/// executed the *body* block.
|
||||
fileprivate func forEachConnection(_ body: (Database) -> Void) {
|
||||
writer.sync(body)
|
||||
readerPool.forEach { $0.sync(body) }
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
|
||||
// MARK: - WAL Checkpoints
|
||||
|
||||
|
||||
/// Runs a WAL checkpoint
|
||||
///
|
||||
/// See https://www.sqlite.org/wal.html and
|
||||
@@ -126,33 +157,28 @@ extension DatabasePool {
|
||||
/// - parameter kind: The checkpoint mode (default passive)
|
||||
public func checkpoint(_ kind: Database.CheckpointMode = .passive) throws {
|
||||
try writer.sync { db in
|
||||
// TODO: read https://www.sqlite.org/c3ref/wal_checkpoint_v2.html and
|
||||
// check whether we need a busy handler on writer and/or readers
|
||||
// when kind is not .Passive.
|
||||
let code = sqlite3_wal_checkpoint_v2(db.sqliteConnection, nil, kind.rawValue, nil, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: db.lastErrorMessage, sql: nil)
|
||||
}
|
||||
try db.checkpoint(kind)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
|
||||
// MARK: - Memory management
|
||||
|
||||
|
||||
/// Free as much memory as possible.
|
||||
///
|
||||
/// This method blocks the current thread until all database accesses are completed.
|
||||
/// This method blocks the current thread until all database accesses
|
||||
/// are completed.
|
||||
///
|
||||
/// See also setupMemoryManagement(application:)
|
||||
public func releaseMemory() {
|
||||
// TODO: test that this method blocks the current thread until all database accesses are completed.
|
||||
// Release writer memory
|
||||
writer.sync { $0.releaseMemory() }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.releaseMemory() }
|
||||
// Release readers memory by closing all connections
|
||||
readerPool.barrier {
|
||||
readerPool.removeAll()
|
||||
}
|
||||
readerPool.clear()
|
||||
}
|
||||
|
||||
|
||||
@@ -167,19 +193,26 @@ extension DatabasePool {
|
||||
public func setupMemoryManagement(in application: UIApplication) {
|
||||
self.application = application
|
||||
let center = NotificationCenter.default
|
||||
center.addObserver(self, selector: #selector(DatabasePool.applicationDidReceiveMemoryWarning(_:)), name: .UIApplicationDidReceiveMemoryWarning, object: nil)
|
||||
center.addObserver(self, selector: #selector(DatabasePool.applicationDidEnterBackground(_:)), name: .UIApplicationDidEnterBackground, object: nil)
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabasePool.applicationDidReceiveMemoryWarning(_:)),
|
||||
name: UIApplication.didReceiveMemoryWarningNotification,
|
||||
object: nil)
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabasePool.applicationDidEnterBackground(_:)),
|
||||
name: UIApplication.didEnterBackgroundNotification,
|
||||
object: nil)
|
||||
}
|
||||
|
||||
@objc private func applicationDidEnterBackground(_ notification: NSNotification) {
|
||||
@objc
|
||||
private func applicationDidEnterBackground(_ notification: NSNotification) {
|
||||
guard let application = application else {
|
||||
return
|
||||
}
|
||||
|
||||
var task: UIBackgroundTaskIdentifier! = nil
|
||||
task = application.beginBackgroundTask(expirationHandler: nil)
|
||||
|
||||
if task == UIBackgroundTaskInvalid {
|
||||
let task: UIBackgroundTaskIdentifier = application.beginBackgroundTask(expirationHandler: nil)
|
||||
if task == .invalid {
|
||||
// Perform releaseMemory() synchronously.
|
||||
releaseMemory()
|
||||
} else {
|
||||
@@ -191,7 +224,8 @@ extension DatabasePool {
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
|
||||
@objc
|
||||
private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
|
||||
DispatchQueue.global().async {
|
||||
self.releaseMemory()
|
||||
}
|
||||
@@ -200,24 +234,26 @@ extension DatabasePool {
|
||||
}
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
extension DatabasePool {
|
||||
|
||||
// MARK: - Encryption
|
||||
|
||||
/// Changes the passphrase of an encrypted database
|
||||
public func change(passphrase: String) throws {
|
||||
try readerPool.clear(andThen: {
|
||||
try writer.sync { try $0.change(passphrase: passphrase) }
|
||||
readerConfig.passphrase = passphrase
|
||||
})
|
||||
extension DatabasePool {
|
||||
|
||||
// MARK: - Encryption
|
||||
|
||||
/// Changes the passphrase of an encrypted database
|
||||
@available(*, deprecated, message: "Use Database.changePassphrase(_:) instead")
|
||||
public func change(passphrase: String) throws {
|
||||
try readerPool.barrier {
|
||||
try writer.sync { try $0.changePassphrase(passphrase) }
|
||||
readerPool.removeAll()
|
||||
readerConfiguration._passphrase = passphrase
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
extension DatabasePool : DatabaseReader {
|
||||
extension DatabasePool: DatabaseReader {
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
|
||||
/// Synchronously executes a read-only block in a protected dispatch queue,
|
||||
/// and returns its result. The block is wrapped in a deferred transaction.
|
||||
///
|
||||
@@ -231,13 +267,13 @@ extension DatabasePool : DatabaseReader {
|
||||
/// try dbPool.read { db in
|
||||
/// // Those two values are guaranteed to be equal, even if the
|
||||
/// // `wine` table is modified between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// let count1 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
|
||||
/// let count2 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
|
||||
/// }
|
||||
///
|
||||
/// try dbPool.read { db in
|
||||
/// // Now this value may be different:
|
||||
/// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// let count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
@@ -254,8 +290,9 @@ extension DatabasePool : DatabaseReader {
|
||||
// See DatabasePoolTests.testReadMethodIsolationOfBlock().
|
||||
try db.inTransaction(.deferred) {
|
||||
// Reset the schema cache before running user code in snapshot isolation
|
||||
db.schemaCache = SimpleDatabaseSchemaCache()
|
||||
result = try block(db)
|
||||
result = try db.withSchemaCache(SimpleDatabaseSchemaCache()) {
|
||||
try block(db)
|
||||
}
|
||||
return .commit
|
||||
}
|
||||
return result!
|
||||
@@ -263,6 +300,58 @@ extension DatabasePool : DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// Asynchronously executes a read-only block in a protected dispatch queue.
|
||||
///
|
||||
/// let players = try dbQueue.asyncRead { result in
|
||||
/// do {
|
||||
/// let db = try result.get()
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // Handle error
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
|
||||
/// SQLCipher), attempts to write in the database from this method throw a
|
||||
/// DatabaseError of resultCode `SQLITE_READONLY`.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
public func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void) {
|
||||
// First async jump in order to grab a reader connection.
|
||||
// Honor configuration dispatching (qos/targetQueue).
|
||||
configuration
|
||||
.makeDispatchQueue(defaultLabel: "GRDB.DatabasePool", purpose: "asyncRead")
|
||||
.async {
|
||||
do {
|
||||
let (reader, releaseReader) = try self.readerPool.get()
|
||||
|
||||
// Second async jump because sync could deadlock if
|
||||
// configuration has a serial targetQueue.
|
||||
reader.async { db in
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader()
|
||||
}
|
||||
do {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.beginTransaction(.deferred)
|
||||
|
||||
// Reset the schema cache before running user code in snapshot isolation
|
||||
db.withSchemaCache(SimpleDatabaseSchemaCache()) {
|
||||
block(.success(db))
|
||||
}
|
||||
} catch {
|
||||
block(.failure(error))
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
block(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Synchronously executes a read-only block in a protected dispatch queue,
|
||||
/// and returns its result.
|
||||
///
|
||||
@@ -272,15 +361,15 @@ extension DatabasePool : DatabaseReader {
|
||||
/// try dbPool.unsafeRead { db in
|
||||
/// // Those two values may be different because some other thread
|
||||
/// // may have inserted or deleted a wine between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// let count1 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
|
||||
/// let count2 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
|
||||
/// }
|
||||
///
|
||||
/// Cursor iteration is safe, though:
|
||||
///
|
||||
/// try dbPool.unsafeRead { db in
|
||||
/// // No concurrent update can mess with this iteration:
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT ...")
|
||||
/// let rows = try Row.fetchCursor(db, sql: "SELECT ...")
|
||||
/// while let row = try rows.next() { ... }
|
||||
/// }
|
||||
///
|
||||
@@ -294,8 +383,9 @@ extension DatabasePool : DatabaseReader {
|
||||
return try readerPool.get { reader in
|
||||
try reader.sync { db in
|
||||
// No schema cache when snapshot isolation is not established
|
||||
db.schemaCache = EmptyDatabaseSchemaCache()
|
||||
return try block(db)
|
||||
return try db.withSchemaCache(EmptyDatabaseSchemaCache()) {
|
||||
try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -309,15 +399,15 @@ extension DatabasePool : DatabaseReader {
|
||||
/// try dbPool.unsafeReentrantRead { db in
|
||||
/// // Those two values may be different because some other thread
|
||||
/// // may have inserted or deleted a wine between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// let count1 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
|
||||
/// let count2 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
|
||||
/// }
|
||||
///
|
||||
/// Cursor iteration is safe, though:
|
||||
///
|
||||
/// try dbPool.unsafeReentrantRead { db in
|
||||
/// // No concurrent update can mess with this iteration:
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT ...")
|
||||
/// let rows = try Row.fetchCursor(db, sql: "SELECT ...")
|
||||
/// while let row = try rows.next() { ... }
|
||||
/// }
|
||||
///
|
||||
@@ -334,121 +424,190 @@ extension DatabasePool : DatabaseReader {
|
||||
return try readerPool.get { reader in
|
||||
try reader.sync { db in
|
||||
// No schema cache when snapshot isolation is not established
|
||||
db.schemaCache = EmptyDatabaseSchemaCache()
|
||||
return try block(db)
|
||||
return try db.withSchemaCache(EmptyDatabaseSchemaCache()) {
|
||||
try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Asynchronously executes a read-only block in a protected dispatch queue,
|
||||
/// wrapped in a deferred transaction.
|
||||
public func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
// The semaphore that blocks until futureResult is defined:
|
||||
let futureSemaphore = DispatchSemaphore(value: 0)
|
||||
var futureResult: DatabaseResult<T>? = nil
|
||||
|
||||
#if compiler(>=5.0)
|
||||
asyncConcurrentRead { db in
|
||||
// Fetch and release the future
|
||||
futureResult = DatabaseResult { try block(db.get()) }
|
||||
futureSemaphore.signal()
|
||||
}
|
||||
#else
|
||||
// Check that we're on the writer queue...
|
||||
writer.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
GRDBPrecondition(!db.isInsideTransaction, """
|
||||
must not be called from inside a transaction. \
|
||||
If this error is raised from a DatabasePool.write block, use \
|
||||
DatabasePool.writeWithoutTransaction instead (and use \
|
||||
transactions when needed).
|
||||
""")
|
||||
}
|
||||
|
||||
// The semaphore that blocks the writing dispatch queue until snapshot
|
||||
// isolation has been established:
|
||||
let isolationSemaphore = DispatchSemaphore(value: 0)
|
||||
|
||||
do {
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
reader.async { db in
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader()
|
||||
}
|
||||
do {
|
||||
try db.beginSnapshotTransaction()
|
||||
} catch {
|
||||
futureResult = .failure(error)
|
||||
isolationSemaphore.signal()
|
||||
futureSemaphore.signal()
|
||||
return
|
||||
}
|
||||
|
||||
// Release the writer queue
|
||||
isolationSemaphore.signal()
|
||||
|
||||
// Reset the schema cache before running user code in snapshot isolation
|
||||
db.schemaCache = SimpleDatabaseSchemaCache()
|
||||
|
||||
// Fetch and release the future
|
||||
futureResult = DatabaseResult { try block(db) }
|
||||
futureSemaphore.signal()
|
||||
}
|
||||
} catch {
|
||||
futureResult = .failure(error)
|
||||
isolationSemaphore.signal()
|
||||
futureSemaphore.signal()
|
||||
}
|
||||
|
||||
// Block the writer queue until snapshot isolation success or error
|
||||
_ = isolationSemaphore.wait(timeout: .distantFuture)
|
||||
#endif
|
||||
|
||||
return DatabaseFuture {
|
||||
// Block the future until results are fetched
|
||||
_ = futureSemaphore.wait(timeout: .distantFuture)
|
||||
return try futureResult!.get()
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// Performs the same job as asyncConcurrentRead.
|
||||
///
|
||||
/// This method must be called from the writing dispatch queue, outside of a
|
||||
/// :nodoc:
|
||||
public func spawnConcurrentRead(_ block: @escaping (Result<Database, Error>) -> Void) {
|
||||
asyncConcurrentRead(block)
|
||||
}
|
||||
#endif
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// Asynchronously executes a read-only block in a protected dispatch queue.
|
||||
///
|
||||
/// This method must be called from a writing dispatch queue, outside of any
|
||||
/// transaction. You'll get a fatal error otherwise.
|
||||
///
|
||||
/// The *block* argument is guaranteed to see the database in the last
|
||||
/// committed state at the moment this method is called. Eventual concurrent
|
||||
/// database updates are *not visible* inside the block.
|
||||
///
|
||||
/// try dbPool.write { db in
|
||||
/// try db.execute("DELETE FROM player")
|
||||
/// try dbPool.readFromCurrentState { db in
|
||||
/// // Guaranteed to be zero
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM player")!
|
||||
/// This method returns as soon as the isolation guarantees described above
|
||||
/// are established.
|
||||
///
|
||||
/// In the example below, the number of players is fetched concurrently with
|
||||
/// the player insertion. Yet the future is guaranteed to return zero:
|
||||
///
|
||||
/// try writer.asyncWriteWithoutTransaction { db in
|
||||
/// // Delete all players
|
||||
/// try Player.deleteAll()
|
||||
///
|
||||
/// // Count players concurrently
|
||||
/// writer.asyncConcurrentRead { result in
|
||||
/// do {
|
||||
/// let db = try result.get()
|
||||
/// // Guaranteed to be zero
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // Handle error
|
||||
/// }
|
||||
/// }
|
||||
/// try db.execute("INSERT INTO player ...")
|
||||
///
|
||||
/// // Insert a player
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
///
|
||||
/// This method blocks the current thread until the isolation guarantee has
|
||||
/// been established, and before the block argument has run.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
/// happen while establishing the read access to the database.
|
||||
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws {
|
||||
// https://www.sqlite.org/isolation.html
|
||||
//
|
||||
// > In WAL mode, SQLite exhibits "snapshot isolation". When a read
|
||||
// > transaction starts, that reader continues to see an unchanging
|
||||
// > "snapshot" of the database file as it existed at the moment in time
|
||||
// > when the read transaction started. Any write transactions that
|
||||
// > commit while the read transaction is active are still invisible to
|
||||
// > the read transaction, because the reader is seeing a snapshot of
|
||||
// > database file from a prior moment in time.
|
||||
//
|
||||
// That's exactly what we need. But what does "when read transaction
|
||||
// starts" mean?
|
||||
//
|
||||
// http://www.sqlite.org/lang_transaction.html
|
||||
//
|
||||
// > Deferred [transaction] means that no locks are acquired on the
|
||||
// > database until the database is first accessed. [...] Locks are not
|
||||
// > acquired until the first read or write operation. [...] Because the
|
||||
// > acquisition of locks is deferred until they are needed, it is
|
||||
// > possible that another thread or process could create a separate
|
||||
// > transaction and write to the database after the BEGIN on the
|
||||
// > current thread has executed.
|
||||
//
|
||||
// Now that's precise enough: SQLite defers "snapshot isolation" until
|
||||
// the first SELECT:
|
||||
//
|
||||
// Reader Writer
|
||||
// BEGIN DEFERRED TRANSACTION
|
||||
// UPDATE ... (1)
|
||||
// Here the change (1) is visible
|
||||
// SELECT ...
|
||||
// UPDATE ... (2)
|
||||
// Here the change (2) is not visible
|
||||
//
|
||||
// The readFromCurrentState method says that no change should be visible
|
||||
// at all. We thus have to perform a select that establishes the
|
||||
// snapshot isolation before we release the writer queue:
|
||||
//
|
||||
// Reader Writer
|
||||
// BEGIN DEFERRED TRANSACTION
|
||||
// SELECT anything
|
||||
// UPDATE ...
|
||||
// Here the change is not visible by GRDB user
|
||||
|
||||
public func asyncConcurrentRead(_ block: @escaping (Result<Database, Error>) -> Void) {
|
||||
// Check that we're on the writer queue...
|
||||
writer.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction. If this error is raised from a DatabasePool.write block, use DatabasePool.writeWithoutTransaction instead (and use transactions when needed).")
|
||||
GRDBPrecondition(!db.isInsideTransaction, """
|
||||
must not be called from inside a transaction. \
|
||||
If this error is raised from a DatabasePool.write block, use \
|
||||
DatabasePool.writeWithoutTransaction instead (and use \
|
||||
transactions when needed).
|
||||
""")
|
||||
}
|
||||
|
||||
// The semaphore that blocks the writing dispatch queue until snapshot
|
||||
// isolation has been established:
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
let isolationSemaphore = DispatchSemaphore(value: 0)
|
||||
|
||||
var readError: Error? = nil
|
||||
try readerPool.get { reader in
|
||||
do {
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
reader.async { db in
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader()
|
||||
}
|
||||
do {
|
||||
try db.beginTransaction(.deferred)
|
||||
assert(db.isInsideTransaction)
|
||||
try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").cursor().next()
|
||||
try db.beginSnapshotTransaction()
|
||||
} catch {
|
||||
readError = error
|
||||
semaphore.signal() // Release the writer queue and rethrow error
|
||||
isolationSemaphore.signal()
|
||||
block(.failure(error))
|
||||
return
|
||||
}
|
||||
semaphore.signal() // We can release the writer queue now that we are isolated for good
|
||||
|
||||
// Release the writer queue
|
||||
isolationSemaphore.signal()
|
||||
|
||||
// Reset the schema cache before running user code in snapshot isolation
|
||||
db.schemaCache = SimpleDatabaseSchemaCache()
|
||||
block(db)
|
||||
|
||||
_ = try? db.commit() // Ignore commit error
|
||||
db.withSchemaCache(SimpleDatabaseSchemaCache()) {
|
||||
// Fetch and release the future
|
||||
block(.success(db))
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
isolationSemaphore.signal()
|
||||
block(.failure(error))
|
||||
}
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
if let readError = readError {
|
||||
// TODO: write a test for this
|
||||
throw readError
|
||||
}
|
||||
|
||||
// Block the writer queue until snapshot isolation success or error
|
||||
_ = isolationSemaphore.wait(timeout: .distantFuture)
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
/// Invalidates open read-only SQLite connections.
|
||||
///
|
||||
/// After this method is called, read-only database access methods will use
|
||||
/// new SQLite connections.
|
||||
///
|
||||
/// Eventual concurrent read-only accesses are not invalidated: they will
|
||||
/// proceed until completion.
|
||||
public func invalidateReadOnlyConnections() {
|
||||
readerPool.removeAll()
|
||||
}
|
||||
|
||||
/// Returns a reader that can be used from the current dispatch queue,
|
||||
/// if any.
|
||||
private var currentReader: SerializedDatabase? {
|
||||
@@ -473,108 +632,101 @@ extension DatabasePool : DatabaseReader {
|
||||
|
||||
// MARK: - Writing in Database
|
||||
|
||||
/// Synchronously executes an update block in a protected dispatch queue,
|
||||
/// wrapped inside a transaction, and returns the result of the block.
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, and returns the result.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
/// Eventual concurrent database updates are postponed until the updates
|
||||
/// are completed.
|
||||
///
|
||||
/// try dbPool.write { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
///
|
||||
/// Eventual concurrent reads are guaranteed not to see any changes
|
||||
/// performed in the block until they are all saved in the database.
|
||||
/// Eventual concurrent reads may see partial updates unless you wrap them
|
||||
/// in a transaction.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameters block: A block that executes SQL statements.
|
||||
/// - throws: The error thrown by the block, or by the wrapping transaction.
|
||||
public func write<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try writer.sync { db in
|
||||
var result: T? = nil
|
||||
try db.inTransaction {
|
||||
result = try block(db)
|
||||
return .commit
|
||||
}
|
||||
return result!
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates.
|
||||
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.sync(updates)
|
||||
}
|
||||
|
||||
/// A barrier write ensures that no database access is executed until all
|
||||
/// previous accesses have completed, and the specified updates have been
|
||||
/// executed.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - important: Reads executed by concurrent *database snapshots* are not
|
||||
/// considered: they can run concurrently with the barrier updates.
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates.
|
||||
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
return try readerPool.barrier {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a block that takes a database connection, and
|
||||
/// returns its result.
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// wrapped inside a transaction, and returns the result.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
/// If the updates throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If the updates return .rollback, the transaction is
|
||||
/// also rollbacked, but no error is thrown.
|
||||
///
|
||||
/// Eventual concurrent reads may see changes performed in the block before
|
||||
/// the block completes.
|
||||
/// Eventual concurrent database updates are postponed until the transaction
|
||||
/// has completed.
|
||||
///
|
||||
/// The block is guaranteed to be executed outside of a transaction.
|
||||
/// Eventual concurrent reads are guaranteed to not see any partial updates
|
||||
/// of the database until the transaction has completed.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameters block: A block that executes SQL statements and return
|
||||
/// either .commit or .rollback.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func writeWithoutTransaction<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.sync(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, wrapped
|
||||
/// inside a transaction.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// If the block throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If the block returns .rollback, the transaction is
|
||||
/// also rollbacked, but no error is thrown.
|
||||
///
|
||||
/// try dbPool.writeInTransaction { db in
|
||||
/// db.execute(...)
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// Eventual concurrent reads are guaranteed not to see any changes
|
||||
/// performed in the block until they are all saved in the database.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
|
||||
/// for more information.
|
||||
/// - block: A block that executes SQL statements and return either
|
||||
/// .commit or .rollback.
|
||||
/// - throws: The error thrown by the block, or any error establishing the
|
||||
/// transaction.
|
||||
public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws {
|
||||
/// - updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates, or by the
|
||||
/// wrapping transaction.
|
||||
public func writeInTransaction(
|
||||
_ kind: Database.TransactionKind? = nil,
|
||||
_ updates: (Database) throws -> Database.TransactionCompletion)
|
||||
throws
|
||||
{
|
||||
try writer.sync { db in
|
||||
try db.inTransaction(kind) {
|
||||
try block(db)
|
||||
try updates(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes an update block in a protected dispatch queue,
|
||||
/// and returns its result.
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, and returns the result.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
/// Eventual concurrent database updates are postponed until the updates
|
||||
/// are completed.
|
||||
///
|
||||
/// try dbPool.unsafeReentrantWrite { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
/// Eventual concurrent reads may see partial updates unless you wrap them
|
||||
/// in a transaction.
|
||||
///
|
||||
/// Eventual concurrent reads may see changes performed in the block before
|
||||
/// the block completes.
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.reentrantSync(updates)
|
||||
}
|
||||
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction.
|
||||
///
|
||||
/// This method is reentrant. It is unsafe because it fosters dangerous
|
||||
/// concurrency practices.
|
||||
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.reentrantSync(block)
|
||||
/// Eventual concurrent reads may see partial updates unless you wrap them
|
||||
/// in a transaction.
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
writer.async(updates)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
@@ -589,23 +741,17 @@ extension DatabasePool : DatabaseReader {
|
||||
/// }
|
||||
/// dbPool.add(function: fn)
|
||||
/// try dbPool.read { db in
|
||||
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
|
||||
/// try Int.fetchOne(db, sql: "SELECT succ(1)") // 2
|
||||
/// }
|
||||
public func add(function: DatabaseFunction) {
|
||||
functions.update(with: function)
|
||||
writer.sync { $0.add(function: function) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.add(function: function) }
|
||||
}
|
||||
forEachConnection { $0.add(function: function) }
|
||||
}
|
||||
|
||||
/// Remove an SQL function.
|
||||
public func remove(function: DatabaseFunction) {
|
||||
functions.remove(function)
|
||||
writer.sync { $0.remove(function: function) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.remove(function: function) }
|
||||
}
|
||||
forEachConnection { $0.remove(function: function) }
|
||||
}
|
||||
|
||||
// MARK: - Collations
|
||||
@@ -617,24 +763,34 @@ extension DatabasePool : DatabaseReader {
|
||||
/// }
|
||||
/// dbPool.add(collation: collation)
|
||||
/// try dbPool.write { db in
|
||||
/// try db.execute("CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD")
|
||||
/// try db.execute(sql: "CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD")
|
||||
/// }
|
||||
public func add(collation: DatabaseCollation) {
|
||||
collations.update(with: collation)
|
||||
writer.sync { $0.add(collation: collation) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.add(collation: collation) }
|
||||
}
|
||||
forEachConnection { $0.add(collation: collation) }
|
||||
}
|
||||
|
||||
/// Remove a collation.
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
collations.remove(collation)
|
||||
writer.sync { $0.remove(collation: collation) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.remove(collation: collation) }
|
||||
}
|
||||
forEachConnection { $0.remove(collation: collation) }
|
||||
}
|
||||
|
||||
// MARK: - Custom FTS5 Tokenizers
|
||||
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
/// Add a custom FTS5 tokenizer.
|
||||
///
|
||||
/// class MyTokenizer : FTS5CustomTokenizer { ... }
|
||||
/// dbPool.add(tokenizer: MyTokenizer.self)
|
||||
public func add<Tokenizer: FTS5CustomTokenizer>(tokenizer: Tokenizer.Type) {
|
||||
func registerTokenizer(db: Database) {
|
||||
db.add(tokenizer: Tokenizer.self)
|
||||
}
|
||||
tokenizerRegistrations.append(registerTokenizer)
|
||||
forEachConnection(registerTokenizer)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
extension DatabasePool {
|
||||
@@ -703,14 +859,17 @@ extension DatabasePool {
|
||||
// Sanity check
|
||||
if writer.onValidQueue {
|
||||
writer.execute { db in
|
||||
GRDBPrecondition(!db.isInsideTransaction, "makeSnapshot() must not be called from inside a transaction.")
|
||||
GRDBPrecondition(
|
||||
!db.isInsideTransaction,
|
||||
"makeSnapshot() must not be called from inside a transaction.")
|
||||
}
|
||||
}
|
||||
|
||||
let snapshot = try DatabaseSnapshot(
|
||||
path: path,
|
||||
configuration: writer.configuration,
|
||||
labelSuffix: ".snapshot.\(snapshotCount.increment())")
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "snapshot.\(databaseSnapshotCount.increment())")
|
||||
snapshot.read { setupDatabase($0) }
|
||||
return snapshot
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ public final class DatabaseQueue: DatabaseWriter {
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
schemaCache: SimpleDatabaseSchemaCache(),
|
||||
label: configuration.label ?? "GRDB.DatabaseQueue")
|
||||
defaultLabel: "GRDB.DatabaseQueue")
|
||||
}
|
||||
|
||||
/// Opens an in-memory SQLite database.
|
||||
@@ -56,7 +56,7 @@ public final class DatabaseQueue: DatabaseWriter {
|
||||
path: ":memory:",
|
||||
configuration: configuration,
|
||||
schemaCache: SimpleDatabaseSchemaCache(),
|
||||
label: configuration.label ?? "GRDB.DatabaseQueue")
|
||||
defaultLabel: "GRDB.DatabaseQueue")
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
@@ -71,9 +71,9 @@ public final class DatabaseQueue: DatabaseWriter {
|
||||
}
|
||||
|
||||
extension DatabaseQueue {
|
||||
|
||||
|
||||
// MARK: - Memory management
|
||||
|
||||
|
||||
/// Free as much memory as possible.
|
||||
///
|
||||
/// This method blocks the current thread until all database accesses are completed.
|
||||
@@ -94,19 +94,26 @@ extension DatabaseQueue {
|
||||
public func setupMemoryManagement(in application: UIApplication) {
|
||||
self.application = application
|
||||
let center = NotificationCenter.default
|
||||
center.addObserver(self, selector: #selector(DatabaseQueue.applicationDidReceiveMemoryWarning(_:)), name: .UIApplicationDidReceiveMemoryWarning, object: nil)
|
||||
center.addObserver(self, selector: #selector(DatabaseQueue.applicationDidEnterBackground(_:)), name: .UIApplicationDidEnterBackground, object: nil)
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabaseQueue.applicationDidReceiveMemoryWarning(_:)),
|
||||
name: UIApplication.didReceiveMemoryWarningNotification,
|
||||
object: nil)
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabaseQueue.applicationDidEnterBackground(_:)),
|
||||
name: UIApplication.didEnterBackgroundNotification,
|
||||
object: nil)
|
||||
}
|
||||
|
||||
@objc private func applicationDidEnterBackground(_ notification: NSNotification) {
|
||||
@objc
|
||||
private func applicationDidEnterBackground(_ notification: NSNotification) {
|
||||
guard let application = application else {
|
||||
return
|
||||
}
|
||||
|
||||
var task: UIBackgroundTaskIdentifier! = nil
|
||||
task = application.beginBackgroundTask(expirationHandler: nil)
|
||||
|
||||
if task == UIBackgroundTaskInvalid {
|
||||
let task: UIBackgroundTaskIdentifier = application.beginBackgroundTask(expirationHandler: nil)
|
||||
if task == .invalid {
|
||||
// Perform releaseMemory() synchronously.
|
||||
releaseMemory()
|
||||
} else {
|
||||
@@ -118,7 +125,8 @@ extension DatabaseQueue {
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
|
||||
@objc
|
||||
private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
|
||||
DispatchQueue.global().async {
|
||||
self.releaseMemory()
|
||||
}
|
||||
@@ -127,15 +135,16 @@ extension DatabaseQueue {
|
||||
}
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
extension DatabaseQueue {
|
||||
|
||||
// MARK: - Encryption
|
||||
|
||||
/// Changes the passphrase of an encrypted database
|
||||
public func change(passphrase: String) throws {
|
||||
try writer.sync { try $0.change(passphrase: passphrase) }
|
||||
}
|
||||
extension DatabaseQueue {
|
||||
|
||||
// MARK: - Encryption
|
||||
|
||||
/// Changes the passphrase of an encrypted database
|
||||
@available(*, deprecated, message: "Use Database.changePassphrase(_:) instead")
|
||||
public func change(passphrase: String) throws {
|
||||
try writer.sync { try $0.changePassphrase(passphrase) }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
extension DatabaseQueue {
|
||||
@@ -152,7 +161,7 @@ extension DatabaseQueue {
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
|
||||
/// SQLCipher), attempts to write in the database from this meethod throw a
|
||||
/// SQLCipher), attempts to write in the database from this method throw a
|
||||
/// DatabaseError of resultCode `SQLITE_READONLY`.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
@@ -163,6 +172,40 @@ extension DatabaseQueue {
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// Asynchronously executes a read-only block in a protected dispatch queue.
|
||||
///
|
||||
/// let players = try dbQueue.asyncRead { result in
|
||||
/// do {
|
||||
/// let db = try result.get()
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // Handle error
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
|
||||
/// SQLCipher), attempts to write in the database from this method throw a
|
||||
/// DatabaseError of resultCode `SQLITE_READONLY`.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
public func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void) {
|
||||
writer.async { db in
|
||||
do {
|
||||
try db.beginReadOnly()
|
||||
} catch {
|
||||
block(.failure(error))
|
||||
return
|
||||
}
|
||||
|
||||
block(.success(db))
|
||||
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
@@ -191,107 +234,105 @@ extension DatabaseQueue {
|
||||
/// concurrency practices.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.reentrantSync(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes *block*.
|
||||
///
|
||||
/// This method must be called from the protected database dispatch queue,
|
||||
/// outside of a transaction. You'll get a fatal error otherwise.
|
||||
///
|
||||
/// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
|
||||
/// SQLCipher), attempts to write in the database from this meethod throw a
|
||||
/// DatabaseError of resultCode `SQLITE_READONLY`.
|
||||
///
|
||||
/// See `DatabaseWriter.readFromCurrentState`.
|
||||
public func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
// DatabaseQueue can't perform parallel reads.
|
||||
// Perform a blocking read instead.
|
||||
return DatabaseFuture(DatabaseResult {
|
||||
// Check that we're on the writer queue...
|
||||
try writer.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
|
||||
return try db.readOnly {
|
||||
try block(db)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// Performs the same job as asyncConcurrentRead.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func readFromCurrentState(_ block: @escaping (Database) -> Void) {
|
||||
// Check that we're on the correct queue...
|
||||
public func spawnConcurrentRead(_ block: @escaping (Result<Database, Error>) -> Void) {
|
||||
// Check that we're on the writer queue...
|
||||
writer.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction.")
|
||||
db.readOnly { block(db) }
|
||||
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
|
||||
|
||||
do {
|
||||
try db.beginReadOnly()
|
||||
} catch {
|
||||
block(.failure(error))
|
||||
return
|
||||
}
|
||||
|
||||
block(.success(db))
|
||||
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Writing in Database
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, wrapped
|
||||
/// inside a transaction.
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// wrapped inside a transaction, and returns the result.
|
||||
///
|
||||
/// If the block throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown.
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter block: A block that executes SQL statements.
|
||||
/// - throws: An eventual database error, or the error thrown by the block.
|
||||
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.sync { db in
|
||||
var result: T? = nil
|
||||
try db.inTransaction {
|
||||
result = try block(db)
|
||||
return .commit
|
||||
}
|
||||
return result!
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, wrapped
|
||||
/// inside a transaction.
|
||||
///
|
||||
/// If the block throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If the block returns .rollback, the transaction is
|
||||
/// If the updates throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If the updates return .rollback, the transaction is
|
||||
/// also rollbacked, but no error is thrown.
|
||||
///
|
||||
/// try dbQueue.inTransaction { db in
|
||||
/// try Player(...).insert(db)
|
||||
/// return .commit
|
||||
/// }
|
||||
/// Eventual concurrent database accesses are postponed until the
|
||||
/// transaction has completed.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// try dbQueue.writeInTransaction { db in
|
||||
/// db.execute(...)
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
|
||||
/// for more information.
|
||||
/// - block: A block that executes SQL statements and return either
|
||||
/// .commit or .rollback.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func inTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws {
|
||||
/// - updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates, or by the
|
||||
/// wrapping transaction.
|
||||
public func inTransaction(
|
||||
_ kind: Database.TransactionKind? = nil,
|
||||
_ updates: (Database) throws -> Database.TransactionCompletion)
|
||||
throws
|
||||
{
|
||||
try writer.sync { db in
|
||||
try db.inTransaction(kind) {
|
||||
try block(db)
|
||||
try updates(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, and returns the result.
|
||||
///
|
||||
/// let players = try dbQueue.writeWithoutTransaction { db in
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
/// Eventual concurrent database accesses are postponed until the updates
|
||||
/// are completed.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func writeWithoutTransaction<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.sync(block)
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates.
|
||||
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.sync(updates)
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, and returns the result.
|
||||
///
|
||||
/// // INSERT INTO player ...
|
||||
/// let players = try dbQueue.inDatabase { db in
|
||||
@@ -302,12 +343,12 @@ extension DatabaseQueue {
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func inDatabase<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.sync(block)
|
||||
public func inDatabase<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.sync(updates)
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
/// Synchronously executes database updates in a protected dispatch queue, and
|
||||
/// returns the result.
|
||||
///
|
||||
/// // INSERT INTO player ...
|
||||
/// try dbQueue.unsafeReentrantWrite { db in
|
||||
@@ -316,8 +357,14 @@ extension DatabaseQueue {
|
||||
///
|
||||
/// This method is reentrant. It is unsafe because it fosters dangerous
|
||||
/// concurrency practices.
|
||||
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.reentrantSync(block)
|
||||
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.reentrantSync(updates)
|
||||
}
|
||||
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction.
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
writer.async(updates)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
@@ -332,7 +379,7 @@ extension DatabaseQueue {
|
||||
/// }
|
||||
/// dbQueue.add(function: fn)
|
||||
/// try dbQueue.read { db in
|
||||
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
|
||||
/// try Int.fetchOne(db, sql: "SELECT succ(1)") // 2
|
||||
/// }
|
||||
public func add(function: DatabaseFunction) {
|
||||
writer.sync { $0.add(function: function) }
|
||||
@@ -352,7 +399,7 @@ extension DatabaseQueue {
|
||||
/// }
|
||||
/// dbQueue.add(collation: collation)
|
||||
/// try dbQueue.write { db in
|
||||
/// try db.execute("CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD")
|
||||
/// try db.execute(sql: "CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD")
|
||||
/// }
|
||||
public func add(collation: DatabaseCollation) {
|
||||
writer.sync { $0.add(collation: collation) }
|
||||
@@ -363,4 +410,3 @@ extension DatabaseQueue {
|
||||
writer.sync { $0.remove(collation: collation) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// The protocol for all types that can fetch values from a database.
|
||||
@@ -19,7 +21,10 @@
|
||||
/// connection to the database. Should you have to cope with external
|
||||
/// connections, protect yourself with transactions, and be ready to setup a
|
||||
/// [busy handler](https://www.sqlite.org/c3ref/busy_handler.html).
|
||||
public protocol DatabaseReader : class {
|
||||
public protocol DatabaseReader: AnyObject {
|
||||
|
||||
/// The database configuration
|
||||
var configuration: Configuration { get }
|
||||
|
||||
// MARK: - Read From Database
|
||||
|
||||
@@ -31,14 +36,14 @@ public protocol DatabaseReader : class {
|
||||
///
|
||||
/// try reader.read { db in
|
||||
/// // Those two values are guaranteed to be equal, even if the
|
||||
/// // `wine` table is modified between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// // `player` table is modified between the two requests:
|
||||
/// let count1 = try Player.fetchCount(db)
|
||||
/// let count2 = try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// try reader.read { db in
|
||||
/// // Now this value may be different:
|
||||
/// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds
|
||||
@@ -50,6 +55,33 @@ public protocol DatabaseReader : class {
|
||||
/// happen while establishing the read access to the database.
|
||||
func read<T>(_ block: (Database) throws -> T) throws -> T
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// Asynchronously executes a read-only block that takes a
|
||||
/// database connection.
|
||||
///
|
||||
/// Guarantee 1: the block argument is isolated. Eventual concurrent
|
||||
/// database updates are not visible inside the block:
|
||||
///
|
||||
/// try reader.asyncRead { result in
|
||||
/// do (
|
||||
/// let db = try result.get()
|
||||
/// // Those two values are guaranteed to be equal, even if the
|
||||
/// // `player` table is modified between the two requests:
|
||||
/// let count1 = try Player.fetchCount(db)
|
||||
/// let count2 = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // handle error
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds
|
||||
/// and SQLCipher, attempts to write in the database throw a DatabaseError
|
||||
/// whose resultCode is `SQLITE_READONLY`.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void)
|
||||
#endif
|
||||
|
||||
/// Synchronously executes a read-only block that takes a database
|
||||
/// connection, and returns its result.
|
||||
///
|
||||
@@ -60,16 +92,16 @@ public protocol DatabaseReader : class {
|
||||
///
|
||||
/// try reader.unsafeRead { db in
|
||||
/// // Those two values may be different because some other thread
|
||||
/// // may have inserted or deleted a wine between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// // may have inserted or deleted a player between the two requests:
|
||||
/// let count1 = try Player.fetchCount(db)
|
||||
/// let count2 = try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// Cursor iterations are isolated, though:
|
||||
///
|
||||
/// try reader.unsafeRead { db in
|
||||
/// // No concurrent update can mess with this iteration:
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT ...")
|
||||
/// let rows = try Row.fetchCursor(db, sql: "SELECT ...")
|
||||
/// while let row = try rows.next() { ... }
|
||||
/// }
|
||||
///
|
||||
@@ -91,16 +123,16 @@ public protocol DatabaseReader : class {
|
||||
///
|
||||
/// try reader.unsafeReentrantRead { db in
|
||||
/// // Those two values may be different because some other thread
|
||||
/// // may have inserted or deleted a wine between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// // may have inserted or deleted a player between the two requests:
|
||||
/// let count1 = try Player.fetchCount(db)
|
||||
/// let count2 = try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// Cursor iterations are isolated, though:
|
||||
///
|
||||
/// try reader.unsafeReentrantRead { db in
|
||||
/// // No concurrent update can mess with this iteration:
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT ...")
|
||||
/// let rows = try Row.fetchCursor(db, sql: "SELECT ...")
|
||||
/// while let row = try rows.next() { ... }
|
||||
/// }
|
||||
///
|
||||
@@ -128,7 +160,7 @@ public protocol DatabaseReader : class {
|
||||
/// }
|
||||
/// reader.add(function: fn)
|
||||
/// try reader.read { db in
|
||||
/// try Int.fetchOne(db, "SELECT succ(1)")! // 2
|
||||
/// try Int.fetchOne(db, sql: "SELECT succ(1)")! // 2
|
||||
/// }
|
||||
func add(function: DatabaseFunction)
|
||||
|
||||
@@ -144,11 +176,32 @@ public protocol DatabaseReader : class {
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// reader.add(collation: collation)
|
||||
/// try reader.execute("SELECT * FROM file ORDER BY name COLLATE localized_standard")
|
||||
/// try reader.execute(sql: "SELECT * FROM file ORDER BY name COLLATE localized_standard")
|
||||
func add(collation: DatabaseCollation)
|
||||
|
||||
/// Remove a collation.
|
||||
func remove(collation: DatabaseCollation)
|
||||
|
||||
// MARK: - Value Observation
|
||||
|
||||
/// Starts a value observation.
|
||||
///
|
||||
/// You should use the `ValueObservation.start(in:onError:onChange:)`
|
||||
/// method instead.
|
||||
///
|
||||
/// - parameter observation: the stared observation
|
||||
/// - parameter onError: a closure that is provided by eventual errors that happen
|
||||
/// during observation
|
||||
/// - parameter onChange: a closure that is provided fresh values
|
||||
/// - returns: a TransactionObserver
|
||||
func add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> TransactionObserver
|
||||
|
||||
/// Remove a transaction observer.
|
||||
func remove(transactionObserver: TransactionObserver)
|
||||
}
|
||||
|
||||
extension DatabaseReader {
|
||||
@@ -167,10 +220,14 @@ extension DatabaseReader {
|
||||
try backup(to: writer, afterBackupInit: nil, afterBackupStep: nil)
|
||||
}
|
||||
|
||||
func backup(to writer: DatabaseWriter, afterBackupInit: (() -> ())?, afterBackupStep: (() -> ())?) throws {
|
||||
func backup(to writer: DatabaseWriter, afterBackupInit: (() -> Void)?, afterBackupStep: (() -> Void)?) throws {
|
||||
try read { dbFrom in
|
||||
try writer.writeWithoutTransaction { dbDest in
|
||||
try Database.backup(from: dbFrom, to: dbDest, afterBackupInit: afterBackupInit, afterBackupStep: afterBackupStep)
|
||||
try Database.backup(
|
||||
from: dbFrom,
|
||||
to: dbDest,
|
||||
afterBackupInit: afterBackupInit,
|
||||
afterBackupStep: afterBackupStep)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -180,7 +237,7 @@ extension DatabaseReader {
|
||||
///
|
||||
/// Instances of AnyDatabaseReader forward their methods to an arbitrary
|
||||
/// underlying database reader.
|
||||
public final class AnyDatabaseReader : DatabaseReader {
|
||||
public final class AnyDatabaseReader: DatabaseReader {
|
||||
private let base: DatabaseReader
|
||||
|
||||
/// Creates a database reader that wraps a base database reader.
|
||||
@@ -188,6 +245,11 @@ public final class AnyDatabaseReader : DatabaseReader {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public var configuration: Configuration {
|
||||
return base.configuration
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// :nodoc:
|
||||
@@ -195,6 +257,13 @@ public final class AnyDatabaseReader : DatabaseReader {
|
||||
return try base.read(block)
|
||||
}
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// :nodoc:
|
||||
public func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void) {
|
||||
base.asyncRead(block)
|
||||
}
|
||||
#endif
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeRead(block)
|
||||
@@ -228,4 +297,21 @@ public final class AnyDatabaseReader : DatabaseReader {
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
base.remove(collation: collation)
|
||||
}
|
||||
|
||||
// MARK: - Value Observation
|
||||
|
||||
/// :nodoc:
|
||||
public func add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> TransactionObserver
|
||||
{
|
||||
return base.add(observation: observation, onError: onError, onChange: onChange)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func remove(transactionObserver: TransactionObserver) {
|
||||
base.remove(transactionObserver: transactionObserver)
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,7 @@
|
||||
/// `observes(eventsOfKind:)` and `databaseDidChange(with:)` methods.
|
||||
///
|
||||
/// A database region is the union of any number of "table regions", which can
|
||||
/// cover a full table, or the combination of columns and rows (identified by
|
||||
/// their rowids):
|
||||
/// cover a full table, or the combination of columns and rows:
|
||||
///
|
||||
/// |Table1 | |Table2 | |Table3 | |Table4 | |Table5 |
|
||||
/// |-------| |-------| |-------| |-------| |-------|
|
||||
@@ -13,41 +12,36 @@
|
||||
/// |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | |
|
||||
/// |x|x|x|x| |x| | | | | | | | | | | | | | | | | | |
|
||||
///
|
||||
/// You don't create a database region directly. Instead, you use one of
|
||||
/// those methods:
|
||||
/// To create a database region, you use one of those methods:
|
||||
///
|
||||
/// - `DatabaseRegion.fullDatabase`: the region that covers all database tables.
|
||||
///
|
||||
/// - `DatabaseRegion()`: the empty region.
|
||||
///
|
||||
/// - `DatabaseRegion(table:)`: the region that covers one database table.
|
||||
///
|
||||
/// - `SelectStatement.databaseRegion`:
|
||||
///
|
||||
/// let statement = db.makeSelectStatement("SELECT name, score FROM player")
|
||||
/// print(statement.databaseRegion)
|
||||
/// // prints "player(name,score)"
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name, score FROM player")
|
||||
/// let region = statement.databaseRegion
|
||||
///
|
||||
/// - `FetchRequest.databaseRegion(_:)`
|
||||
///
|
||||
/// let request = Player.filter(key: 1)
|
||||
/// try print(request.databaseRegion(db))
|
||||
/// // prints "player(*)[1]"
|
||||
///
|
||||
/// Database regions returned by requests can be more precise than regions
|
||||
/// returned by select statements. Especially, regions returned by statements
|
||||
/// don't know about rowids:
|
||||
///
|
||||
/// // A plain statement
|
||||
/// let statement = db.makeSelectStatement("SELECT * FROM player WHERE id = 1")
|
||||
/// statement.databaseRegion // "player(*)"
|
||||
///
|
||||
/// // A query interface request that executes the same statement:
|
||||
/// let request = Player.filter(key: 1)
|
||||
/// try request.databaseRegion(db) // "player(*)[1]"
|
||||
/// let request = Player.filter(key: 1)
|
||||
/// let region = try request.databaseRegion(db)
|
||||
public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
private let tableRegions: [String: TableRegion]?
|
||||
|
||||
private init(tableRegions: [String: TableRegion]?) {
|
||||
self.tableRegions = tableRegions
|
||||
}
|
||||
|
||||
/// Returns whether the region is empty.
|
||||
public var isEmpty: Bool {
|
||||
guard let tableRegions = tableRegions else { return false }
|
||||
guard let tableRegions = tableRegions else {
|
||||
// full database
|
||||
return false
|
||||
}
|
||||
return tableRegions.isEmpty
|
||||
}
|
||||
|
||||
@@ -55,13 +49,15 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
/// from all tables.
|
||||
public static let fullDatabase = DatabaseRegion(tableRegions: nil)
|
||||
|
||||
/// The empty database region
|
||||
/// Creates an empty database region.
|
||||
public init() {
|
||||
self.init(tableRegions: [:])
|
||||
}
|
||||
|
||||
/// A full table: (all columns in the table) × (all rows)
|
||||
init(table: String) {
|
||||
/// Creates a region that spans all rows and columns of a database table.
|
||||
///
|
||||
/// - parameter table: A table name.
|
||||
public init(table: String) {
|
||||
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: nil)])
|
||||
}
|
||||
|
||||
@@ -122,7 +118,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
guard let otherTableRegions = other.tableRegions else { return .fullDatabase }
|
||||
|
||||
var tableRegionsUnion: [String: TableRegion] = [:]
|
||||
let tableNames = Set(tableRegions.map { $0.key }).union(Set(otherTableRegions.map { $0.key }))
|
||||
let tableNames = Set(tableRegions.keys).union(Set(otherTableRegions.keys))
|
||||
for table in tableNames {
|
||||
let tableRegion = tableRegions[table]
|
||||
let otherTableRegion = otherTableRegions[table]
|
||||
@@ -130,9 +126,9 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
switch (tableRegion, otherTableRegion) {
|
||||
case (nil, nil):
|
||||
preconditionFailure()
|
||||
case (nil, let tableRegion?), (let tableRegion?, nil):
|
||||
case let (nil, tableRegion?), let (tableRegion?, nil):
|
||||
tableRegionUnion = tableRegion
|
||||
case (let tableRegion?, let otherTableRegion?):
|
||||
case let (tableRegion?, otherTableRegion?):
|
||||
tableRegionUnion = tableRegion.union(otherTableRegion)
|
||||
}
|
||||
tableRegionsUnion[table] = tableRegionUnion
|
||||
@@ -145,6 +141,26 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
public mutating func formUnion(_ other: DatabaseRegion) {
|
||||
self = union(other)
|
||||
}
|
||||
|
||||
/// Returns a region suitable for database observation by removing views.
|
||||
///
|
||||
/// We can do it because modifications only happen in actual tables. And we
|
||||
/// want to do it because we have a fast path for regions that span a
|
||||
/// single table.
|
||||
func ignoringViews(_ db: Database) throws -> DatabaseRegion {
|
||||
guard let tableRegions = tableRegions else { return .fullDatabase }
|
||||
let viewNames = try db.schema().names(ofType: .view)
|
||||
guard viewNames.isEmpty == false else { return self }
|
||||
let filteredRegions = tableRegions.filter { viewNames.contains($0.key) == false }
|
||||
return DatabaseRegion(tableRegions: filteredRegions)
|
||||
}
|
||||
|
||||
/// Returns a region which doesn't contain any SQLite internal table.
|
||||
func ignoringInternalSQLiteTables() -> DatabaseRegion {
|
||||
guard let tableRegions = tableRegions else { return .fullDatabase }
|
||||
let filteredRegions = tableRegions.filter { !$0.key.starts(with: "sqlite_") }
|
||||
return DatabaseRegion(tableRegions: filteredRegions)
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseRegion {
|
||||
@@ -154,7 +170,7 @@ extension DatabaseRegion {
|
||||
/// Returns whether the content in the region would be impacted if the
|
||||
/// database were modified by an event of this kind.
|
||||
public func isModified(byEventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
return !intersection(eventKind.modifiedRegion).isEmpty
|
||||
return intersection(eventKind.modifiedRegion).isEmpty == false
|
||||
}
|
||||
|
||||
/// Returns whether the content in the region is impacted by this event.
|
||||
@@ -164,32 +180,21 @@ extension DatabaseRegion {
|
||||
/// region.isModified(byEventsOfKind:)
|
||||
public func isModified(by event: DatabaseEvent) -> Bool {
|
||||
guard let tableRegions = tableRegions else {
|
||||
// Full database: all changes are impactful
|
||||
return true
|
||||
}
|
||||
|
||||
switch tableRegions.count {
|
||||
case 1:
|
||||
// The precondition applies here:
|
||||
//
|
||||
// The region contains a single table. Due to the
|
||||
// filtering of events performed in observes(eventsOfKind:), the
|
||||
// event argument is guaranteed to be about the fetched table.
|
||||
// We thus only have to check for rowIds.
|
||||
assert(event.tableName == tableRegions[tableRegions.startIndex].key) // sanity check
|
||||
guard let rowIds = tableRegions[tableRegions.startIndex].value.rowIds else {
|
||||
return true
|
||||
}
|
||||
return rowIds.contains(event.rowID)
|
||||
default:
|
||||
guard let tableRegion = tableRegions[event.tableName] else {
|
||||
// Shouldn't happen if the precondition is met.
|
||||
fatalError("precondition failure: event was not filtered out in observes(eventsOfKind:) by region.isModified(byEventsOfKind:)")
|
||||
}
|
||||
guard let rowIds = tableRegion.rowIds else {
|
||||
return true
|
||||
}
|
||||
return rowIds.contains(event.rowID)
|
||||
guard let tableRegion = tableRegions[event.tableName] else {
|
||||
// FTS4 (and maybe other virtual tables) perform unadvertised
|
||||
// changes. For example, an "INSERT INTO document ..." statement
|
||||
// advertises an insertion in the `document` table, but the
|
||||
// actual change events happen in the `document_content` shadow
|
||||
// table. When such a non-advertised event happens, assume that
|
||||
// the region is modified.
|
||||
// See https://github.com/groue/GRDB.swift/issues/620
|
||||
return true
|
||||
}
|
||||
return tableRegion.contains(rowID: event.rowID)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -200,16 +205,14 @@ extension DatabaseRegion {
|
||||
switch (lhs.tableRegions, rhs.tableRegions) {
|
||||
case (nil, nil):
|
||||
return true
|
||||
case (let ltableRegions?, let rtableRegions?):
|
||||
let ltableNames = Set(ltableRegions.map { $0.key })
|
||||
let rtableNames = Set(rtableRegions.map { $0.key })
|
||||
case let (ltableRegions?, rtableRegions?):
|
||||
let ltableNames = Set(ltableRegions.keys)
|
||||
let rtableNames = Set(rtableRegions.keys)
|
||||
guard ltableNames == rtableNames else {
|
||||
return false
|
||||
}
|
||||
for tableName in ltableNames {
|
||||
if ltableRegions[tableName]! != rtableRegions[tableName]! {
|
||||
return false
|
||||
}
|
||||
for tableName in ltableNames where ltableRegions[tableName]! != rtableRegions[tableName]! {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
default:
|
||||
@@ -259,17 +262,17 @@ private struct TableRegion: Equatable {
|
||||
func intersection(_ other: TableRegion) -> TableRegion {
|
||||
let columnsIntersection: Set<String>?
|
||||
switch (self.columns, other.columns) {
|
||||
case (nil, let columns), (let columns, nil):
|
||||
case let (nil, columns), let (columns, nil):
|
||||
columnsIntersection = columns
|
||||
case (let columns?, let other?):
|
||||
case let (columns?, other?):
|
||||
columnsIntersection = columns.intersection(other)
|
||||
}
|
||||
|
||||
let rowIdsIntersection: Set<Int64>?
|
||||
switch (self.rowIds, other.rowIds) {
|
||||
case (nil, let rowIds), (let rowIds, nil):
|
||||
case let (nil, rowIds), let (rowIds, nil):
|
||||
rowIdsIntersection = rowIds
|
||||
case (let rowIds?, let other?):
|
||||
case let (rowIds?, other?):
|
||||
rowIdsIntersection = rowIds.intersection(other)
|
||||
}
|
||||
|
||||
@@ -281,7 +284,7 @@ private struct TableRegion: Equatable {
|
||||
switch (self.columns, other.columns) {
|
||||
case (nil, _), (_, nil):
|
||||
columnsUnion = nil
|
||||
case (let columns?, let other?):
|
||||
case let (columns?, other?):
|
||||
columnsUnion = columns.union(other)
|
||||
}
|
||||
|
||||
@@ -289,10 +292,69 @@ private struct TableRegion: Equatable {
|
||||
switch (self.rowIds, other.rowIds) {
|
||||
case (nil, _), (_, nil):
|
||||
rowIdsUnion = nil
|
||||
case (let rowIds?, let other?):
|
||||
case let (rowIds?, other?):
|
||||
rowIdsUnion = rowIds.union(other)
|
||||
}
|
||||
|
||||
return TableRegion(columns: columnsUnion, rowIds: rowIdsUnion)
|
||||
}
|
||||
|
||||
func contains(rowID: Int64) -> Bool {
|
||||
guard let rowIds = rowIds else {
|
||||
return true
|
||||
}
|
||||
return rowIds.contains(rowID)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - DatabaseRegionConvertible
|
||||
|
||||
public protocol DatabaseRegionConvertible {
|
||||
/// Returns a database region.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
func databaseRegion(_ db: Database) throws -> DatabaseRegion
|
||||
}
|
||||
|
||||
extension DatabaseRegion: DatabaseRegionConvertible {
|
||||
/// :nodoc:
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
/// A type-erased DatabaseRegionConvertible
|
||||
public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
|
||||
let _region: (Database) throws -> DatabaseRegion
|
||||
|
||||
public init(_ region: @escaping (Database) throws -> DatabaseRegion) {
|
||||
_region = region
|
||||
}
|
||||
|
||||
public init(_ region: DatabaseRegionConvertible) {
|
||||
_region = { try region.databaseRegion($0) }
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try _region(db)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Utils
|
||||
|
||||
extension DatabaseRegion {
|
||||
static func union(_ regions: DatabaseRegion...) -> DatabaseRegion {
|
||||
return regions.reduce(into: DatabaseRegion()) { union, region in
|
||||
union.formUnion(region)
|
||||
}
|
||||
}
|
||||
|
||||
static func union(_ regions: [DatabaseRegionConvertible]) -> (Database) throws -> DatabaseRegion {
|
||||
return { db in
|
||||
try regions.reduce(into: DatabaseRegion()) { union, region in
|
||||
try union.formUnion(region.databaseRegion(db))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
/// DatabaseRegionObservation tracks changes in the results of database
|
||||
/// requests, and notifies each database transaction whenever the
|
||||
/// database changes.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let observation = DatabaseRegionObservation(tracking: Player.all)
|
||||
/// let observer = try observation.start(in: dbQueue) { db: Database in
|
||||
/// print("Players have changed.")
|
||||
/// }
|
||||
public struct DatabaseRegionObservation {
|
||||
/// The extent of the database observation. The default is
|
||||
/// `.observerLifetime`: the observation lasts until the
|
||||
/// observer returned by the `start(in:onChange:)` method
|
||||
/// is deallocated.
|
||||
public var extent: Database.TransactionObservationExtent
|
||||
|
||||
/// A closure that is evaluated when the observation starts, and returns
|
||||
/// the observed database region.
|
||||
var observedRegion: (Database) throws -> DatabaseRegion
|
||||
}
|
||||
|
||||
extension DatabaseRegionObservation {
|
||||
/// Creates a DatabaseRegionObservation which observes *regions*, and
|
||||
/// notifies whenever one of the observed regions is modified by a
|
||||
/// database transaction.
|
||||
///
|
||||
/// For example, this sample code counts the number of a times the player
|
||||
/// table is modified:
|
||||
///
|
||||
/// let observation = DatabaseRegionObservation(tracking: Player.all())
|
||||
///
|
||||
/// var count = 0
|
||||
/// let observer = observation.start(in: dbQueue) { _ in
|
||||
/// count += 1
|
||||
/// print("Players have been modified \(count) times.")
|
||||
/// }
|
||||
///
|
||||
/// The observation lasts until the observer returned by `start` is
|
||||
/// deallocated. See the `extent` property for more information.
|
||||
///
|
||||
/// - parameter regions: A list of observed regions.
|
||||
public init(tracking regions: DatabaseRegionConvertible...) {
|
||||
self.init(tracking: regions)
|
||||
}
|
||||
|
||||
/// Creates a DatabaseRegionObservation which observes *regions*, and
|
||||
/// notifies whenever one of the observed regions is modified by a
|
||||
/// database transaction.
|
||||
///
|
||||
/// For example, this sample code counts the number of a times the player
|
||||
/// table is modified:
|
||||
///
|
||||
/// let observation = DatabaseRegionObservation(tracking: [Player.all()])
|
||||
///
|
||||
/// var count = 0
|
||||
/// let observer = observation.start(in: dbQueue) { _ in
|
||||
/// count += 1
|
||||
/// print("Players have been modified \(count) times.")
|
||||
/// }
|
||||
///
|
||||
/// The observation lasts until the observer returned by `start` is
|
||||
/// deallocated. See the `extent` property for more information.
|
||||
///
|
||||
/// - parameter regions: A list of observed regions.
|
||||
public init(tracking regions: [DatabaseRegionConvertible]) {
|
||||
self.init(
|
||||
extent: .observerLifetime,
|
||||
observedRegion: DatabaseRegion.union(regions))
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseRegionObservation {
|
||||
/// Starts the observation in the provided database writer (such as
|
||||
/// a database queue or database pool), and returns a transaction observer.
|
||||
///
|
||||
/// - parameter reader: A DatabaseWriter.
|
||||
/// - parameter onChange: A closure that is provided a database connection
|
||||
/// with write access each time the observed region has been modified.
|
||||
/// - returns: a TransactionObserver
|
||||
public func start(
|
||||
in dbWriter: DatabaseWriter,
|
||||
onChange: @escaping (Database) -> Void)
|
||||
throws -> TransactionObserver
|
||||
{
|
||||
// Use unsafeReentrantWrite so that observation can start from any
|
||||
// dispatch queue.
|
||||
return try dbWriter.unsafeReentrantWrite { db -> TransactionObserver in
|
||||
let region = try observedRegion(db).ignoringViews(db)
|
||||
let observer = DatabaseRegionObserver(region: region, onChange: onChange)
|
||||
db.add(transactionObserver: observer, extent: extent)
|
||||
return observer
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class DatabaseRegionObserver: TransactionObserver {
|
||||
let region: DatabaseRegion
|
||||
let onChange: (Database) -> Void
|
||||
var isChanged = false
|
||||
|
||||
init(region: DatabaseRegion, onChange: @escaping (Database) -> Void) {
|
||||
self.region = region
|
||||
self.onChange = onChange
|
||||
}
|
||||
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
return region.isModified(byEventsOfKind: eventKind)
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
if region.isModified(by: event) {
|
||||
isChanged = true
|
||||
stopObservingDatabaseChangesUntilNextTransaction()
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidCommit(_ db: Database) {
|
||||
guard isChanged else { return }
|
||||
isChanged = false
|
||||
|
||||
onChange(db)
|
||||
}
|
||||
|
||||
func databaseDidRollback(_ db: Database) {
|
||||
isChanged = false
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,8 @@
|
||||
protocol DatabaseSchemaCache {
|
||||
mutating func clear()
|
||||
|
||||
func canonicalTableName(_ table: String) -> String?
|
||||
mutating func set(canonicalTableName: String, forTable table: String)
|
||||
|
||||
var schemaInfo: SchemaInfo? { get set }
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo?
|
||||
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String)
|
||||
|
||||
@@ -20,26 +19,18 @@ protocol DatabaseSchemaCache {
|
||||
|
||||
/// A thread-unsafe database schema cache
|
||||
struct SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
private var canonicalTableNames: [String: String] = [:]
|
||||
var schemaInfo: SchemaInfo?
|
||||
private var primaryKeys: [String: PrimaryKeyInfo] = [:]
|
||||
private var columns: [String: [ColumnInfo]] = [:]
|
||||
private var indexes: [String: [IndexInfo]] = [:]
|
||||
private var foreignKeys: [String: [ForeignKeyInfo]] = [:]
|
||||
|
||||
mutating func clear() {
|
||||
canonicalTableNames = [:]
|
||||
primaryKeys = [:]
|
||||
columns = [:]
|
||||
indexes = [:]
|
||||
foreignKeys = [:]
|
||||
}
|
||||
|
||||
func canonicalTableName(_ table: String) -> String? {
|
||||
return canonicalTableNames[table]
|
||||
}
|
||||
|
||||
mutating func set(canonicalTableName: String, forTable table: String) {
|
||||
canonicalTableNames[table] = table
|
||||
schemaInfo = nil
|
||||
}
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
|
||||
@@ -79,8 +70,10 @@ struct SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
struct EmptyDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
func clear() { }
|
||||
|
||||
func canonicalTableName(_ table: String) -> String? { return nil }
|
||||
func set(canonicalTableName: String, forTable table: String) { }
|
||||
var schemaInfo: SchemaInfo? {
|
||||
get { return nil }
|
||||
set { }
|
||||
}
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo? { return nil }
|
||||
func set(primaryKey: PrimaryKeyInfo, forTable table: String) { }
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
import Dispatch
|
||||
|
||||
/// A DatabaseSnapshot sees an unchanging database content, as it existed at the
|
||||
/// moment it was created.
|
||||
///
|
||||
/// See DatabasePool.makeSnapshot()
|
||||
///
|
||||
/// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html
|
||||
public class DatabaseSnapshot : DatabaseReader {
|
||||
public class DatabaseSnapshot: DatabaseReader {
|
||||
private var serializedDatabase: SerializedDatabase
|
||||
|
||||
/// The database configuration
|
||||
var configuration: Configuration {
|
||||
public var configuration: Configuration {
|
||||
return serializedDatabase.configuration
|
||||
}
|
||||
|
||||
init(path: String, configuration: Configuration = Configuration(), labelSuffix: String) throws {
|
||||
init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws {
|
||||
var configuration = configuration
|
||||
configuration.readonly = true
|
||||
configuration.allowsUnsafeTransactions = true // Snaphost keeps a long-lived transaction
|
||||
@@ -21,21 +23,16 @@ public class DatabaseSnapshot : DatabaseReader {
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
schemaCache: SimpleDatabaseSchemaCache(),
|
||||
label: (configuration.label ?? "GRDB.DatabasePool") + labelSuffix)
|
||||
defaultLabel: defaultLabel,
|
||||
purpose: purpose)
|
||||
|
||||
try serializedDatabase.sync { db in
|
||||
// Assert WAL mode
|
||||
let journalMode = try String.fetchOne(db, "PRAGMA journal_mode")
|
||||
let journalMode = try String.fetchOne(db, sql: "PRAGMA journal_mode")
|
||||
guard journalMode == "wal" else {
|
||||
throw DatabaseError(message: "WAL mode is not activated at path: \(path)")
|
||||
}
|
||||
|
||||
// Establish snapshot isolation (see deinit)
|
||||
try db.beginTransaction(.deferred)
|
||||
|
||||
// Take snapshot
|
||||
// See DatabasePool.readFromCurrentState for a complete discussion
|
||||
try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").cursor().next()
|
||||
try db.beginSnapshotTransaction()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,61 +62,109 @@ extension DatabaseSnapshot {
|
||||
return try serializedDatabase.sync(block)
|
||||
}
|
||||
|
||||
/// Alias for `read`. See `DatabaseReader.unsafeRead`.
|
||||
#if compiler(>=5.0)
|
||||
/// Asynchronously executes a read-only block in a protected dispatch queue.
|
||||
///
|
||||
/// let players = try snapshot.asyncRead { result in
|
||||
/// do {
|
||||
/// let db = try result.get()
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // Handle error
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
public func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void) {
|
||||
serializedDatabase.async { block(.success($0)) }
|
||||
}
|
||||
#endif
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.sync(block)
|
||||
}
|
||||
|
||||
/// Alias for `read`. See `DatabaseReader.unsafeReentrantRead`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try serializedDatabase.sync(block)
|
||||
return try serializedDatabase.reentrantSync(block)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
///
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int + 1
|
||||
/// }
|
||||
/// snapshot.add(function: fn)
|
||||
/// try snapshot.read { db in
|
||||
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
|
||||
/// }
|
||||
public func add(function: DatabaseFunction) {
|
||||
serializedDatabase.sync { $0.add(function: function) }
|
||||
}
|
||||
|
||||
/// Remove an SQL function.
|
||||
public func remove(function: DatabaseFunction) {
|
||||
serializedDatabase.sync { $0.remove(function: function) }
|
||||
}
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// Add or redefine a collation.
|
||||
///
|
||||
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// snapshot.add(collation: collation)
|
||||
/// let files = try snapshot.read { db in
|
||||
/// try File.fetchAll(db, "SELECT * FROM file ORDER BY name COLLATE localized_standard")
|
||||
/// }
|
||||
public func add(collation: DatabaseCollation) {
|
||||
serializedDatabase.sync { $0.add(collation: collation) }
|
||||
}
|
||||
|
||||
/// Remove a collation.
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
serializedDatabase.sync { $0.remove(collation: collation) }
|
||||
}
|
||||
|
||||
// MARK: - Value Observation
|
||||
|
||||
public func add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> TransactionObserver
|
||||
{
|
||||
// TODO: fetch asynchronously when possible
|
||||
do {
|
||||
// Deal with initial value
|
||||
switch observation.scheduling {
|
||||
case .mainQueue:
|
||||
if let value = try unsafeReentrantRead(observation.fetchFirst) {
|
||||
if DispatchQueue.isMain {
|
||||
onChange(value)
|
||||
} else {
|
||||
DispatchQueue.main.async {
|
||||
onChange(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
case let .async(onQueue: queue, startImmediately: startImmediately):
|
||||
if startImmediately {
|
||||
if let value = try unsafeReentrantRead(observation.fetchFirst) {
|
||||
queue.async {
|
||||
onChange(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
case let .unsafe(startImmediately: startImmediately):
|
||||
if startImmediately {
|
||||
if let value = try unsafeReentrantRead(observation.fetchFirst) {
|
||||
onChange(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
onError(error)
|
||||
}
|
||||
|
||||
// Return a dummy observer, because snapshots never change
|
||||
return SnapshotValueObserver()
|
||||
}
|
||||
|
||||
public func remove(transactionObserver: TransactionObserver) {
|
||||
// Can't remove an observer which could not be added :-)
|
||||
}
|
||||
}
|
||||
|
||||
/// An observer that does nothing, support for
|
||||
/// `DatabaseSnapshot.add(observation:onError:onChange:)`.
|
||||
private class SnapshotValueObserver: TransactionObserver {
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { return false }
|
||||
func databaseDidChange(with event: DatabaseEvent) { }
|
||||
func databaseDidCommit(_ db: Database) { }
|
||||
func databaseDidRollback(_ db: Database) { }
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
// MARK: - DatabaseValue
|
||||
@@ -18,7 +20,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
|
||||
public static let null = DatabaseValue(storage: .null)
|
||||
|
||||
/// An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB).
|
||||
public enum Storage : Equatable {
|
||||
public enum Storage: Equatable {
|
||||
/// The NULL storage class.
|
||||
case null
|
||||
|
||||
@@ -58,10 +60,10 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
|
||||
public static func == (_ lhs: Storage, _ rhs: Storage) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case (.null, .null): return true
|
||||
case (.int64(let lhs), .int64(let rhs)): return lhs == rhs
|
||||
case (.double(let lhs), .double(let rhs)): return lhs == rhs
|
||||
case (.string(let lhs), .string(let rhs)): return lhs == rhs
|
||||
case (.blob(let lhs), .blob(let rhs)): return lhs == rhs
|
||||
case let (.int64(lhs), .int64(rhs)): return lhs == rhs
|
||||
case let (.double(lhs), .double(rhs)): return lhs == rhs
|
||||
case let (.string(lhs), .string(rhs)): return lhs == rhs
|
||||
case let (.blob(lhs), .blob(rhs)): return lhs == rhs
|
||||
default: return false
|
||||
}
|
||||
}
|
||||
@@ -118,21 +120,21 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
|
||||
fatalError("Unexpected SQLite value type: \(type)")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Returns a DatabaseValue initialized from a raw SQLite statement pointer.
|
||||
init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
switch sqlite3_column_type(sqliteStatement, Int32(index)) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_NULL:
|
||||
storage = .null
|
||||
case SQLITE_INTEGER:
|
||||
storage = .int64(sqlite3_column_int64(sqliteStatement, Int32(index)))
|
||||
storage = .int64(sqlite3_column_int64(sqliteStatement, index))
|
||||
case SQLITE_FLOAT:
|
||||
storage = .double(sqlite3_column_double(sqliteStatement, Int32(index)))
|
||||
storage = .double(sqlite3_column_double(sqliteStatement, index))
|
||||
case SQLITE_TEXT:
|
||||
storage = .string(String(cString: sqlite3_column_text(sqliteStatement, Int32(index))))
|
||||
storage = .string(String(cString: sqlite3_column_text(sqliteStatement, index)))
|
||||
case SQLITE_BLOB:
|
||||
if let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) {
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
if let bytes = sqlite3_column_blob(sqliteStatement, index) {
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, index))
|
||||
storage = .blob(Data(bytes: bytes, count: count)) // copy bytes
|
||||
} else {
|
||||
storage = .blob(Data())
|
||||
@@ -149,21 +151,20 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
|
||||
// Hashable
|
||||
extension DatabaseValue {
|
||||
|
||||
/// The hash value
|
||||
/// :nodoc:
|
||||
public var hashValue: Int {
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
switch storage {
|
||||
case .null:
|
||||
return 0
|
||||
hasher.combine(0)
|
||||
case .int64(let int64):
|
||||
// 1 == 1.0, hence 1 and 1.0 must have the same hash:
|
||||
return Double(int64).hashValue
|
||||
hasher.combine(Double(int64))
|
||||
case .double(let double):
|
||||
return double.hashValue
|
||||
hasher.combine(double)
|
||||
case .string(let string):
|
||||
return string.hashValue
|
||||
hasher.combine(string)
|
||||
case .blob(let data):
|
||||
return data.hashValue
|
||||
hasher.combine(data)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,17 +187,17 @@ extension DatabaseValue {
|
||||
switch (lhs.storage, rhs.storage) {
|
||||
case (.null, .null):
|
||||
return true
|
||||
case (.int64(let lhs), .int64(let rhs)):
|
||||
case let (.int64(lhs), .int64(rhs)):
|
||||
return lhs == rhs
|
||||
case (.double(let lhs), .double(let rhs)):
|
||||
case let (.double(lhs), .double(rhs)):
|
||||
return lhs == rhs
|
||||
case (.int64(let lhs), .double(let rhs)):
|
||||
case let (.int64(lhs), .double(rhs)):
|
||||
return Int64(exactly: rhs) == lhs
|
||||
case (.double(let lhs), .int64(let rhs)):
|
||||
case let (.double(lhs), .int64(rhs)):
|
||||
return rhs == Int64(exactly: lhs)
|
||||
case (.string(let lhs), .string(let rhs)):
|
||||
case let (.string(lhs), .string(rhs)):
|
||||
return lhs == rhs
|
||||
case (.blob(let lhs), .blob(let rhs)):
|
||||
case let (.blob(lhs), .blob(rhs)):
|
||||
return lhs == rhs
|
||||
default:
|
||||
return false
|
||||
@@ -204,84 +205,6 @@ extension DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Lossless conversions
|
||||
|
||||
extension DatabaseValue {
|
||||
/// Converts the database value to the type T.
|
||||
///
|
||||
/// let dbValue = "foo".databaseValue
|
||||
/// let string = dbValue.losslessConvert() as String // "foo"
|
||||
///
|
||||
/// Conversion is successful if and only if T.fromDatabaseValue returns a
|
||||
/// non-nil value.
|
||||
///
|
||||
/// This method crashes with a fatal error when conversion fails.
|
||||
///
|
||||
/// let dbValue = "foo".databaseValue
|
||||
/// let int = dbValue.losslessConvert() as Int // fatalError
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: Optional SQL statement that enhances the eventual
|
||||
/// conversion error
|
||||
/// - arguments: Optional statement arguments that enhances the eventual
|
||||
/// conversion error
|
||||
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T where T : DatabaseValueConvertible {
|
||||
if let value = T.fromDatabaseValue(self) {
|
||||
return value
|
||||
}
|
||||
// Failed conversion: this is data loss, a programmer error.
|
||||
var error = "could not convert database value \(self) to \(T.self)"
|
||||
if let sql = sql {
|
||||
error += " with statement `\(sql)`"
|
||||
}
|
||||
if let arguments = arguments, !arguments.isEmpty {
|
||||
error += " arguments \(arguments)"
|
||||
}
|
||||
fatalError(error)
|
||||
}
|
||||
|
||||
/// Converts the database value to the type Optional<T>.
|
||||
///
|
||||
/// let dbValue = "foo".databaseValue
|
||||
/// let string = dbValue.losslessConvert() as String? // "foo"
|
||||
/// let null = DatabaseValue.null.losslessConvert() as String? // nil
|
||||
///
|
||||
/// Conversion is successful if and only if T.fromDatabaseValue returns a
|
||||
/// non-nil value.
|
||||
///
|
||||
/// This method crashes with a fatal error when conversion fails.
|
||||
///
|
||||
/// let dbValue = "foo".databaseValue
|
||||
/// let int = dbValue.losslessConvert() as Int? // fatalError
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: Optional SQL statement that enhances the eventual
|
||||
/// conversion error
|
||||
/// - arguments: Optional statement arguments that enhances the eventual
|
||||
/// conversion error
|
||||
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T? where T : DatabaseValueConvertible {
|
||||
// Use fromDatabaseValue first: this allows DatabaseValue to convert NULL to .null.
|
||||
if let value = T.fromDatabaseValue(self) {
|
||||
return value
|
||||
}
|
||||
if isNull {
|
||||
// Failed conversion from null: ok
|
||||
return nil
|
||||
} else {
|
||||
// Failed conversion from a non-null database value: this is data
|
||||
// loss, a programmer error.
|
||||
var error = "could not convert database value \(self) to \(T.self)"
|
||||
if let sql = sql {
|
||||
error += " with statement `\(sql)`"
|
||||
}
|
||||
if let arguments = arguments, !arguments.isEmpty {
|
||||
error += " arguments \(arguments)"
|
||||
}
|
||||
fatalError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// DatabaseValueConvertible
|
||||
extension DatabaseValue {
|
||||
/// Returns self
|
||||
@@ -308,18 +231,18 @@ extension DatabaseValue {
|
||||
extension DatabaseValue {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func expressionSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
|
||||
// fast path for NULL
|
||||
if isNull {
|
||||
return "NULL"
|
||||
}
|
||||
|
||||
if context.appendArguments([self]) {
|
||||
if context.append(arguments: [self]) {
|
||||
return "?"
|
||||
} else {
|
||||
// Correctness above all: use SQLite to quote the value.
|
||||
// Assume that the Quote function always succeeds
|
||||
return DatabaseQueue().inDatabase { try! String.fetchOne($0, "SELECT QUOTE(?)", arguments: [self])! }
|
||||
return DatabaseQueue().inDatabase { try! String.fetchOne($0, sql: "SELECT QUOTE(?)", arguments: [self])! }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -343,8 +266,10 @@ extension DatabaseValue {
|
||||
case .blob:
|
||||
// We can't assume all blobs are true, and return false:
|
||||
//
|
||||
// SELECT NOT X'31' -- 0 (because X'31' is turned into the string '1', then into integer 1, which is negated into 0)
|
||||
// SELECT NOT X'30' -- 1 (because X'30' is turned into the string '0', then into integer 0, which is negated into 1)
|
||||
// SELECT NOT X'31' -- 0 (because X'31' is turned into the string '1',
|
||||
// then into integer 1, which is negated into 0)
|
||||
// SELECT NOT X'30' -- 1 (because X'30' is turned into the string '0',
|
||||
// then into integer 0, which is negated into 1)
|
||||
return SQLExpressionNot(self)
|
||||
}
|
||||
}
|
||||
@@ -354,12 +279,6 @@ extension DatabaseValue {
|
||||
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
return self
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
// CustomStringConvertible
|
||||
@@ -380,3 +299,45 @@ extension DatabaseValue {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Compares DatabaseValue like SQLite.
|
||||
///
|
||||
/// See RxGRDB for tests.
|
||||
///
|
||||
/// This comparison is not public because it does not handle text collations,
|
||||
/// and may be dangerous when put in user hands.
|
||||
///
|
||||
/// So far, the only goal of this sorting method so far is aesthetic, and
|
||||
/// easier testing.
|
||||
func < (lhs: DatabaseValue, rhs: DatabaseValue) -> Bool {
|
||||
switch (lhs.storage, rhs.storage) {
|
||||
case let (.int64(lhs), .int64(rhs)):
|
||||
return lhs < rhs
|
||||
case let (.double(lhs), .double(rhs)):
|
||||
return lhs < rhs
|
||||
case let (.int64(lhs), .double(rhs)):
|
||||
return Double(lhs) < rhs
|
||||
case let (.double(lhs), .int64(rhs)):
|
||||
return lhs < Double(rhs)
|
||||
case let (.string(lhs), .string(rhs)):
|
||||
return lhs.utf8.lexicographicallyPrecedes(rhs.utf8)
|
||||
case let (.blob(lhs), .blob(rhs)):
|
||||
return lhs.lexicographicallyPrecedes(rhs, by: <)
|
||||
case (.blob, _):
|
||||
return false
|
||||
case (_, .blob):
|
||||
return true
|
||||
case (.string, _):
|
||||
return false
|
||||
case (_, .string):
|
||||
return true
|
||||
case (.int64, _), (.double, _):
|
||||
return false
|
||||
case (_, .int64), (_, .double):
|
||||
return true
|
||||
case (.null, _):
|
||||
return false
|
||||
case (_, .null):
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
// MARK: - Conversion Context and Errors
|
||||
|
||||
/// A type that helps the user understanding value conversion errors
|
||||
struct ValueConversionContext {
|
||||
private enum Column {
|
||||
case columnIndex(Int)
|
||||
case columnName(String)
|
||||
}
|
||||
|
||||
var row: Row?
|
||||
var sql: String?
|
||||
var arguments: StatementArguments?
|
||||
private var column: Column?
|
||||
|
||||
func atColumn(_ columnIndex: Int) -> ValueConversionContext {
|
||||
var result = self
|
||||
result.column = .columnIndex(columnIndex)
|
||||
return result
|
||||
}
|
||||
|
||||
func atColumn(_ columnName: String) -> ValueConversionContext {
|
||||
var result = self
|
||||
result.column = .columnName(columnName)
|
||||
return result
|
||||
}
|
||||
|
||||
var columnIndex: Int? {
|
||||
guard let column = column else { return nil }
|
||||
switch column {
|
||||
case .columnIndex(let index):
|
||||
return index
|
||||
case .columnName(let name):
|
||||
return row?.index(ofColumn: name)
|
||||
}
|
||||
}
|
||||
|
||||
var columnName: String? {
|
||||
guard let column = column else { return nil }
|
||||
switch column {
|
||||
case .columnIndex(let index):
|
||||
guard let row = row else { return nil }
|
||||
return Array(row.columnNames)[index]
|
||||
case .columnName(let name):
|
||||
return name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension ValueConversionContext {
|
||||
init(_ statement: SelectStatement) {
|
||||
self.init(
|
||||
row: Row(statement: statement).copy(),
|
||||
sql: statement.sql,
|
||||
arguments: statement.arguments,
|
||||
column: nil)
|
||||
}
|
||||
|
||||
init(_ row: Row) {
|
||||
if let statement = row.statement {
|
||||
self.init(
|
||||
row: row.copy(),
|
||||
sql: statement.sql,
|
||||
arguments: statement.arguments,
|
||||
column: nil)
|
||||
} else if let sqliteStatement = row.sqliteStatement {
|
||||
let sql = String(cString: sqlite3_sql(sqliteStatement)).trimmingCharacters(in: .sqlStatementSeparators)
|
||||
self.init(
|
||||
row: row.copy(),
|
||||
sql: sql,
|
||||
arguments: nil,
|
||||
column: nil)
|
||||
} else {
|
||||
self.init(
|
||||
row: row.copy(),
|
||||
sql: nil,
|
||||
arguments: nil,
|
||||
column: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The canonical conversion error message
|
||||
///
|
||||
/// - parameter dbValue: nil means "missing column"
|
||||
func conversionErrorMessage<T>(
|
||||
to: T.Type,
|
||||
from dbValue: DatabaseValue?,
|
||||
conversionContext: ValueConversionContext?)
|
||||
-> String
|
||||
{
|
||||
var message: String
|
||||
var extras: [String] = []
|
||||
|
||||
if let dbValue = dbValue {
|
||||
message = "could not convert database value \(dbValue) to \(T.self)"
|
||||
if let columnName = conversionContext?.columnName {
|
||||
extras.append("column: `\(columnName)`")
|
||||
}
|
||||
if let columnIndex = conversionContext?.columnIndex {
|
||||
extras.append("column index: \(columnIndex)")
|
||||
}
|
||||
} else {
|
||||
message = "could not read \(T.self) from missing column"
|
||||
if let columnName = conversionContext?.columnName {
|
||||
message += " `\(columnName)`"
|
||||
}
|
||||
}
|
||||
|
||||
if let row = conversionContext?.row {
|
||||
extras.append("row: \(row)")
|
||||
}
|
||||
|
||||
if let sql = conversionContext?.sql {
|
||||
extras.append("sql: `\(sql)`")
|
||||
if let arguments = conversionContext?.arguments, arguments.isEmpty == false {
|
||||
extras.append("arguments: \(arguments)")
|
||||
}
|
||||
}
|
||||
|
||||
if extras.isEmpty == false {
|
||||
message += " (" + extras.joined(separator: ", ") + ")"
|
||||
}
|
||||
return message
|
||||
}
|
||||
|
||||
/// The canonical conversion fatal error
|
||||
///
|
||||
/// - parameter dbValue: nil means "missing column", for consistency with (row["missing"] as DatabaseValue? == nil)
|
||||
func fatalConversionError<T>(
|
||||
to: T.Type,
|
||||
from dbValue: DatabaseValue?,
|
||||
conversionContext: ValueConversionContext?,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
-> Never
|
||||
{
|
||||
fatalError(
|
||||
conversionErrorMessage(
|
||||
to: T.self,
|
||||
from: dbValue,
|
||||
conversionContext: conversionContext),
|
||||
file: file,
|
||||
line: line)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func fatalConversionError<T>(
|
||||
to: T.Type,
|
||||
from dbValue: DatabaseValue?,
|
||||
in row: Row,
|
||||
atColumn columnName: String,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
-> Never
|
||||
{
|
||||
fatalConversionError(
|
||||
to: T.self,
|
||||
from: dbValue,
|
||||
conversionContext: ValueConversionContext(row).atColumn(columnName))
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func fatalConversionError<T>(
|
||||
to: T.Type,
|
||||
sqliteStatement: SQLiteStatement,
|
||||
index: Int32,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
-> Never
|
||||
{
|
||||
let row = Row(sqliteStatement: sqliteStatement)
|
||||
fatalConversionError(
|
||||
to: T.self,
|
||||
from: DatabaseValue(sqliteStatement: sqliteStatement, index: index),
|
||||
conversionContext: ValueConversionContext(row).atColumn(Int(index)))
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func fatalConversionError<T>(
|
||||
to: T.Type,
|
||||
from dbValue: DatabaseValue?,
|
||||
sqliteStatement: SQLiteStatement,
|
||||
index: Int32,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
-> Never
|
||||
{
|
||||
let row = Row(sqliteStatement: sqliteStatement)
|
||||
fatalConversionError(
|
||||
to: T.self,
|
||||
from: dbValue,
|
||||
conversionContext: ValueConversionContext(row).atColumn(Int(index)))
|
||||
}
|
||||
|
||||
// MARK: - DatabaseValueConvertible
|
||||
|
||||
/// Lossless conversions from database values and rows
|
||||
extension DatabaseValueConvertible {
|
||||
@usableFromInline
|
||||
static func decode(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self {
|
||||
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
|
||||
if let value = fromDatabaseValue(dbValue) {
|
||||
return value
|
||||
} else {
|
||||
fatalConversionError(to: Self.self, from: dbValue, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
}
|
||||
|
||||
static func decode(
|
||||
from dbValue: DatabaseValue,
|
||||
conversionContext: @autoclosure () -> ValueConversionContext?)
|
||||
-> Self
|
||||
{
|
||||
if let value = fromDatabaseValue(dbValue) {
|
||||
return value
|
||||
} else {
|
||||
fatalConversionError(to: Self.self, from: dbValue, conversionContext: conversionContext())
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
static func decode(from row: Row, atUncheckedIndex index: Int) -> Self {
|
||||
return decode(
|
||||
from: row.impl.databaseValue(atUncheckedIndex: index),
|
||||
conversionContext: ValueConversionContext(row).atColumn(index))
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
static func decodeIfPresent(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self? {
|
||||
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
|
||||
if let value = fromDatabaseValue(dbValue) {
|
||||
return value
|
||||
} else if dbValue.isNull {
|
||||
return nil
|
||||
} else {
|
||||
fatalConversionError(to: Self.self, from: dbValue, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
}
|
||||
|
||||
static func decodeIfPresent(
|
||||
from dbValue: DatabaseValue,
|
||||
conversionContext: @autoclosure () -> ValueConversionContext?)
|
||||
-> Self?
|
||||
{
|
||||
// Use fromDatabaseValue before checking for null: this allows DatabaseValue to convert NULL to .null.
|
||||
if let value = fromDatabaseValue(dbValue) {
|
||||
return value
|
||||
} else if dbValue.isNull {
|
||||
return nil
|
||||
} else {
|
||||
fatalConversionError(to: Self.self, from: dbValue, conversionContext: conversionContext())
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
static func decodeIfPresent(from row: Row, atUncheckedIndex index: Int) -> Self? {
|
||||
return decodeIfPresent(
|
||||
from: row.impl.databaseValue(atUncheckedIndex: index),
|
||||
conversionContext: ValueConversionContext(row).atColumn(index))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - DatabaseValueConvertible & StatementColumnConvertible
|
||||
|
||||
/// Lossless conversions from database values and rows
|
||||
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
@inlinable
|
||||
static func fastDecode(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self {
|
||||
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
|
||||
fatalConversionError(to: Self.self, sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
return self.init(sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func fastDecode(from row: Row, atUncheckedIndex index: Int) -> Self {
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return fastDecode(from: sqliteStatement, atUncheckedIndex: Int32(index))
|
||||
}
|
||||
return row.fastDecode(Self.self, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func fastDecodeIfPresent(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self? {
|
||||
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
|
||||
return nil
|
||||
}
|
||||
return self.init(sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func fastDecodeIfPresent(from row: Row, atUncheckedIndex index: Int) -> Self? {
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return fastDecodeIfPresent(from: sqliteStatement, atUncheckedIndex: Int32(index))
|
||||
}
|
||||
return row.fastDecodeIfPresent(Self.self, atUncheckedIndex: index)
|
||||
}
|
||||
}
|
||||
|
||||
// Support for @inlinable decoding
|
||||
extension Row {
|
||||
@usableFromInline
|
||||
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int)
|
||||
-> Value
|
||||
{
|
||||
return impl.fastDecode(type, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int)
|
||||
-> Value?
|
||||
{
|
||||
return impl.fastDecodeIfPresent(type, atUncheckedIndex: index)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
// MARK: - DatabaseValueConvertible
|
||||
@@ -12,17 +14,17 @@
|
||||
/// The protocol comes with built-in methods that allow to fetch cursors,
|
||||
/// arrays, or single values:
|
||||
///
|
||||
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
|
||||
/// try String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
|
||||
/// try String.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String]
|
||||
/// try String.fetchOne(db, sql: "SELECT name FROM ...", arguments:...) // String?
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// try String.fetchCursor(statement, arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(statement, arguments:...) // [String]
|
||||
/// try String.fetchOne(statement, arguments:...) // String?
|
||||
///
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
public protocol DatabaseValueConvertible : SQLExpressible {
|
||||
public protocol DatabaseValueConvertible: SQLExpressible {
|
||||
/// Returns a value that can be stored in the database.
|
||||
var databaseValue: DatabaseValue { get }
|
||||
|
||||
@@ -42,38 +44,54 @@ extension DatabaseValueConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let urls: DatabaseValueCursor<URL> = try URL.fetchCursor(db, "SELECT url FROM link")
|
||||
/// let urls: DatabaseValueCursor<URL> = try URL.fetchCursor(db, sql: "SELECT url FROM link")
|
||||
/// while let url = urls.next() { // URL
|
||||
/// print(url)
|
||||
/// }
|
||||
/// }
|
||||
public final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
|
||||
private let statement: SelectStatement
|
||||
private let sqliteStatement: SQLiteStatement
|
||||
private let columnIndex: Int32
|
||||
private var done = false
|
||||
public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor {
|
||||
@usableFromInline let _statement: SelectStatement
|
||||
@usableFromInline let _sqliteStatement: SQLiteStatement
|
||||
@usableFromInline let _columnIndex: Int32
|
||||
@usableFromInline var _done = false
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
// We'll read from leftmost column at index 0, unless adapter mangles columns
|
||||
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
statement.cursorReset(arguments: arguments)
|
||||
_statement = statement
|
||||
_sqliteStatement = statement.sqliteStatement
|
||||
if let adapter = adapter {
|
||||
// adapter may redefine the index of the leftmost column
|
||||
_columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
|
||||
} else {
|
||||
_columnIndex = 0
|
||||
}
|
||||
_statement.reset(withArguments: arguments)
|
||||
|
||||
// Assume cursor is created for iteration
|
||||
statement.database.selectStatementWillExecute(statement)
|
||||
}
|
||||
|
||||
deinit {
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? _statement.reset()
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
@inlinable
|
||||
public func next() throws -> Value? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
if _done {
|
||||
// make sure this instance never yields a value again, even if the
|
||||
// statement is reset by another cursor.
|
||||
return nil
|
||||
}
|
||||
switch sqlite3_step(_sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
done = true
|
||||
_done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: columnIndex)
|
||||
return dbValue.losslessConvert() as Value
|
||||
return Value.decode(from: _sqliteStatement, atUncheckedIndex: _columnIndex)
|
||||
case let code:
|
||||
statement.database.selectStatementDidFail(statement)
|
||||
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
try _statement.didFail(withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -82,38 +100,54 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let urls: NullableDatabaseValueCursor<URL> = try Optional<URL>.fetchCursor(db, "SELECT url FROM link")
|
||||
/// let urls: NullableDatabaseValueCursor<URL> = try Optional<URL>.fetchCursor(db, sql: "SELECT url FROM link")
|
||||
/// while let url = urls.next() { // URL?
|
||||
/// print(url)
|
||||
/// }
|
||||
/// }
|
||||
public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
|
||||
private let statement: SelectStatement
|
||||
private let sqliteStatement: SQLiteStatement
|
||||
private let columnIndex: Int32
|
||||
private var done = false
|
||||
public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor {
|
||||
@usableFromInline let _statement: SelectStatement
|
||||
@usableFromInline let _sqliteStatement: SQLiteStatement
|
||||
@usableFromInline let _columnIndex: Int32
|
||||
@usableFromInline var _done = false
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
// We'll read from leftmost column at index 0, unless adapter mangles columns
|
||||
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
statement.cursorReset(arguments: arguments)
|
||||
_statement = statement
|
||||
_sqliteStatement = statement.sqliteStatement
|
||||
if let adapter = adapter {
|
||||
// adapter may redefine the index of the leftmost column
|
||||
_columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
|
||||
} else {
|
||||
_columnIndex = 0
|
||||
}
|
||||
_statement.reset(withArguments: arguments)
|
||||
|
||||
// Assume cursor is created for iteration
|
||||
statement.database.selectStatementWillExecute(statement)
|
||||
}
|
||||
|
||||
deinit {
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? _statement.reset()
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
@inlinable
|
||||
public func next() throws -> Value?? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
if _done {
|
||||
// make sure this instance never yields a value again, even if the
|
||||
// statement is reset by another cursor.
|
||||
return nil
|
||||
}
|
||||
switch sqlite3_step(_sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
done = true
|
||||
_done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: columnIndex)
|
||||
return dbValue.losslessConvert() as Value?
|
||||
return Value.decodeIfPresent(from: _sqliteStatement, atUncheckedIndex: _columnIndex)
|
||||
case let code:
|
||||
statement.database.selectStatementDidFail(statement)
|
||||
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
try _statement.didFail(withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -121,11 +155,11 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>
|
||||
/// DatabaseValueConvertible comes with built-in methods that allow to fetch
|
||||
/// cursors, arrays, or single values:
|
||||
///
|
||||
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
|
||||
/// try String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
|
||||
/// try String.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String]
|
||||
/// try String.fetchOne(db, sql: "SELECT name FROM ...", arguments:...) // String?
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// try String.fetchCursor(statement, arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(statement, arguments:...) // [String]
|
||||
/// try String.fetchOne(statement, arguments:...) // String
|
||||
@@ -137,7 +171,7 @@ extension DatabaseValueConvertible {
|
||||
|
||||
/// Returns a cursor over values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try String.fetchCursor(statement) // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
@@ -154,13 +188,18 @@ extension DatabaseValueConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> {
|
||||
public static func fetchCursor(
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> DatabaseValueCursor<Self>
|
||||
{
|
||||
return try DatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try String.fetchAll(statement) // [String]
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -169,7 +208,12 @@ extension DatabaseValueConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
|
||||
public static func fetchAll(
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Self]
|
||||
{
|
||||
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
@@ -178,7 +222,7 @@ extension DatabaseValueConvertible {
|
||||
/// The result is nil if the query returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let name = try String.fetchOne(statement) // String?
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -187,7 +231,12 @@ extension DatabaseValueConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
|
||||
public static func fetchOne(
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Self?
|
||||
{
|
||||
// fetchOne returns nil if there is no row, or if there is a row with a null value
|
||||
let cursor = try NullableDatabaseValueCursor<Self>(statement: statement, arguments: arguments, adapter: adapter)
|
||||
return try cursor.next() ?? nil
|
||||
@@ -195,12 +244,12 @@ extension DatabaseValueConvertible {
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible {
|
||||
|
||||
|
||||
// MARK: Fetching From SQL
|
||||
|
||||
/// Returns a cursor over values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try String.fetchCursor(db, "SELECT name FROM ...") // Cursor of String
|
||||
/// let names = try String.fetchCursor(db, sql: "SELECT name FROM ...") // Cursor of String
|
||||
/// while let name = try name.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
@@ -213,27 +262,39 @@ extension DatabaseValueConvertible {
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> {
|
||||
return try fetchCursor(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
|
||||
public static func fetchCursor(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> DatabaseValueCursor<Self>
|
||||
{
|
||||
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String]
|
||||
/// let names = try String.fetchAll(db, sql: "SELECT name FROM ...") // [String]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
|
||||
return try fetchAll(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
|
||||
public static func fetchAll(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Self]
|
||||
{
|
||||
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from an SQL query.
|
||||
@@ -241,17 +302,23 @@ extension DatabaseValueConvertible {
|
||||
/// The result is nil if the query returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let name = try String.fetchOne(db, "SELECT name FROM ...") // String?
|
||||
/// let name = try String.fetchOne(db, sql: "SELECT name FROM ...") // String?
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
|
||||
return try fetchOne(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
|
||||
public static func fetchOne(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Self?
|
||||
{
|
||||
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -278,8 +345,8 @@ extension DatabaseValueConvertible {
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> DatabaseValueCursor<Self> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchCursor(request.statement, adapter: request.adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from a fetch request.
|
||||
@@ -293,8 +360,8 @@ extension DatabaseValueConvertible {
|
||||
/// - returns: An array.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [Self] {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchAll(statement, adapter: adapter)
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchAll(request.statement, adapter: request.adapter)
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from a fetch request.
|
||||
@@ -311,8 +378,8 @@ extension DatabaseValueConvertible {
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne<R: FetchRequest>(_ db: Database, _ request: R) throws -> Self? {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchOne(statement, adapter: adapter)
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: true)
|
||||
return try fetchOne(request.statement, adapter: request.adapter)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -322,7 +389,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
|
||||
/// A cursor over fetched values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let request: ... // Some FetchRequest that fetches String
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String
|
||||
/// while let string = try strings.next() { // String
|
||||
/// ...
|
||||
@@ -342,7 +409,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
|
||||
/// An array of fetched values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let request: ... // Some FetchRequest that fetches String
|
||||
/// let strings = try request.fetchAll(db) // [String]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -357,7 +424,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// The result is nil if the request returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let request: ... // Some FetchRequest that fetches String
|
||||
/// let string = try request.fetchOne(db) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -371,10 +438,10 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// Swift's Optional comes with built-in methods that allow to fetch cursors
|
||||
/// and arrays of optional DatabaseValueConvertible:
|
||||
///
|
||||
/// try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
|
||||
/// try Optional<String>.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String?]
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// try Optional<String>.fetchCursor(statement, arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(statement, arguments:...) // [String?]
|
||||
///
|
||||
@@ -385,7 +452,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a cursor over optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchCursor(statement) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
@@ -402,13 +469,18 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> {
|
||||
public static func fetchCursor(
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
{
|
||||
return try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchAll(statement) // [String?]
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -417,7 +489,12 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
|
||||
public static func fetchAll(
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Wrapped?]
|
||||
{
|
||||
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
@@ -428,7 +505,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a cursor over optional values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // Cursor of String?
|
||||
/// let names = try Optional<String>.fetchCursor(db, sql: "SELECT name FROM ...") // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
@@ -441,27 +518,39 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> {
|
||||
return try fetchCursor(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
|
||||
public static func fetchCursor(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
{
|
||||
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String?]
|
||||
/// let names = try String.fetchAll(db, sql: "SELECT name FROM ...") // [String?]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - parameter arguments: Optional statement arguments.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
|
||||
return try fetchAll(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
|
||||
public static func fetchAll(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Wrapped?]
|
||||
{
|
||||
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -487,9 +576,11 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> NullableDatabaseValueCursor<Wrapped> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R)
|
||||
throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
{
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchCursor(request.statement, adapter: request.adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a fetch request.
|
||||
@@ -503,8 +594,8 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
/// - returns: An array of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [Wrapped?] {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchAll(statement, adapter: adapter)
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchAll(request.statement, adapter: request.adapter)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -514,7 +605,7 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped:
|
||||
|
||||
/// A cursor over fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Optional<String>
|
||||
/// let request: ... // Some FetchRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String?
|
||||
/// while let string = try strings.next() { // String?
|
||||
/// ...
|
||||
@@ -534,7 +625,7 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped:
|
||||
|
||||
/// An array of fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Optional<String>
|
||||
/// let request: ... // Some FetchRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchAll(db) // [String?]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -544,4 +635,3 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped:
|
||||
return try Optional<RowDecoder._Wrapped>.fetchAll(db, self)
|
||||
}
|
||||
}
|
||||
|
||||