Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
0dabd36123 | ||
|
|
8a83ee4599 | ||
|
|
29e720c474 | ||
|
|
444f5b003f | ||
|
|
3e60b00bab | ||
|
|
fc2c2658b7 | ||
|
|
fdef88d150 | ||
|
|
1a84a84bd1 | ||
|
|
22006e2251 | ||
|
|
3405585d60 | ||
|
|
91d0a453da | ||
|
|
d814249c5a | ||
|
|
fc2d5419b3 | ||
|
|
3593806685 | ||
|
|
e84b539de2 | ||
|
|
fee4486d1b | ||
|
|
a73be9c010 | ||
|
|
0bc25f8773 | ||
|
|
a465f16ff7 | ||
|
|
86d93b11dd | ||
|
|
f8aa5b7e21 | ||
|
|
16184ae89b | ||
|
|
af2a3ea827 | ||
|
|
ca7df229fa | ||
|
|
f121c6b139 | ||
|
|
2a6f7b7588 | ||
|
|
a87d06d609 | ||
|
|
7c85a973dc | ||
|
|
97961f4374 | ||
|
|
4436badbc8 | ||
|
|
9060048044 | ||
|
|
99566225f0 | ||
|
|
b4bd25decc | ||
|
|
0e94c7b44e | ||
|
|
c750fd7b1d | ||
|
|
0ed4491b46 | ||
|
|
b4a3adafb1 | ||
|
|
2e953221fa | ||
|
|
1886ac5cfb | ||
|
|
7ed7196c48 | ||
|
|
38b1e41aab | ||
|
|
467819bdd5 | ||
|
|
e81e818305 | ||
|
|
342dcc5094 | ||
|
|
8f89a2063e | ||
|
|
2e80db8aed | ||
|
|
4e7fc83ad5 | ||
|
|
200f12a558 | ||
|
|
5c1eea4c6f | ||
|
|
b73771fd6c | ||
|
|
a47f10cf07 | ||
|
|
75d0643642 | ||
|
|
732e0bd34b | ||
|
|
ac2cd485c8 | ||
|
|
b967018390 | ||
|
|
df16c4856f | ||
|
|
4e97b80274 | ||
|
|
65b3e21e65 | ||
|
|
5b97dea3c6 | ||
|
|
20322640c3 | ||
|
|
89ce13c43c | ||
|
|
27e94c211d | ||
|
|
bca4af679e | ||
|
|
cb7f827118 | ||
|
|
1bc4299bfc | ||
|
|
79c788e571 | ||
|
|
0125107855 | ||
|
|
24694b8b23 | ||
|
|
0c79224209 | ||
|
|
a88b5dc3df | ||
|
|
f259cac51f | ||
|
|
fe1146134b | ||
|
|
6dd4f1c666 | ||
|
|
4415681c92 | ||
|
|
5a0425a23c | ||
|
|
8729085528 | ||
|
|
88cbbf5c5e | ||
|
|
6816bceed0 | ||
|
|
76dc5e6b89 | ||
|
|
ee39a52069 | ||
|
|
82482bdbf7 | ||
|
|
062f916607 | ||
|
|
2b73c4f348 | ||
|
|
54b2135b74 | ||
|
|
bf3b4e7e02 | ||
|
|
ad8b80bafd | ||
|
|
06476bc6fe | ||
|
|
0616209e58 | ||
|
|
415f2971e5 | ||
|
|
3a7b2cc4a2 | ||
|
|
726e40984a | ||
|
|
63a68978f0 | ||
|
|
13d973dde4 | ||
|
|
8f5ef76e7e | ||
|
|
36ac5fa53e | ||
|
|
cda891ca02 | ||
|
|
ff4447713a | ||
|
|
70190e2a23 | ||
|
|
2682dae34b | ||
|
|
3a1e695a39 | ||
|
|
604f80f6fa | ||
|
|
5c0b88eb82 | ||
|
|
7e39fbaba0 | ||
|
|
815424770b | ||
|
|
30fcd95f1d | ||
|
|
4637930027 | ||
|
|
729ec6714c | ||
|
|
b2683eb864 | ||
|
|
e7bcf7c7db | ||
|
|
d1c47c3364 | ||
|
|
44140cb1db | ||
|
|
4bc6a77588 | ||
|
|
edd294550f | ||
|
|
69c2077037 | ||
|
|
b3f1997049 | ||
|
|
c2e624c78d | ||
|
|
ff69d3fbc3 | ||
|
|
018fac8c57 | ||
|
|
0b1bc80c41 | ||
|
|
7e6de4fbd0 | ||
|
|
fa31c484da | ||
|
|
2556fd041f | ||
|
|
e915d28cb2 | ||
|
|
60eb868fa5 | ||
|
|
6130c6f985 | ||
|
|
b7f44785ec | ||
|
|
8b44b0af7b | ||
|
|
caea11fbbb | ||
|
|
c7f018c635 | ||
|
|
b8328bd3bb | ||
|
|
0dd8fce854 | ||
|
|
f8b7156b48 | ||
|
|
cfba53e586 | ||
|
|
003020dd29 | ||
|
|
f2b46963bd | ||
|
|
62a434f898 | ||
|
|
16af4513d6 | ||
|
|
ead89420c4 | ||
|
|
88fac9e21d | ||
|
|
d601e06f25 | ||
|
|
6cdcd97912 | ||
|
|
8a4fbcc725 | ||
|
|
e9cbbe2903 | ||
|
|
366e049ddf | ||
|
|
4e73c31662 | ||
|
|
0d2079df42 | ||
|
|
318e7455e7 | ||
|
|
eb7c98c510 | ||
|
|
ac955873f2 | ||
|
|
051f0416a4 | ||
|
|
c96ed597ed | ||
|
|
5ccf87802e | ||
|
|
c93f3cda06 | ||
|
|
2e477feb33 | ||
|
|
dcb626b32b | ||
|
|
ce03deeccc | ||
|
|
1213fa0a43 | ||
|
|
76299d9302 | ||
|
|
7b59c097c6 | ||
|
|
af8971bcd8 | ||
|
|
5de7a5274e | ||
|
|
e0a1ee4c10 | ||
|
|
cdf5462005 | ||
|
|
86f084cb3e | ||
|
|
5d7245af2a | ||
|
|
cacc3e8456 | ||
|
|
0620b1b513 | ||
|
|
4eac0797fa | ||
|
|
07176e941b | ||
|
|
dadece1b04 | ||
|
|
b98992eb18 | ||
|
|
0191d64f56 | ||
|
|
02d5b9c014 | ||
|
|
aa81b992c4 | ||
|
|
9be001533c | ||
|
|
7be345521b | ||
|
|
67e48f8ad7 | ||
|
|
c0bd8ce917 | ||
|
|
da65deec69 | ||
|
|
34db8efea0 | ||
|
|
df8887be05 | ||
|
|
55472c2d7f | ||
|
|
2a1c87f24a | ||
|
|
88c4f02f5d | ||
|
|
3017668ba2 | ||
|
|
4f5fdf45e8 | ||
|
|
6037c418cb | ||
|
|
785853dd2b | ||
|
|
2ce2b4885d | ||
|
|
5637514dd6 | ||
|
|
0a3a8d738a | ||
|
|
1d1c7fc467 | ||
|
|
1f274f5c04 | ||
|
|
eddc078c2d | ||
|
|
5136142d83 | ||
|
|
857798b939 | ||
|
|
82d8fd65d0 | ||
|
|
2de040a6f1 | ||
|
|
aead6eec4a | ||
|
|
756863152c | ||
|
|
c1c3233ba2 | ||
|
|
91ad986d0b | ||
|
|
a35f012286 | ||
|
|
56a0dab443 | ||
|
|
69cf95e828 | ||
|
|
56ae745851 | ||
|
|
62f985469c | ||
|
|
a12bc2e90e | ||
|
|
402f9d3ba9 | ||
|
|
a360976e23 | ||
|
|
de6667a236 | ||
|
|
6db0831bfd | ||
|
|
26607ba193 | ||
|
|
15299eaac0 | ||
|
|
9c9217727c | ||
|
|
6434f0cdb1 | ||
|
|
7a520f3269 | ||
|
|
cc7cf597f3 | ||
|
|
0a6b34bb85 | ||
|
|
175c96cd38 | ||
|
|
cce0e332e0 | ||
|
|
214748fe5a | ||
|
|
dc7bdfed50 | ||
|
|
2d008b8c54 | ||
|
|
310c2637cb | ||
|
|
264bceee2a | ||
|
|
cdad6fa313 | ||
|
|
babaefca8f | ||
|
|
6a4382c323 | ||
|
|
231906e5ea | ||
|
|
1c9db9ec10 | ||
|
|
31e927f9da | ||
|
|
26b9030eaa | ||
|
|
da38df6bd6 | ||
|
|
ebb1eba96f | ||
|
|
c7a1daa8e5 | ||
|
|
0aa75f418f | ||
|
|
a5d56d38d6 | ||
|
|
fa04627ece | ||
|
|
33ec30438d | ||
|
|
e3ab3a991e | ||
|
|
287422f2f8 | ||
|
|
e184963b8f | ||
|
|
06f9a4601c | ||
|
|
7a30eb2613 | ||
|
|
5160b69c34 | ||
|
|
fa00b8ad99 | ||
|
|
1bf7f67008 | ||
|
|
872d6d21ac | ||
|
|
ab36df6e0f | ||
|
|
ffaabdfd62 | ||
|
|
8e2cdeebc3 | ||
|
|
a3189f79b6 | ||
|
|
66a425f718 | ||
|
|
344eba821f | ||
|
|
8d5e57873e | ||
|
|
9f78a758bd | ||
|
|
e6f084d397 | ||
|
|
09458c1d37 | ||
|
|
9a379fc1bc | ||
|
|
a45d019472 | ||
|
|
50dd846a36 | ||
|
|
dddeff458a | ||
|
|
ae162a88c6 | ||
|
|
ccc259c25c | ||
|
|
5e7235307a | ||
|
|
5747d1cff0 | ||
|
|
e05a64f1cb | ||
|
|
83104769ef | ||
|
|
39c5313738 | ||
|
|
d6f088609e | ||
|
|
4586eb9a82 | ||
|
|
a16bd6b54e | ||
|
|
3e46942f30 | ||
|
|
df79bb8ed8 | ||
|
|
d6183a4745 | ||
|
|
bf470b5870 | ||
|
|
175656aa26 | ||
|
|
497295a0c6 | ||
|
|
0f21f886b4 | ||
|
|
f4382e6bcb | ||
|
|
26108badd4 | ||
|
|
2ae93a2a0b | ||
|
|
d8860d2527 | ||
|
|
40cfbd8c9c | ||
|
|
6dea09ec24 | ||
|
|
8d84050f77 | ||
|
|
af8801c28a | ||
|
|
58edfcbc99 | ||
|
|
25748566ea | ||
|
|
66bd7cff77 | ||
|
|
d09afc8929 | ||
|
|
92f037eb74 | ||
|
|
7032bb6416 | ||
|
|
433f4e828f | ||
|
|
319baad70c | ||
|
|
56d06d0889 | ||
|
|
727491ca1a | ||
|
|
bc57d67a91 | ||
|
|
4754a9dbe0 | ||
|
|
c4bb84a88f | ||
|
|
543c361f87 | ||
|
|
e5c4409ad4 | ||
|
|
5fe609ae5c | ||
|
|
f1baa0503f | ||
|
|
9d8015925d | ||
|
|
32ec7504e5 | ||
|
|
16513dc387 | ||
|
|
4804f78042 | ||
|
|
eae2c38e23 | ||
|
|
7ffc2faa9a | ||
|
|
6f03d51390 | ||
|
|
4409b07ef5 | ||
|
|
5ee390f0da | ||
|
|
3aa5719600 | ||
|
|
70e6454c38 | ||
|
|
d6f93afffe | ||
|
|
f2ae44384f | ||
|
|
3c290ed6e2 | ||
|
|
85849a889f | ||
|
|
4993198266 | ||
|
|
ee7b8f74d7 | ||
|
|
8fd321f823 | ||
|
|
0526994603 | ||
|
|
0688305f86 | ||
|
|
e54ccdfc54 | ||
|
|
29b364d5cb | ||
|
|
71d602850e | ||
|
|
b590ee5444 | ||
|
|
db31a94461 | ||
|
|
405b537ef2 | ||
|
|
6722ea8676 | ||
|
|
d3879567c4 | ||
|
|
4c6147fc37 | ||
|
|
b2d2d17dda | ||
|
|
2dae6d945f | ||
|
|
ddc551626c | ||
|
|
7aacaef2cd | ||
|
|
e80dab2ea9 | ||
|
|
822ff97050 | ||
|
|
73e89f76aa | ||
|
|
c21a330dce | ||
|
|
b8fc762e11 | ||
|
|
e44249be1c | ||
|
|
f4ab65e399 | ||
|
|
d63565f191 | ||
|
|
729f6bdc6c | ||
|
|
c691625b15 | ||
|
|
4e57bf5a0e | ||
|
|
223d0a3fd3 | ||
|
|
00fa47b6b7 | ||
|
|
f52536f4ae | ||
|
|
76e1d4381d | ||
|
|
6c5d6ba631 | ||
|
|
1311f6c87c | ||
|
|
219f96a11a | ||
|
|
8b175280fa | ||
|
|
632bce5521 | ||
|
|
316d28746b | ||
|
|
9efe4a6efa | ||
|
|
85fbf64068 | ||
|
|
282255b841 | ||
|
|
9e380e5fea | ||
|
|
f12495b24a | ||
|
|
266040747e | ||
|
|
11a4a6acbd | ||
|
|
c70689fe54 | ||
|
|
936b31f1f0 | ||
|
|
8915672ce5 | ||
|
|
0640f90fc1 | ||
|
|
d1a0e8d906 | ||
|
|
e9a668ca56 | ||
|
|
27194c802d | ||
|
|
7aabfeaeac | ||
|
|
6d9bce3a25 | ||
|
|
efa0e3850f | ||
|
|
1e7e011a61 | ||
|
|
e45642b6c1 | ||
|
|
b550e2bfd5 | ||
|
|
4b3854d05d | ||
|
|
0362ae76ea | ||
|
|
098c11baf2 | ||
|
|
4e659c550e | ||
|
|
9cb1bac2fc | ||
|
|
33d65e85d8 | ||
|
|
7e260cf537 | ||
|
|
57932235ba | ||
|
|
2daba261a2 | ||
|
|
9a6daedd6d | ||
|
|
3b546dedd8 | ||
|
|
7320f88066 | ||
|
|
bde72e562e | ||
|
|
33066133fc | ||
|
|
3bcc5b8064 | ||
|
|
eba5df1fcc | ||
|
|
dad163771f | ||
|
|
bb59f5e6f7 | ||
|
|
7a1aa88edb | ||
|
|
a2c06c1bdb | ||
|
|
2a2c5a772f | ||
|
|
969fac5c4b | ||
|
|
b444d376f4 | ||
|
|
59d7909f50 | ||
|
|
f5f8ab5971 | ||
|
|
362c4baeca | ||
|
|
d39f02113c | ||
|
|
c9dc1223dd | ||
|
|
ba848d2d53 | ||
|
|
1c9c3d4399 | ||
|
|
090f872e80 | ||
|
|
3d9c1a2739 | ||
|
|
c97c260613 | ||
|
|
a46505e907 | ||
|
|
ea3f22c8a4 | ||
|
|
d78479e4af | ||
|
|
267371ba90 | ||
|
|
cc136922e5 | ||
|
|
02927106ca | ||
|
|
1275ebc2b1 | ||
|
|
2ac2a148c6 | ||
|
|
1a5f432ee1 | ||
|
|
5df4e713b6 | ||
|
|
20d2c74f87 | ||
|
|
bc244802c0 | ||
|
|
bd2f17ee10 | ||
|
|
563a4d5c71 | ||
|
|
78e6241d16 | ||
|
|
d08f630a2c | ||
|
|
26912e746b | ||
|
|
fa68b62be1 | ||
|
|
07a1d4d1b8 | ||
|
|
9c6b48980c | ||
|
|
79c7dd03a5 | ||
|
|
b252c689df | ||
|
|
c34380cf5c | ||
|
|
75ab9d615c | ||
|
|
b9333fab34 | ||
|
|
64899e5a39 | ||
|
|
80889dc9d2 | ||
|
|
b7239c4b6f | ||
|
|
67ae1d4cf0 | ||
|
|
03f5a83cbf | ||
|
|
77bb2ecc82 | ||
|
|
3160b65172 | ||
|
|
65b3ba1d12 | ||
|
|
ce919f0411 | ||
|
|
2dfbe8e5f2 | ||
|
|
e9d45b5435 | ||
|
|
c3f9c75b3c | ||
|
|
d24f79ee4d | ||
|
|
2992bd544e | ||
|
|
31ed3ce277 | ||
|
|
91b574e153 | ||
|
|
7966b43daf | ||
|
|
17dfb0db9d | ||
|
|
2c3a62abbc | ||
|
|
f9a806d9aa | ||
|
|
afd2d25e5e | ||
|
|
4ee9580d31 | ||
|
|
b35cf4afdc | ||
|
|
930246592a | ||
|
|
727be0a8ab | ||
|
|
ebe1d93c3a | ||
|
|
c7ad3ef4a9 | ||
|
|
fa8ed89eae | ||
|
|
0d7f392bcd | ||
|
|
d61551cedb | ||
|
|
07b944039c | ||
|
|
95933e93dd | ||
|
|
1cbe60a13f | ||
|
|
9505ba1606 | ||
|
|
bca1fe0d9b | ||
|
|
1d28ca1fca | ||
|
|
a75e519294 | ||
|
|
75d5c2a39f | ||
|
|
85d3c584ef | ||
|
|
ad0f6de809 | ||
|
|
5defb058d3 | ||
|
|
f202ad5e3f | ||
|
|
1cd8467b8f | ||
|
|
f2462d4270 | ||
|
|
4a4f4e37ba | ||
|
|
3a625157ff | ||
|
|
3bbc17fe4a | ||
|
|
8cff147029 | ||
|
|
ce984783ec | ||
|
|
dbde432948 | ||
|
|
85f945dcba | ||
|
|
487f4e220f | ||
|
|
6a8dec11ea | ||
|
|
1a91020a84 | ||
|
|
08a08cd74f | ||
|
|
639de6ca11 | ||
|
|
ba6a026cdc | ||
|
|
07634229f9 | ||
|
|
619aeb4355 | ||
|
|
e8d0af93fc | ||
|
|
4faa9964bd | ||
|
|
15a0ea79b0 | ||
|
|
d0a281e14f | ||
|
|
49e624e532 | ||
|
|
3bbcb8151d | ||
|
|
c7b9358bc7 | ||
|
|
a552e7d25c | ||
|
|
c108094aa5 | ||
|
|
769c67e7d3 | ||
|
|
f605e049fd | ||
|
|
e44201e0e3 | ||
|
|
028093199b | ||
|
|
6043b4288e | ||
|
|
11ec16494d | ||
|
|
b4922f60a2 | ||
|
|
b0e126f29d | ||
|
|
d8c411ad52 | ||
|
|
4f8f0e0bf3 | ||
|
|
dee6bf79d1 | ||
|
|
baeba0dea3 | ||
|
|
3dc31ad638 | ||
|
|
4201e2a611 | ||
|
|
d9f6fa7de6 | ||
|
|
d0146762bc | ||
|
|
7e8f2e2fbc | ||
|
|
497f4b65ef | ||
|
|
03c44778ba | ||
|
|
0cc744ae16 | ||
|
|
fae3862547 | ||
|
|
70a222f3c9 | ||
|
|
5676adca99 | ||
|
|
3a77ca68c4 | ||
|
|
248437d1d6 | ||
|
|
afcde4609e | ||
|
|
2e98974373 | ||
|
|
086a33fd62 | ||
|
|
33359dd435 | ||
|
|
574d71b50c | ||
|
|
c806b706d4 | ||
|
|
c3b8c0f7e9 | ||
|
|
a1cd622892 | ||
|
|
dea3ee0b84 | ||
|
|
5c64348ea8 | ||
|
|
262ac2c476 | ||
|
|
dbfbe30749 | ||
|
|
70437bd4cb | ||
|
|
2d30b5ea1c | ||
|
|
5414111bed | ||
|
|
9168bac16e | ||
|
|
8760d36f6c | ||
|
|
141b870bc0 | ||
|
|
5e4406e78c | ||
|
|
c5426bfcf7 | ||
|
|
76561a567f | ||
|
|
8288f0c751 | ||
|
|
7dc008db8b | ||
|
|
86bb4a27a4 | ||
|
|
f2d9f50930 | ||
|
|
b9af7e6a25 | ||
|
|
00825748ff | ||
|
|
fe0edde4a9 | ||
|
|
edfea91920 | ||
|
|
319e6bcdc8 | ||
|
|
274f73e040 | ||
|
|
fab37838b2 | ||
|
|
a5a3610bf6 | ||
|
|
07e600163c | ||
|
|
14a5dc5489 | ||
|
|
46c2b94425 | ||
|
|
9a1dc7f292 | ||
|
|
c68fc37959 | ||
|
|
aa1f555e05 | ||
|
|
699e64c610 | ||
|
|
e8c1392314 | ||
|
|
c1ae47d188 | ||
|
|
13a9f1113a | ||
|
|
c4ad86863f | ||
|
|
8300a618f8 | ||
|
|
52f0038262 | ||
|
|
31710ce91c | ||
|
|
a9c75652e1 | ||
|
|
3e13e5be57 | ||
|
|
c27979a210 | ||
|
|
37d7c84bc3 | ||
|
|
62f5c8fc2f | ||
|
|
289c449dff | ||
|
|
e7b7b603d2 | ||
|
|
e7e342600b | ||
|
|
db6e3b8371 | ||
|
|
79ed15c38c | ||
|
|
6f175dcafb | ||
|
|
ca70a10bd4 | ||
|
|
ae3319e9f9 | ||
|
|
5112cb24f5 | ||
|
|
c6bbccc02e | ||
|
|
93ec4d2515 | ||
|
|
955dc6094b | ||
|
|
bd694cbc53 | ||
|
|
c115a035ec | ||
|
|
288144f347 | ||
|
|
3bdfdaa40a | ||
|
|
22949813af | ||
|
|
5c98b01484 | ||
|
|
ea5e1cd0db | ||
|
|
b5d9955442 | ||
|
|
feb5cb35b4 | ||
|
|
654c7083eb | ||
|
|
a0457928b3 | ||
|
|
4df535a3a9 | ||
|
|
0b251ec4e0 | ||
|
|
7704a9ac41 | ||
|
|
59031893ff | ||
|
|
fcfa044320 | ||
|
|
f95658e7ce | ||
|
|
2c16fcaa99 | ||
|
|
4e638016e1 | ||
|
|
5d811c0e68 | ||
|
|
9f1f51637a | ||
|
|
7c16ffcdf8 | ||
|
|
7ca582719b | ||
|
|
e4b83baa53 | ||
|
|
ac6b2933a8 | ||
|
|
92758fa51d | ||
|
|
acd06a4f5a | ||
|
|
eec6b17398 | ||
|
|
15fbf02647 | ||
|
|
c296be5057 | ||
|
|
129e178ee0 | ||
|
|
1e5caa62a8 | ||
|
|
420ed0764b | ||
|
|
ce6bbb2885 | ||
|
|
87d6c5dd29 | ||
|
|
dccd456497 | ||
|
|
520bdd64e6 | ||
|
|
72608fd016 | ||
|
|
69b51ffbd5 | ||
|
|
c9044ea07b | ||
|
|
362c40326f | ||
|
|
28d0793688 | ||
|
|
abdc2000c4 | ||
|
|
3d845b1e9f | ||
|
|
bae8c97df4 | ||
|
|
452c1d4b92 | ||
|
|
9990e6e2a6 | ||
|
|
8d0dc3eb78 | ||
|
|
0a2a3c75c1 | ||
|
|
830e6acb4f | ||
|
|
1da85dff58 | ||
|
|
dd40e3be5b | ||
|
|
224d6488a9 | ||
|
|
cac31d3294 | ||
|
|
951d5fa58d | ||
|
|
7a4f0778df | ||
|
|
5aff4d29fc | ||
|
|
402b7001ee | ||
|
|
f7d0979fb1 | ||
|
|
2289ed9d95 | ||
|
|
dfcb44016f | ||
|
|
37a434a615 | ||
|
|
0ddcf1e401 | ||
|
|
0aa673f24e | ||
|
|
b3a24daa2f | ||
|
|
8c6954cd75 | ||
|
|
283f08de07 | ||
|
|
d96543ddeb | ||
|
|
4b320f3cb5 | ||
|
|
69a6d3e3f3 | ||
|
|
93d4587732 | ||
|
|
7481b9788a | ||
|
|
acf3e0b397 | ||
|
|
88ae0fa059 | ||
|
|
a1e63d9028 | ||
|
|
2a1ad8d31c | ||
|
|
ba7cd2160f | ||
|
|
8e50383371 | ||
|
|
ffc5352840 | ||
|
|
53e849cbec | ||
|
|
b71d57d7ec | ||
|
|
4fe2b2542f | ||
|
|
8c7895d8ab | ||
|
|
ad15f4dc59 | ||
|
|
c4ef161a83 | ||
|
|
bb48025947 | ||
|
|
389a7f28c4 | ||
|
|
714cc1c734 | ||
|
|
8d0da7f870 | ||
|
|
e42e74103d | ||
|
|
4bcdb91895 | ||
|
|
938977bbca | ||
|
|
581c1c46e2 | ||
|
|
768b2ab620 | ||
|
|
4eff5ab357 | ||
|
|
888892b92f | ||
|
|
ba4f146c9c | ||
|
|
8359dd2ae2 | ||
|
|
0be80db8f9 | ||
|
|
72de142519 | ||
|
|
0a7468f56d | ||
|
|
33b5c6c616 | ||
|
|
4003d7600d | ||
|
|
a7122ba8bb | ||
|
|
dc8c85d3db | ||
|
|
fc1b4a6f35 | ||
|
|
af42623654 | ||
|
|
ab1a672336 | ||
|
|
4501d7dcde | ||
|
|
5d463d6bff | ||
|
|
9c8a9fbe32 | ||
|
|
1a89b2eae5 | ||
|
|
fd65e72bbb | ||
|
|
33e8d0875d | ||
|
|
19e75576a8 | ||
|
|
980860b2e9 | ||
|
|
eee3e36238 | ||
|
|
eaadd37e87 | ||
|
|
a1e508b1df | ||
|
|
2c8f9dffdd | ||
|
|
92fd3bf8ae | ||
|
|
c940675bf3 | ||
|
|
2a147d5029 | ||
|
|
0d236ae32c | ||
|
|
cf4654108e | ||
|
|
7e9eed9374 | ||
|
|
383581938a | ||
|
|
df50da9024 | ||
|
|
d3a65303a1 | ||
|
|
9a2bf923d2 | ||
|
|
9b27c0c651 | ||
|
|
2af85e7347 | ||
|
|
071f0f4443 | ||
|
|
903e8c96aa | ||
|
|
79a5fb9c15 | ||
|
|
46ef4b27bb | ||
|
|
1838797d38 | ||
|
|
c7d500b8ba | ||
|
|
95a09cb644 | ||
|
|
c6ab92e60a | ||
|
|
c0d5f3019b | ||
|
|
b09d5c3833 | ||
|
|
3eff1b48b1 | ||
|
|
a12fffc4e7 | ||
|
|
94715130fc | ||
|
|
313188ca0e | ||
|
|
5a68b008c6 | ||
|
|
6fe9098c76 | ||
|
|
631a914acd | ||
|
|
d1f24c9722 | ||
|
|
7b76c9319a | ||
|
|
63083c5d1e | ||
|
|
c51a3cd624 | ||
|
|
1fadb7485a | ||
|
|
58e05d13d1 | ||
|
|
d8c9692d4d | ||
|
|
f83ffd3a25 | ||
|
|
d12ff2a92b | ||
|
|
8709d6f9a9 | ||
|
|
e2806c55ff | ||
|
|
08d6c843d6 | ||
|
|
0da3726a89 | ||
|
|
36676bcad3 | ||
|
|
1509e1e9a8 | ||
|
|
4c71dd9ebe | ||
|
|
ef8d0d6334 | ||
|
|
7477b7a173 | ||
|
|
246f36821b | ||
|
|
d567ee60bf | ||
|
|
3a157d2808 | ||
|
|
7d0c2f9ef8 | ||
|
|
f356f8734a | ||
|
|
5b7f4a7ff5 | ||
|
|
e10efca17a | ||
|
|
578b9a5275 | ||
|
|
63304b3d12 | ||
|
|
39f6ca0035 | ||
|
|
5e3c62c963 | ||
|
|
6966600223 | ||
|
|
e028cbb6d5 | ||
|
|
8b3c3f48a8 | ||
|
|
2d84e72097 | ||
|
|
d91fe7b633 | ||
|
|
090df10831 | ||
|
|
f21037bb69 | ||
|
|
f3041bcc9a | ||
|
|
67b1225dfa | ||
|
|
23f2e0371e | ||
|
|
a3d8df222f | ||
|
|
632ef3707c | ||
|
|
79dc099e6d | ||
|
|
75035fb40c | ||
|
|
b4887b661c | ||
|
|
e8835af363 | ||
|
|
1fabe08332 | ||
|
|
c2e3638e8d | ||
|
|
71abced420 | ||
|
|
ac00046b07 | ||
|
|
38b5204713 | ||
|
|
4b173dece5 | ||
|
|
8ce2c09b52 | ||
|
|
8125574f8f | ||
|
|
8974360cac | ||
|
|
6e48cc1524 | ||
|
|
a1ea75ca34 | ||
|
|
81d2f21093 | ||
|
|
fd73a31abc | ||
|
|
1583ac0c08 | ||
|
|
cafbecd8af | ||
|
|
78c36612b7 | ||
|
|
a95385c740 | ||
|
|
a58ebf7c48 | ||
|
|
13623575ff | ||
|
|
87c5f913b8 | ||
|
|
41172d7967 | ||
|
|
820bc87cfe | ||
|
|
2901acfb41 | ||
|
|
681460a415 | ||
|
|
19b067405f | ||
|
|
3b494b5737 | ||
|
|
5f11a19296 | ||
|
|
3ff7675eb7 | ||
|
|
3d06841eba | ||
|
|
188c026c6b | ||
|
|
caf051f19d | ||
|
|
c4a3d934a9 | ||
|
|
b19424aa23 | ||
|
|
bc229fa6fd | ||
|
|
9beb5b553b | ||
|
|
667e6a8e06 | ||
|
|
8f9b667c29 | ||
|
|
a8e0c76a30 | ||
|
|
49609ff08e | ||
|
|
efe201e032 | ||
|
|
28c903f7ea | ||
|
|
a5b45031d2 | ||
|
|
42e178b41d | ||
|
|
c3fe2c13f4 | ||
|
|
af8a6872d9 | ||
|
|
f40a5e68ea | ||
|
|
c4ad98426c | ||
|
|
a0e3d4ad69 | ||
|
|
d64bfe1cec | ||
|
|
8a213af2ab | ||
|
|
f02659e5d7 | ||
|
|
bdf943c3d9 | ||
|
|
9f1d5bc631 | ||
|
|
f2b46679a6 | ||
|
|
c5f38af247 | ||
|
|
2bfef4f02d | ||
|
|
07ae50cbb0 | ||
|
|
7f10bf4005 | ||
|
|
9130fe7b38 | ||
|
|
340dcd1748 | ||
|
|
8919bb5810 | ||
|
|
bea98db813 | ||
|
|
05a0130c1e | ||
|
|
e486437865 | ||
|
|
1043516fb7 | ||
|
|
c9b8b81ffb | ||
|
|
99b143a55c | ||
|
|
8401f42f3e | ||
|
|
f69949edea | ||
|
|
62e33f294e | ||
|
|
2a8e48ba63 | ||
|
|
6372bf663f | ||
|
|
ac7cc09bfe | ||
|
|
c9f0d473cf | ||
|
|
8a7ffdbb67 | ||
|
|
d30baaf16c | ||
|
|
1981adeb22 | ||
|
|
8427b8b668 | ||
|
|
6db590a31b | ||
|
|
22faa03a48 | ||
|
|
d3cd0ae85a | ||
|
|
b624955bf3 | ||
|
|
1b20cd14d1 | ||
|
|
baf2f780c9 | ||
|
|
9d1997b6cd | ||
|
|
313baa0064 | ||
|
|
006eee9f51 | ||
|
|
2720caf945 | ||
|
|
62faa57bf0 | ||
|
|
abbdb995e6 | ||
|
|
fd2ae60a65 | ||
|
|
2c4cf2d06b | ||
|
|
0f5ec15d47 | ||
|
|
1c3dfb346f | ||
|
|
b76013d60b | ||
|
|
e3ed95571c | ||
|
|
c749893858 | ||
|
|
9135be3da6 | ||
|
|
9930fd3938 | ||
|
|
c62c3df00d | ||
|
|
0419d67533 | ||
|
|
32d69c5be0 | ||
|
|
c2fb23c69c | ||
|
|
47611e14f7 | ||
|
|
b90f876b5b | ||
|
|
9037d51bc7 | ||
|
|
fb8c68f5e0 | ||
|
|
4995b5bb8c | ||
|
|
c87ebfd4eb | ||
|
|
b9d0dae5ac | ||
|
|
ab2a74285d | ||
|
|
e37ab72182 | ||
|
|
891dec64a0 | ||
|
|
90086789c6 | ||
|
|
2cdcdb9cd6 | ||
|
|
9c6879bd97 | ||
|
|
fc88acc782 | ||
|
|
1578dfe26b | ||
|
|
eb5e5a7069 | ||
|
|
b58cfefa13 | ||
|
|
de4d395aea | ||
|
|
7072bd9f36 | ||
|
|
8e36bc64fd | ||
|
|
4326a705f3 | ||
|
|
eb99e294ed | ||
|
|
27acb2b967 | ||
|
|
9cf5124a52 | ||
|
|
d00282f077 | ||
|
|
2556bedcda | ||
|
|
a569acd12a | ||
|
|
5e6c462708 | ||
|
|
4e0900dffa | ||
|
|
5c61211522 | ||
|
|
0747dc5cf6 | ||
|
|
85099c8ad6 | ||
|
|
72da91a8c7 | ||
|
|
4aced858a8 | ||
|
|
786ab176c9 | ||
|
|
973af107da | ||
|
|
1911ef0172 | ||
|
|
d2e9b340c9 | ||
|
|
5b487d1722 | ||
|
|
a91da59448 | ||
|
|
2846254304 | ||
|
|
5fe765dd29 | ||
|
|
9815f44134 | ||
|
|
3f8969b88f | ||
|
|
4fc7a44a9d | ||
|
|
e132688e00 | ||
|
|
588df57840 | ||
|
|
4a8ca6fdc1 | ||
|
|
2bb2493731 | ||
|
|
c61949ceaf | ||
|
|
3fce1e00c9 | ||
|
|
2f2add1c49 | ||
|
|
697acb103f | ||
|
|
c830e43e8f | ||
|
|
834ef45ca6 | ||
|
|
279faa13e9 | ||
|
|
0309abca6f | ||
|
|
fedee67bda | ||
|
|
a6c3566aa5 | ||
|
|
52fa24e1c4 | ||
|
|
a7ecf41e3b | ||
|
|
e68e5f6265 | ||
|
|
aad5a9b060 | ||
|
|
aa064029ec | ||
|
|
e84060e01c | ||
|
|
f4f72ebb43 | ||
|
|
da51e81e38 | ||
|
|
247cbdd0d0 | ||
|
|
c528740154 | ||
|
|
37b357b050 | ||
|
|
18c376979d | ||
|
|
9cc4357a70 | ||
|
|
f2d35a052f | ||
|
|
221f378d10 | ||
|
|
06a8c8b940 | ||
|
|
eee80b421a | ||
|
|
f6e22c3636 | ||
|
|
20d77fbba5 | ||
|
|
0393ebe012 | ||
|
|
2beddcf77b | ||
|
|
e784ebbcdd | ||
|
|
30ee538dbd | ||
|
|
7939ba6e05 | ||
|
|
2785e69fc1 | ||
|
|
d472c1696d | ||
|
|
d9cfa71fc7 | ||
|
|
715e12912b | ||
|
|
b182fe27f6 | ||
|
|
5594b33933 | ||
|
|
059b8800f6 | ||
|
|
9f687b1848 | ||
|
|
a4a05b1f0a | ||
|
|
1a7b0b0626 | ||
|
|
4c467e46cf | ||
|
|
fa71edeb07 | ||
|
|
4ff436371d | ||
|
|
9d8fa0bc5a | ||
|
|
1a8ecd7889 | ||
|
|
f6614fdfda | ||
|
|
a6055df756 | ||
|
|
5af91c5eab | ||
|
|
41974c4a46 | ||
|
|
f001b5bd76 | ||
|
|
28cf457853 | ||
|
|
8ccc23333d | ||
|
|
d95954d980 | ||
|
|
3506881c2a | ||
|
|
51d127c378 | ||
|
|
2d5dd7ef63 | ||
|
|
ef23ba55a1 | ||
|
|
ffdbf2f3f1 | ||
|
|
56cad83f55 | ||
|
|
719f33f7a7 | ||
|
|
700ffacdb1 | ||
|
|
a6ef4ed55c | ||
|
|
c5da564fb3 | ||
|
|
a6b04ebb64 | ||
|
|
99ba6db257 | ||
|
|
a3cddb72b9 | ||
|
|
2a9e896095 | ||
|
|
89d522d325 | ||
|
|
3c4ff587ca | ||
|
|
e111529035 | ||
|
|
cae1f97032 | ||
|
|
20419834a6 | ||
|
|
5dabc2a20b | ||
|
|
c700f5fc68 | ||
|
|
0b71cf86f2 | ||
|
|
96159bd09c | ||
|
|
bcff802ccb | ||
|
|
376d295853 | ||
|
|
0030ad1804 | ||
|
|
4ec3e0f7d8 | ||
|
|
e36219e408 | ||
|
|
8f8f53a697 | ||
|
|
567292c72f | ||
|
|
b744f73a76 | ||
|
|
da440a5e16 | ||
|
|
017af1d5c3 | ||
|
|
1f5d75d8e9 | ||
|
|
8b80abc701 | ||
|
|
dc75ca4caf | ||
|
|
d7d4c0a54d | ||
|
|
823b094b60 | ||
|
|
06a6c982aa | ||
|
|
1d15ef01f9 | ||
|
|
f72ffcbb43 | ||
|
|
e0f2305cd9 | ||
|
|
210939d2c1 | ||
|
|
2fd071d90e | ||
|
|
badec62cdd | ||
|
|
895cda4de7 | ||
|
|
21fdc9f350 | ||
|
|
398c0ef687 | ||
|
|
3b0a9aef3c | ||
|
|
48ec0916bf | ||
|
|
10af87a7d0 | ||
|
|
96e7996f37 | ||
|
|
0f7af931a9 | ||
|
|
cfd2d80b78 | ||
|
|
0386c01aa9 | ||
|
|
2c39c91ac6 | ||
|
|
0eb51e3e8b | ||
|
|
bb931e9da7 | ||
|
|
7b2e672496 | ||
|
|
cdc6370ee5 | ||
|
|
cc762e4e1d | ||
|
|
ed525bd1d8 | ||
|
|
2b2e92c810 | ||
|
|
44d31ead76 | ||
|
|
ec163e94eb | ||
|
|
ec2ac33fec | ||
|
|
20bda2af26 | ||
|
|
7a49f6293d | ||
|
|
81b21010f1 | ||
|
|
2526e0a2f7 | ||
|
|
af1e8470c9 | ||
|
|
dfd9da68a7 | ||
|
|
5e702234f4 | ||
|
|
9020dcca9a | ||
|
|
930a4e4c1d | ||
|
|
4db77f96b7 | ||
|
|
cc12c046b9 | ||
|
|
f5c63e0997 | ||
|
|
29a26800b7 | ||
|
|
bc5eeb3b3a | ||
|
|
40d02518b0 | ||
|
|
a2556edc69 | ||
|
|
111970fda9 | ||
|
|
ebeb7bc969 | ||
|
|
6ccac5f69c | ||
|
|
cc41b8b259 | ||
|
|
db1a3456b7 | ||
|
|
1b9305c073 | ||
|
|
a33814ef40 | ||
|
|
581bc9f27c | ||
|
|
40cff0053f | ||
|
|
cc33b12b0d | ||
|
|
2add1c68ea | ||
|
|
380b6676a6 | ||
|
|
f133a36477 | ||
|
|
5f2d6f8e2f |
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'
|
||||
@@ -0,0 +1,31 @@
|
||||
<!--
|
||||
ℹ We use Github issues for bug reports, feature requests, general support, and questions about the library.
|
||||
|
||||
Please fill out this template when filing an issue.
|
||||
-->
|
||||
|
||||
### What did you do?
|
||||
|
||||
<!-- Please replace this with what you did. -->
|
||||
|
||||
### What did you expect to happen?
|
||||
|
||||
<!-- Please replace this with what you expected to happen. -->
|
||||
|
||||
### What happened instead?
|
||||
|
||||
<!-- Please replace this with of what happened instead. -->
|
||||
|
||||
### Environment
|
||||
|
||||
**GRDB flavor(s):** (GRDB, SQLCipher, Custom SQLite build?)
|
||||
**GRDB version:**
|
||||
**Installation method:** (CocoaPods, SPM, manual?)
|
||||
**Xcode version:**
|
||||
**Swift version:**
|
||||
**Platform(s) running GRDB:** (iOS, macOS, watchOS?)
|
||||
**macOS version running Xcode:**
|
||||
|
||||
### Demo Project
|
||||
|
||||
<!-- Please link to or upload a project we can download that reproduces the issue. -->
|
||||
@@ -0,0 +1,12 @@
|
||||
<!-- Please describe your pull request here. -->
|
||||
|
||||
### Pull Request Checklist
|
||||
|
||||
<!--
|
||||
Please verify that your pull request checks those boxes:
|
||||
-->
|
||||
|
||||
- [ ] 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.
|
||||
@@ -101,12 +101,12 @@ SQLiteCustom/GRDBCustomSQLite-USER.h
|
||||
SQLiteCustom/GRDBCustomSQLite-USER.xcconfig
|
||||
|
||||
# CocoaPods test
|
||||
Podfile.lock
|
||||
Pods
|
||||
Podfile.lock
|
||||
|
||||
# SPM
|
||||
.build
|
||||
Package.pins
|
||||
Package.resolved
|
||||
Tests/SPM/Packages
|
||||
|
||||
# Ruby
|
||||
|
||||
@@ -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 @@
|
||||
3.1
|
||||
@@ -0,0 +1,57 @@
|
||||
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_first_not_nil
|
||||
- convenience_type
|
||||
- empty_count
|
||||
- empty_string
|
||||
- explicit_init
|
||||
- fatal_error_message
|
||||
- first_where
|
||||
- joined_default_parameter
|
||||
- last_where
|
||||
- legacy_multiple
|
||||
- legacy_random
|
||||
- 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
|
||||
- unused_private_declaration
|
||||
- yoda_condition
|
||||
|
||||
vertical_whitespace:
|
||||
max_empty_lines: 2
|
||||
|
||||
@@ -1,6 +1,19 @@
|
||||
# The OS X Build Environment
|
||||
# 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:
|
||||
@@ -10,142 +23,377 @@ jobs:
|
||||
include:
|
||||
|
||||
###########################################
|
||||
## Test GRDB
|
||||
|
||||
# Test GRDBOSX (Xcode 8.3)
|
||||
- stage: Test GRDB
|
||||
## Test GRDB Xcode 10.2
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDBOSX (Xcode 8.3, macOS 10.12)
|
||||
script: make test_framework_GRDBOSX
|
||||
|
||||
# Test GRDBWatchOS (Xcode 8.3)
|
||||
- stage: Test GRDB
|
||||
- TID=GRDBOSX (Swift 5, macOS)
|
||||
script: make test_framework_GRDBOSX_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDBWatchOS (Xcode 8.3, watchOS)
|
||||
- TID=GRDBOSX (Swift 4.2, macOS)
|
||||
script: make test_framework_GRDBOSX_minSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDBWatchOS (watchOS)
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
# Test GRDBiOS (Xcode 8.3, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDBiOS (Xcode 8.3, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget
|
||||
|
||||
# Test GRDBiOS (Xcode 8.3, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB
|
||||
- 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: xcode8.3
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDBiOS (Xcode 8.3, iOS <MIN>)
|
||||
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget_minSwift
|
||||
|
||||
- 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
|
||||
|
||||
# Test GRDB [SPM] (Xcode 8.3, macOS 10.12)
|
||||
- stage: Test GRDB
|
||||
|
||||
- stage: Test GRDB Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDB [SPM] (Xcode 8.3, macOS 10.12)
|
||||
- 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 4.2, tvOS <MAX>)
|
||||
script: make test_framework_GRDBtvOS_maxTarget_minSwift
|
||||
|
||||
- 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 (Custom SQLite)
|
||||
|
||||
# Test GRDBCustomSQLiteOSX (Xcode 8.3)
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
## Test GRDBCustom Xcode 10.2
|
||||
|
||||
- stage: Test GRDBCustom Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteOSX (Xcode 8.3, macOS 10.12)
|
||||
- TID=GRDBOSX (Swift 5, macOS)
|
||||
script: make test_framework_GRDBCustomSQLiteOSX
|
||||
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 8.3, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
|
||||
- stage: Test GRDBCustom Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 8.3, iOS <MAX>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget
|
||||
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 8.3, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
- TID=GRDBiOS (Swift 5, iOS <MAX>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDBCustom Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 8.3, iOS <MIN>)
|
||||
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_minSwift
|
||||
|
||||
- stage: Test GRDBCustom Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 5, iOS <MIN>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
|
||||
|
||||
|
||||
###########################################
|
||||
## Test GRDB (SQLCipher)
|
||||
|
||||
# Test GRDBCipherOSX (Xcode 8.3)
|
||||
- stage: Test GRDB + SQLCipher
|
||||
## Test SQLCipher Xcode 10.2
|
||||
|
||||
- stage: Test SQLCipher Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDBCipherOSX (Xcode 8.3, macOS 10.12)
|
||||
script: make test_framework_GRDBCipherOSX
|
||||
|
||||
# Test GRDBCipheriOS (Xcode 8.3, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB + SQLCipher
|
||||
- TID=SQLCipher 3
|
||||
script: make test_framework_SQLCipher3
|
||||
|
||||
- stage: Test SQLCipher Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=GRDBCipheriOS (Xcode 8.3, iOS <MAX>)
|
||||
script: make test_framework_GRDBCipheriOS_maxTarget
|
||||
|
||||
# Test GRDBCipheriOS (Xcode 8.3, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
env:
|
||||
- TID=GRDBCipheriOS (Xcode 8.3, iOS <MIN>)
|
||||
script: make test_framework_GRDBCipheriOS_minTarget
|
||||
|
||||
- TID=SQLCipher 4
|
||||
script: make test_framework_SQLCipher4
|
||||
|
||||
###########################################
|
||||
## Test Installation Methods
|
||||
|
||||
## Test Installation Xcode 10.2
|
||||
|
||||
# Manual Install
|
||||
- stage: Test Installation
|
||||
- stage: Test Installation Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=Manual Install
|
||||
script: make test_install_manual
|
||||
|
||||
# Manual Install (GRDBCipher)
|
||||
- stage: Test Installation
|
||||
|
||||
# CocoaPods Lint
|
||||
- stage: Test Installation Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=Manual Install (GRDBCipher)
|
||||
script: make test_install_GRDBCipher
|
||||
|
||||
# Cocoapods Lint
|
||||
- stage: Test Installation
|
||||
osx_image: xcode8.3
|
||||
install:
|
||||
- gem install cocoapods # Since Travis is not always on latest version
|
||||
- TID=CocoaPods Lint
|
||||
script: make test_CocoaPodsLint_GRDB
|
||||
|
||||
# CocoaPods Install GRDB
|
||||
- stage: Test Installation Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=Cocoapods
|
||||
script: make test_CocoaPodsLint
|
||||
|
||||
- TID=CocoaPods GRDB (framework)
|
||||
script: make test_install_GRDB_CocoaPods_framework
|
||||
|
||||
# CocoaPods Install GRDB
|
||||
- stage: Test Installation Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=CocoaPods GRDB (static)
|
||||
script: make test_install_GRDB_CocoaPods_static
|
||||
|
||||
# SPM Install
|
||||
- stage: Test Installation
|
||||
osx_image: xcode8.3
|
||||
- stage: Test Installation Xcode 10.2
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10.2
|
||||
env:
|
||||
- TID=SPM
|
||||
script: make test_install_SPM
|
||||
|
||||
## The following doesn’t work, as `make test_CarthageBuild` does not yet work.
|
||||
## Carthage Build
|
||||
#- stage: Carthage
|
||||
# osx_image: xcode8.3
|
||||
# before_install:
|
||||
# - brew update
|
||||
# - brew outdated carthage || brew upgrade carthage
|
||||
# script: make test_CarthageBuild
|
||||
|
||||
###########################################
|
||||
## 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 GRDBCustom Xcode 10.1
|
||||
#
|
||||
# - stage: Test GRDBCustom Xcode 10.1
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode10.1
|
||||
# env:
|
||||
# - TID=GRDBOSX (Swift 4.2, macOS)
|
||||
# script: make test_framework_GRDBCustomSQLiteOSX
|
||||
#
|
||||
# - stage: Test GRDBCustom Xcode 10.1
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode10.1
|
||||
# env:
|
||||
# - TID=GRDBiOS (Swift 4.2, iOS <MAX>)
|
||||
# script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
|
||||
#
|
||||
# - stage: Test GRDBCustom Xcode 10.1
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode10.1
|
||||
# env:
|
||||
# - TID=GRDBiOS (Swift 4.2, iOS <MIN>)
|
||||
# script: make test_framework_GRDBCustomSQLiteiOS_minTarget
|
||||
|
||||
###########################################
|
||||
## Test GRDB Xcode 10
|
||||
|
||||
- stage: Test GRDB Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=GRDBOSX (Swift 4.2, macOS)
|
||||
script: make test_framework_GRDBOSX_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=GRDBWatchOS (watchOS)
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
- stage: Test GRDB Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
|
||||
- stage: Test GRDB Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 4.2, iOS <MIN>)
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
- stage: Test GRDB Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=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
|
||||
|
||||
# ###########################################
|
||||
# ## Test GRDBCustom Xcode 10
|
||||
#
|
||||
# - stage: Test GRDBCustom Xcode 10
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode10
|
||||
# env:
|
||||
# - TID=GRDBOSX (Swift 4.2, macOS)
|
||||
# script: make test_framework_GRDBCustomSQLiteOSX
|
||||
#
|
||||
# - stage: Test GRDBCustom Xcode 10
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode10
|
||||
# env:
|
||||
# - TID=GRDBiOS (Swift 4.2, iOS <MAX>)
|
||||
# script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
|
||||
#
|
||||
# - stage: Test GRDBCustom Xcode 10
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode10
|
||||
# env:
|
||||
# - TID=GRDBiOS (Swift 4.2, iOS <MIN>)
|
||||
# script: make test_framework_GRDBCustomSQLiteiOS_minTarget
|
||||
#
|
||||
# ###########################################
|
||||
# ## Test SQLCipher Xcode 10
|
||||
#
|
||||
# - stage: Test SQLCipher Xcode 10
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode10
|
||||
# env:
|
||||
# - TID=SQLCipher 3
|
||||
# script: make test_framework_SQLCipher3
|
||||
#
|
||||
# - stage: Test SQLCipher Xcode 10
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode10
|
||||
# env:
|
||||
# - TID=SQLCipher 4
|
||||
# script: make test_framework_SQLCipher4
|
||||
|
||||
###########################################
|
||||
## Test Installation Xcode 10
|
||||
|
||||
# # Manual Install
|
||||
# - stage: Test Installation Xcode 10
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode10
|
||||
# env:
|
||||
# - TID=Manual Install
|
||||
# script: make test_install_manual
|
||||
#
|
||||
# # CocoaPods Lint
|
||||
# - stage: Test Installation Xcode 10
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode10
|
||||
# env:
|
||||
# - TID=CocoaPods Lint
|
||||
# script: make test_CocoaPodsLint_GRDB
|
||||
|
||||
# CocoaPods Install GRDB
|
||||
- stage: Test Installation Xcode 10
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode10
|
||||
env:
|
||||
- TID=CocoaPods GRDB (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
|
||||
|
||||
# # SPM Install
|
||||
# - stage: Test Installation Xcode 10
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode10
|
||||
# env:
|
||||
# - TID=SPM
|
||||
# script: make test_install_SPM
|
||||
@@ -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,390 @@
|
||||
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]
|
||||
- [FetchedRecordsController Diffing Algorithm]
|
||||
- [FetchedRecordsController Support for Any Request]
|
||||
- [FetchedRecordsController Support for Sections]
|
||||
- [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.
|
||||
|
||||
|
||||
### FetchedRecordsController Diffing Algorithm
|
||||
|
||||
:muscle: Hard
|
||||
|
||||
[FetchedRecordsController] uses a Levenshtein-based diffing algorithm which has a terrible algorithmic complexity. This makes this very useful class unable to deal with more than hundreds of elements.
|
||||
|
||||
There exists much more efficient O(n) diffing algorithms that would lift this limitation.
|
||||
|
||||
Starting points:
|
||||
|
||||
- [RxSwiftCommunity/RxDataSources](https://github.com/RxSwiftCommunity/RxDataSources)
|
||||
- [ra1028/DifferenceKit](https://github.com/ra1028/DifferenceKit)
|
||||
- [tonyarnold/Differ](https://github.com/tonyarnold/Differ)
|
||||
- [onmyway133/DeepDiff](https://github.com/onmyway133/DeepDiff)
|
||||
- [mcudich/HeckelDiff](https://github.com/mcudich/HeckelDiff)
|
||||
|
||||
|
||||
### FetchedRecordsController Support for Any Request
|
||||
|
||||
:muscle: Hard
|
||||
|
||||
[FetchedRecordsController] is able to deal with records, but not with raw rows or values:
|
||||
|
||||
```swift
|
||||
// Supported by FetchedRecordsController
|
||||
let recordRequest = Player.all()
|
||||
|
||||
// Not supported by FetchedRecordsController
|
||||
let stringRequest = Player.select(Column("name"), as: String.self)
|
||||
let rowRequest = SQLRequest<Row>("SELECT ...")
|
||||
```
|
||||
|
||||
This limitation does not apply to [ValueObservation] and [RxGRDB]. It would be nice if FetchedRecordsController would become just as versatile.
|
||||
|
||||
|
||||
### FetchedRecordsController Support for Sections
|
||||
|
||||
:muscle: Hard
|
||||
|
||||
[FetchedRecordsController] mimics the API of Core Data's [NSFetchedResultsController](https://developer.apple.com/documentation/coredata/nsfetchedresultscontroller), but does not yet support table and collection view sections.
|
||||
|
||||
This improvement most certainly depends on a refreshing of the [FetchedRecordsController Diffing Algorithm].
|
||||
|
||||
|
||||
### Full Text Search Demo Application
|
||||
|
||||
:baby: Starter Task :pencil: Documentation
|
||||
|
||||
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
|
||||
[FetchedRecordsController]: README.md#fetchedrecordscontroller
|
||||
[FetchedRecordsController Diffing Algorithm]: #fetchedrecordscontroller-diffing-algorithm
|
||||
[FetchedRecordsController Support for Any Request]: #fetchedrecordscontroller-support-for-any-request
|
||||
[FetchedRecordsController Support for Sections]: #fetchedrecordscontroller-support-for-sections
|
||||
[Full Text Search Demo Application]: #full-text-search-demo-application
|
||||
[How is the Library Organized?]: Documentation/LibraryOrganization.md
|
||||
[How is the Repository Organized?]: Documentation/RepositoryOrganization.md
|
||||
[JSON]: #json
|
||||
[Linux]: #linux
|
||||
[More SQL Generation]: #more-sql-generation
|
||||
[Reactive Database Observation]: #reactive-database-observation
|
||||
[Records: Splitting Database Encoding from Ability to Write in the Database]: #records-splitting-database-encoding-from-ability-to-write-in-the-database
|
||||
[Non-Goals]: #non-goals
|
||||
[Report Bugs]: #report-bugs
|
||||
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
|
||||
[Concurrency]: #concurrency
|
||||
[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,11 +1,3 @@
|
||||
//
|
||||
// ExtensionDelegate.swift
|
||||
// GRDBDemoWatchOS Extension
|
||||
//
|
||||
// Created by Gwendal Roué on 03/04/2017.
|
||||
// Copyright © 2017 Gwendal Roué. All rights reserved.
|
||||
//
|
||||
|
||||
import WatchKit
|
||||
|
||||
class ExtensionDelegate: NSObject, WKExtensionDelegate {
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -1,14 +1,7 @@
|
||||
//
|
||||
// InterfaceController.swift
|
||||
// GRDBDemoWatchOS Extension
|
||||
//
|
||||
// Created by Gwendal Roué on 03/04/2017.
|
||||
// Copyright © 2017 Gwendal Roué. All rights reserved.
|
||||
//
|
||||
|
||||
import WatchKit
|
||||
import Foundation
|
||||
import GRDB
|
||||
import SQLite3
|
||||
|
||||
class InterfaceController: WKInterfaceController {
|
||||
|
||||
|
||||
@@ -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,7 +7,6 @@
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
5657C36E1E926B05008402E8 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 5657C36D1E926B05008402E8 /* libsqlite3.tbd */; };
|
||||
568E5FC31E926430002582E0 /* Interface.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FC11E926430002582E0 /* Interface.storyboard */; };
|
||||
568E5FC51E926430002582E0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FC41E926430002582E0 /* Assets.xcassets */; };
|
||||
568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = 568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
|
||||
@@ -21,17 +20,22 @@
|
||||
56B0360C1E8D9EBE003B6DA4 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */; };
|
||||
56B0360E1E8D9EBE003B6DA4 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */; };
|
||||
56B036111E8D9EBE003B6DA4 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */; };
|
||||
56B0361B1E8D9F38003B6DA4 /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036191E8D9F38003B6DA4 /* Database.swift */; };
|
||||
56B0361C1E8D9F38003B6DA4 /* Person.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Person.swift */; };
|
||||
56B036221E8D9F4C003B6DA4 /* DemoViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */; };
|
||||
56B036231E8D9F4C003B6DA4 /* PersonEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PersonEditionViewController.swift */; };
|
||||
56B036241E8D9F4C003B6DA4 /* PersonsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PersonsViewController.swift */; };
|
||||
56B036251E8D9F4C003B6DA4 /* SimplePersonsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036211E8D9F4C003B6DA4 /* SimplePersonsViewController.swift */; };
|
||||
56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */; };
|
||||
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 */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56439B501F4CA1DC0066043F;
|
||||
remoteInfo = GRDBOSXPerformanceComparisonTests;
|
||||
};
|
||||
568E5FCD1E926430002582E0 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B035FB1E8D9EBE003B6DA4 /* Project object */;
|
||||
@@ -88,41 +92,6 @@
|
||||
remoteGlobalIDString = 56553C181C3E906C00522B5C;
|
||||
remoteInfo = GRDBOSXCrashTests;
|
||||
};
|
||||
56B036421E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 560FC54D1CB003810014AA8E;
|
||||
remoteInfo = GRDBCipherOSX;
|
||||
};
|
||||
56B036441E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 560FC5B01CB00B880014AA8E;
|
||||
remoteInfo = GRDBCipherOSXTests;
|
||||
};
|
||||
56B036461E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 5671566C1CB16729007DC145;
|
||||
remoteInfo = GRDBCipherOSXEncryptedTests;
|
||||
};
|
||||
56B036481E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = F3BA805A1CFB2BB2003DC1BA;
|
||||
remoteInfo = GRDBCustomSQLiteOSX;
|
||||
};
|
||||
56B0364A1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = F3BA809B1CFB2F6F003DC1BA;
|
||||
remoteInfo = GRDBCustomSQLiteOSXTests;
|
||||
};
|
||||
56B0364C1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
@@ -137,41 +106,6 @@
|
||||
remoteGlobalIDString = 56E5D7D31B4D3FEE00430942;
|
||||
remoteInfo = GRDBiOSTests;
|
||||
};
|
||||
56B036501E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56AFCA231CB1A8BB00F48B96;
|
||||
remoteInfo = GRDBCipheriOS;
|
||||
};
|
||||
56B036521E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56AFCA7F1CB1AA9900F48B96;
|
||||
remoteInfo = GRDBCipheriOSTests;
|
||||
};
|
||||
56B036541E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56AFCAD71CB1ABC800F48B96;
|
||||
remoteInfo = GRDBCipheriOSEncryptedTests;
|
||||
};
|
||||
56B036561E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = F3BA7FFE1CFB25E4003DC1BA;
|
||||
remoteInfo = GRDBCustomSQLiteiOS;
|
||||
};
|
||||
56B036581E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = F3BA80411CFB2AD7003DC1BA;
|
||||
remoteInfo = GRDBCustomSQLiteiOSTests;
|
||||
};
|
||||
56B0365A1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
@@ -243,7 +177,6 @@
|
||||
/* End PBXCopyFilesBuildPhase section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
5657C36D1E926B05008402E8 /* libsqlite3.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libsqlite3.tbd; path = Platforms/WatchOS.platform/Developer/SDKs/WatchOS3.2.sdk/usr/lib/libsqlite3.tbd; sourceTree = DEVELOPER_DIR; };
|
||||
568E5FBF1E926430002582E0 /* GRDBDemoWatchOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBDemoWatchOS.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
568E5FC21E926430002582E0 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Interface.storyboard; sourceTree = "<group>"; };
|
||||
568E5FC41E926430002582E0 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
|
||||
@@ -259,12 +192,10 @@
|
||||
56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
|
||||
56B036101E8D9EBE003B6DA4 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
|
||||
56B036121E8D9EBE003B6DA4 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
56B036191E8D9F38003B6DA4 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = "<group>"; };
|
||||
56B0361A1E8D9F38003B6DA4 /* Person.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Person.swift; sourceTree = "<group>"; };
|
||||
56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DemoViewController.swift; sourceTree = "<group>"; };
|
||||
56B0361F1E8D9F4C003B6DA4 /* PersonEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonEditionViewController.swift; sourceTree = "<group>"; };
|
||||
56B036201E8D9F4C003B6DA4 /* PersonsViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonsViewController.swift; sourceTree = "<group>"; };
|
||||
56B036211E8D9F4C003B6DA4 /* SimplePersonsViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SimplePersonsViewController.swift; sourceTree = "<group>"; };
|
||||
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
|
||||
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>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
@@ -273,7 +204,6 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
5657C36E1E926B05008402E8 /* libsqlite3.tbd in Frameworks */,
|
||||
568E5FE41E926547002582E0 /* GRDB.framework in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
@@ -289,14 +219,6 @@
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
5657C36C1E926B05008402E8 /* Frameworks */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5657C36D1E926B05008402E8 /* libsqlite3.tbd */,
|
||||
);
|
||||
name = Frameworks;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
568E5FC01E926430002582E0 /* GRDBDemoWatchOS */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -326,7 +248,6 @@
|
||||
568E5FC01E926430002582E0 /* GRDBDemoWatchOS */,
|
||||
568E5FCF1E926430002582E0 /* GRDBDemoWatchOS Extension */,
|
||||
56B036041E8D9EBE003B6DA4 /* Products */,
|
||||
5657C36C1E926B05008402E8 /* Frameworks */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
@@ -344,9 +265,10 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */,
|
||||
56B036191E8D9F38003B6DA4 /* Database.swift */,
|
||||
56B0361A1E8D9F38003B6DA4 /* Person.swift */,
|
||||
56B0361D1E8D9F3D003B6DA4 /* Controllers */,
|
||||
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */,
|
||||
56B0361A1E8D9F38003B6DA4 /* Player.swift */,
|
||||
56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */,
|
||||
56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */,
|
||||
56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */,
|
||||
56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */,
|
||||
56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */,
|
||||
@@ -355,36 +277,16 @@
|
||||
path = GRDBDemoiOS;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56B0361D1E8D9F3D003B6DA4 /* Controllers */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */,
|
||||
56B0361F1E8D9F4C003B6DA4 /* PersonEditionViewController.swift */,
|
||||
56B036201E8D9F4C003B6DA4 /* PersonsViewController.swift */,
|
||||
56B036211E8D9F4C003B6DA4 /* SimplePersonsViewController.swift */,
|
||||
);
|
||||
name = Controllers;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56B036271E8D9F79003B6DA4 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56B0363B1E8D9F79003B6DA4 /* GRDB.framework */,
|
||||
56B0363D1E8D9F79003B6DA4 /* GRDBOSXTests.xctest */,
|
||||
56B0363F1E8D9F79003B6DA4 /* GRDBOSXPerformanceTests.xctest */,
|
||||
563BD2F11F8364C1006A5390 /* GRDBOSXPerformanceComparisonTests.xctest */,
|
||||
56B036411E8D9F79003B6DA4 /* GRDBOSXCrashTests.xctest */,
|
||||
56B036431E8D9F79003B6DA4 /* GRDBCipher.framework */,
|
||||
56B036451E8D9F79003B6DA4 /* GRDBCipherOSXTests.xctest */,
|
||||
56B036471E8D9F79003B6DA4 /* GRDBCipherOSXEncryptedTests.xctest */,
|
||||
56B036491E8D9F79003B6DA4 /* GRDBCustomSQLite.framework */,
|
||||
56B0364B1E8D9F79003B6DA4 /* GRDBCustomSQLiteOSXTests.xctest */,
|
||||
56B0364D1E8D9F79003B6DA4 /* GRDB.framework */,
|
||||
56B0364F1E8D9F79003B6DA4 /* GRDBiOSTests.xctest */,
|
||||
56B036511E8D9F79003B6DA4 /* GRDBCipher.framework */,
|
||||
56B036531E8D9F79003B6DA4 /* GRDBCipheriOSTests.xctest */,
|
||||
56B036551E8D9F79003B6DA4 /* GRDBCipheriOSEncryptedTests.xctest */,
|
||||
56B036571E8D9F79003B6DA4 /* GRDBCustomSQLite.framework */,
|
||||
56B036591E8D9F79003B6DA4 /* GRDBCustomSQLiteiOSTests.xctest */,
|
||||
56B0365B1E8D9F79003B6DA4 /* GRDB.framework */,
|
||||
);
|
||||
name = Products;
|
||||
@@ -459,7 +361,7 @@
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastSwiftUpdateCheck = 0830;
|
||||
LastUpgradeCheck = 0830;
|
||||
LastUpgradeCheck = 1020;
|
||||
ORGANIZATIONNAME = "Gwendal Roué";
|
||||
TargetAttributes = {
|
||||
568E5FBE1E926430002582E0 = {
|
||||
@@ -470,18 +372,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,
|
||||
@@ -506,6 +410,13 @@
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXReferenceProxy section */
|
||||
563BD2F11F8364C1006A5390 /* GRDBOSXPerformanceComparisonTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBOSXPerformanceComparisonTests.xctest;
|
||||
remoteRef = 563BD2F01F8364C1006A5390 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B0363B1E8D9F79003B6DA4 /* GRDB.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
@@ -534,41 +445,6 @@
|
||||
remoteRef = 56B036401E8D9F79003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B036431E8D9F79003B6DA4 /* GRDBCipher.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDBCipher.framework;
|
||||
remoteRef = 56B036421E8D9F79003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B036451E8D9F79003B6DA4 /* GRDBCipherOSXTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBCipherOSXTests.xctest;
|
||||
remoteRef = 56B036441E8D9F79003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B036471E8D9F79003B6DA4 /* GRDBCipherOSXEncryptedTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBCipherOSXEncryptedTests.xctest;
|
||||
remoteRef = 56B036461E8D9F79003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B036491E8D9F79003B6DA4 /* GRDBCustomSQLite.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDBCustomSQLite.framework;
|
||||
remoteRef = 56B036481E8D9F79003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B0364B1E8D9F79003B6DA4 /* GRDBCustomSQLiteOSXTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBCustomSQLiteOSXTests.xctest;
|
||||
remoteRef = 56B0364A1E8D9F79003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B0364D1E8D9F79003B6DA4 /* GRDB.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
@@ -583,41 +459,6 @@
|
||||
remoteRef = 56B0364E1E8D9F79003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B036511E8D9F79003B6DA4 /* GRDBCipher.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDBCipher.framework;
|
||||
remoteRef = 56B036501E8D9F79003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B036531E8D9F79003B6DA4 /* GRDBCipheriOSTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBCipheriOSTests.xctest;
|
||||
remoteRef = 56B036521E8D9F79003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B036551E8D9F79003B6DA4 /* GRDBCipheriOSEncryptedTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBCipheriOSEncryptedTests.xctest;
|
||||
remoteRef = 56B036541E8D9F79003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B036571E8D9F79003B6DA4 /* GRDBCustomSQLite.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDBCustomSQLite.framework;
|
||||
remoteRef = 56B036561E8D9F79003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B036591E8D9F79003B6DA4 /* GRDBCustomSQLiteiOSTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBCustomSQLiteiOSTests.xctest;
|
||||
remoteRef = 56B036581E8D9F79003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B0365B1E8D9F79003B6DA4 /* GRDB.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
@@ -671,13 +512,11 @@
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
56B0361C1E8D9F38003B6DA4 /* Person.swift in Sources */,
|
||||
56B0361B1E8D9F38003B6DA4 /* Database.swift in Sources */,
|
||||
56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */,
|
||||
56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */,
|
||||
56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */,
|
||||
56B036241E8D9F4C003B6DA4 /* PersonsViewController.swift in Sources */,
|
||||
56B036231E8D9F4C003B6DA4 /* PersonEditionViewController.swift in Sources */,
|
||||
56B036251E8D9F4C003B6DA4 /* SimplePersonsViewController.swift in Sources */,
|
||||
56B036221E8D9F4C003B6DA4 /* DemoViewController.swift in Sources */,
|
||||
56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */,
|
||||
56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -748,14 +587,14 @@
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_COMPLICATION_NAME = Complication;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
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;
|
||||
SWIFT_VERSION = 3.0;
|
||||
TARGETED_DEVICE_FAMILY = 4;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 3.2;
|
||||
};
|
||||
@@ -765,14 +604,14 @@
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_COMPLICATION_NAME = Complication;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
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;
|
||||
SWIFT_VERSION = 3.0;
|
||||
TARGETED_DEVICE_FAMILY = 4;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 3.2;
|
||||
};
|
||||
@@ -783,14 +622,14 @@
|
||||
buildSettings = {
|
||||
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
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;
|
||||
SWIFT_VERSION = 3.0;
|
||||
TARGETED_DEVICE_FAMILY = 4;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 3.2;
|
||||
};
|
||||
@@ -801,14 +640,14 @@
|
||||
buildSettings = {
|
||||
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
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;
|
||||
SWIFT_VERSION = 3.0;
|
||||
TARGETED_DEVICE_FAMILY = 4;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 3.2;
|
||||
};
|
||||
@@ -818,21 +657,30 @@
|
||||
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";
|
||||
CLANG_CXX_LIBRARY = "libc++";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
||||
CLANG_WARN_EMPTY_BODY = YES;
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
@@ -855,12 +703,12 @@
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 10.3;
|
||||
MTL_ENABLE_DEBUG_INFO = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 4.2;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -868,21 +716,30 @@
|
||||
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";
|
||||
CLANG_CXX_LIBRARY = "libc++";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
||||
CLANG_WARN_EMPTY_BODY = YES;
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
@@ -899,10 +756,10 @@
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 10.3;
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
|
||||
SWIFT_VERSION = 4.2;
|
||||
VALIDATE_PRODUCT = YES;
|
||||
};
|
||||
name = Release;
|
||||
@@ -912,12 +769,12 @@
|
||||
buildSettings = {
|
||||
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
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)";
|
||||
SWIFT_VERSION = 3.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -926,12 +783,12 @@
|
||||
buildSettings = {
|
||||
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
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)";
|
||||
SWIFT_VERSION = 3.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
</Workspace>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>IDEDidComputeMac32BitWarning</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0730"
|
||||
LastUpgradeVersion = "1030"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0830"
|
||||
LastUpgradeVersion = "1030"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import GRDB
|
||||
|
||||
/// A type responsible for initializing the application database.
|
||||
///
|
||||
/// See AppDelegate.setupDatabase()
|
||||
struct AppDatabase {
|
||||
|
||||
/// Creates a fully initialized database at path
|
||||
static func openDatabase(atPath path: String) throws -> DatabaseQueue {
|
||||
// Connect to the database
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
let dbQueue = try DatabaseQueue(path: path)
|
||||
|
||||
// Define the database schema
|
||||
try migrator.migrate(dbQueue)
|
||||
|
||||
return dbQueue
|
||||
}
|
||||
|
||||
/// The DatabaseMigrator that defines the database schema.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#migrations
|
||||
static var migrator: DatabaseMigrator {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
migrator.registerMigration("createPlayer") { db in
|
||||
// Create a table
|
||||
// See https://github.com/groue/GRDB.swift#create-tables
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
|
||||
// Sort player names in a localized case insensitive fashion by default
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#unicode
|
||||
t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare)
|
||||
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
}
|
||||
|
||||
migrator.registerMigration("fixtures") { db in
|
||||
// Populate the players table with random data
|
||||
for _ in 0..<8 {
|
||||
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
|
||||
try player.insert(db)
|
||||
}
|
||||
}
|
||||
|
||||
// // Migrations for future application versions will be inserted here:
|
||||
// migrator.registerMigration(...) { db in
|
||||
// ...
|
||||
// }
|
||||
|
||||
return migrator
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,26 @@
|
||||
import UIKit
|
||||
import GRDB
|
||||
|
||||
// The shared database queue
|
||||
var dbQueue: DatabaseQueue!
|
||||
|
||||
@UIApplicationMain
|
||||
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
|
||||
}
|
||||
|
||||
private func setupDatabase(_ application: UIApplication) throws {
|
||||
let databaseURL = try FileManager.default
|
||||
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
.appendingPathComponent("db.sqlite")
|
||||
dbQueue = try AppDatabase.openDatabase(atPath: databaseURL.path)
|
||||
|
||||
// Be a nice iOS citizen, and don't consume too much memory
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#memory-management
|
||||
dbQueue.setupMemoryManagement(in: application)
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,5 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"idiom" : "iphone",
|
||||
"size" : "20x20",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "iphone",
|
||||
"size" : "20x20",
|
||||
"scale" : "3x"
|
||||
},
|
||||
{
|
||||
"idiom" : "iphone",
|
||||
"size" : "29x29",
|
||||
@@ -42,16 +32,6 @@
|
||||
"filename" : "Icon-60@3x.png",
|
||||
"scale" : "3x"
|
||||
},
|
||||
{
|
||||
"idiom" : "ipad",
|
||||
"size" : "20x20",
|
||||
"scale" : "1x"
|
||||
},
|
||||
{
|
||||
"idiom" : "ipad",
|
||||
"size" : "20x20",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "ipad",
|
||||
"size" : "29x29",
|
||||
|
||||
@@ -1,70 +1,18 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11129.15" systemVersion="15F34" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14313.18" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
|
||||
<device id="retina4_7" orientation="portrait">
|
||||
<adaptation id="fullscreen"/>
|
||||
</device>
|
||||
<dependencies>
|
||||
<deployment identifier="iOS"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11103.10"/>
|
||||
<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>
|
||||
<!--Hall Of Fame-->
|
||||
<scene sceneID="8jG-C9-QsI">
|
||||
<objects>
|
||||
<tableViewController id="cyv-nk-Plb" customClass="SimplePersonsViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="oON-zg-8kO">
|
||||
<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"/>
|
||||
<prototypes>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" reuseIdentifier="Person" textLabel="XIE-DF-pSO" detailTextLabel="vyz-CH-eMb" style="IBUITableViewCellStyleValue1" id="V5t-oJ-KD9">
|
||||
<frame key="frameInset" minY="92" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="V5t-oJ-KD9" id="Coo-th-ywF">
|
||||
<frame key="frameInset" width="342" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="XIE-DF-pSO">
|
||||
<frame key="frameInset" minX="15" minY="12" width="31.5" height="19.5"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<color key="textColor" white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Detail" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="vyz-CH-eMb">
|
||||
<frame key="frameInset" minX="298.5" minY="12" width="41.5" height="19.5"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<color key="textColor" red="0.55686274509803924" green="0.55686274509803924" blue="0.57647058823529407" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
</subviews>
|
||||
</tableViewCellContentView>
|
||||
<connections>
|
||||
<segue destination="iNr-Oe-muq" kind="show" identifier="EditPerson" id="czF-1h-sYn"/>
|
||||
</connections>
|
||||
</tableViewCell>
|
||||
</prototypes>
|
||||
<connections>
|
||||
<outlet property="dataSource" destination="cyv-nk-Plb" id="uBb-Bn-Lhg"/>
|
||||
<outlet property="delegate" destination="cyv-nk-Plb" id="nLb-Ak-ZXS"/>
|
||||
</connections>
|
||||
</tableView>
|
||||
<toolbarItems/>
|
||||
<navigationItem key="navigationItem" title="Hall Of Fame" id="YLU-iz-PGw"/>
|
||||
<simulatedToolbarMetrics key="simulatedBottomBarMetrics"/>
|
||||
<connections>
|
||||
<segue destination="ein-Sr-i8w" kind="presentation" identifier="NewPerson" id="zii-bJ-cOA"/>
|
||||
</connections>
|
||||
</tableViewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="PrM-ex-2C8" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="630" y="640"/>
|
||||
</scene>
|
||||
<!--Person Edition View Controller-->
|
||||
<!--Player Edition View Controller-->
|
||||
<scene sceneID="Juk-Ad-tZ2">
|
||||
<objects>
|
||||
<tableViewController id="iNr-Oe-muq" customClass="PersonEditionViewController" 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">
|
||||
<tableViewController id="iNr-Oe-muq" customClass="PlayerEditionViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" dataMode="static" style="plain" separatorStyle="none" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="vlV-lc-eQA">
|
||||
<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"/>
|
||||
@@ -72,13 +20,14 @@
|
||||
<tableViewSection id="Nzq-eO-jT3">
|
||||
<cells>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="2gb-gB-918">
|
||||
<rect key="frame" x="0.0" y="64" width="375" height="44"/>
|
||||
<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">
|
||||
<frame key="frameInset" width="375" height="44"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Name" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="m5m-Zs-j0z">
|
||||
<rect key="frame" x="16" y="12" width="343" height="20"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<textInputTraits key="textInputTraits" autocapitalizationType="words" autocorrectionType="no" spellCheckingType="no" returnKeyType="next"/>
|
||||
<connections>
|
||||
@@ -87,20 +36,21 @@
|
||||
</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>
|
||||
</tableViewCellContentView>
|
||||
</tableViewCell>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="vp3-Ft-Gth">
|
||||
<rect key="frame" x="0.0" y="108" width="375" height="44"/>
|
||||
<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">
|
||||
<frame key="frameInset" width="375" height="44"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Score" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="rZ9-Fa-cyr">
|
||||
<rect key="frame" x="16" y="12" width="343" height="20"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<textInputTraits key="textInputTraits" autocorrectionType="no" spellCheckingType="no" keyboardType="numberPad" returnKeyType="done"/>
|
||||
</textField>
|
||||
@@ -108,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>
|
||||
@@ -124,12 +74,12 @@
|
||||
<navigationItem key="navigationItem" id="U4g-xG-W8b">
|
||||
<barButtonItem key="leftBarButtonItem" systemItem="cancel" id="VIN-Hi-Twt">
|
||||
<connections>
|
||||
<segue destination="lTz-K0-aRY" kind="unwind" unwindAction="cancelPersonEdition:" id="fOs-ol-qJL"/>
|
||||
<segue destination="lTz-K0-aRY" kind="unwind" unwindAction="cancelPlayerEdition:" id="fOs-ol-qJL"/>
|
||||
</connections>
|
||||
</barButtonItem>
|
||||
<barButtonItem key="rightBarButtonItem" systemItem="done" id="2um-u5-BhV">
|
||||
<barButtonItem key="rightBarButtonItem" style="done" systemItem="done" id="2um-u5-BhV">
|
||||
<connections>
|
||||
<segue destination="lTz-K0-aRY" kind="unwind" identifier="" unwindAction="commitPersonEdition:" id="Y1E-dI-wcl"/>
|
||||
<segue destination="lTz-K0-aRY" kind="unwind" identifier="Commit" unwindAction="commitPlayerEdition:" id="Y1E-dI-wcl"/>
|
||||
</connections>
|
||||
</barButtonItem>
|
||||
</navigationItem>
|
||||
@@ -146,79 +96,14 @@
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="fNC-Ls-uRw" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
<exit id="lTz-K0-aRY" userLabel="Exit" sceneMemberID="exit"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="1450" y="1435"/>
|
||||
</scene>
|
||||
<!--GRDB Demo-->
|
||||
<scene sceneID="XjB-aQ-v94">
|
||||
<objects>
|
||||
<tableViewController id="9kw-c5-KTk" customClass="DemoViewController" 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="f4Y-o2-7VW">
|
||||
<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"/>
|
||||
<sections>
|
||||
<tableViewSection id="dCg-qU-h2X">
|
||||
<cells>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" textLabel="clL-nG-zPX" style="IBUITableViewCellStyleDefault" id="kJB-sX-YAb">
|
||||
<rect key="frame" x="0.0" y="64" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="kJB-sX-YAb" id="f5l-ob-3DG">
|
||||
<frame key="frameInset" width="342" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Simple TableView" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="clL-nG-zPX">
|
||||
<frame key="frameInset" minX="15" width="325" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<color key="textColor" white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
</subviews>
|
||||
</tableViewCellContentView>
|
||||
<connections>
|
||||
<segue destination="cyv-nk-Plb" kind="show" id="Bgq-9t-jRc"/>
|
||||
</connections>
|
||||
</tableViewCell>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" textLabel="I78-c5-0kp" style="IBUITableViewCellStyleDefault" id="q4C-mT-5mi">
|
||||
<rect key="frame" x="0.0" y="108" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="q4C-mT-5mi" id="2Cu-K1-hiz">
|
||||
<frame key="frameInset" width="342" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="FetchedRecordsController" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="I78-c5-0kp">
|
||||
<frame key="frameInset" minX="15" width="325" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<color key="textColor" white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
</subviews>
|
||||
</tableViewCellContentView>
|
||||
<connections>
|
||||
<segue destination="PJp-Eq-ZjA" kind="show" id="1fk-ZR-6XN"/>
|
||||
</connections>
|
||||
</tableViewCell>
|
||||
</cells>
|
||||
</tableViewSection>
|
||||
</sections>
|
||||
<connections>
|
||||
<outlet property="dataSource" destination="9kw-c5-KTk" id="IK7-Os-Odc"/>
|
||||
<outlet property="delegate" destination="9kw-c5-KTk" id="U7E-yB-s8d"/>
|
||||
</connections>
|
||||
</tableView>
|
||||
<navigationItem key="navigationItem" title="GRDB Demo" id="z0z-02-Ucy"/>
|
||||
</tableViewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="OhY-4B-BcJ" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="-190" y="1435"/>
|
||||
<point key="canvasLocation" x="1134" y="2891"/>
|
||||
</scene>
|
||||
<!--Navigation Controller-->
|
||||
<scene sceneID="2KX-IU-Z5Q">
|
||||
<objects>
|
||||
<navigationController id="ein-Sr-i8w" sceneMemberID="viewController">
|
||||
<navigationBar key="navigationBar" contentMode="scaleToFill" id="zIT-dB-Mfo">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
|
||||
<rect key="frame" x="0.0" y="20" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
</navigationBar>
|
||||
<connections>
|
||||
@@ -227,49 +112,49 @@
|
||||
</navigationController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="kNr-vk-I5l" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="630" y="1435"/>
|
||||
<point key="canvasLocation" x="1134" y="2071"/>
|
||||
</scene>
|
||||
<!--Navigation Controller-->
|
||||
<scene sceneID="N1X-4j-Re4">
|
||||
<objects>
|
||||
<navigationController id="UAh-8N-CM8" sceneMemberID="viewController">
|
||||
<navigationBar key="navigationBar" contentMode="scaleToFill" id="U7d-1C-GnL">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
|
||||
<rect key="frame" x="0.0" y="20" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
</navigationBar>
|
||||
<connections>
|
||||
<segue destination="9kw-c5-KTk" kind="relationship" relationship="rootViewController" id="qDW-qI-Hyg"/>
|
||||
<segue destination="PJp-Eq-ZjA" kind="relationship" relationship="rootViewController" id="klT-ZP-gtX"/>
|
||||
</connections>
|
||||
</navigationController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="sVt-e9-ghQ" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="-1006" y="1435"/>
|
||||
<point key="canvasLocation" x="-459" y="2071"/>
|
||||
</scene>
|
||||
<!--Hall Of Fame-->
|
||||
<scene sceneID="9su-ms-vdJ">
|
||||
<objects>
|
||||
<tableViewController id="PJp-Eq-ZjA" customClass="PersonsViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableViewController id="PJp-Eq-ZjA" customClass="PlayersViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="tX0-ON-WSI">
|
||||
<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"/>
|
||||
<prototypes>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" reuseIdentifier="Person" textLabel="G8y-VE-YRu" detailTextLabel="NNc-J4-xiE" style="IBUITableViewCellStyleValue1" id="bFj-Hd-fwd">
|
||||
<frame key="frameInset" minY="92" width="375" height="44"/>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" reuseIdentifier="Player" textLabel="G8y-VE-YRu" detailTextLabel="NNc-J4-xiE" style="IBUITableViewCellStyleValue1" id="bFj-Hd-fwd">
|
||||
<rect key="frame" x="0.0" y="28" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="bFj-Hd-fwd" id="kDf-TZ-xhb">
|
||||
<frame key="frameInset" width="342" height="43.5"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="341" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="G8y-VE-YRu">
|
||||
<frame key="frameInset" minX="15" minY="12" width="31.5" height="19.5"/>
|
||||
<rect key="frame" x="16" y="12" width="31.5" height="19.5"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<color key="textColor" white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
|
||||
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Detail" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="NNc-J4-xiE">
|
||||
<frame key="frameInset" minX="298.5" minY="12" width="41.5" height="19.5"/>
|
||||
<rect key="frame" x="298.5" y="12" width="41.5" height="19.5"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<color key="textColor" red="0.5568627451" green="0.5568627451" blue="0.57647058819999997" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
@@ -278,7 +163,7 @@
|
||||
</subviews>
|
||||
</tableViewCellContentView>
|
||||
<connections>
|
||||
<segue destination="iNr-Oe-muq" kind="show" identifier="EditPerson" id="Lgu-Yd-HSy"/>
|
||||
<segue destination="iNr-Oe-muq" kind="show" identifier="Edit" id="Lgu-Yd-HSy"/>
|
||||
</connections>
|
||||
</tableViewCell>
|
||||
</prototypes>
|
||||
@@ -291,20 +176,23 @@
|
||||
<barButtonItem title="Item" id="hMF-Rv-dAe"/>
|
||||
</toolbarItems>
|
||||
<navigationItem key="navigationItem" title="Hall Of Fame" id="QIv-M6-kT1">
|
||||
<barButtonItem key="rightBarButtonItem" systemItem="add" id="2bK-Fl-55Q"/>
|
||||
<barButtonItem key="leftBarButtonItem" systemItem="add" id="2bK-Fl-55Q">
|
||||
<connections>
|
||||
<segue destination="ein-Sr-i8w" kind="presentation" identifier="New" id="ehP-ZN-Nt4"/>
|
||||
</connections>
|
||||
</barButtonItem>
|
||||
</navigationItem>
|
||||
<simulatedToolbarMetrics key="simulatedBottomBarMetrics"/>
|
||||
<connections>
|
||||
<segue destination="ein-Sr-i8w" kind="presentation" identifier="NewPerson" id="7PC-xN-zD4"/>
|
||||
<outlet property="newPlayerButtonItem" destination="2bK-Fl-55Q" id="O9m-8s-oRL"/>
|
||||
</connections>
|
||||
</tableViewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="af5-Qo-AkD" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="630" y="2254"/>
|
||||
<point key="canvasLocation" x="348" y="2071"/>
|
||||
</scene>
|
||||
</scenes>
|
||||
<inferredMetricsTieBreakers>
|
||||
<segue reference="7PC-xN-zD4"/>
|
||||
<segue reference="czF-1h-sYn"/>
|
||||
<segue reference="Lgu-Yd-HSy"/>
|
||||
</inferredMetricsTieBreakers>
|
||||
</document>
|
||||
@@ -1,56 +0,0 @@
|
||||
import GRDB
|
||||
import UIKit
|
||||
|
||||
// The shared database queue
|
||||
var dbQueue: DatabaseQueue!
|
||||
|
||||
func setupDatabase(_ application: UIApplication) throws {
|
||||
|
||||
// Connect to the database
|
||||
// See https://github.com/groue/GRDB.swift/#database-connections
|
||||
|
||||
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString
|
||||
let databasePath = documentsPath.appendingPathComponent("db.sqlite")
|
||||
dbQueue = try DatabaseQueue(path: databasePath)
|
||||
|
||||
|
||||
// Be a nice iOS citizen, and don't consume too much memory
|
||||
// See https://github.com/groue/GRDB.swift/#memory-management
|
||||
|
||||
dbQueue.setupMemoryManagement(in: application)
|
||||
|
||||
|
||||
// Use DatabaseMigrator to setup the database
|
||||
// See https://github.com/groue/GRDB.swift/#migrations
|
||||
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
migrator.registerMigration("createPersons") { db in
|
||||
|
||||
// Create a table
|
||||
// See https://github.com/groue/GRDB.swift#create-tables
|
||||
|
||||
try db.create(table: "persons") { t in
|
||||
// An integer primary key auto-generates unique IDs
|
||||
t.column("id", .integer).primaryKey()
|
||||
|
||||
// Sort person names in a localized case insensitive fashion by default
|
||||
// See https://github.com/groue/GRDB.swift/#unicode
|
||||
t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare)
|
||||
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
|
||||
// Populate the persons table with random data
|
||||
for _ in 0..<8 {
|
||||
try Person(name: Person.randomName(), score: Person.randomScore()).insert(db)
|
||||
}
|
||||
}
|
||||
|
||||
// // Migrations for future application versions will be inserted here:
|
||||
// migrator.registerMigration(...) { db in
|
||||
// ...
|
||||
// }
|
||||
|
||||
try migrator.migrate(dbQueue)
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import UIKit
|
||||
|
||||
class DemoViewController: UITableViewController {
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(true)
|
||||
navigationController?.isToolbarHidden = true
|
||||
navigationItem.backBarButtonItem = UIBarButtonItem(title: "Demo", style: .plain, target: nil, action: nil)
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,6 @@
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>en</string>
|
||||
<key>CFBundleDisplayName</key>
|
||||
<string>GRDB Demo</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
@@ -18,6 +16,8 @@
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>LSRequiresIPhoneOS</key>
|
||||
@@ -33,6 +33,8 @@
|
||||
<key>UISupportedInterfaceOrientations</key>
|
||||
<array>
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,49 +0,0 @@
|
||||
import GRDB
|
||||
|
||||
class Person: Record {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
var score: Int
|
||||
|
||||
init(name: String, score: Int) {
|
||||
self.name = name
|
||||
self.score = score
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: Record overrides
|
||||
|
||||
override class var databaseTableName: String {
|
||||
return "persons"
|
||||
}
|
||||
|
||||
required init(row: Row) {
|
||||
id = row.value(named: "id")
|
||||
name = row.value(named: "name")
|
||||
score = row.value(named: "score")
|
||||
super.init(row: row)
|
||||
}
|
||||
|
||||
override func encode(to container: inout PersistenceContainer) {
|
||||
container["id"] = id
|
||||
container["name"] = name
|
||||
container["score"] = score
|
||||
}
|
||||
|
||||
override func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
}
|
||||
|
||||
// MARK: Random
|
||||
|
||||
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é"]
|
||||
|
||||
class func randomName() -> String {
|
||||
return names[Int(arc4random_uniform(UInt32(names.count)))]
|
||||
}
|
||||
|
||||
class func randomScore() -> Int {
|
||||
return 10 * Int(arc4random_uniform(101))
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,234 +0,0 @@
|
||||
import UIKit
|
||||
import GRDB
|
||||
|
||||
class PersonsViewController: UITableViewController {
|
||||
var personsController: FetchedRecordsController<Person>!
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
|
||||
navigationItem.rightBarButtonItems = [
|
||||
UIBarButtonItem(barButtonSystemItem: .add, target: self, action: .addPerson),
|
||||
editButtonItem
|
||||
]
|
||||
|
||||
personsController = try! FetchedRecordsController(dbQueue, request: personsSortedByScore)
|
||||
personsController.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! personsController.performFetch()
|
||||
|
||||
configureToolbar()
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
navigationController?.isToolbarHidden = false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Navigation
|
||||
|
||||
extension PersonsViewController : PersonEditionViewControllerDelegate {
|
||||
|
||||
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
|
||||
if segue.identifier == "EditPerson" {
|
||||
let person = personsController.record(at: tableView.indexPathForSelectedRow!)
|
||||
let controller = segue.destination as! PersonEditionViewController
|
||||
controller.title = person.name
|
||||
controller.person = person
|
||||
controller.delegate = self // we will save person when back button is tapped
|
||||
controller.cancelButtonHidden = true
|
||||
controller.commitButtonHidden = true
|
||||
}
|
||||
else if segue.identifier == "NewPerson" {
|
||||
setEditing(false, animated: true)
|
||||
let navigationController = segue.destination as! UINavigationController
|
||||
let controller = navigationController.viewControllers.first as! PersonEditionViewController
|
||||
controller.title = "New Person"
|
||||
controller.person = Person(name: "", score: 0)
|
||||
}
|
||||
}
|
||||
|
||||
@IBAction func addPerson(_ sender: AnyObject?) {
|
||||
performSegue(withIdentifier: "NewPerson", sender: sender)
|
||||
}
|
||||
|
||||
@IBAction func cancelPersonEdition(_ segue: UIStoryboardSegue) {
|
||||
// Person creation: cancel button was tapped
|
||||
}
|
||||
|
||||
@IBAction func commitPersonEdition(_ segue: UIStoryboardSegue) {
|
||||
// Person creation: commit button was tapped
|
||||
let controller = segue.source as! PersonEditionViewController
|
||||
controller.applyChanges()
|
||||
let person = controller.person!
|
||||
if !person.name.isEmpty {
|
||||
try! dbQueue.inDatabase { db in
|
||||
try person.save(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func personEditionControllerDidComplete(_ controller: PersonEditionViewController) {
|
||||
// Person edition: back button was tapped
|
||||
controller.applyChanges()
|
||||
let person = controller.person!
|
||||
if !person.name.isEmpty {
|
||||
try! dbQueue.inDatabase { db in
|
||||
try person.save(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - UITableViewDataSource
|
||||
|
||||
extension PersonsViewController {
|
||||
func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
|
||||
let person = personsController.record(at: indexPath)
|
||||
cell.textLabel?.text = person.name
|
||||
cell.detailTextLabel?.text = abs(person.score) > 1 ? "\(person.score) points" : "0 point"
|
||||
}
|
||||
|
||||
override func numberOfSections(in tableView: UITableView) -> Int {
|
||||
return personsController.sections.count
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
||||
return personsController.sections[section].numberOfRecords
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
||||
let cell = tableView.dequeueReusableCell(withIdentifier: "Person", for: indexPath)
|
||||
configure(cell, at: indexPath)
|
||||
return cell
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
|
||||
// Delete the person
|
||||
let person = personsController.record(at: indexPath)
|
||||
try! dbQueue.inDatabase { db in
|
||||
_ = try person.delete(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - FetchedRecordsController Demo
|
||||
|
||||
extension PersonsViewController {
|
||||
|
||||
fileprivate func configureToolbar() {
|
||||
toolbarItems = [
|
||||
UIBarButtonItem(title: "Name ⬆︎", style: .plain, target: self, action: .sortByName),
|
||||
UIBarButtonItem(title: "Score ⬇︎", style: .plain, target: self, action: .sortByScore),
|
||||
UIBarButtonItem(title: "Randomize", style: .plain, target: self, action: .randomizeScores),
|
||||
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
|
||||
UIBarButtonItem(title: "💣", style: .plain, target: self, action: .stressTest)
|
||||
]
|
||||
}
|
||||
|
||||
@IBAction func sortByName() {
|
||||
setEditing(false, animated: true)
|
||||
try! personsController.setRequest(personsSortedByName)
|
||||
}
|
||||
|
||||
@IBAction func sortByScore() {
|
||||
setEditing(false, animated: true)
|
||||
try! personsController.setRequest(personsSortedByScore)
|
||||
}
|
||||
|
||||
@IBAction func randomizeScores() {
|
||||
setEditing(false, animated: true)
|
||||
|
||||
try! dbQueue.inTransaction { db in
|
||||
for person in try Person.fetchAll(db) {
|
||||
person.score = Person.randomScore()
|
||||
try person.update(db)
|
||||
}
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
|
||||
@IBAction func stressTest() {
|
||||
setEditing(false, animated: true)
|
||||
|
||||
for _ in 0..<50 {
|
||||
DispatchQueue.global().async {
|
||||
try! dbQueue.inTransaction { db in
|
||||
if try Person.fetchCount(db) == 0 {
|
||||
// Insert persons
|
||||
for _ in 0..<8 {
|
||||
try Person(name: Person.randomName(), score: Person.randomScore()).insert(db)
|
||||
}
|
||||
} else {
|
||||
// Insert a person
|
||||
if arc4random_uniform(2) == 0 {
|
||||
let person = Person(name: Person.randomName(), score: Person.randomScore())
|
||||
try person.insert(db)
|
||||
}
|
||||
// Delete a person
|
||||
if arc4random_uniform(2) == 0 {
|
||||
if let person = try Person.order(sql: "RANDOM()").fetchOne(db) {
|
||||
try person.delete(db)
|
||||
}
|
||||
}
|
||||
// Update some persons
|
||||
for person in try Person.fetchAll(db) {
|
||||
if arc4random_uniform(2) == 0 {
|
||||
person.score = Person.randomScore()
|
||||
try person.update(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// https://medium.com/swift-programming/swift-selector-syntax-sugar-81c8a8b10df3
|
||||
private extension Selector {
|
||||
static let addPerson = #selector(PersonsViewController.addPerson(_:))
|
||||
static let sortByName = #selector(PersonsViewController.sortByName)
|
||||
static let sortByScore = #selector(PersonsViewController.sortByScore)
|
||||
static let randomizeScores = #selector(PersonsViewController.randomizeScores)
|
||||
static let stressTest = #selector(PersonsViewController.stressTest)
|
||||
}
|
||||
|
||||
private let personsSortedByName = Person.order(Column("name"))
|
||||
private let personsSortedByScore = Person.order(Column("score").desc, Column("name"))
|
||||
@@ -0,0 +1,63 @@
|
||||
import GRDB
|
||||
|
||||
// A plain Player struct
|
||||
struct Player {
|
||||
// Prefer Int64 for auto-incremented database ids
|
||||
var id: Int64?
|
||||
var name: String
|
||||
var score: Int
|
||||
}
|
||||
|
||||
// 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,14 +1,16 @@
|
||||
import UIKit
|
||||
|
||||
protocol PersonEditionViewControllerDelegate: class {
|
||||
func personEditionControllerDidComplete(_ controller: PersonEditionViewController)
|
||||
}
|
||||
|
||||
class PersonEditionViewController: UITableViewController {
|
||||
weak var delegate: PersonEditionViewControllerDelegate?
|
||||
var person: Person! { didSet { configureView() } }
|
||||
var cancelButtonHidden: Bool = false { didSet { configureView() } }
|
||||
var commitButtonHidden: Bool = false { didSet { configureView() } }
|
||||
class PlayerEditionViewController: UITableViewController {
|
||||
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 presentation: Presentation! { didSet { configureView() } }
|
||||
|
||||
@IBOutlet fileprivate weak var cancelBarButtonItem: UIBarButtonItem!
|
||||
@IBOutlet fileprivate weak var commitBarButtonItem: UIBarButtonItem!
|
||||
@@ -17,38 +19,29 @@ class PersonEditionViewController: UITableViewController {
|
||||
@IBOutlet fileprivate weak var scoreCell: UITableViewCell!
|
||||
@IBOutlet fileprivate weak var scoreTextField: UITextField!
|
||||
|
||||
func applyChanges() {
|
||||
if let name = nameTextField.text, !name.isEmpty {
|
||||
person.name = name
|
||||
}
|
||||
person.score = scoreTextField.text.flatMap { Int($0) } ?? 0
|
||||
}
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
configureView()
|
||||
}
|
||||
|
||||
private func configureView() {
|
||||
fileprivate func configureView() {
|
||||
guard isViewLoaded else { return }
|
||||
|
||||
nameTextField.text = person.name
|
||||
if person.score == 0 && person.id == nil {
|
||||
nameTextField.text = player.name
|
||||
|
||||
if player.score == 0 && player.id == nil {
|
||||
scoreTextField.text = ""
|
||||
} else {
|
||||
scoreTextField.text = "\(person.score)"
|
||||
scoreTextField.text = "\(player.score)"
|
||||
}
|
||||
|
||||
if cancelButtonHidden {
|
||||
navigationItem.leftBarButtonItem = nil
|
||||
} else {
|
||||
|
||||
switch presentation! {
|
||||
case .modal:
|
||||
navigationItem.leftBarButtonItem = cancelBarButtonItem
|
||||
}
|
||||
|
||||
if cancelButtonHidden {
|
||||
navigationItem.rightBarButtonItem = nil
|
||||
} else {
|
||||
navigationItem.rightBarButtonItem = commitBarButtonItem
|
||||
case .push:
|
||||
navigationItem.leftBarButtonItem = nil
|
||||
navigationItem.rightBarButtonItem = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -56,7 +49,7 @@ class PersonEditionViewController: UITableViewController {
|
||||
|
||||
// MARK: - Navigation
|
||||
|
||||
extension PersonEditionViewController {
|
||||
extension PlayerEditionViewController {
|
||||
|
||||
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
|
||||
// Force keyboard to dismiss early
|
||||
@@ -64,12 +57,23 @@ extension PersonEditionViewController {
|
||||
return true
|
||||
}
|
||||
|
||||
override func willMove(toParentViewController parent: UIViewController?) {
|
||||
super.willMove(toParentViewController: parent)
|
||||
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
|
||||
if segue.identifier == "Commit" {
|
||||
saveChanges()
|
||||
}
|
||||
}
|
||||
|
||||
override func willMove(toParent parent: UIViewController?) {
|
||||
super.willMove(toParent: parent)
|
||||
|
||||
if parent == nil {
|
||||
// Self is popping from its navigation controller
|
||||
delegate?.personEditionControllerDidComplete(self)
|
||||
switch presentation! {
|
||||
case .modal:
|
||||
break
|
||||
case .push:
|
||||
if parent == nil {
|
||||
// Self is popping from its navigation controller
|
||||
saveChanges()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,7 +82,7 @@ extension PersonEditionViewController {
|
||||
|
||||
// MARK: - Form
|
||||
|
||||
extension PersonEditionViewController: UITextFieldDelegate {
|
||||
extension PlayerEditionViewController: UITextFieldDelegate {
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
@@ -101,4 +105,17 @@ extension PersonEditionViewController: UITextFieldDelegate {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
import UIKit
|
||||
import GRDB
|
||||
|
||||
/// PlayersViewController displays the list of players.
|
||||
class PlayersViewController: UITableViewController {
|
||||
private enum PlayerOrdering {
|
||||
case byName
|
||||
case byScore
|
||||
}
|
||||
|
||||
@IBOutlet private weak var newPlayerButtonItem: UIBarButtonItem!
|
||||
private var playersController: FetchedRecordsController<Player>!
|
||||
private var playerCountObserver: TransactionObserver?
|
||||
private var playerOrdering: PlayerOrdering = .byScore {
|
||||
didSet {
|
||||
try! playersController.setRequest(playersRequest)
|
||||
configureOrderingBarButtonItem()
|
||||
}
|
||||
}
|
||||
private var playersRequest: QueryInterfaceRequest<Player> {
|
||||
switch playerOrdering {
|
||||
case .byName:
|
||||
return Player.orderedByName()
|
||||
case .byScore:
|
||||
return Player.orderedByScore()
|
||||
}
|
||||
}
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
configureToolbar()
|
||||
configureNavigationItem()
|
||||
configureTableView()
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
navigationController?.isToolbarHidden = false
|
||||
}
|
||||
|
||||
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 configureNavigationItem() {
|
||||
navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem]
|
||||
configureOrderingBarButtonItem()
|
||||
configureTitle()
|
||||
}
|
||||
|
||||
private func configureOrderingBarButtonItem() {
|
||||
switch playerOrdering {
|
||||
case .byScore:
|
||||
navigationItem.rightBarButtonItem = UIBarButtonItem(
|
||||
title: "Score ⬇︎",
|
||||
style: .plain,
|
||||
target: self, action: #selector(sortByName))
|
||||
case .byName:
|
||||
navigationItem.rightBarButtonItem = UIBarButtonItem(
|
||||
title: "Name ⬆︎",
|
||||
style: .plain,
|
||||
target: self, action: #selector(sortByScore))
|
||||
}
|
||||
}
|
||||
|
||||
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: { [unowned self] count in
|
||||
switch count {
|
||||
case 0: self.navigationItem.title = "No Player"
|
||||
case 1: self.navigationItem.title = "1 Player"
|
||||
default: self.navigationItem.title = "\(count) Players"
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private func configureTableView() {
|
||||
// Track changes in the database players
|
||||
playersController = try! FetchedRecordsController(dbQueue, request: playersRequest)
|
||||
|
||||
// Animate changes in the table view
|
||||
playersController.trackChanges(
|
||||
willChange: { [unowned self] _ in
|
||||
self.tableView.beginUpdates()
|
||||
},
|
||||
onChange: { [unowned self] (controller, record, change) in
|
||||
switch change {
|
||||
case .insertion(let indexPath):
|
||||
self.tableView.insertRows(at: [indexPath], with: .fade)
|
||||
|
||||
case .deletion(let indexPath):
|
||||
self.tableView.deleteRows(at: [indexPath], with: .fade)
|
||||
|
||||
case .update(let indexPath, _):
|
||||
if let cell = self.tableView.cellForRow(at: indexPath) {
|
||||
self.configure(cell, at: indexPath)
|
||||
}
|
||||
|
||||
case .move(let indexPath, let newIndexPath, _):
|
||||
// Actually move cells around for more demo effect :-)
|
||||
let cell = self.tableView.cellForRow(at: indexPath)
|
||||
self.tableView.moveRow(at: indexPath, to: newIndexPath)
|
||||
if let cell = cell {
|
||||
self.configure(cell, at: newIndexPath)
|
||||
}
|
||||
|
||||
// A quieter animation:
|
||||
// self.tableView.deleteRows(at: [indexPath], with: .fade)
|
||||
// self.tableView.insertRows(at: [newIndexPath], with: .fade)
|
||||
}
|
||||
},
|
||||
didChange: { [unowned self] _ in
|
||||
self.tableView.endUpdates()
|
||||
})
|
||||
|
||||
// Initial fetch
|
||||
try! playersController.performFetch()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Navigation
|
||||
|
||||
extension PlayersViewController {
|
||||
|
||||
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.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 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: UITableViewCell.EditingStyle, 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 = "-"
|
||||
} 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
|
||||
}
|
||||
|
||||
@IBAction func sortByScore() {
|
||||
setEditing(false, animated: true)
|
||||
playerOrdering = .byScore
|
||||
}
|
||||
|
||||
@IBAction func deletePlayers() {
|
||||
setEditing(false, animated: true)
|
||||
try! dbQueue.write { db in
|
||||
_ = try Player.deleteAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
@IBAction func refresh() {
|
||||
setEditing(false, animated: true)
|
||||
refreshPlayers()
|
||||
}
|
||||
|
||||
@IBAction func stressTest() {
|
||||
setEditing(false, animated: true)
|
||||
for _ in 0..<50 {
|
||||
DispatchQueue.global().async {
|
||||
self.refreshPlayers()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func refreshPlayers() {
|
||||
try! dbQueue.write { db in
|
||||
if try Player.fetchCount(db) == 0 {
|
||||
// Insert new random players
|
||||
for _ in 0..<8 {
|
||||
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
|
||||
try player.insert(db)
|
||||
}
|
||||
} else {
|
||||
// Insert a player
|
||||
if Bool.random() {
|
||||
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
|
||||
try player.insert(db)
|
||||
}
|
||||
// Delete a random player
|
||||
if Bool.random() {
|
||||
try Player.order(sql: "RANDOM()").limit(1).deleteAll(db)
|
||||
}
|
||||
// Update some players
|
||||
for var player in try Player.fetchAll(db) where Bool.random() {
|
||||
player.score = Player.randomScore()
|
||||
try player.update(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
import UIKit
|
||||
import GRDB
|
||||
|
||||
class SimplePersonsViewController: UITableViewController {
|
||||
var persons: [Person]!
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
|
||||
navigationItem.rightBarButtonItems = [
|
||||
UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(SimplePersonsViewController.addPerson(_:))),
|
||||
editButtonItem
|
||||
]
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
loadPersons()
|
||||
tableView.reloadData()
|
||||
}
|
||||
|
||||
private func loadPersons() {
|
||||
persons = try! dbQueue.inDatabase { db in
|
||||
try Person.order(Column("score").desc, Column("name")).fetchAll(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Navigation
|
||||
|
||||
extension SimplePersonsViewController : PersonEditionViewControllerDelegate {
|
||||
|
||||
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
|
||||
if segue.identifier == "EditPerson" {
|
||||
let person = persons[tableView.indexPathForSelectedRow!.row]
|
||||
let controller = segue.destination as! PersonEditionViewController
|
||||
controller.title = person.name
|
||||
controller.person = person
|
||||
controller.delegate = self // we will save person when back button is tapped
|
||||
controller.cancelButtonHidden = true
|
||||
controller.commitButtonHidden = true
|
||||
}
|
||||
else if segue.identifier == "NewPerson" {
|
||||
setEditing(false, animated: true)
|
||||
let navigationController = segue.destination as! UINavigationController
|
||||
let controller = navigationController.viewControllers.first as! PersonEditionViewController
|
||||
controller.title = "New Person"
|
||||
controller.person = Person(name: "", score: 0)
|
||||
}
|
||||
}
|
||||
|
||||
@IBAction func addPerson(_ sender: AnyObject?) {
|
||||
performSegue(withIdentifier: "NewPerson", sender: sender)
|
||||
}
|
||||
|
||||
@IBAction func cancelPersonEdition(_ segue: UIStoryboardSegue) {
|
||||
// Person creation: cancel button was tapped
|
||||
}
|
||||
|
||||
@IBAction func commitPersonEdition(_ segue: UIStoryboardSegue) {
|
||||
// Person creation: commit button was tapped
|
||||
let controller = segue.source as! PersonEditionViewController
|
||||
controller.applyChanges()
|
||||
let person = controller.person!
|
||||
if !person.name.isEmpty {
|
||||
try! dbQueue.inDatabase { db in
|
||||
try person.save(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func personEditionControllerDidComplete(_ controller: PersonEditionViewController) {
|
||||
// Person edition: back button was tapped
|
||||
controller.applyChanges()
|
||||
let person = controller.person!
|
||||
if !person.name.isEmpty {
|
||||
try! dbQueue.inDatabase { db in
|
||||
try person.save(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - UITableViewDataSource
|
||||
|
||||
extension SimplePersonsViewController {
|
||||
func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
|
||||
let person = persons[indexPath.row]
|
||||
cell.textLabel?.text = person.name
|
||||
cell.detailTextLabel?.text = abs(person.score) > 1 ? "\(person.score) points" : "0 point"
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
||||
return persons.count
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
||||
let cell = tableView.dequeueReusableCell(withIdentifier: "Person", for: indexPath)
|
||||
configure(cell, at: indexPath)
|
||||
return cell
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
|
||||
// Delete the person
|
||||
let person = persons[indexPath.row]
|
||||
try! dbQueue.inDatabase { db in
|
||||
_ = try person.delete(db)
|
||||
}
|
||||
persons.remove(at: indexPath.row)
|
||||
tableView.deleteRows(at: [indexPath], with: .fade)
|
||||
}
|
||||
}
|
||||
@@ -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 [FetchedRecordsController](../../README.md#fetchedrecordscontroller).
|
||||
|
||||
**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 title up-to-date with [ValueObservation](../../README.md#valueobservation), and animates its table view according to database changes with [FetchedRecordsController](../../README.md#fetchedrecordscontroller).
|
||||
|
||||
- [PlayerEditionViewController.swift](GRDBDemoiOS/PlayerEditionViewController.swift)
|
||||
|
||||
`PlayerEditionViewController` can create or edit a player, and save it in the database.
|
||||
@@ -3,7 +3,7 @@ Custom SQLite Builds
|
||||
|
||||
By default, GRDB uses the version of SQLite that ships with the target operating system.
|
||||
|
||||
**You can build GRDB with a custom build of [SQLite 3.19.2](https://www.sqlite.org/changes.html).**
|
||||
**You can build GRDB with a custom build of [SQLite 3.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,11 +11,11 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
|
||||
**To install GRDB with a custom SQLite build:**
|
||||
|
||||
1. Clone the GRDB.swift git repository, checkout the latest tagged version, and download SQLite sources:
|
||||
1. Clone the GRDB git repository, checkout the latest tagged version, and download SQLite sources:
|
||||
|
||||
```sh
|
||||
cd [GRDB.swift directory]
|
||||
git checkout v1.1
|
||||
cd [GRDB directory]
|
||||
git checkout v4.3.0
|
||||
git submodule update --init SQLiteCustom/src
|
||||
````
|
||||
|
||||
@@ -60,7 +60,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
# !! MODIFY THESE TO MATCH YOUR PROJECT HIERARCHY !!
|
||||
#######################################################
|
||||
|
||||
# The path to the folder containing GRDB.xcodeproj:
|
||||
# The path to the folder containing GRDBCustom.xcodeproj:
|
||||
GRDB_SOURCE_PATH="${PROJECT_DIR}/GRDB"
|
||||
|
||||
# The path to your custom "SQLiteLib-USER.xcconfig":
|
||||
@@ -107,7 +107,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
|
||||
Modify the top of `GRDBCustomSQLite-INSTALL.sh` file so that it contains correct paths.
|
||||
|
||||
5. Embed the `GRDB.xcodeproj` project in your own project.
|
||||
5. Embed the `GRDBCustom.xcodeproj` project in your own project.
|
||||
|
||||
6. Add the `GRDBCustomSQLiteOSX` or `GRDBCustomSQLiteiOS` target in the **Target Dependencies** section of the **Build Phases** tab of your **application target**.
|
||||
|
||||
|
||||
@@ -1,591 +0,0 @@
|
||||
GRDB Extension Guide
|
||||
====================
|
||||
|
||||
**Some parts of GRDB are extensible, so that you can make it better fit your needs.**
|
||||
|
||||
This guide is a step-by-step tour of GRDB extensibility, around a few topics:
|
||||
|
||||
- **[Add a value type](#add-a-value-type)**
|
||||
|
||||
You'll learn how to turn UIColor into a value type that you can store, fetch, and use in your records:
|
||||
|
||||
```swift
|
||||
let rows = try Row.fetchCursor(db, "SELECT name, color FROM clothes")
|
||||
while let row = try rows.next() {
|
||||
let name: String = row.value(named: "name")
|
||||
let color: UIColor = row.value(named: "color") // <-- New! UIColor as value
|
||||
}
|
||||
```
|
||||
|
||||
- **[Add an SQLite function or operator](#add-an-sqlite-function-or-operator)**
|
||||
|
||||
You'll learn how to add support for the [STRFTIME](https://www.sqlite.org/lang_datefunc.html) function, and the [GLOB](https://www.sqlite.org/lang_expr.html#like) operator:
|
||||
|
||||
```swift
|
||||
Books.select(strftime("%Y", Column("publishedDate"))) // <-- New! strftime function
|
||||
Books.filter(Column("body").glob("*Moby-Dick*")) // <-- New! glob method
|
||||
```
|
||||
|
||||
- **[Add a new kind of SQLite expression](#add-a-new-kind-of-sqlite-expression)**
|
||||
|
||||
You'll learn how to add support for [CAST expressions](https://www.sqlite.org/lang_expr.html#castexpr):
|
||||
|
||||
```swift
|
||||
let jsonString = Column("jsonString")
|
||||
let request = Books.select(cast(jsonString, as: .blob)) // <-- New! cast function
|
||||
let rows = try Row.fetchCursor(db, request)
|
||||
while let row = try rows.next() {
|
||||
let data = row.dataNoCopy(atIndex: 0)
|
||||
}
|
||||
```
|
||||
|
||||
- **Extend the query interface requests**
|
||||
|
||||
You may need to extend the [query interface requests](../../../#requests) so that their SELECT queries could embed recursive clauses, table joins, etc.
|
||||
|
||||
Pull requests are welcome. Open issues if you have questions.
|
||||
|
||||
Meanwhile, you can build your own [custom requests](../../../#custom-requests).
|
||||
|
||||
- **[Add a custom FTS5 full-text tokenizer](FTS5Tokenizers.md)**
|
||||
|
||||
Custom tokenizers can leverage extra full-text features such as synonyms or stop words.
|
||||
|
||||
- **Support a new kind of SQL query**
|
||||
|
||||
For example, you may need to generate SQL triggers, or create specific kinds of virtual tables.
|
||||
|
||||
Pull requests are welcome. Open issues if you have questions.
|
||||
|
||||
|
||||
## Add a Value Type
|
||||
|
||||
**All value types adopt the [DatabaseValueConvertible protocol](../../../#custom-value-types).**
|
||||
|
||||
```swift
|
||||
protocol DatabaseValueConvertible {
|
||||
/// Returns a value that can be stored in the database.
|
||||
var databaseValue: DatabaseValue { get }
|
||||
|
||||
/// Returns a value initialized from databaseValue, if possible.
|
||||
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self?
|
||||
}
|
||||
```
|
||||
|
||||
The `databaseValue` property returns [DatabaseValue](../../../#databasevalue), a type that wraps the five values supported by SQLite: NULL, Int64, Double, String and Data. Since DatabaseValue has no public initializer, use `DatabaseValue.null`, or another type that already adopts the protocol: `1.databaseValue`, `"foo".databaseValue`, etc. Conversion to DatabaseValue *must not* fail.
|
||||
|
||||
The `fromDatabaseValue()` factory method returns an instance of your custom type if the databaseValue contains a suitable value. If the databaseValue does not contain a suitable value, such as "foo" for Date, `fromDatabaseValue` *must* return nil (GRDB will interpret this nil result as a conversion error, and react accordingly).
|
||||
|
||||
**What does the DatabaseValueConvertible protocol bring to a type like UIColor?**
|
||||
|
||||
Well, you will be able to use UIColor like all other [value types](../../../#values) (Bool, Int, String, Date, Swift enums, etc.):
|
||||
|
||||
- Use UIColor as [statement arguments](../../../#executing-updates):
|
||||
|
||||
```swift
|
||||
try db.execute(
|
||||
"INSERT INTO clothes (name, color) VALUES (?, ?)",
|
||||
arguments: ["Shirt", UIColor.red])
|
||||
```
|
||||
|
||||
- UIColor can be [extracted from rows](../../../#column-values):
|
||||
|
||||
```swift
|
||||
let rows = try Row.fetchCursor(db, "SELECT * FROM clothes")
|
||||
while let row = try rows.next() {
|
||||
let name: String = row.value(named: "name")
|
||||
let color: UIColor = row.value(named: "color")
|
||||
}
|
||||
```
|
||||
|
||||
- UIColor can be [directly fetched](../../../#value-queries):
|
||||
|
||||
```swift
|
||||
let colors = try UIColor.fetchAll(db, "SELECT DISTINCT color FROM clothes") // [UIColor]
|
||||
```
|
||||
|
||||
- Use UIColor in [Records](../../../#records):
|
||||
|
||||
```swift
|
||||
class ClothingItem : Record {
|
||||
var name: String
|
||||
var color: UIColor
|
||||
|
||||
required init(row: Row) {
|
||||
name = row.value(named: "name")
|
||||
color = row.value(named: "color")
|
||||
super.init(row: row)
|
||||
}
|
||||
|
||||
override func encode(to container: inout PersistenceContainer) {
|
||||
container["name"] = name
|
||||
container["color"] = color
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- Use UIColor in the [query interface](../../../#the-query-interface):
|
||||
|
||||
```swift
|
||||
let redClothes = try ClothingItem.filter(colorColumn == UIColor.red).fetchAll(db)
|
||||
```
|
||||
|
||||
**Let's have UIColor adopt DatabaseValueConvertible**
|
||||
|
||||
In order to preserve as most information as possible, we'll archive UIColor as a data blob using the NSCoding protocol. But YMMV.
|
||||
|
||||
```swift
|
||||
extension UIColor : DatabaseValueConvertible {
|
||||
|
||||
/// Encode UIColor as a data blob
|
||||
var databaseValue: DatabaseValue {
|
||||
// Use NSKeyedArchiver to build Data
|
||||
let data = NSKeyedArchiver.archivedData(withRootObject: self)
|
||||
|
||||
// Data is already DatabaseValueConvertible
|
||||
return data.databaseValue
|
||||
}
|
||||
|
||||
/// Returns a UIColor if databaseValue contains suitable data, and
|
||||
/// nil otherwise.
|
||||
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
// Only Data blobs can contain a UIColor
|
||||
guard let data = Data.fromDatabaseValue(databaseValue) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
// We're looking for an archived object
|
||||
guard let color = NSKeyedUnarchiver.unarchiveObject(with: data) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
// The cast function will return nil if the unarchived object doesn't
|
||||
// have the correct type
|
||||
return cast(color) // Converts Any to Self?
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Use the `cast` utility function when you want *non-final classes* to implement DatabaseValueConvertible. It avoids compiler errors that are not easy to deal with. Note that final classes and value types won't need it.
|
||||
|
||||
```swift
|
||||
// Workaround Swift inconvenience around factories methods of non-final classes
|
||||
func cast<T, U>(_ value: T) -> U? {
|
||||
return value as? U
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Add an SQLite Function or Operator
|
||||
|
||||
**When an SQLite [function](https://www.sqlite.org/lang_corefunc.html) or [operator](https://www.sqlite.org/lang_expr.html) is missing from GRDB**, this usually means that there hasn't been a [feature request](http://github.com/groue/GRDB.swift/issues) yet.
|
||||
|
||||
But you don't have to wait: you can extend GRDB and the query interface to add support for the missing syntax element (and eventually submit a pull request later).
|
||||
|
||||
Let's remind our goal: we'll add the [STRFTIME](https://www.sqlite.org/lang_datefunc.html) function, and the [GLOB](https://www.sqlite.org/lang_expr.html#like) operator.
|
||||
|
||||
Their SQL usage is the following:
|
||||
|
||||
```sql
|
||||
-- Publication years of books
|
||||
SELECT STRFTIME('%Y', publishedOn) FROM books;
|
||||
-- Books that talk about Moby Dick
|
||||
SELECT * FROM books WHERE body GLOB '*Moby-Dick*';
|
||||
```
|
||||
|
||||
Translated in the query interface, this gives:
|
||||
|
||||
```swift
|
||||
Books.select(strftime("%Y", Column("publishedDate")))
|
||||
Books.filter(Column("body").glob("*Moby-Dick*"))
|
||||
```
|
||||
|
||||
`strftime` is a top-level Swift function because this is how GRDB usually imports SQLite functions which do not have matching standard Swift counterpart, like AVG, LEGNTH, SUM. It helps the Swift code looking like SQL when it is relevant.
|
||||
|
||||
In the same fashion, we expose the GLOB SQL operator as the `glob` Swift method, just because `value.glob(pattern)` reads like `value GLOB pattern`.
|
||||
|
||||
Whenever you import a SQL feature to Swift, you'll have to decide: should you preserve the SQL look and feel, or adopt a well-established swiftism? It's really up to you.
|
||||
|
||||
|
||||
### STRFTIME
|
||||
|
||||
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
|
||||
The [STRFTIME](https://www.sqlite.org/lang_datefunc.html) SQL function accepts many arguments. We'll simplify it to `strftime(format, date)`, so that we can write:
|
||||
|
||||
```sql
|
||||
// Publication years of books
|
||||
// SELECT STRFTIME('%Y', publishedOn) FROM books
|
||||
Books.select(strftime("%Y", Column("publishedDate")))
|
||||
```
|
||||
|
||||
The signature of the Swift `strftime` function is:
|
||||
|
||||
```swift
|
||||
func strftime(_ format: String, _ date: SQLSpecificExpressible) -> SQLExpression
|
||||
```
|
||||
|
||||
SQLSpecificExpressible and SQLExpression are types of the [query interface](../../../#the-query-interface) that you do not usually see. We have moved down one floor, closer to the SQL guts of GRDB. We'll see more new types and protocols below.
|
||||
|
||||
The return value is SQLExpression. All GRDB functions and operators that build [query interface expressions](../../../#expressions) return values of this type. It represents actual [SQLite expressions](https://www.sqlite.org/lang_expr.html).
|
||||
|
||||
SQLExpression is a protocol, so that you can build your own [custom expressions](#add-a-new-kind-of-sqlite-expression). But GRDB ships with a variety of [built-in expressions](#built-in-expressions) that are ready-made, and here we'll use SQLExpressionFunction that is dedicated to function calls:
|
||||
|
||||
```swift
|
||||
struct SQLExpressionFunction : SQLExpression {
|
||||
/// Creates an SQL function call
|
||||
///
|
||||
/// // ABS(-1)
|
||||
/// SQLExpressionFunction(.abs, arguments: -1)
|
||||
init(_ functionName: SQLFunctionName, arguments: SQLExpressible...)
|
||||
}
|
||||
```
|
||||
|
||||
So here is the code that defines our `strftime` function:
|
||||
|
||||
```swift
|
||||
// Add a SQLFunctionName just like we add NSNotification.Name since
|
||||
// the release of Swift 3.
|
||||
extension SQLFunctionName {
|
||||
/// The `STRFTIME` SQL function
|
||||
static let strftime = SQLFunctionName("STRFTIME")
|
||||
}
|
||||
|
||||
/// Returns an expression that evaluates the `STRFTIME` SQL function.
|
||||
///
|
||||
/// // STRFTIME('%Y', date)
|
||||
/// strftime("%Y", Column("date"))
|
||||
func strftime(_ format: String, _ date: SQLSpecificExpressible) -> SQLExpression {
|
||||
return SQLExpressionFunction(.strftime, arguments: format, date)
|
||||
}
|
||||
```
|
||||
|
||||
The `strftime` function is now complete, ready to be used. We haven't yet described the SQLSpecificExpressible type of the `date` argument:
|
||||
|
||||
SQLSpecificExpressible is the protocol for all types that can be turned into a SQL expression, but types like Int, Date, or UIColor that exist outside of GRDB and the query interface. Having `strftime` accept a SQLSpecificExpressible date prevents it from polluting the global space. It is *specific* to GRDB:
|
||||
|
||||
```swift
|
||||
strftime("%Y", Date()) // Compiler error
|
||||
strftime("%Y", Column("date")) // SQLExpression: STRFTIME('%Y', date)
|
||||
```
|
||||
|
||||
You may want to compare it to another protocol, SQLExpressible, which will be described [below](#add-a-new-kind-of-sqlite-expression), when we add support for CAST SQL expressions.
|
||||
|
||||
> :point_up: **Note**: whenever you extend GRDB with a Swift function, method, or operator, you should generally make sure that its signature contains at least one GRDB-specific type. In the `strftime` function, it is the SQLSpecificExpressible protocol.
|
||||
|
||||
|
||||
### GLOB
|
||||
|
||||
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
|
||||
For the [GLOB](https://www.sqlite.org/lang_expr.html#like) operator, we want to define the glob Swift method:
|
||||
|
||||
```swift
|
||||
// Books that talk about Moby Dick
|
||||
// SELECT * FROM books WHERE body GLOB '*Moby-Dick*'
|
||||
Books.filter(Column("body").glob("*Moby-Dick*"))
|
||||
```
|
||||
|
||||
This time we can't use the SQLExpressionFunction type, because it can't generate the SQL for a binary operator. Instead, we'll use another [built-in expression](#built-in-expressions), SQLExpressionBinary:
|
||||
|
||||
```swift
|
||||
struct SQLExpressionBinary : SQLExpression {
|
||||
/// Creates an expression made of two expressions joined with a binary operator.
|
||||
///
|
||||
/// // length * width
|
||||
/// SQLExpressionBinary(.multiply, Column("length"), Column("width"))
|
||||
init(_ op: SQLBinaryOperator, _ lhs: SQLExpressible, _ rhs: SQLExpressible)
|
||||
}
|
||||
```
|
||||
|
||||
Now we have to find the signature of our Swift method. The GLOB operator accepts any value on both sides. However, what kind of Swift code should we accept?
|
||||
|
||||
```swift
|
||||
// 1) body GLOB '*Moby-Dick*' -- Yes, of course
|
||||
Column("body").glob("*Moby-Dick*")
|
||||
// 2) body GLOB pattern -- Sure, why not?
|
||||
Column("body").glob(Column("pattern"))
|
||||
// 3) 'Some Swift String' GLOB pattern - Not sure, but OK
|
||||
"Some Swift String".glob(Column("pattern"))
|
||||
// 4) 'Some Swift String' GLOB 'Another Swift String' -- NO
|
||||
"Some Swift String".glob("Another Swift String")
|
||||
```
|
||||
|
||||
We don't want the form 4, because this is an unacceptable pollution of the Swift global namespace. A good GRDB extension limits its scope to database-related code.
|
||||
|
||||
We thus have two overloaded definitions of the `glob` method:
|
||||
|
||||
```swift
|
||||
extension SQLSpecificExpressible {
|
||||
func glob(_ pattern: SQLExpressible) -> SQLExpression
|
||||
}
|
||||
extension SQLExpressible {
|
||||
func glob(_ pattern: SQLSpecificExpressible) -> SQLExpression
|
||||
}
|
||||
```
|
||||
|
||||
SQLExpressible is the protocol for all types that can be turned into a SQL expression. This includes all expressions, and all [value types](../../../#values) (including String).
|
||||
|
||||
SQLSpecificExpressible is a sub protocol of SQLExpressible protocol, restricted to all types that can be turned into a SQL expression, but types like Int, Date, or String that exist outside of GRDB and the query interface.
|
||||
|
||||
By extending both, we can define the GLOB operators for any pair that contains at least one type that is specific to GRDB - and leave the global Swift space clean.
|
||||
|
||||
The final implementation follows:
|
||||
|
||||
```swift
|
||||
// Add a SQLBinaryOperator just like we add NSNotification.Name since
|
||||
// the release of Swift 3.
|
||||
extension SQLBinaryOperator {
|
||||
/// The `GLOB` binary operator
|
||||
static let glob = SQLBinaryOperator("GLOB")
|
||||
}
|
||||
|
||||
extension SQLSpecificExpressible {
|
||||
/// Returns an SQL `GLOB` expression.
|
||||
///
|
||||
/// // body GLOB '*Moby-Dick*'
|
||||
/// Column("body").glob("*Moby-Dick*")
|
||||
func glob(_ pattern: SQLExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.glob, self, pattern)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLExpressible {
|
||||
/// Returns an SQL `GLOB` expression.
|
||||
///
|
||||
/// // 'Some Swift String' GLOB pattern
|
||||
/// "Some Swift String".glob(Column("pattern"))
|
||||
func glob(_ pattern: SQLSpecificExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.glob, self, pattern)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Built-in Expressions
|
||||
|
||||
When you extend GRDB with a new function, method, or operator that generates an [SQL expression](https://www.sqlite.org/lang_expr.html), you have to return a value the adopts the SQLExpression protocol.
|
||||
|
||||
We have already seen in our [previous](#strftime) [examples](#glob) two concrete types that generate SQL function calls and binary operators: SQLExpressionFunction and SQLExpressionBinary.
|
||||
|
||||
This section of the documentation lists all built-in expressions. Adding a custom SQLExpression type will be documented [below](#add-a-new-kind-of-sqlite-expression).
|
||||
|
||||
|
||||
#### Column and DatabaseValue
|
||||
|
||||
The [Column](../../../#the-query-interface) type from the query interface, and [DatabaseValue](../../../#databasevalue), the type that wraps the five values supported by SQLite (NULL, Int64, Double, String and Data) are expressions. They are rather trivial, and it is unlikely that you use them in your GRDB extensions.
|
||||
|
||||
|
||||
#### SQLExpressionLiteral
|
||||
|
||||
Use SQLExpressionLiteral when you need to go fast:
|
||||
|
||||
```swift
|
||||
struct SQLExpressionLiteral : SQLExpression {
|
||||
/// Creates an SQL literal expression.
|
||||
///
|
||||
/// SQLExpressionLiteral("1 + 2")
|
||||
/// SQLExpressionLiteral("? + ?", arguments: [1, 2])
|
||||
init(_ sql: String, arguments: StatementArguments? = nil)
|
||||
}
|
||||
```
|
||||
|
||||
For an example of use, see the [Add a new kind of SQLite expression](#add-a-new-kind-of-sqlite-expression) chapter.
|
||||
|
||||
|
||||
#### SQLExpressionUnary
|
||||
|
||||
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
|
||||
SQLExpressionUnary builds an expression by prefixing another expression with an unary operator:
|
||||
|
||||
```swift
|
||||
struct SQLExpressionUnary : SQLExpression {
|
||||
/// Creates an expression made of an unary operator and
|
||||
/// an operand expression.
|
||||
///
|
||||
/// // NOT favorite
|
||||
/// SQLExpressionUnary(.not, Column("favorite"))
|
||||
init(_ op: SQLUnaryOperator, _ value: SQLExpressible)
|
||||
}
|
||||
```
|
||||
|
||||
You add missing SQLite unary operators by extending SQLUnaryOperator:
|
||||
|
||||
```swift
|
||||
extension SQLUnaryOperator {
|
||||
/// The `+` unary operator
|
||||
static let plus = SQLUnaryOperator("+", needsRightSpace: false)
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
#### SQLExpressionBinary
|
||||
|
||||
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
|
||||
SQLExpressionBinary builds an expression by joining two expressions with a binary operator:
|
||||
|
||||
```swift
|
||||
struct SQLExpressionBinary : SQLExpression {
|
||||
/// Creates an expression made of two expressions joined with a binary operator.
|
||||
///
|
||||
/// // length * width
|
||||
/// SQLExpressionBinary(.multiply, Column("length"), Column("width"))
|
||||
init(_ op: SQLBinaryOperator, _ lhs: SQLExpressible, _ rhs: SQLExpressible)
|
||||
}
|
||||
```
|
||||
|
||||
You add missing SQLite binary operators by extending SQLBinaryOperator:
|
||||
|
||||
```swift
|
||||
extension SQLBinaryOperator {
|
||||
/// The `GLOB` binary operator
|
||||
static let glob = SQLBinaryOperator("GLOB")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
#### SQLExpressionFunction
|
||||
|
||||
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
|
||||
SQLExpressionFunction builds an SQL function call:
|
||||
|
||||
```swift
|
||||
struct SQLExpressionFunction : SQLExpression {
|
||||
/// Creates an SQL function call
|
||||
///
|
||||
/// // ABS(-1)
|
||||
/// SQLExpressionFunction(.abs, arguments: -1)
|
||||
init(_ functionName: SQLFunctionName, arguments: SQLExpressible...)
|
||||
}
|
||||
```
|
||||
|
||||
You add missing SQLite function names by extending SQLFunctionName:
|
||||
|
||||
```swift
|
||||
extension SQLFunctionName {
|
||||
/// The `STRFTIME` SQL function
|
||||
static let strftime = SQLFunctionName("STRFTIME")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
#### The IN Operator
|
||||
|
||||
Build a `value IN (...)` expression from any sequence of [values](../../../#values):
|
||||
|
||||
```swift
|
||||
// SQLExpression: id IN (1, 2, 3)
|
||||
[1,2,3].contains(Column("id"))
|
||||
|
||||
// SQLExpression: id NOT IN (1, 2, 3)
|
||||
![1,2,3].contains(Column("id"))
|
||||
```
|
||||
|
||||
|
||||
#### The BETWEEN Operator
|
||||
|
||||
Build a `value BETWEEN min AND max` expression from Swift ranges:
|
||||
|
||||
```swift
|
||||
// SQLExpression: id BETWEEN 1 AND 10
|
||||
1...10.contains(Column("id")
|
||||
```
|
||||
|
||||
|
||||
#### The COUNT Function
|
||||
|
||||
Build a `COUNT(...)` expression from the [count](http://groue.github.io/GRDB.swift/docs/1.1/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/1.1/Functions.html) functions:
|
||||
|
||||
```swift
|
||||
// SQLExpression: COUNT(email)
|
||||
count(Column("email"))
|
||||
|
||||
// SQLExpression: COUNT(DISTINCT email)
|
||||
count(distinct: Column("email"))
|
||||
```
|
||||
|
||||
|
||||
#### The COLLATE Operator
|
||||
|
||||
Build a `expression COLLATE collation` expression with the `collating` method:
|
||||
|
||||
```swift
|
||||
// SQLExpression: name = 'Arthur' COLLATE NOCASE
|
||||
Column("name").collating(.nocase) == "Arthur"
|
||||
```
|
||||
|
||||
|
||||
## Add a New Kind of SQLite Expression
|
||||
|
||||
GRDB does not have built-in support for the full range of the SQLite [expression grammar](https://www.sqlite.org/lang_expr.html).
|
||||
|
||||
For example, [CAST expressions](https://www.sqlite.org/lang_expr.html#castexpr) are not ready-made. They can be useful, though: a CAST expression can efficiently convert json strings to UTF-8 data blobs for you:
|
||||
|
||||
```sql
|
||||
SELECT CAST(jsonString AS BLOB) FROM books
|
||||
```
|
||||
|
||||
We'll add below a Swift `cast` function:
|
||||
|
||||
```swift
|
||||
let request = Books.select(cast(Column("jsonString"), as: .blob))
|
||||
let jsonDatas = try Data.fetchAll(db, request) // [Data]
|
||||
```
|
||||
|
||||
`cast` is a top-level Swift function because this is how GRDB usually imports SQLite features which do not have matching standard Swift counterpart. It helps the Swift code looking like SQL when it is relevant. But YMMV.
|
||||
|
||||
The signature of the `cast` function is:
|
||||
|
||||
```swift
|
||||
func cast(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression
|
||||
```
|
||||
|
||||
Database.ColumnType is a String-based enumeration of all database column types (.integer, .text, .blob, etc.) You have already used if you have [created tables](../../../#create-tables) using the query interface.
|
||||
|
||||
The return type SQLExpression is the type returned by all GRDB functions and operators that build [query interface expressions](../../../#expressions).
|
||||
|
||||
SQLExpression is a protocol. But GRDB ships with a variety of [built-in expressions](#built-in-expressions) that are ready-made, so that you generally don't have to write your custom expression type. Here we need something new. So we'll use the most versatile of all, SQLExpressionLiteral:
|
||||
|
||||
```swift
|
||||
struct SQLExpressionLiteral : SQLExpression {
|
||||
/// Creates an SQL literal expression.
|
||||
///
|
||||
/// SQLExpressionLiteral("1 + 2")
|
||||
/// SQLExpressionLiteral("? + ?", arguments: [1, 2])
|
||||
init(_ sql: String, arguments: StatementArguments? = nil)
|
||||
}
|
||||
```
|
||||
|
||||
Here is the code that defines our `cast` function:
|
||||
|
||||
|
||||
```swift
|
||||
func cast(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression {
|
||||
// Turn the value into a literal expression
|
||||
let literal: SQLExpressionLiteral = value.sqlExpression.literal
|
||||
|
||||
// Build our "CAST(value AS type)" sql snippet
|
||||
let sql = "CAST(\(literal.sql) AS \(type.rawValue))"
|
||||
|
||||
// And return a new literal expression, preserving input arguments
|
||||
return SQLExpressionLiteral(sql, arguments: literal.arguments)
|
||||
}
|
||||
```
|
||||
|
||||
We haven't yet described the SQLExpressible type of the `value` argument:
|
||||
|
||||
SQLExpressible is the protocol for all types that can be turned into a SQL expression. This includes all [value types](../../../#values) (Bool, Int, String, Date, Swift enums, etc.):
|
||||
|
||||
```swift
|
||||
cast("foo", as: .blob) // SQLExpression: CAST('foo' AS BLOB)
|
||||
cast(Column("name"), as: .blob) // SQLExpression: CAST(name AS BLOB)
|
||||
```
|
||||
|
||||
You may want to compare it to another protocol, SQLSpecificExpressible, which has been described [above](#strftime), when we were adding support for the STRFTIME SQL function.
|
||||
|
||||
> :point_up: **Note**: whenever you extend GRDB with a Swift function, method, or operator, you should generally make sure that its signature contains at least one GRDB-specific type. In the `cast` function, it is Database.ColumnType.
|
||||
|
||||
**If SQLExpressionLiteral reveals too limited for your purpose**, you may have to implement a new type that adopts the [SQLExpression](http://groue.github.io/GRDB.swift/docs/1.1/Protocols/SQLExpression.html) protocol.
|
||||
@@ -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,523 @@
|
||||
Migrating From GRDB 2 to GRDB 3
|
||||
===============================
|
||||
|
||||
GRDB 3 comes with new features, but also a few breaking changes, and a set of updated good practices. This guide aims at helping you upgrading your applications.
|
||||
|
||||
**For all users**
|
||||
|
||||
- [Swift 4.1 Required]
|
||||
- [iOS 8 Sunsetting]
|
||||
- [Database Schema Recommendations]
|
||||
- [Record Protocols Renaming]
|
||||
- [Columns Definition]
|
||||
|
||||
**By topic**
|
||||
|
||||
- [If You Use Database Queues]
|
||||
- [If You Use Database Pools]
|
||||
- [If You Use Database Snapshots]
|
||||
- [If You Use Record Types]
|
||||
- [If You Use Custom Requests]
|
||||
- [If You Use RxGRDB]
|
||||
- [Notable Documentation Updates]
|
||||
|
||||
|
||||
## Swift 4.1 Required
|
||||
|
||||
GRDB 3 uses [conditional conformances], introduced in Swift 4.1. It can only be built on Xcode 9.3+.
|
||||
|
||||
|
||||
## iOS 8 Sunsetting
|
||||
|
||||
GRDB 3 is only tested on iOS 9+, due to a limitation in Xcode 9.3. Code that targets older versions of SQLite and iOS is still there, but is not supported.
|
||||
|
||||
|
||||
## Database Schema Recommendations
|
||||
|
||||
GRDB 2 was totally schema-agnostic, and would gladly accept any database.
|
||||
|
||||
GRDB 3 still accepts any database, but brings two schema recommendations:
|
||||
|
||||
- :bulb: Integer primary keys should be auto-incremented, in order to avoid any row id to be reused.
|
||||
|
||||
When ids can be reused, your app and [database observation tools] may think that a row was updated, when it was actually deleted, then replaced. Depending on your application needs, this may be OK. Or not.
|
||||
|
||||
GRDB 3 thus comes with a new good practice: use the `autoIncrementedPrimaryKey` method when you create a database table with an integer primary key:
|
||||
|
||||
```diff
|
||||
try db.create(table: "author") { t in
|
||||
- t.column("id", .integer).primaryKey() // GRDB 2
|
||||
+ t.autoIncrementedPrimaryKey("id") // GRDB 3 recommendation
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
- :bulb: Database table names should be singular, and camel-cased. Make them look like Swift identifiers: `place`, `country`, `postalAddress`, 'httpRequest'.
|
||||
|
||||
This will help you using the new [Associations] feature when you need it. Database table names that follow another naming convention are totally OK, but you will need to perform extra configuration.
|
||||
|
||||
This convention is applied by the default implementation of the `TableRecord.databaseTableName`: see [If You Use Record Types] below.
|
||||
|
||||
Since you are reading this guide, your application has already defined its database schema. You can migrate it in order to apply the new recommendations, if needed. Below is a sample code that uses [DatabaseMigrator], the recommended tool for managing your database schema:
|
||||
|
||||
```swift
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
// Existing GRDB 2 migration:
|
||||
migrator.registerMigration("initial") { db in
|
||||
try db.create(table: "authors") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
try db.create(table: "books") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.column("authorId", .integer).notNull().references("authors")
|
||||
t.column("title", .text).notNull()
|
||||
}
|
||||
}
|
||||
|
||||
// New GRDB 3 migration:
|
||||
// - Rename tables so that they look like Swift identifiers (singular and camelCased)
|
||||
// - Make integer primary keys auto-incremented
|
||||
//
|
||||
// Since several tables are recreated from scratch, referential integrity
|
||||
// constraints may break during the process. The
|
||||
// registerMigrationWithDeferredForeignKeyCheck method makes sure that foreign
|
||||
// key checks are temporarily disabled, and checked at the end:
|
||||
migrator.registerMigrationWithDeferredForeignKeyCheck("GRDB3") { db in
|
||||
try db.create(table: "author") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
try db.create(table: "book") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("authorId", .integer).notNull().references("author")
|
||||
t.column("title", .text).notNull()
|
||||
}
|
||||
try db.execute("""
|
||||
INSERT INTO author SELECT * FROM authors;
|
||||
INSERT INTO book SELECT * FROM books;
|
||||
""")
|
||||
try db.drop(table: "authors")
|
||||
try db.drop(table: "books")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Record Protocols Renaming
|
||||
|
||||
GRDB 3 has renamed the [record protocols]:
|
||||
|
||||
- `RowConvertible` -> `FetchableRecord`
|
||||
- `TableMapping` -> `TableRecord`
|
||||
- `Persistable` -> `PersistableRecord`
|
||||
- `MutablePersistable` -> `MutablePersistableRecord`
|
||||
|
||||
After upgrading, build your project: the compiler will guide you through the renaming by the way of fixits.
|
||||
|
||||
|
||||
## Columns Definition
|
||||
|
||||
GRDB 2 has you define columns of the query interface with the Column type:
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
let nameColumn = Column("name")
|
||||
let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db)
|
||||
```
|
||||
|
||||
A recommended practice was to define enum namespaces in record types:
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
struct Player: RowConvertible, TableMapping {
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
static let name = Column("name")
|
||||
static let score = Column("score")
|
||||
}
|
||||
|
||||
init(row: Row) {
|
||||
id = row[Columns.id]
|
||||
name = row[Columns.name]
|
||||
score = row[Columns.score]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In GRDB 3, `Column` is still there, but a new `ColumnExpression` protocol has been introduced in order to streamline column enums:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
struct Player: FetchableRecord, TableRecord {
|
||||
enum Columns: String, ColumnExpression {
|
||||
case id, name, score
|
||||
}
|
||||
|
||||
init(row: Row) {
|
||||
id = row[Columns.id]
|
||||
name = row[Columns.name]
|
||||
score = row[Columns.score]
|
||||
}
|
||||
}
|
||||
|
||||
extension Player {
|
||||
static func filter(name: String) -> QueryInterfaceRequest<Player> {
|
||||
return filter(Columns.name == name)
|
||||
}
|
||||
|
||||
static var maximumScore: QueryInterfaceRequest<Int> {
|
||||
return select(max(Columns.score), as: Int.self)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
When your record adopts the Codable protocol, you can use its [coding keys](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types) to safely define database columns:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
struct Player: Codable {
|
||||
var id: Int64
|
||||
var name: String
|
||||
var score: Int
|
||||
}
|
||||
|
||||
extension Player: FetchableRecord, PersistableRecord {
|
||||
enum Columns {
|
||||
static let id = Column(CodingKeys.id.stringValue)
|
||||
static let name = Column(CodingKeys.name.stringValue)
|
||||
static let score = Column(CodingKeys.score.stringValue)
|
||||
}
|
||||
|
||||
static func filter(name: String) -> QueryInterfaceRequest<Player> {
|
||||
return filter(Columns.name == name)
|
||||
}
|
||||
|
||||
static var maximumScore: QueryInterfaceRequest<Int> {
|
||||
return select(max(Columns.score), as: Int.self)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## If You Use Database Queues
|
||||
|
||||
With GRDB 2, you used to access the database through the `inDatabase` or `inTransaction` [DatabaseQueue] methods:
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
let players = try dbQueue.inDatabase { db in
|
||||
try Player.fetchAll(db)
|
||||
}
|
||||
|
||||
try dbQueue.inDatabase { db in
|
||||
try player.updateChanges(db)
|
||||
}
|
||||
|
||||
var balance: Amount! = nil
|
||||
try dbQueue.inTransaction { db in
|
||||
try Credit(destinationAccout, amount).insert(db)
|
||||
try Debit(sourceAccount, amount).insert(db)
|
||||
balance = try sourceAccount.fetchBalance(db)
|
||||
return .commit
|
||||
}
|
||||
```
|
||||
|
||||
The code above still runs, unchanged, in GRDB 3.
|
||||
|
||||
Yet it is now recommended that you use the `read` and `write` methods instead:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
let players = try dbQueue.read { db in
|
||||
try Player.fetchAll(db)
|
||||
}
|
||||
|
||||
try dbQueue.write { db in
|
||||
try player.updateChanges(db)
|
||||
}
|
||||
|
||||
let balance = try dbQueue.write { db in
|
||||
try Credit(destinationAccout, amount).insert(db)
|
||||
try Debit(sourceAccount, amount).insert(db)
|
||||
return try sourceAccount.fetchBalance(db)
|
||||
}
|
||||
```
|
||||
|
||||
The purpose of the new `read` and `write` methods is to soothe the "transaction mental load" of previous versions of GRDB, a legacy of the [FMDB] heritage. All developers can *forget* to open transactions, with the unfortunate consequence that the database may end up containing inconsistent values. Experienced developers may *wonder* whether they should open transactions or not, even when this doesn't matter a lot.
|
||||
|
||||
With GRDB 3, use `read` when you need to read values. It's impossible to write within a `read` block, which means that you can be sure that no unwanted side effect can happen.
|
||||
|
||||
When you need to write, use `write`: your database changes are automatically wrapped in a transaction, with the guarantee that all changes are written to disk, or, should any error happen, none at all.
|
||||
|
||||
Of course, precise transaction handling sometimes matter. Check the updated [Transactions and Savepoints] chapter.
|
||||
|
||||
|
||||
## If You Use Database Pools
|
||||
|
||||
With GRDB 2, you used to access the database through the `read`, `write` or `writeInTransaction` [DatabasePool] methods:
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
let players = try dbPool.read { db in
|
||||
try Player.fetchAll(db)
|
||||
}
|
||||
|
||||
try dbPool.write { db in
|
||||
try player.updateChanges(db)
|
||||
}
|
||||
|
||||
var balance: Amount! = nil
|
||||
try dbPool.writeInTransaction { db in
|
||||
try Credit(destinationAccout, amount).insert(db)
|
||||
try Debit(sourceAccount, amount).insert(db)
|
||||
balance = try sourceAccount.fetchBalance(db)
|
||||
return .commit
|
||||
}
|
||||
```
|
||||
|
||||
In GRDB 3, the `write` method has changed: it now automatically wraps your database changes in a transaction, which means that the last block can be rewritten as below:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
let balance = try dbPool.write { db in
|
||||
try Credit(destinationAccout, amount).insert(db)
|
||||
try Debit(sourceAccount, amount).insert(db)
|
||||
return try sourceAccount.fetchBalance(db)
|
||||
}
|
||||
```
|
||||
|
||||
Side effect: you can no longer open explicit transactions inside a `write` block:
|
||||
|
||||
```swift
|
||||
// GRDB 2: OK
|
||||
// GRDB 3: SQLite error 1 with statement `BEGIN DEFERRED TRANSACTION`:
|
||||
// cannot start a transaction within a transaction
|
||||
try dbPool.write { db in
|
||||
try db.inTransaction { ... }
|
||||
}
|
||||
```
|
||||
|
||||
When precise transaction handling is needed, check the updated [Transactions and Savepoints] chapter.
|
||||
|
||||
The purpose of this change is to prevent an easy misuse of database pools in previous GRDB versions. Unless writes were wrapped inside an explicit transactions, concurrent reads could see an inconsistent state of the database:
|
||||
|
||||
```swift
|
||||
// GRDB 2: unsafe
|
||||
// GRDB 3: safe
|
||||
try dbPool.write { db in
|
||||
try Credit(destinationAccout, amount).insert(db)
|
||||
try Debit(sourceAccount, amount).insert(db)
|
||||
}
|
||||
```
|
||||
|
||||
Since `write` now wraps your changes in a transaction, you have the guarantee that concurrent reads can't see them until they are all written to disk.
|
||||
|
||||
|
||||
## If You Use Database Snapshots
|
||||
|
||||
With GRDB 2, you used to create [database snapshots] with the `makeSnaphot` [DatabasePool] method. For example:
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
let snapshot: DatabaseSnapshot = try dbPool.write { db in
|
||||
try Player.deleteAll()
|
||||
return dbPool.makeSnapshot()
|
||||
}
|
||||
|
||||
// Guaranteed to be zero
|
||||
let count = try snapshot.read { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
GRDB 3 will crash the above code on the `makeSnapshot()` line, with a fatal error: "makeSnapshot() must not be called from inside a transaction."
|
||||
|
||||
To avoid this error, you will need [precise transaction handling]:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
let snapshot: DatabaseSnapshot = try dbPool.writeWithoutTransaction { db in
|
||||
try Player.deleteAll()
|
||||
return dbPool.makeSnapshot()
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## If You Use Record Types
|
||||
|
||||
Record types that adopt the former TableMapping protocol, renamed TableRecord, used to declare their table name:
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
struct Place: TableMapping {
|
||||
static let databaseTableName = "place"
|
||||
}
|
||||
print(Place.databaseTableName) // print "place"
|
||||
```
|
||||
|
||||
With GRDB 3, the `databaseTableName` property gets a default implementation:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
struct Place: TableRecord { }
|
||||
print(Place.databaseTableName) // print "place"
|
||||
```
|
||||
|
||||
That default name follows the [Database Schema Recommendations]: it is singular, camel-cased, and looks like a Swift identifier:
|
||||
|
||||
- Place: `place`
|
||||
- Country: `country`
|
||||
- PostalAddress: `postalAddress`
|
||||
- HTTPRequest: `httpRequest`
|
||||
- TOEFL: `toefl`
|
||||
|
||||
When you subclass the Record class, the Swift compiler won't let you profit from this default name: you have to keep on providing an explicit table name:
|
||||
|
||||
```swift
|
||||
// GRDB 2 and GRDB 3
|
||||
class Place: Record {
|
||||
override var databaseTableName: String {
|
||||
return "place"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## If You Use Custom Requests
|
||||
|
||||
[Custom requests] let you escape the limitations of the [query interface], when it can not generate the requests you need.
|
||||
|
||||
You may, for example, use `SQLRequest`:
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
extension Player {
|
||||
static func filter(color: Color) -> AnyTypedRequest<Player> {
|
||||
let sql = "SELECT * FROM players WHERE color = ?"
|
||||
let request = SQLRequest(sql, arguments: [color])
|
||||
return request.asRequest(of: Player.self)
|
||||
}
|
||||
}
|
||||
|
||||
let players = try Player.filter(color: .red).fetchAll(db)
|
||||
```
|
||||
|
||||
The `AnyTypedRequest` type is no longer available, and `SQLRequest` is now a generic type:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
extension Player {
|
||||
static func filter(color: Color) -> SQLRequest<Player> {
|
||||
let sql = "SELECT * FROM players WHERE color = ?"
|
||||
return SQLRequest(sql, arguments: [color])
|
||||
}
|
||||
}
|
||||
|
||||
let players = try Player.filter(color: .red).fetchAll(db)
|
||||
```
|
||||
|
||||
See the updated [Custom Requests](../README.md#custom-requests) chapter for more information.
|
||||
|
||||
|
||||
## If You Use RxGRDB
|
||||
|
||||
Some RxGRDB APIs have slighly changed. Did you track multiple requests at the same time with "fetch tokens"?
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
dbQueue.rx
|
||||
.fetchTokens(in: [request, ...])
|
||||
.mapFetch { db in try fetchResult(db) }
|
||||
.subscribe(...)
|
||||
```
|
||||
|
||||
Now you'll write instead:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
ValueObservation
|
||||
.tracking([request, ...], fetch: { db in try fetchResult(db) })
|
||||
.rx
|
||||
.fetch(in: dbQueue)
|
||||
.subscribe(...)
|
||||
```
|
||||
|
||||
It's just a syntactic change, without any impact on the runtime.
|
||||
|
||||
GRDB 3.6 also introduces a new protocol, [DatabaseRegionConvertible], that allows a better encapsulation of complex requests, and a streamlined observable definition.
|
||||
|
||||
For example:
|
||||
|
||||
```swift
|
||||
// GRDB 2: Track a team and its players
|
||||
let teamId = 1
|
||||
let teamRequest = Team.filter(key: teamId)
|
||||
let playersRequest = Player.filter(teamId: teamId)
|
||||
dbQueue.rx
|
||||
.fetchTokens(in: [teamRequest, playersRequest])
|
||||
.mapFetch { db -> TeamInfo? in
|
||||
guard let team = try teamRequest.fetchOne(db) else {
|
||||
return nil
|
||||
}
|
||||
let players = try playersRequest.fetchAll(db)
|
||||
return TeamInfo(team: team, players: players)
|
||||
}
|
||||
.subscribe(onNext: { teamInfo: TeamInfo? in
|
||||
...
|
||||
})
|
||||
|
||||
// GRDB 3: Track a team and its players
|
||||
struct TeamInfoRequest: DatabaseRegionConvertible { ... }
|
||||
let request = TeamInfoRequest(teamId: 1)
|
||||
ValueObservation.tracking(request, fetch: { try request.fetchOne($0) })
|
||||
.rx
|
||||
.fetch(in: dbQueue)
|
||||
.subscribe(onNext: { teamInfo: TeamInfo? in
|
||||
...
|
||||
})
|
||||
```
|
||||
|
||||
|
||||
## Notable Documentation Updates
|
||||
|
||||
If you have time, you may dig deeper in GRDB 3 with those updated documentation chapter:
|
||||
|
||||
- [Database Queues](../README.md#database-queues): focus on the new `read` and `write` methods.
|
||||
- [Transactions and Savepoints](../README.md#transactions-and-savepoints): the chapter has been rewritten in order to introduce transactions as a power-user feature.
|
||||
- [ScopeAdapter](../README.md#scopeadapter): do you use row adapters? If so, have a look.
|
||||
- [Examples of Record Definitions](../README.md#examples-of-record-definitions): this new chapter provides a handy reference of the three main ways to define record types (Codable, plain struct, Record subclass).
|
||||
- [SQL Operators](../README.md#sql-operators): the chapter introduces the new `joined(operator:)` method that lets you join a chain of expressions with `AND` or `OR` without nesting: `[cond1, cond2, ...].joined(operator: .and)`.
|
||||
- [Custom Requests](../README.md#custom-requests): the old `Request` and `TypedRequest` protocols have been replaced with `FetchRequest`. If you want to know more about custom requests, check this chapter.
|
||||
- [Migrations](../README.md#migrations): learn how to check if a migration has been applied (very useful for migration tests).
|
||||
|
||||
|
||||
[How To Upgrade]: #how-to-upgrade
|
||||
[Database Schema Recommendations]: #database-schema-recommendations
|
||||
[Record Protocols Renaming]: #record-protocols-renaming
|
||||
[Columns Definition]: #columns-definition
|
||||
[Swift 4.1 Required]: #swift-41-required
|
||||
[iOS 8 Sunsetting]: #ios-8-sunsetting
|
||||
[If You Use Database Queues]: #if-you-use-database-queues
|
||||
[If You Use Database Pools]: #if-you-use-database-pools
|
||||
[If You Use Database Snapshots]: #if-you-use-database-snapshots
|
||||
[If You Use Record Types]: #if-you-use-record-types
|
||||
[If You Use Custom Requests]: #if-you-use-custom-requests
|
||||
[If You Use RxGRDB]: #if-you-use-rxgrdb
|
||||
[Notable Documentation Updates]: #notable-documentation-updates
|
||||
[FetchedRecordsController]: ../README.md#fetchedrecordscontroller
|
||||
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
|
||||
[Associations]: AssociationsBasics.md
|
||||
[DatabaseMigrator]: ../README.md#migrations
|
||||
[database observation tools]: ../README.md#database-changes-observation
|
||||
[Transactions and Savepoints]: ../README.md#transactions-and-savepoints
|
||||
[precise transaction handling]: ../README.md#transactions-and-savepoints
|
||||
[DatabaseQueue]: ../README.md#database-queues
|
||||
[DatabasePool]: ../README.md#database-pools
|
||||
[database snapshots]: ../README.md#database-snapshots
|
||||
[FMDB]: http://github.com/ccgus/fmdb
|
||||
[record protocols]: ../README.md#record-protocols-overview
|
||||
[Custom requests]: ../README.md#custom-requests
|
||||
[query interface]: ../README.md#the-query-interface
|
||||
[DatabaseRegionConvertible]: https://github.com/groue/GRDB.swift#the-databaseregionconvertible-protocol
|
||||
[conditional conformances]: https://github.com/apple/swift-evolution/blob/master/proposals/0143-conditional-conformances.md
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,732 @@
|
||||
Good Practices for Designing Record Types
|
||||
=========================================
|
||||
|
||||
This guide aims at helping you leverage the best of GRDB [records] and [associations].
|
||||
|
||||
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 simple library application that lets the user crawl through books and their authors.
|
||||
|
||||
- [Trust SQLite More Than Yourself]
|
||||
- [Persistable Record Types are Responsible for Their Tables]
|
||||
- [Define Record Requests]
|
||||
- [Compose Records]
|
||||
- [How to Design Database Managers]
|
||||
- [Observe the Database and Refetch when Needed]
|
||||
|
||||
|
||||
## Trust SQLite More Than Yourself
|
||||
|
||||
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 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:
|
||||
|
||||
```swift
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
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() // (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 [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. 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 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.
|
||||
>
|
||||
> :bulb: **Tip**: Plan early for future versions of your application, and use [migrations].
|
||||
>
|
||||
> :bulb: **Tip**: In the definition of your migrations, define tables and their columns with **strings**:
|
||||
>
|
||||
> ```swift
|
||||
> migrator.registerMigration("createLibrary") { db in
|
||||
> // RECOMMENDED
|
||||
> try db.create(table: "author") { t in
|
||||
> t.autoIncrementedPrimaryKey("id")
|
||||
> ...
|
||||
> }
|
||||
>
|
||||
> // NOT RECOMMENDED
|
||||
> try db.create(table: Author.databaseTableName) { t in
|
||||
> t.autoIncrementedPrimaryKey(Author.Columns.id.name)
|
||||
> ...
|
||||
> }
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> By using strings, you make sure that you will not have to change the Swift code of your migrations in the future. Even if author columns eventually change. Even if the Author type eventually gets replaced with another type. Even when your startup eventually pivots and starts selling pet food. A good migration that never changes is easy to test once and for good. A good migration that never changes will run smoothly on all devices in the wild, even if a user upgrades straight from version 1.0 to version 5.0 of your application.
|
||||
>
|
||||
> 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**.
|
||||
|
||||
|
||||
## Persistable Record Types are Responsible for Their Tables
|
||||
|
||||
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.
|
||||
|
||||
```swift
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
extension Book: FetchableRecord, MutablePersistableRecord {
|
||||
// Update auto-incremented id upon successful insertion
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
That's it. The `Author` type can read and write in the `author` database table. `Book` as well, in `book`. See [record protocols] for more information.
|
||||
|
||||
> :bulb: **Tip**: When a column of a database table can't be NULL, store it in a non-optional property of your record type. On the other side, when the database may contain NULL, define an optional property.
|
||||
>
|
||||
> :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
|
||||
> 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*.
|
||||
|
||||
Applying the **[Single Responsibility Principle]** has a consequence: don't even try to have an author responsible for its books. Don't add a `books: [Book]` property in Author. Don't let Author write in the `book` table. When a new fellow coworker joins your team and asks you "who is saving books in the database?", you don't want to answer "it depends." You want to confidently answer: "the Book type".
|
||||
|
||||
> :bulb: **Tip**: Make sure each record type deals with one database table, and only one database table.
|
||||
|
||||
|
||||
## Define Record Requests
|
||||
|
||||
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.
|
||||
|
||||
> :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 {
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Otherwise, declare a plain String enum that conforms to the ColumnExpression protocol:
|
||||
|
||||
```swift
|
||||
// For a non-codable record
|
||||
extension Author {
|
||||
// Define database columns as an enum
|
||||
enum Columns: String, ColumnExpression {
|
||||
case id, name, country
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> :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))
|
||||
}
|
||||
}
|
||||
|
||||
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.filter(country: "Colombia"))
|
||||
return try Authorship.fetchAll(db, request)
|
||||
}
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
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].
|
||||
|
||||
> :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.
|
||||
|
||||
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] = 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: Codable, FetchableRecord {
|
||||
var author: Author
|
||||
var books: [Book]
|
||||
}
|
||||
let authorId = 123
|
||||
let authorInfo: AuthorInfo? = try dbQueue.read { db in
|
||||
let request = Author
|
||||
.filter(key: authorId)
|
||||
.including(all: Author.books)
|
||||
return try AuthorInfo.fetchOne(db, request)
|
||||
}
|
||||
```
|
||||
|
||||
3. Prepare the application screen that displays a book information:
|
||||
|
||||
```swift
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
var book: Book
|
||||
var author: Author
|
||||
}
|
||||
let bookId = 123
|
||||
let bookInfo: BookInfo? = try dbQueue.read { db in
|
||||
let request = Book
|
||||
.filter(key: bookId)
|
||||
.including(required: Book.author)
|
||||
return try BookInfo.fetchOne(db, request)
|
||||
}
|
||||
```
|
||||
|
||||
> :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.
|
||||
|
||||
A last extension on your record types will further help navigation from records to associated ones:
|
||||
|
||||
```swift
|
||||
extension Author {
|
||||
/// The request for the author's books
|
||||
var books: QueryInterfaceRequest<Book> {
|
||||
return request(for: Author.books)
|
||||
}
|
||||
}
|
||||
|
||||
extension Book {
|
||||
/// The request for the author of the book
|
||||
var author: QueryInterfaceRequest<Author> {
|
||||
return request(for: Book.author)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Those properties provide an alternative way to feed our application:
|
||||
|
||||
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)
|
||||
}
|
||||
```
|
||||
|
||||
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)
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 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
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> :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.
|
||||
|
||||
Design your database managers with the [GRDB concurrency rules] in mind.
|
||||
|
||||
Practically, let's start with a naive example, and gradually improve it:
|
||||
|
||||
```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 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.
|
||||
|
||||
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.
|
||||
|
||||
This synchronization is not automatic with GRDB: records do not "auto-update". That is because applications do not always want this feature, and because it is difficult to write correct multi-threaded applications when values can change in unexpected ways.
|
||||
|
||||
Instead, have a look at [Database Observation]:
|
||||
|
||||
> :bulb: **Tip**: [ValueObservation] performs automated tracking of database changes.
|
||||
>
|
||||
> :bulb: **Tip**: [FetchedRecordsController] performs automated tracking of database changes, and can animate the cells of a table or collection view.
|
||||
>
|
||||
> :bulb: **Tip**: [GRDBCombine] performs automated tracking of database changes, in the [Combine](https://developer.apple.com/documentation/combine) way.
|
||||
>
|
||||
> :bulb: **Tip**: [RxGRDB] performs automated tracking of database changes, in the [RxSwift](https://github.com/ReactiveX/RxSwift) way.
|
||||
>
|
||||
> :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
|
||||
[Core Data]: https://developer.apple.com/documentation/coredata
|
||||
[Realm]: https://realm.io
|
||||
[Active Record]: http://guides.rubyonrails.org/active_record_basics.html
|
||||
[Django]: https://docs.djangoproject.com/en/2.0/topics/db/
|
||||
[record protocols]: ../README.md#record-protocols-overview
|
||||
[Separation of Concerns]: https://en.wikipedia.org/wiki/Separation_of_concerns
|
||||
[Single Responsibility Principle]: https://en.wikipedia.org/wiki/Single_responsibility_principle
|
||||
[Single Source of Truth]: https://en.wikipedia.org/wiki/Single_source_of_truth
|
||||
[Divide and Conquer]: https://en.wikipedia.org/wiki/Divide_and_rule
|
||||
[Why Adopt GRDB?]: WhyAdoptGRDB.md
|
||||
[isolation]: https://en.wikipedia.org/wiki/Isolation_(database_systems)
|
||||
[migrations]: ../README.md#migrations
|
||||
[migration]: ../README.md#migrations
|
||||
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
|
||||
[Concurrency Guide]: ../README.md#concurrency
|
||||
[GRDB concurrency rules]: ../README.md#concurrency
|
||||
[PersistableRecord]: ../README.md#persistablerecord-protocol
|
||||
[Database Observation]: ../README.md#database-changes-observation
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[FetchedRecordsController]: ../README.md#fetchedrecordscontroller
|
||||
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
|
||||
[GRDBCombine]: http://github.com/groue/GRDBCombine
|
||||
[TransactionObserver]: ../README.md#transactionobserver-protocol
|
||||
[Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself
|
||||
[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
|
||||
[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
|
||||
@@ -0,0 +1,154 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="468px" height="145px" viewBox="0 0 468 145" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
|
||||
<title>AmbiguousForeignKeys</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="200" height="127" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-9.1%" width="114.5%" height="122.8%" 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="200" height="103" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" 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>
|
||||
<circle id="path-8" cx="3.5" cy="28.5" r="3.5"></circle>
|
||||
<path d="M57.4068802,4.62378409 L50.4819187,0.815055312 C49.9979981,0.548898936 49.3899405,0.725431787 49.1237841,1.20935247 C49.0425794,1.35699745 49,1.52276825 49,1.69127122 L49,9.30872878 C49,9.86101353 49.4477153,10.3087288 50,10.3087288 C50.168503,10.3087288 50.3342738,10.2661494 50.4819187,10.1849447 L57.4068802,6.37621591 C57.8908008,6.11005953 58.0673337,5.50200193 57.8011773,5.01808125 C57.7097895,4.85192153 57.5730399,4.71517193 57.4068802,4.62378409 Z" id="path-9"></path>
|
||||
<circle id="path-10" cx="3.5" cy="47.5" r="3.5"></circle>
|
||||
</defs>
|
||||
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<g id="AmbiguousForeignKeys" transform="translate(9.000000, 6.000000)">
|
||||
<g id="Table">
|
||||
<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>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="128" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">id</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">authorId</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">translatorId</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 103.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">title</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="book" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="82.9443359" y="21">book</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-2" transform="translate(250.000000, 0.000000)">
|
||||
<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>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">id</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">name</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500"></text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal"></text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="person" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="76.2109375" y="21">person</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Group-3" transform="translate(197.000000, 39.000000)">
|
||||
<g id="Oval">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="28.5" r="4"></circle>
|
||||
</g>
|
||||
<g id="Path-3">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-9"></use>
|
||||
<path stroke="#FFFFFF" stroke-width="1" d="M57.6478395,4.18567614 C57.8970791,4.3227579 58.1022035,4.5278823 58.2392853,4.77712188 C58.6385198,5.5030029 58.3737206,6.4150893 57.6478395,6.81432386 L50.7228781,10.6230526 C50.5014107,10.7448598 50.2527545,10.8087288 50,10.8087288 C49.1715729,10.8087288 48.5,10.1371559 48.5,9.30872878 L48.5,1.69127122 C48.5,1.43851677 48.563869,1.18986057 48.6856761,0.968393096 C49.0849107,0.242512071 49.9969971,-0.0222872062 50.7228781,0.376947358 L57.6478395,4.18567614 Z"></path>
|
||||
</g>
|
||||
<path d="M2.5,28.5 C2.5,28.5 2.5,28.5 16.5,28.5 C30.5,28.5 27.5,5.5 40.5,5.5 C49.1666667,5.5 53.5,5.5 53.5,5.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
</g>
|
||||
<g id="Group-3" transform="translate(197.000000, 44.000000)">
|
||||
<g id="Oval">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-10"></use>
|
||||
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="47.5" r="4"></circle>
|
||||
</g>
|
||||
<path d="M2.5,47.5 C2.5,47.5 2.5,47.5 16.5,47.5 C30.5,47.5 27.5,0.5 40.5,0.5 C49.1666667,0.5 53.5,0.5 53.5,0.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 12 KiB |
@@ -0,0 +1,133 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="468px" height="121px" viewBox="0 0 468 121" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
|
||||
<title>BelongsToSchema</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="200" height="103" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" 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="200" height="103" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" 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>
|
||||
<circle id="path-8" cx="200.5" cy="67.5" r="3.5"></circle>
|
||||
<path d="M254.40688,43.6237841 L247.481919,39.8150553 C246.997998,39.5488989 246.38994,39.7254318 246.123784,40.2093525 C246.042579,40.3569975 246,40.5227683 246,40.6912712 L246,48.3087288 C246,48.8610135 246.447715,49.3087288 247,49.3087288 C247.168503,49.3087288 247.334274,49.2661494 247.481919,49.1849447 L254.40688,45.3762159 C254.890801,45.1100595 255.067334,44.5020019 254.801177,44.0180813 C254.709789,43.8519215 254.57304,43.7151719 254.40688,43.6237841 Z" id="path-9"></path>
|
||||
</defs>
|
||||
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<g id="BelongsToSchema" transform="translate(9.000000, 6.000000)">
|
||||
<g id="Table">
|
||||
<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>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">id</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">authorId</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">title</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="book" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="82.9443359" y="21">book</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-2" transform="translate(250.000000, 0.000000)">
|
||||
<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>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">id</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">name</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500"></text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal"></text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="author" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="77.3867188" y="21">author</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Oval">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<circle stroke="#FFFFFF" stroke-width="1" cx="200.5" cy="67.5" r="4"></circle>
|
||||
</g>
|
||||
<g id="Path-3">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-9"></use>
|
||||
<path stroke="#FFFFFF" stroke-width="1" d="M254.64784,43.1856761 C254.897079,43.3227579 255.102204,43.5278823 255.239285,43.7771219 C255.63852,44.5030029 255.373721,45.4150893 254.64784,45.8143239 L247.722878,49.6230526 C247.501411,49.7448598 247.252754,49.8087288 247,49.8087288 C246.171573,49.8087288 245.5,49.1371559 245.5,48.3087288 L245.5,40.6912712 C245.5,40.4385168 245.563869,40.1898606 245.685676,39.9683931 C246.084911,39.2425121 246.996997,38.9777128 247.722878,39.3769474 L254.64784,43.1856761 Z"></path>
|
||||
</g>
|
||||
<path d="M199.5,67.5 C199.5,67.5 199.5,67.5 213.5,67.5 C227.5,67.5 224.5,44.5 237.5,44.5 C246.166667,44.5 250.5,44.5 250.5,44.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 10 KiB |
@@ -0,0 +1,135 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="468px" height="121px" viewBox="0 0 468 121" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
|
||||
<title>HasManySchema</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="200" height="103" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" 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="200" height="103" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" 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>
|
||||
<circle id="path-8" cx="3.5" cy="28.5" r="3.5"></circle>
|
||||
<path d="M57.4068802,4.62378409 L50.4819187,0.815055312 C49.9979981,0.548898936 49.3899405,0.725431787 49.1237841,1.20935247 C49.0425794,1.35699745 49,1.52276825 49,1.69127122 L49,9.30872878 C49,9.86101353 49.4477153,10.3087288 50,10.3087288 C50.168503,10.3087288 50.3342738,10.2661494 50.4819187,10.1849447 L57.4068802,6.37621591 C57.8908008,6.11005953 58.0673337,5.50200193 57.8011773,5.01808125 C57.7097895,4.85192153 57.5730399,4.71517193 57.4068802,4.62378409 Z" id="path-9"></path>
|
||||
</defs>
|
||||
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<g id="HasManySchema" transform="translate(9.000000, 6.000000)">
|
||||
<g id="Table" transform="translate(250.000000, 0.000000)">
|
||||
<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>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">id</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">authorId</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">title</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="book" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="82.9443359" y="21">book</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-2">
|
||||
<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>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">id</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">name</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500"></text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal"></text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="author" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="77.3867188" y="21">author</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Group" transform="translate(224.000000, 55.000000) scale(-1, 1) translate(-224.000000, -55.000000) translate(195.000000, 39.000000)">
|
||||
<g id="Oval">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="28.5" r="4"></circle>
|
||||
</g>
|
||||
<g id="Path-3">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-9"></use>
|
||||
<path stroke="#FFFFFF" stroke-width="1" d="M57.6478395,4.18567614 C57.8970791,4.3227579 58.1022035,4.5278823 58.2392853,4.77712188 C58.6385198,5.5030029 58.3737206,6.4150893 57.6478395,6.81432386 L50.7228781,10.6230526 C50.5014107,10.7448598 50.2527545,10.8087288 50,10.8087288 C49.1715729,10.8087288 48.5,10.1371559 48.5,9.30872878 L48.5,1.69127122 C48.5,1.43851677 48.563869,1.18986057 48.6856761,0.968393096 C49.0849107,0.242512071 49.9969971,-0.0222872062 50.7228781,0.376947358 L57.6478395,4.18567614 Z"></path>
|
||||
</g>
|
||||
<path d="M2.5,28.5 C2.5,28.5 2.5,28.5 16.5,28.5 C30.5,28.5 27.5,5.5 40.5,5.5 C49.1666667,5.5 53.5,5.5 53.5,5.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 10 KiB |
@@ -0,0 +1,185 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="468px" height="200px" viewBox="0 0 468 200" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
|
||||
<title>HasManyThroughSchema</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="200" height="103" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" 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="200" height="79" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-14.6%" width="114.5%" height="136.7%" 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="200" height="79" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-14.6%" width="114.5%" height="136.7%" 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>
|
||||
<circle id="path-11" cx="3.5" cy="44.5" r="3.5"></circle>
|
||||
<path d="M57.4068802,4.62378409 L50.4819187,0.815055312 C49.9979981,0.548898936 49.3899405,0.725431787 49.1237841,1.20935247 C49.0425794,1.35699745 49,1.52276825 49,1.69127122 L49,9.30872878 C49,9.86101353 49.4477153,10.3087288 50,10.3087288 C50.168503,10.3087288 50.3342738,10.2661494 50.4819187,10.1849447 L57.4068802,6.37621591 C57.8908008,6.11005953 58.0673337,5.50200193 57.8011773,5.01808125 C57.7097895,4.85192153 57.5730399,4.71517193 57.4068802,4.62378409 Z" id="path-12"></path>
|
||||
<circle id="path-13" cx="3.5" cy="3.5" r="3.5"></circle>
|
||||
<path d="M57.4068802,42.6237841 L50.4819187,38.8150553 C49.9979981,38.5488989 49.3899405,38.7254318 49.1237841,39.2093525 C49.0425794,39.3569975 49,39.5227683 49,39.6912712 L49,47.3087288 C49,47.8610135 49.4477153,48.3087288 50,48.3087288 C50.168503,48.3087288 50.3342738,48.2661494 50.4819187,48.1849447 L57.4068802,44.3762159 C57.8908008,44.1100595 58.0673337,43.5020019 57.8011773,43.0180813 C57.7097895,42.8519215 57.5730399,42.7151719 57.4068802,42.6237841 Z" id="path-14"></path>
|
||||
</defs>
|
||||
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<g id="HasManyThroughSchema" transform="translate(9.000000, 6.000000)">
|
||||
<g id="Table" transform="translate(250.000000, 40.000000)">
|
||||
<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>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">countryCode</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">citizenId</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">issueDate</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">date</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="passport" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="69.3613281" y="21">passport</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-2">
|
||||
<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>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="80" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">code</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">name</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="country" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="73.3740234" y="21">country</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-2" transform="translate(0.000000, 103.000000)">
|
||||
<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="#005CC5" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="80" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-9)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">id</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-9)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">name</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="citizen" mask="url(#mask-9)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="77.1782227" y="21">citizen</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Group" transform="translate(224.000000, 63.000000) scale(-1, 1) translate(-224.000000, -63.000000) translate(195.000000, 39.000000)">
|
||||
<g id="Oval">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-11"></use>
|
||||
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="44.5" r="4"></circle>
|
||||
</g>
|
||||
<g id="Path-3">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-12"></use>
|
||||
<path stroke="#FFFFFF" stroke-width="1" d="M57.6478395,4.18567614 C57.8970791,4.3227579 58.1022035,4.5278823 58.2392853,4.77712188 C58.6385198,5.5030029 58.3737206,6.4150893 57.6478395,6.81432386 L50.7228781,10.6230526 C50.5014107,10.7448598 50.2527545,10.8087288 50,10.8087288 C49.1715729,10.8087288 48.5,10.1371559 48.5,9.30872878 L48.5,1.69127122 C48.5,1.43851677 48.563869,1.18986057 48.6856761,0.968393096 C49.0849107,0.242512071 49.9969971,-0.0222872062 50.7228781,0.376947358 L57.6478395,4.18567614 Z"></path>
|
||||
</g>
|
||||
<path d="M2.5,44.5 C2.5,44.5 2.5,44.5 16.5,44.5 C30.5,44.5 27.5,5.5 40.5,5.5 C49.1666667,5.5 53.5,5.5 53.5,5.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
</g>
|
||||
<g id="Group" transform="translate(224.000000, 128.500000) scale(-1, 1) translate(-224.000000, -128.500000) translate(195.000000, 104.000000)">
|
||||
<g id="Oval">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-13"></use>
|
||||
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="3.5" r="4"></circle>
|
||||
</g>
|
||||
<g id="Path-3">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-14"></use>
|
||||
<path stroke="#FFFFFF" stroke-width="1" d="M57.6478395,42.1856761 C57.8970791,42.3227579 58.1022035,42.5278823 58.2392853,42.7771219 C58.6385198,43.5030029 58.3737206,44.4150893 57.6478395,44.8143239 L50.7228781,48.6230526 C50.5014107,48.7448598 50.2527545,48.8087288 50,48.8087288 C49.1715729,48.8087288 48.5,48.1371559 48.5,47.3087288 L48.5,39.6912712 C48.5,39.4385168 48.563869,39.1898606 48.6856761,38.9683931 C49.0849107,38.2425121 49.9969971,37.9777128 50.7228781,38.3769474 L57.6478395,42.1856761 Z"></path>
|
||||
</g>
|
||||
<path d="M2.5,3.5 C2.5,3.5 2.5,3.5 16.5,3.5 C30.5,3.5 27.5,43.5 40.5,43.5 C49.1666667,43.5 53.5,43.5 53.5,43.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 15 KiB |
@@ -0,0 +1,153 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="468px" height="145px" viewBox="0 0 468 145" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
|
||||
<title>HasOneSchema</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="200" height="127" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-9.1%" width="114.5%" height="122.8%" 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="200" height="127" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-9.1%" width="114.5%" height="122.8%" 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>
|
||||
<circle id="path-8" cx="3.5" cy="28.5" r="3.5"></circle>
|
||||
<path d="M57.4068802,4.62378409 L50.4819187,0.815055312 C49.9979981,0.548898936 49.3899405,0.725431787 49.1237841,1.20935247 C49.0425794,1.35699745 49,1.52276825 49,1.69127122 L49,9.30872878 C49,9.86101353 49.4477153,10.3087288 50,10.3087288 C50.168503,10.3087288 50.3342738,10.2661494 50.4819187,10.1849447 L57.4068802,6.37621591 C57.8908008,6.11005953 58.0673337,5.50200193 57.8011773,5.01808125 C57.7097895,4.85192153 57.5730399,4.71517193 57.4068802,4.62378409 Z" id="path-9"></path>
|
||||
</defs>
|
||||
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<g id="HasOneSchema" transform="translate(9.000000, 6.000000)">
|
||||
<g id="Table" transform="translate(250.000000, 0.000000)">
|
||||
<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>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="128" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">id</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">countryCode</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">population</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 103.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">density</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">double</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="demographics" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="50.894043" y="21">demographics</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-2">
|
||||
<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>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="128" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">code</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">name</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500"></text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal"></text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 103.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500"></text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal"></text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="country" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="73.3740234" y="21">country</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Group" transform="translate(224.000000, 55.000000) scale(-1, 1) translate(-224.000000, -55.000000) translate(195.000000, 39.000000)">
|
||||
<g id="Oval">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="28.5" r="4"></circle>
|
||||
</g>
|
||||
<g id="Path-3">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-9"></use>
|
||||
<path stroke="#FFFFFF" stroke-width="1" d="M57.6478395,4.18567614 C57.8970791,4.3227579 58.1022035,4.5278823 58.2392853,4.77712188 C58.6385198,5.5030029 58.3737206,6.4150893 57.6478395,6.81432386 L50.7228781,10.6230526 C50.5014107,10.7448598 50.2527545,10.8087288 50,10.8087288 C49.1715729,10.8087288 48.5,10.1371559 48.5,9.30872878 L48.5,1.69127122 C48.5,1.43851677 48.563869,1.18986057 48.6856761,0.968393096 C49.0849107,0.242512071 49.9969971,-0.0222872062 50.7228781,0.376947358 L57.6478395,4.18567614 Z"></path>
|
||||
</g>
|
||||
<path d="M2.5,28.5 C2.5,28.5 2.5,28.5 16.5,28.5 C30.5,28.5 27.5,5.5 40.5,5.5 C49.1666667,5.5 53.5,5.5 53.5,5.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 12 KiB |
@@ -0,0 +1,198 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="468px" height="247px" viewBox="0 0 468 247" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
|
||||
<title>HasOneThroughSchema</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="200" height="79" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-14.6%" width="114.5%" height="136.7%" 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="200" height="103" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" 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="200" height="102" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-11.3%" width="114.5%" height="128.4%" 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>
|
||||
<circle id="path-11" cx="3.5" cy="56.5" r="3.5"></circle>
|
||||
<path d="M57.4068802,4.62378409 L50.4819187,0.815055312 C49.9979981,0.548898936 49.3899405,0.725431787 49.1237841,1.20935247 C49.0425794,1.35699745 49,1.52276825 49,1.69127122 L49,9.30872878 C49,9.86101353 49.4477153,10.3087288 50,10.3087288 C50.168503,10.3087288 50.3342738,10.2661494 50.4819187,10.1849447 L57.4068802,6.37621591 C57.8908008,6.11005953 58.0673337,5.50200193 57.8011773,5.01808125 C57.7097895,4.85192153 57.5730399,4.71517193 57.4068802,4.62378409 Z" id="path-12"></path>
|
||||
<circle id="path-13" cx="3.5" cy="3.5" r="3.5"></circle>
|
||||
<path d="M57.4068802,54.6237841 L50.4819187,50.8150553 C49.9979981,50.5488989 49.3899405,50.7254318 49.1237841,51.2093525 C49.0425794,51.3569975 49,51.5227683 49,51.6912712 L49,59.3087288 C49,59.8610135 49.4477153,60.3087288 50,60.3087288 C50.168503,60.3087288 50.3342738,60.2661494 50.4819187,60.1849447 L57.4068802,56.3762159 C57.8908008,56.1100595 58.0673337,55.5020019 57.8011773,55.0180813 C57.7097895,54.8519215 57.5730399,54.7151719 57.4068802,54.6237841 Z" id="path-14"></path>
|
||||
</defs>
|
||||
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<g id="HasOneThroughSchema" transform="translate(9.000000, 6.000000)">
|
||||
<g id="Table" transform="translate(250.000000, 75.000000)">
|
||||
<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>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="80" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">id</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">name</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="library" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="77.800293" y="21">library</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Group-2">
|
||||
<g id="Table-Copy-2">
|
||||
<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>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">id</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">libraryId</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">title</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="book" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="82.9443359" y="21">book</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-2" transform="translate(0.000000, 127.000000)">
|
||||
<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="#005CC5" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="103" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-9)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">libraryId</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-9)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">street</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-9)">
|
||||
<g transform="translate(0.000000, 78.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">city</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="address" mask="url(#mask-9)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="72.4545898" y="21">address</tspan>
|
||||
</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Group" transform="translate(226.000000, 93.500000) scale(1, -1) translate(-226.000000, -93.500000) translate(197.000000, 63.000000)">
|
||||
<g id="Oval">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-11"></use>
|
||||
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="56.5" r="4"></circle>
|
||||
</g>
|
||||
<g id="Path-3">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-12"></use>
|
||||
<path stroke="#FFFFFF" stroke-width="1" d="M57.6478395,4.18567614 C57.8970791,4.3227579 58.1022035,4.5278823 58.2392853,4.77712188 C58.6385198,5.5030029 58.3737206,6.4150893 57.6478395,6.81432386 L50.7228781,10.6230526 C50.5014107,10.7448598 50.2527545,10.8087288 50,10.8087288 C49.1715729,10.8087288 48.5,10.1371559 48.5,9.30872878 L48.5,1.69127122 C48.5,1.43851677 48.563869,1.18986057 48.6856761,0.968393096 C49.0849107,0.242512071 49.9969971,-0.0222872062 50.7228781,0.376947358 L57.6478395,4.18567614 Z"></path>
|
||||
</g>
|
||||
<path d="M2.5,56.5 C2.5,56.5 2.5,56.5 16.5,56.5 C30.5,56.5 27.5,5.5 40.5,5.5 C49.1666667,5.5 53.5,5.5 53.5,5.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
</g>
|
||||
<g id="Group" transform="translate(226.000000, 143.500000) scale(1, -1) translate(-226.000000, -143.500000) translate(197.000000, 113.000000)">
|
||||
<g id="Oval">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-13"></use>
|
||||
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="3.5" r="4"></circle>
|
||||
</g>
|
||||
<g id="Path-3">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-14"></use>
|
||||
<path stroke="#FFFFFF" stroke-width="1" d="M57.6478395,54.1856761 C57.8970791,54.3227579 58.1022035,54.5278823 58.2392853,54.7771219 C58.6385198,55.5030029 58.3737206,56.4150893 57.6478395,56.8143239 L50.7228781,60.6230526 C50.5014107,60.7448598 50.2527545,60.8087288 50,60.8087288 C49.1715729,60.8087288 48.5,60.1371559 48.5,59.3087288 L48.5,51.6912712 C48.5,51.4385168 48.563869,51.1898606 48.6856761,50.9683931 C49.0849107,50.2425121 49.9969971,49.9777128 50.7228781,50.3769474 L57.6478395,54.1856761 Z"></path>
|
||||
</g>
|
||||
<path d="M2.5,3.5 C2.5,3.5 2.5,3.5 16.5,3.5 C30.5,3.5 27.5,55.5 40.5,55.5 C49.1666667,55.5 53.5,55.5 53.5,55.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 16 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
|
||||
@@ -0,0 +1,91 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="233px" height="121px" viewBox="0 0 233 121" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
|
||||
<title>RecursiveSchema</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="200" height="103" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" 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>
|
||||
<circle id="path-5" cx="22.5" cy="28.5" r="3.5"></circle>
|
||||
<path d="M27.4068802,4.62378409 L20.4819187,0.815055312 C19.9979981,0.548898936 19.3899405,0.725431787 19.1237841,1.20935247 C19.0425794,1.35699745 19,1.52276825 19,1.69127122 L19,9.30872878 C19,9.86101353 19.4477153,10.3087288 20,10.3087288 C20.168503,10.3087288 20.3342738,10.2661494 20.4819187,10.1849447 L27.4068802,6.37621591 C27.8908008,6.11005953 28.0673337,5.50200193 27.8011773,5.01808125 C27.7097895,4.85192153 27.5730399,4.71517193 27.4068802,4.62378409 Z" id="path-6"></path>
|
||||
</defs>
|
||||
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<g id="RecursiveSchema" transform="translate(9.000000, 6.000000)">
|
||||
<g id="Table-Copy-2">
|
||||
<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>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">id</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">managerId</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">name</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500"></text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal"></text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="employee" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="66.8730469" y="21">employee</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Group" transform="translate(209.000000, 55.000000) scale(-1, 1) translate(-209.000000, -55.000000) translate(195.000000, 39.000000)">
|
||||
<g id="Oval">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<circle stroke="#FFFFFF" stroke-width="1" cx="22.5" cy="28.5" r="4"></circle>
|
||||
</g>
|
||||
<g id="Path-3">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-6"></use>
|
||||
<path stroke="#FFFFFF" stroke-width="1" d="M27.6478395,4.18567614 C27.8970791,4.3227579 28.1022035,4.5278823 28.2392853,4.77712188 C28.6385198,5.5030029 28.3737206,6.4150893 27.6478395,6.81432386 L20.7228781,10.6230526 C20.5014107,10.7448598 20.2527545,10.8087288 20,10.8087288 C19.1715729,10.8087288 18.5,10.1371559 18.5,9.30872878 L18.5,1.69127122 C18.5,1.43851677 18.563869,1.18986057 18.6856761,0.968393096 C19.0849107,0.242512071 19.9969971,-0.0222872062 20.7228781,0.376947358 L27.6478395,4.18567614 Z"></path>
|
||||
</g>
|
||||
<path d="M23.5,28.5 C23.5,28.5 19.1666667,28.5 10.5,28.5 C-2.5,28.5 -2.5,5.5 10.5,5.5 C19.1666667,5.5 23.5,5.5 23.5,5.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 7.1 KiB |
@@ -0,0 +1,110 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="292px" height="166px" viewBox="0 0 292 166" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
|
||||
<title>TreeOfAssociationKeys</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="119" height="28" rx="10"></rect>
|
||||
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.6%" 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="119" height="28" rx="10"></rect>
|
||||
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.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="119" height="28" rx="10"></rect>
|
||||
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.6%" 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="119" height="28" rx="10"></rect>
|
||||
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.6%" 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>
|
||||
</defs>
|
||||
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<g id="TreeOfAssociationKeys" transform="translate(9.000000, 6.000000)">
|
||||
<path d="M60,78 L60,114" id="Line" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<path id="Line-decoration-1" d="M57,103.2 L60,114 L63,103.2" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<path d="M139,14 L77,57" id="Line" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<path id="Line-decoration-1" d="M84.1648227,48.3799469 L77,57 L87.5842165,53.3102356" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<path d="M140,14 L206,57" id="Line-Copy" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<path id="Line-Copy-decoration-1" d="M195.313438,53.61808 L206,57 L198.58872,48.5909017" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<g id="Table-Copy-2" transform="translate(80.000000, 0.000000)">
|
||||
<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>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
|
||||
</g>
|
||||
<text id="root" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="45.390625" y="19">root</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-3" transform="translate(0.000000, 62.000000)">
|
||||
<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="#417505" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
|
||||
</g>
|
||||
<text id=""author"" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="30.2421875" y="19">"author"</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-5" transform="translate(155.000000, 62.000000)">
|
||||
<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="#9013FE" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
|
||||
</g>
|
||||
<text id=""coverImage"" mask="url(#mask-9)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="12.8037109" y="19">"coverImage"</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-4" transform="translate(0.000000, 120.000000)">
|
||||
<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="#D0021B" fill-rule="evenodd" xlink:href="#path-11"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-11"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
|
||||
</g>
|
||||
<text id=""country"" mask="url(#mask-12)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="26.2294922" y="19">"country"</tspan>
|
||||
</text>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 8.5 KiB |
@@ -0,0 +1,130 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="421px" height="227px" viewBox="0 0 421 227" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
|
||||
<title>TreeOfAssociationKeysMapping</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="119" height="28" rx="10"></rect>
|
||||
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.6%" 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="119" height="28" rx="10"></rect>
|
||||
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.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="119" height="28" rx="10"></rect>
|
||||
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.6%" 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="119" height="28" rx="10"></rect>
|
||||
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.6%" 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>
|
||||
</defs>
|
||||
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<g id="TreeOfAssociationKeysMapping" transform="translate(0.000000, 6.000000)">
|
||||
<g id="Group-4">
|
||||
<path d="M83,36 L83,186" id="Line-Copy-2" stroke="#727272" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="4,8"></path>
|
||||
<path d="M159,96 L159,186" id="Line-Copy-3" stroke="#727272" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="4,8"></path>
|
||||
<path d="M246,156 L246,186" id="Line-Copy-4" stroke="#727272" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="4,8"></path>
|
||||
<path d="M352,96 L352,186" id="Line-Copy-5" stroke="#727272" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="4,8"></path>
|
||||
<path d="M85,14 L136,57" id="Line" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<path id="Line-decoration-1" d="M125.809367,52.3319166 L136,57 L129.676951,47.7447827" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<path d="M85,14 L292,57" id="Line" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<path id="Line-decoration-1" d="M280.815576,57.7407092 L292,57 L282.035901,51.8661193" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<path d="M156,72 L207,115" id="Line" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<path id="Line-decoration-1" d="M196.809367,110.331917 L207,115 L200.676951,105.744783" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<g id="Table-Copy-6" transform="translate(23.000000, 0.000000)">
|
||||
<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>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
|
||||
</g>
|
||||
<text id="root" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="45.390625" y="19">root</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-7" transform="translate(100.000000, 62.000000)">
|
||||
<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="#417505" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
|
||||
</g>
|
||||
<text id=""author"" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="30.2421875" y="19">"author"</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-8" transform="translate(293.000000, 62.000000)">
|
||||
<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="#9013FE" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
|
||||
</g>
|
||||
<text id=""coverImage"" mask="url(#mask-9)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="12.8037109" y="19">"coverImage"</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-9" transform="translate(187.000000, 120.000000)">
|
||||
<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="#D0021B" fill-rule="evenodd" xlink:href="#path-11"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-11"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
|
||||
</g>
|
||||
<text id=""country"" mask="url(#mask-12)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="26.2294922" y="19">"country"</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Group-5" transform="translate(0.000000, 191.000000)" font-family="Menlo-Regular, Menlo" font-size="14" font-weight="normal">
|
||||
<text id="SELECT-book.*,-autho">
|
||||
<tspan x="0" y="13" fill="#404040">SELECT </tspan>
|
||||
<tspan x="59.0009766" y="13" fill="#4A90E2">book.*</tspan>
|
||||
<tspan x="109.573242" y="13" fill="#404040">, </tspan>
|
||||
<tspan x="126.430664" y="13" fill="#417505">author.*</tspan>
|
||||
<tspan x="193.860352" y="13" fill="#404040">, </tspan>
|
||||
<tspan x="210.717773" y="13" fill="#D0021B">country.*</tspan>
|
||||
<tspan x="286.576172" y="13" fill="#404040">, </tspan>
|
||||
<tspan x="303.433594" y="13" fill="#9013FE">coverImage.*</tspan>
|
||||
<tspan x="404.578125" y="13" fill="#404040"></tspan>
|
||||
<tspan x="0" y="29" fill="#404040">FROM …</tspan>
|
||||
</text>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 10 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 |
@@ -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
|
||||
@@ -1 +1 @@
|
||||
The main documentation is available in [README.md](../../../#documentation).
|
||||
The main documentation is available in [README.md](../README.md#documentation).
|
||||
@@ -10,24 +10,21 @@ To release a new GRDB version:
|
||||
- Build and run GRDBDemoiOS in Release configuration on a device
|
||||
- Archive GRDBDemoiOS
|
||||
- Check for performance regression with GRDBOSXPerformanceTests
|
||||
- On SDK upgrade, update Support/sqlite3.h
|
||||
- On https://github.com/groue/sqlcipher.git upgrade, update SQLCipher version in README.md
|
||||
- On https://github.com/swiftlyfalling/SQLiteLib upgrade, update SQLite version in README.md and Documentation/CustomSQLiteBuilds.md
|
||||
- Update GRDB version number and release date in:
|
||||
- Makefile
|
||||
- CHANGELOG.md
|
||||
- Documentation/CustomSQLiteBuilds.md
|
||||
- Documentation/ExtendingGRDB.md
|
||||
- GRDB.swift.podspec
|
||||
- GRDBCipher.podspec
|
||||
- README.md
|
||||
- Support/Info.plist
|
||||
- Commit and tag
|
||||
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
|
||||
- Push to the master branch
|
||||
- Push to the Swift3 branch
|
||||
- `pod trunk push --allow-warnings GRDB.swift.podspec`
|
||||
- `pod trunk push --allow-warnings GRDBCipher.podspec`
|
||||
- `make doc`, and update index.html in the `gh-pages` branch
|
||||
- Update http://github.com/groue/GRDBDemo
|
||||
- Update http://github.com/groue/WWDCCompanion
|
||||
- Update [performance comparison](https://github.com/groue/GRDB.swift/wiki/Performance):
|
||||
|
||||
`make test_performance | Tests/parsePerformanceTests.rb | Tests/generatePerformanceReport.rb`
|
||||
@@ -0,0 +1,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
|
||||
@@ -0,0 +1,315 @@
|
||||
Why Adopt GRDB?
|
||||
===============
|
||||
|
||||
This document aims at exposing why GRDB could become your favorite database library.
|
||||
|
||||
We'll start with a few [core principles](#core-principles), so that you see where this library aims at. Then we'll see how GRDB [solves problems](#solving-problems) that developers often face when they use database libraries such as FMDB, FCModel, SQLite.swift, Core Data, or Realm.
|
||||
|
||||
|
||||
## Core Principles
|
||||
|
||||
### It is generally easier to access a database through "record types".
|
||||
|
||||
This is because a database row is not an easy type to deal with, and will never be, compared to a regular model. `player.name` looks and feels more natural than `playerRow["name"]`, doesn't it?
|
||||
|
||||
The reputation of "active records" and ORMs has been tarnished by the recent focus on immutability, memory safety, and functional idioms that comes with languages like Swift and Rust. Features of 1st-generation records such as auto-updating, uniquing, lazy loading of relations, etc. are now considered ill-advised, if not plain harmful because of the multi-threading headaches they cause.
|
||||
|
||||
Yet recent ORMs such as Rust's [Diesel] have shown that it is possible to build record types that behave as plain and simple values. GRDB belongs to this family.
|
||||
|
||||
|
||||
### Raw SQL is sometimes the correct tool for the job.
|
||||
|
||||
Complex database queries sometimes need to be prototyped and debugged in an SQL shell. Once perfected, the process of translating this raw SQL query into calls to a query builder can be long and painful, with no guarantee of success. And the resulting code often lacks the legibility of the initial SQL. When this happens, the query builder is no longer useful: whoever wants to write raw SQL should always be welcome.
|
||||
|
||||
|
||||
### The database file is the single source of truth.
|
||||
|
||||
Each Core Data's managed object context has its own version of the database. This can be useful when developing a macOS application full of inspector panels and nested undo stacks. But that's about it.
|
||||
|
||||
In the same vein, each application thread has its own version of a Realm database, with non trivial synchronization points.
|
||||
|
||||
Conversely, GRDB assumes that many apps want to use the database as a reliable and unambiguous storage.
|
||||
|
||||
|
||||
### Applications developers have specific needs.
|
||||
|
||||
GRDB puts all bets on SQLite, and focuses on front-end GUI applications.
|
||||
|
||||
This means that dealing with servers, MySQL, or PostgreSQL is out of scope. GRDB is not an alternative to IBM's [Swift-Kuery], Vapor's [Fluent], or Perfect's [StORM].
|
||||
|
||||
Focusing on SQLite and applications has allowed GRDB to build features usually only found in company-sponsored libraries: migrations, record comparison, database observation, multi-threading safety, table view animations, support for reactive streams...
|
||||
|
||||
The bet of GRDB is that developers can take great profit from a library that provides efficient and community-tested solutions to existing problems. For example, one can not address the multithreading difficulties of Core Data or Realm without looking at database concurrency and records straight in the face.
|
||||
|
||||
Since you don't have to take my words for granted, we'll now see how GRDB actually solves common problems that developers face with other database libraries.
|
||||
|
||||
|
||||
## Solving Problems
|
||||
|
||||
What is the purpose of the above principles, if not providing solutions to difficulties and limitations of other persistence libraries?
|
||||
|
||||
|
||||
### Allow any Swift struct or class to become a database record
|
||||
|
||||
Most libraries that provide record types want you to subclass a root class: [NSManagedObject](https://developer.apple.com/documentation/coredata/nsmanagedobject), [Realm.Object](https://www.realm.io/docs/swift/latest), [FCModel](https://github.com/marcoarment/FCModel).
|
||||
|
||||
The main problem with those root classes is that they are classes. You can't define records from plain Swift structs, and leverage all advantages of Swift value types: immutability, multi-threading safety, etc.
|
||||
|
||||
With GRDB, any type can become a database record. For example, let's start from this `Place` struct:
|
||||
|
||||
```swift
|
||||
struct Place {
|
||||
var id: Int64?
|
||||
let title: String
|
||||
let coordinate: CLLocationCoordinate2D
|
||||
}
|
||||
```
|
||||
|
||||
By adopting the [FetchableRecord] protocol, places can be loaded from SQL requests:
|
||||
|
||||
```swift
|
||||
extension Place: FetchableRecord { ... }
|
||||
let places = try Place.fetchAll(db, sql: "SELECT * FROM place") // [Place]
|
||||
```
|
||||
|
||||
Add the [TableRecord] protocol, and SQL requests are generated for you:
|
||||
|
||||
```swift
|
||||
extension Place: TableRecord { ... }
|
||||
let place = try Place.fetchOne(db, key: 1) // Place?
|
||||
```
|
||||
|
||||
Add the [PersistableRecord] protocol, and places know how to insert, update and delete themselves:
|
||||
|
||||
```swift
|
||||
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
|
||||
|
||||
As soon as records are immutable values, they can safely be used from different threads. You no longer have to pass object ids or references between threads, as in Core Data or Realm:
|
||||
|
||||
```swift
|
||||
if let player = try Player.fetchOne(db, key: 1) {
|
||||
DispatchQueue.main.async {
|
||||
nameField.text = player.name
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Replace auto-updating records with notifications of database changes
|
||||
|
||||
GRDB records are plain values, like other values in your application. They are not tied to the database. Sometimes you build them from scratch, and sometimes you fetch them:
|
||||
|
||||
```swift
|
||||
let player = Player(name: "arthur", score: 1000)
|
||||
let players = try Player.fetchAll(db)
|
||||
```
|
||||
|
||||
**Fetched records behave just like an in-memory cache of the database content.** Your application is free to decide, on its own, how it should handle the lifetime of those cached values: by ignoring future database changes, by observing database changes and react accordingly, or in any way deemed relevant.
|
||||
|
||||
There are several ways to be notified of database changes. You can build on top of the fundamental but low-level [TransactionObserver] protocol. Usually, you'll use [ValueObservation], which notifies fresh values after each database change, or [FetchedRecordsController], which animates table and collection views. And don't forget [GRDBCombine] and [RxGRDB], two sets of reactive extensions based on [Combine] and [RxSwift]:
|
||||
|
||||
```swift
|
||||
Player.all().rx
|
||||
.fetchAll(in: dbQueue)
|
||||
.subscribe(onNext: { players: [Player] in
|
||||
print("Players have changed")
|
||||
})
|
||||
```
|
||||
|
||||
No matter which observation technique you use, you have common guarantees:
|
||||
|
||||
First, notifications only come from database changes safely saved on disk. This is part of the "database as the single source of truth" core principle. You won't get notifications from unsaved changes or changes that have an opportunity to be rollbacked.
|
||||
|
||||
Next, you choose the dispatch queue on which notifications happen. It can be on the special "writer queue", which allows you to process changes before any other thread has any opportunity to perform further database modifications. But notifications can also happen on the queue of your choice (generally the main queue, by default, as in the example above). Of course, GRDB makes sure notifications happen in the same order as database transactions.
|
||||
|
||||
Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, and even SQL triggers. GRDB roots its notification system in the rock-solid SQLite itself, so that high-level requests and raw SQL queries are equally supported.
|
||||
|
||||
|
||||
### Non-blocking database reads
|
||||
|
||||
GRDB ships with two ways to access databases, [database queues](../README.md#database-queues) and [pools](../README.md#database-pools).
|
||||
|
||||
Database queues look a lot like FMDB's [FMDatabaseQueue](https://github.com/ccgus/fmdb#using-fmdatabasequeue-and-thread-safety): they serialize database accesses in a serial dispatch queue. There is never more than one thread that is accessing the database. This means that a long running database transaction that happens in a background thread, such as the synchronization of your local database from a remote server, can block your UI. As long as the queue is busy, the main thread can't fetch the values it wants to display on screen.
|
||||
|
||||
[Database pools](../README.md#database-pools) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured).
|
||||
|
||||
|
||||
### Strong and clear multi-threading guarantees
|
||||
|
||||
I'd like to compare GRDB's handling of concurrency with other libraries. To be as clear as possible, we'll identify a few threats, or potential sources of bugs, and wonder if those are handled by the library, or left to the host application.
|
||||
|
||||
The more threats are handled by the application, the more skilled and careful a developer has to be in order to avoid them.
|
||||
|
||||
- **Concurrent writes**: Two threads want to write in the database at the same time. SQLite does not allow that.
|
||||
- **Isolation troubles**: As two database queries run one after the other, a concurrent thread sneaks in and modifies the database in between. The two queries can thus perform inconsistent fetches or updates, unless they are properly isolated. Lack of isolation may display funny values on the screen, trigger a relational constraint error, or silently corrupt the database content.
|
||||
- **Conflicts**: The same piece of data is both edited by the application user, and refreshed from a network operation. What will eventually be stored in the database? Can any conflict be noticed?
|
||||
- **Blocked UI**: Can it happen that the UI is blocked because the main thread has to wait for a background thread to release a lock on the database?
|
||||
|
||||
|
||||
| Library | Concurrent Writes | Isolation Trouble | Conflicts | Blocked UI |
|
||||
| ------- | ----------------- | ----------------- | --------- | ---------- |
|
||||
| FMDB's FMDatabase | Handled by the application | Handled by the application | Handled by the application | Handled by the application |
|
||||
| FMDB's FMDatabaseQueue | :white_check_mark: | :white_check_mark: | Handled by the application | UI is blocked |
|
||||
| SQLite.swift | :white_check_mark: | Handled by the application | Handled by the application | Handled by the application |
|
||||
| Core Data | Handled by the application, because of the constant threat of conflict errors | :white_check_mark: | Handled by the application, and it is very difficult because of the subtleties of Core Data's conflict policies | Handled by the application |
|
||||
| GRDB's DatabaseQueue | :white_check_mark: | :white_check_mark: | Handled by the application | UI is blocked |
|
||||
| GRDB's DatabasePool | :white_check_mark: | :white_check_mark: | Handled by the application | :white_check_mark: (as long as the maximum number of readers has not been reached) |
|
||||
|
||||
I had to omit [Realm] and [FCModel] from the list, because I don't know them well enough. Yet I'd bet that Realm shares some behaviors with Core Data, and FCModel shares some behaviors with FMDatabaseQueue.
|
||||
|
||||
We can see that the threat of conflicts is *always* left to the application. Core Data provides conflict policies, but no one can pretend that they are easy to plan, use, or test. This is an argument for leaving the application 100% responsible for conflict handling, in hope that simple ones can be handled in a simple way.
|
||||
|
||||
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 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 [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)
|
||||
.limit(10)
|
||||
.fetchAll(db)
|
||||
|
||||
// SELECT MAX(score) FROM player
|
||||
let maximumScore: Int? = try Player
|
||||
.select(max(scoreColumn))
|
||||
.asRequestOf(Int.self)
|
||||
.fetchOne(db)
|
||||
|
||||
// SELECT book.*, author.*
|
||||
// FROM book
|
||||
// LEFT JOIN author ON author.id = book.authorId
|
||||
let request = Book.including(optional: Book.author)
|
||||
let bookInfos: [BookInfo] = BookInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
But you can always switch to SQL when you want to:
|
||||
|
||||
```swift
|
||||
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, 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>(sql: """
|
||||
SELECT book.*, author.*
|
||||
FROM book
|
||||
LEFT JOIN author ON author.id = book.authorId
|
||||
""")
|
||||
.adapted { db in
|
||||
let adapters = try splittingRowAdapters(columnCounts: [
|
||||
db.columns(in: "book").count,
|
||||
db.columns(in: "author").count])
|
||||
return ScopeAdapter([
|
||||
"book": adapters[0],
|
||||
"author": adapters[1]])
|
||||
}
|
||||
```
|
||||
|
||||
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, sql: "SELECT id, name, score FROM player")
|
||||
while let row = try rows.next() {
|
||||
let id: Int64 = row[0]
|
||||
let name: String = row[1]
|
||||
let score: Int = row[2]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
If this little tour of GRDB has convinced you, the real trip starts here: [GRDB].
|
||||
|
||||
And if you happen to maintain an Objective-C application that uses FMDB, checkout [GRDBObjc]. It provides FMDB-compatible bindings to GRDB, so that you can inject sweet drops of Swift into your app, at your own pace, and at minimal cost.
|
||||
|
||||
Happy GRDB! :gift:
|
||||
|
||||
[Concurrency Guide]: ../README.md#concurrency
|
||||
[Core Data]: https://developer.apple.com/documentation/coredata
|
||||
[DatabasePool]: ../README.md#database-pools
|
||||
[Diesel]: http://diesel.rs
|
||||
[FCModel]: https://github.com/marcoarment/FCModel
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[FetchedRecordsController]: ../README.md#fetchedrecordscontroller
|
||||
[Fluent]: https://github.com/vapor/fluent
|
||||
[FMDB]: http://github.com/ccgus/fmdb
|
||||
[GRDB]: http://github.com/groue/GRDB.swift
|
||||
[GRDBObjc]: http://github.com/groue/GRDBObjc
|
||||
[PersistableRecord]: ../README.md#records
|
||||
[Realm]: http://realm.io
|
||||
[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
|
||||
[TableRecord]: ../README.md#records
|
||||
[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 = '1.1'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A Swift application toolkit for SQLite databases.'
|
||||
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/*.{c,h}'
|
||||
s.module_map = 'Support/module.modulemap'
|
||||
s.framework = 'Foundation'
|
||||
s.library = 'sqlite3'
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '4.3.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.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 = "0810"
|
||||
LastUpgradeVersion = "1030"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -40,8 +40,8 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
codeCoverageEnabled = "YES">
|
||||
codeCoverageEnabled = "YES"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1030"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Release"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56439B2D1F4CA1DC0066043F"
|
||||
BuildableName = "GRDBOSXPerformanceComparisonTests.xctest"
|
||||
BlueprintName = "GRDBOSXPerformanceComparisonTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0730"
|
||||
LastUpgradeVersion = "1030"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0810"
|
||||
LastUpgradeVersion = "1030"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0810"
|
||||
LastUpgradeVersion = "1030"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -26,8 +26,8 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
codeCoverageEnabled = "YES">
|
||||
codeCoverageEnabled = "YES"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0830"
|
||||
LastUpgradeVersion = "1030"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -14,9 +14,9 @@
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56AFC9EE1CB1A8BB00F48B96"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipheriOS"
|
||||
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBtvOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
@@ -26,25 +26,16 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
codeCoverageEnabled = "YES"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56AFCA2B1CB1AA9900F48B96"
|
||||
BuildableName = "GRDBCipheriOSTests.xctest"
|
||||
BlueprintName = "GRDBCipheriOSTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56AFCA841CB1ABC800F48B96"
|
||||
BuildableName = "GRDBCipheriOSEncryptedTests.xctest"
|
||||
BlueprintName = "GRDBCipheriOSEncryptedTests"
|
||||
BlueprintIdentifier = "AAA4DD07230F262000C74B15"
|
||||
BuildableName = "GRDBtvOSTests.xctest"
|
||||
BlueprintName = "GRDBtvOSTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
@@ -52,9 +43,9 @@
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56AFC9EE1CB1A8BB00F48B96"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipheriOS"
|
||||
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBtvOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
@@ -74,9 +65,9 @@
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56AFC9EE1CB1A8BB00F48B96"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipheriOS"
|
||||
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBtvOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
@@ -92,9 +83,9 @@
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56AFC9EE1CB1A8BB00F48B96"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipheriOS"
|
||||
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBtvOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
@@ -11,18 +11,42 @@
|
||||
location = "group:JSONSynchronization.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Record.playground">
|
||||
location = "group:TransactionObserver.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:TransactionObserver.playground">
|
||||
location = "group:Issue156.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:CustomizedDecodingOfDatabaseRows.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Associations.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:MyPlayground.playground">
|
||||
</FileRef>
|
||||
</Group>
|
||||
<FileRef
|
||||
location = "group:CHANGELOG.md">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:README.md">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:TODO.md">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Documentation/ReleaseProcess.md">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Makefile">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:GRDB.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:GRDBCustom.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj">
|
||||
</FileRef>
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>IDEDidComputeMac32BitWarning</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,7 +1,11 @@
|
||||
import Foundation
|
||||
|
||||
import Dispatch
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// Configuration for a DatabaseQueue or DatabasePool.
|
||||
@@ -19,6 +23,53 @@ public struct Configuration {
|
||||
/// Default: false
|
||||
public var readonly: Bool = false
|
||||
|
||||
/// The database label.
|
||||
///
|
||||
/// You can query this label at runtime:
|
||||
///
|
||||
/// var configuration = Configuration()
|
||||
/// configuration.label = "MyDatabase"
|
||||
/// let dbQueue = try DatabaseQueue(path: ..., configuration: configuration)
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// print(db.configuration.label) // Prints "MyDatabase"
|
||||
/// }
|
||||
///
|
||||
/// The database label is also used to name the various dispatch queues
|
||||
/// created by GRDB, visible in debugging sessions and crash logs. However
|
||||
/// those dispatch queue labels are intended for debugging only. Their
|
||||
/// format may change between GRDB releases. Applications should not depend
|
||||
/// on the GRDB dispatch queue labels.
|
||||
///
|
||||
/// If the database label is nil, the current GRDB implementation uses the
|
||||
/// following dispatch queue labels:
|
||||
///
|
||||
/// - `GRDB.DatabaseQueue`: the (unique) dispatch queue of a DatabaseQueue
|
||||
/// - `GRDB.DatabasePool.writer`: the (unique) writer dispatch queue of
|
||||
/// a DatabasePool
|
||||
/// - `GRDB.DatabasePool.reader.N`, where N is 1, 2, ...: one of the reader
|
||||
/// dispatch queue(s) of a DatabasePool. N grows with the number of SQLite
|
||||
/// connections: it may get bigger than the maximum number of concurrent
|
||||
/// readers, as SQLite connections get closed and new ones are opened.
|
||||
/// - `GRDB.DatabasePool.snapshot.N`: the dispatch queue of a
|
||||
/// DatabaseSnapshot. N grows with the number of snapshots.
|
||||
///
|
||||
/// If the database label is not nil, for example "MyDatabase", the current
|
||||
/// GRDB implementation uses the following dispatch queue labels:
|
||||
///
|
||||
/// - `MyDatabase`: the (unique) dispatch queue of a DatabaseQueue
|
||||
/// - `MyDatabase.writer`: the (unique) writer dispatch queue of
|
||||
/// a DatabasePool
|
||||
/// - `MyDatabase.reader.N`, where N is 1, 2, ...: one of the reader
|
||||
/// dispatch queue(s) of a DatabasePool. N grows with the number of SQLite
|
||||
/// connections: it may get bigger than the maximum number of concurrent
|
||||
/// readers, as SQLite connections get closed and new ones are opened.
|
||||
/// - `MyDatabase.snapshot.N`: the dispatch queue of a
|
||||
/// DatabaseSnapshot. N grows with the number of snapshots.
|
||||
///
|
||||
/// The default label is nil.
|
||||
public var label: String? = nil
|
||||
|
||||
/// A function that is called on every statement executed by the database.
|
||||
///
|
||||
/// Default: nil
|
||||
@@ -28,12 +79,27 @@ public struct Configuration {
|
||||
// MARK: - Encryption
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
/// The passphrase for encrypted database.
|
||||
/// The passphrase for the encrypted database.
|
||||
///
|
||||
/// Default: nil
|
||||
public var passphrase: String?
|
||||
|
||||
#endif
|
||||
|
||||
/// If set, allows custom configuration to be run every time
|
||||
/// a new connection is opened.
|
||||
///
|
||||
/// This block is run after the Database's connection has opened, but
|
||||
/// before that connection has been made available to any read/write
|
||||
/// API's.
|
||||
///
|
||||
/// 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
|
||||
|
||||
@@ -42,6 +108,38 @@ public struct Configuration {
|
||||
/// Default: deferred
|
||||
public var defaultTransactionKind: Database.TransactionKind = .deferred
|
||||
|
||||
/// If false, it is a programmer error to leave a transaction opened at the
|
||||
/// end of a database access block.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
///
|
||||
/// // fatal error: A transaction has been left opened at the end of a database access
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.beginTransaction()
|
||||
/// }
|
||||
///
|
||||
/// If true, one can leave opened transaction at the end of database access
|
||||
/// blocks:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.allowsUnsafeTransactions = true
|
||||
/// let dbQueue = DatabaseQueue(configuration: config)
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.beginTransaction()
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.commit()
|
||||
/// }
|
||||
///
|
||||
/// This configuration flag has no effect on DatabasePool readers: those
|
||||
/// never allow leaving a transaction opened at the end of a read access.
|
||||
///
|
||||
/// Default: false
|
||||
public var allowsUnsafeTransactions: Bool = false
|
||||
|
||||
// MARK: - Concurrency
|
||||
|
||||
@@ -56,23 +154,49 @@ 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 the work performed by the database.
|
||||
///
|
||||
/// 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.
|
||||
|
||||
@@ -1,8 +1,22 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// Parts of this file are derived from the Swift.org open source project:
|
||||
//
|
||||
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// MARK: - Array, Sequence, Set extensions
|
||||
|
||||
extension Array {
|
||||
/// Creates an array containing the elements of a cursor.
|
||||
///
|
||||
/// 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() {
|
||||
@@ -11,6 +25,33 @@ extension Array {
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult: Cursor>(
|
||||
_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult)
|
||||
-> FlattenCursor<MapCursor<AnyCursor<Iterator.Element>, SegmentOfResult>>
|
||||
{
|
||||
return AnyCursor(self).flatMap(transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension Set {
|
||||
/// Creates a set containing the elements of a cursor.
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'foo'")
|
||||
/// let strings = try Set(cursor) // ["foo"]
|
||||
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
|
||||
self.init()
|
||||
while let element = try cursor.next() {
|
||||
insert(element)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Cursor
|
||||
|
||||
/// A type that supplies the values of some external resource, one at a time.
|
||||
///
|
||||
/// ## Overview
|
||||
@@ -33,20 +74,12 @@ extension Array {
|
||||
/// - A cursor can not be repeated.
|
||||
///
|
||||
/// The protocol comes with default implementations for many operations similar
|
||||
/// to those defined by Swift's LazySequenceProtocol:
|
||||
///
|
||||
/// - `func contains(Self.Element)`
|
||||
/// - `func contains(where: (Self.Element) throws -> Bool)`
|
||||
/// - `func enumerated()`
|
||||
/// - `func filter((Self.Element) throws -> Bool)`
|
||||
/// - `func first(where: (Self.Element) throws -> Bool)`
|
||||
/// - `func flatMap<ElementOfResult>((Self.Element) throws -> ElementOfResult?)`
|
||||
/// - `func flatMap<SegmentOfResult>((Self.Element) throws -> SegmentOfResult)`
|
||||
/// - `func forEach((Self.Element) throws -> Void)`
|
||||
/// - `func joined()`
|
||||
/// - `func map<T>((Self.Element) throws -> T)`
|
||||
/// - `func reduce<Result>(Result, (Result, Self.Element) throws -> Result)`
|
||||
public protocol Cursor : class {
|
||||
/// to those defined by Swift's Sequence protocol: `contains`, `dropFirst`,
|
||||
/// `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`,
|
||||
/// `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`,
|
||||
/// `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`,
|
||||
/// `suffix`.
|
||||
public protocol Cursor: AnyObject {
|
||||
/// The type of element traversed by the cursor.
|
||||
associatedtype Element
|
||||
|
||||
@@ -55,33 +88,13 @@ public protocol Cursor : class {
|
||||
func next() throws -> Element?
|
||||
}
|
||||
|
||||
/// A type-erased cursor of Element.
|
||||
///
|
||||
/// This cursor forwards its next() method to an arbitrary underlying cursor
|
||||
/// having the same Element type, hiding the specifics of the underlying
|
||||
/// cursor.
|
||||
public class AnyCursor<Element> : Cursor {
|
||||
/// Creates a cursor that wraps a base cursor but whose type depends only on
|
||||
/// the base cursor’s element type
|
||||
public init<C: Cursor>(_ base: C) where C.Element == Element {
|
||||
element = base.next
|
||||
}
|
||||
|
||||
/// Creates a cursor that wraps the given closure in its next() method
|
||||
public init(_ body: @escaping () throws -> Element?) {
|
||||
element = body
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
public func next() throws -> Element? {
|
||||
return try element()
|
||||
}
|
||||
|
||||
private let element: () throws -> Element?
|
||||
}
|
||||
|
||||
extension Cursor {
|
||||
/// Returns a Boolean value indicating whether the cursor contains
|
||||
/// an element.
|
||||
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.
|
||||
///
|
||||
@@ -102,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)")
|
||||
@@ -131,19 +144,123 @@ extension Cursor {
|
||||
|
||||
/// Returns a cursor over the concatenated non-nil results of mapping
|
||||
/// transform over this cursor.
|
||||
public func flatMap<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! }
|
||||
}
|
||||
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult: Sequence>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, IteratorCursor<SegmentOfResult.Iterator>>> {
|
||||
return flatMap { try IteratorCursor(transform($0)) }
|
||||
/// Returns a cursor that skips any initial elements that satisfy
|
||||
/// `predicate`.
|
||||
///
|
||||
/// - Parameter predicate: A closure that takes an element of the cursir as
|
||||
/// its argument and returns `true` if the element should be skipped or
|
||||
/// `false` otherwise. Once `predicate` returns `false` it will not be
|
||||
/// called again.
|
||||
public func drop(while predicate: @escaping (Element) throws -> Bool) -> DropWhileCursor<Self> {
|
||||
return DropWhileCursor(self, predicate: predicate)
|
||||
}
|
||||
|
||||
/// Returns a cursor containing all but the given number of initial
|
||||
/// elements.
|
||||
///
|
||||
/// If the number of elements to drop exceeds the number of elements in
|
||||
/// the cursor, the result is an empty cursor.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropFirst(2))
|
||||
/// // Prints "[3, 4, 5]"
|
||||
/// try print(numbers.dropFirst(10))
|
||||
/// // Prints "[]"
|
||||
///
|
||||
/// - Parameter n: The number of elements to drop from the beginning of
|
||||
/// the cursor. `n` must be greater than or equal to zero.
|
||||
/// - Returns: A cursor starting after the specified number of
|
||||
/// elements.
|
||||
public func dropFirst(_ n: Int) -> DropFirstCursor<Self> {
|
||||
return DropFirstCursor(self, limit: n)
|
||||
}
|
||||
|
||||
/// Returns a cursor containing all but the first element of the cursor.
|
||||
///
|
||||
/// The following example drops the first element from a cursor of integers.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropFirst())
|
||||
/// // Prints "[2, 3, 4, 5]"
|
||||
///
|
||||
/// If the cursor has no elements, the result is an empty cursor.
|
||||
///
|
||||
/// - Returns: A cursor starting after the first element of the cursor.
|
||||
public func dropFirst() -> DropFirstCursor<Self> {
|
||||
return dropFirst(1)
|
||||
}
|
||||
|
||||
/// Returns an array containing all but the given number of final
|
||||
/// elements.
|
||||
///
|
||||
/// The cursor must be finite. If the number of elements to drop exceeds
|
||||
/// the number of elements in the cursor, the result is an empty array.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropLast(2))
|
||||
/// // Prints "[1, 2, 3]"
|
||||
/// try print(numbers.dropLast(10))
|
||||
/// // Prints "[]"
|
||||
///
|
||||
/// - Parameter n: The number of elements to drop off the end of the
|
||||
/// cursor. `n` must be greater than or equal to zero.
|
||||
/// - Returns: An array leaving off the specified number of elements.
|
||||
public func dropLast(_ n: Int) throws -> [Element] {
|
||||
GRDBPrecondition(n >= 0, "Can't drop a negative number of elements from a cursor")
|
||||
if n == 0 { return try Array(self) }
|
||||
|
||||
var result: [Element] = []
|
||||
var ringBuffer: [Element] = []
|
||||
var i = ringBuffer.startIndex
|
||||
|
||||
while let element = try next() {
|
||||
if ringBuffer.count < n {
|
||||
ringBuffer.append(element)
|
||||
} else {
|
||||
result.append(ringBuffer[i])
|
||||
ringBuffer[i] = element
|
||||
i = ringBuffer.index(after: i) % n
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/// Returns an array containing all but the last element of the cursor.
|
||||
///
|
||||
/// The following example drops the last element from a cursor of integers.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropLast())
|
||||
/// // Prints "[1, 2, 3, 4]"
|
||||
///
|
||||
/// If the cursor has no elements, the result is an empty cursor.
|
||||
///
|
||||
/// - Returns: An array leaving off the last element of the cursor.
|
||||
public func dropLast() throws -> [Element] {
|
||||
return try dropLast(1)
|
||||
}
|
||||
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, SegmentOfResult>> {
|
||||
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>(_ transform: @escaping (Element) throws -> SegmentOfResult)
|
||||
-> FlattenCursor<MapCursor<Self, SegmentOfResult>>
|
||||
where SegmentOfResult: Cursor
|
||||
{
|
||||
return map(transform).joined()
|
||||
}
|
||||
|
||||
@@ -160,17 +277,152 @@ extension Cursor {
|
||||
return MapCursor(self, transform)
|
||||
}
|
||||
|
||||
/// Returns the result of calling the given combining closure with each
|
||||
/// element of this sequence and an accumulating value.
|
||||
public func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) throws -> Result {
|
||||
var result = initialResult
|
||||
while let element = try next() {
|
||||
result = try nextPartialResult(result, element)
|
||||
/// Returns the maximum element in the cursor, using the given predicate as
|
||||
/// the comparison between elements.
|
||||
///
|
||||
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
|
||||
/// if its first argument should be ordered before its second
|
||||
/// argument; otherwise, `false`.
|
||||
/// - Returns: The cursor's maximum element, according to
|
||||
/// `areInIncreasingOrder`. If the cursor has no elements, returns `nil`.
|
||||
public func max(by areInIncreasingOrder: (Element, Element) throws -> Bool) throws -> Element? {
|
||||
guard var result = try next() else {
|
||||
return nil
|
||||
}
|
||||
while let e = try next() {
|
||||
if try areInIncreasingOrder(result, e) {
|
||||
result = e
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/// Returns the minimum element in the cursor, using the given predicate as
|
||||
/// the comparison between elements.
|
||||
///
|
||||
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
|
||||
/// if its first argument should be ordered before its second
|
||||
/// argument; otherwise, `false`.
|
||||
/// - Returns: The cursor's minimum element, according to
|
||||
/// `areInIncreasingOrder`. If the cursor has no elements, returns `nil`.
|
||||
public func min(by areInIncreasingOrder: (Element, Element) throws -> Bool) throws -> Element? {
|
||||
guard var result = try next() else {
|
||||
return nil
|
||||
}
|
||||
while let e = try next() {
|
||||
if try areInIncreasingOrder(e, result) {
|
||||
result = e
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/// Returns a cursor, up to the specified maximum length, containing the
|
||||
/// initial elements of the cursor.
|
||||
///
|
||||
/// If the maximum length exceeds the number of elements in the cursor,
|
||||
/// the result contains all the elements in the cursor.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.prefix(2))
|
||||
/// // Prints "[1, 2]"
|
||||
/// try print(numbers.prefix(10))
|
||||
/// // Prints "[1, 2, 3, 4, 5]"
|
||||
///
|
||||
/// - Parameter maxLength: The maximum number of elements to return. The
|
||||
/// value of `maxLength` must be greater than or equal to zero.
|
||||
/// - Returns: A cursor starting at the beginning of this cursor
|
||||
/// with at most `maxLength` elements.
|
||||
public func prefix(_ maxLength: Int) -> PrefixCursor<Self> {
|
||||
return PrefixCursor(self, maxLength: maxLength)
|
||||
}
|
||||
|
||||
/// Returns a cursor of the initial consecutive elements that satisfy
|
||||
/// `predicate`.
|
||||
///
|
||||
/// - Parameter predicate: A closure that takes an element of the cursor as
|
||||
/// its argument and returns `true` if the element should be included or
|
||||
/// `false` otherwise. Once `predicate` returns `false` it will not be
|
||||
/// called again.
|
||||
public func prefix(while predicate: @escaping (Element) throws -> Bool) -> PrefixWhileCursor<Self> {
|
||||
return PrefixWhileCursor(self, predicate: predicate)
|
||||
}
|
||||
|
||||
/// Returns the result of calling the given combining closure with each
|
||||
/// element of this cursor and an accumulating value.
|
||||
public func reduce<Result>(
|
||||
_ initialResult: Result,
|
||||
_ nextPartialResult: (Result, Element) throws -> Result)
|
||||
throws -> Result
|
||||
{
|
||||
var accumulator = initialResult
|
||||
while let element = try next() {
|
||||
accumulator = try nextPartialResult(accumulator, element)
|
||||
}
|
||||
return accumulator
|
||||
}
|
||||
|
||||
/// Returns the result of calling the given combining closure with each
|
||||
/// element of this cursor and an accumulating value.
|
||||
public func reduce<Result>(
|
||||
into initialResult: Result,
|
||||
_ updateAccumulatingResult: (inout Result, Element) throws -> Void)
|
||||
throws -> Result
|
||||
{
|
||||
var accumulator = initialResult
|
||||
while let element = try next() {
|
||||
try updateAccumulatingResult(&accumulator, element)
|
||||
}
|
||||
return accumulator
|
||||
}
|
||||
|
||||
/// Returns an array, up to the given maximum length, containing the
|
||||
/// final elements of the cursor.
|
||||
///
|
||||
/// The cursor must be finite. If the maximum length exceeds the number of
|
||||
/// elements in the cursor, the result contains all the elements in the
|
||||
/// cursor.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.suffix(2))
|
||||
/// // Prints "[4, 5]"
|
||||
/// try print(numbers.suffix(10))
|
||||
/// // Prints "[1, 2, 3, 4, 5]"
|
||||
///
|
||||
/// - Parameter maxLength: The maximum number of elements to return. The
|
||||
/// value of `maxLength` must be greater than or equal to zero.
|
||||
public func suffix(_ maxLength: Int) throws -> [Element] {
|
||||
GRDBPrecondition(maxLength >= 0, "Can't take a suffix of negative length from a cursor")
|
||||
if maxLength == 0 {
|
||||
return []
|
||||
}
|
||||
|
||||
var ringBuffer: [Element] = []
|
||||
ringBuffer.reserveCapacity(maxLength)
|
||||
|
||||
var i = ringBuffer.startIndex
|
||||
|
||||
while let element = try next() {
|
||||
if ringBuffer.count < maxLength {
|
||||
ringBuffer.append(element)
|
||||
} else {
|
||||
ringBuffer[i] = element
|
||||
i += 1
|
||||
i %= maxLength
|
||||
}
|
||||
}
|
||||
|
||||
if i != ringBuffer.startIndex {
|
||||
let s0 = ringBuffer[i..<ringBuffer.endIndex]
|
||||
let s1 = ringBuffer[0..<i]
|
||||
return Array([s0, s1].joined())
|
||||
}
|
||||
return ringBuffer
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Equatable elements
|
||||
|
||||
extension Cursor where Element: Equatable {
|
||||
/// Returns a Boolean value indicating whether the cursor contains the
|
||||
/// given element.
|
||||
@@ -184,6 +436,36 @@ extension Cursor where Element: Equatable {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Comparable elements
|
||||
|
||||
extension Cursor where Element: Comparable {
|
||||
/// Returns the maximum element in the cursor.
|
||||
///
|
||||
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
|
||||
/// if its first argument should be ordered before its second
|
||||
/// argument; otherwise, `false`.
|
||||
/// - Returns: The cursor's maximum element, according to
|
||||
/// `areInIncreasingOrder`. If the cursor has no elements, returns
|
||||
/// `nil`.
|
||||
public func max() throws -> Element? {
|
||||
return try max(by: <)
|
||||
}
|
||||
|
||||
/// Returns the minimum element in the cursor.
|
||||
///
|
||||
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
|
||||
/// if its first argument should be ordered before its second
|
||||
/// argument; otherwise, `false`.
|
||||
/// - Returns: The cursor's minimum element, according to
|
||||
/// `areInIncreasingOrder`. If the cursor has no elements, returns
|
||||
/// `nil`.
|
||||
public func min() throws -> Element? {
|
||||
return try min(by: <)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Cursor elements
|
||||
|
||||
extension Cursor where Element: Cursor {
|
||||
/// Returns the elements of this cursor of cursors, concatenated.
|
||||
public func joined() -> FlattenCursor<Self> {
|
||||
@@ -191,46 +473,176 @@ extension Cursor where Element: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Sequence elements
|
||||
|
||||
extension Cursor where Element: Sequence {
|
||||
/// Returns the elements of this cursor of sequences, concatenated.
|
||||
public func joined() -> FlattenCursor<MapCursor<Self, IteratorCursor<Self.Element.Iterator>>> {
|
||||
public func joined() -> FlattenCursor<MapCursor<Self, AnyCursor<Element.Element>>> {
|
||||
return flatMap { $0 }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: String elements
|
||||
|
||||
extension Cursor where Element: StringProtocol {
|
||||
/// Returns the elements of this cursor of sequences, concatenated.
|
||||
public func joined(separator: String = "") throws -> String {
|
||||
if separator.isEmpty {
|
||||
var result = ""
|
||||
while let x = try next() {
|
||||
result.append(String(x))
|
||||
}
|
||||
return result
|
||||
} else {
|
||||
var result = ""
|
||||
if let first = try next() {
|
||||
result.append(String(first))
|
||||
while let next = try next() {
|
||||
result.append(separator)
|
||||
result.append(String(next))
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Specialized Cursors
|
||||
|
||||
/// A type-erased cursor of Element.
|
||||
///
|
||||
/// This cursor forwards its next() method to an arbitrary underlying cursor
|
||||
/// having the same Element type, hiding the specifics of the underlying
|
||||
/// cursor.
|
||||
public final class AnyCursor<Element>: Cursor {
|
||||
private let element: () throws -> Element?
|
||||
|
||||
/// Creates a cursor that wraps a base cursor but whose type depends only on
|
||||
/// the base cursor’s element type
|
||||
public init<C: Cursor>(_ base: C) where C.Element == Element {
|
||||
element = base.next
|
||||
}
|
||||
|
||||
/// Creates a cursor that wraps a base iterator but whose type depends only
|
||||
/// on the base iterator’s element type
|
||||
public convenience init<I: IteratorProtocol>(iterator: I) where I.Element == Element {
|
||||
var iterator = iterator
|
||||
self.init { iterator.next() }
|
||||
}
|
||||
|
||||
/// Creates a cursor that wraps a base sequence but whose type depends only
|
||||
/// on the base sequence’s element type
|
||||
public convenience init<S: Sequence>(_ s: S) where S.Element == Element {
|
||||
self.init(iterator: s.makeIterator())
|
||||
}
|
||||
|
||||
/// Creates a cursor that wraps the given closure in its next() method
|
||||
public init(_ body: @escaping () throws -> Element?) {
|
||||
element = body
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
/// :nodoc:
|
||||
public func next() throws -> Element? {
|
||||
return try element()
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public final class DropFirstCursor<Base: Cursor>: Cursor {
|
||||
private let base: Base
|
||||
private let limit: Int
|
||||
private var dropped: Int = 0
|
||||
|
||||
init(_ base: Base, limit: Int) {
|
||||
GRDBPrecondition(limit >= 0, "Can't drop a negative number of elements from a cursor")
|
||||
self.base = base
|
||||
self.limit = limit
|
||||
}
|
||||
|
||||
public func next() throws -> Base.Element? {
|
||||
while dropped < limit {
|
||||
if try base.next() == nil {
|
||||
dropped = limit
|
||||
return nil
|
||||
}
|
||||
dropped += 1
|
||||
}
|
||||
return try base.next()
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor whose elements consist of the elements that follow the initial
|
||||
/// consecutive elements of some base cursor that satisfy a given predicate.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class DropWhileCursor<Base: Cursor>: Cursor {
|
||||
private let base: Base
|
||||
private let predicate: (Base.Element) throws -> Bool
|
||||
private var predicateHasFailed = false
|
||||
|
||||
init(_ base: Base, predicate: @escaping (Base.Element) throws -> Bool) {
|
||||
self.base = base
|
||||
self.predicate = predicate
|
||||
}
|
||||
|
||||
public func next() throws -> Base.Element? {
|
||||
if predicateHasFailed {
|
||||
return try base.next()
|
||||
}
|
||||
|
||||
while let nextElement = try base.next() {
|
||||
if try !predicate(nextElement) {
|
||||
predicateHasFailed = true
|
||||
return nextElement
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// An enumeration of the elements of a cursor.
|
||||
///
|
||||
/// To create an instance of `EnumeratedCursor`, call the `enumerated()` method
|
||||
/// 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)")
|
||||
/// }
|
||||
/// // Prints: "0: foo"
|
||||
/// // Prints: "1: bar"
|
||||
public final class EnumeratedCursor<Base: Cursor> : Cursor {
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class EnumeratedCursor<Base: Cursor>: Cursor {
|
||||
private let base: Base
|
||||
private var index: Int
|
||||
|
||||
init(_ base: Base) {
|
||||
self.index = 0
|
||||
self.base = base
|
||||
self.index = 0
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
/// :nodoc:
|
||||
public func next() throws -> (Int, Base.Element)? {
|
||||
guard let element = try base.next() else { return nil }
|
||||
defer { index += 1 }
|
||||
return (index, element)
|
||||
}
|
||||
|
||||
private var index: Int
|
||||
private var base: Base
|
||||
}
|
||||
|
||||
/// A cursor whose elements consist of the elements of some base cursor that
|
||||
/// also satisfy a given predicate.
|
||||
public final class FilterCursor<Base: Cursor> : Cursor {
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class FilterCursor<Base: Cursor>: Cursor {
|
||||
private let base: Base
|
||||
private let isIncluded: (Base.Element) throws -> Bool
|
||||
|
||||
init(_ base: Base, _ isIncluded: @escaping (Base.Element) throws -> Bool) {
|
||||
self.base = base
|
||||
self.isIncluded = isIncluded
|
||||
@@ -238,6 +650,7 @@ public final class FilterCursor<Base: Cursor> : Cursor {
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
/// :nodoc:
|
||||
public func next() throws -> Base.Element? {
|
||||
while let element = try base.next() {
|
||||
if try isIncluded(element) {
|
||||
@@ -246,22 +659,25 @@ public final class FilterCursor<Base: Cursor> : Cursor {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private let base: Base
|
||||
private let isIncluded: (Base.Element) throws -> Bool
|
||||
}
|
||||
|
||||
/// A cursor consisting of all the elements contained in each segment contained
|
||||
/// in some Base cursor.
|
||||
///
|
||||
/// See Cursor.joined(), Cursor.flatMap(_:), Sequence.flatMap(_:)
|
||||
public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Cursor {
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class FlattenCursor<Base: Cursor>: Cursor where Base.Element: Cursor {
|
||||
private let base: Base
|
||||
private var inner: Base.Element?
|
||||
|
||||
init(_ base: Base) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
/// :nodoc:
|
||||
public func next() throws -> Base.Element.Element? {
|
||||
while true {
|
||||
if let element = try inner?.next() {
|
||||
@@ -273,16 +689,18 @@ public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Curs
|
||||
self.inner = inner
|
||||
}
|
||||
}
|
||||
|
||||
private var inner: Base.Element?
|
||||
private let base: Base
|
||||
}
|
||||
|
||||
/// A Cursor whose elements consist of those in a Base Cursor passed through a
|
||||
/// transform function returning Element.
|
||||
///
|
||||
/// See Cursor.map(_:)
|
||||
public final class MapCursor<Base: Cursor, Element> : Cursor {
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class MapCursor<Base: Cursor, Element>: Cursor {
|
||||
private let base: Base
|
||||
private let transform: (Base.Element) throws -> Element
|
||||
|
||||
init(_ base: Base, _ transform: @escaping (Base.Element) throws -> Element) {
|
||||
self.base = base
|
||||
self.transform = transform
|
||||
@@ -290,42 +708,62 @@ public final class MapCursor<Base: Cursor, Element> : Cursor {
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
/// :nodoc:
|
||||
public func next() throws -> Element? {
|
||||
guard let element = try base.next() else { return nil }
|
||||
return try transform(element)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// A cursor that only consumes up to `n` elements from an underlying
|
||||
/// `Base` cursor.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class PrefixCursor<Base: Cursor>: Cursor {
|
||||
private let base: Base
|
||||
private let transform: (Base.Element) throws -> Element
|
||||
}
|
||||
|
||||
/// A Cursor whose elements are those of a sequence iterator.
|
||||
public final class IteratorCursor<Base: IteratorProtocol> : Cursor {
|
||||
private let maxLength: Int
|
||||
private var taken = 0
|
||||
|
||||
/// Creates a cursor from a sequence iterator.
|
||||
public init(_ base: Base) {
|
||||
init(_ base: Base, maxLength: Int) {
|
||||
self.base = base
|
||||
self.maxLength = maxLength
|
||||
}
|
||||
|
||||
/// Creates a cursor from a sequence.
|
||||
public init<S: Sequence>(_ s: S) where S.Iterator == Base {
|
||||
self.base = s.makeIterator()
|
||||
public func next() throws -> Base.Element? {
|
||||
if taken >= maxLength { return nil }
|
||||
taken += 1
|
||||
|
||||
if let next = try base.next() {
|
||||
return next
|
||||
}
|
||||
|
||||
taken = maxLength
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
public func next() -> Base.Element? {
|
||||
return base.next()
|
||||
}
|
||||
|
||||
private var base: Base
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
/// A cursor whose elements consist of the initial consecutive elements of
|
||||
/// some base cursor that satisfy a given predicate.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class PrefixWhileCursor<Base: Cursor>: Cursor {
|
||||
private let base: Base
|
||||
private let predicate: (Base.Element) throws -> Bool
|
||||
private var predicateHasFailed = false
|
||||
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<IteratorCursor<Self.Iterator>, SegmentOfResult>> {
|
||||
return IteratorCursor(self).flatMap(transform)
|
||||
init(_ base: Base, predicate: @escaping (Base.Element) throws -> Bool) {
|
||||
self.base = base
|
||||
self.predicate = predicate
|
||||
}
|
||||
|
||||
public func next() throws -> Base.Element? {
|
||||
if !predicateHasFailed, let nextElement = try base.next() {
|
||||
if try predicate(nextElement) {
|
||||
return nextElement
|
||||
} else {
|
||||
predicateHasFailed = true
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,638 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Database Schema
|
||||
|
||||
/// Clears the database schema cache.
|
||||
///
|
||||
/// You may need to clear the cache manually if the database schema is
|
||||
/// modified by another connection.
|
||||
public func clearSchemaCache() {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
schemaCache.clear()
|
||||
|
||||
// We also clear updateStatementCache and selectStatementCache despite
|
||||
// the automatic statement recompilation (see https://www.sqlite.org/c3ref/prepare.html)
|
||||
// because the automatic statement recompilation only happens a
|
||||
// limited number of times.
|
||||
internalStatementCache.clear()
|
||||
publicStatementCache.clear()
|
||||
}
|
||||
|
||||
/// Returns whether a table exists.
|
||||
public func tableExists(_ name: String) throws -> Bool {
|
||||
return try exists(type: .table, name: name)
|
||||
}
|
||||
|
||||
/// Returns whether a table is an internal SQLite table.
|
||||
///
|
||||
/// Those are tables whose name begins with "sqlite_".
|
||||
///
|
||||
/// For more information, see https://www.sqlite.org/fileformat2.html
|
||||
public func isSQLiteInternalTable(_ tableName: String) -> Bool {
|
||||
// https://www.sqlite.org/fileformat2.html#internal_schema_objects
|
||||
// > The names of internal schema objects always begin with "sqlite_"
|
||||
// > and any table, index, view, or trigger whose name begins with
|
||||
// > "sqlite_" is an internal schema object. SQLite prohibits
|
||||
// > applications from creating objects whose names begin with
|
||||
// > "sqlite_".
|
||||
return tableName.starts(with: "sqlite_")
|
||||
}
|
||||
|
||||
/// Returns whether a table is an internal GRDB table.
|
||||
///
|
||||
/// Those are tables whose name begins with "grdb_".
|
||||
public func isGRDBInternalTable(_ tableName: String) -> Bool {
|
||||
return tableName.starts(with: "grdb_")
|
||||
}
|
||||
|
||||
/// Returns whether a view exists.
|
||||
public func viewExists(_ name: String) throws -> Bool {
|
||||
return try exists(type: .view, name: name)
|
||||
}
|
||||
|
||||
/// Returns whether a trigger exists.
|
||||
public func triggerExists(_ name: String) throws -> Bool {
|
||||
return try exists(type: .trigger, name: name)
|
||||
}
|
||||
|
||||
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
|
||||
/// table has no explicit primary key, the result is the hidden
|
||||
/// "rowid" column.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
public func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
|
||||
if let primaryKey = schemaCache.primaryKey(tableName) {
|
||||
return primaryKey
|
||||
}
|
||||
|
||||
// https://www.sqlite.org/pragma.html
|
||||
//
|
||||
// > PRAGMA database.table_info(table-name);
|
||||
// >
|
||||
// > This pragma returns one row for each column in the named table.
|
||||
// > Columns in the result set include the column name, data type,
|
||||
// > whether or not the column can be NULL, and the default value for
|
||||
// > the column. The "pk" column in the result set is zero for columns
|
||||
// > that are not part of the primary key, and is the index of the
|
||||
// > column in the primary key for columns that are part of the primary
|
||||
// > key.
|
||||
//
|
||||
// CREATE TABLE players (
|
||||
// id INTEGER PRIMARY KEY,
|
||||
// name TEXT,
|
||||
// score INTEGER)
|
||||
//
|
||||
// PRAGMA table_info("players")
|
||||
//
|
||||
// cid | name | type | notnull | dflt_value | pk |
|
||||
// 0 | id | INTEGER | 0 | NULL | 1 |
|
||||
// 1 | name | TEXT | 0 | NULL | 0 |
|
||||
// 2 | score | INTEGER | 0 | NULL | 0 |
|
||||
|
||||
let columns = try self.columns(in: tableName)
|
||||
|
||||
let primaryKey: PrimaryKeyInfo
|
||||
let pkColumns = columns
|
||||
.filter { $0.primaryKeyIndex > 0 }
|
||||
.sorted { $0.primaryKeyIndex < $1.primaryKeyIndex }
|
||||
|
||||
switch pkColumns.count {
|
||||
case 0:
|
||||
// No explicit primary key => primary key is hidden rowID column
|
||||
primaryKey = .hiddenRowID
|
||||
case 1:
|
||||
// Single column
|
||||
let pkColumn = pkColumns.first!
|
||||
|
||||
// https://www.sqlite.org/lang_createtable.html:
|
||||
//
|
||||
// > With one exception noted below, if a rowid table has a primary
|
||||
// > key that consists of a single column and the declared type of
|
||||
// > that column is "INTEGER" in any mixture of upper and lower
|
||||
// > case, then the column becomes an alias for the rowid. Such a
|
||||
// > column is usually referred to as an "integer primary key".
|
||||
// > A PRIMARY KEY column only becomes an integer primary key if the
|
||||
// > declared type name is exactly "INTEGER". Other integer type
|
||||
// > names like "INT" or "BIGINT" or "SHORT INTEGER" or "UNSIGNED
|
||||
// > INTEGER" causes the primary key column to behave as an ordinary
|
||||
// > table column with integer affinity and a unique index, not as
|
||||
// > an alias for the rowid.
|
||||
// >
|
||||
// > The exception mentioned above is that if the declaration of a
|
||||
// > column with declared type "INTEGER" includes an "PRIMARY KEY
|
||||
// > DESC" clause, it does not become an alias for the rowid [...]
|
||||
//
|
||||
// FIXME: We ignore the exception, and consider all INTEGER primary
|
||||
// keys as aliases for the rowid:
|
||||
if pkColumn.type.uppercased() == "INTEGER" {
|
||||
primaryKey = .rowID(pkColumn.name)
|
||||
} else {
|
||||
primaryKey = .regular([pkColumn.name])
|
||||
}
|
||||
default:
|
||||
// Multi-columns primary key
|
||||
primaryKey = .regular(pkColumns.map { $0.name })
|
||||
}
|
||||
|
||||
schemaCache.set(primaryKey: primaryKey, forTable: tableName)
|
||||
return primaryKey
|
||||
}
|
||||
|
||||
/// The indexes on table named `tableName`; returns the empty array if the
|
||||
/// table does not exist.
|
||||
///
|
||||
/// Note: SQLite does not define any index for INTEGER PRIMARY KEY columns:
|
||||
/// this method does not return any index that represents this primary key.
|
||||
///
|
||||
/// If you want to know if a set of columns uniquely identify a row, prefer
|
||||
/// table(_:hasUniqueKey:) instead.
|
||||
public func indexes(on tableName: String) throws -> [IndexInfo] {
|
||||
if let indexes = schemaCache.indexes(on: tableName) {
|
||||
return indexes
|
||||
}
|
||||
|
||||
let indexes = try Row
|
||||
.fetchAll(self, 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 {
|
||||
// PRAGMA index_list doesn't throw any error when table does
|
||||
// not exist. So let's check if table exists:
|
||||
if try tableExists(tableName) == false {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
}
|
||||
}
|
||||
|
||||
schemaCache.set(indexes: indexes, forTable: tableName)
|
||||
return indexes
|
||||
}
|
||||
|
||||
/// True if a sequence of columns uniquely identifies a row, that is to say
|
||||
/// if the columns are the primary key, or if there is a unique index on them.
|
||||
public func table<T: Sequence>(
|
||||
_ tableName: String,
|
||||
hasUniqueKey columns: T)
|
||||
throws -> Bool
|
||||
where T.Iterator.Element == String
|
||||
{
|
||||
return try columnsForUniqueKey(Array(columns), in: tableName) != nil
|
||||
}
|
||||
|
||||
/// The foreign keys defined on table named `tableName`.
|
||||
public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo] {
|
||||
if let foreignKeys = schemaCache.foreignKeys(on: tableName) {
|
||||
return foreignKeys
|
||||
}
|
||||
|
||||
var rawForeignKeys: [(
|
||||
destinationTable: String,
|
||||
mapping: [(origin: String, destination: String?, seq: Int)])] = []
|
||||
var previousId: Int? = nil
|
||||
for row in try Row.fetchAll(self, 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]
|
||||
let table: String = row[2]
|
||||
let origin: String = row[3]
|
||||
let destination: String? = row[4]
|
||||
|
||||
if previousId == id {
|
||||
rawForeignKeys[rawForeignKeys.count - 1]
|
||||
.mapping
|
||||
.append((origin: origin, destination: destination, seq: seq))
|
||||
} else {
|
||||
rawForeignKeys.append((
|
||||
destinationTable: table,
|
||||
mapping: [(origin: origin, destination: destination, seq: seq)]))
|
||||
previousId = id
|
||||
}
|
||||
}
|
||||
|
||||
if rawForeignKeys.isEmpty {
|
||||
// PRAGMA foreign_key_list doesn't throw any error when table does
|
||||
// not exist. So let's check if table exists:
|
||||
if try tableExists(tableName) == false {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
}
|
||||
}
|
||||
|
||||
let foreignKeys = try rawForeignKeys.map { (destinationTable, columnMapping) -> ForeignKeyInfo in
|
||||
let orderedMapping = columnMapping
|
||||
.sorted { $0.seq < $1.seq }
|
||||
.map { (origin: $0.origin, destination: $0 .destination) }
|
||||
|
||||
let completeMapping: [(origin: String, destination: String)]
|
||||
if orderedMapping.contains(where: { (_, destination) in destination == nil }) {
|
||||
let pk = try primaryKey(destinationTable)
|
||||
completeMapping = zip(pk.columns, orderedMapping).map { (pkColumn, arrow) in
|
||||
(origin: arrow.origin, destination: pkColumn)
|
||||
}
|
||||
} else {
|
||||
completeMapping = orderedMapping.map { (origin, destination) in
|
||||
(origin: origin, destination: destination!)
|
||||
}
|
||||
}
|
||||
return ForeignKeyInfo(destinationTable: destinationTable, mapping: completeMapping)
|
||||
}
|
||||
|
||||
schemaCache.set(foreignKeys: foreignKeys, forTable: tableName)
|
||||
return foreignKeys
|
||||
}
|
||||
|
||||
/// Returns the actual name of the database table
|
||||
func canonicalTableName(_ tableName: String) throws -> String {
|
||||
guard let name = try schema().canonicalName(tableName, ofType: .table) else {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
func schema() throws -> SchemaInfo {
|
||||
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.
|
||||
public func columns(in tableName: String) throws -> [ColumnInfo] {
|
||||
if let columns = schemaCache.columns(in: tableName) {
|
||||
return columns
|
||||
}
|
||||
|
||||
// https://www.sqlite.org/pragma.html
|
||||
//
|
||||
// > PRAGMA database.table_info(table-name);
|
||||
// >
|
||||
// > This pragma returns one row for each column in the named table.
|
||||
// > Columns in the result set include the column name, data type,
|
||||
// > whether or not the column can be NULL, and the default value for
|
||||
// > the column. The "pk" column in the result set is zero for columns
|
||||
// > that are not part of the primary key, and is the index of the
|
||||
// > column in the primary key for columns that are part of the primary
|
||||
// > key.
|
||||
//
|
||||
// CREATE TABLE players (
|
||||
// id INTEGER PRIMARY KEY,
|
||||
// firstName TEXT,
|
||||
// lastName TEXT)
|
||||
//
|
||||
// PRAGMA table_info("players")
|
||||
//
|
||||
// cid | name | type | notnull | dflt_value | pk |
|
||||
// 0 | id | INTEGER | 0 | NULL | 1 |
|
||||
// 1 | name | TEXT | 0 | NULL | 0 |
|
||||
// 2 | score | INTEGER | 0 | NULL | 0 |
|
||||
|
||||
if sqlite3_libversion_number() < 3008005 {
|
||||
// Work around a bug in SQLite where PRAGMA table_info would
|
||||
// return a result even after the table was deleted.
|
||||
if try !tableExists(tableName) {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
}
|
||||
}
|
||||
let columns = try ColumnInfo
|
||||
.fetchAll(self, sql: "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
|
||||
.sorted(by: { $0.cid < $1.cid })
|
||||
if columns.isEmpty {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
}
|
||||
|
||||
schemaCache.set(columns: columns, forTable: tableName)
|
||||
return columns
|
||||
}
|
||||
|
||||
/// If there exists a unique key on columns, return the columns
|
||||
/// ordered as the matching index (or primay key). Case of returned columns
|
||||
/// is not guaranteed.
|
||||
func columnsForUniqueKey<T: Sequence>(
|
||||
_ columns: T,
|
||||
in tableName: String)
|
||||
throws -> [String]?
|
||||
where T.Iterator.Element == String
|
||||
{
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
}
|
||||
|
||||
/// A column of a database table.
|
||||
///
|
||||
/// This type closely matches the information returned by the
|
||||
/// `table_info` pragma.
|
||||
///
|
||||
/// > CREATE TABLE player (
|
||||
/// id INTEGER PRIMARY KEY,
|
||||
/// firstName TEXT,
|
||||
/// lastName TEXT)
|
||||
/// > PRAGMA table_info("player")
|
||||
/// cid name type notnull dflt_value pk
|
||||
/// ---- ----- ------- -------- ---------- ---
|
||||
/// 0 id INTEGER 0 NULL 1
|
||||
/// 1 name TEXT 0 NULL 0
|
||||
/// 2 score INTEGER 0 NULL 0
|
||||
///
|
||||
/// See `Database.columns(in:)` and https://www.sqlite.org/pragma.html#pragma_table_info
|
||||
public struct ColumnInfo: FetchableRecord {
|
||||
let cid: Int
|
||||
|
||||
/// The column name
|
||||
public let name: String
|
||||
|
||||
/// The column data type
|
||||
public let type: String
|
||||
|
||||
/// True if and only if the column is constrained to be not null.
|
||||
public let isNotNull: Bool
|
||||
|
||||
/// The SQL snippet that defines the default value, if any.
|
||||
///
|
||||
/// When nil, the column has no default value.
|
||||
///
|
||||
/// When not nil, it contains an SQL string that defines an expression. That
|
||||
/// expression may be a literal, as `1`, or `'foo'`. It may also contain a
|
||||
/// non-constant expression such as `CURRENT_TIMESTAMP`.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try db.execute(sql: """
|
||||
/// CREATE TABLE player(
|
||||
/// id INTEGER PRIMARY KEY,
|
||||
/// name TEXT DEFAULT 'Anonymous',
|
||||
/// score INT DEFAULT 0,
|
||||
/// creationDate DATE DEFAULT CURRENT_TIMESTAMP
|
||||
/// )
|
||||
/// """)
|
||||
/// let columnInfos = try db.columns(in: "player")
|
||||
/// columnInfos[0].defaultValueSQL // nil
|
||||
/// columnInfos[1].defaultValueSQL // "'Anoynymous'"
|
||||
/// columnInfos[2].defaultValueSQL // "0"
|
||||
/// columnInfos[3].defaultValueSQL // "CURRENT_TIMESTAMP"
|
||||
public let defaultValueSQL: String?
|
||||
|
||||
/// Zero for columns that are not part of the primary key.
|
||||
///
|
||||
/// Before SQLite 3.7.16, it is 1 for columns that are part of the
|
||||
/// primary key.
|
||||
///
|
||||
/// Starting from SQLite 3.7.16, it is the one-based index of the column in
|
||||
/// the primary key for columns that are part of the primary key.
|
||||
///
|
||||
/// References:
|
||||
/// - https://sqlite.org/releaselog/3_7_16.html
|
||||
/// - http://mailinglists.sqlite.org/cgi-bin/mailman/private/sqlite-users/2013-April/046034.html
|
||||
public let primaryKeyIndex: Int
|
||||
|
||||
/// :nodoc:
|
||||
public init(row: Row) {
|
||||
cid = row["cid"]
|
||||
name = row["name"]
|
||||
type = row["type"]
|
||||
isNotNull = row["notnull"]
|
||||
defaultValueSQL = row["dflt_value"]
|
||||
primaryKeyIndex = row["pk"]
|
||||
}
|
||||
}
|
||||
|
||||
/// An index on a database table.
|
||||
///
|
||||
/// See `Database.indexes(on:)`
|
||||
public struct IndexInfo {
|
||||
/// The name of the index
|
||||
public let name: String
|
||||
|
||||
/// The indexed columns
|
||||
public let columns: [String]
|
||||
|
||||
/// True if the index is unique
|
||||
public let isUnique: Bool
|
||||
|
||||
init(name: String, columns: [String], unique: Bool) {
|
||||
self.name = name
|
||||
self.columns = columns
|
||||
self.isUnique = unique
|
||||
}
|
||||
}
|
||||
|
||||
/// Primary keys are returned from the Database.primaryKey(_:) method.
|
||||
///
|
||||
/// When the table's primary key is the rowid:
|
||||
///
|
||||
/// // CREATE TABLE item (name TEXT)
|
||||
/// let pk = try db.primaryKey("item")
|
||||
/// pk.columns // ["rowid"]
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // true
|
||||
///
|
||||
/// // CREATE TABLE citizen (
|
||||
/// // id INTEGER PRIMARY KEY,
|
||||
/// // name TEXT
|
||||
/// // )
|
||||
/// let pk = try db.primaryKey("citizen")!
|
||||
/// pk.columns // ["id"]
|
||||
/// pk.rowIDColumn // "id"
|
||||
/// pk.isRowID // true
|
||||
///
|
||||
/// When the table's primary key is not the rowid:
|
||||
///
|
||||
/// // CREATE TABLE country (
|
||||
/// // isoCode TEXT NOT NULL PRIMARY KEY
|
||||
/// // name TEXT
|
||||
/// // )
|
||||
/// let pk = db.primaryKey("country")!
|
||||
/// pk.columns // ["isoCode"]
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // false
|
||||
///
|
||||
/// // CREATE TABLE citizenship (
|
||||
/// // citizenID INTEGER NOT NULL REFERENCES citizen(id)
|
||||
/// // countryIsoCode TEXT NOT NULL REFERENCES country(isoCode)
|
||||
/// // PRIMARY KEY (citizenID, countryIsoCode)
|
||||
/// // )
|
||||
/// let pk = db.primaryKey("citizenship")!
|
||||
/// pk.columns // ["citizenID", "countryIsoCode"]
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // false
|
||||
public struct PrimaryKeyInfo {
|
||||
private enum Impl {
|
||||
/// The hidden rowID.
|
||||
case hiddenRowID
|
||||
|
||||
/// An INTEGER PRIMARY KEY column that aliases the Row ID.
|
||||
/// Associated string is the column name.
|
||||
case rowID(String)
|
||||
|
||||
/// Any primary key, but INTEGER PRIMARY KEY.
|
||||
/// Associated strings are column names.
|
||||
case regular([String])
|
||||
}
|
||||
|
||||
private let impl: Impl
|
||||
|
||||
static func rowID(_ column: String) -> PrimaryKeyInfo {
|
||||
return PrimaryKeyInfo(impl: .rowID(column))
|
||||
}
|
||||
|
||||
static func regular(_ columns: [String]) -> PrimaryKeyInfo {
|
||||
assert(!columns.isEmpty)
|
||||
return PrimaryKeyInfo(impl: .regular(columns))
|
||||
}
|
||||
|
||||
static let hiddenRowID = PrimaryKeyInfo(impl: .hiddenRowID)
|
||||
|
||||
/// The columns in the primary key; this array is never empty.
|
||||
public var columns: [String] {
|
||||
switch impl {
|
||||
case .hiddenRowID:
|
||||
return [Column.rowID.name]
|
||||
case .rowID(let column):
|
||||
return [column]
|
||||
case .regular(let columns):
|
||||
return columns
|
||||
}
|
||||
}
|
||||
|
||||
/// When not nil, the name of the column that contains the INTEGER PRIMARY KEY.
|
||||
public var rowIDColumn: String? {
|
||||
switch impl {
|
||||
case .hiddenRowID:
|
||||
return nil
|
||||
case .rowID(let column):
|
||||
return column
|
||||
case .regular:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// When true, the primary key is the rowid:
|
||||
public var isRowID: Bool {
|
||||
switch impl {
|
||||
case .hiddenRowID:
|
||||
return true
|
||||
case .rowID:
|
||||
return true
|
||||
case .regular:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// You get foreign keys from table names, with the
|
||||
/// `foreignKeys(on:)` method.
|
||||
public struct ForeignKeyInfo {
|
||||
/// The name of the destination table
|
||||
public let destinationTable: String
|
||||
|
||||
/// The column to column mapping
|
||||
public let mapping: [(origin: String, destination: String)]
|
||||
|
||||
/// The origin columns
|
||||
public var originColumns: [String] {
|
||||
return mapping.map { $0.origin }
|
||||
}
|
||||
|
||||
/// The destination columns
|
||||
public var destinationColumns: [String] {
|
||||
return mapping.map { $0.destination }
|
||||
}
|
||||
}
|
||||
|
||||
enum SchemaObjectType: String {
|
||||
case index
|
||||
case table
|
||||
case trigger
|
||||
case view
|
||||
}
|
||||
|
||||
struct SchemaInfo: Equatable {
|
||||
private var objects: Set<SchemaObject>
|
||||
|
||||
init(_ db: Database) throws {
|
||||
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
|
||||
"""))
|
||||
}
|
||||
|
||||
/// 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?
|
||||
var sql: String?
|
||||
var isTemporary: Bool
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Statements
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// 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: sql, prepFlags: 0)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// 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])!
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
/// - returns: A SelectStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
func makeSelectStatement(sql: String, prepFlags: Int32) throws -> SelectStatement {
|
||||
return try SelectStatement.prepare(self, sql: sql, prepFlags: prepFlags)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// 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])!
|
||||
///
|
||||
/// The returned statement may have already been used: it may or may not
|
||||
/// contain values for its eventual arguments.
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func cachedSelectStatement(sql: String) throws -> SelectStatement {
|
||||
return try publicStatementCache.selectStatement(sql)
|
||||
}
|
||||
|
||||
/// Returns a cached statement that does not conflict with user's cached statements.
|
||||
func internalCachedSelectStatement(sql: String) throws -> SelectStatement {
|
||||
return try internalStatementCache.selectStatement(sql)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeUpdateStatement(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: sql, prepFlags: 0)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)", prepFlags: 0)
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
func makeUpdateStatement(sql: String, prepFlags: Int32) throws -> UpdateStatement {
|
||||
return try UpdateStatement.prepare(self, sql: sql, prepFlags: prepFlags)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// The returned statement may have already been used: it may or may not
|
||||
/// contain values for its eventual arguments.
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func cachedUpdateStatement(sql: String) throws -> UpdateStatement {
|
||||
return try publicStatementCache.updateStatement(sql)
|
||||
}
|
||||
|
||||
/// Returns a cached statement that does not conflict with user's cached statements.
|
||||
func internalCachedUpdateStatement(sql: String) throws -> UpdateStatement {
|
||||
return try internalStatementCache.updateStatement(sql)
|
||||
}
|
||||
|
||||
/// Executes one or several SQL statements, separated by semi-colons.
|
||||
///
|
||||
/// try db.execute(
|
||||
/// sql: "INSERT INTO player (name) VALUES (:name)",
|
||||
/// arguments: ["name": "Arthur"])
|
||||
///
|
||||
/// try db.execute(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// """, arguments: ["Arthur", "Barbara", "O'Brien"])
|
||||
///
|
||||
/// This method may throw a DatabaseError.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func execute(sql: String, arguments: StatementArguments = StatementArguments()) throws {
|
||||
try execute(literal: SQLLiteral(sql: sql, arguments: arguments))
|
||||
}
|
||||
|
||||
/// 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.
|
||||
//
|
||||
// This job is performed by StatementArguments.extractBindings(forStatement:allowingRemainingValues:)
|
||||
//
|
||||
// And before we return, we'll check that all arguments were consumed.
|
||||
|
||||
var arguments = sqlLiteral.arguments
|
||||
let initialValuesCount = arguments.values.count
|
||||
|
||||
// Build a C string (SQLite wants that), and execute SQL statements one
|
||||
// after the other.
|
||||
try sqlLiteral.sql.utf8CString.withUnsafeBufferPointer { buffer in
|
||||
guard let sqlStart = buffer.baseAddress else { return }
|
||||
let sqlEnd = sqlStart + buffer.count // past \0
|
||||
var statementStart = sqlStart
|
||||
while statementStart < sqlEnd {
|
||||
var statementEnd: UnsafePointer<Int8>? = nil
|
||||
let nextStatement: UpdateStatement?
|
||||
|
||||
// Compile
|
||||
do {
|
||||
let authorizer = StatementCompilationAuthorizer()
|
||||
nextStatement = try withAuthorizer(authorizer) {
|
||||
try UpdateStatement(
|
||||
database: self,
|
||||
statementStart: statementStart,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: 0,
|
||||
authorizer: authorizer)
|
||||
}
|
||||
}
|
||||
|
||||
guard let statement = nextStatement else {
|
||||
// End of SQL string
|
||||
break
|
||||
}
|
||||
|
||||
// Extract statement arguments
|
||||
let bindings = try arguments.extractBindings(forStatement: statement, allowingRemainingValues: true)
|
||||
// unsafe is OK because we just extracted the correct number of arguments
|
||||
statement.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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
private func updateStatementDidExecute(_ statement: UpdateStatement) throws {
|
||||
if statement.invalidatesDatabaseSchemaCache {
|
||||
clearSchemaCache()
|
||||
}
|
||||
|
||||
try observationBroker.updateStatementDidExecute(statement)
|
||||
}
|
||||
|
||||
private func updateStatementDidFail(_ statement: UpdateStatement) throws {
|
||||
// Failed statements can not be reused, because sqlite3_reset won't
|
||||
// be able to restore the statement to its initial state:
|
||||
// https://www.sqlite.org/c3ref/reset.html
|
||||
//
|
||||
// So make sure we clear this statement from the cache.
|
||||
internalStatementCache.remove(statement)
|
||||
publicStatementCache.remove(statement)
|
||||
|
||||
try observationBroker.updateStatementDidFail(statement)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
func selectStatementWillExecute(_ statement: SelectStatement) {
|
||||
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:
|
||||
// https://www.sqlite.org/c3ref/reset.html
|
||||
//
|
||||
// So make sure we clear this statement from the cache.
|
||||
internalStatementCache.remove(statement)
|
||||
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 }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// A Collation is a string comparison function used by SQLite.
|
||||
public final class DatabaseCollation {
|
||||
public let name: String
|
||||
let function: (Int32, UnsafeRawPointer?, Int32, UnsafeRawPointer?) -> ComparisonResult
|
||||
|
||||
/// Creates a collation.
|
||||
///
|
||||
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// db.add(collation: collation)
|
||||
/// try db.execute(sql: "CREATE TABLE file (name TEXT COLLATE localized_standard")
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The function name.
|
||||
/// - function: A function that compares two strings.
|
||||
public init(_ name: String, function: @escaping (String, String) -> ComparisonResult) {
|
||||
self.name = name
|
||||
self.function = { (length1, buffer1, length2, buffer2) in
|
||||
// Buffers are not C strings: they do not end with \0.
|
||||
let string1 = String(
|
||||
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped),
|
||||
length: Int(length1),
|
||||
encoding: .utf8,
|
||||
freeWhenDone: false)!
|
||||
let string2 = String(
|
||||
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped),
|
||||
length: Int(length2),
|
||||
encoding: .utf8,
|
||||
freeWhenDone: false)!
|
||||
return function(string1, string2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseCollation: Hashable {
|
||||
// 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 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, rhs.name) == 0
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,13 @@
|
||||
import Foundation
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible {
|
||||
public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
|
||||
public let rawValue: Int32
|
||||
|
||||
public init(rawValue: Int32) {
|
||||
@@ -24,24 +27,6 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
|
||||
return self == primaryResultCode
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
// sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, iOSApplicationExtension 8.2, *) {
|
||||
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
|
||||
} else {
|
||||
return "\(rawValue)"
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
public static func == (_ lhs: ResultCode, _ rhs: ResultCode) -> Bool {
|
||||
return lhs.rawValue == rhs.rawValue
|
||||
}
|
||||
|
||||
/// Returns true if the code on the left matches the code on the right.
|
||||
///
|
||||
/// Primary result codes match themselves and their extended result codes,
|
||||
@@ -63,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
|
||||
@@ -94,10 +80,12 @@ 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
|
||||
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)))
|
||||
@@ -154,11 +142,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
|
||||
}
|
||||
|
||||
// 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 {
|
||||
if let errorString = errorString {
|
||||
return "\(rawValue) (\(errorString))"
|
||||
} else {
|
||||
return "\(rawValue)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// DatabaseError wraps an SQLite error.
|
||||
public struct DatabaseError : Error {
|
||||
public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
|
||||
/// The SQLite error code (see
|
||||
/// https://www.sqlite.org/rescode.html#primary_result_code_list).
|
||||
@@ -197,9 +212,14 @@ public struct DatabaseError : Error {
|
||||
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
|
||||
}
|
||||
@@ -219,10 +239,11 @@ public struct DatabaseError : Error {
|
||||
let arguments: StatementArguments?
|
||||
}
|
||||
|
||||
extension DatabaseError: CustomStringConvertible {
|
||||
/// A textual representation of `self`.
|
||||
// CustomStringConvertible
|
||||
extension DatabaseError {
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
var description = "SQLite error \(extendedResultCode.rawValue)"
|
||||
var description = "SQLite error \(resultCode.rawValue)"
|
||||
if let sql = sql {
|
||||
description += " with statement `\(sql)`"
|
||||
}
|
||||
@@ -236,20 +257,24 @@ extension DatabaseError: CustomStringConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseError : CustomNSError {
|
||||
// CustomNSError
|
||||
extension DatabaseError {
|
||||
|
||||
/// NSError bridging: the domain of the error.
|
||||
/// :nodoc:
|
||||
public static var errorDomain: String {
|
||||
return "GRDB.DatabaseError"
|
||||
}
|
||||
|
||||
/// NSError bridging: the error code within the given domain.
|
||||
/// :nodoc:
|
||||
public var errorCode: Int {
|
||||
return Int(extendedResultCode.rawValue)
|
||||
}
|
||||
|
||||
/// NSError bridging: the user-info dictionary.
|
||||
public var errorUserInfo: [String : Any] {
|
||||
/// :nodoc:
|
||||
public var errorUserInfo: [String: Any] {
|
||||
return [NSLocalizedDescriptionKey: description]
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,24 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// An SQL function or aggregate.
|
||||
public final class DatabaseFunction {
|
||||
public let name: String
|
||||
let argumentCount: Int32?
|
||||
public final class DatabaseFunction: Hashable {
|
||||
// SQLite identifies functions by (name + argument count)
|
||||
private struct Identity: Hashable {
|
||||
let name: String
|
||||
let nArg: Int32 // -1 for variadic functions
|
||||
}
|
||||
|
||||
public var name: String { return identity.name }
|
||||
private let identity: Identity
|
||||
let pure: Bool
|
||||
private let kind: Kind
|
||||
fileprivate var nArg: Int32 { return argumentCount ?? -1 }
|
||||
fileprivate var eTextRep: Int32 { return (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
|
||||
private var eTextRep: Int32 { return (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
|
||||
|
||||
/// Returns an SQL function.
|
||||
///
|
||||
@@ -20,7 +29,7 @@ public final class DatabaseFunction {
|
||||
/// 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.
|
||||
@@ -35,9 +44,13 @@ public final class DatabaseFunction {
|
||||
/// 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?) {
|
||||
self.name = name
|
||||
self.argumentCount = argumentCount
|
||||
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
|
||||
let arguments = (0..<Int(argc)).map { index in
|
||||
@@ -66,11 +79,11 @@ public final class DatabaseFunction {
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// dbQueue.add(function: fn)
|
||||
/// try dbQueue.inDatabase { 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 dbQueue.write { db in
|
||||
/// 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:
|
||||
@@ -86,11 +99,15 @@ public final class DatabaseFunction {
|
||||
/// 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) {
|
||||
self.name = name
|
||||
self.argumentCount = argumentCount
|
||||
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
|
||||
@@ -102,8 +119,8 @@ public final class DatabaseFunction {
|
||||
|
||||
let code = sqlite3_create_function_v2(
|
||||
db.sqliteConnection,
|
||||
name,
|
||||
nArg,
|
||||
identity.name,
|
||||
identity.nArg,
|
||||
eTextRep,
|
||||
definitionP,
|
||||
kind.xFunc,
|
||||
@@ -125,8 +142,8 @@ public final class DatabaseFunction {
|
||||
func uninstall(in db: Database) {
|
||||
let code = sqlite3_create_function_v2(
|
||||
db.sqliteConnection,
|
||||
name,
|
||||
nArg,
|
||||
identity.name,
|
||||
identity.nArg,
|
||||
eTextRep,
|
||||
nil, nil, nil, nil, nil)
|
||||
|
||||
@@ -190,7 +207,9 @@ public final class DatabaseFunction {
|
||||
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),
|
||||
@@ -255,11 +274,15 @@ public final class DatabaseFunction {
|
||||
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...
|
||||
@@ -270,9 +293,9 @@ public final class DatabaseFunction {
|
||||
|
||||
// retain and store in SQLite's buffer
|
||||
let aggregateContextU = Unmanaged.passRetained(aggregateContext)
|
||||
var aggregateContextP = aggregateContextU.toOpaque()
|
||||
withUnsafeBytes(of: &aggregateContextP) {
|
||||
aggregateContextBufferP.copyBytes(from: $0)
|
||||
let aggregateContextP = aggregateContextU.toOpaque()
|
||||
withUnsafeBytes(of: aggregateContextP) {
|
||||
aggregateContextBufferP.copyMemory(from: $0)
|
||||
}
|
||||
return aggregateContextU
|
||||
}
|
||||
@@ -289,9 +312,15 @@ public final class DatabaseFunction {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,15 +336,16 @@ public final class DatabaseFunction {
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseFunction : Hashable {
|
||||
/// The hash value
|
||||
public var hashValue: Int {
|
||||
return name.hashValue ^ nArg.hashValue
|
||||
extension DatabaseFunction {
|
||||
/// :nodoc:
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(identity)
|
||||
}
|
||||
|
||||
/// Two functions are equal if they share the same name and arity.
|
||||
/// :nodoc:
|
||||
public static func == (lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool {
|
||||
return lhs.name == rhs.name && lhs.nArg == rhs.nArg
|
||||
return lhs.identity == rhs.identity
|
||||
}
|
||||
}
|
||||
|
||||
@@ -340,11 +370,11 @@ extension DatabaseFunction : Hashable {
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// dbQueue.add(function: fn)
|
||||
/// try dbQueue.inDatabase { 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 dbQueue.write { db in
|
||||
/// 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.
|
||||
@@ -356,10 +386,10 @@ public protocol DatabaseAggregate {
|
||||
/// aggregate function.
|
||||
///
|
||||
/// -- One value
|
||||
/// SELECT maxLength(name) FROM persons
|
||||
/// SELECT maxLength(name) FROM player
|
||||
///
|
||||
/// -- Two values
|
||||
/// SELECT maxFullNameLength(firstName, lastName) FROM persons
|
||||
/// SELECT maxFullNameLength(firstName, lastName) FROM player
|
||||
///
|
||||
/// This method is never called after the finalize() method has been called.
|
||||
mutating func step(_ dbValues: [DatabaseValue]) throws
|
||||
|
||||
@@ -5,7 +5,23 @@ import UIKit
|
||||
#endif
|
||||
|
||||
/// A DatabaseQueue serializes access to an SQLite database.
|
||||
public final class DatabaseQueue {
|
||||
public final class DatabaseQueue: DatabaseWriter {
|
||||
private var writer: SerializedDatabase
|
||||
#if os(iOS)
|
||||
private weak var application: UIApplication?
|
||||
#endif
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// The database configuration
|
||||
public var configuration: Configuration {
|
||||
return writer.configuration
|
||||
}
|
||||
|
||||
/// The path to the database file; it is ":memory:" for in-memory databases.
|
||||
public var path: String {
|
||||
return writer.path
|
||||
}
|
||||
|
||||
// MARK: - Initializers
|
||||
|
||||
@@ -20,10 +36,11 @@ public final class DatabaseQueue {
|
||||
/// - configuration: A configuration.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public init(path: String, configuration: Configuration = Configuration()) throws {
|
||||
serializedDatabase = try SerializedDatabase(
|
||||
writer = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
schemaCache: SimpleDatabaseSchemaCache())
|
||||
schemaCache: SimpleDatabaseSchemaCache(),
|
||||
defaultLabel: "GRDB.DatabaseQueue")
|
||||
}
|
||||
|
||||
/// Opens an in-memory SQLite database.
|
||||
@@ -35,10 +52,11 @@ public final class DatabaseQueue {
|
||||
/// - parameter configuration: A configuration.
|
||||
public init(configuration: Configuration = Configuration()) {
|
||||
// Assume SQLite always succeeds creating an in-memory database
|
||||
serializedDatabase = try! SerializedDatabase(
|
||||
writer = try! SerializedDatabase(
|
||||
path: ":memory:",
|
||||
configuration: configuration,
|
||||
schemaCache: SimpleDatabaseSchemaCache())
|
||||
schemaCache: SimpleDatabaseSchemaCache(),
|
||||
defaultLabel: "GRDB.DatabaseQueue")
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
@@ -50,68 +68,9 @@ public final class DatabaseQueue {
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// The database configuration
|
||||
public var configuration: Configuration {
|
||||
return serializedDatabase.configuration
|
||||
}
|
||||
|
||||
/// The path to the database file; it is ":memory:" for in-memory databases.
|
||||
public var path: String {
|
||||
return serializedDatabase.path
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Database access
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// let persons = try dbQueue.inDatabase { db in
|
||||
/// try Person.fetchAll(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - 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 serializedDatabase.sync(block)
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// also rollbacked, but no error is thrown.
|
||||
///
|
||||
/// try dbQueue.inTransaction { db in
|
||||
/// db.execute(...)
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .immediate. 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 {
|
||||
try inDatabase { db in
|
||||
try db.inTransaction(kind) {
|
||||
try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension DatabaseQueue {
|
||||
|
||||
// MARK: - Memory management
|
||||
|
||||
@@ -121,10 +80,9 @@ public final class DatabaseQueue {
|
||||
///
|
||||
/// See also setupMemoryManagement(application:)
|
||||
public func releaseMemory() {
|
||||
inDatabase { $0.releaseMemory() }
|
||||
writer.sync { $0.releaseMemory() }
|
||||
}
|
||||
|
||||
|
||||
#if os(iOS)
|
||||
/// Listens to UIApplicationDidEnterBackgroundNotification and
|
||||
/// UIApplicationDidReceiveMemoryWarningNotification in order to release
|
||||
@@ -136,21 +94,26 @@ public final class 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)
|
||||
}
|
||||
|
||||
private var application: UIApplication?
|
||||
|
||||
@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 {
|
||||
@@ -162,92 +125,246 @@ public final class DatabaseQueue {
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
|
||||
@objc
|
||||
private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
|
||||
DispatchQueue.global().async {
|
||||
self.releaseMemory()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// MARK: - Not public
|
||||
|
||||
// https://www.sqlite.org/isolation.html
|
||||
//
|
||||
// > Within a single database connection X, a SELECT statement always
|
||||
// > sees all changes to the database that are completed prior to the
|
||||
// > start of the SELECT statement, whether committed or uncommitted.
|
||||
// > And the SELECT statement obviously does not see any changes that
|
||||
// > occur after the SELECT statement completes. But what about changes
|
||||
// > that occur while the SELECT statement is running? What if a SELECT
|
||||
// > statement is started and the sqlite3_step() interface steps through
|
||||
// > roughly half of its output, then some UPDATE statements are run by
|
||||
// > the application that modify the table that the SELECT statement is
|
||||
// > reading, then more calls to sqlite3_step() are made to finish out
|
||||
// > the SELECT statement? Will the later steps of the SELECT statement
|
||||
// > see the changes made by the UPDATE or not? The answer is that this
|
||||
// > behavior is undefined.
|
||||
//
|
||||
// This is why we use a serialized database:
|
||||
fileprivate var serializedDatabase: SerializedDatabase
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - Encryption
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
extension DatabaseQueue {
|
||||
|
||||
/// Changes the passphrase of an encrypted database
|
||||
public func change(passphrase: String) throws {
|
||||
try inDatabase { try $0.change(passphrase: passphrase) }
|
||||
}
|
||||
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) }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - DatabaseReader
|
||||
|
||||
extension DatabaseQueue : DatabaseReader {
|
||||
extension DatabaseQueue {
|
||||
|
||||
// MARK: - DatabaseReader Protocol Adoption
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// Synchronously executes a read-only block in a protected dispatch queue,
|
||||
/// and returns its result.
|
||||
///
|
||||
/// let persons = try dbQueue.read { db in
|
||||
/// try Person.fetchAll(...)
|
||||
/// let players = try dbQueue.read { db in
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// 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`.
|
||||
/// 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.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
return try inDatabase { try readOnly($0, block) }
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, *) {
|
||||
return try inDatabase { try readOnly($0, block) }
|
||||
} else {
|
||||
return try inDatabase(block)
|
||||
return try writer.sync { db in
|
||||
try db.readOnly { try block(db) }
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// Asynchronously executes a read-only block in a protected dispatch queue.
|
||||
///
|
||||
/// let players = try dbQueue.asyncRead { result in
|
||||
/// 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
|
||||
}
|
||||
#endif
|
||||
|
||||
block(.success(db))
|
||||
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Alias for `inDatabase`. See `DatabaseReader.unsafeRead`.
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// let players = try dbQueue.unsafeRead { db in
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try inDatabase(block)
|
||||
return try writer.sync(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// let players = try dbQueue.unsafeReentrantRead { db in
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It is unsafe because it fosters dangerous
|
||||
/// concurrency practices.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.reentrantSync(block)
|
||||
}
|
||||
|
||||
public func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
// DatabaseQueue can't perform parallel reads.
|
||||
// Perform a blocking read instead.
|
||||
return DatabaseFuture(DatabaseResult {
|
||||
// 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 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, "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 database updates in a protected dispatch queue,
|
||||
/// wrapped inside a transaction, and returns the result.
|
||||
///
|
||||
/// 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 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.
|
||||
/// - 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 updates(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, and returns the result.
|
||||
///
|
||||
/// Eventual concurrent database accesses are postponed until the updates
|
||||
/// are completed.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates.
|
||||
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.sync(updates)
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func inDatabase<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.sync(updates)
|
||||
}
|
||||
|
||||
/// Synchronously executes database updates in a protected dispatch queue, and
|
||||
/// returns the result.
|
||||
///
|
||||
/// // INSERT INTO player ...
|
||||
/// try dbQueue.unsafeReentrantWrite { db in
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It is unsafe because it fosters dangerous
|
||||
/// concurrency practices.
|
||||
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.reentrantSync(updates)
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -260,19 +377,18 @@ extension DatabaseQueue : DatabaseReader {
|
||||
/// return int + 1
|
||||
/// }
|
||||
/// dbQueue.add(function: fn)
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
|
||||
/// try dbQueue.read { db in
|
||||
/// try Int.fetchOne(db, sql: "SELECT succ(1)") // 2
|
||||
/// }
|
||||
public func add(function: DatabaseFunction) {
|
||||
inDatabase { $0.add(function: function) }
|
||||
writer.sync { $0.add(function: function) }
|
||||
}
|
||||
|
||||
/// Remove an SQL function.
|
||||
public func remove(function: DatabaseFunction) {
|
||||
inDatabase { $0.remove(function: function) }
|
||||
writer.sync { $0.remove(function: function) }
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// Add or redefine a collation.
|
||||
@@ -281,81 +397,15 @@ extension DatabaseQueue : DatabaseReader {
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// dbQueue.add(collation: collation)
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD")
|
||||
/// try dbQueue.write { db in
|
||||
/// try db.execute(sql: "CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD")
|
||||
/// }
|
||||
public func add(collation: DatabaseCollation) {
|
||||
inDatabase { $0.add(collation: collation) }
|
||||
writer.sync { $0.add(collation: collation) }
|
||||
}
|
||||
|
||||
/// Remove a collation.
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
inDatabase { $0.remove(collation: collation) }
|
||||
writer.sync { $0.remove(collation: collation) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - DatabaseWriter
|
||||
|
||||
extension DatabaseQueue : DatabaseWriter {
|
||||
|
||||
// MARK: - DatabaseWriter Protocol Adoption
|
||||
|
||||
/// Alias for `inDatabase`. See `DatabaseWriter.write`.
|
||||
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try inDatabase(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes *block*.
|
||||
///
|
||||
/// 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`.
|
||||
///
|
||||
/// This method must be called from the protected database dispatch queue.
|
||||
/// See `DatabaseWriter.readFromCurrentState`.
|
||||
public func readFromCurrentState(_ block: @escaping (Database) -> Void) {
|
||||
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
serializedDatabase.execute { readOnly($0, block) }
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, *) {
|
||||
serializedDatabase.execute { readOnly($0, block) }
|
||||
} else {
|
||||
serializedDatabase.execute(block)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// let persons = try dbQueue.unsafeReentrantWrite { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.reentrantSync(block)
|
||||
}
|
||||
}
|
||||
|
||||
// Wraps the block between two `PRAGMA query_only` statements.
|
||||
//
|
||||
// This method is unsafe because the two calls to `PRAGMA query_only` are
|
||||
// not guaranteed to be serialized (some other thread could mess with this).
|
||||
private func readOnly<T>(_ db: Database, _ block: (Database) throws -> T) rethrows -> T {
|
||||
if db.configuration.readonly {
|
||||
return try block(db)
|
||||
} else {
|
||||
try! db.execute("PRAGMA query_only = 1") // Assume can't fail
|
||||
let result = try block(db)
|
||||
try! db.execute("PRAGMA query_only = 0") // Assume can't fail
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// The protocol for all types that can fetch values from a database.
|
||||
@@ -17,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
|
||||
|
||||
@@ -29,14 +36,14 @@ public protocol DatabaseReader : class {
|
||||
///
|
||||
/// try reader.read { db in
|
||||
/// // Those two values are guaranteed to be equal, even if the
|
||||
/// // `wines` table is modified between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// // `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 wines")!
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds
|
||||
@@ -48,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.
|
||||
///
|
||||
@@ -58,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 wines")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// // 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() { ... }
|
||||
/// }
|
||||
///
|
||||
@@ -79,6 +113,40 @@ public protocol DatabaseReader : class {
|
||||
/// happen while establishing the read access to the database.
|
||||
func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T
|
||||
|
||||
/// Synchronously executes a block that takes a database connection, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// The two guarantees of the safe `read` method are lifted:
|
||||
///
|
||||
/// The block argument is not isolated: eventual concurrent database updates
|
||||
/// are visible inside the block:
|
||||
///
|
||||
/// try reader.unsafeReentrantRead { db in
|
||||
/// // Those two values may be different because some other thread
|
||||
/// // 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, sql: "SELECT ...")
|
||||
/// while let row = try rows.next() { ... }
|
||||
/// }
|
||||
///
|
||||
/// The block argument is not prevented from writing (DatabaseQueue, in
|
||||
/// particular, will accept database modifications in `unsafeReentrantRead`).
|
||||
///
|
||||
/// - 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.
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T
|
||||
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
@@ -92,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)
|
||||
|
||||
@@ -108,11 +176,32 @@ public protocol DatabaseReader : class {
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// reader.add(collation: collation)
|
||||
/// try reader.execute("SELECT * FROM files 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 {
|
||||
@@ -131,44 +220,98 @@ 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.write { dbDest in
|
||||
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)
|
||||
}
|
||||
|
||||
afterBackupInit?()
|
||||
|
||||
do {
|
||||
backupLoop: while true {
|
||||
switch sqlite3_backup_step(backup, -1) {
|
||||
case SQLITE_DONE:
|
||||
afterBackupStep?()
|
||||
break backupLoop
|
||||
case SQLITE_OK:
|
||||
afterBackupStep?()
|
||||
case let code:
|
||||
throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
sqlite3_backup_finish(backup)
|
||||
throw error
|
||||
}
|
||||
|
||||
switch sqlite3_backup_finish(backup) {
|
||||
case SQLITE_OK:
|
||||
break
|
||||
case let code:
|
||||
throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage)
|
||||
}
|
||||
|
||||
dbDest.clearSchemaCache()
|
||||
try writer.writeWithoutTransaction { dbDest in
|
||||
try Database.backup(
|
||||
from: dbFrom,
|
||||
to: dbDest,
|
||||
afterBackupInit: afterBackupInit,
|
||||
afterBackupStep: afterBackupStep)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A type-erased DatabaseReader
|
||||
///
|
||||
/// Instances of AnyDatabaseReader forward their methods to an arbitrary
|
||||
/// underlying database reader.
|
||||
public final class AnyDatabaseReader: DatabaseReader {
|
||||
private let base: DatabaseReader
|
||||
|
||||
/// Creates a database reader that wraps a base database reader.
|
||||
public init(_ base: DatabaseReader) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public var configuration: Configuration {
|
||||
return base.configuration
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// :nodoc:
|
||||
public func read<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
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)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeReentrantRead(block)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// :nodoc:
|
||||
public func add(function: DatabaseFunction) {
|
||||
base.add(function: function)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func remove(function: DatabaseFunction) {
|
||||
base.remove(function: function)
|
||||
}
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// :nodoc:
|
||||
public func add(collation: DatabaseCollation) {
|
||||
base.add(collation: collation)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
base.remove(collation: collation)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
/// DatabaseRegion defines a region in the database. DatabaseRegion is dedicated
|
||||
/// to help transaction observers recognize impactful database changes in their
|
||||
/// `observes(eventsOfKind:)` and `databaseDidChange(with:)` methods.
|
||||
///
|
||||
/// A database region is the union of any number of "table regions", which can
|
||||
/// cover a full table, or the combination of columns and rows:
|
||||
///
|
||||
/// |Table1 | |Table2 | |Table3 | |Table4 | |Table5 |
|
||||
/// |-------| |-------| |-------| |-------| |-------|
|
||||
/// |x|x|x|x| |x| | | | |x|x|x|x| |x|x| |x| | | | | |
|
||||
/// |x|x|x|x| |x| | | | | | | | | | | | | | | |x| | |
|
||||
/// |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | |
|
||||
/// |x|x|x|x| |x| | | | | | | | | | | | | | | | | | |
|
||||
///
|
||||
/// 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 = try db.makeSelectStatement(sql: "SELECT name, score FROM player")
|
||||
/// let region = statement.databaseRegion
|
||||
///
|
||||
/// - `FetchRequest.databaseRegion(_:)`
|
||||
///
|
||||
/// 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 {
|
||||
// full database
|
||||
return false
|
||||
}
|
||||
return tableRegions.isEmpty
|
||||
}
|
||||
|
||||
/// The region that covers the full database: all columns and all rows
|
||||
/// from all tables.
|
||||
public static let fullDatabase = DatabaseRegion(tableRegions: nil)
|
||||
|
||||
/// Creates an empty database region.
|
||||
public init() {
|
||||
self.init(tableRegions: [:])
|
||||
}
|
||||
|
||||
/// 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)])
|
||||
}
|
||||
|
||||
/// Full columns in a table: (some columns in a table) × (all rows)
|
||||
init(table: String, columns: Set<String>) {
|
||||
self.init(tableRegions: [table: TableRegion(columns: columns, rowIds: nil)])
|
||||
}
|
||||
|
||||
/// Full rows in a table: (all columns in a table) × (some rows)
|
||||
init(table: String, rowIds: Set<Int64>) {
|
||||
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: rowIds)])
|
||||
}
|
||||
|
||||
/// Returns the intersection of this region and the given one.
|
||||
///
|
||||
/// This method is not public because there is no known public use case for
|
||||
/// this intersection. It is currently only used as support for
|
||||
/// the isModified(byEventsOfKind:) method.
|
||||
func intersection(_ other: DatabaseRegion) -> DatabaseRegion {
|
||||
guard let tableRegions = tableRegions else { return other }
|
||||
guard let otherTableRegions = other.tableRegions else { return self }
|
||||
|
||||
var tableRegionsIntersection: [String: TableRegion] = [:]
|
||||
for (table, tableRegion) in tableRegions {
|
||||
guard let otherTableRegion = otherTableRegions
|
||||
.first(where: { (otherTable, _) in otherTable == table })?
|
||||
.value else { continue }
|
||||
let tableRegionIntersection = tableRegion.intersection(otherTableRegion)
|
||||
guard !tableRegionIntersection.isEmpty else { continue }
|
||||
tableRegionsIntersection[table] = tableRegionIntersection
|
||||
}
|
||||
|
||||
return DatabaseRegion(tableRegions: tableRegionsIntersection)
|
||||
}
|
||||
|
||||
/// Only keeps those rowIds in the given table
|
||||
func tableIntersection(_ table: String, rowIds: Set<Int64>) -> DatabaseRegion {
|
||||
guard var tableRegions = tableRegions else {
|
||||
return DatabaseRegion(table: table, rowIds: rowIds)
|
||||
}
|
||||
|
||||
guard let tableRegion = tableRegions[table] else {
|
||||
return self
|
||||
}
|
||||
|
||||
let intersection = tableRegion.intersection(TableRegion(columns: nil, rowIds: rowIds))
|
||||
if intersection.isEmpty {
|
||||
tableRegions.removeValue(forKey: table)
|
||||
} else {
|
||||
tableRegions[table] = intersection
|
||||
}
|
||||
return DatabaseRegion(tableRegions: tableRegions)
|
||||
}
|
||||
|
||||
/// Returns the union of this region and the given one.
|
||||
public func union(_ other: DatabaseRegion) -> DatabaseRegion {
|
||||
guard let tableRegions = tableRegions else { return .fullDatabase }
|
||||
guard let otherTableRegions = other.tableRegions else { return .fullDatabase }
|
||||
|
||||
var tableRegionsUnion: [String: TableRegion] = [:]
|
||||
let tableNames = Set(tableRegions.keys).union(Set(otherTableRegions.keys))
|
||||
for table in tableNames {
|
||||
let tableRegion = tableRegions[table]
|
||||
let otherTableRegion = otherTableRegions[table]
|
||||
let tableRegionUnion: TableRegion
|
||||
switch (tableRegion, otherTableRegion) {
|
||||
case (nil, nil):
|
||||
preconditionFailure()
|
||||
case let (nil, tableRegion?), let (tableRegion?, nil):
|
||||
tableRegionUnion = tableRegion
|
||||
case let (tableRegion?, otherTableRegion?):
|
||||
tableRegionUnion = tableRegion.union(otherTableRegion)
|
||||
}
|
||||
tableRegionsUnion[table] = tableRegionUnion
|
||||
}
|
||||
|
||||
return DatabaseRegion(tableRegions: tableRegionsUnion)
|
||||
}
|
||||
|
||||
/// Inserts the given region into this region
|
||||
public mutating func formUnion(_ other: DatabaseRegion) {
|
||||
self = union(other)
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
|
||||
// MARK: - Database Events
|
||||
|
||||
/// Returns whether the content in the region would be impacted if the
|
||||
/// database were modified by an event of this kind.
|
||||
public func isModified(byEventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
return intersection(eventKind.modifiedRegion).isEmpty == false
|
||||
}
|
||||
|
||||
/// Returns whether the content in the region is impacted by this event.
|
||||
///
|
||||
/// - precondition: event has been filtered by the same region
|
||||
/// in the TransactionObserver.observes(eventsOfKind:) method, by calling
|
||||
/// region.isModified(byEventsOfKind:)
|
||||
public func isModified(by event: DatabaseEvent) -> Bool {
|
||||
guard let tableRegions = tableRegions else {
|
||||
// Full database: all changes are impactful
|
||||
return true
|
||||
}
|
||||
|
||||
if tableRegions.count == 1 {
|
||||
// Fast path when the region contains a single table.
|
||||
//
|
||||
// We can apply the precondition: 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 in debug mode
|
||||
let tableRegion = tableRegions[tableRegions.startIndex].value
|
||||
return tableRegion.contains(rowID: event.rowID)
|
||||
} else {
|
||||
// Slow path when several tables are observed.
|
||||
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:)
|
||||
""")
|
||||
}
|
||||
return tableRegion.contains(rowID: event.rowID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Equatable
|
||||
extension DatabaseRegion {
|
||||
/// :nodoc:
|
||||
public static func == (lhs: DatabaseRegion, rhs: DatabaseRegion) -> Bool {
|
||||
switch (lhs.tableRegions, rhs.tableRegions) {
|
||||
case (nil, nil):
|
||||
return true
|
||||
case let (ltableRegions?, rtableRegions?):
|
||||
let ltableNames = Set(ltableRegions.keys)
|
||||
let rtableNames = Set(rtableRegions.keys)
|
||||
guard ltableNames == rtableNames else {
|
||||
return false
|
||||
}
|
||||
for tableName in ltableNames where ltableRegions[tableName]! != rtableRegions[tableName]! {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// CustomStringConvertible
|
||||
extension DatabaseRegion {
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
guard let tableRegions = tableRegions else {
|
||||
return "full database"
|
||||
}
|
||||
if tableRegions.isEmpty {
|
||||
return "empty"
|
||||
}
|
||||
return tableRegions
|
||||
.sorted(by: { (l, r) in l.key < r.key })
|
||||
.map { (table, tableRegion) in
|
||||
var desc = table
|
||||
if let columns = tableRegion.columns {
|
||||
desc += "(" + columns.sorted().joined(separator: ",") + ")"
|
||||
} else {
|
||||
desc += "(*)"
|
||||
}
|
||||
if let rowIds = tableRegion.rowIds {
|
||||
desc += "[" + rowIds.sorted().map { "\($0)" }.joined(separator: ",") + "]"
|
||||
}
|
||||
return desc
|
||||
}
|
||||
.joined(separator: ",")
|
||||
}
|
||||
}
|
||||
|
||||
private struct TableRegion: Equatable {
|
||||
var columns: Set<String>? // nil means "all columns"
|
||||
var rowIds: Set<Int64>? // nil means "all rowids"
|
||||
|
||||
var isEmpty: Bool {
|
||||
if let columns = columns, columns.isEmpty { return true }
|
||||
if let rowIds = rowIds, rowIds.isEmpty { return true }
|
||||
return false
|
||||
}
|
||||
|
||||
func intersection(_ other: TableRegion) -> TableRegion {
|
||||
let columnsIntersection: Set<String>?
|
||||
switch (self.columns, other.columns) {
|
||||
case let (nil, columns), let (columns, nil):
|
||||
columnsIntersection = columns
|
||||
case let (columns?, other?):
|
||||
columnsIntersection = columns.intersection(other)
|
||||
}
|
||||
|
||||
let rowIdsIntersection: Set<Int64>?
|
||||
switch (self.rowIds, other.rowIds) {
|
||||
case let (nil, rowIds), let (rowIds, nil):
|
||||
rowIdsIntersection = rowIds
|
||||
case let (rowIds?, other?):
|
||||
rowIdsIntersection = rowIds.intersection(other)
|
||||
}
|
||||
|
||||
return TableRegion(columns: columnsIntersection, rowIds: rowIdsIntersection)
|
||||
}
|
||||
|
||||
func union(_ other: TableRegion) -> TableRegion {
|
||||
let columnsUnion: Set<String>?
|
||||
switch (self.columns, other.columns) {
|
||||
case (nil, _), (_, nil):
|
||||
columnsUnion = nil
|
||||
case let (columns?, other?):
|
||||
columnsUnion = columns.union(other)
|
||||
}
|
||||
|
||||
let rowIdsUnion: Set<Int64>?
|
||||
switch (self.rowIds, other.rowIds) {
|
||||
case (nil, _), (_, nil):
|
||||
rowIdsUnion = nil
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,11 @@
|
||||
/// The protocol for schema cache.
|
||||
///
|
||||
/// This protocol must not contain values that are valid for a single connection
|
||||
/// only, because several connections can share the same schema cache.
|
||||
///
|
||||
/// Statements can't be cached here, for example.
|
||||
/// The protocol for database schema cache.
|
||||
protocol DatabaseSchemaCache {
|
||||
mutating func clear()
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo??
|
||||
mutating func set(primaryKey: PrimaryKeyInfo?, forTable table: String)
|
||||
var schemaInfo: SchemaInfo? { get set }
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo?
|
||||
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String)
|
||||
|
||||
func columns(in table: String) -> [ColumnInfo]?
|
||||
mutating func set(columns: [ColumnInfo], forTable table: String)
|
||||
@@ -21,24 +18,26 @@ protocol DatabaseSchemaCache {
|
||||
}
|
||||
|
||||
/// A thread-unsafe database schema cache
|
||||
final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
private var primaryKeys: [String: PrimaryKeyInfo?] = [:]
|
||||
struct SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
var schemaInfo: SchemaInfo?
|
||||
private var primaryKeys: [String: PrimaryKeyInfo] = [:]
|
||||
private var columns: [String: [ColumnInfo]] = [:]
|
||||
private var indexes: [String: [IndexInfo]] = [:]
|
||||
private var foreignKeys: [String: [ForeignKeyInfo]] = [:]
|
||||
|
||||
func clear() {
|
||||
mutating func clear() {
|
||||
primaryKeys = [:]
|
||||
columns = [:]
|
||||
indexes = [:]
|
||||
foreignKeys = [:]
|
||||
schemaInfo = nil
|
||||
}
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo?? {
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
|
||||
return primaryKeys[table]
|
||||
}
|
||||
|
||||
func set(primaryKey: PrimaryKeyInfo?, forTable table: String) {
|
||||
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
|
||||
primaryKeys[table] = primaryKey
|
||||
}
|
||||
|
||||
@@ -46,7 +45,7 @@ final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
return columns[table]
|
||||
}
|
||||
|
||||
func set(columns: [ColumnInfo], forTable table: String) {
|
||||
mutating func set(columns: [ColumnInfo], forTable table: String) {
|
||||
self.columns[table] = columns
|
||||
}
|
||||
|
||||
@@ -54,7 +53,7 @@ final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
return indexes[table]
|
||||
}
|
||||
|
||||
func set(indexes: [IndexInfo], forTable table: String) {
|
||||
mutating func set(indexes: [IndexInfo], forTable table: String) {
|
||||
self.indexes[table] = indexes
|
||||
}
|
||||
|
||||
@@ -62,48 +61,29 @@ final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
return foreignKeys[table]
|
||||
}
|
||||
|
||||
func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
|
||||
mutating func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
|
||||
self.foreignKeys[table] = foreignKeys
|
||||
}
|
||||
}
|
||||
|
||||
/// A thread-safe database schema cache
|
||||
final class SharedDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
private let cache = ReadWriteBox(SimpleDatabaseSchemaCache())
|
||||
/// An always empty database schema cache
|
||||
struct EmptyDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
func clear() { }
|
||||
|
||||
func clear() {
|
||||
cache.write { $0.clear() }
|
||||
var schemaInfo: SchemaInfo? {
|
||||
get { return nil }
|
||||
set { }
|
||||
}
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo?? {
|
||||
return cache.read { $0.primaryKey(table) }
|
||||
}
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo? { return nil }
|
||||
func set(primaryKey: PrimaryKeyInfo, forTable table: String) { }
|
||||
|
||||
func set(primaryKey: PrimaryKeyInfo?, forTable table: String) {
|
||||
cache.write { $0.set(primaryKey: primaryKey, forTable: table) }
|
||||
}
|
||||
func columns(in table: String) -> [ColumnInfo]? { return nil }
|
||||
func set(columns: [ColumnInfo], forTable table: String) { }
|
||||
|
||||
func columns(in table: String) -> [ColumnInfo]? {
|
||||
return cache.read { $0.columns(in: table) }
|
||||
}
|
||||
func indexes(on table: String) -> [IndexInfo]? { return nil }
|
||||
func set(indexes: [IndexInfo], forTable table: String) { }
|
||||
|
||||
func set(columns: [ColumnInfo], forTable table: String) {
|
||||
cache.write { $0.set(columns: columns, forTable: table) }
|
||||
}
|
||||
|
||||
func indexes(on table: String) -> [IndexInfo]? {
|
||||
return cache.read { $0.indexes(on: table) }
|
||||
}
|
||||
|
||||
func set(indexes: [IndexInfo], forTable table: String) {
|
||||
cache.write { $0.set(indexes: indexes, forTable: table) }
|
||||
}
|
||||
|
||||
func foreignKeys(on table: String) -> [ForeignKeyInfo]? {
|
||||
return cache.read { $0.foreignKeys(on: table) }
|
||||
}
|
||||
|
||||
func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
|
||||
cache.write { $0.set(foreignKeys: foreignKeys, forTable: table) }
|
||||
}
|
||||
func foreignKeys(on table: String) -> [ForeignKeyInfo]? { return nil }
|
||||
func set(foreignKeys: [ForeignKeyInfo], forTable table: String) { }
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
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 {
|
||||
private var serializedDatabase: SerializedDatabase
|
||||
|
||||
/// The database configuration
|
||||
public var configuration: Configuration {
|
||||
return serializedDatabase.configuration
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
serializedDatabase = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
schemaCache: SimpleDatabaseSchemaCache(),
|
||||
defaultLabel: defaultLabel,
|
||||
purpose: purpose)
|
||||
|
||||
try serializedDatabase.sync { db in
|
||||
// Assert WAL 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)")
|
||||
}
|
||||
try db.beginSnapshotIsolation()
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
// Leave snapshot isolation
|
||||
serializedDatabase.sync { db in
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// DatabaseReader
|
||||
extension DatabaseSnapshot {
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// Synchronously executes a read-only block that takes a database
|
||||
/// connection, and returns its result.
|
||||
///
|
||||
/// let players = try snapshot.read { db in
|
||||
/// try Player.fetchAll(...)
|
||||
/// }
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.sync(block)
|
||||
}
|
||||
|
||||
#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
|
||||
|
||||
/// Alias for `read`. See `DatabaseReader.unsafeRead`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.sync(block)
|
||||
}
|
||||
|
||||
/// Alias for `read`. See `DatabaseReader.unsafeReentrantRead`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try serializedDatabase.sync(block)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
public func add(function: DatabaseFunction) {
|
||||
serializedDatabase.sync { $0.add(function: function) }
|
||||
}
|
||||
|
||||
public func remove(function: DatabaseFunction) {
|
||||
serializedDatabase.sync { $0.remove(function: function) }
|
||||
}
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
public func add(collation: DatabaseCollation) {
|
||||
serializedDatabase.sync { $0.add(collation: 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,7 +1,10 @@
|
||||
import Foundation
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
// MARK: - DatabaseValue
|
||||
@@ -9,10 +12,15 @@ import Foundation
|
||||
/// DatabaseValue is the intermediate type between SQLite and your values.
|
||||
///
|
||||
/// See https://www.sqlite.org/datatype3.html
|
||||
public struct DatabaseValue {
|
||||
public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLExpression {
|
||||
/// The SQLite storage
|
||||
public let storage: Storage
|
||||
|
||||
/// The NULL DatabaseValue.
|
||||
public static let null = DatabaseValue(storage: .null)
|
||||
|
||||
/// An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB).
|
||||
public enum Storage : Equatable {
|
||||
public enum Storage: Equatable {
|
||||
/// The NULL storage class.
|
||||
case null
|
||||
|
||||
@@ -52,21 +60,15 @@ public struct DatabaseValue {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The SQLite storage
|
||||
public let storage: Storage
|
||||
|
||||
/// The NULL DatabaseValue.
|
||||
public static let null = DatabaseValue(storage: .null)
|
||||
|
||||
/// Creates a DatabaseValue from Any.
|
||||
///
|
||||
/// The result is nil unless object adopts DatabaseValueConvertible.
|
||||
@@ -77,7 +79,6 @@ public struct DatabaseValue {
|
||||
self = convertible.databaseValue
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Extracting Value
|
||||
|
||||
/// Returns true if databaseValue is NULL.
|
||||
@@ -90,13 +91,9 @@ public struct DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Not Public
|
||||
|
||||
init(storage: Storage) {
|
||||
// This initializer is not public because Storage is not a safe type:
|
||||
// one can create a Storage of zero-length Data, which is invalid
|
||||
// because SQLite can't store zero-length blobs.
|
||||
self.storage = storage
|
||||
}
|
||||
|
||||
@@ -112,30 +109,36 @@ public struct DatabaseValue {
|
||||
case SQLITE_TEXT:
|
||||
storage = .string(String(cString: sqlite3_value_text(sqliteValue)!))
|
||||
case SQLITE_BLOB:
|
||||
let bytes = unsafeBitCast(sqlite3_value_blob(sqliteValue), to: UnsafePointer<UInt8>.self)
|
||||
let count = Int(sqlite3_value_bytes(sqliteValue))
|
||||
storage = .blob(Data(bytes: bytes, count: count)) // copy bytes
|
||||
if let bytes = sqlite3_value_blob(sqliteValue) {
|
||||
let count = Int(sqlite3_value_bytes(sqliteValue))
|
||||
storage = .blob(Data(bytes: bytes, count: count)) // copy bytes
|
||||
} else {
|
||||
storage = .blob(Data())
|
||||
}
|
||||
case let type:
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError("Unexpected SQLite value type: \(type)")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// 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:
|
||||
let bytes = unsafeBitCast(sqlite3_column_blob(sqliteStatement, Int32(index)), to: UnsafePointer<UInt8>.self)
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
storage = .blob(Data(bytes: bytes, count: count)) // copy bytes
|
||||
if let bytes = sqlite3_column_blob(sqliteStatement, index) {
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, index))
|
||||
storage = .blob(Data(bytes: bytes, count: count)) // copy bytes
|
||||
} else {
|
||||
storage = .blob(Data())
|
||||
}
|
||||
case let type:
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError("Unexpected SQLite column type: \(type)")
|
||||
@@ -143,26 +146,25 @@ public struct DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Hashable & Equatable
|
||||
|
||||
/// DatabaseValue adopts Hashable.
|
||||
extension DatabaseValue : Hashable {
|
||||
// Hashable
|
||||
extension DatabaseValue {
|
||||
|
||||
/// The hash value
|
||||
public var hashValue: Int {
|
||||
/// :nodoc:
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,17 +187,17 @@ extension DatabaseValue : Hashable {
|
||||
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)):
|
||||
return int64EqualDouble(lhs, rhs)
|
||||
case (.double(let lhs), .int64(let rhs)):
|
||||
return int64EqualDouble(rhs, lhs)
|
||||
case (.string(let lhs), .string(let rhs)):
|
||||
case let (.int64(lhs), .double(rhs)):
|
||||
return Int64(exactly: rhs) == lhs
|
||||
case let (.double(lhs), .int64(rhs)):
|
||||
return rhs == Int64(exactly: lhs)
|
||||
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
|
||||
@@ -203,100 +205,8 @@ extension DatabaseValue : Hashable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if i and d hold exactly the same value, and if converting one
|
||||
/// type to the other does not lose any information.
|
||||
private func int64EqualDouble(_ i: Int64, _ d: Double) -> Bool {
|
||||
// See http://stackoverflow.com/questions/33719132/how-to-test-for-lossless-double-integer-conversion/33784296#33784296
|
||||
return (d >= Double(Int64.min))
|
||||
&& (d < Double(Int64.max))
|
||||
&& (round(d) == d)
|
||||
&& (i == Int64(d))
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Lossless conversions
|
||||
|
||||
// DatabaseValueConvertible
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - DatabaseValueConvertible & SQLExpressible & SQLExpression
|
||||
|
||||
/// DatabaseValue adopts DatabaseValueConvertible.
|
||||
extension DatabaseValue : DatabaseValueConvertible {
|
||||
/// Returns self
|
||||
public var databaseValue: DatabaseValue {
|
||||
return self
|
||||
@@ -308,34 +218,36 @@ extension DatabaseValue : DatabaseValueConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValue : SQLExpressible {
|
||||
|
||||
// SQLExpressible
|
||||
extension DatabaseValue {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public var sqlExpression: SQLExpression {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
/// DatabaseValue adopts SQLExpression.
|
||||
extension DatabaseValue : SQLExpression {
|
||||
// SQLExpression
|
||||
extension DatabaseValue {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
/// :nodoc:
|
||||
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
|
||||
// fast path for NULL
|
||||
if isNull {
|
||||
return "NULL"
|
||||
}
|
||||
|
||||
if arguments != nil {
|
||||
arguments!.values.append(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])! }
|
||||
}
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public var negated: SQLExpression {
|
||||
switch storage {
|
||||
case .null:
|
||||
@@ -354,18 +266,24 @@ extension DatabaseValue : SQLExpression {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
/// DatabaseValue adopts CustomStringConvertible.
|
||||
extension DatabaseValue : CustomStringConvertible {
|
||||
/// A textual representation of `self`.
|
||||
// CustomStringConvertible
|
||||
extension DatabaseValue {
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
switch storage {
|
||||
case .null:
|
||||
@@ -377,7 +295,49 @@ extension DatabaseValue : CustomStringConvertible {
|
||||
case .string(let string):
|
||||
return String(reflecting: string)
|
||||
case .blob(let data):
|
||||
return data.description
|
||||
return "Data(\(data.description))"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,3 +1,11 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
// MARK: - DatabaseValueConvertible
|
||||
|
||||
/// Types that adopt DatabaseValueConvertible can be initialized from
|
||||
@@ -6,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:...) // DatabaseCursor<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 ...")
|
||||
/// try String.fetchCursor(statement, arguments:...) // DatabaseCursor<String>
|
||||
/// 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 }
|
||||
|
||||
@@ -24,38 +32,147 @@ public protocol DatabaseValueConvertible : SQLExpressible {
|
||||
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self?
|
||||
}
|
||||
|
||||
// SQLExpressible adoption
|
||||
extension DatabaseValueConvertible {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public var sqlExpression: SQLExpression {
|
||||
return databaseValue
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor of database values extracted from a single column.
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// 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 {
|
||||
@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 {
|
||||
_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 {
|
||||
// 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
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return Value.decode(from: _sqliteStatement, atUncheckedIndex: _columnIndex)
|
||||
case let code:
|
||||
try _statement.didFail(withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor of optional database values extracted from a single column.
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// 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 {
|
||||
@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 {
|
||||
_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 {
|
||||
// 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
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return Value.decodeIfPresent(from: _sqliteStatement, atUncheckedIndex: _columnIndex)
|
||||
case let code:
|
||||
try _statement.didFail(withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// DatabaseValueConvertible comes with built-in methods that allow to fetch
|
||||
/// cursors, arrays, or single values:
|
||||
///
|
||||
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // DatabaseCursor<String>
|
||||
/// try String.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 ...")
|
||||
/// try String.fetchCursor(statement, arguments:...) // DatabaseCursor<String>
|
||||
/// 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.
|
||||
extension DatabaseValueConvertible {
|
||||
|
||||
|
||||
// MARK: Fetching From SelectStatement
|
||||
|
||||
/// Returns a cursor over values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let names = try String.fetchCursor(statement) // DatabaseCursor<String>
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try String.fetchCursor(statement) // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
@@ -71,18 +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 -> DatabaseCursor<Self> {
|
||||
// Reuse a single mutable row for performance
|
||||
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
return statement.cursor(arguments: arguments, next: {
|
||||
let dbValue: DatabaseValue = row.value(atIndex: 0)
|
||||
return dbValue.losslessConvert(sql: statement.sql, arguments: arguments) as Self
|
||||
})
|
||||
public static func fetchCursor(
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> DatabaseValueCursor<Self>
|
||||
{
|
||||
return try DatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from a prepared statement.
|
||||
///
|
||||
/// 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:
|
||||
@@ -91,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))
|
||||
}
|
||||
|
||||
@@ -100,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:
|
||||
@@ -109,82 +231,25 @@ 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? {
|
||||
// Reuse a single mutable row for performance
|
||||
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
let cursor: DatabaseCursor<Self?> = statement.cursor(arguments: arguments, next: {
|
||||
let dbValue: DatabaseValue = row.value(atIndex: 0)
|
||||
return dbValue.losslessConvert(sql: statement.sql, arguments: arguments) as Self?
|
||||
})
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching From Request
|
||||
|
||||
/// Returns a cursor over values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn)
|
||||
/// let names = try String.fetchCursor(db, request) // DatabaseCursor<String>
|
||||
/// for let name = try names.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A fetch request.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseCursor<Self> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn)
|
||||
/// let names = try String.fetchAll(db, request) // [String]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ request: Request) throws -> [Self] {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchAll(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from a fetch request.
|
||||
///
|
||||
/// The result is nil if the query returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn)
|
||||
/// let name = try String.fetchOne(db, request) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: Database, _ request: Request) throws -> Self? {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchOne(statement, adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
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 ...") // DatabaseCursor<String>
|
||||
/// let names = try String.fetchCursor(db, sql: "SELECT name FROM ...") // Cursor of String
|
||||
/// while let name = try name.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
@@ -197,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 -> DatabaseCursor<Self> {
|
||||
return try fetchCursor(db, SQLRequest(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(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.
|
||||
@@ -225,29 +302,147 @@ 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(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))
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching From FetchRequest
|
||||
|
||||
/// Returns a cursor over values fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try String.fetchCursor(db, request) // Cursor of String
|
||||
/// while let name = try name.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - 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 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.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try String.fetchAll(db, request) // [String]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - 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 request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchAll(request.statement, adapter: request.adapter)
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from a fetch request.
|
||||
///
|
||||
/// The result is nil if the query returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let request = Player.filter(key: 1).select(Column("name"))
|
||||
/// let name = try String.fetchOne(db, request) // String?
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - 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 request = try request.makePreparedRequest(db, forSingleResult: true)
|
||||
return try fetchOne(request.statement, adapter: request.adapter)
|
||||
}
|
||||
}
|
||||
|
||||
extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching Values
|
||||
|
||||
/// A cursor over fetched values.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches String
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String
|
||||
/// while let string = try strings.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched values.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches String
|
||||
/// let strings = try request.fetchAll(db) // [String]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
return try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched value.
|
||||
///
|
||||
/// The result is nil if the request returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches String
|
||||
/// let string = try request.fetchOne(db) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
return try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Swift's Optional comes with built-in methods that allow to fetch cursors
|
||||
/// and arrays of optional DatabaseValueConvertible:
|
||||
///
|
||||
/// try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // DatabaseCursor<String?>
|
||||
/// try Optional<String>.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 ...")
|
||||
/// try Optional<String>.fetchCursor(statement, arguments:...) // DatabaseCursor<String?>
|
||||
/// 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?]
|
||||
///
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
@@ -257,8 +452,8 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a cursor over optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchCursor(statement) // DatabaseCursor<String?>
|
||||
/// let 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?
|
||||
/// ...
|
||||
/// }
|
||||
@@ -274,18 +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 -> DatabaseCursor<Wrapped?> {
|
||||
// Reuse a single mutable row for performance
|
||||
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
return statement.cursor(arguments: arguments, next: {
|
||||
let dbValue: DatabaseValue = row.value(atIndex: 0)
|
||||
return dbValue.losslessConvert(sql: statement.sql, arguments: arguments) as Wrapped?
|
||||
})
|
||||
public static func fetchCursor(
|
||||
_ statement: SelectStatement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
{
|
||||
return try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a prepared statement.
|
||||
///
|
||||
/// 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:
|
||||
@@ -294,60 +489,23 @@ 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))
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching From Request
|
||||
|
||||
/// Returns a cursor over optional values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn)
|
||||
/// let names = try Optional<String>.fetchCursor(db, request) // DatabaseCursor<String?>
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - requet: A fetch request.
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseCursor<Wrapped?> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn)
|
||||
/// let names = try Optional<String>.fetchAll(db, request) // [String?]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ request: Request) throws -> [Wrapped?] {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchAll(statement, adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching From SQL
|
||||
|
||||
/// Returns a cursor over optional values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // DatabaseCursor<String?>
|
||||
/// let names = try Optional<String>.fetchCursor(db, sql: "SELECT name FROM ...") // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
@@ -360,26 +518,120 @@ 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 -> DatabaseCursor<Wrapped?> {
|
||||
return try fetchCursor(db, SQLRequest(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(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))
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching From FetchRequest
|
||||
|
||||
/// Returns a cursor over optional values fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try Optional<String>.fetchCursor(db, request) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - 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 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.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try Optional<String>.fetchAll(db, request) // [String?]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - 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 request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchAll(request.statement, adapter: request.adapter)
|
||||
}
|
||||
}
|
||||
|
||||
extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching Optional values
|
||||
|
||||
/// A cursor over fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String?
|
||||
/// while let string = try strings.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor<RowDecoder._Wrapped> {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchAll(db) // [String?]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchAll(db, self)
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import Dispatch
|
||||
|
||||
/// The protocol for all types that can update a database.
|
||||
///
|
||||
/// It is adopted by DatabaseQueue and DatabasePool.
|
||||
@@ -13,113 +15,681 @@
|
||||
/// 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 DatabaseWriter : DatabaseReader {
|
||||
public protocol DatabaseWriter: DatabaseReader {
|
||||
|
||||
// MARK: - Writing in Database
|
||||
|
||||
/// 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 throw an error, the transaction is rollbacked and the
|
||||
/// error is rethrown.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the transaction
|
||||
/// has completed.
|
||||
///
|
||||
/// Eventual concurrent reads are guaranteed to not see any partial updates
|
||||
/// of the database until the transaction has completed.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
func write<T>(_ block: (Database) throws -> T) rethrows -> T
|
||||
|
||||
/// Synchronously executes a block that takes a database connection, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates, or by the
|
||||
/// wrapping transaction.
|
||||
func write<T>(_ updates: (Database) throws -> T) throws -> T
|
||||
|
||||
/// 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 updates
|
||||
/// are completed.
|
||||
///
|
||||
/// Eventual concurrent reads may see partial updates unless you wrap them
|
||||
/// in a transaction.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates.
|
||||
func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
/// wrapped inside a transaction.
|
||||
///
|
||||
/// If the updates throw an error, the transaction is rollbacked.
|
||||
///
|
||||
/// The *completion* closure is always called with the result of the
|
||||
/// database updates. Its arguments are a database connection and the
|
||||
/// result of the transaction. This result is a failure if the transaction
|
||||
/// could not be committed.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the transaction
|
||||
/// and the *completion* closure have completed.
|
||||
///
|
||||
/// Eventual concurrent reads are guaranteed to not see any partial updates
|
||||
/// of the database until the transaction has completed.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - parameter completion: A closure that is called with the eventual
|
||||
/// transaction error.
|
||||
/// - throws: The error thrown by the updates, or by the wrapping transaction.
|
||||
func asyncWrite<T>(
|
||||
_ updates: @escaping (Database) throws -> T,
|
||||
completion: @escaping (Database, Result<T, Error>) -> Void)
|
||||
#endif
|
||||
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction.
|
||||
///
|
||||
/// Eventual concurrent reads may see partial updates unless you wrap them
|
||||
/// in a transaction.
|
||||
func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
|
||||
|
||||
/// 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 updates
|
||||
/// are completed.
|
||||
///
|
||||
/// Eventual concurrent reads may see partial updates unless you wrap them
|
||||
/// in a transaction.
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T
|
||||
|
||||
func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// Synchronously or asynchronously executes a read-only block that takes a
|
||||
/// database connection.
|
||||
/// Concurrently executes a read-only block in a protected dispatch queue.
|
||||
///
|
||||
/// This method must be called from a writing dispatch queue.
|
||||
/// This method must be called from a writing dispatch queue, outside of any
|
||||
/// transaction. You'll get a fatal error otherwise.
|
||||
///
|
||||
/// The *block* argument is guaranteed to see the database in the state it
|
||||
/// has at the moment this method is called (see below). Eventual concurrent
|
||||
/// The *block* argument is guaranteed to see the database in the last
|
||||
/// committed state at the moment this method is called. Eventual concurrent
|
||||
/// database updates are *not visible* inside the block.
|
||||
///
|
||||
/// What is the "current state" of the database?
|
||||
/// To access the fetched results, you call the wait() method of the
|
||||
/// returned future, on any dispatch queue.
|
||||
///
|
||||
/// - When this method is called outside of any transaction, the current
|
||||
/// state is the last committed state.
|
||||
/// 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.write { db in
|
||||
/// try db.execute("DELETE FROM persons")
|
||||
/// try writer.readFromCurrentState { db in
|
||||
/// try writer.writeWithoutTransaction { db in
|
||||
/// // Delete all players
|
||||
/// try Player.deleteAll()
|
||||
///
|
||||
/// // Count players concurrently
|
||||
/// let future = writer.concurrentRead { db in
|
||||
/// return try Player.fetchCount()
|
||||
/// }
|
||||
///
|
||||
/// // Insert a player
|
||||
/// try Player(...).insert(db)
|
||||
///
|
||||
/// // Guaranteed to be zero
|
||||
/// let count = try future.wait()
|
||||
/// }
|
||||
func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> DatabaseFuture<T>
|
||||
|
||||
#if compiler(>=5.0)
|
||||
// Exposed for RxGRDB and GRBCombine. Naming is not stabilized.
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Concurrently 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.
|
||||
///
|
||||
/// 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
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
|
||||
/// }
|
||||
/// try db.execute("INSERT INTO persons ...")
|
||||
/// }
|
||||
///
|
||||
/// - When this method is called inside an uncommitted transation, the
|
||||
/// current state depends on the caller:
|
||||
///
|
||||
/// DatabasePool.readFromCurrentState runs *block* asynchronously in a
|
||||
/// concurrent reader dispatch queue, and release the writing dispatch
|
||||
/// queue early, before the block has finished. In the example below,
|
||||
/// the insertion runs concurrently with the select, and the select sees
|
||||
/// the database in its last committed state.
|
||||
///
|
||||
/// try dbPool.write { db in
|
||||
/// try db.execute("DELETE FROM persons")
|
||||
/// db.inTransaction {
|
||||
/// try db.execute("INSERT INTO persons ...")
|
||||
/// try dbPool.readFromCurrentState { db in
|
||||
/// // Zero
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
|
||||
/// }
|
||||
/// return .commit
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // Handle error
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// DatabaseQueue.readFromCurrentState simply runs *block* synchronously,
|
||||
/// and returns when the block has completed. In the example below, the
|
||||
/// select sees the uncommitted state of the database, and the insertion
|
||||
/// is run after the select.
|
||||
/// // Insert a player
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// try db.execute("DELETE FROM persons")
|
||||
/// db.inTransaction {
|
||||
/// try db.execute("INSERT INTO persons ...")
|
||||
/// try dbQueue.readFromCurrentState { db in
|
||||
/// // One
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
|
||||
/// }
|
||||
/// return .commit
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
func readFromCurrentState(_ block: @escaping (Database) -> Void) throws
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// :nodoc:
|
||||
func spawnConcurrentRead(_ block: @escaping (Result<Database, Error>) -> Void)
|
||||
#endif
|
||||
}
|
||||
|
||||
extension DatabaseWriter {
|
||||
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// wrapped inside a transaction, and returns the result.
|
||||
///
|
||||
/// If the updates throw an error, the transaction is rollbacked and the
|
||||
/// error is rethrown.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the transaction
|
||||
/// has completed.
|
||||
///
|
||||
/// Eventual concurrent reads are guaranteed to not see any partial updates
|
||||
/// of the database until the transaction has completed.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates, or by the
|
||||
/// wrapping transaction.
|
||||
public func write<T>(_ updates: (Database) throws -> T) throws -> T {
|
||||
return try writeWithoutTransaction { db in
|
||||
var result: T?
|
||||
try db.inTransaction {
|
||||
result = try updates(db)
|
||||
return .commit
|
||||
}
|
||||
return result!
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
/// wrapped inside a transaction.
|
||||
///
|
||||
/// If the updates throw an error, the transaction is rollbacked.
|
||||
///
|
||||
/// The *completion* closure is always called with the result of the
|
||||
/// database updates. Its arguments are a database connection and the
|
||||
/// result of the transaction. This result is a failure if the transaction
|
||||
/// could not be committed. The completion closure is executed in a
|
||||
/// protected dispatch queue, outside of any transaction.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the transaction
|
||||
/// and the *completion* closure have completed.
|
||||
///
|
||||
/// Eventual concurrent reads are guaranteed to not see any partial updates
|
||||
/// of the database until the transaction has completed.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - parameter completion: A closure that is called with the eventual
|
||||
/// transaction error.
|
||||
/// - throws: The error thrown by the updates, or by the wrapping transaction.
|
||||
public func asyncWrite<T>(
|
||||
_ updates: @escaping (Database) throws -> T,
|
||||
completion: @escaping (Database, Result<T, Error>) -> Void)
|
||||
{
|
||||
asyncWriteWithoutTransaction { db in
|
||||
do {
|
||||
var result: T?
|
||||
try db.inTransaction {
|
||||
result = try updates(db)
|
||||
return .commit
|
||||
}
|
||||
completion(db, .success(result!))
|
||||
} catch {
|
||||
completion(db, .failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Transaction Observers
|
||||
|
||||
/// Add a transaction observer, so that it gets notified of
|
||||
/// database changes.
|
||||
///
|
||||
/// To remove the observer, use `DatabaseReader.remove(transactionObserver:)`.
|
||||
///
|
||||
/// - parameter transactionObserver: A transaction observer.
|
||||
/// - parameter extent: The duration of the observation. The default is
|
||||
/// the observer lifetime (observation lasts until observer
|
||||
/// is deallocated).
|
||||
public func add(transactionObserver: TransactionObserver, extent: Database.TransactionObservationExtent = .observerLifetime) {
|
||||
write { $0.add(transactionObserver: transactionObserver, extent: extent) }
|
||||
public func add(
|
||||
transactionObserver: TransactionObserver,
|
||||
extent: Database.TransactionObservationExtent = .observerLifetime)
|
||||
{
|
||||
writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) }
|
||||
}
|
||||
|
||||
/// Remove a transaction observer.
|
||||
/// Default implementation for the DatabaseReader requirement.
|
||||
/// :nodoc:
|
||||
public func remove(transactionObserver: TransactionObserver) {
|
||||
write { $0.remove(transactionObserver: transactionObserver) }
|
||||
writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) }
|
||||
}
|
||||
|
||||
// MARK: - Erasing the content of the database
|
||||
|
||||
/// Erases the content of the database.
|
||||
///
|
||||
/// - precondition: database is not accessed concurrently during the
|
||||
/// execution of this method.
|
||||
public func erase() throws {
|
||||
#if SQLITE_HAS_CODEC
|
||||
// SQLCipher does not support the backup API:
|
||||
// https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631
|
||||
// So we'll drop all database objects one after the other.
|
||||
try writeWithoutTransaction { db in
|
||||
// Prevent foreign keys from messing with drop table statements
|
||||
let foreignKeysEnabled = try Bool.fetchOne(db, sql: "PRAGMA foreign_keys")!
|
||||
if foreignKeysEnabled {
|
||||
try db.execute(sql: "PRAGMA foreign_keys = OFF")
|
||||
}
|
||||
|
||||
// Remove all database objects, one after the other
|
||||
do {
|
||||
try db.inTransaction {
|
||||
let sql = "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'"
|
||||
while let row = try Row.fetchOne(db, sql: sql) {
|
||||
let type: String = row["type"]
|
||||
let name: String = row["name"]
|
||||
try db.execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)")
|
||||
}
|
||||
return .commit
|
||||
}
|
||||
|
||||
// Restore foreign keys if needed
|
||||
if foreignKeysEnabled {
|
||||
try db.execute(sql: "PRAGMA foreign_keys = ON")
|
||||
}
|
||||
} catch {
|
||||
// Restore foreign keys if needed
|
||||
if foreignKeysEnabled {
|
||||
try? db.execute(sql: "PRAGMA foreign_keys = ON")
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
#else
|
||||
try DatabaseQueue().backup(to: self)
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - Claiming Disk Space
|
||||
|
||||
/// Rebuilds the database file, repacking it into a minimal amount of
|
||||
/// disk space.
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_vacuum.html for more information.
|
||||
public func vacuum() throws {
|
||||
try writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
|
||||
}
|
||||
|
||||
// MARK: - Value Observation
|
||||
|
||||
/// Default implementation for the DatabaseReader requirement.
|
||||
/// :nodoc:
|
||||
public func add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> TransactionObserver
|
||||
{
|
||||
let requiresWriteAccess = observation.requiresWriteAccess
|
||||
let observer = ValueObserver<Reducer>(
|
||||
requiresWriteAccess: requiresWriteAccess,
|
||||
observesSelectedRegion: observation.observesSelectedRegion,
|
||||
writer: self,
|
||||
reduceQueue: configuration.makeDispatchQueue(defaultLabel: "GRDB", purpose: "ValueObservation.reducer"),
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
|
||||
switch observation.scheduling {
|
||||
case .mainQueue:
|
||||
if DispatchQueue.isMain {
|
||||
// Use case: observation starts on the main queue and wants
|
||||
// a synchronous initial fetch. Typically, this helps avoiding
|
||||
// flashes of missing content.
|
||||
var startValue: Reducer.Value? = nil
|
||||
defer {
|
||||
if let startValue = startValue {
|
||||
onChange(startValue)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
try unsafeReentrantWrite { db in
|
||||
observer.notificationQueue = DispatchQueue.main
|
||||
observer.baseRegion = try observation.baseRegion(db).ignoringViews(db)
|
||||
observer.reducer = try observation.makeReducer(db)
|
||||
|
||||
// Initial value & selected region
|
||||
let fetchedValue: Reducer.Fetched
|
||||
if observation.observesSelectedRegion {
|
||||
(fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion {
|
||||
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
} else {
|
||||
fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
if let value = observer.reducer.value(fetchedValue) {
|
||||
startValue = value
|
||||
}
|
||||
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
}
|
||||
} catch {
|
||||
onError(error)
|
||||
}
|
||||
} else {
|
||||
// Use case: observation does not start on the main queue, but
|
||||
// has the default scheduling .mainQueue
|
||||
asyncWriteWithoutTransaction { db in
|
||||
do {
|
||||
observer.notificationQueue = DispatchQueue.main
|
||||
observer.baseRegion = try observation.baseRegion(db).ignoringViews(db)
|
||||
observer.reducer = try observation.makeReducer(db)
|
||||
|
||||
// Initial value & selected region
|
||||
let fetchedValue: Reducer.Fetched
|
||||
if observation.observesSelectedRegion {
|
||||
(fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion {
|
||||
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
} else {
|
||||
fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
if let value = observer.reducer.value(fetchedValue) {
|
||||
DispatchQueue.main.async {
|
||||
onChange(value)
|
||||
}
|
||||
}
|
||||
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
} catch {
|
||||
DispatchQueue.main.async {
|
||||
onError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
case let .async(onQueue: queue, startImmediately: startImmediately):
|
||||
// Use case: observation must not block the target queue
|
||||
asyncWriteWithoutTransaction { db in
|
||||
do {
|
||||
observer.notificationQueue = queue
|
||||
observer.baseRegion = try observation.baseRegion(db).ignoringViews(db)
|
||||
observer.reducer = try observation.makeReducer(db)
|
||||
|
||||
// Initial value & selected region
|
||||
if startImmediately {
|
||||
let fetchedValue: Reducer.Fetched
|
||||
if observation.observesSelectedRegion {
|
||||
(fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion {
|
||||
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
} else {
|
||||
fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
if let value = observer.reducer.value(fetchedValue) {
|
||||
queue.async {
|
||||
onChange(value)
|
||||
}
|
||||
}
|
||||
} else if observation.observesSelectedRegion {
|
||||
(_, observer.selectedRegion) = try db.recordingSelectedRegion {
|
||||
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
}
|
||||
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
} catch {
|
||||
queue.async {
|
||||
onError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
case let .unsafe(startImmediately: startImmediately):
|
||||
if startImmediately {
|
||||
// Use case: third-party integration (RxSwift, Combine, ...) that
|
||||
// need a synchronous initial fetch.
|
||||
//
|
||||
// This is really super extra unsafe.
|
||||
//
|
||||
// If the observation is started on one dispatch queue, then
|
||||
// the onChange and onError callbacks must be asynchronously
|
||||
// dispatched on the *same* queue.
|
||||
//
|
||||
// A failure to follow this rule may mess with the ordering of
|
||||
// initial values.
|
||||
var startValue: Reducer.Value? = nil
|
||||
defer {
|
||||
if let startValue = startValue {
|
||||
onChange(startValue)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
try unsafeReentrantWrite { db in
|
||||
observer.notificationQueue = nil
|
||||
observer.baseRegion = try observation.baseRegion(db).ignoringViews(db)
|
||||
observer.reducer = try observation.makeReducer(db)
|
||||
|
||||
// Initial value & selected region
|
||||
if startImmediately {
|
||||
let fetchedValue: Reducer.Fetched
|
||||
if observation.observesSelectedRegion {
|
||||
(fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion {
|
||||
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
} else {
|
||||
fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
if let value = observer.reducer.value(fetchedValue) {
|
||||
startValue = value
|
||||
}
|
||||
} else if observation.observesSelectedRegion {
|
||||
(_, observer.selectedRegion) = try db.recordingSelectedRegion {
|
||||
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
}
|
||||
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
}
|
||||
} catch {
|
||||
onError(error)
|
||||
}
|
||||
} else {
|
||||
// Use case: ?
|
||||
//
|
||||
// This is unsafe because no promise is made on the dispatch
|
||||
// queue on which the onChange and onError callbacks are called.
|
||||
asyncWriteWithoutTransaction { db in
|
||||
do {
|
||||
observer.notificationQueue = nil
|
||||
observer.baseRegion = try observation.baseRegion(db).ignoringViews(db)
|
||||
observer.reducer = try observation.makeReducer(db)
|
||||
|
||||
// Selected region
|
||||
if observation.observesSelectedRegion {
|
||||
(_, observer.selectedRegion) = try db.recordingSelectedRegion {
|
||||
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
}
|
||||
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
} catch {
|
||||
onError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO
|
||||
//
|
||||
// We promise that observation stops when the returned observer is
|
||||
// deallocated. But the real observer may have not started observing
|
||||
// the database, because some observations start asynchronously.
|
||||
// Well... This forces us to return a "token" that cancels any
|
||||
// observation started asynchronously.
|
||||
//
|
||||
// We'll eventually return a proper Cancellable. In GRDB 5?
|
||||
return ValueObserverToken(writer: self, observer: observer)
|
||||
}
|
||||
}
|
||||
|
||||
/// A future database value, returned by the DatabaseWriter.concurrentRead(_:)
|
||||
/// method.
|
||||
///
|
||||
/// let futureCount: Future<Int> = try writer.writeWithoutTransaction { db in
|
||||
/// try Player(...).insert()
|
||||
///
|
||||
/// // Count players concurrently
|
||||
/// return writer.concurrentRead { db in
|
||||
/// return try Player.fetchCount()
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let count: Int = try futureCount.wait()
|
||||
public class DatabaseFuture<Value> {
|
||||
private var consumed = false
|
||||
private let _wait: () throws -> Value
|
||||
|
||||
init(_ wait: @escaping () throws -> Value) {
|
||||
_wait = wait
|
||||
}
|
||||
|
||||
init(_ result: DatabaseResult<Value>) {
|
||||
_wait = result.get
|
||||
}
|
||||
|
||||
/// Blocks the current thread until the value is available, and returns it.
|
||||
///
|
||||
/// It is a programmer error to call this method several times.
|
||||
///
|
||||
/// - throws: Any error that prevented the value from becoming available.
|
||||
public func wait() throws -> Value {
|
||||
// Not thread-safe and quick and dirty.
|
||||
// Goal is that users learn not to call this method twice.
|
||||
GRDBPrecondition(consumed == false, "DatabaseFuture.wait() must be called only once")
|
||||
consumed = true
|
||||
return try _wait()
|
||||
}
|
||||
}
|
||||
|
||||
/// A type-erased DatabaseWriter
|
||||
///
|
||||
/// Instances of AnyDatabaseWriter forward their methods to an arbitrary
|
||||
/// underlying database writer.
|
||||
public final class AnyDatabaseWriter: DatabaseWriter {
|
||||
private let base: DatabaseWriter
|
||||
|
||||
/// Creates a database writer that wraps a base database writer.
|
||||
public init(_ base: DatabaseWriter) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public var configuration: Configuration {
|
||||
return base.configuration
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// :nodoc:
|
||||
public func read<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
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)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeReentrantRead(block)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
return base.concurrentRead(block)
|
||||
}
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// :nodoc:
|
||||
public func spawnConcurrentRead(_ block: @escaping (Result<Database, Error>) -> Void) {
|
||||
base.spawnConcurrentRead(block)
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Writing in Database
|
||||
|
||||
/// :nodoc:
|
||||
public func write<T>(_ updates: (Database) throws -> T) throws -> T {
|
||||
return try base.write(updates)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
return try base.writeWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// :nodoc:
|
||||
public func asyncWrite<T>(
|
||||
_ updates: @escaping (Database) throws -> T,
|
||||
completion: @escaping (Database, Result<T, Error>) -> Void)
|
||||
{
|
||||
base.asyncWrite(updates, completion: completion)
|
||||
}
|
||||
#endif
|
||||
|
||||
/// :nodoc:
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
base.asyncWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
return try base.unsafeReentrantWrite(updates)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// :nodoc:
|
||||
public func add(function: DatabaseFunction) {
|
||||
base.add(function: function)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func remove(function: DatabaseFunction) {
|
||||
base.remove(function: function)
|
||||
}
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// :nodoc:
|
||||
public func add(collation: DatabaseCollation) {
|
||||
base.add(collation: collation)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
base.remove(collation: collation)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
// MARK: - PreparedRequest
|
||||
|
||||
/// A PreparedRequest is a request that is ready to be executed.
|
||||
public struct PreparedRequest {
|
||||
/// A prepared statement
|
||||
public var statement: SelectStatement
|
||||
|
||||
/// An eventual adapter for rows fetched by the select statement
|
||||
public var adapter: RowAdapter?
|
||||
|
||||
/// Support for eager loading of hasMany associations.
|
||||
var supplementaryFetch: (([Row]) throws -> Void)?
|
||||
|
||||
/// Creates a PreparedRequest.
|
||||
///
|
||||
/// - parameter statement: A prepared statement that is ready to
|
||||
/// be executed.
|
||||
/// - parameter adapter: An eventual adapter for rows fetched by the
|
||||
/// select statement.
|
||||
public init(
|
||||
statement: SelectStatement,
|
||||
adapter: RowAdapter? = nil)
|
||||
{
|
||||
self.init(statement: statement, adapter: adapter, supplementaryFetch: nil)
|
||||
}
|
||||
|
||||
init(
|
||||
statement: SelectStatement,
|
||||
adapter: RowAdapter?,
|
||||
supplementaryFetch: (([Row]) throws -> Void)?)
|
||||
{
|
||||
self.statement = statement
|
||||
self.adapter = adapter
|
||||
self.supplementaryFetch = supplementaryFetch
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - FetchRequest
|
||||
|
||||
/// The protocol for all requests that fetch database rows, and tell how those
|
||||
/// rows should be interpreted.
|
||||
///
|
||||
/// struct Player: FetchableRecord { ... }
|
||||
/// let request: ... // Some FetchRequest that fetches Player
|
||||
/// try request.fetchCursor(db) // Cursor of Player
|
||||
/// try request.fetchAll(db) // [Player]
|
||||
/// try request.fetchOne(db) // Player?
|
||||
public protocol FetchRequest: DatabaseRegionConvertible {
|
||||
/// The type that tells how fetched database rows should be interpreted.
|
||||
associatedtype RowDecoder
|
||||
|
||||
// TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method
|
||||
/// This method is deprecated. Use
|
||||
/// `makePreparedRequest(_:forSingleResult:)` instead.
|
||||
///
|
||||
/// Returns a tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter singleResult: A hint that a single result row will be
|
||||
/// consumed. Implementations can optionally use this to optimize the
|
||||
/// prepared statement.
|
||||
/// - returns: A prepared statement and an eventual row adapter.
|
||||
func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
|
||||
|
||||
/// Returns a PreparedRequest that is ready to be executed.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter singleResult: A hint that a single result row will be
|
||||
/// consumed. Implementations can optionally use this to optimize the
|
||||
/// prepared statement.
|
||||
/// - returns: A prepared request.
|
||||
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
|
||||
|
||||
/// Returns the number of rows fetched by the request.
|
||||
///
|
||||
/// The default implementation builds a naive SQL query based on the
|
||||
/// statement returned by the `prepare` method:
|
||||
/// `SELECT COUNT(*) FROM (...)`.
|
||||
///
|
||||
/// Adopting types can refine this method in order to use more
|
||||
/// efficient SQL.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
func fetchCount(_ db: Database) throws -> Int
|
||||
}
|
||||
|
||||
extension FetchRequest {
|
||||
|
||||
/// Returns an adapted request.
|
||||
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest<Self> {
|
||||
return AdaptedFetchRequest(self, adapter)
|
||||
}
|
||||
|
||||
/// Returns the number of rows fetched by the request.
|
||||
///
|
||||
/// This default implementation builds a naive SQL query based on the
|
||||
/// statement returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
let request = try makePreparedRequest(db, forSingleResult: false)
|
||||
let sql = "SELECT COUNT(*) FROM (\(request.statement.sql))"
|
||||
return try Int.fetchOne(db, sql: sql, arguments: request.statement.arguments)!
|
||||
}
|
||||
|
||||
/// Returns the database region that the request looks into.
|
||||
///
|
||||
/// This default implementation returns a region built from the statement
|
||||
/// returned by the `prepare` method.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
let request = try makePreparedRequest(db, forSingleResult: false)
|
||||
return request.statement.databaseRegion
|
||||
}
|
||||
|
||||
// Support for legacy requests which only define prepare(_:forSingleResult:)
|
||||
// TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method
|
||||
/// :nodoc:
|
||||
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
|
||||
let (statement, adapter) = try prepare(db, forSingleResult: singleResult)
|
||||
return PreparedRequest(statement: statement, adapter: adapter)
|
||||
}
|
||||
|
||||
// TODO: remove when we remove the deprecated prepare(_:forSingleResult:) method
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) {
|
||||
let request = try makePreparedRequest(db, forSingleResult: singleResult)
|
||||
return (request.statement, request.adapter)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - AdaptedFetchRequest
|
||||
|
||||
/// An adapted request.
|
||||
public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
|
||||
public typealias RowDecoder = Base.RowDecoder
|
||||
|
||||
private let base: Base
|
||||
private let adapter: (Database) throws -> RowAdapter
|
||||
|
||||
/// Creates an adapted request from a base request and a closure that builds
|
||||
/// a row adapter from a database connection.
|
||||
init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) {
|
||||
self.base = base
|
||||
self.adapter = adapter
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
|
||||
var request = try base.makePreparedRequest(db, forSingleResult: singleResult)
|
||||
if let baseAdapter = request.adapter {
|
||||
request.adapter = try ChainedAdapter(first: baseAdapter, second: adapter(db))
|
||||
} else {
|
||||
request.adapter = try adapter(db)
|
||||
}
|
||||
return request
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try base.fetchCount(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try base.databaseRegion(db)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - AnyFetchRequest
|
||||
|
||||
/// A type-erased FetchRequest.
|
||||
///
|
||||
/// An AnyFetchRequest forwards its operations to an underlying request,
|
||||
/// hiding its specifics.
|
||||
public struct AnyFetchRequest<T>: FetchRequest {
|
||||
public typealias RowDecoder = T
|
||||
|
||||
private let _preparedRequest: (Database, _ singleResult: Bool) throws -> PreparedRequest
|
||||
private let _fetchCount: (Database) throws -> Int
|
||||
private let _databaseRegion: (Database) throws -> DatabaseRegion
|
||||
|
||||
/// Creates a request that wraps and forwards operations to `request`.
|
||||
public init<Request: FetchRequest>(_ request: Request) {
|
||||
_preparedRequest = request.makePreparedRequest
|
||||
_fetchCount = request.fetchCount
|
||||
_databaseRegion = request.databaseRegion
|
||||
}
|
||||
|
||||
/// Creates a request whose `prepare()` method wraps and forwards
|
||||
/// operations the argument closure.
|
||||
@available(*, deprecated, message: "Define your own FetchRequest type instead.")
|
||||
public init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?)) {
|
||||
_preparedRequest = { db, singleResult in
|
||||
let (statement, adapter) = try prepare(db, singleResult)
|
||||
return PreparedRequest(statement: statement, adapter: adapter)
|
||||
}
|
||||
|
||||
_fetchCount = { db in
|
||||
let (statement, _) = try prepare(db, false)
|
||||
let sql = "SELECT COUNT(*) FROM (\(statement.sql))"
|
||||
return try Int.fetchOne(db, sql: sql, arguments: statement.arguments)!
|
||||
}
|
||||
|
||||
_databaseRegion = { db in
|
||||
let (statement, _) = try prepare(db, false)
|
||||
return statement.databaseRegion
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
|
||||
return try _preparedRequest(db, singleResult)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try _fetchCount(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try _databaseRegion(db)
|
||||
}
|
||||
}
|
||||
@@ -1,519 +0,0 @@
|
||||
/// The protocol for all types that define a way to fetch database rows.
|
||||
///
|
||||
/// Requests can feed the fetching methods of any fetchable type (Row,
|
||||
/// value, record):
|
||||
///
|
||||
/// let request: Request = ...
|
||||
/// try Row.fetchCursor(db, request) // DatabaseCursor<Row>
|
||||
/// try String.fetchAll(db, request) // [String]
|
||||
/// try Person.fetchOne(db, request) // Person?
|
||||
public protocol Request {
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
|
||||
|
||||
/// The number of rows fetched by the request.
|
||||
///
|
||||
/// Default implementation builds a naive SQL query based on the statement
|
||||
/// returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`.
|
||||
///
|
||||
/// Adopting types can refine this countRequest method and return more
|
||||
/// efficient SQL.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
func fetchCount(_ db: Database) throws -> Int
|
||||
}
|
||||
|
||||
extension Request {
|
||||
/// The number of rows fetched by the request.
|
||||
///
|
||||
/// This default implementation builds a naive SQL query based on the
|
||||
/// statement returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
let (statement, _) = try prepare(db)
|
||||
let sql = "SELECT COUNT(*) FROM (\(statement.sql))"
|
||||
return try Int.fetchOne(db, sql, arguments: statement.arguments)!
|
||||
}
|
||||
}
|
||||
|
||||
extension Request {
|
||||
/// Returns a request bound to type T.
|
||||
///
|
||||
/// The returned request can fetch if the type T is fetchable (Row,
|
||||
/// value, record).
|
||||
///
|
||||
/// // minHeight in Double?
|
||||
/// let minHeight = Person
|
||||
/// .select(min(heightColumn))
|
||||
/// .asRequest(of: Double.self) // <--
|
||||
/// .fetchOne(db)
|
||||
///
|
||||
/// - parameter type: The fetched type T
|
||||
/// - returns: A typed request bound to type T.
|
||||
public func asRequest<T>(of type: T.Type) -> AnyTypedRequest<T> {
|
||||
return AnyTypedRequest { try self.prepare($0) }
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns an adapted request.
|
||||
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedRequest<Self> {
|
||||
return AdaptedRequest(self, adapter)
|
||||
}
|
||||
}
|
||||
|
||||
/// An adapted request.
|
||||
public struct AdaptedRequest<Base: Request> : Request {
|
||||
/// Creates an adapted request from a base request and a closure that builds
|
||||
/// a row adapter from a database connection.
|
||||
init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) {
|
||||
self.base = base
|
||||
self.adapter = adapter
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
let (statement, baseAdapter) = try base.prepare(db)
|
||||
if let baseAdapter = baseAdapter {
|
||||
return try (statement, ChainedAdapter(first: baseAdapter, second: adapter(db)))
|
||||
} else {
|
||||
return try (statement, adapter(db))
|
||||
}
|
||||
}
|
||||
|
||||
/// The number of rows fetched by the request.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try base.fetchCount(db)
|
||||
}
|
||||
|
||||
private let base: Base
|
||||
private let adapter: (Database) throws -> RowAdapter
|
||||
}
|
||||
|
||||
/// A type-erased Request.
|
||||
///
|
||||
/// An instance of AnyRequest forwards its operations to an underlying request,
|
||||
/// hiding its specifics.
|
||||
public struct AnyRequest : Request {
|
||||
/// Creates a new request that wraps and forwards operations to `request`.
|
||||
public init(_ request: Request) {
|
||||
self._prepare = { try request.prepare($0) }
|
||||
}
|
||||
|
||||
/// Creates a new request whose `prepare()` method wraps and forwards
|
||||
/// operations the argument closure.
|
||||
public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) {
|
||||
_prepare = prepare
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try _prepare(db)
|
||||
}
|
||||
|
||||
private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?)
|
||||
}
|
||||
|
||||
/// A Request built from raw SQL.
|
||||
public struct SQLRequest : Request {
|
||||
/// Creates a new request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
///
|
||||
/// let request = SQLRequest("SELECT * FROM persons")
|
||||
/// let request = SQLRequest("SELECT * FROM persons WHERE id = ?", arguments: [1])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: A SQLRequest
|
||||
public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) {
|
||||
self.init(sql, arguments: arguments, adapter: adapter, fromCache: cached ? .user : nil)
|
||||
}
|
||||
|
||||
/// Creates a new request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
///
|
||||
/// let request = SQLRequest("SELECT * FROM persons")
|
||||
/// let request = SQLRequest("SELECT * FROM persons WHERE id = ?", arguments: [1])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - statementCacheName: Optional statement cache name.
|
||||
/// - returns: A SQLRequest
|
||||
init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache statementCacheName: Database.StatementCacheName?) {
|
||||
self.sql = sql
|
||||
self.arguments = arguments
|
||||
self.adapter = adapter
|
||||
self.statementCacheName = statementCacheName
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
let statement: SelectStatement
|
||||
if let statementCacheName = statementCacheName {
|
||||
statement = try db.selectStatement(sql, fromCache: statementCacheName)
|
||||
} else {
|
||||
statement = try db.makeSelectStatement(sql)
|
||||
}
|
||||
if let arguments = arguments {
|
||||
try statement.setArgumentsWithValidation(arguments)
|
||||
}
|
||||
return (statement, adapter)
|
||||
}
|
||||
|
||||
private let sql: String
|
||||
private let arguments: StatementArguments?
|
||||
private let adapter: RowAdapter?
|
||||
private let statementCacheName: Database.StatementCacheName?
|
||||
}
|
||||
|
||||
/// The protocol for requests that know how to decode database rows.
|
||||
///
|
||||
/// Typed requests can fetch if their associated type RowDecoder is able to
|
||||
/// decode rows (Row, value, record)
|
||||
///
|
||||
/// struct Person: RowConvertible { ... }
|
||||
/// let request: ... // Some TypedRequest that fetches Person
|
||||
/// try request.fetchCursor(db) // DatabaseCursor<Person>
|
||||
/// try request.fetchAll(db) // [Person]
|
||||
/// try request.fetchOne(db) // Person?
|
||||
public protocol TypedRequest : Request {
|
||||
|
||||
/// The type that can convert raw database rows to fetched values
|
||||
associatedtype RowDecoder
|
||||
}
|
||||
|
||||
extension TypedRequest {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns an adapted typed request.
|
||||
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedTypedRequest<Self> {
|
||||
return AdaptedTypedRequest(self, adapter)
|
||||
}
|
||||
}
|
||||
|
||||
/// An adapted typed request.
|
||||
public struct AdaptedTypedRequest<Base: TypedRequest> : TypedRequest {
|
||||
|
||||
/// The type that can convert raw database rows to fetched values
|
||||
public typealias RowDecoder = Base.RowDecoder
|
||||
|
||||
/// Creates an adapted request from a base request and a closure that builds
|
||||
/// a row adapter from a database connection.
|
||||
init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) {
|
||||
adaptedRequest = AdaptedRequest(base, adapter)
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try adaptedRequest.prepare(db)
|
||||
}
|
||||
|
||||
/// The number of rows fetched by the request.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try adaptedRequest.fetchCount(db)
|
||||
}
|
||||
|
||||
private let adaptedRequest: AdaptedRequest<Base>
|
||||
}
|
||||
|
||||
/// A type-erased TypedRequest.
|
||||
///
|
||||
/// An instance of AnyTypedRequest forwards its operations to an underlying
|
||||
/// typed request, hiding its specifics.
|
||||
public struct AnyTypedRequest<T> : TypedRequest {
|
||||
/// The type that can convert raw database rows to fetched values
|
||||
public typealias RowDecoder = T
|
||||
|
||||
/// Creates a new request that wraps and forwards operations to `request`.
|
||||
public init<Request>(_ request: Request) where Request: TypedRequest, Request.RowDecoder == RowDecoder {
|
||||
self._prepare = { try request.prepare($0) }
|
||||
}
|
||||
|
||||
/// Creates a new request whose `prepare()` method wraps and forwards
|
||||
/// operations the argument closure.
|
||||
public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) {
|
||||
_prepare = prepare
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try _prepare(db)
|
||||
}
|
||||
|
||||
private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?)
|
||||
}
|
||||
|
||||
extension TypedRequest where RowDecoder: RowConvertible {
|
||||
|
||||
// MARK: Fetching Record and RowConvertible
|
||||
|
||||
/// A cursor over fetched records.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Person
|
||||
/// let persons = try request.fetchCursor(db) // DatabaseCursor<Person>
|
||||
/// while let person = try persons.next() { // Person
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched records.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Person
|
||||
/// let persons = try request.fetchAll(db) // [Person]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
return try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched record.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Person
|
||||
/// let person = try request.fetchOne(db) // Person?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional record.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
return try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
extension TypedRequest where RowDecoder: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching Values
|
||||
|
||||
/// A cursor over fetched values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let strings = try request.fetchCursor(db) // DatabaseCursor<String>
|
||||
/// while let string = try strings.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let strings = try request.fetchAll(db) // [String]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
return try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched value.
|
||||
///
|
||||
/// The result is nil if the request returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let string = try request.fetchOne(db) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
return try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
extension TypedRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching Values
|
||||
|
||||
/// A cursor over fetched values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let strings = try request.fetchCursor(db) // DatabaseCursor<String>
|
||||
/// while let string = try strings.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let strings = try request.fetchAll(db) // [String]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
return try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched value.
|
||||
///
|
||||
/// The result is nil if the request returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let string = try request.fetchOne(db) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
return try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching Optional values
|
||||
|
||||
/// A cursor over fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchCursor(db) // DatabaseCursor<String?>
|
||||
/// while let string = try strings.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder._Wrapped?> {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchAll(db) // [String?]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchAll(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
extension TypedRequest where RowDecoder: Row {
|
||||
|
||||
// MARK: Fetching Rows
|
||||
|
||||
/// A cursor over fetched rows.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Row
|
||||
/// let rows = try request.fetchCursor(db) // DatabaseCursor<Row>
|
||||
/// while let row = try rows.next() { // Row
|
||||
/// let id: Int64 = row.value(atIndex: 0)
|
||||
/// let name: String = row.value(atIndex: 1)
|
||||
/// }
|
||||
///
|
||||
/// Fetched rows are reused during the cursor iteration: don't turn a row
|
||||
/// cursor into an array with `Array(rows)` or `rows.filter { ... }` since
|
||||
/// you would not get the distinct rows you expect. Use `Row.fetchAll(...)`
|
||||
/// instead.
|
||||
///
|
||||
/// For the same reason, make sure you make a copy whenever you extract a
|
||||
/// row for later use: `row.copy()`.
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<Row> {
|
||||
return try Row.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched rows.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Row
|
||||
/// let rows = try request.fetchAll(db)
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of fetched rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [Row] {
|
||||
return try Row.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched row.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Row
|
||||
/// let row = try request.fetchOne(db)
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A,n optional rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> Row? {
|
||||
return try Row.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,50 @@
|
||||
import Foundation
|
||||
|
||||
/// Returns an array of row adapters that split a row according to the input
|
||||
/// number of columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let sql = "SELECT 1, 2,3,4, 5,6, 7,8"
|
||||
/// // <.><. . .><. .><. .>
|
||||
/// let adapters = splittingRowAdapters([1, 3, 2])
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "a": adapters[0],
|
||||
/// "b": adapters[1],
|
||||
/// "c": adapters[2],
|
||||
/// "d": adapters[3]])
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// row.scopes["a"] // [1]
|
||||
/// row.scopes["b"] // [2, 3, 4]
|
||||
/// row.scopes["c"] // [5, 6]
|
||||
/// row.scopes["d"] // [7, 8]
|
||||
public func splittingRowAdapters(columnCounts: [Int]) -> [RowAdapter] {
|
||||
guard !columnCounts.isEmpty else {
|
||||
// Identity adapter
|
||||
return [SuffixRowAdapter(fromIndex: 0)]
|
||||
}
|
||||
|
||||
// [1, 3, 2] -> [0, 1, 4, 6]
|
||||
let columnIndexes = columnCounts.reduce(into: [0]) { (acc, count) in
|
||||
acc.append(acc.last! + count)
|
||||
}
|
||||
|
||||
// [0, 1, 4, 6] -> [(0..<1), (1..<4), (4..<6)]
|
||||
let rangeAdapters = zip(columnIndexes, columnIndexes.suffix(from: 1))
|
||||
.map { RangeRowAdapter($0..<$1) }
|
||||
|
||||
// (6...)
|
||||
let suffixAdapter = SuffixRowAdapter(fromIndex: columnIndexes.last!)
|
||||
|
||||
// [(0..<1), (1..<4), (4..<6), (6...)]
|
||||
return rangeAdapters + [suffixAdapter]
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// LayoutedColumnMapping is a type that supports the RowAdapter protocol.
|
||||
///
|
||||
/// :nodoc:
|
||||
public struct LayoutedColumnMapping {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -35,14 +77,15 @@ public struct LayoutedColumnMapping {
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // <Row foo:"foo" bar: "bar">
|
||||
/// try Row.fetchOne(db, "SELECT NULL, 'foo', 'bar'", adapter: FooBarAdapter())
|
||||
/// // [foo:"foo" bar: "bar"]
|
||||
/// try Row.fetchOne(db, sql: "SELECT NULL, 'foo', 'bar'", adapter: FooBarAdapter())
|
||||
public init<S: Sequence>(layoutColumns: S) where S.Iterator.Element == (Int, String) {
|
||||
self.layoutColumns = Array(layoutColumns)
|
||||
self.lowercaseColumnIndexes = Dictionary(keyValueSequence: layoutColumns
|
||||
.enumerated()
|
||||
.map { ($1.1.lowercased(), $0) }
|
||||
.reversed()) // reversed() so that the the dictionary caches leftmost indexes
|
||||
self.lowercaseColumnIndexes = Dictionary(
|
||||
layoutColumns
|
||||
.enumerated()
|
||||
.map { ($0.element.1.lowercased(), $0.offset) },
|
||||
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
|
||||
}
|
||||
|
||||
func baseColumnIndex(atMappingIndex index: Int) -> Int {
|
||||
@@ -55,7 +98,9 @@ public struct LayoutedColumnMapping {
|
||||
}
|
||||
|
||||
/// LayoutedColumnMapping adopts LayoutedRowAdapter
|
||||
extension LayoutedColumnMapping : LayoutedRowAdapter {
|
||||
///
|
||||
/// :nodoc:
|
||||
extension LayoutedColumnMapping: LayoutedRowAdapter {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns self.
|
||||
@@ -71,7 +116,8 @@ extension LayoutedColumnMapping : LayoutedRowAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
extension LayoutedColumnMapping : RowLayout {
|
||||
/// :nodoc:
|
||||
extension LayoutedColumnMapping: RowLayout {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns the index of the leftmost column named `name`, in a
|
||||
@@ -90,6 +136,8 @@ extension LayoutedColumnMapping : RowLayout {
|
||||
///
|
||||
/// GRBD ships with a ready-made type that adopts this protocol:
|
||||
/// LayoutedColumnMapping.
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol LayoutedRowAdapter {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -107,6 +155,8 @@ public protocol LayoutedRowAdapter {
|
||||
///
|
||||
/// RowLayout is a protocol that supports the RowAdapter protocol. It describes
|
||||
/// a layout of a base row.
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol RowLayout {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -121,13 +171,15 @@ public protocol RowLayout {
|
||||
func layoutIndex(ofColumn name: String) -> Int?
|
||||
}
|
||||
|
||||
extension SelectStatement : RowLayout {
|
||||
extension SelectStatement: RowLayout {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public var layoutColumns: [(Int, String)] {
|
||||
return Array(columnNames.enumerated())
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func layoutIndex(ofColumn name: String) -> Int? {
|
||||
return index(ofColumn: name)
|
||||
}
|
||||
@@ -148,8 +200,8 @@ extension SelectStatement : RowLayout {
|
||||
/// let adapter = SuffixRowAdapter(fromIndex: 2)
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
|
||||
///
|
||||
/// // <Row baz:3>
|
||||
/// try Row.fetchOne(db, sql, adapter: adapter)
|
||||
/// // [baz:3]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
public protocol RowAdapter {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
@@ -171,8 +223,8 @@ public protocol RowAdapter {
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // <Row foo:1>
|
||||
/// try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: FirstColumnAdapter())
|
||||
/// // [foo:1]
|
||||
/// try Row.fetchOne(db, sql: "SELECT 1, 2, 3", adapter: FirstColumnAdapter())
|
||||
func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter
|
||||
}
|
||||
|
||||
@@ -185,7 +237,11 @@ extension RowAdapter {
|
||||
/// - parameter scopes: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
public func addingScopes(_ scopes: [String: RowAdapter]) -> RowAdapter {
|
||||
return ScopeAdapter(mainAdapter: self, scopes: scopes)
|
||||
if scopes.isEmpty {
|
||||
return self
|
||||
} else {
|
||||
return ScopeAdapter(base: self, scopes: scopes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,14 +251,26 @@ extension RowAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/// EmptyRowAdapter is a row adapter that hides all columns.
|
||||
public struct EmptyRowAdapter: RowAdapter {
|
||||
/// Creates an EmptyRowAdapter
|
||||
public init() { }
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
return LayoutedColumnMapping(layoutColumns: [])
|
||||
}
|
||||
}
|
||||
|
||||
/// ColumnMapping is a row adapter that maps column names.
|
||||
///
|
||||
/// let adapter = ColumnMapping(["foo": "bar"])
|
||||
/// let sql = "SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz"
|
||||
///
|
||||
/// // <Row foo:"bar">
|
||||
/// try Row.fetchOne(db, sql, adapter: adapter)
|
||||
public struct ColumnMapping : RowAdapter {
|
||||
/// // [foo:"bar"]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
public struct ColumnMapping: RowAdapter {
|
||||
/// A dictionary from mapped column names to column names in a base row.
|
||||
let mapping: [String: String]
|
||||
|
||||
@@ -213,12 +281,18 @@ public struct ColumnMapping : RowAdapter {
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
let layoutColumns = try mapping
|
||||
.map { (mappedColumn, baseColumn) -> (Int, String) in
|
||||
guard let index = layout.layoutIndex(ofColumn: baseColumn) else {
|
||||
let columnNames = layout.layoutColumns.map { $0.1 }
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Mapping references missing column \(baseColumn). Valid column names are: \(columnNames.joined(separator: ", ")).")
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: """
|
||||
Mapping references missing column \(baseColumn). \
|
||||
Valid column names are: \(columnNames.joined(separator: ", ")).
|
||||
""")
|
||||
}
|
||||
let baseIndex = layout.layoutColumns[index].0
|
||||
return (baseIndex, mappedColumn)
|
||||
@@ -233,9 +307,9 @@ public struct ColumnMapping : RowAdapter {
|
||||
/// let adapter = SuffixRowAdapter(fromIndex: 2)
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
|
||||
///
|
||||
/// // <Row baz:3>
|
||||
/// try Row.fetchOne(db, sql, adapter: adapter)
|
||||
public struct SuffixRowAdapter : RowAdapter {
|
||||
/// // [baz:3]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
public struct SuffixRowAdapter: RowAdapter {
|
||||
/// The suffix index
|
||||
let index: Int
|
||||
|
||||
@@ -249,6 +323,7 @@ public struct SuffixRowAdapter : RowAdapter {
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
return LayoutedColumnMapping(layoutColumns: layout.layoutColumns.suffix(from: index))
|
||||
}
|
||||
@@ -259,9 +334,9 @@ public struct SuffixRowAdapter : RowAdapter {
|
||||
/// let adapter = RangeRowAdapter(1..<3)
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz, 4 as qux"
|
||||
///
|
||||
/// // <Row bar:2 baz: 3>
|
||||
/// try Row.fetchOne(db, sql, adapter: adapter)
|
||||
public struct RangeRowAdapter : RowAdapter {
|
||||
/// // [bar:2 baz:3]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
public struct RangeRowAdapter: RowAdapter {
|
||||
/// The range
|
||||
let range: CountableRange<Int>
|
||||
|
||||
@@ -278,6 +353,7 @@ public struct RangeRowAdapter : RowAdapter {
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
return LayoutedColumnMapping(layoutColumns: layout.layoutColumns[range])
|
||||
}
|
||||
@@ -296,40 +372,67 @@ public struct RangeRowAdapter : RowAdapter {
|
||||
///
|
||||
/// // Fetch
|
||||
/// let sql = "SELECT 'foo' AS foo, 'bar' AS bar"
|
||||
/// let row = try Row.fetchOne(db, sql, adapter: adapter)!
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
///
|
||||
/// // Scoped rows:
|
||||
/// if let fooRow = row.scoped(on: "foo") {
|
||||
/// fooRow.value(named: "value") // "foo"
|
||||
/// if let fooRow = row.scopes["foo"] {
|
||||
/// fooRow["value"] // "foo"
|
||||
/// }
|
||||
/// if let barRow = row.scopeed(on: "bar") {
|
||||
/// barRow.value(named: "value") // "bar"
|
||||
/// if let barRow = row.scopes["bar"] {
|
||||
/// barRow["value"] // "bar"
|
||||
/// }
|
||||
public struct ScopeAdapter : RowAdapter {
|
||||
public struct ScopeAdapter: RowAdapter {
|
||||
|
||||
/// The main adapter
|
||||
let mainAdapter: RowAdapter
|
||||
/// The base adapter
|
||||
let base: RowAdapter
|
||||
|
||||
/// The scope adapters
|
||||
let scopes: [String: RowAdapter]
|
||||
|
||||
/// Creates a scoped adapter.
|
||||
/// Creates an adapter that preserves row contents and add scoped rows.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let adapter = ScopeAdapter(["suffix": SuffixRowAdapter(fromIndex: 1)])
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 1, 2, 3", adapter: adapter)!
|
||||
/// row // [1, 2, 3]
|
||||
/// row.scopes["suffix"] // [2, 3]
|
||||
///
|
||||
/// - parameter scopes: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
public init(_ scopes: [String: RowAdapter]) {
|
||||
self.mainAdapter = SuffixRowAdapter(fromIndex: 0) // Use SuffixRowAdapter(fromIndex: 0) as the identity adapter
|
||||
self.scopes = scopes
|
||||
// Use SuffixRowAdapter(fromIndex: 0) as the identity adapter
|
||||
self.init(base: SuffixRowAdapter(fromIndex: 0), scopes: scopes)
|
||||
}
|
||||
|
||||
init(mainAdapter: RowAdapter, scopes: [String: RowAdapter]) {
|
||||
self.mainAdapter = mainAdapter
|
||||
/// Creates an adapter based on the base adapter, and add scoped rows.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let baseAdapter = RangeRowAdapter(0..<1)
|
||||
/// let adapter = ScopeAdapter(base: baseAdapter, scopes: ["suffix": SuffixRowAdapter(fromIndex: 1)])
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 1, 2, 3", adapter: adapter)!
|
||||
/// row // [1]
|
||||
/// row.scopes["initial"] // [2, 3]
|
||||
///
|
||||
/// If the base adapter already defines scopes, the given scopes replace
|
||||
/// eventual existing scopes with the same name.
|
||||
///
|
||||
/// This initializer is equivalent to `baseAdapter.addingScopes(scopes)`.
|
||||
///
|
||||
/// - parameter base: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
/// - parameter scopes: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
public init(base: RowAdapter, scopes: [String: RowAdapter]) {
|
||||
self.base = base
|
||||
self.scopes = scopes
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
let layoutedAdapter = try mainAdapter.layoutedAdapter(from: layout)
|
||||
let layoutedAdapter = try base.layoutedAdapter(from: layout)
|
||||
var layoutedScopes = layoutedAdapter.scopes
|
||||
for (name, adapter) in scopes {
|
||||
try layoutedScopes[name] = adapter.layoutedAdapter(from: layout)
|
||||
@@ -341,15 +444,15 @@ public struct ScopeAdapter : RowAdapter {
|
||||
}
|
||||
|
||||
/// The LayoutedRowAdapter for ScopeAdapter
|
||||
struct LayoutedScopeAdapter : LayoutedRowAdapter {
|
||||
struct LayoutedScopeAdapter: LayoutedRowAdapter {
|
||||
let mapping: LayoutedColumnMapping
|
||||
let scopes: [String: LayoutedRowAdapter]
|
||||
}
|
||||
|
||||
struct ChainedAdapter : RowAdapter {
|
||||
struct ChainedAdapter: RowAdapter {
|
||||
let first: RowAdapter
|
||||
let second: RowAdapter
|
||||
|
||||
|
||||
func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
return try second.layoutedAdapter(from: first.layoutedAdapter(from: layout).mapping)
|
||||
}
|
||||
@@ -358,9 +461,9 @@ struct ChainedAdapter : RowAdapter {
|
||||
extension Row {
|
||||
/// Creates a row from a base row and a statement adapter
|
||||
convenience init(base: Row, adapter: LayoutedRowAdapter) {
|
||||
self.init(impl: AdapterRowImpl(base: base, adapter: adapter))
|
||||
self.init(impl: AdaptedRowImpl(base: base, adapter: adapter))
|
||||
}
|
||||
|
||||
|
||||
/// Returns self if adapter is nil
|
||||
func adapted(with adapter: RowAdapter?, layout: RowLayout) throws -> Row {
|
||||
guard let adapter = adapter else {
|
||||
@@ -370,7 +473,7 @@ extension Row {
|
||||
}
|
||||
}
|
||||
|
||||
struct AdapterRowImpl : RowImpl {
|
||||
struct AdaptedRowImpl: RowImpl {
|
||||
let base: Row
|
||||
let adapter: LayoutedRowAdapter
|
||||
let mapping: LayoutedColumnMapping
|
||||
@@ -389,12 +492,39 @@ struct AdapterRowImpl : RowImpl {
|
||||
return base.isFetched
|
||||
}
|
||||
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
|
||||
return base.value(atIndex: mapping.baseColumnIndex(atMappingIndex: index))
|
||||
func scopes(prefetchedRows: Row.PrefetchedRowsView) -> Row.ScopesView {
|
||||
return Row.ScopesView(row: base, scopes: adapter.scopes, prefetchedRows: prefetchedRows)
|
||||
}
|
||||
|
||||
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
|
||||
return base.dataNoCopy(atIndex: mapping.baseColumnIndex(atMappingIndex: index))
|
||||
func hasNull(atUncheckedIndex index: Int) -> Bool {
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return base.impl.hasNull(atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return base.impl.databaseValue(atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int) -> Value
|
||||
{
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return Value.fastDecode(from: base, atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int) -> Value?
|
||||
{
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return Value.fastDecodeIfPresent(from: base, atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func dataNoCopy(atUncheckedIndex index: Int) -> Data? {
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return base.impl.dataNoCopy(atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func columnName(atUncheckedIndex index: Int) -> String {
|
||||
@@ -405,18 +535,16 @@ struct AdapterRowImpl : RowImpl {
|
||||
return mapping.layoutIndex(ofColumn: name)
|
||||
}
|
||||
|
||||
func scoped(on name: String) -> Row? {
|
||||
guard let adapter = adapter.scopes[name] else {
|
||||
return nil
|
||||
}
|
||||
return Row(base: base, adapter: adapter)
|
||||
}
|
||||
|
||||
var scopeNames: Set<String> {
|
||||
return Set(adapter.scopes.keys)
|
||||
}
|
||||
|
||||
func copy(_ row: Row) -> Row {
|
||||
func copiedRow(_ row: Row) -> Row {
|
||||
return Row(base: base.copy(), adapter: adapter)
|
||||
}
|
||||
|
||||
func unscopedRow(_ row: Row) -> Row {
|
||||
assert(adapter.mapping.scopes.isEmpty)
|
||||
return Row(base: base, adapter: adapter.mapping)
|
||||
}
|
||||
|
||||
func unadaptedRow(_ row: Row) -> Row {
|
||||
return base.unadapted
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
#if swift(>=5.0)
|
||||
/// :nodoc:
|
||||
public struct SQLInterpolation: StringInterpolationProtocol {
|
||||
var context = SQLGenerationContext.literalGenerationContext(withArguments: true)
|
||||
var sql: String
|
||||
var arguments: StatementArguments {
|
||||
get { return context.arguments! }
|
||||
set { context.arguments = newValue }
|
||||
}
|
||||
|
||||
public init(literalCapacity: Int, interpolationCount: Int) {
|
||||
sql = ""
|
||||
sql.reserveCapacity(literalCapacity + interpolationCount)
|
||||
}
|
||||
|
||||
/// "SELECT * FROM player"
|
||||
public mutating func appendLiteral(_ sql: String) {
|
||||
self.sql += sql
|
||||
}
|
||||
|
||||
/// "SELECT * FROM \(sql: "player")"
|
||||
public mutating func appendInterpolation(sql: String, arguments: StatementArguments = StatementArguments()) {
|
||||
self.sql += sql
|
||||
self.arguments += arguments
|
||||
}
|
||||
|
||||
/// "SELECT * FROM player WHERE \(literal: condition)"
|
||||
public mutating func appendInterpolation(literal sqlLiteral: SQLLiteral) {
|
||||
sql += sqlLiteral.sql
|
||||
arguments += sqlLiteral.arguments
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,146 @@
|
||||
/// SQLLiteral is a type which support [SQL
|
||||
/// Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md).
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// let name: String = ...
|
||||
/// let id: Int64 = ...
|
||||
/// let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
/// try db.execute(literal: query)
|
||||
/// }
|
||||
public struct SQLLiteral {
|
||||
public private(set) var sql: String
|
||||
public private(set) var arguments: StatementArguments
|
||||
|
||||
/// Creates an SQLLiteral from a plain SQL string, and eventual arguments.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let query = SQLLiteral(
|
||||
/// sql: "UPDATE player SET name = ? WHERE id = ?",
|
||||
/// arguments: [name, id])
|
||||
public init(sql: String, arguments: StatementArguments = StatementArguments()) {
|
||||
self.sql = sql
|
||||
self.arguments = arguments
|
||||
}
|
||||
|
||||
/// Returns a literal whose SQL is transformed by the given closure.
|
||||
public func mapSQL(_ transform: (String) throws -> String) rethrows -> SQLLiteral {
|
||||
var result = self
|
||||
result.sql = try transform(sql)
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLLiteral {
|
||||
/// Returns the SQLLiteral produced by the concatenation of two literals.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// let selection: SQLLiteral = "SELECT * FROM player "
|
||||
/// let condition: SQLLiteral = "WHERE name = \(name)"
|
||||
/// let query = selection + condition
|
||||
public static func + (lhs: SQLLiteral, rhs: SQLLiteral) -> SQLLiteral {
|
||||
var result = lhs
|
||||
result += rhs
|
||||
return result
|
||||
}
|
||||
|
||||
/// Appends an SQLLiteral to the receiver.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQLLiteral = "SELECT * FROM player "
|
||||
/// query += "WHERE name = \(name)"
|
||||
public static func += (lhs: inout SQLLiteral, rhs: SQLLiteral) {
|
||||
lhs.sql += rhs.sql
|
||||
lhs.arguments += rhs.arguments
|
||||
}
|
||||
|
||||
/// Appends an SQLLiteral to the receiver.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQLLiteral = "SELECT * FROM player "
|
||||
/// query.append(literal: "WHERE name = \(name)")
|
||||
public mutating func append(literal sqlLiteral: SQLLiteral) {
|
||||
self += sqlLiteral
|
||||
}
|
||||
|
||||
/// Appends a plain SQL string to the receiver, and eventual arguments.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQLLiteral = "SELECT * FROM player "
|
||||
/// query.append(sql: "WHERE name = ?", arguments: [name])
|
||||
public mutating func append(sql: String, arguments: StatementArguments = StatementArguments()) {
|
||||
self += SQLLiteral(sql: sql, arguments: arguments)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence where Element == SQLLiteral {
|
||||
/// Returns the concatenated SQLLiteral of this sequence of literals,
|
||||
/// inserting the given separator between each element.
|
||||
///
|
||||
/// let components: [SQLLiteral] = [
|
||||
/// "UPDATE player",
|
||||
/// "SET name = \(name)",
|
||||
/// "WHERE id = \(id)"
|
||||
/// ]
|
||||
/// let query = components.joined(separator: " ")
|
||||
public func joined(separator: String = "") -> SQLLiteral {
|
||||
var sql = ""
|
||||
var arguments = StatementArguments()
|
||||
var first = true
|
||||
for literal in self {
|
||||
if first {
|
||||
first = false
|
||||
} else {
|
||||
sql += separator
|
||||
}
|
||||
sql += literal.sql
|
||||
arguments += literal.arguments
|
||||
}
|
||||
return SQLLiteral(sql: sql, arguments: arguments)
|
||||
}
|
||||
}
|
||||
|
||||
extension Collection where Element == SQLLiteral {
|
||||
/// Returns the concatenated SQLLiteral of this collection of literals,
|
||||
/// inserting the given separator between each element.
|
||||
///
|
||||
/// let components: [SQLLiteral] = [
|
||||
/// "UPDATE player",
|
||||
/// "SET name = \(name)",
|
||||
/// "WHERE id = \(id)"
|
||||
/// ]
|
||||
/// let query = components.joined(separator: " ")
|
||||
public func joined(separator: String = "") -> SQLLiteral {
|
||||
let sql = map { $0.sql }.joined(separator: separator)
|
||||
let arguments = reduce(into: StatementArguments()) { $0 += $1.arguments }
|
||||
return SQLLiteral(sql: sql, arguments: arguments)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ExpressibleByStringInterpolation
|
||||
|
||||
#if swift(>=5.0)
|
||||
extension SQLLiteral: ExpressibleByStringInterpolation {
|
||||
/// :nodoc
|
||||
public init(unicodeScalarLiteral: String) {
|
||||
self.init(sql: unicodeScalarLiteral, arguments: [])
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(extendedGraphemeClusterLiteral: String) {
|
||||
self.init(sql: extendedGraphemeClusterLiteral, arguments: [])
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(stringLiteral: String) {
|
||||
self.init(sql: stringLiteral, arguments: [])
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(stringInterpolation sqlInterpolation: SQLInterpolation) {
|
||||
self.init(sql: sqlInterpolation.sql, arguments: sqlInterpolation.arguments)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,185 @@
|
||||
/// A FetchRequest built from raw SQL.
|
||||
public struct SQLRequest<T>: FetchRequest {
|
||||
/// There are two statement caches: one "public" for statements generated by
|
||||
/// the user, and one "internal" for the statements generated by GRDB. Those
|
||||
/// are separated so that GRDB has no opportunity to inadvertently modify
|
||||
/// the arguments of user's cached statements.
|
||||
enum Cache {
|
||||
/// The public cache, for library user
|
||||
case `public`
|
||||
|
||||
/// The internal cache, for GRDB
|
||||
case `internal`
|
||||
}
|
||||
|
||||
public typealias RowDecoder = T
|
||||
|
||||
/// The raw SQL query
|
||||
///
|
||||
/// let id = 42
|
||||
/// let request: SQLRequest<Player> = "SELECT * FROM player WHERE id = \(id)"
|
||||
/// request.sql // "SELECT * FROM player WHERE id = ?"
|
||||
public var sql: String { return sqlLiteral.sql }
|
||||
|
||||
/// The request argument
|
||||
///
|
||||
/// let id = 42
|
||||
/// let request: SQLRequest<Player> = "SELECT * FROM player WHERE id = \(id)"
|
||||
/// request.arguments // [42]
|
||||
public var arguments: StatementArguments { return sqlLiteral.arguments }
|
||||
|
||||
/// The request adapter
|
||||
public var adapter: RowAdapter?
|
||||
|
||||
private var sqlLiteral: SQLLiteral
|
||||
private let cache: Cache?
|
||||
|
||||
/// Creates a request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
///
|
||||
/// let request = SQLRequest<String>(sql: """
|
||||
/// SELECT name FROM player
|
||||
/// """)
|
||||
/// let request = SQLRequest<Player>(sql: """
|
||||
/// SELECT * FROM player WHERE id = ?
|
||||
/// """, arguments: [1])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: A SQLRequest
|
||||
public init(
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil,
|
||||
cached: Bool = false)
|
||||
{
|
||||
self.init(
|
||||
literal: SQLLiteral(sql: sql, arguments: arguments),
|
||||
adapter: adapter,
|
||||
fromCache: cached ? .public : nil)
|
||||
}
|
||||
|
||||
/// Creates a request from an SQLLiteral, and optional row adapter.
|
||||
///
|
||||
/// let request = SQLRequest<String>(literal: SQLLiteral(sql: """
|
||||
/// SELECT name FROM player
|
||||
/// """))
|
||||
/// let request = SQLRequest<Player>(literal: SQLLiteral(sql: """
|
||||
/// SELECT * FROM player WHERE name = ?
|
||||
/// """, arguments: ["O'Brien"]))
|
||||
///
|
||||
/// With Swift 5, you can safely embed raw values in your SQL queries,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// let request = SQLRequest<Player>(literal: """
|
||||
/// SELECT * FROM player WHERE name = \("O'brien")
|
||||
/// """)
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqlLiteral: An SQLLiteral.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: A SQLRequest
|
||||
public init(literal sqlLiteral: SQLLiteral, adapter: RowAdapter? = nil, cached: Bool = false) {
|
||||
self.init(literal: sqlLiteral, adapter: adapter, fromCache: cached ? .public : nil)
|
||||
}
|
||||
|
||||
/// Creates an SQL request from any other fetch request.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A request.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: An SQLRequest
|
||||
public init<Request>(
|
||||
_ db: Database,
|
||||
request: Request,
|
||||
cached: Bool = false)
|
||||
throws
|
||||
where Request: FetchRequest, Request.RowDecoder == RowDecoder
|
||||
{
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
self.init(
|
||||
literal: SQLLiteral(sql: request.statement.sql, arguments: request.statement.arguments),
|
||||
adapter: request.adapter,
|
||||
cached: cached)
|
||||
}
|
||||
|
||||
/// Creates a request from an SQLLiteral, and optional row adapter.
|
||||
///
|
||||
/// let request = SQLRequest<String>(literal: SQLLiteral(sql: """
|
||||
/// SELECT name FROM player
|
||||
/// """))
|
||||
/// let request = SQLRequest<Player>(literal: SQLLiteral(sql: """
|
||||
/// SELECT * FROM player WHERE name = ?
|
||||
/// """, arguments: ["O'Brien"]))
|
||||
///
|
||||
/// With Swift 5, you can safely embed raw values in your SQL queries,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// let request = SQLRequest<Player>(literal: """
|
||||
/// SELECT * FROM player WHERE name = \("O'brien")
|
||||
/// """)
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqlLiteral: An SQLLiteral.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - cache: The eventual cache
|
||||
/// - returns: A SQLRequest
|
||||
init(literal sqlLiteral: SQLLiteral, adapter: RowAdapter? = nil, fromCache cache: Cache?) {
|
||||
self.sqlLiteral = sqlLiteral
|
||||
self.adapter = adapter
|
||||
self.cache = cache
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter singleResult: SQLRequest disregards this hint.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
|
||||
let statement: SelectStatement
|
||||
switch cache {
|
||||
case .none:
|
||||
statement = try db.makeSelectStatement(sql: sqlLiteral.sql)
|
||||
case .public?:
|
||||
statement = try db.cachedSelectStatement(sql: sqlLiteral.sql)
|
||||
case .internal?:
|
||||
statement = try db.internalCachedSelectStatement(sql: sqlLiteral.sql)
|
||||
}
|
||||
try statement.setArgumentsWithValidation(sqlLiteral.arguments)
|
||||
return PreparedRequest(statement: statement, adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
#if swift(>=5.0)
|
||||
extension SQLRequest: ExpressibleByStringInterpolation {
|
||||
/// :nodoc
|
||||
public init(unicodeScalarLiteral: String) {
|
||||
self.init(sql: unicodeScalarLiteral)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(extendedGraphemeClusterLiteral: String) {
|
||||
self.init(sql: extendedGraphemeClusterLiteral)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(stringLiteral: String) {
|
||||
self.init(sql: stringLiteral)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(stringInterpolation sqlInterpolation: SQLInterpolation) {
|
||||
self.init(literal: SQLLiteral(stringInterpolation: sqlInterpolation))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,9 +1,5 @@
|
||||
import Dispatch
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#endif
|
||||
|
||||
/// SchedulingWatchdog makes sure that databases connections are used on correct
|
||||
/// dispatch queues, and warns the user with a fatal error whenever she misuses
|
||||
/// a database connection.
|
||||
@@ -20,47 +16,47 @@ import Dispatch
|
||||
/// of the dispatch queue, a SchedulingWatchdog that allows that database only.
|
||||
///
|
||||
/// Later on, the queue can be shared by several databases with the method
|
||||
/// allowing(databases:execute:). See SerializedDatabase.sync() for
|
||||
/// an example.
|
||||
/// inheritingAllowedDatabases(from:execute:). See SerializedDatabase.sync()
|
||||
/// for an example.
|
||||
///
|
||||
/// - preconditionValidQueue() crashes whenever a database is used in an invalid
|
||||
/// dispatch queue.
|
||||
final class SchedulingWatchdog {
|
||||
private static let specificKey = DispatchSpecificKey<SchedulingWatchdog>()
|
||||
private static let watchDogKey = DispatchSpecificKey<SchedulingWatchdog>()
|
||||
private(set) var allowedDatabases: [Database]
|
||||
var databaseObservationBroker: DatabaseObservationBroker?
|
||||
|
||||
private init(allowedDatabase database: Database) {
|
||||
allowedDatabases = [database]
|
||||
}
|
||||
|
||||
static func makeSerializedQueue(allowingDatabase database: Database) -> DispatchQueue {
|
||||
let queue = DispatchQueue(label: "GRDB.SerializedDatabase")
|
||||
static func allowDatabase(_ database: Database, onQueue queue: DispatchQueue) {
|
||||
precondition(queue.getSpecific(key: watchDogKey) == nil)
|
||||
let watchdog = SchedulingWatchdog(allowedDatabase: database)
|
||||
queue.setSpecific(key: specificKey, value: watchdog)
|
||||
return queue
|
||||
queue.setSpecific(key: watchDogKey, value: watchdog)
|
||||
}
|
||||
|
||||
// Temporarily allows `databases` while executing `body`
|
||||
func allowing<T>(databases: [Database], execute body: () throws -> T) rethrows -> T {
|
||||
func inheritingAllowedDatabases<T>(from other: SchedulingWatchdog, execute body: () throws -> T) rethrows -> T {
|
||||
let backup = allowedDatabases
|
||||
allowedDatabases.append(contentsOf: databases)
|
||||
allowedDatabases.append(contentsOf: other.allowedDatabases)
|
||||
defer { allowedDatabases = backup }
|
||||
return try body()
|
||||
}
|
||||
|
||||
static func preconditionValidQueue(_ db: Database, _ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
|
||||
GRDBPrecondition(allows(db), message, file: file, line: line)
|
||||
static func preconditionValidQueue(
|
||||
_ db: Database,
|
||||
_ message: @autoclosure() -> String = "Database was not used on the correct thread.",
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
{
|
||||
GRDBPrecondition(current?.allows(db) ?? false, message(), file: file, line: line)
|
||||
}
|
||||
|
||||
static func allows(_ db: Database) -> Bool {
|
||||
return current?.allows(db) ?? false
|
||||
static var current: SchedulingWatchdog? {
|
||||
return DispatchQueue.getSpecific(key: watchDogKey)
|
||||
}
|
||||
|
||||
func allows(_ db: Database) -> Bool {
|
||||
return allowedDatabases.contains { $0 === db }
|
||||
}
|
||||
|
||||
static var current: SchedulingWatchdog? {
|
||||
return DispatchQueue.getSpecific(key: specificKey)
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,14 @@ final class SerializedDatabase {
|
||||
/// The dispatch queue
|
||||
private let queue: DispatchQueue
|
||||
|
||||
init(path: String, configuration: Configuration = Configuration(), schemaCache: DatabaseSchemaCache) throws {
|
||||
init(
|
||||
path: String,
|
||||
configuration: Configuration = Configuration(),
|
||||
schemaCache: DatabaseSchemaCache,
|
||||
defaultLabel: String,
|
||||
purpose: String? = nil)
|
||||
throws
|
||||
{
|
||||
// According to https://www.sqlite.org/threadsafe.html
|
||||
//
|
||||
// > SQLite support three different threading modes:
|
||||
@@ -37,11 +44,17 @@ final class SerializedDatabase {
|
||||
var config = configuration
|
||||
config.threadingMode = .multiThread
|
||||
|
||||
db = try Database(path: path, configuration: config, schemaCache: schemaCache)
|
||||
queue = SchedulingWatchdog.makeSerializedQueue(allowingDatabase: db)
|
||||
self.path = path
|
||||
self.db = try Database(path: path, configuration: config, schemaCache: schemaCache)
|
||||
self.queue = configuration.makeDispatchQueue(defaultLabel: defaultLabel, purpose: purpose)
|
||||
SchedulingWatchdog.allowDatabase(db, onQueue: queue)
|
||||
try queue.sync {
|
||||
try db.setup()
|
||||
do {
|
||||
try db.setup()
|
||||
} catch {
|
||||
db.close()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,27 +74,28 @@ final class SerializedDatabase {
|
||||
//
|
||||
// 1. A database is invoked from some queue like the main queue:
|
||||
//
|
||||
// dbQueue.inDatabase { db in // <-- we're here
|
||||
// serializedDatabase.sync { db in // <-- we're here
|
||||
// }
|
||||
//
|
||||
// 2. A database is invoked in a reentrant way:
|
||||
//
|
||||
// dbQueue.inDatabase { db in
|
||||
// dbQueue.inDatabase { db in // <-- we're here
|
||||
// serializedDatabase.sync { db in
|
||||
// serializedDatabase.sync { db in // <-- we're here
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// 3. A database in invoked from another database:
|
||||
//
|
||||
// dbQueue1.inDatabase { db1 in
|
||||
// dbQueue2.inDatabase { db2 in // <-- we're here
|
||||
// serializedDatabase1.sync { db1 in
|
||||
// serializedDatabase2.sync { db2 in // <-- we're here
|
||||
// }
|
||||
// }
|
||||
|
||||
guard let watchdog = SchedulingWatchdog.current else {
|
||||
// Case 1
|
||||
return try queue.sync {
|
||||
try block(db)
|
||||
defer { preconditionNoUnsafeTransactionLeft(db) }
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,8 +104,9 @@ final class SerializedDatabase {
|
||||
|
||||
// Case 3
|
||||
return try queue.sync {
|
||||
try SchedulingWatchdog.current!.allowing(databases: watchdog.allowedDatabases) {
|
||||
try block(db)
|
||||
try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) {
|
||||
defer { preconditionNoUnsafeTransactionLeft(db) }
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -105,39 +120,60 @@ final class SerializedDatabase {
|
||||
//
|
||||
// 1. A database is invoked from some queue like the main queue:
|
||||
//
|
||||
// dbQueue.inDatabase { db in // <-- we're here
|
||||
// serializedDatabase.reentrantSync { db in // <-- we're here
|
||||
// }
|
||||
//
|
||||
// 2. A database is invoked in a reentrant way:
|
||||
//
|
||||
// dbQueue.inDatabase { db in
|
||||
// dbQueue.inDatabase { db in // <-- we're here
|
||||
// serializedDatabase.reentrantSync { db in
|
||||
// serializedDatabase.reentrantSync { db in // <-- we're here
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// 3. A database in invoked from another database:
|
||||
//
|
||||
// dbQueue1.inDatabase { db1 in
|
||||
// dbQueue2.inDatabase { db2 in // <-- we're here
|
||||
// serializedDatabase1.reentrantSync { db1 in
|
||||
// serializedDatabase2.reentrantSync { db2 in // <-- we're here
|
||||
// }
|
||||
// }
|
||||
|
||||
guard let watchdog = SchedulingWatchdog.current else {
|
||||
// Case 1
|
||||
return try queue.sync {
|
||||
try block(db)
|
||||
// Since we are reentrant, a transaction may already be opened.
|
||||
// In this case, don't check for unsafe transaction at the end.
|
||||
if db.isInsideTransaction {
|
||||
return try block(db)
|
||||
} else {
|
||||
defer { preconditionNoUnsafeTransactionLeft(db) }
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Case 2
|
||||
if watchdog.allows(db) {
|
||||
return try block(db)
|
||||
// Since we are reentrant, a transaction may already be opened.
|
||||
// In this case, don't check for unsafe transaction at the end.
|
||||
if db.isInsideTransaction {
|
||||
return try block(db)
|
||||
} else {
|
||||
defer { preconditionNoUnsafeTransactionLeft(db) }
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
|
||||
// Case 3
|
||||
return try queue.sync {
|
||||
try SchedulingWatchdog.current!.allowing(databases: watchdog.allowedDatabases) {
|
||||
try block(db)
|
||||
try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) {
|
||||
// Since we are reentrant, a transaction may already be opened.
|
||||
// In this case, don't check for unsafe transaction at the end.
|
||||
if db.isInsideTransaction {
|
||||
return try block(db)
|
||||
} else {
|
||||
defer { preconditionNoUnsafeTransactionLeft(db) }
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -146,17 +182,14 @@ final class SerializedDatabase {
|
||||
func async(_ block: @escaping (Database) -> Void) {
|
||||
queue.async {
|
||||
block(self.db)
|
||||
self.preconditionNoUnsafeTransactionLeft(self.db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an optional database connection. If not nil, the caller is
|
||||
/// executing on the serialized dispatch queue.
|
||||
var availableDatabaseConnection: Database? {
|
||||
guard let watchdog = SchedulingWatchdog.current else { return nil }
|
||||
guard watchdog.allows(db) else { return nil }
|
||||
return db
|
||||
/// Returns true if any only if the current dispatch queue is valid.
|
||||
var onValidQueue: Bool {
|
||||
return SchedulingWatchdog.current?.allows(db) ?? false
|
||||
}
|
||||
|
||||
|
||||
/// Executes the block in the current queue.
|
||||
///
|
||||
@@ -167,7 +200,25 @@ final class SerializedDatabase {
|
||||
}
|
||||
|
||||
/// Fatal error if current dispatch queue is not valid.
|
||||
func preconditionValidQueue(_ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
|
||||
SchedulingWatchdog.preconditionValidQueue(db, message, file: file, line: line)
|
||||
func preconditionValidQueue(
|
||||
_ message: @autoclosure() -> String = "Database was not used on the correct thread.",
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
{
|
||||
SchedulingWatchdog.preconditionValidQueue(db, message(), file: file, line: line)
|
||||
}
|
||||
|
||||
/// Fatal error if a transaction has been left opened.
|
||||
private func preconditionNoUnsafeTransactionLeft(
|
||||
_ db: Database,
|
||||
_ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access",
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
{
|
||||
GRDBPrecondition(
|
||||
configuration.allowsUnsafeTransactions || !db.isInsideTransaction,
|
||||
message(),
|
||||
file: file,
|
||||
line: line)
|
||||
}
|
||||
}
|
||||