mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-01 04:38:44 +00:00
Compare commits
858
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4c541a99b5 | ||
|
|
2cf6c756e1 | ||
|
|
d56223cba1 | ||
|
|
bc4fd8ff58 | ||
|
|
cdb181d9ca | ||
|
|
f4b4035704 | ||
|
|
57a4587b5b | ||
|
|
ae837a3a44 | ||
|
|
c64bc11627 | ||
|
|
de96d5f6f0 | ||
|
|
d3d2a9c4f7 | ||
|
|
f10c74c374 | ||
|
|
fcfdab2f11 | ||
|
|
f441341543 | ||
|
|
dd6b98ce04 | ||
|
|
5b73581126 | ||
|
|
9a896650ff | ||
|
|
344878cdb2 | ||
|
|
20ffddd572 | ||
|
|
4ddb6b89ce | ||
|
|
9da1a83cca | ||
|
|
8205f02672 | ||
|
|
78377d5cc0 | ||
|
|
04543755d8 | ||
|
|
cdc0131369 | ||
|
|
1cd6c7cbff | ||
|
|
bbbe0d899d | ||
|
|
9f16865ff1 | ||
|
|
14d2b931a4 | ||
|
|
802b4ca78a | ||
|
|
1c60e5ef42 | ||
|
|
9f41e56c32 | ||
|
|
0ae3f32f7f | ||
|
|
c977cb8226 | ||
|
|
78448cf8f4 | ||
|
|
30de9853d6 | ||
|
|
7a1196263d | ||
|
|
3043d7dca5 | ||
|
|
d2dd757d0c | ||
|
|
764ad4bf72 | ||
|
|
e6d4223b14 | ||
|
|
ba3c938eb9 | ||
|
|
5999227c01 | ||
|
|
78545f2c8c | ||
|
|
263a549c21 | ||
|
|
6689470457 | ||
|
|
bbbd6bba90 | ||
|
|
bb789e3dee | ||
|
|
b312d4cf5a | ||
|
|
f335123c2b | ||
|
|
34d87c0e85 | ||
|
|
0f2e993790 | ||
|
|
1831017d64 | ||
|
|
4b934fda75 | ||
|
|
53c40fd80f | ||
|
|
639fa9168d | ||
|
|
1c5017a108 | ||
|
|
9ca1f6644c | ||
|
|
3f3cfa5381 | ||
|
|
bde61b26ab | ||
|
|
0a5bef4c0e | ||
|
|
218774d39a | ||
|
|
a0a9cfca65 | ||
|
|
c8bb0a4799 | ||
|
|
f1ff7f2a2a | ||
|
|
725cccccab | ||
|
|
1525075cce | ||
|
|
7110a1fab3 | ||
|
|
de382d30b8 | ||
|
|
3521030e13 | ||
|
|
eeacf93772 | ||
|
|
000aaa8698 | ||
|
|
77b85bed25 | ||
|
|
bb8323b91d | ||
|
|
d804b5ed9c | ||
|
|
2af60cb324 | ||
|
|
0434567f30 | ||
|
|
155a16bef8 | ||
|
|
2ad1f37d2b | ||
|
|
32642d566b | ||
|
|
1f4d5ac61a | ||
|
|
87fdd9a66f | ||
|
|
79d82337b2 | ||
|
|
fab4638fc9 | ||
|
|
a49fd85627 | ||
|
|
ac8c4aea63 | ||
|
|
5413dcfeeb | ||
|
|
4e0ab25106 | ||
|
|
c52db6095a | ||
|
|
1464940eeb | ||
|
|
f274e464cd | ||
|
|
c3e7736534 | ||
|
|
9b95dd5be1 | ||
|
|
77da5f4a30 | ||
|
|
43ced9b2f0 | ||
|
|
4ffad63f1b | ||
|
|
62e7ea1ef2 | ||
|
|
91492b849d | ||
|
|
d54d0abc07 | ||
|
|
3b096b38e7 | ||
|
|
9593297cf0 | ||
|
|
8ac5591189 | ||
|
|
4232fa687d | ||
|
|
bd9aea303d | ||
|
|
5abc737bf0 | ||
|
|
d4d14e3dd7 | ||
|
|
660d2b1fe7 | ||
|
|
bb44f48414 | ||
|
|
bbe7d2f1ca | ||
|
|
45e0de9960 | ||
|
|
1920482158 | ||
|
|
0437c0fed6 | ||
|
|
d08d2f52fb | ||
|
|
d1ff0912f1 | ||
|
|
e069e2732e | ||
|
|
c791e376e8 | ||
|
|
acf1eb935b | ||
|
|
87c4b1cfa8 | ||
|
|
d0fc34b199 | ||
|
|
9cee1e218d | ||
|
|
f5d55cb1a1 | ||
|
|
345a3dae28 | ||
|
|
1239178bee | ||
|
|
e5a7c73dc9 | ||
|
|
11e914db12 | ||
|
|
181ccd8d7d | ||
|
|
2800e9a81e | ||
|
|
18d2d512f0 | ||
|
|
c06552fbd4 | ||
|
|
a00a3f7c80 | ||
|
|
b9ac9b1ca8 | ||
|
|
07f1ddac04 | ||
|
|
12829e5bfb | ||
|
|
09fa46a0d9 | ||
|
|
e359529503 | ||
|
|
ac8d1b77b9 | ||
|
|
002c5ec2f1 | ||
|
|
b42f618a01 | ||
|
|
27a4215424 | ||
|
|
65167ec7da | ||
|
|
73489fc0e7 | ||
|
|
1aca8efa65 | ||
|
|
a22bf83ae8 | ||
|
|
f00a974211 | ||
|
|
ac475cc158 | ||
|
|
eacbdf23af | ||
|
|
e31a80e3c4 | ||
|
|
e3cf966c81 | ||
|
|
eeb71039d4 | ||
|
|
c5203f078d | ||
|
|
e29c52d7e5 | ||
|
|
06ac26a213 | ||
|
|
fae845a986 | ||
|
|
b671bb0faa | ||
|
|
93462cfd2c | ||
|
|
54357e4fec | ||
|
|
d8760253ff | ||
|
|
dc281cee25 | ||
|
|
a8ed98e414 | ||
|
|
f1a8c5ac92 | ||
|
|
079c0c7f26 | ||
|
|
bced461c4f | ||
|
|
9d6e127822 | ||
|
|
dff7971cd7 | ||
|
|
3df718c1a6 | ||
|
|
3e52e265ce | ||
|
|
abf48eb86f | ||
|
|
56ad833ab7 | ||
|
|
8afd986790 | ||
|
|
918afbd33e | ||
|
|
b5cb8fadf0 | ||
|
|
1a16bdeac8 | ||
|
|
5e749eb50b | ||
|
|
836e7733da | ||
|
|
8b19c3424c | ||
|
|
7eaf67fb6a | ||
|
|
753d7db65f | ||
|
|
f0fe5ff017 | ||
|
|
225d7a8c2d | ||
|
|
46ad19d2e3 | ||
|
|
2603b6ea03 | ||
|
|
f7156b9490 | ||
|
|
f1f8e8438a | ||
|
|
6bd1e6b8fb | ||
|
|
ae21996947 | ||
|
|
8479c4c874 | ||
|
|
4c8fc93fec | ||
|
|
38bb8d3505 | ||
|
|
850542dd25 | ||
|
|
aaad020b0b | ||
|
|
ba320a08e3 | ||
|
|
42fd32731a | ||
|
|
8fa434272e | ||
|
|
fd2e552cfb | ||
|
|
13bf0686ef | ||
|
|
1a9e306c78 | ||
|
|
565335ea0d | ||
|
|
aabdffabc2 | ||
|
|
85792b8293 | ||
|
|
c4c13b6f53 | ||
|
|
d597fd56e9 | ||
|
|
94a7a59cc9 | ||
|
|
f6f93469fb | ||
|
|
120241b069 | ||
|
|
856d9cbe53 | ||
|
|
a8331d7335 | ||
|
|
dc1f9450c0 | ||
|
|
7a7ee554c7 | ||
|
|
aadb887b34 | ||
|
|
69ae4c4e96 | ||
|
|
f4ac0ab119 | ||
|
|
8d4cc05021 | ||
|
|
16d6c92722 | ||
|
|
c7047c4b33 | ||
|
|
e22bf8fe0a | ||
|
|
e994fca2b5 | ||
|
|
c599f6423e | ||
|
|
458b7211df | ||
|
|
703e3c2b68 | ||
|
|
0eb973b6db | ||
|
|
cbcc057222 | ||
|
|
d64de2bbdb | ||
|
|
1f0b52a012 | ||
|
|
908f8b242a | ||
|
|
9faea276d8 | ||
|
|
5a42d78e06 | ||
|
|
546e8aa77c | ||
|
|
ed01d40ba9 | ||
|
|
97e6f88b31 | ||
|
|
718102f743 | ||
|
|
8cc52983b7 | ||
|
|
b896923fd4 | ||
|
|
4abcbdf452 | ||
|
|
6706de0103 | ||
|
|
cc534fd19c | ||
|
|
65dd5f1da8 | ||
|
|
76dbcfe700 | ||
|
|
7944979d56 | ||
|
|
7f6ab59250 | ||
|
|
746f65a979 | ||
|
|
9188251780 | ||
|
|
1e995b659d | ||
|
|
e560993b44 | ||
|
|
eec476b9ba | ||
|
|
3f96a965b9 | ||
|
|
ce63f697ed | ||
|
|
92f5b2a9dd | ||
|
|
5f103df04d | ||
|
|
7cbcbe12f0 | ||
|
|
c12fff16d3 | ||
|
|
e40569844f | ||
|
|
3ac7598e9b | ||
|
|
fd847d5a25 | ||
|
|
6fec245d2f | ||
|
|
9e5cb95e1f | ||
|
|
13bc9ae56c | ||
|
|
e79b4e25db | ||
|
|
f76093a0c7 | ||
|
|
45b248b4ed | ||
|
|
97c04a7f26 | ||
|
|
9ff58c32e7 | ||
|
|
0b2b26fd11 | ||
|
|
6f18de6a94 | ||
|
|
28c6ea96b4 | ||
|
|
206bf209af | ||
|
|
e83f3eb25e | ||
|
|
e16d4accb3 | ||
|
|
9ff4060b10 | ||
|
|
4ac434c83c | ||
|
|
913168df2d | ||
|
|
f8c99f96bc | ||
|
|
466ecd5ba5 | ||
|
|
7a0a354d22 | ||
|
|
349253e196 | ||
|
|
dd85e699e2 | ||
|
|
c647840485 | ||
|
|
3375282252 | ||
|
|
82d3af48c3 | ||
|
|
bebb751b3c | ||
|
|
08fbd82ead | ||
|
|
89dd426403 | ||
|
|
3206d04f0e | ||
|
|
ee0d3e43e0 | ||
|
|
f113963d31 | ||
|
|
7d48703986 | ||
|
|
f06e117d66 | ||
|
|
5fca5fdabf | ||
|
|
2bd080799f | ||
|
|
1577825585 | ||
|
|
9b7ba606d8 | ||
|
|
c9d8ce57a7 | ||
|
|
2bb904775f | ||
|
|
66826288d6 | ||
|
|
59c41c97af | ||
|
|
47d8ef4358 | ||
|
|
25b49cba01 | ||
|
|
788887a2b8 | ||
|
|
4057e3be07 | ||
|
|
284a4ee1ac | ||
|
|
b27e378cfa | ||
|
|
459726f9af | ||
|
|
4f00e405c3 | ||
|
|
87f4d816e6 | ||
|
|
ea7ebe1ff5 | ||
|
|
89899432ba | ||
|
|
3a1c211746 | ||
|
|
c3664e2b16 | ||
|
|
ea1353bd6c | ||
|
|
4a5d4d6e49 | ||
|
|
c85abdba86 | ||
|
|
57aa4c30bf | ||
|
|
67b7941129 | ||
|
|
db01b0063c | ||
|
|
e1ddc8154f | ||
|
|
e637c156a2 | ||
|
|
60ad8a809a | ||
|
|
84ac401886 | ||
|
|
26b875f64c | ||
|
|
fdc8abfdbe | ||
|
|
fc641092f7 | ||
|
|
63d360053b | ||
|
|
dc440d5a8f | ||
|
|
5ab0d18055 | ||
|
|
437b800d8c | ||
|
|
b840babb55 | ||
|
|
725d4a3fba | ||
|
|
4ab8ac8d3f | ||
|
|
73b279b5c1 | ||
|
|
fa681fb8c6 | ||
|
|
cedcfbe330 | ||
|
|
abd3ba39b1 | ||
|
|
d66d2118b5 | ||
|
|
0a92a99223 | ||
|
|
19e5e62098 | ||
|
|
d948e37388 | ||
|
|
60de81633e | ||
|
|
c02139c045 | ||
|
|
93bd527984 | ||
|
|
157d02b55c | ||
|
|
82d28b3167 | ||
|
|
717c2836ec | ||
|
|
cf8fa0e5f8 | ||
|
|
84ef0a92da | ||
|
|
2ae000df43 | ||
|
|
738a187f68 | ||
|
|
4ff057ac3b | ||
|
|
0d49d7612f | ||
|
|
342b81f65e | ||
|
|
a651f34f67 | ||
|
|
5475dc98dc | ||
|
|
3692ba2293 | ||
|
|
266efa041c | ||
|
|
ebb2f7346d | ||
|
|
f955e5fabc | ||
|
|
65c803a110 | ||
|
|
8b1b3b0396 | ||
|
|
bf28d1bd85 | ||
|
|
45edf58f9e | ||
|
|
d07e8bd3a0 | ||
|
|
7feaa748a4 | ||
|
|
c159638498 | ||
|
|
5aa385094b | ||
|
|
1cd20176c6 | ||
|
|
06891e99e1 | ||
|
|
d5f38a6a24 | ||
|
|
68d23a5f33 | ||
|
|
75f92f6f14 | ||
|
|
6c70ee6b77 | ||
|
|
c8ae3cb61c | ||
|
|
dd4d3e35f3 | ||
|
|
7b2619e757 | ||
|
|
a7b9a27c51 | ||
|
|
fcfd6e9028 | ||
|
|
9011f71247 | ||
|
|
069bce217d | ||
|
|
5a91340671 | ||
|
|
ba2e3cb468 | ||
|
|
f633be4ba1 | ||
|
|
4074fcfcc7 | ||
|
|
18cdf4956e | ||
|
|
18e06a78a3 | ||
|
|
065ca71876 | ||
|
|
859a1d6184 | ||
|
|
f2ea4e91db | ||
|
|
1add9a9752 | ||
|
|
17c3f82f50 | ||
|
|
52a3d6ba23 | ||
|
|
54007a9ce1 | ||
|
|
77d8a46039 | ||
|
|
f6e695a21d | ||
|
|
3184334535 | ||
|
|
12e3923af1 | ||
|
|
b81e858ca0 | ||
|
|
82f300e534 | ||
|
|
9df1cfd110 | ||
|
|
373fe467d6 | ||
|
|
81eb6b128f | ||
|
|
c7ee12eff7 | ||
|
|
89330daa52 | ||
|
|
e408bd17d8 | ||
|
|
99ddc5e13c | ||
|
|
4c0cc84c2d | ||
|
|
4762f8bb36 | ||
|
|
7e6f71912c | ||
|
|
6b311941b1 | ||
|
|
5facc24ebb | ||
|
|
018ae03f8e | ||
|
|
52aef76b63 | ||
|
|
2fa5ca767f | ||
|
|
a1b76f9e06 | ||
|
|
2d19cab2b5 | ||
|
|
a551fbf443 | ||
|
|
c6e220a531 | ||
|
|
600d1b84b6 | ||
|
|
5629cfe6ff | ||
|
|
5d9b9edfe1 | ||
|
|
449c243a36 | ||
|
|
6ca4986bc2 | ||
|
|
063877d49c | ||
|
|
2f4d0c4588 | ||
|
|
0a544dc0d2 | ||
|
|
d64274474b | ||
|
|
e66dfacab8 | ||
|
|
0d4c6e592e | ||
|
|
5d7fdeae5a | ||
|
|
378c6785ea | ||
|
|
6d392f0a87 | ||
|
|
7c81c37e1f | ||
|
|
3f876978a1 | ||
|
|
a0ed1bfd33 | ||
|
|
be41d2dd03 | ||
|
|
e6c3a8d07a | ||
|
|
5e41ca7e4e | ||
|
|
0f942c014c | ||
|
|
40bebda712 | ||
|
|
37fd4c18b0 | ||
|
|
d5a41bd11b | ||
|
|
c22fc202a9 | ||
|
|
a0f14d816a | ||
|
|
ad33dfcfbf | ||
|
|
840fa3b5da | ||
|
|
397a008237 | ||
|
|
f7559d4c76 | ||
|
|
8cd71ac832 | ||
|
|
0ffd25bc74 | ||
|
|
ff7f9073fc | ||
|
|
93616775f6 | ||
|
|
81751625e0 | ||
|
|
9798f9f9fa | ||
|
|
db165581ea | ||
|
|
b4e851aa49 | ||
|
|
0169e340dc | ||
|
|
1d5d1aea68 | ||
|
|
0c333b6e22 | ||
|
|
6a24d835d3 | ||
|
|
3382280cc3 | ||
|
|
60fa8a630f | ||
|
|
9ba64c2426 | ||
|
|
29b5b99b89 | ||
|
|
725d38ea06 | ||
|
|
6509f7ed40 | ||
|
|
67bdc740bd | ||
|
|
1e2b454c4c | ||
|
|
a77f9d3f6a | ||
|
|
229bd98b9c | ||
|
|
692eac43a9 | ||
|
|
4f398a3457 | ||
|
|
44c13e5bff | ||
|
|
7b2393f2cd | ||
|
|
67dfdc1bbb | ||
|
|
cc8ed5ccb5 | ||
|
|
441823d5f4 | ||
|
|
1e5ee4b292 | ||
|
|
159a34bdf2 | ||
|
|
e936d6b42d | ||
|
|
cc567f2555 | ||
|
|
b3763ad08e | ||
|
|
c824b42757 | ||
|
|
d3862c0424 | ||
|
|
f6cb77a489 | ||
|
|
a1faa88579 | ||
|
|
43ff278748 | ||
|
|
5ed44b94bc | ||
|
|
e683df3494 | ||
|
|
9f0bd4944b | ||
|
|
3fab2db88d | ||
|
|
5f013b6ee7 | ||
|
|
734d911416 | ||
|
|
86bde428bf | ||
|
|
c5045dbe7a | ||
|
|
b0d73f3126 | ||
|
|
9e2eb6c599 | ||
|
|
3bf73e9f66 | ||
|
|
9bd26a5a1b | ||
|
|
84f5a91f7b | ||
|
|
c9ae697a44 | ||
|
|
e76cda27dc | ||
|
|
2618c9fa1e | ||
|
|
522e4be817 | ||
|
|
ff8b9e5cb8 | ||
|
|
38c9ec29f5 | ||
|
|
3b0cf1fb0b | ||
|
|
dc4f10ecb0 | ||
|
|
012ed8133f | ||
|
|
d0314e0db8 | ||
|
|
850db8f2e9 | ||
|
|
44ec63dbe2 | ||
|
|
e9afb04b1e | ||
|
|
72216beacb | ||
|
|
6500a97f88 | ||
|
|
3c71a6deea | ||
|
|
e4421c509c | ||
|
|
c8339db68b | ||
|
|
961b3a9cad | ||
|
|
efa8f0e69d | ||
|
|
93928a791a | ||
|
|
f649d9e19e | ||
|
|
31350672c7 | ||
|
|
17906dc505 | ||
|
|
f8f586a98c | ||
|
|
302fc69f3a | ||
|
|
0045592891 | ||
|
|
69105e6f80 | ||
|
|
aff924a72b | ||
|
|
abaa14db83 | ||
|
|
9b113fb548 | ||
|
|
ac214e6760 | ||
|
|
d3c289a320 | ||
|
|
c64e9f947b | ||
|
|
7a790c1f23 | ||
|
|
bc9190a1dc | ||
|
|
a9feac1339 | ||
|
|
846939d632 | ||
|
|
ba68e3b02d | ||
|
|
59f98ae1fd | ||
|
|
590158ca3e | ||
|
|
7d7724c3aa | ||
|
|
76a065af6d | ||
|
|
2976e81a95 | ||
|
|
fb547c1a15 | ||
|
|
38ce06d263 | ||
|
|
3794e7e801 | ||
|
|
557ad3d3d3 | ||
|
|
70a35afad8 | ||
|
|
4a5713502f | ||
|
|
c3cc998fc1 | ||
|
|
0f0f33d0d1 | ||
|
|
0b92c856ae | ||
|
|
6e2e1f4889 | ||
|
|
0dd17a9a16 | ||
|
|
4100b0627f | ||
|
|
c50cfd937e | ||
|
|
3d7170f1bc | ||
|
|
2c5a86479a | ||
|
|
119f226610 | ||
|
|
d2db26d570 | ||
|
|
82ed41b700 | ||
|
|
639eadbad2 | ||
|
|
4ff3221feb | ||
|
|
a61a769da9 | ||
|
|
04bdafd448 | ||
|
|
5fa5e62d0e | ||
|
|
1d5f05351a | ||
|
|
05da03ab1a | ||
|
|
7b63ddf542 | ||
|
|
13860219be | ||
|
|
4cbf442cc8 | ||
|
|
2bde3e11bc | ||
|
|
5ab7bfb229 | ||
|
|
520766a74e | ||
|
|
6c16a9a4e5 | ||
|
|
726022d5a5 | ||
|
|
4a4ff9950c | ||
|
|
afc578db7f | ||
|
|
df3bd46346 | ||
|
|
08ec50f44b | ||
|
|
156ed53588 | ||
|
|
f9cfadce78 | ||
|
|
2269a82479 | ||
|
|
8330469ac3 | ||
|
|
72f56a1b03 | ||
|
|
cbd05c9037 | ||
|
|
a27c34e635 | ||
|
|
35019f7a36 | ||
|
|
69e4706549 | ||
|
|
65bd4d90c2 | ||
|
|
7343912ac3 | ||
|
|
409bd3bb26 | ||
|
|
fed4833764 | ||
|
|
e3cc15707a | ||
|
|
5302b98a15 | ||
|
|
ef019bb9da | ||
|
|
35e60f2b97 | ||
|
|
2e2b79a3a9 | ||
|
|
7bd1992e61 | ||
|
|
f8728bbed8 | ||
|
|
f774aa7c07 | ||
|
|
7a9b8093ed | ||
|
|
c7df15faf5 | ||
|
|
f5ebf0de4d | ||
|
|
cd16e921fe | ||
|
|
8b8e480391 | ||
|
|
3074b61cb7 | ||
|
|
d91e6c2db6 | ||
|
|
a0bfbafd9c | ||
|
|
4e4699ebed | ||
|
|
6295f4609e | ||
|
|
e430b4ebd7 | ||
|
|
4ff8928dc4 | ||
|
|
10596e17bf | ||
|
|
392e9e447d | ||
|
|
e8f1e76958 | ||
|
|
131f414a75 | ||
|
|
d4cefc984f | ||
|
|
2dce8d533e | ||
|
|
dc43607921 | ||
|
|
0ba3dff901 | ||
|
|
fcf8ac43b7 | ||
|
|
9b4d76ca37 | ||
|
|
9b663e3bcc | ||
|
|
847386860f | ||
|
|
8a42c11624 | ||
|
|
e4c5cc3451 | ||
|
|
79d4db7827 | ||
|
|
b1770e89b7 | ||
|
|
12d656d3a1 | ||
|
|
0bc49460d7 | ||
|
|
2743ded335 | ||
|
|
e129df15db | ||
|
|
c4c0b1ce90 | ||
|
|
9ac8c0703d | ||
|
|
433ed36a4b | ||
|
|
c23b93d71b | ||
|
|
b8bc8273a9 | ||
|
|
bcb70855d5 | ||
|
|
eaf8dc239a | ||
|
|
6864e6b2fb | ||
|
|
4b21704258 | ||
|
|
a71eb3d662 | ||
|
|
dffe56f8a9 | ||
|
|
4871304c60 | ||
|
|
a6f9b1c4b7 | ||
|
|
cbac0e7286 | ||
|
|
997d6cb677 | ||
|
|
51230834c8 | ||
|
|
638e586dbc | ||
|
|
6dc4d50e00 | ||
|
|
5d50e396c1 | ||
|
|
981d42aed6 | ||
|
|
8ffceb49c8 | ||
|
|
b14ef2112c | ||
|
|
2d31ed4618 | ||
|
|
5e7b604ecd | ||
|
|
90ec3c188b | ||
|
|
1625bc83f8 | ||
|
|
be9740b5f6 | ||
|
|
f914fe73ff | ||
|
|
57b07515c7 | ||
|
|
9d03c1ae61 | ||
|
|
3014ddb00a | ||
|
|
85b2e113b2 | ||
|
|
c5a0598cea | ||
|
|
5242fe10f6 | ||
|
|
71880a9b8e | ||
|
|
14fb1945be | ||
|
|
33cdf6f270 | ||
|
|
ca079cab17 | ||
|
|
0873474a17 | ||
|
|
bfe2450da5 | ||
|
|
19b0b6af3e | ||
|
|
cdf480ef1f | ||
|
|
da3059f0a8 | ||
|
|
754ced7b5e | ||
|
|
fb81ec6792 | ||
|
|
1be868c4b0 | ||
|
|
4dda8d7650 | ||
|
|
16fe4331f2 | ||
|
|
5ff2ad9e71 | ||
|
|
f5259af512 | ||
|
|
2dd2d2db35 | ||
|
|
9fd3e822e5 | ||
|
|
edbfc7749c | ||
|
|
2aa7e3c79f | ||
|
|
3592db997a | ||
|
|
4307f6a680 | ||
|
|
b7b83a965b | ||
|
|
fcfecc5a73 | ||
|
|
39a76ff929 | ||
|
|
aef2d087ae | ||
|
|
0b12e89e62 | ||
|
|
0379947ab1 | ||
|
|
2e5cf546c6 | ||
|
|
0c011b970b | ||
|
|
a08a86cc76 | ||
|
|
29a21302a2 | ||
|
|
13c804d1cc | ||
|
|
811d287bd9 | ||
|
|
1818534513 | ||
|
|
8d316dc969 | ||
|
|
38e7e649c7 | ||
|
|
3df9e8e5c1 | ||
|
|
c98d918bf6 | ||
|
|
c197e2f520 | ||
|
|
13b3f1d741 | ||
|
|
ad011a0974 | ||
|
|
a89dad2554 | ||
|
|
4f4553f4f0 | ||
|
|
9b505bb34b | ||
|
|
6c841bf96e | ||
|
|
76b05369ff | ||
|
|
e79b6a5622 | ||
|
|
13e1f4d7c2 | ||
|
|
8aaf1af9f0 | ||
|
|
3b10e1df41 | ||
|
|
6caa27cb20 | ||
|
|
6ca3bb051a | ||
|
|
901d010ab3 | ||
|
|
3c4ff5b26e | ||
|
|
2ade133b50 | ||
|
|
c57e76be52 | ||
|
|
9531a7f8fc | ||
|
|
9e3eebf4c2 | ||
|
|
1221cb703a | ||
|
|
59b40de83e | ||
|
|
0ac435744a | ||
|
|
589e53b231 | ||
|
|
125f112fb7 | ||
|
|
c6aa323cd8 | ||
|
|
1c7b618a89 | ||
|
|
d3ad7acd59 | ||
|
|
82b4d90a82 | ||
|
|
2a3318ef9a | ||
|
|
f2c46784a6 | ||
|
|
9340fdc7c2 | ||
|
|
b0f7493765 | ||
|
|
30234fde62 | ||
|
|
fdbcb07452 | ||
|
|
dced16bdce | ||
|
|
849be02906 | ||
|
|
b3f5b892a6 | ||
|
|
65efc413fe | ||
|
|
f3b8b7221c | ||
|
|
f04a02731d | ||
|
|
6add38e3e5 | ||
|
|
202b3e5620 | ||
|
|
49cce0aa8a | ||
|
|
ccf3486827 | ||
|
|
cb93979a44 | ||
|
|
628ac58535 | ||
|
|
373f95a6cb | ||
|
|
f2859ff8bf | ||
|
|
e2b412afc8 | ||
|
|
040e5d9d87 | ||
|
|
189430c1fe | ||
|
|
3d77a8da86 | ||
|
|
c40256600a | ||
|
|
b617f432c0 | ||
|
|
72ef13f4fb | ||
|
|
535f44c463 | ||
|
|
4c10899a3c | ||
|
|
524ee1d098 | ||
|
|
973b679baa | ||
|
|
0321c79c2d | ||
|
|
e82a03615f | ||
|
|
51c9071b3d | ||
|
|
91e5f838d3 | ||
|
|
d026232cbf | ||
|
|
c2e4aaf51d | ||
|
|
05b81df614 | ||
|
|
3e4b04d4d1 | ||
|
|
56cdaabd9c | ||
|
|
c65a19c50f | ||
|
|
5247a1537c | ||
|
|
58f970701f | ||
|
|
980f5247f0 | ||
|
|
d70032c483 | ||
|
|
14321e411c | ||
|
|
d3d2ad1b91 | ||
|
|
55f3c2f510 | ||
|
|
ffa183821c | ||
|
|
327911d057 | ||
|
|
c6657b7063 | ||
|
|
2a5626efea | ||
|
|
6bf346ccf5 | ||
|
|
1036dd4d6e | ||
|
|
48f14c7a8c | ||
|
|
2789444acd | ||
|
|
8f8b273424 | ||
|
|
37f0a0bb9a | ||
|
|
d2dd18b3e5 | ||
|
|
422e0ae85a | ||
|
|
8f562d3e11 | ||
|
|
a702fe6bc9 | ||
|
|
0ed9367b26 | ||
|
|
eda403bd31 | ||
|
|
c553d2d69e | ||
|
|
5243db7fbc | ||
|
|
4ced8c78e7 | ||
|
|
c38d903f4d | ||
|
|
1239c14e6d | ||
|
|
5004994344 | ||
|
|
c86581dedc | ||
|
|
546bba17fb | ||
|
|
27b65c9a80 | ||
|
|
1bfba945d3 | ||
|
|
4c73456f86 | ||
|
|
84940af3dc | ||
|
|
e0786537db | ||
|
|
496c2ae359 | ||
|
|
5b7c58faf4 | ||
|
|
0658808028 | ||
|
|
fb6ea57d74 | ||
|
|
0879311646 | ||
|
|
2f2cccacf9 | ||
|
|
e5d10ed8c1 | ||
|
|
070ee2c796 | ||
|
|
9a9406a69d | ||
|
|
b2eafd4a13 | ||
|
|
36892fee55 | ||
|
|
49a66e197b | ||
|
|
80ec31f588 | ||
|
|
c26ed6c280 | ||
|
|
eb98541923 | ||
|
|
895964de16 | ||
|
|
927fc21f00 | ||
|
|
a15f731042 | ||
|
|
3000cd3c7f | ||
|
|
2011776cbe | ||
|
|
33a039717c | ||
|
|
a20d543bcf | ||
|
|
55445dcc7c | ||
|
|
34a4fa6444 | ||
|
|
dba7f1b2dc | ||
|
|
180c8975ac | ||
|
|
11a6d53d8a | ||
|
|
42987dd849 | ||
|
|
7ffc332327 | ||
|
|
a9fcf1b9c1 | ||
|
|
c0c6b34869 | ||
|
|
dd55175978 | ||
|
|
58293befc9 | ||
|
|
458e1e2675 | ||
|
|
6f0d45eedb | ||
|
|
fe225fe452 | ||
|
|
78b9c543a3 | ||
|
|
86de843bda | ||
|
|
20dcab75c7 | ||
|
|
23cbf13af0 | ||
|
|
6da7d47394 | ||
|
|
fcb037bdf0 | ||
|
|
df0ae43c5f | ||
|
|
fc59b45493 | ||
|
|
a22113faa5 | ||
|
|
d1a32d1950 | ||
|
|
e150ca6864 | ||
|
|
9d7e27ced1 | ||
|
|
df7ba20ff2 | ||
|
|
8dc0168841 |
No files matched your search
+93
-76
@@ -1,3 +1,5 @@
|
||||
# https://github.com/actions/runner-images/blob/main/images/macos/macos-12-Readme.md
|
||||
|
||||
name: "GRDB CI"
|
||||
|
||||
on:
|
||||
@@ -5,18 +7,21 @@ on:
|
||||
branches:
|
||||
- master
|
||||
- development
|
||||
- GRDB5
|
||||
paths:
|
||||
- 'GRDB/**'
|
||||
- 'Tests/**'
|
||||
- '.github/workflows/**'
|
||||
- 'Makefile'
|
||||
- 'Package.swift'
|
||||
- 'SQLiteCustom/src'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'GRDB/**'
|
||||
- 'Tests/**'
|
||||
- '.github/workflows/**'
|
||||
- 'Makefile'
|
||||
- 'Package.swift'
|
||||
- 'SQLiteCustom/src'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.ref_name }}
|
||||
@@ -25,148 +30,160 @@ permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
macOS:
|
||||
name: macOS
|
||||
Framework:
|
||||
name: Framework
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
env:
|
||||
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
- xcode: "Xcode_14.3.1.app"
|
||||
runsOn: macOS-13
|
||||
destination: "platform=macOS"
|
||||
name: "macOS"
|
||||
- xcode: "Xcode_14.3.1.app"
|
||||
runsOn: macOS-13
|
||||
destination: "OS=16.4,name=iPhone 14 Pro"
|
||||
name: "iOS"
|
||||
- xcode: "Xcode_14.3.1.app"
|
||||
runsOn: macOS-13
|
||||
destination: "OS=16.4,name=Apple TV"
|
||||
name: "tvOS"
|
||||
- xcode: "Xcode_14.2.app"
|
||||
runsOn: macOS-13
|
||||
destination: "platform=macOS"
|
||||
name: "macOS"
|
||||
- xcode: "Xcode_14.2.app"
|
||||
runsOn: macOS-13
|
||||
destination: "OS=16.2,name=iPhone 14"
|
||||
name: "iOS"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-13
|
||||
destination: "platform=macOS"
|
||||
name: "macOS"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-13
|
||||
destination: "OS=16.1,name=iPhone 14"
|
||||
name: "iOS"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_13.2.1.app"
|
||||
runsOn: macOS-11
|
||||
name: "macOS 11, Xcode 13.2.1, Swift 5.5.2"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_13.1.app"
|
||||
runsOn: macOS-11
|
||||
name: "macOS 11, Xcode 13.1, Swift 5.5.1"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_13.0.app"
|
||||
runsOn: macOS-11
|
||||
name: "macOS 11, Xcode 13.0, Swift 5.5.0"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.5.1.app"
|
||||
runsOn: macOS-11
|
||||
name: "macOS 11, Xcode 12.5.1, Swift 5.4"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.4.app"
|
||||
runsOn: macOS-10.15
|
||||
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_GRDBOSX_maxSwift
|
||||
iOS:
|
||||
name: iOS
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
destination: "platform=macOS"
|
||||
name: "macOS"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.4.app"
|
||||
runsOn: macOS-10.15
|
||||
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
|
||||
shell: "/bin/zsh {0}"
|
||||
destination: "OS=16.0,name=iPhone 14"
|
||||
name: "iOS"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project GRDB.xcodeproj -scheme GRDB -destination "${{ matrix.destination }}" OTHER_SWIFT_FLAGS='$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' GCC_PREPROCESSOR_DEFINITIONS='$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' clean test
|
||||
SPM:
|
||||
name: SPM
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
env:
|
||||
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
- xcode: "Xcode_14.3.1.app"
|
||||
runsOn: macOS-13
|
||||
name: "Xcode 14.3.1"
|
||||
- xcode: "Xcode_14.2.app"
|
||||
runsOn: macOS-13
|
||||
name: "Xcode 14.2"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-13
|
||||
name: "Xcode 14.1"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
name: "Xcode 14.0.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_SPM test_install_SPM
|
||||
SQLCipher3:
|
||||
name: SQLCipher3
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
env:
|
||||
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
- xcode: "Xcode_14.3.1.app"
|
||||
runsOn: macOS-13
|
||||
name: "Xcode 14.3.1"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
name: "Xcode 14.0.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_SQLCipher3Encrypted
|
||||
SQLCipher4:
|
||||
name: SQLCipher4
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
env:
|
||||
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
- xcode: "Xcode_14.3.1.app"
|
||||
runsOn: macOS-13
|
||||
name: "Xcode 14.3.1"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.4.app"
|
||||
runsOn: macOS-10.15
|
||||
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
|
||||
shell: "/bin/zsh {0}"
|
||||
name: "Xcode 14.0.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_SQLCipher4Encrypted
|
||||
CustomSQLite:
|
||||
name: CustomSQLite
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
env:
|
||||
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
- xcode: "Xcode_14.3.1.app"
|
||||
runsOn: macOS-13
|
||||
name: "Xcode 14.3.1"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.4.app"
|
||||
runsOn: macOS-10.15
|
||||
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
|
||||
shell: "/bin/zsh {0}"
|
||||
name: "Xcode 14.0.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_GRDBCustomSQLiteOSX
|
||||
XCFramework:
|
||||
name: XCFramework
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
env:
|
||||
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
- xcode: "Xcode_14.3.1.app"
|
||||
runsOn: macOS-13
|
||||
name: "Xcode 14.3.1"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
name: "Xcode 14.0.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_archive_GRDBOSX_xcframework
|
||||
run: make test_universal_xcframework
|
||||
|
||||
+1
-2
@@ -1,4 +1,4 @@
|
||||
## https://github.com/github/gitignore/blob/master/Global/OSX.gitignore
|
||||
## https://github.com/github/gitignore/blob/master/Global/macOS.gitignore
|
||||
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
@@ -106,7 +106,6 @@ Podfile.lock
|
||||
|
||||
# SPM
|
||||
.build
|
||||
.swiftpm/
|
||||
GRDB.xcworkspace/xcshareddata/swiftpm
|
||||
#Package.resolved
|
||||
Tests/SPM/Packages
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
<FileRef
|
||||
location = "self:">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
@@ -0,0 +1,134 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1410"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "GRDB_GRDBTests"
|
||||
BuildableName = "GRDB_GRDBTests"
|
||||
BlueprintName = "GRDB_GRDBTests"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "GRDB"
|
||||
BuildableName = "GRDB"
|
||||
BlueprintName = "GRDB"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "GRDB-dynamic"
|
||||
BuildableName = "GRDB-dynamic"
|
||||
BlueprintName = "GRDB-dynamic"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "GRDBTests"
|
||||
BuildableName = "GRDBTests"
|
||||
BlueprintName = "GRDBTests"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "CSQLite"
|
||||
BuildableName = "CSQLite"
|
||||
BlueprintName = "CSQLite"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO"
|
||||
parallelizable = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "GRDBTests"
|
||||
BuildableName = "GRDBTests"
|
||||
BlueprintName = "GRDBTests"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "GRDB_GRDBTests"
|
||||
BuildableName = "GRDB_GRDBTests"
|
||||
BlueprintName = "GRDB_GRDBTests"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -4,6 +4,46 @@ Here is a list of people who were happy to meet GRDB :-)
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/DamienPetrilli/status/1623922310976786433
|
||||
|
||||
> I can't overstate how much more productive I am since I ditched the obsolete Core Data framework and started to use GRDB instead.
|
||||
>
|
||||
> The hard stuff is doable, and the simple stuff is even simpler, as it should be.
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/fullqueuedev/status/1603350969357684736
|
||||
|
||||
> Yes, I much prefer GRDB. I’ve tested many SQLite wrappers over the years 💜
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/cassiuspacheco/status/1574948903857770497
|
||||
|
||||
> SQLite using @groue’s GRDB, no brainer! Awesome documentation, support and beautifully designed.
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/simrandotdev/status/1552004471122587649
|
||||
|
||||
> We get Core Data from Apple which is the worst library to deal with.
|
||||
> Then there is Realm which is nice but again you do not get the RAW SQL power as it is its own type of Db.
|
||||
> Then comes the most beautiful library every written which is very close to Room called GRDB.
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/bellebcooper/status/1534070340850094080
|
||||
|
||||
> When I first started using GRDB I didn't know SQL or much at all about databases 😬 So I've always really liked the query API. But these days I really appreciate that you support raw SQL too, because it gives me more control and freedom when I need it. 👍👍👍
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/mikeash/status/1504810545429499909
|
||||
|
||||
> Another cool library using SQL interpolation!
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/swiftkarim/status/1354753451377483781
|
||||
|
||||
> I cannot recommend GRDB enough. It works well with Swift and eliminates whole classes of potential programming errors that can be made with Core Data. Also being able to use raw SQL queries if needed can be extremely useful!
|
||||
|
||||
+488
-27
@@ -5,13 +5,47 @@ All notable changes to this project will be documented in this file.
|
||||
|
||||
GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library.
|
||||
|
||||
#### 6.x Releases
|
||||
|
||||
- `6.29.x` Releases - [6.29.0](#6290) - [6.29.1](#6291) - [6.29.2](#6292) - [6.29.3](#6293)
|
||||
- `6.28.x` Releases - [6.28.0](#6280)
|
||||
- `6.27.x` Releases - [6.27.0](#6270)
|
||||
- `6.26.x` Releases - [6.26.0](#6260)
|
||||
- `6.25.x` Releases - [6.25.0](#6250)
|
||||
- `6.24.x` Releases - [6.24.0](#6240) - [6.24.1](#6241) - [6.24.2](#6242)
|
||||
- `6.23.x` Releases - [6.23.0](#6230)
|
||||
- `6.22.x` Releases - [6.22.0](#6220)
|
||||
- `6.21.x` Releases - [6.21.0](#6210)
|
||||
- `6.20.x` Releases - [6.20.0](#6200) - [6.20.1](#6201) - [6.20.2](#6202)
|
||||
- `6.19.x` Releases - [6.19.0](#6190)
|
||||
- `6.18.x` Releases - [6.18.0](#6180)
|
||||
- `6.17.x` Releases - [6.17.0](#6170)
|
||||
- `6.16.x` Releases - [6.16.0](#6160)
|
||||
- `6.15.x` Releases - [6.15.0](#6150) - [6.15.1](#6151)
|
||||
- `6.14.x` Releases - [6.14.0](#6140)
|
||||
- `6.13.x` Releases - [6.13.0](#6130)
|
||||
- `6.12.x` Releases - [6.12.0](#6120)
|
||||
- `6.11.x` Releases - [6.11.0](#6110)
|
||||
- `6.10.x` Releases - [6.10.0](#6100) - [6.10.1](#6101) - [6.10.2](#6102)
|
||||
- `6.9.x` Releases - [6.9.0](#690) - [6.9.1](#691) - [6.9.2](#692)
|
||||
- `6.8.x` Releases - [6.8.0](#680)
|
||||
- `6.7.x` Releases - [6.7.0](#670)
|
||||
- `6.6.x` Releases - [6.6.0](#660) - [6.6.1](#661)
|
||||
- `6.5.x` Releases - [6.5.0](#650)
|
||||
- `6.4.x` Releases - [6.4.0](#640)
|
||||
- `6.3.x` Releases - [6.3.0](#630) - [6.3.1](#631)
|
||||
- `6.2.x` Releases - [6.2.0](#620)
|
||||
- `6.1.x` Releases - [6.1.0](#610)
|
||||
- `6.0.x` Releases - [6.0.0](#600)
|
||||
- `6.0.0` Betas - [6.0.0-beta](#600-beta) - [6.0.0-beta.2](#600-beta2) - [6.0.0-beta.3](#600-beta3) - [6.0.0-beta.4](#600-beta4)
|
||||
|
||||
#### 5.x Releases
|
||||
|
||||
- `5.26.x` Releases - [5.26.0](#5260) | [5.26.1](#5261)
|
||||
- `5.26.x` Releases - [5.26.0](#5260) - [5.26.1](#5261)
|
||||
- `5.25.x` Releases - [5.25.0](#5250)
|
||||
- `5.24.x` Releases - [5.24.0](#5240) | [5.24.1](#5241)
|
||||
- `5.24.x` Releases - [5.24.0](#5240) - [5.24.1](#5241)
|
||||
- `5.23.x` Releases - [5.23.0](#5230)
|
||||
- `5.22.x` Releases - [5.22.0](#5220) | [5.22.1](#5221) | [5.22.2](#5222)
|
||||
- `5.22.x` Releases - [5.22.0](#5220) - [5.22.1](#5221) - [5.22.2](#5222)
|
||||
- `5.21.x` Releases - [5.21.0](#5210)
|
||||
- `5.20.x` Releases - [5.20.0](#5200)
|
||||
- `5.19.x` Releases - [5.19.0](#5190)
|
||||
@@ -26,41 +60,41 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
- `5.10.x` Releases - [5.10.0](#5100)
|
||||
- `5.9.x` Releases - [5.9.0](#590)
|
||||
- `5.8.x` Releases - [5.8.0](#580)
|
||||
- `5.7.x` Releases - [5.7.0](#570) | [5.7.1](#571) | [5.7.2](#572) | [5.7.3](#573) | [5.7.4](#574)
|
||||
- `5.7.x` Releases - [5.7.0](#570) - [5.7.1](#571) - [5.7.2](#572) - [5.7.3](#573) - [5.7.4](#574)
|
||||
- `5.6.x` Releases - [5.6.0](#560)
|
||||
- `5.5.x` Releases - [5.5.0](#550)
|
||||
- `5.4.x` Releases - [5.4.0](#540)
|
||||
- `5.3.x` Releases - [5.3.0](#530)
|
||||
- `5.2.x` Releases - [5.2.0](#520)
|
||||
- `5.1.x` Releases - [5.1.0](#510)
|
||||
- `5.0.x` Releases - [5.0.0](#500) | [5.0.1](#501) | [5.0.2](#502) | [5.0.3](#503)
|
||||
- `5.0.0` Betas - [5.0.0-beta](#500-beta) | [5.0.0-beta.2](#500-beta2) | [5.0.0-beta.3](#500-beta3) | [5.0.0-beta.4](#500-beta4) | [5.0.0-beta.5](#500-beta5) | [5.0.0-beta.6](#500-beta6) | [5.0.0-beta.7](#500-beta7) | [5.0.0-beta.8](#500-beta8) | [5.0.0-beta.9](#500-beta9) | [5.0.0-beta.10](#500-beta10) | [5.0.0-beta.11](#500-beta11)
|
||||
- `5.0.x` Releases - [5.0.0](#500) - [5.0.1](#501) - [5.0.2](#502) - [5.0.3](#503)
|
||||
- `5.0.0` Betas - [5.0.0-beta](#500-beta) - [5.0.0-beta.2](#500-beta2) - [5.0.0-beta.3](#500-beta3) - [5.0.0-beta.4](#500-beta4) - [5.0.0-beta.5](#500-beta5) - [5.0.0-beta.6](#500-beta6) - [5.0.0-beta.7](#500-beta7) - [5.0.0-beta.8](#500-beta8) - [5.0.0-beta.9](#500-beta9) - [5.0.0-beta.10](#500-beta10) - [5.0.0-beta.11](#500-beta11)
|
||||
|
||||
#### 4.x Releases
|
||||
|
||||
- `4.14.x` Releases - [4.14.0](#4140)
|
||||
- `4.13.x` Releases - [4.13.0](#4130)
|
||||
- `4.12.x` Releases - [4.12.0](#4120) | [4.12.1](#4121) | [4.12.2](#4122)
|
||||
- `4.12.x` Releases - [4.12.0](#4120) - [4.12.1](#4121) - [4.12.2](#4122)
|
||||
- `4.11.x` Releases - [4.11.0](#4110)
|
||||
- `4.10.x` Releases - [4.10.0](#4100)
|
||||
- `4.9.x` Releases - [4.9.0](#490)
|
||||
- `4.8.x` Releases - [4.8.0](#480) | [4.8.1](#481)
|
||||
- `4.8.x` Releases - [4.8.0](#480) - [4.8.1](#481)
|
||||
- `4.7.x` Releases - [4.7.0](#470)
|
||||
- `4.6.x` Releases - [4.6.0](#460) | [4.6.1](#461) | [4.6.2](#462)
|
||||
- `4.6.x` Releases - [4.6.0](#460) - [4.6.1](#461) - [4.6.2](#462)
|
||||
- `4.5.x` Releases - [4.5.0](#450)
|
||||
- `4.4.x` Releases - [4.4.0](#440)
|
||||
- `4.3.x` Releases - [4.3.0](#430)
|
||||
- `4.2.x` Releases - [4.2.0](#420) | [4.2.1](#421)
|
||||
- `4.1.x` Releases - [4.1.0](#410) | [4.1.1](#411)
|
||||
- `4.0.x` Releases - [4.0.0](#400) | [4.0.1](#401)
|
||||
- `4.2.x` Releases - [4.2.0](#420) - [4.2.1](#421)
|
||||
- `4.1.x` Releases - [4.1.0](#410) - [4.1.1](#411)
|
||||
- `4.0.x` Releases - [4.0.0](#400) - [4.0.1](#401)
|
||||
|
||||
#### 3.x Releases
|
||||
|
||||
- `3.7.x` Releases - [3.7.0](#370)
|
||||
- `3.6.x` Releases - [3.6.0](#360) | [3.6.1](#361) | [3.6.2](#362)
|
||||
- `3.6.x` Releases - [3.6.0](#360) - [3.6.1](#361) - [3.6.2](#362)
|
||||
- `3.5.x` Releases - [3.5.0](#350)
|
||||
- `3.4.x` Releases - [3.4.0](#340)
|
||||
- `3.3.x` Releases - [3.3.0](#330) | [3.3.1](#331)
|
||||
- `3.3.x` Releases - [3.3.0](#330) - [3.3.1](#331)
|
||||
- `3.3.0` Betas - [3.3.0-beta1](#330-beta1)
|
||||
- `3.2.x` Releases - [3.2.0](#320)
|
||||
- `3.1.x` Releases - [3.1.0](#310)
|
||||
@@ -72,18 +106,18 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
- `2.9.x` Releases - [2.9.0](#290)
|
||||
- `2.8.x` Releases - [2.8.0](#280)
|
||||
- `2.7.x` Releases - [2.7.0](#270)
|
||||
- `2.6.x` Releases - [2.6.0](#260) | [2.6.1](#261)
|
||||
- `2.6.x` Releases - [2.6.0](#260) - [2.6.1](#261)
|
||||
- `2.5.x` Releases - [2.5.0](#250)
|
||||
- `2.4.x` Releases - [2.4.0](#240) | [2.4.1](#241) | [2.4.2](#242)
|
||||
- `2.3.x` Releases - [2.3.0](#230) | [2.3.1](#231)
|
||||
- `2.4.x` Releases - [2.4.0](#240) - [2.4.1](#241) - [2.4.2](#242)
|
||||
- `2.3.x` Releases - [2.3.0](#230) - [2.3.1](#231)
|
||||
- `2.2.x` Releases - [2.2.0](#220)
|
||||
- `2.1.x` Releases - [2.1.0](#210)
|
||||
- `2.0.x` Releases - [2.0.0](#200) | [2.0.1](#201) | [2.0.2](#202) | [2.0.3](#203)
|
||||
- `2.0.x` Releases - [2.0.0](#200) - [2.0.1](#201) - [2.0.2](#202) - [2.0.3](#203)
|
||||
|
||||
#### 1.x Releases
|
||||
|
||||
- `1.3.x` Releases - [1.3.0](#130)
|
||||
- `1.2.x` Releases - [1.2.0](#120) | [1.2.1](#121) | [1.2.2](#122)
|
||||
- `1.2.x` Releases - [1.2.0](#120) - [1.2.1](#121) - [1.2.2](#122)
|
||||
- `1.1.x` Releases - [1.1.0](#110)
|
||||
- `1.0.x` Releases - [1.0.0](#100)
|
||||
|
||||
@@ -93,11 +127,438 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 6.29.3
|
||||
|
||||
Released September 7, 2024
|
||||
|
||||
- **Fixed**: [#1613](https://github.com/groue/GRDB.swift/pull/1613) by [@groue](https://github.com/groue): Avoid SQLite misuse when releasing memory on a closed database connection
|
||||
|
||||
## 6.29.2
|
||||
|
||||
Released August 24, 2024
|
||||
|
||||
- **New**: [#1593](https://github.com/groue/GRDB.swift/pull/1593) by [@mingchen](https://github.com/mingchen): Fix sample code in README
|
||||
|
||||
## 6.29.1
|
||||
|
||||
Released August 7, 2024
|
||||
|
||||
- **New**: [#1579](https://github.com/groue/GRDB.swift/pull/1579) by [@groue](https://github.com/groue): Modernize the demo apps
|
||||
- **New**: [#1584](https://github.com/groue/GRDB.swift/pull/1584) by [@SagarSDagdu](https://github.com/SagarSDagdu): Update README to highlight deployment issue with CocoaPods
|
||||
- **New**: [#1589](https://github.com/groue/GRDB.swift/pull/1589) by [@groue](https://github.com/groue): Fix compilation issue with Xcode 16 beta 5 due to a missing import
|
||||
|
||||
## 6.29.0
|
||||
|
||||
Released July 20, 2024
|
||||
|
||||
- **New**: [#1574](https://github.com/groue/GRDB.swift/pull/1574) by [@sroebert](https://github.com/sroebert): Support for single value decoding (the complement of [#1570](https://github.com/groue/GRDB.swift/pull/1570) shipped in 6.28.0)
|
||||
- **New**: [#1575](https://github.com/groue/GRDB.swift/pull/1575) by [@Jason-Abbott](https://github.com/Jason-Abbott): Show comments when tracing expanded statements
|
||||
|
||||
## 6.28.0
|
||||
|
||||
Released July 11, 2024
|
||||
|
||||
- **New**: [#1570](https://github.com/groue/GRDB.swift/pull/1570) by [@groue](https://github.com/groue): Support single-value encoding
|
||||
- **New**: Added `QueryInterfaceRequest.deleteAndFetchIds(_:)` which returns the set of deleted ids.
|
||||
- **New**: Added `Set` methods `union`, `formUnion`, `intersection` and `formIntersection` that accept a cursor.
|
||||
- **New**: `DatabaseUUIDEncodingStrategy` is Sendable.
|
||||
|
||||
## 6.27.0
|
||||
|
||||
Released April 21, 2024
|
||||
|
||||
- **Fixed**: [#1533](https://github.com/groue/GRDB.swift/pull/1533) by [@groue](https://github.com/groue): Fix a bug in Decodable support
|
||||
- **Documentation Update**: [#1534](https://github.com/groue/GRDB.swift/pull/1534) The [Single-Row Tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables) guide was updated with guidance about default configuration values.
|
||||
- **Documentation Update**: [#1535](https://github.com/groue/GRDB.swift/pull/1535) The [ValueObservation Scheduling](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation#ValueObservation-Scheduling) documentation chapter explains the default behavior of `ValueObservation` fetches, and explains how to make sure they are never performed on the main thread.
|
||||
|
||||
## 6.26.0
|
||||
|
||||
Released March 23, 2024
|
||||
|
||||
- **New**: [#1503](https://github.com/groue/GRDB.swift/pull/1503) by [@simba909](https://github.com/simba909): Conform Database.ColumnType to Sendable
|
||||
- **New**: [#1510](https://github.com/groue/GRDB.swift/pull/1510) by [@groue](https://github.com/groue): Add Sendable conformances and unavailabilities
|
||||
- **New**: [#1511](https://github.com/groue/GRDB.swift/pull/1511) by [@groue](https://github.com/groue): Database schema dump
|
||||
- **New**: [#1515](https://github.com/groue/GRDB.swift/pull/1515) by [@groue](https://github.com/groue): Support for the CAST SQLite function
|
||||
- **Fixed**: [#1508](https://github.com/groue/GRDB.swift/pull/1508) by [@groue](https://github.com/groue): Fix ValueObservation mishandling of database schema modification
|
||||
- **Fixed**: [#1512](https://github.com/groue/GRDB.swift/issues/1512): Decoding errors are now correctly reported when decoding NULL into a non-optional property of type `Data` or `Date`.
|
||||
|
||||
## 6.25.0
|
||||
|
||||
Released February 25, 2024
|
||||
|
||||
- **New**: [#1496](https://github.com/groue/GRDB.swift/pull/1496) by [@danielepantaleone](https://github.com/danielepantaleone): Add privacy manifest file.
|
||||
|
||||
A `PrivacyInfo.xcprivacy` resource was added to the GRDB SPM package and Xcode projects. It declares that GRDB does not collect anything.
|
||||
|
||||
## 6.24.2
|
||||
|
||||
Released January 21, 2024
|
||||
|
||||
- **Documentation Update**: [#1485](https://github.com/groue/GRDB.swift/pull/1485) The [Sharing a Database](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing) guide was updated with a new recommendation for databases shared between multiple processes. Writers should always perform IMMEDIATE transactions in order to avoid the `SQLITE_BUSY` error that can occur when transactions overlap. The new recommendation fits in a single line of code: `configuration.defaultTransactionKind = .immediate`.
|
||||
- **New**: Associations that involve views instead of tables were already supported, with an explicit `ForeignKey` in their definition. When the foreign key is missing, a clear diagnostic message is now emitted, instead of an unhelpful "no such table" runtime error.
|
||||
|
||||
## 6.24.1
|
||||
|
||||
Released January 6, 2024
|
||||
|
||||
- **New**: [#1477](https://github.com/groue/GRDB.swift/pull/1477): Remove shadow tables from database dump
|
||||
|
||||
## 6.24.0
|
||||
|
||||
Released January 6, 2024
|
||||
|
||||
- **New**: [#1466](https://github.com/groue/GRDB.swift/pull/1466) by [@barnettben](https://github.com/barnettben): Add schema name option to database introspection methods
|
||||
|
||||
## 6.23.0
|
||||
|
||||
Released December 1, 2023
|
||||
|
||||
- **New**: [#1462](https://github.com/groue/GRDB.swift/pull/1462) Temporary read-only access
|
||||
|
||||
## 6.22.0
|
||||
|
||||
Released November 26, 2023
|
||||
|
||||
- **New**: [#1452](https://github.com/groue/GRDB.swift/pull/1452) by [@groue](https://github.com/groue): SQLite 3.44.0, FILTER and ORDER BY clauses in aggregate functions
|
||||
- **New**: [#1460](https://github.com/groue/GRDB.swift/pull/1460) by [@groue](https://github.com/groue): Explicit change notifications help applications deal with undetected database changes.
|
||||
- **Documentation Update**: The documentations of [`ValueObservation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation), [`DatabaseRegionObservation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation), and [`TransactionObserver`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver) have a new "Dealing with Undetected Changes" that documents possible strategies for notifying applications of undetected database changes.
|
||||
|
||||
## 6.21.0
|
||||
|
||||
Released October 29, 2023
|
||||
|
||||
- **New**: [#1448](https://github.com/groue/GRDB.swift/pull/1448) by [@groue](https://github.com/groue): Add support for stable ordering and dump of views
|
||||
- **New**: [#1449](https://github.com/groue/GRDB.swift/pull/1449) by [@groue](https://github.com/groue): Backport temporary copies from GRDBSnapshotTesting
|
||||
|
||||
## 6.20.2
|
||||
|
||||
Released October 15, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.20.1...v6.20.2)
|
||||
|
||||
- **Fixed**: [#1442](https://github.com/groue/GRDB.swift/pull/1442) by [@groue](https://github.com/groue): Extend the macOS availability of JSON functions
|
||||
|
||||
## 6.20.1
|
||||
|
||||
Released October 13, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.20.0...v6.20.1)
|
||||
|
||||
- **Fixed**: Removed a debug print
|
||||
|
||||
## 6.20.0
|
||||
|
||||
Released October 13, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.19.0...v6.20.0)
|
||||
|
||||
- **New**: [#1439](https://github.com/groue/GRDB.swift/pull/1439) by [@groue](https://github.com/groue): Dump requests
|
||||
- **New**: `QueryInterfaceRequest.withStableOrder()` returns a request with well-defined order, suitable for tests.
|
||||
|
||||
## 6.19.0
|
||||
|
||||
Released October 4, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.18.0...v6.19.0)
|
||||
|
||||
- **New**: [#1429](https://github.com/groue/GRDB.swift/pull/1429) by [@JhonnyBillM](https://github.com/JhonnyBillM): Allow `DatabaseValueConvertible` types to customize their database JSON format
|
||||
- **New**: [#1436](https://github.com/groue/GRDB.swift/pull/1436) by [@myyra](https://github.com/myyra) and [@groue](https://github.com/groue): JSON functions
|
||||
- **New**: `Database` has learned to create indexes on expressions, and specify specific collations on indexed columns, with the `create(index:on:expressions:options:condition:)` method.
|
||||
- **New**: Codable records can specify coding strategies for their `Data` properties. See [#1436](https://github.com/groue/GRDB.swift/pull/1436) for more information.
|
||||
- **Documentation Update**: A new [JSON Support](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/json) article provides an overview of JSON handling.
|
||||
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) now recommend that record types with an auto-incremented id avoid conforming to the `Identifiable` protocol.
|
||||
|
||||
## 6.18.0
|
||||
|
||||
Released September 1, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.17.0...v6.18.0)
|
||||
|
||||
- **New**: Expose the database path from `DatabaseReader`.
|
||||
|
||||
## 6.17.0
|
||||
|
||||
Released August 26, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.16.0...v6.17.0)
|
||||
|
||||
- **New**: [#1421](https://github.com/groue/GRDB.swift/pull/1421) by [@groue](https://github.com/groue): Make it possible to open a DatabaseQueue in the WAL mode
|
||||
|
||||
## 6.16.0
|
||||
|
||||
Released July 9, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.15.1...v6.16.0)
|
||||
|
||||
- **New**: [#1397](https://github.com/groue/GRDB.swift/pull/1397) by [@groue](https://github.com/groue): Swift API for creating database views
|
||||
- **New**: [#1401](https://github.com/groue/GRDB.swift/pull/1401) by [@kustra](https://github.com/kustra): Linux compilation fixes
|
||||
- **New**: [#1402](https://github.com/groue/GRDB.swift/pull/1402) by [@groue](https://github.com/groue): Upgrade custom SQLite builds to 3.42.0
|
||||
- **New**: [#1403](https://github.com/groue/GRDB.swift/pull/1403) by [@groue](https://github.com/groue): GitHub CI: test Xcode 14.3.1, macOS 13
|
||||
- **New**: :star: [#1405](https://github.com/groue/GRDB.swift/pull/1405) Simplify the declaration of BelongsTo associations in the database schema
|
||||
- **Documentation Update**: The documentation was updated for the new recommended way to declare associations in the database schema, with the `belongsTo()` method introduced by [#1405](https://github.com/groue/GRDB.swift/pull/1405):
|
||||
- [`belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tabledefinition/belongsto(_:intable:ondelete:onupdate:deferred:indexed:))
|
||||
- [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema)
|
||||
- [Migrations](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations)
|
||||
- [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices)
|
||||
- [Associations](Documentation/AssociationsBasics.md)
|
||||
- [`BelongsToAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/belongstoassociation)
|
||||
- [`HasManyAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/hasmanyassociation)
|
||||
- [`HasOneAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/hasoneassociation)
|
||||
|
||||
|
||||
## 6.15.1
|
||||
|
||||
Released June 17, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.15.0...v6.15.1)
|
||||
|
||||
- **Fixed**: Fixed Xcode 15 warnings
|
||||
- **Fixed**: [#1391](https://github.com/groue/GRDB.swift/pull/1391) Fix upsert in FTS5-synchronized tables
|
||||
|
||||
|
||||
## 6.15.0
|
||||
|
||||
Released June 2, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.14.0...v6.15.0)
|
||||
|
||||
- **New**: [#1382](https://github.com/groue/GRDB.swift/pull/1382) Add `DerivableRequest.all()`
|
||||
- **New**: [#1384](https://github.com/groue/GRDB.swift/pull/1384) Allow ValueObservation to start from a truncated wal file
|
||||
- **Documentation Update**: The [ValueObservation Performance](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation#ValueObservation-Performance) documentation chapter explains how truncating WAL checkpoints impact `ValueObservation`.
|
||||
|
||||
|
||||
## 6.14.0
|
||||
|
||||
Released May 25, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.13.0...v6.14.0)
|
||||
|
||||
- **New**: [#1376](https://github.com/groue/GRDB.swift/pull/1376) Bitwise operations
|
||||
- **New**: [#1379](https://github.com/groue/GRDB.swift/pull/1379) Create indexes with a default name
|
||||
|
||||
|
||||
## 6.13.0
|
||||
|
||||
Released May 15, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.12.0...v6.13.0)
|
||||
|
||||
- **New**: [#1373](https://github.com/groue/GRDB.swift/pull/1373) Deprecate string literal arguments for `TableDefinition.check()`
|
||||
|
||||
|
||||
## 6.12.0
|
||||
|
||||
Released April 29, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.11.0...v6.12.0)
|
||||
|
||||
- **Fixed**: [#1364](https://github.com/groue/GRDB.swift/pull/1364) Fix a regression introduced with version 6.10.0, where starting multiple observations while performing writes could create a deadlock.
|
||||
- **New**: `FetchableRecordDecoder` is an object that decodes `Decodable` fetchable records from database rows. You may want to use this decoder when you want to use the `Decodable` initializer from `init(row: Row)`.
|
||||
|
||||
## 6.11.0
|
||||
|
||||
Released April 17, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.10.2...v6.11.0)
|
||||
|
||||
- **New**: [#1361](https://github.com/groue/GRDB.swift/pull/1361) `DatabaseMigrator.eraseDatabaseOnSchemaChange` ignores internal schema objects
|
||||
|
||||
## 6.10.2
|
||||
|
||||
Released April 10, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.10.1...v6.10.2)
|
||||
|
||||
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) guide has moved to DocC.
|
||||
- **Documentation Update**: The [Demo Applications](Documentation/DemoApps/) demonstrate how their `AppDatabase` "database manager" can provide a base database configuration.
|
||||
|
||||
## 6.10.1
|
||||
|
||||
Released April 1, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.10.0...v6.10.1)
|
||||
|
||||
- **Fixed**: [#1357](https://github.com/groue/GRDB.swift/pull/1357) `QueryInterfaceRequest.fetchCount` no longer executes invalid SQL queries for some requests.
|
||||
|
||||
## 6.10.0
|
||||
|
||||
Released March 20, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.9.2...v6.10.0)
|
||||
|
||||
- **New**: [#1350](https://github.com/groue/GRDB.swift/pull/1350) by [@groue](https://github.com/groue): DatabasePool won't close read-only connections if requested, and ValueObservation no longer opens a new database connection when it starts.
|
||||
|
||||
## 6.9.2
|
||||
|
||||
Released March 14, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.9.1...v6.9.2)
|
||||
|
||||
- **Fixed**: [#1349](https://github.com/groue/GRDB.swift/pull/1349) by [@JonLz](https://github.com/JonLz): Fix Migrations.md example so it compiles
|
||||
- **Fixed**: Avoid the risk for pathologically deep stack trace, or stack overflow, introduced by [#1348](https://github.com/groue/GRDB.swift/pull/1348).
|
||||
|
||||
## 6.9.1
|
||||
|
||||
Released March 12, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.9.0...v6.9.1)
|
||||
|
||||
- **Documentation Updates**: Moved more README chapters into DocC:
|
||||
- [`RowAdapter`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter)
|
||||
- [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/splittingrowadapters(columncounts:))
|
||||
|
||||
## 6.9.0
|
||||
|
||||
Released March 12, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.8.0...v6.9.0)
|
||||
|
||||
- **New**: [#1348](https://github.com/groue/GRDB.swift/pull/1348) by [@groue](https://github.com/groue): SQLite argument binding optimization
|
||||
- **New**: `FTS5.api(db)` returns a pointer to the `fts5_api` structure, useful for low-level [FTS5 customization](https://www.sqlite.org/fts5.html#extending_fts5).
|
||||
- **Documentation Updates**: Moved more README chapters into DocC, enhanced and extended DocC articles:
|
||||
- [Database Connections](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections)
|
||||
- [Prepared Statements](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statement)
|
||||
- [DatabaseValueConvertible](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasevalueconvertible)
|
||||
|
||||
## 6.8.0
|
||||
|
||||
Released February 24, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.7.0...v6.8.0)
|
||||
|
||||
- **New**: [#1338](https://github.com/groue/GRDB.swift/pull/1338) by [@groue](https://github.com/groue): TimestampedRecord sample code
|
||||
- **New**: `EncodableRecord.databaseChanges(modify:)` modifies a record and returns a dictionary of applied changes.
|
||||
- **Documentation Update**: The [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordtimestamps) article provides a sample `TimestampedRecord` protocol that application may adapt for their own use.
|
||||
|
||||
## 6.7.0
|
||||
|
||||
Released February 19, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.6.1...v6.7.0)
|
||||
|
||||
- **Fixed**: [#1316](https://github.com/groue/GRDB.swift/pull/1316) and [#1320](https://github.com/groue/GRDB.swift/pull/1320) by [@baekteun](https://github.com/baekteun): Replace "OSX" with "macOS".
|
||||
- **Fixed**: [#1328](https://github.com/groue/GRDB.swift/pull/1328) by [@ytti](https://github.com/ytti): Fix documentation about Data passphrases.
|
||||
- **Fixed**: [#1327](https://github.com/groue/GRDB.swift/pull/1327) by [@groue](https://github.com/groue): Remove dependency on any specific SwiftLint version.
|
||||
- **New**: [#1331](https://github.com/groue/GRDB.swift/pull/1331) by [@groue](https://github.com/groue): Transaction Date
|
||||
- **New**: [#1336](https://github.com/groue/GRDB.swift/pull/1336) by [@groue](https://github.com/groue): Enable FTS5 by default
|
||||
- **Documentation Update**: The new [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordtimestamps) article explains how applications can save the creation and modification date of records.
|
||||
- Added support for `Table` in SQL interpolation.
|
||||
|
||||
## 6.6.1
|
||||
|
||||
Released January 15, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.6.0...v6.6.1)
|
||||
|
||||
- **Fixed**: [#1317](https://github.com/groue/GRDB.swift/pull/1317) by [@groue](https://github.com/groue): Fix handling of multiple deep prefetched associations
|
||||
|
||||
## 6.6.0
|
||||
|
||||
Released December 29, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.5.0...v6.6.0)
|
||||
|
||||
- **New**: [#1304](https://github.com/groue/GRDB.swift/pull/1304) by [@groue](https://github.com/groue): Expose generated columns with availability checks
|
||||
|
||||
## 6.5.0
|
||||
|
||||
Released December 5, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.4.0...v6.5.0)
|
||||
|
||||
- **New**: [#1299](https://github.com/groue/GRDB.swift/pull/1299) by [@groue](https://github.com/groue): Record.find() convenience methods
|
||||
|
||||
## 6.4.0
|
||||
|
||||
Released November 28, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.3.1...v6.4.0)
|
||||
|
||||
- **New**: [#1293](https://github.com/groue/GRDB.swift/pull/1293) by [@groue](https://github.com/groue): Enable concurrent reads from a WAL snapshot.
|
||||
- **New**: [#1297](https://github.com/groue/GRDB.swift/pull/1297) by [@groue](https://github.com/groue): SPM: expose the CSQLite product.
|
||||
- **New**: `DatabaseReader.configuration.readQoS` and `writeQoS` return the effective quality of service of read-only and write database accesses. This helps application code avoid priority inversion and similar scheduling misuses when needed.
|
||||
- **New**: `DatabaseReader.configuration.maximumReaderCount` returns the effective capacity for concurrent reads, so that application code can adapt when needed.
|
||||
- **New**: `DatabasePool.makeSnapshot()` no longer throws an error when the database is not in the WAL mode. In such case, the returned snapshot prevents all database modifications during its lifetime.
|
||||
- **New**: A new [`DatabaseSnapshotReader`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesnapshotreader) protocol was introduced for types that see an unchanging database content (`DatabaseSnapshot` and the new `DatabaseSnapshotPool`).
|
||||
- **New**: [`Database.registerAccess(to:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/registeraccess(to:)) has `ValueObservation` track a region. This helps building optimized observations of a constant database region with [`ValueObservation.trackingConstantRegion(_:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/trackingconstantregion(_:)).
|
||||
- **New**: Open several connections to the same in-memory database with [`DatabaseQueue(named:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue/init(named:configuration:)).
|
||||
- **New**: [`TableDefinition`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tabledefinition) has new methods for defining primary keys, with automatic NOT NULL constraints. They workaround [an SQLite bug](https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls). Previous techniques for defining primary keys are preserved for backwards compatibility, but their use is not recommended.
|
||||
- **New**: The [Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) documentation article has a brand new "Database Schema Recommendations" section.
|
||||
- **New**: Multiple improvements to the DocC documentation.
|
||||
|
||||
## 6.3.1
|
||||
|
||||
Released November 11, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.3.0...v6.3.1)
|
||||
|
||||
- **New**: DocC documentation is hosted at https://swiftpackageindex.com/groue/GRDB.swift/documentation
|
||||
|
||||
## 6.3.0
|
||||
|
||||
Released November 6, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.2.0...v6.3.0)
|
||||
|
||||
- **New**: [#1291](https://github.com/groue/GRDB.swift/pull/1291) by [@groue](https://github.com/groue): DocC inline documentation
|
||||
- **New**: The `Row.dataNoCopy` methods are deprecated. Use `Row.withUnsafeData` instead.
|
||||
|
||||
## 6.2.0
|
||||
|
||||
Released October 28, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.1.0...v6.2.0)
|
||||
|
||||
- **New**: [#1289](https://github.com/groue/GRDB.swift/pull/1289) by [@arkie](https://github.com/arkie): Add support for passing in categories to the FTS5 unicode61 tokenizer (SQLite 3.25+)
|
||||
- **Fixed**: The `FTS5Tokenizer.tokenize(query:)` method no longer returns incorrect results for certain tokenizer arguments.
|
||||
|
||||
## 6.1.0
|
||||
|
||||
Released October 20, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.0.0...v6.1.0)
|
||||
|
||||
- **New**: [#1288](https://github.com/groue/GRDB.swift/pull/1288) by [@jcavar](https://github.com/jcavar): Support for strict tables
|
||||
|
||||
## 6.0.0
|
||||
|
||||
Released September 9, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.0.0-beta.4...v6.0.0)
|
||||
|
||||
- **New**: Bump custom SQLite builds v3.39.3
|
||||
- **Fixed**: [#1274](https://github.com/groue/GRDB.swift/discussions/1274) Fixed a bug with HasManyThrough associations when the "through" association has the same association key as the association itself.
|
||||
- **Fixed**: [#1275](https://github.com/groue/GRDB.swift/issues/1275) Enhance error message for some requests involving associations on common table expressions.
|
||||
- **Fixed**: [#1276](https://github.com/groue/GRDB.swift/issues/1276) Fix build error with Xcode 14.0 RC (14A309)
|
||||
- **Breaking Change**: Request methods that accept a closure with a `Database` argument have been renamed with the `WhenConnected` suffix: `request.filterWhenConnected { db in ... }`, etc.
|
||||
|
||||
## 6.0.0-beta.4
|
||||
|
||||
Released August 28, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.0.0-beta.3...v6.0.0-beta.4)
|
||||
|
||||
- **New**: [#1271](https://github.com/groue/GRDB.swift/pull/1271) by [@groue](https://github.com/groue): Bump custom SQLite builds v3.39.2
|
||||
- **New**: [SQLITE_OPEN_EXRESCODE](https://www.sqlite.org/c3ref/open.html), when available, exposes [extended result codes](README.md#databaseerror) when opening a database connection.
|
||||
- **Fixed**: [PRAGMA table_list](https://www.sqlite.org/pragma.html#pragma_table_list), when available, makes it possible for GRDB to detect [WITHOUT ROWID](https://www.sqlite.org/withoutrowid.html) tables without [polluting the SQLite error log](https://github.com/groue/GRDB.swift/issues/945).
|
||||
- **Breaking Change**: The`GRDB.xcodeproj` or `GRDBCustom.xcodeproj` projects now define cross-platforms targets.
|
||||
- **Documentation Update**: [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) describes how to update applications that directly embed the `GRDB.xcodeproj` or `GRDBCustom.xcodeproj` project.
|
||||
- **Documentation Update**: [Custom SQLite Builds](CustomSQLiteBuilds.md) was updated for the new cross-platform target defined by the `GRDBCustom.xcodeproj` project.
|
||||
|
||||
## 6.0.0-beta.3
|
||||
|
||||
Released August 25, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.0.0-beta.2...v6.0.0-beta.3)
|
||||
|
||||
- **Fix**: [#1268](https://github.com/groue/GRDB.swift/pull/1268) by [@groue](https://github.com/groue): Fix SQL generation of CHECK constraints
|
||||
- **Breaking Change**: The `Column` type is no longer `Equatable`
|
||||
- **Documentation Update**: [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) describes in detail how to update records that customize their persistence methods.
|
||||
- **Documentation Update**: The [Single-Row Tables](Documentation/SingleRowTables.md) guide was updated for the new persistence callbacks.
|
||||
|
||||
## 6.0.0-beta.2
|
||||
|
||||
Released August 23, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.0.0-beta...v6.0.0-beta.2)
|
||||
|
||||
- **New**: Extended UPSERT apis with the ability to define the conflict target, and the assignments performed in case of conflicts.
|
||||
- **Documentation Update**: A new [Upsert](README.md#upsert) chapter describes upserts in detail.
|
||||
|
||||
## 6.0.0-beta
|
||||
|
||||
Released August 21, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.26.0...v6.0.0-beta)
|
||||
|
||||
### New
|
||||
|
||||
Upgrading your app can bring improvements: check [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) for some suggestions.
|
||||
|
||||
- :star: Support for [`UPSERT`](https://www.sqlite.org/lang_UPSERT.html): `player.upsert(db)`, etc. See [Persistence Methods](README.md#persistence-methods).
|
||||
|
||||
- :star: Support for the [`RETURNING` clause](https://www.sqlite.org/lang_returning.html): `player.insertAndFetch(db)`, `Player.deleteAndFetchAll(db)`, etc. See [Persistence Methods and the `RETURNING` clause](README.md#persistence-methods-and-the-returning-clause).
|
||||
|
||||
- :star: [Persistence Callbacks](README.md#persistence-callbacks) allow record types to customize persistence methods: `didInsert`, `willSave`, etc.
|
||||
|
||||
- :star: Better support for unexpected database values. Where GRDB 5 would crash during encoding and decoding database values, GRDB 6 has learned to throw errors instead. Record protocols throw decoding and encoding errors, and value requests throw errors on invalid inputs.
|
||||
|
||||
- Request protocols and cursors now define primary associated types, enabled by [SE-0346](https://github.com/apple/swift-evolution/blob/main/proposals/0346-light-weight-same-type-syntax.md).
|
||||
|
||||
- All persistence methods now accept an explicit conflict policy: `player.insert(db, onConflict: .replace)`, etc.
|
||||
|
||||
- You can append the contents of a cursor to a collection with `RangeReplaceableCollection.append(contentsOf:)`.
|
||||
|
||||
- `ValueObservation.map` now accepts a throwing closure argument.
|
||||
|
||||
### Documentation Updates
|
||||
|
||||
- :star: **[Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)**: suggestions for improving your applications, and guidance for handling the breaking changes.
|
||||
- The [Persistence Methods](README.md#persistence-methods) chapter introduces the `upsert` method.
|
||||
- The [Persistence Methods and the `RETURNING` clause](README.md#persistence-methods-and-the-returning-clause) chapter introduces persistence methods that fetch inserted, updated and deleted values.
|
||||
- The [Persistence Callbacks](README.md#persistence-callbacks) chapter introduces the callback invoked from persistence methods, such as `didInsert`, `willSave`, etc.
|
||||
- The [DatabaseRegionObservation](README.md#databaseregionobservation) chapter was updated for the new `DatabaseRegionObservation.start` method.
|
||||
- The [Transaction Hook](README.md#transaction-hook) chapter describes the new `Database.afterNextTransaction(onCommit:onRollback:)` method.
|
||||
- The [Value Queries](README.md#value-queries) chapter explains how to distinguish a request that returns no value from a request that fetches a NULL value.
|
||||
|
||||
### Breaking Changes
|
||||
|
||||
- Removed deprecated methods
|
||||
- :star: Bumped requirements:
|
||||
- Swift 5.7+ and Xcode 14+ are required.
|
||||
- iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ / SQLite 3.19.3+ are required.
|
||||
- :star: Record protocols were refactored:
|
||||
- The `FetchableRecord.init(row:)` initializer can now throw errors.
|
||||
- The `EncodableRecord.encode(to:)` method can now throw errors.
|
||||
- Record types can no longer override persistence methods. You use [Persistence Callbacks](README.md#persistence-callbacks) instead.
|
||||
- Various breaking changes:
|
||||
- The in-memory `DatabaseQueue()` initializer can now throw errors.
|
||||
- The `selectID()` method is replaced with `selectPrimaryKey(as:)`.
|
||||
- `Cursor.isEmpty` is now a throwing property, instead of a method.
|
||||
- The `Record.copy()` method was removed, without replacement.
|
||||
- The `DerivableRequest.limit(_:offset_:)` method was removed, without replacement.
|
||||
- `DatabaseRegionObservation.start(in:onError:onChange:)` now returns a cancellable.
|
||||
- The `DatabaseRegionObservation.extent` property was removed.
|
||||
- The `statement` property of database cursors was replaced with read-only properties such as `sql` or `columnNames`.
|
||||
- The `Database.afterNextTransactionCommit(_:)` method was renamed `Database.afterNextTransaction(onCommit:onRollback:)`, and is now able to report rollbacks as well as commits.
|
||||
|
||||
## 5.26.1
|
||||
|
||||
Released September 8, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.26.0...v5.26.1)
|
||||
|
||||
- **Fixed**: [#1276](https://github.com/groue/GRDB.swift/pull/1276) Fix build error with Xcode 14.0 RC (14A309)
|
||||
- **Fixed**: [#1276](https://github.com/groue/GRDB.swift/issues/1276) Fix build error with Xcode 14.0 RC (14A309)
|
||||
|
||||
## 5.26.0
|
||||
|
||||
@@ -3497,7 +3958,7 @@ It comes with breaking changes, but the good news is that they are the last (unt
|
||||
|
||||
As a matter of fact, GRDB 1.0 still supports Xcode 8.1 and Swift 3.0. But future versions are free to use Swift 3.1 features, and will require Xcode 8.3+.
|
||||
|
||||
The targetted operating systems are unchanged: iOS 8.0+ / OSX 10.9+ / watchOS 2.0+
|
||||
The targetted operating systems are unchanged: iOS 8.0+ / macOS 10.9+ / watchOS 2.0+
|
||||
|
||||
- **[Record types](https://github.com/groue/GRDB.swift#records) have their `persistentDictionary` property replaced with the `encode(to:)` method:**
|
||||
|
||||
@@ -5305,11 +5766,11 @@ Released May 17, 2016
|
||||
|
||||
**Fixed**
|
||||
|
||||
- Restored support for iOS before 8.2 and OS X before 10.10. Fixes [#51](https://github.com/groue/GRDB.swift/issues/51).
|
||||
- Restored support for iOS before 8.2 and macOS before 10.10. Fixes [#51](https://github.com/groue/GRDB.swift/issues/51).
|
||||
|
||||
**Breaking Changes**
|
||||
|
||||
- Support for advanced migrations is not available until iOS 8.2 and OS X 10.10:
|
||||
- Support for advanced migrations is not available until iOS 8.2 and macOS 10.10:
|
||||
|
||||
```diff
|
||||
struct DatabaseMigrator {
|
||||
@@ -5365,7 +5826,7 @@ Released May 10, 2016
|
||||
|
||||
**New**
|
||||
|
||||
- `FetchedRecordsController` is now exposed in OSX CocoaPods framework ([documentation](https://github.com/groue/GRDB.swift#fetchedrecordscontroller))
|
||||
- `FetchedRecordsController` is now exposed in macOS CocoaPods framework ([documentation](https://github.com/groue/GRDB.swift#fetchedrecordscontroller))
|
||||
|
||||
**Fixed**
|
||||
|
||||
@@ -5498,7 +5959,7 @@ Released April 5, 2016
|
||||
|
||||
**Fixed**
|
||||
|
||||
- Restored CocoaPods support for iOS 8+ and OS X 10.9+
|
||||
- Restored CocoaPods support for iOS 8+ and macOS 10.9+
|
||||
|
||||
|
||||
## 0.56.0
|
||||
@@ -5541,7 +6002,7 @@ Released March 31, 2016
|
||||
|
||||
Released March 29, 2016
|
||||
|
||||
This release restores CocoaPods support for iOS 9.0+ and OSX 10.11+. We'll try to bring back CocoaPods support for iOS 8.0+ or OSX 10.9+ in a further release.
|
||||
This release restores CocoaPods support for iOS 9.0+ and macOS 10.11+. We'll try to bring back CocoaPods support for iOS 8.0+ or macOS 10.9+ in a further release.
|
||||
|
||||
|
||||
## 0.54.0
|
||||
@@ -6440,7 +6901,7 @@ Released August 25, 2015
|
||||
|
||||
**Fixed**
|
||||
|
||||
- Reduced iOS Deployment Target to 8.0, and OSX Deployment Target to 10.9.
|
||||
- Reduced iOS Deployment Target to 8.0, and macOS Deployment Target to 10.9.
|
||||
- `DatabaseQueue.inTransaction()` is now declared as `rethrows`.
|
||||
|
||||
**Breaking changes**
|
||||
|
||||
+5
-5
@@ -15,8 +15,6 @@ How you can Contribute
|
||||
- [xcpretty](https://github.com/xcpretty/xcpretty) (gem)
|
||||
- For contributing code:
|
||||
- [Swiftlint](https://github.com/realm/SwiftLint) (present in the `$PATH` or in `/opt/homebrew/bin/`)
|
||||
- For generating documentation:
|
||||
- [Jazzy](https://github.com/realm/jazzy) (gem)
|
||||
|
||||
2. **Clone the `development` branch on your machine.**
|
||||
|
||||
@@ -40,7 +38,7 @@ How you can Contribute
|
||||
|
||||
5. **Run tests**
|
||||
|
||||
You can run tests from `GRDB.xcworkspace`, after selecting your target (GRDBOSX, GRDBiOS, GRDBtvOS, from `GRDB.xcodeproj` or `GRDBCustom.xcodeproj`).
|
||||
You can run tests from `GRDB.xcworkspace`, after selecting your scheme (`GRDB` from `GRDB.xcodeproj` or `GRDBCustom` from `GRDBCustom.xcodeproj`).
|
||||
|
||||
Before submitting a pull request, please run in the terminal:
|
||||
|
||||
@@ -63,13 +61,15 @@ How you can Contribute
|
||||
- Get familiar with the [Swift API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/).
|
||||
- Spaces, not tabs.
|
||||
- Whitespace-only lines are not trimmed.
|
||||
- Documentation comments are hard-wrapped at column 80 (Xcode > Preferences > Text Editing > Display > [X] Page guide at column: 80).
|
||||
- Documentation comments are hard-wrapped at column 76 (Xcode > Preferences > Text Editing > Display > [X] Page guide at column: 76).
|
||||
- No Swiftlint warning after a build.
|
||||
|
||||
|
||||
7. **Please provide documentation for your changes**
|
||||
|
||||
GRDB documentation is provided as reference (inline doc comments starting with `///`, see [Documentation Comment Syntax](https://github.com/apple/swift/blob/main/docs/DocumentationComments.md)), and guides ([README.md](README.md) and the [Documentation](Documentation) folder).
|
||||
GRDB documentation is provided as a DocC reference, and guides ([README.md](README.md) and the [Documentation](Documentation) folder).
|
||||
|
||||
Please keep the reference and the guides up-to-date. To control the quality of your DocC reference documentation, close the workspace, open `Package.swift` in Xcode, and use Product > Build Documentation.
|
||||
|
||||
GRDB is "documentation-driven", which means that nothing ships until it is supported by documentation that makes sense. Documentation makes sense when someone who is not you is able to figure out what is the purpose of your contribution, how to use it, and what are its eventual caveats and corner cases. When the documentation is hard to write, or reveals too many caveats, it is the sign that the api needs to be fixed.
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Sharing a Database in an App Group Container
|
||||
============================================
|
||||
|
||||
This guide [has moved](SharingADatabase.md).
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing).
|
||||
@@ -130,7 +130,7 @@ let request = Book.including(optional: Book.author)
|
||||
let bookInfos = BookInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
Before we dive in, please remember that associations can not generate all possible SQL queries that involve several tables. You may also *prefer* writing SQL, and this is just OK, because your SQL skills are welcome: see the [Joined Queries Support](../README.md#joined-queries-support) chapter.
|
||||
Before we dive in, please remember that associations can not generate all possible SQL queries that involve several tables. You may also *prefer* writing SQL, and this is just OK, because your SQL skills are welcome. The [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/splittingrowadapters(columncounts:)) method can help you consume the rows fetched from joined queries, as in `SELECT book.*, author.* FROM ...`.
|
||||
|
||||
|
||||
## Required Protocols
|
||||
@@ -429,15 +429,13 @@ The matching [migration] would look like:
|
||||
migrator.registerMigration("Employees") { db in
|
||||
try db.create(table: "employee") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("managerId", .integer)
|
||||
.indexed()
|
||||
.references("employee", onDelete: .restrict)
|
||||
t.belongsTo("manager", inTable: "employee", onDelete: .setNull)
|
||||
t.column("name", .text)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Note that both sides of the self-join use a customized **[association key](#the-structure-of-a-joined-request)**. This helps consuming this association. For example:
|
||||
Note that the associations on both sides of the self-join use a customized **[association key](#the-structure-of-a-joined-request)**. This helps consuming this association. For example:
|
||||
|
||||
```swift
|
||||
struct EmployeeInfo: FetchableRecord, Decodable {
|
||||
@@ -511,7 +509,7 @@ When using class names composed of two or more words, the table name should use
|
||||
| Mouse | mouse | `mouse`, `mice`, `maxMouseSize` |
|
||||
| Person | person | `person`, `people`, `personCount` |
|
||||
|
||||
If your application relies on non-English names, GRDB may generate unexpected identifiers. If this happens, please [open an issue](http://github.com/groue/GRDB.swift/issues).
|
||||
If your application relies on non-English names, GRDB may generate unexpected identifiers. If this happens, please [open an issue](https://github.com/groue/GRDB.swift/issues).
|
||||
|
||||
See [The Structure of a Joined Request] for more information.
|
||||
|
||||
@@ -536,20 +534,16 @@ migrator.registerMigration("Books and Authors") { db in
|
||||
}
|
||||
try db.create(table: "book") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("authorId", .integer) // (2)
|
||||
t.belongsTo("author", onDelete: .cascade) // (2)
|
||||
.notNull() // (3)
|
||||
.indexed() // (4)
|
||||
.references("author", onDelete: .cascade) // (5)
|
||||
t.column("title", .text)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
1. The `author` table has a primary key.
|
||||
2. The `book.authorId` column is used to link a book to the author it belongs to.
|
||||
2. The `book.authorId` column is used to link a book to the author it belongs to. This column is indexed in order to ease the selection of an author's books. A foreign key is defined from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. 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.
|
||||
3. Make the `book.authorId` column not null if you want SQLite to guarantee that all books have an author.
|
||||
4. Create an index on the `book.authorId` column in order to ease the selection of an author's books.
|
||||
5. Create a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. 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.
|
||||
|
||||
The example above uses auto-incremented primary keys. But generally speaking, all primary keys are supported, including composite primary keys that span several columns.
|
||||
|
||||
@@ -595,20 +589,16 @@ migrator.registerMigration("Books and Authors") { db in
|
||||
}
|
||||
try db.create(table: "book") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("authorId", .integer) // (2)
|
||||
t.belongsTo("author", onDelete: .cascade) // (2)
|
||||
.notNull() // (3)
|
||||
.indexed() // (4)
|
||||
.references("author", onDelete: .cascade) // (5)
|
||||
t.column("title", .text)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
1. The `author` table has a primary key.
|
||||
2. The `book.authorId` column is used to link a book to the author it belongs to.
|
||||
2. The `book.authorId` column is used to link a book to the author it belongs to. This column is indexed in order to ease the selection of an author's books. A foreign key is defined from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. 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.
|
||||
3. Make the `book.authorId` column not null if you want SQLite to guarantee that all books have an author.
|
||||
4. Create an index on the `book.authorId` column in order to ease the selection of an author's books.
|
||||
5. Create a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. 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.
|
||||
|
||||
The example above uses auto-incremented primary keys. But generally speaking, all primary keys are supported, including composite primary keys that span several columns.
|
||||
|
||||
@@ -649,15 +639,14 @@ Here is the recommended [migration] for the **[HasOne]** association:
|
||||
```swift
|
||||
migrator.registerMigration("Countries") { db in
|
||||
try db.create(table: "country") { t in
|
||||
t.column("code", .text).primaryKey() // (1)
|
||||
t.primaryKey("code", .text) // (1)
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "demographics") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("countryCode", .text) // (2)
|
||||
t.belongsTo("country", onDelete: .cascade) // (2)
|
||||
.notNull() // (3)
|
||||
.unique() // (4)
|
||||
.references("country", onDelete: .cascade) // (5)
|
||||
t.column("population", .integer)
|
||||
t.column("density", .double)
|
||||
}
|
||||
@@ -665,10 +654,9 @@ migrator.registerMigration("Countries") { db in
|
||||
```
|
||||
|
||||
1. The `country` table has a primary key.
|
||||
2. The `demographics.countryCode` column is used to link a demographic profile to the country it belongs to.
|
||||
2. The `demographics.countryCode` column is used to link a demographic profile to the country it belongs to. This column is indexed in order to ease the selection of the demographics of a country. A foreign key is defined from `demographics.countryCode` column to `country.code`, so that SQLite guarantees that no profile refers to a missing country. The `onDelete: .cascade` option has SQLite automatically delete a profile when its country is deleted. See [Foreign Key Actions] for more information.
|
||||
3. Make the `demographics.countryCode` column not null if you want SQLite to guarantee that all profiles are linked to a country.
|
||||
4. Create a unique index on the `demographics.countryCode` column in order to guarantee the unicity of any country's profile.
|
||||
5. Create a foreign key from `demographics.countryCode` column to `country.code`, so that SQLite guarantees that no profile refers to a missing country. The `onDelete: .cascade` option has SQLite automatically delete a profile when its country is deleted. See [Foreign Key Actions] for more information.
|
||||
|
||||
The example above uses a string primary key for the "country" table. But generally speaking, all primary keys are supported, including composite primary keys that span several columns.
|
||||
|
||||
@@ -712,14 +700,30 @@ struct Author: TableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
> :point_up: **Note**: Generally speaking, all foreign keys are supported, including composite keys that span several columns.
|
||||
> **Note**: Generally speaking, all foreign keys are supported, including composite keys that span several columns.
|
||||
>
|
||||
> :warning: **Warning**: SQLite voids foreign key constraints when one or more of a foreign key column is NULL (see [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html)). GRDB does not match foreign keys that involve a NULL value either.
|
||||
> **Warning**: SQLite voids foreign key constraints when one or more of a foreign key column is NULL (see [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html)). GRDB does not match foreign keys that involve a NULL value either.
|
||||
|
||||
Sometimes the database schema does not define any foreign key. And sometimes, there are *several* foreign keys from a table to another.
|
||||
|
||||

|
||||
|
||||
```swift
|
||||
// The migration that has created the above schema
|
||||
migrator.registerMigration("Library") { db in
|
||||
try db.create(table: "person") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "book") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("author", inTable: "person")
|
||||
t.belongsTo("translator", inTable: "person")
|
||||
t.column("title", .text)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
When this happens, associations can't be automatically inferred from the database schema. GRDB will complain with a fatal error such as "Ambiguous foreign key from book to person", or "Could not infer foreign key from book to person".
|
||||
|
||||
Your help is needed. You have to instruct GRDB which foreign key to use:
|
||||
@@ -1210,7 +1214,7 @@ In the description of the [joining methods] above, we have seen that you need to
|
||||
|
||||
In this chapter, we take the reversed perspective. We list various shapes of decoded record types. When you find the type you want, you'll know the joining method you need.
|
||||
|
||||
> :point_up: **Note**: If you don't find the type you want, chances are that you are fighting the framework, and should reconsider your position. Your escape hatch is the low-level apis described in [Decoding a Joined Request with FetchableRecord].
|
||||
> **Note**: If you don't find the type you want, chances are that you are fighting the framework, and should reconsider your position. Your escape hatch is the low-level apis described in [Decoding a Joined Request with FetchableRecord].
|
||||
|
||||
- [`including(required:)`]
|
||||
|
||||
@@ -1435,7 +1439,7 @@ struct BookInfo: FetchableRecord, Decodable {
|
||||
let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
> :warning: **Warning**: you can not currently chain a required association behind an optional association:
|
||||
> **Warning**: you can not currently chain a required association behind an optional association:
|
||||
>
|
||||
> ```swift
|
||||
> // Not implemented
|
||||
@@ -1751,7 +1755,7 @@ Associations support more refinements:
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
> :warning: **Warning**: associations refined with `limit`, `distinct`, `group`, `having`, or association aggregates can only be used with `including(all:)`. You will get a fatal error if you use them with other joining methods: `including(required:)`, etc.
|
||||
> **Warning**: associations refined with `limit`, `distinct`, `group`, `having`, or association aggregates can only be used with `including(all:)`. You will get a fatal error if you use them with other joining methods: `including(required:)`, etc.
|
||||
|
||||
|
||||
## Table Aliases
|
||||
@@ -1823,7 +1827,7 @@ let request = Book.aliased(bookAlias)
|
||||
.filter(sql: "b.publishDate >= a.deathDate")
|
||||
```
|
||||
|
||||
> :point_up: **Note**: avoid reusing table aliases between several tables or requests, because you will get a fatal error:
|
||||
> **Note**: avoid reusing table aliases between several tables or requests, because you will get a fatal error:
|
||||
>
|
||||
> ```swift
|
||||
> // Fatal error: A TableAlias most not be used to refer to multiple tables
|
||||
@@ -1832,7 +1836,7 @@ let request = Book.aliased(bookAlias)
|
||||
> let people = Person.aliased(alias)...
|
||||
> ```
|
||||
>
|
||||
> :point_up: **Note**: you can't use the `including(all:)` method and use table aliases to filter the associated records on other records:
|
||||
> **Note**: you can't use the `including(all:)` method and use table aliases to filter the associated records on other records:
|
||||
>
|
||||
> ```swift
|
||||
> // NOT IMPLEMENTED: loading all authors along with their posthumous books
|
||||
@@ -1899,7 +1903,7 @@ For example, we can start by defining base requests as extensions to the [Deriva
|
||||
|
||||
```swift
|
||||
// Author requests
|
||||
extension DerivableRequest where RowDecoder == Author {
|
||||
extension DerivableRequest<Author> {
|
||||
/// Filters authors by country
|
||||
func filter(country: String) -> Self {
|
||||
filter(Column("country") == country)
|
||||
@@ -1907,7 +1911,7 @@ extension DerivableRequest where RowDecoder == Author {
|
||||
}
|
||||
|
||||
// Book requests
|
||||
extension DerivableRequest where RowDecoder == Book {
|
||||
extension DerivableRequest<Book> {
|
||||
/// Filters books by author country
|
||||
func filter(authorCountry: String) -> Self {
|
||||
joining(required: Book.author.filter(country: country))
|
||||
@@ -2000,7 +2004,7 @@ Each association included in the request can feed a property of the decoded reco
|
||||
- [Decoding a Joined Request with a Decodable Record]
|
||||
- [Decoding a Joined Request with FetchableRecord]
|
||||
- [Debugging Request Decoding]
|
||||
- [Good Practices for Designing Record Types] - in this general guide about records, check out the "Compose Records" chapter.
|
||||
- [Recommended Practices for Designing Record Types] - in this general guide about records, check out the "Associations" chapter.
|
||||
|
||||
|
||||
## The Structure of a Joined Request
|
||||
@@ -2165,8 +2169,8 @@ struct BookInfo: FetchableRecord {
|
||||
var country: Country?
|
||||
var coverImage: CoverImage?
|
||||
|
||||
init(row: Row) {
|
||||
book = Book(row: row)
|
||||
init(row: Row) throws {
|
||||
book = try Book(row: row)
|
||||
author = row["author"]
|
||||
country = row["country"]
|
||||
coverImage = row["coverImage"]
|
||||
@@ -2200,8 +2204,8 @@ struct AuthorInfo: FetchableRecord {
|
||||
var author: Author
|
||||
var books: [Book]
|
||||
|
||||
init(row: Row) {
|
||||
author = Author(row: row)
|
||||
init(row: Row) throws {
|
||||
author = try Author(row: row)
|
||||
books = row["books"]
|
||||
}
|
||||
}
|
||||
@@ -2657,7 +2661,7 @@ Aggregates can be modified and combined with Swift operators:
|
||||
let request = Team.annotated(with: Team.players.min(Column("score")) ?? 0)
|
||||
```
|
||||
|
||||
- SQL functions `ABS` and `LENGTH` are available as the `abs` and `length` Swift functions:
|
||||
- SQL functions `ABS`, `CAST`, and `LENGTH` are available as the `abs`, `cast`, and `length` Swift functions:
|
||||
|
||||
<details>
|
||||
<summary>SQL</summary>
|
||||
@@ -2843,7 +2847,7 @@ let request = Book.all().filter(country: "ES")
|
||||
Those methods are defined on extensions to the `DerivableRequest` protocol:
|
||||
|
||||
```swift
|
||||
extension DerivableRequest where RowDecoder == Author {
|
||||
extension DerivableRequest<Author> {
|
||||
func filter(country: String) -> Self {
|
||||
filter(Column("country") == country)
|
||||
}
|
||||
@@ -2853,14 +2857,14 @@ extension DerivableRequest where RowDecoder == Author {
|
||||
}
|
||||
}
|
||||
|
||||
extension DerivableRequest where RowDecoder == Book {
|
||||
extension DerivableRequest<Book> {
|
||||
func filter(country: String) -> Self {
|
||||
joining(required: Book.author.filter(country: country))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
See [Good Practices for Designing Record Types] for more information.
|
||||
See [Recommended Practices for Designing Record Types] for more information.
|
||||
|
||||
|
||||
## Known Issues
|
||||
@@ -2907,8 +2911,6 @@ See [Good Practices for Designing Record Types] for more information.
|
||||
.including(required: Passport.citizen))
|
||||
```
|
||||
|
||||
Come [discuss](http://twitter.com/groue) for more information, or if you wish to help turning those missing features into reality.
|
||||
|
||||
---
|
||||
|
||||
This documentation owns a lot to the [Active Record Associations](http://guides.rubyonrails.org/association_basics.html) guide, which is an immensely well-written introduction to database relations. Many thanks to the Rails team and contributors.
|
||||
@@ -2919,7 +2921,7 @@ This documentation owns a lot to the [Active Record Associations](http://guides.
|
||||
|
||||
**GRDB**
|
||||
|
||||
Copyright (C) 2015-2020 Gwendal Roué
|
||||
Copyright (C) 2015-2023 Gwendal Roué
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
@@ -2963,7 +2965,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
[Further Refinements to Associations]: #further-refinements-to-associations
|
||||
[The Types of Associations]: #the-types-of-associations
|
||||
[FetchableRecord]: ../README.md#fetchablerecord-protocols
|
||||
[migration]: Migrations.md
|
||||
[migration]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations
|
||||
[Record]: ../README.md#records
|
||||
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
|
||||
[Associations and the Database Schema]: #associations-and-the-database-schema
|
||||
@@ -2998,18 +3000,17 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
[Isolation of Multiple Aggregates]: #isolation-of-multiple-aggregates
|
||||
[DerivableRequest Protocol]: #derivablerequest-protocol
|
||||
[Known Issues]: #known-issues
|
||||
[Row Adapters]: ../README.md#row-adapters
|
||||
[Row Adapters]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter
|
||||
[query interface requests]: ../README.md#requests
|
||||
[TableRecord]: ../README.md#tablerecord-protocol
|
||||
[Good Practices for Designing Record Types]: GoodPracticesForDesigningRecordTypes.md
|
||||
[Recommended Practices for Designing Record Types]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices
|
||||
[regular aggregating methods]: ../README.md#fetching-aggregated-values
|
||||
[Record class]: ../README.md#record-class
|
||||
[EncodableRecord]: ../README.md#persistablerecord-protocol
|
||||
[PersistableRecord]: ../README.md#persistablerecord-protocol
|
||||
[Codable Records]: ../README.md#codable-records
|
||||
[persistence methods]: ../README.md#persistence-methods
|
||||
[database observation tools]: ../README.md#database-changes-observation
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[database observation tools]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
|
||||
[FAQ]: ../README.md#faq-associations
|
||||
[common table expressions]: CommonTableExpressions.md
|
||||
[Common Table Expressions]: CommonTableExpressions.md
|
||||
|
||||
+11
-13
@@ -191,7 +191,7 @@ let newPlayerCount = dbQueue.writePublisher { db -> Int in
|
||||
|
||||
The difference is that the last fetches are performed in the `thenRead` function. This function accepts two arguments: a readonly database connection, and the result of the `updates` function. This allows you to pass information from a function to the other (it is ignored in the sample code above).
|
||||
|
||||
When you use a [database pool], this method applies a scheduling optimization: the `thenRead` function sees the database in the state left by the `updates` function, and yet does not block any concurrent writes. This can reduce database write contention. See [Advanced DatabasePool](Concurrency.md#advanced-databasepool) for more information.
|
||||
When you use a [database pool], this method applies a scheduling optimization: the `thenRead` function sees the database in the state left by the `updates` function, and yet does not block any concurrent writes. This can reduce database write contention.
|
||||
|
||||
When you use a [database queue], the results are guaranteed to be identical, but no scheduling optimization is applied.
|
||||
|
||||
@@ -226,11 +226,11 @@ This publisher has the same behavior as ValueObservation:
|
||||
|
||||
- It notifies an initial value before the eventual changes.
|
||||
- It may coalesce subsequent changes into a single notification.
|
||||
- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](../README.md#valueobservationremoveduplicates) GRDB operator also.
|
||||
- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/removeduplicates()) GRDB operator also.
|
||||
- It only completes when it is cancelled.
|
||||
- By default, it notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously.
|
||||
|
||||
This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservation scheduler](../README.md#valueobservation-scheduling).
|
||||
This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservationScheduler](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservationscheduler).
|
||||
|
||||
For example, the `.immediate` scheduler makes sure the initial value is notified immediately when the publisher is subscribed. It can help your application update the user interface without having to wait for any asynchronous notifications:
|
||||
|
||||
@@ -248,8 +248,6 @@ This publisher has the same behavior as ValueObservation:
|
||||
|
||||
Note that the `.immediate` scheduler requires that the publisher is subscribed from the main thread. It raises a fatal error otherwise.
|
||||
|
||||
See [ValueObservation Scheduling](../README.md#valueobservation-scheduling) for more information.
|
||||
|
||||
|
||||
#### `SharedValueObservation.publisher()`
|
||||
|
||||
@@ -384,23 +382,23 @@ let cancellable = hallOfFamePublisher.sink(
|
||||
[Usage]: #usage
|
||||
[Asynchronous Database Access]: #asynchronous-database-access
|
||||
[Combine]: https://developer.apple.com/documentation/combine
|
||||
[Database Changes Observation]: ../README.md#database-changes-observation
|
||||
[Database Changes Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
|
||||
[Database Observation]: #database-observation
|
||||
[Combine and Data Consistency]: #combine-and-data-consistency
|
||||
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
|
||||
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation
|
||||
[Demo Application]: DemoApps/GRDBCombineDemo/README.md
|
||||
[SQLite]: http://sqlite.org
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[SharedValueObservation]: ../README.md#valueobservation-sharing
|
||||
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
|
||||
[SharedValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/sharedvalueobservation
|
||||
[`DatabaseRegionObservation.publisher(in:)`]: #databaseregionobservationpublisherin
|
||||
[`ValueObservation.publisher(in:scheduling:)`]: #valueobservationpublisherinscheduling
|
||||
[`SharedValueObservation.publisher()`]: #sharedvalueobservationpublisher
|
||||
[`readPublisher(receiveOn:value:)`]: #databasereaderreadpublisherreceiveonvalue
|
||||
[`writePublisher(receiveOn:updates:)`]: #databasewriterwritepublisherreceiveonupdates
|
||||
[`writePublisher(receiveOn:updates:thenRead:)`]: #databasewriterwritepublisherreceiveonupdatesthenread
|
||||
[`migratePublisher(_:receiveOn:)`]: Migrations.md#asynchronous-migrations
|
||||
[`migratePublisher(_:receiveOn:)`]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasemigrator/migratepublisher(_:receiveon:)
|
||||
[configured]: ../README.md#databasepool-configuration
|
||||
[database pool]: ../README.md#database-pools
|
||||
[database queue]: ../README.md#database-queues
|
||||
[database snapshot]: Concurrency.md#database-snapshots
|
||||
[database pool]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool
|
||||
[database queue]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue
|
||||
[database snapshot]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesnapshot
|
||||
[scheduler]: https://developer.apple.com/documentation/combine/scheduler
|
||||
@@ -16,7 +16,7 @@ In this guide, you will learn how to:
|
||||
- [Fetch Values From Common Table Expressions]
|
||||
- Join CTEs with [Associations to Common Table Expressions]
|
||||
|
||||
> :point_up: **Note**: most code examples will be trivial, and not very "useful". This is because the goal of this guide is to stay focused on the GRDB support for CTEs. Rich setup would just be distracting. So bring your own good ideas with you!
|
||||
> **Note**: most code examples will be trivial, and not very "useful". This is because the goal of this guide is to stay focused on the GRDB support for CTEs. Rich setup would just be distracting. So bring your own good ideas with you!
|
||||
|
||||
|
||||
## Define Common Table Expressions
|
||||
@@ -82,7 +82,7 @@ let counterCTE = CommonTableExpression(
|
||||
""")
|
||||
```
|
||||
|
||||
> :point_up: **Note**: many recursive CTEs use the `UNION ALL` SQL operator. The query interface does not provide any Swift support for it, so you'll generally have to write SQL in your definitions of recursive CTEs.
|
||||
> **Note**: many recursive CTEs use the `UNION ALL` SQL operator. The query interface does not provide any Swift support for it, so you'll generally have to write SQL in your definitions of recursive CTEs.
|
||||
|
||||
|
||||
## Embed Common Table Expressions in Requests
|
||||
@@ -126,13 +126,13 @@ let request = Player
|
||||
.filter(Column("name") == playerNameCTE.all())
|
||||
```
|
||||
|
||||
> :point_up: **Note**: the `with(_:)` method can be called as many times as a there are common table expressions in your request.
|
||||
> **Note**: the `with(_:)` method can be called as many times as a there are common table expressions in your request.
|
||||
>
|
||||
> :point_up: **Note**: the `with(_:)` method can be called at any time, as all request methods: `Player.with(...).filter(...).with(...)`.
|
||||
> **Note**: the `with(_:)` method can be called at any time, as all request methods: `Player.with(...).filter(...).with(...)`.
|
||||
>
|
||||
> :point_up: **Note**: the `with(_:)` method replaces any previously embedded CTE that has the same table name. This allows you to embed the same CTE several times if you feel like it.
|
||||
> **Note**: the `with(_:)` method replaces any previously embedded CTE that has the same table name. This allows you to embed the same CTE several times if you feel like it.
|
||||
>
|
||||
> :point_up: **Note**: the `CommonTableExpression.all()` method builds a regular [query interface request] for the content of the CTE (like `SELECT * FROM <cte name>`, not to be mismatched with the request that was used to define the CTE). You can filter this request, sort it, etc, like all query interface requests:
|
||||
> **Note**: the `CommonTableExpression.all()` method builds a regular [query interface request] for the content of the CTE (like `SELECT * FROM <cte name>`, not to be mismatched with the request that was used to define the CTE). You can filter this request, sort it, etc, like all query interface requests:
|
||||
>
|
||||
> ```swift
|
||||
> cte.all().select(...).filter(...).group(...).order(...)
|
||||
@@ -234,7 +234,7 @@ Parent.including(optional: childAssociation)
|
||||
Parent.including(required: childAssociation)
|
||||
```
|
||||
|
||||
> :point_up: **Note**: common table expressions currently only define "to-one" associations, so the `including(all:)` joining method is unavailable.
|
||||
> **Note**: common table expressions currently only define "to-one" associations, so the `including(all:)` joining method is unavailable.
|
||||
|
||||
CTE associations are generally built with the `association(to:on:)` method, which needs:
|
||||
|
||||
@@ -251,7 +251,7 @@ let rightCTE = ...
|
||||
let association = LeftRecord.association(
|
||||
to: rightCTE,
|
||||
on: { left, right in
|
||||
left[Column("x")] = right[Column("y")]
|
||||
left[Column("x")] == right[Column("y")]
|
||||
})
|
||||
```
|
||||
|
||||
@@ -362,7 +362,9 @@ And we can fetch the data that feeds our application screen:
|
||||
|
||||
```swift
|
||||
|
||||
let chatInfos: [ChatInfos] = try dbQueue.read(request.fetchAll)
|
||||
let chatInfos: [ChatInfos] = try dbQueue.read { db in
|
||||
try request.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: **Tip**: the joining methods are generally type-safe: they won't allow you to join apples to oranges. This works when associations have a *precise* type. In this context, anonymous `CommonTableExpression` CTEs can work against type safety. When you want to define associations between several CTEs, and make sure the compiler will notice wrong uses of those associations, tag your common table expressions with an explicit type: `CommonTableExpression<SomeType>`.
|
||||
|
||||
@@ -1,537 +1,4 @@
|
||||
:twisted_rightwards_arrows: Concurrency
|
||||
=======================================
|
||||
|
||||
**GRDB helps your app deal with SQLite concurrency.**
|
||||
|
||||
If your app moves slow database jobs off the main thread, so that the user interface remains responsive, then this guide is for you. In the case of apps that share a database with other processes, such as an iOS app and its extensions, don't miss the dedicated [Sharing a Database] guide after this one.
|
||||
|
||||
**In all cases, and first and foremost, follow the [Concurrency Rules] right from the start.**
|
||||
|
||||
The other chapters cover, with more details, the fundamentals of SQLite concurrency, and how GRDB makes it manageable from your Swift code.
|
||||
|
||||
- [Concurrency Rules]
|
||||
- [Synchronous and Asynchronous Database Accesses]
|
||||
- [Safe and Unsafe Database Accesses]
|
||||
- [Differences between Database Queues and Pools]
|
||||
- [Concurrent Thinking]
|
||||
- [Advanced DatabasePool]
|
||||
- [Database Snapshots]
|
||||
- [Sharing a Database]
|
||||
|
||||
|
||||
## Concurrency Rules
|
||||
|
||||
**The two concurrency rules are strongly recommended practices.** They are all about SQLite, a robust and reliable database that takes great care of your data: don't miss an opportunity to put it on your side!
|
||||
|
||||
<a id="rule-1"></a>:point_up: **[Rule 1](#rule-1): Connect to any database file only once**
|
||||
|
||||
Open one single [DatabaseQueue] or [DatabasePool] per database file, for the whole duration of your use of the database. Not for the duration of _each_ database access, but really for the duration of _all_ database accesses to this file.
|
||||
|
||||
> *Why does this rule exist?* - Since SQLite does not support parallel writes, each [DatabaseQueue] and [DatabasePool] makes sure application threads perform writes one by one, without overlap.
|
||||
>
|
||||
> *Practical advice* - An app that uses a single database will connect only once. A document-based app will connect each time a document is opened, and disconnect when the document is closed. See the [demo apps] in order to see how to setup a UIKit or SwiftUI application for a single database.
|
||||
>
|
||||
> *What if you do not follow this rule?*
|
||||
>
|
||||
> - You will not be able to use the [Database Observation] features.
|
||||
> - You will see SQLite errors with code 5 ([SQLITE_BUSY]).
|
||||
|
||||
<a id="rule-2"></a>:point_up: **[Rule 2](#rule-2): Mind your transactions**
|
||||
|
||||
Database operations that are grouped in an SQLite transaction are guaranteed to be either fully saved on disk, or not at all. Read-only transactions have an interesting property as well: they guarantee a stable and immutable view of the database[^1], and do not see changes performed by eventual concurrent writes. In other words, transactions are the one and single tool that helps you enforce and rely on the important invariants of your database (such as "all credits have a matching debit", or "all books have an author").
|
||||
|
||||
**You are responsible**, in your Swift code, for delimiting transactions. You do so by grouping database accesses inside a pair of `{ db in ... }` brackets:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in /* Inside a transaction */ }
|
||||
try dbQueue.read { db in /* Inside a transaction */ }
|
||||
let observation = ValueObservation.tracking { db in /* Inside a transaction */ }`
|
||||
```
|
||||
|
||||
> *Why does this rule exist?* - Because GRDB and SQLite can not guess where to insert the transaction boundaries that protect the invariants of your database. This is your task.
|
||||
>
|
||||
> *Practical advice* - See below a correct example, as well as frequent mistakes you should avoid:
|
||||
>
|
||||
> <details><summary>Sample code</summary>
|
||||
>
|
||||
> In order to insert a money transfer in the database, in a way that enforces the "all credits have a matching debit" invariant, you can write:
|
||||
>
|
||||
> ```swift
|
||||
> // CORRECT: the "all credits have a matching debit" invariant is preserved.
|
||||
> do {
|
||||
> try dbQueue.write { db in
|
||||
> try credit.insert(db)
|
||||
> try debit.insert(db)
|
||||
> }
|
||||
> } catch {
|
||||
> print("An error occurred: \(error)")
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> A frequent mistake is to forget about grouping inside a pair of `{ db in ... }` brackets:
|
||||
>
|
||||
> ```swift
|
||||
> // INCORRECT. Related database operations are not grouped inside
|
||||
> // one transaction. The invariant is not enforced.
|
||||
> do {
|
||||
> try dbQueue.write { db in try credit.insert(db) }
|
||||
> try dbQueue.write { db in try debit.insert(db) }
|
||||
> } catch {
|
||||
> print("An error occurred: \(error)")
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> Another frequent mistake is to catch database errors at the wrong place:
|
||||
>
|
||||
> ```swift
|
||||
> // INCORRECT. Related database operations are not grouped inside
|
||||
> // one transaction, and a failed operation does not prevent
|
||||
> // subsequent operations from being performed. The invariant is
|
||||
> // not enforced.
|
||||
> do {
|
||||
> try dbQueue.write { db in try credit.insert(db) }
|
||||
> } catch {
|
||||
> print("An error occurred: \(error)")
|
||||
> }
|
||||
>
|
||||
> do {
|
||||
> try dbQueue.write { db in try debit.insert(db) }
|
||||
> } catch {
|
||||
> print("An error occurred: \(error)")
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> </details>
|
||||
>
|
||||
> *What if you do not follow this rule?* - You will see broken database invariants, at runtime, and when your apps wakes up after a crash. You may have a hard time fixing this mess.
|
||||
|
||||
|
||||
## Synchronous and Asynchronous Database Accesses
|
||||
|
||||
**You can access the database from any thread, in a synchronous or asynchronous way.**
|
||||
|
||||
:arrow_right: **A sync access blocks the current thread** until the database operations are completed:
|
||||
|
||||
```swift
|
||||
let playerCount = try dbQueue.read { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
|
||||
let newPlayerCount = try dbQueue.write { db -> Int in
|
||||
try Player(id: 12, name: "Arthur").insert(db)
|
||||
return try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
It is a programmer error to perform a sync access from any other database access (this restriction can be lifted: see [Safe and Unsafe Database Accesses]):
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// Fatal Error: Database methods are not reentrant.
|
||||
try dbQueue.write { db in ... }
|
||||
}
|
||||
```
|
||||
|
||||
:twisted_rightwards_arrows: **An async access does not block the current thread.** Instead, it notifies you when the database operations are completed. There are four ways to access the database asynchronously:
|
||||
|
||||
<details>
|
||||
<summary><b>Swift concurrency</b> (async/await)</summary>
|
||||
|
||||
[**:fire: EXPERIMENTAL**](../README.md#what-are-experimental-features) GRDB support for Swift concurrency requires Xcode 13.3.1+.
|
||||
|
||||
```swift
|
||||
let playerCount = try await dbQueue.read { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
|
||||
let newPlayerCount = try await dbQueue.write { db -> Int in
|
||||
try Player(id: 12, name: "Arthur").insert(db)
|
||||
return try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
Note the identical method names: `read`, `write`. The async version is only available in async Swift functions.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Combine publishers</b></summary>
|
||||
|
||||
```swift
|
||||
let playerCountPublisher = dbQueue.readPublisher { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
|
||||
let newPlayerCountPublisher = dbQueue.writePublisher { db -> Int in
|
||||
try Player(id: 12, name: "Arthur").insert(db)
|
||||
return try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
Those publishers do not access the database until they are subscribed. They complete on the main dispatch queue by default. See [GRDB ❤️ Combine].
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>RxSwift observables</b></summary>
|
||||
|
||||
```swift
|
||||
let playerCountObservable = dbQueue.rx.read { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
|
||||
let newPlayerCountObservable = dbQueue.rx.write { db -> Int in
|
||||
try Player(id: 12, name: "Arthur").insert(db)
|
||||
return try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
Those observables do not access the database until they are subscribed. They complete on the main dispatch queue by default. See the companion library [RxGRDB].
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Completion blocks</b></summary>
|
||||
|
||||
```swift
|
||||
dbQueue.asyncRead { (dbResult: Result<Database, Error>) in
|
||||
do {
|
||||
// Maybe read access could not be established
|
||||
let db = try dbResult.get()
|
||||
let playerCount = try Player.fetchCount(db)
|
||||
... // Handle playerCount
|
||||
} catch {
|
||||
... // Handle error
|
||||
}
|
||||
}
|
||||
|
||||
dbQueue.asyncWrite({ (db: Database) -> Int in
|
||||
try Player(id: 12, name: "Arthur").insert(db)
|
||||
return try Player.fetchCount(db)
|
||||
}, completion: { (db: Database, result: Result<Int, Error>) in
|
||||
// Handle write transaction result:
|
||||
switch result {
|
||||
case let .success(newPlayerCount):
|
||||
... // Handle newPlayerCount
|
||||
case let .failure(error):
|
||||
... // Handle error
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
During one async access, all individual database operations grouped inside (fetch, insert, etc.) are synchronous:
|
||||
|
||||
```swift
|
||||
// One asynchronous access...
|
||||
try await dbQueue.write { db in
|
||||
// ... always performs synchronous database operations:
|
||||
try Player(...).insert(db)
|
||||
try Player(...).insert(db)
|
||||
let players = try Player.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
This is true for all async techniques.
|
||||
|
||||
This prevents the database operations from various concurrent accesses from being interleaved, with disastrous consequences. For example, one access must not be able to issue a `COMMIT` statement in the middle of an unfinished concurrent write!
|
||||
|
||||
|
||||
## Safe and Unsafe Database Accesses
|
||||
|
||||
**You will generally use the safe database access methods `read` and `write`.** In this context, "safe" means that a database access is concurrency-friendly, because GRDB provides the following guarantees:
|
||||
|
||||
- <a id="guarantee-serialized-writes"></a>**[Serialized Writes]** - All writes performed by one [DatabaseQueue] or [DatabasePool] instance are serialized. *Why is it important?* - this guarantee prevents [SQLITE_BUSY] errors during concurrent writes.
|
||||
- <a id="guarantee-write-transactions"></a>**[Write Transactions]** - All writes are wrapped in a transaction. *Why is it important?* - concurrent reads can not see partial database updates (even reads performed by other processes).
|
||||
- <a id="guarantee-isolated-reads"></a>**[Isolated Reads]** - All reads are wrapped in a transaction. *Why is it important?* - an isolated read sees a stable and immutable state of the database[^1], and does not see changes performed by eventual concurrent writes (even writes performed by other processes).
|
||||
- <a id="guarantee-forbidden-writes"></a>**[Forbidden Writes]** - Inside a read access, all attempts to write raise an error. *Why is it important?* - this enforces the immutability of the database during a read.
|
||||
- <a id="guarantee-non-reentrancy"></a>**[Non-Reentrancy]** - Database accesses are not reentrant. *Why is it important?* - this reduces the opportunities for deadlocks, and fosters the clear transaction boundaries of the [second concurrency rule](#rule-2).
|
||||
|
||||
Some applications need to relax this safety net, in order to achieve specific SQLite operations. In this case, replace `read` and `write` with one of the methods below:
|
||||
|
||||
- **Write outside of any transaction**
|
||||
(Lifted guarantee: [Write Transactions])
|
||||
|
||||
```swift
|
||||
try dbQueue.writeWithoutTransaction { db in ... }
|
||||
```
|
||||
|
||||
`writeWithoutTransaction` is also available as an `async` function. You can also use `asyncWriteWithoutTransaction`.
|
||||
|
||||
- **Write outside of any transaction, and prevents concurrent reads**
|
||||
(Lifted guarantee: [Write Transactions])
|
||||
|
||||
```swift
|
||||
try dbQueue.barrierWriteWithoutTransaction { db in ... }
|
||||
```
|
||||
|
||||
The barrier write guarantees an exclusive access to the database: the method blocks until all concurrent database accesses are completed, reads and writes, and postpones all other accesses until it completes.
|
||||
|
||||
There is a known limitation: database accesses performed by other processes, and reads performed by [DatabaseSnapshot] are out of scope of this barrier, and can run concurrently with the barrier.
|
||||
|
||||
You will use this method, for example, when you [change the password](../README.md#changing-the-passphrase-of-an-encrypted-database) of an encrypted database.
|
||||
|
||||
`barrierWriteWithoutTransaction` is also available as an `async` function. You can also use `asyncBarrierWriteWithoutTransaction`.
|
||||
|
||||
- **Reentrant write outside of any transaction**
|
||||
(Lifted guarantees: [Write Transactions], [Non-Reentrancy])
|
||||
|
||||
```swift
|
||||
try dbQueue.unsafeReentrantWrite { db in ... }
|
||||
```
|
||||
|
||||
Reentrant writes can be performed from any other database access:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// No fatal error
|
||||
try dbQueue.unsafeReentrantWrite { db in ... }
|
||||
}
|
||||
```
|
||||
|
||||
`unsafeReentrantWrite` has no async version.
|
||||
|
||||
- **Read outside of any transaction**
|
||||
(Lifted guarantees: [Isolated Reads], [Forbidden Writes])
|
||||
|
||||
```swift
|
||||
try dbQueue.unsafeRead { db in ... }
|
||||
```
|
||||
|
||||
`unsafeRead` is also available as an `async` function.
|
||||
|
||||
- **Reentrant read, outside of any transaction**
|
||||
(Lifted guarantees: [Isolated Reads], [Forbidden Writes], [Non-Reentrancy])
|
||||
|
||||
```swift
|
||||
try dbQueue.unsafeReentrantRead { db in ... }
|
||||
```
|
||||
|
||||
Reentrant reads can be performed from any other database access:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// No fatal error
|
||||
try dbQueue.unsafeReentrantRead { db in ... }
|
||||
}
|
||||
```
|
||||
|
||||
`unsafeReentrantRead` has no async version.
|
||||
|
||||
:point_up: **By using one of the methods above, you become responsible of the thread-safety of your application.** Please understand the consequences of lifting each concurrency guarantee. Some guarantees can also be restored at your convenience:
|
||||
|
||||
- The [Write Transactions] and [Isolated Reads] guarantees can be restored at any point, by opening an [explicit transaction](../README.md#transactions-and-savepoints). For example:
|
||||
|
||||
```swift
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
try db.inTransaction {
|
||||
...
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- The [Forbidden Writes] guarantee can only be lifted with [DatabaseQueue]. It can be restored with [`PRAGMA query_only`](https://www.sqlite.org/pragma.html#pragma_query_only).
|
||||
|
||||
|
||||
## Differences between Database Queues and Pools
|
||||
|
||||
Despite the common [guarantees](#safe-and-unsafe-database-accesses) and [rules](#concurrency-rules) shared by database queues and pools, those two database accessors don't have the same behavior.
|
||||
|
||||
[DatabaseQueue] opens a single database connection, and serializes all database accesses, reads, and writes. There is never more than one thread that uses the database. In the image below, we see how three threads can see the database as time passes:
|
||||
|
||||

|
||||
|
||||
[DatabasePool] manages a pool of several database connections, and allows concurrent reads and writes thanks to the [WAL mode](https://www.sqlite.org/wal.html). A database pool serializes all writes (the [Serialized Writes] guarantee). Reads are isolated so that they don't see changes performed by other threads (the [Isolated Reads] guarantee). This gives a very different picture:
|
||||
|
||||

|
||||
|
||||
See how, with database pools, two reads can see different database states at the same time. This may look scary! Please see the next [Concurrent Thinking] chapter below for a relief.
|
||||
|
||||
|
||||
## Concurrent Thinking
|
||||
|
||||
Despite their [differences](#differences-between-database-queues-and-pools), you can write robust code that works equally well with both database queues and pools.
|
||||
|
||||
This allows your app to switch between queues and pools, at your convenience:
|
||||
|
||||
- The [demo applications] share the same database code for the on-disk pool that feeds the app, and the in-memory queue that feeds tests and SwiftUI previews. This makes sure tests and previews run fast, without any temporary file, with the same behavior as the app.
|
||||
- Applications that perform slow write transactions (when saving a lot of data from a remote server, for example) may want to replace their queue with a pool so that the reads that feed their user interface can run in parallel.
|
||||
|
||||
All you need is a little "concurrent thinking", based on those two basic facts:
|
||||
|
||||
- You are sure, when you perform a write access, that you deal with the latest database state on disk. This is enforced by SQLite, which simply can't perform parallel writes, and by GRDB database queues and pools, which make sure [only one thread can write](#guarantee-serialized-writes). As for writes performed by other processes, they can only trigger [SQLITE_BUSY] errors [that you can handle](SharingADatabase.md).
|
||||
|
||||
- Whenever you extract some data from a database access, immediately consider it as _stale_. It is stale, whether you use a database queue or a database pool. It is stale because nothing prevents other application threads or processes from overwriting the value you have just fetched:
|
||||
|
||||
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/Images/TwoCookiesLeft.jpg" width="50%">
|
||||
|
||||
```swift
|
||||
// or dbQueue.write, for that matter
|
||||
let cookieCount = dbPool.read { db in
|
||||
try Cookie.fetchCount(db)
|
||||
}
|
||||
|
||||
// At this point, the number of cookies on disk
|
||||
// may have already changed.
|
||||
print("We have \(cookieCount) cookies left")
|
||||
```
|
||||
|
||||
Does this mean you can't rely on anything? Of course not:
|
||||
|
||||
- If you intend to display the database content on screen, use [ValueObservation]: it always eventually notifies the latest state of the database. You won't display stale values for a long time [^2].
|
||||
|
||||
- As said above, the moment of truth is the next write access!
|
||||
|
||||
|
||||
## Advanced DatabasePool
|
||||
|
||||
[DatabasePool] is very concurrent, since all reads can run in parallel, and can even run during write operations. But writes are still serialized: at any given point in time, there is no more than a single thread that is writing into the database.
|
||||
|
||||
When your application modifies the database, and then reads some value that depends on those modifications, you may want to avoid blocking concurrent writes longer than necessary:
|
||||
|
||||
```swift
|
||||
try dbPool.write { db in
|
||||
// Increment the number of players
|
||||
try Player(...).insert(db)
|
||||
try Player(...).insert(db)
|
||||
|
||||
// Read the number of players. Concurrent writes are blocked :-(
|
||||
let newPlayerCount = try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
:arrow_right: The solution is the `concurrentRead` method. It must be called from within a write access, outside of any transaction. It returns a *future value* which you consume any time later, with the `wait()` method.
|
||||
|
||||
```swift
|
||||
let future: DatabaseFuture<Int> = try dbPool.writeWithoutTransaction { db in
|
||||
// Increment the number of players
|
||||
try db.inTransaction {
|
||||
try Player(...).insert(db)
|
||||
try Player(...).insert(db)
|
||||
return .commit
|
||||
}
|
||||
|
||||
// <- Not in a transaction here
|
||||
let future = dbPool.concurrentRead { db
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
return future
|
||||
}
|
||||
// <- Concurrent writes can be performed :-)
|
||||
|
||||
// Wait and handle newPlayerCount
|
||||
let newPlayerCount = try future.wait()
|
||||
```
|
||||
|
||||
:twisted_rightwards_arrows: The async version of `concurrentRead` is `asyncConcurrentRead`:
|
||||
|
||||
```swift
|
||||
try dbPool.writeWithoutTransaction { db in
|
||||
// Increment the number of players
|
||||
try db.inTransaction {
|
||||
try Player(...).insert(db)
|
||||
try Player(...).insert(db)
|
||||
return .commit
|
||||
}
|
||||
|
||||
// <- Not in a transaction here
|
||||
dbPool.asyncConcurrentRead { dbResult in
|
||||
do {
|
||||
// Maybe read access could not be established
|
||||
let db = try dbResult.get()
|
||||
let newPlayerCount = try Player.fetchCount(db)
|
||||
// Handle newPlayerCount
|
||||
} catch {
|
||||
// Handle error
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`concurrentRead` and `asyncConcurrentRead` block until they can guarantee their closure argument an isolated access to the database, in the exact state left by the last transaction. It then asynchronously executes this closure.
|
||||
|
||||
In the illustration below, the striped band shows the delay needed for the reading thread to acquire isolation. Until then, no other thread can write:
|
||||
|
||||

|
||||
|
||||
[Transaction Observers](../README.md#transactionobserver-protocol) can also use those methods in their `databaseDidCommit` method, in order to process database changes without blocking other threads that want to write into the database.
|
||||
|
||||
|
||||
## Database Snapshots
|
||||
|
||||
**[DatabasePool] can take snapshots.** A database snapshot sees an unchanging database content, as it existed at the moment it was created.
|
||||
|
||||
"Unchanging" means that a snapshot never sees any database modifications during all its lifetime. And yet it doesn't prevent database updates. This "magic" is made possible by SQLite's WAL mode (see [Isolation In SQLite](https://sqlite.org/isolation.html)).
|
||||
|
||||
```swift
|
||||
let snapshot = try dbPool.makeSnapshot()
|
||||
```
|
||||
|
||||
You can create as many snapshots as you need, regardless of the [maximum number of readers](../README.md#database-configuration) in the pool. A snapshot database connection is closed when the snapshot is deinitialized.
|
||||
|
||||
**A snapshot can be used from any thread.** It has the same [synchronous and asynchronous reading methods](#synchronous-and-asynchronous-database-accesses) as database queues and pools:
|
||||
|
||||
```swift
|
||||
let playerCount = try snapshot.read { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
When you want to control the latest committed changes seen by a snapshot, create the snapshot from within a write, outside of any transaction:
|
||||
|
||||
```swift
|
||||
let snapshot1 = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshot in
|
||||
try db.inTransaction {
|
||||
// delete all players
|
||||
try Player.deleteAll()
|
||||
return .commit
|
||||
}
|
||||
|
||||
// <- not in a transaction here
|
||||
return dbPool.makeSnapshot()
|
||||
}
|
||||
// <- Other threads may modify the database here
|
||||
let snapshot2 = try dbPool.makeSnapshot()
|
||||
|
||||
try snapshot1.read { db in
|
||||
// Guaranteed to be zero
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
|
||||
try snapshot2.read { db in
|
||||
// Could be anything
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
> :point_up: **Note**: snapshots currently serialize all database accesses. In the future, snapshots may allow concurrent reads.
|
||||
|
||||
[^1]: This immutable view of the database is called [snapshot isolation](https://www.sqlite.org/isolation.html).
|
||||
|
||||
[^2]: After the database has been changed on disk, GRDB has to fetch the fresh value, and then hop to the main thread. Only then your screen can be updated.
|
||||
|
||||
[Concurrency Rules]: #concurrency-rules
|
||||
[Synchronous and Asynchronous Database Accesses]: #synchronous-and-asynchronous-database-accesses
|
||||
[Safe and Unsafe Database Accesses]: #safe-and-unsafe-database-accesses
|
||||
[Differences between Database Queues and Pools]: #differences-between-database-queues-and-pools
|
||||
[Concurrent Thinking]: #concurrent-thinking
|
||||
[Advanced DatabasePool]: #advanced-databasepool
|
||||
[Database Snapshots]: #database-snapshots
|
||||
[DatabaseQueue]: ../README.md#database-queues
|
||||
[DatabasePool]: ../README.md#database-pools
|
||||
[DatabaseSnapshot]: #database-snapshots
|
||||
[demo apps]: DemoApps
|
||||
[Database Observation]: ../README.md#database-changes-observation
|
||||
[SQLITE_BUSY]: https://www.sqlite.org/rescode.html#busy
|
||||
[Sharing a Database]: SharingADatabase.md
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[GRDB ❤️ Combine]: Combine.md
|
||||
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
|
||||
[Serialized Writes]: #guarantee-serialized-writes
|
||||
[Write Transactions]: #guarantee-write-transactions
|
||||
[Isolated Reads]: #guarantee-isolated-reads
|
||||
[Forbidden Writes]: #guarantee-forbidden-writes
|
||||
[Non-Reentrancy]: #guarantee-non-reentrancy
|
||||
[demo applications]: DemoApps
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
|
||||
@@ -3,9 +3,9 @@ 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.37.2](https://www.sqlite.org/changes.html).**
|
||||
**You can build GRDB with a custom build of [SQLite 3.44.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).
|
||||
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](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver).
|
||||
|
||||
GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfalling/SQLiteLib), which uses the same SQLite configuration as the one used by Apple in its operating systems, and lets you add extra compilation options that leverage the features you need.
|
||||
|
||||
@@ -21,7 +21,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
|
||||
2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5`, `SQLITE_ENABLE_PREUPDATE_HOOK`.
|
||||
|
||||
It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](../README.md#valueobservation) when you use a [Database Pool](../README.md#database-pools).
|
||||
It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) when you use a [Database Pool](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool).
|
||||
|
||||
3. Create a folder named `GRDBCustomSQLite` somewhere in your project directory.
|
||||
|
||||
@@ -111,9 +111,9 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
|
||||
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**.
|
||||
6. Add the `GRDBCustom` target in the **Target Dependencies** section of the **Build Phases** tab of your **application target**.
|
||||
|
||||
7. Add the `GRDBCustomSQLite.framework` from the targeted platform to the **Embedded Binaries** section of the **General** tab of your **application target**.
|
||||
7. Add the `GRDBCustom.framework` from the targeted platform to the **Embedded Binaries** section of the **General** tab of your **application target**.
|
||||
|
||||
8. Add a Run Script phase for your target in the **Pre-actions** section of the **Build** tab of your **application scheme**:
|
||||
|
||||
|
||||
@@ -26,7 +26,6 @@
|
||||
567C3E7A2520BB650011F6E9 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */; };
|
||||
56B6D1092619EC1B003CC455 /* PlayerRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D1082619EC1B003CC455 /* PlayerRequest.swift */; };
|
||||
56F8A13527359A5A0011ACBE /* GRDB in Frameworks */ = {isa = PBXBuildFile; productRef = 56F8A13427359A5A0011ACBE /* GRDB */; };
|
||||
78E2F9E6261EEC22005D1F7F /* GRDBAsyncDemoUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78E2F9E5261EEC22005D1F7F /* GRDBAsyncDemoUITests.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
@@ -37,13 +36,6 @@
|
||||
remoteGlobalIDString = 567C3E152520B6DE0011F6E9;
|
||||
remoteInfo = GRDBAsyncDemo;
|
||||
};
|
||||
78E2F9E8261EEC22005D1F7F /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 567C3E0E2520B6DE0011F6E9 /* Project object */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 567C3E152520B6DE0011F6E9;
|
||||
remoteInfo = GRDBAsyncDemo;
|
||||
};
|
||||
/* End PBXContainerItemProxy section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
@@ -82,9 +74,6 @@
|
||||
567C3E782520BB650011F6E9 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
|
||||
56B6D1082619EC1B003CC455 /* PlayerRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequest.swift; sourceTree = "<group>"; };
|
||||
56F8A12E27359A350011ACBE /* GRDB.swift */ = {isa = PBXFileReference; lastKnownFileType = folder; name = GRDB.swift; path = ../../..; sourceTree = "<group>"; };
|
||||
78E2F9E3261EEC22005D1F7F /* GRDBAsyncDemoUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBAsyncDemoUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
78E2F9E5261EEC22005D1F7F /* GRDBAsyncDemoUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GRDBAsyncDemoUITests.swift; sourceTree = "<group>"; };
|
||||
78E2F9E7261EEC22005D1F7F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
@@ -104,13 +93,6 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
78E2F9E0261EEC22005D1F7F /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
@@ -140,7 +122,6 @@
|
||||
children = (
|
||||
567C3E182520B6DE0011F6E9 /* GRDBAsyncDemo */,
|
||||
56026C9925B8A7D000D1DF3F /* GRDBAsyncDemoTests */,
|
||||
78E2F9E4261EEC22005D1F7F /* GRDBAsyncDemoUITests */,
|
||||
567C3E172520B6DE0011F6E9 /* Products */,
|
||||
567C3E4D2520B70E0011F6E9 /* Frameworks */,
|
||||
56F8A12E27359A350011ACBE /* GRDB.swift */,
|
||||
@@ -152,7 +133,6 @@
|
||||
children = (
|
||||
567C3E162520B6DE0011F6E9 /* GRDBAsyncDemo.app */,
|
||||
56026C9825B8A7D000D1DF3F /* GRDBAsyncDemoTests.xctest */,
|
||||
78E2F9E3261EEC22005D1F7F /* GRDBAsyncDemoUITests.xctest */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
@@ -200,15 +180,6 @@
|
||||
path = Views;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
78E2F9E4261EEC22005D1F7F /* GRDBAsyncDemoUITests */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
78E2F9E5261EEC22005D1F7F /* GRDBAsyncDemoUITests.swift */,
|
||||
78E2F9E7261EEC22005D1F7F /* Info.plist */,
|
||||
);
|
||||
path = GRDBAsyncDemoUITests;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
@@ -253,30 +224,13 @@
|
||||
productReference = 567C3E162520B6DE0011F6E9 /* GRDBAsyncDemo.app */;
|
||||
productType = "com.apple.product-type.application";
|
||||
};
|
||||
78E2F9E2261EEC22005D1F7F /* GRDBAsyncDemoUITests */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 78E2F9F3261EEC22005D1F7F /* Build configuration list for PBXNativeTarget "GRDBAsyncDemoUITests" */;
|
||||
buildPhases = (
|
||||
78E2F9DF261EEC22005D1F7F /* Sources */,
|
||||
78E2F9E0261EEC22005D1F7F /* Frameworks */,
|
||||
78E2F9E1261EEC22005D1F7F /* Resources */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
78E2F9E9261EEC22005D1F7F /* PBXTargetDependency */,
|
||||
);
|
||||
name = GRDBAsyncDemoUITests;
|
||||
productName = GRDBAsyncDemoUITests;
|
||||
productReference = 78E2F9E3261EEC22005D1F7F /* GRDBAsyncDemoUITests.xctest */;
|
||||
productType = "com.apple.product-type.bundle.ui-testing";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
567C3E0E2520B6DE0011F6E9 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = YES;
|
||||
LastSwiftUpdateCheck = 1250;
|
||||
LastUpgradeCheck = 1200;
|
||||
TargetAttributes = {
|
||||
@@ -287,10 +241,6 @@
|
||||
567C3E152520B6DE0011F6E9 = {
|
||||
CreatedOnToolsVersion = 12.0;
|
||||
};
|
||||
78E2F9E2261EEC22005D1F7F = {
|
||||
CreatedOnToolsVersion = 12.5;
|
||||
TestTargetID = 567C3E152520B6DE0011F6E9;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = 567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBAsyncDemo" */;
|
||||
@@ -311,7 +261,6 @@
|
||||
targets = (
|
||||
567C3E152520B6DE0011F6E9 /* GRDBAsyncDemo */,
|
||||
56026C9725B8A7D000D1DF3F /* GRDBAsyncDemoTests */,
|
||||
78E2F9E2261EEC22005D1F7F /* GRDBAsyncDemoUITests */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
@@ -335,13 +284,6 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
78E2F9E1261EEC22005D1F7F /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
@@ -372,14 +314,6 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
78E2F9DF261EEC22005D1F7F /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
78E2F9E6261EEC22005D1F7F /* GRDBAsyncDemoUITests.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXTargetDependency section */
|
||||
@@ -392,11 +326,6 @@
|
||||
isa = PBXTargetDependency;
|
||||
productRef = 56F8A13027359A540011ACBE /* GRDB */;
|
||||
};
|
||||
78E2F9E9261EEC22005D1F7F /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
target = 567C3E152520B6DE0011F6E9 /* GRDBAsyncDemo */;
|
||||
targetProxy = 78E2F9E8261EEC22005D1F7F /* PBXContainerItemProxy */;
|
||||
};
|
||||
/* End PBXTargetDependency section */
|
||||
|
||||
/* Begin PBXVariantGroup section */
|
||||
@@ -425,6 +354,7 @@
|
||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
INFOPLIST_FILE = GRDBAsyncDemoTests/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -444,6 +374,7 @@
|
||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
INFOPLIST_FILE = GRDBAsyncDemoTests/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -583,7 +514,7 @@
|
||||
DEVELOPMENT_TEAM = "";
|
||||
ENABLE_PREVIEWS = YES;
|
||||
INFOPLIST_FILE = GRDBAsyncDemo/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -605,7 +536,7 @@
|
||||
DEVELOPMENT_TEAM = "";
|
||||
ENABLE_PREVIEWS = YES;
|
||||
INFOPLIST_FILE = GRDBAsyncDemo/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -617,44 +548,6 @@
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
78E2F9EA261EEC22005D1F7F /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_TEAM = "";
|
||||
INFOPLIST_FILE = GRDBAsyncDemoUITests/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.groue.GRDBAsyncDemoUITests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_TARGET_NAME = GRDBAsyncDemo;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
78E2F9EB261EEC22005D1F7F /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_TEAM = "";
|
||||
INFOPLIST_FILE = GRDBAsyncDemoUITests/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.groue.GRDBAsyncDemoUITests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_TARGET_NAME = GRDBAsyncDemo;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
@@ -685,15 +578,6 @@
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
78E2F9F3261EEC22005D1F7F /* Build configuration list for PBXNativeTarget "GRDBAsyncDemoUITests" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
78E2F9EA261EEC22005D1F7F /* Debug */,
|
||||
78E2F9EB261EEC22005D1F7F /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
|
||||
/* Begin XCRemoteSwiftPackageReference section */
|
||||
@@ -702,7 +586,7 @@
|
||||
repositoryURL = "https://github.com/groue/GRDBQuery";
|
||||
requirement = {
|
||||
kind = upToNextMajorVersion;
|
||||
minimumVersion = 0.1.0;
|
||||
minimumVersion = 0.6.0;
|
||||
};
|
||||
};
|
||||
/* End XCRemoteSwiftPackageReference section */
|
||||
|
||||
+11
-13
@@ -1,16 +1,14 @@
|
||||
{
|
||||
"object": {
|
||||
"pins": [
|
||||
{
|
||||
"package": "GRDBQuery",
|
||||
"repositoryURL": "https://github.com/groue/GRDBQuery",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "4301166cd2aee9ce37b4057c9a58f5cc3bbeae06",
|
||||
"version": "0.1.0"
|
||||
}
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "grdbquery",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/groue/GRDBQuery",
|
||||
"state" : {
|
||||
"revision" : "a6c46dd38ecf11a5c37732870dc03a384d582fba",
|
||||
"version" : "0.9.0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 1
|
||||
}
|
||||
],
|
||||
"version" : 2
|
||||
}
|
||||
+10
-12
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1230"
|
||||
LastUpgradeVersion = "1400"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -29,7 +29,8 @@
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
skipped = "NO"
|
||||
parallelizable = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56026C9725B8A7D000D1DF3F"
|
||||
@@ -38,16 +39,6 @@
|
||||
ReferencedContainer = "container:GRDBAsyncDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "78E2F9E2261EEC22005D1F7F"
|
||||
BuildableName = "GRDBAsyncDemoUITests.xctest"
|
||||
BlueprintName = "GRDBAsyncDemoUITests"
|
||||
ReferencedContainer = "container:GRDBAsyncDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
@@ -70,6 +61,13 @@
|
||||
ReferencedContainer = "container:GRDBAsyncDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
<EnvironmentVariables>
|
||||
<EnvironmentVariable
|
||||
key = "SQL_TRACE"
|
||||
value = "1"
|
||||
isEnabled = "NO">
|
||||
</EnvironmentVariable>
|
||||
</EnvironmentVariables>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
|
||||
@@ -1,13 +1,30 @@
|
||||
import Foundation
|
||||
import GRDB
|
||||
import os.log
|
||||
|
||||
/// AppDatabase lets the application access the database.
|
||||
/// A database of players.
|
||||
///
|
||||
/// It applies the pratices recommended at
|
||||
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
/// You create an `AppDatabase` with a connection to an SQLite database
|
||||
/// (see <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>).
|
||||
///
|
||||
/// Create those connections with a configuration returned from
|
||||
/// `AppDatabase/makeConfiguration(_:)`.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create an in-memory AppDatabase
|
||||
/// let config = AppDatabase.makeConfiguration()
|
||||
/// let dbQueue = try DatabaseQueue(configuration: config)
|
||||
/// let appDatabase = try AppDatabase(dbQueue)
|
||||
/// ```
|
||||
struct AppDatabase {
|
||||
/// Creates an `AppDatabase`, and make sure the database schema is ready.
|
||||
init(_ dbWriter: DatabaseWriter) throws {
|
||||
/// Creates an `AppDatabase`, and makes sure the database schema
|
||||
/// is ready.
|
||||
///
|
||||
/// - important: Create the `DatabaseWriter` with a configuration
|
||||
/// returned by ``makeConfiguration(_:)``.
|
||||
init(_ dbWriter: any DatabaseWriter) throws {
|
||||
self.dbWriter = dbWriter
|
||||
try migrator.migrate(dbWriter)
|
||||
}
|
||||
@@ -17,24 +34,73 @@ struct AppDatabase {
|
||||
/// Application can use a `DatabasePool`, while SwiftUI previews and tests
|
||||
/// can use a fast in-memory `DatabaseQueue`.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections>
|
||||
private let dbWriter: DatabaseWriter
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
|
||||
private let dbWriter: any DatabaseWriter
|
||||
}
|
||||
|
||||
// MARK: - Database Configuration
|
||||
|
||||
extension AppDatabase {
|
||||
private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
|
||||
|
||||
/// Returns a database configuration suited for `PlayerRepository`.
|
||||
///
|
||||
/// SQL statements are logged if the `SQL_TRACE` environment variable
|
||||
/// is set.
|
||||
///
|
||||
/// - parameter base: A base configuration.
|
||||
public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration {
|
||||
var config = base
|
||||
|
||||
// An opportunity to add required custom SQL functions or
|
||||
// collations, if needed:
|
||||
// config.prepareDatabase { db in
|
||||
// db.add(function: ...)
|
||||
// }
|
||||
|
||||
// Log SQL statements if the `SQL_TRACE` environment variable is set.
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/trace(options:_:)>
|
||||
if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil {
|
||||
config.prepareDatabase { db in
|
||||
db.trace {
|
||||
// It's ok to log statements publicly. Sensitive
|
||||
// information (statement arguments) are not logged
|
||||
// unless config.publicStatementArguments is set
|
||||
// (see below).
|
||||
os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
// Protect sensitive information by enabling verbose debugging in
|
||||
// DEBUG builds only.
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/publicstatementarguments>
|
||||
config.publicStatementArguments = true
|
||||
#endif
|
||||
|
||||
return config
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Database Migrations
|
||||
|
||||
extension AppDatabase {
|
||||
/// The DatabaseMigrator that defines the database schema.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md>
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
|
||||
private var migrator: DatabaseMigrator {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
#if DEBUG
|
||||
#if DEBUG
|
||||
// Speed up development by nuking the database when migrations change
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md#the-erasedatabaseonschemachange-option
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
#endif
|
||||
#endif
|
||||
|
||||
migrator.registerMigration("createPlayer") { db in
|
||||
// Create a table
|
||||
// See https://github.com/groue/GRDB.swift#create-tables
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema>
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
@@ -52,6 +118,7 @@ struct AppDatabase {
|
||||
}
|
||||
|
||||
// MARK: - Database Access: Writes
|
||||
// The write methods execute invariant-preserving database transactions.
|
||||
|
||||
extension AppDatabase {
|
||||
/// A validation error that prevents some players from being saved into
|
||||
@@ -127,8 +194,8 @@ extension AppDatabase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static let uiTestPlayers = [
|
||||
|
||||
private static let uiTestPlayers = [
|
||||
Player(id: nil, name: "Arthur", score: 5),
|
||||
Player(id: nil, name: "Barbara", score: 6),
|
||||
Player(id: nil, name: "Craig", score: 8),
|
||||
@@ -137,7 +204,7 @@ extension AppDatabase {
|
||||
Player(id: nil, name: "Frederik", score: 2),
|
||||
Player(id: nil, name: "Gilbert", score: 7),
|
||||
Player(id: nil, name: "Henriette", score: 3)]
|
||||
|
||||
|
||||
func createPlayersForUITests() throws {
|
||||
try dbWriter.write { db in
|
||||
try AppDatabase.uiTestPlayers.forEach { player in
|
||||
@@ -162,7 +229,7 @@ extension AppDatabase {
|
||||
// reading methods.
|
||||
extension AppDatabase {
|
||||
/// Provides a read-only access to the database
|
||||
var databaseReader: DatabaseReader {
|
||||
var reader: DatabaseReader {
|
||||
dbWriter
|
||||
}
|
||||
}
|
||||
@@ -5,17 +5,12 @@ import SwiftUI
|
||||
struct GRDBAsyncDemoApp: App {
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
AppView().environment(\.appDatabase, .shared)
|
||||
AppView().appDatabase(.shared)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Give SwiftUI access to the database
|
||||
//
|
||||
// Define a new environment key that grants access to an AppDatabase.
|
||||
//
|
||||
// The technique is documented at
|
||||
// <https://developer.apple.com/documentation/swiftui/environmentkey>.
|
||||
|
||||
private struct AppDatabaseKey: EnvironmentKey {
|
||||
static var defaultValue: AppDatabase { .empty() }
|
||||
@@ -28,13 +23,10 @@ extension EnvironmentValues {
|
||||
}
|
||||
}
|
||||
|
||||
// In this demo app, views observe the database with the @Query property
|
||||
// wrapper, defined in the GRDBQuery package. Its documentation recommends to
|
||||
// define a dedicated initializer for `appDatabase` access, so we comply:
|
||||
|
||||
extension Query where Request.DatabaseContext == AppDatabase {
|
||||
/// Convenience initializer for requests that feed from `AppDatabase`.
|
||||
init(_ request: Request) {
|
||||
self.init(request, in: \.appDatabase)
|
||||
extension View {
|
||||
func appDatabase(_ appDatabase: AppDatabase) -> some View {
|
||||
self
|
||||
.environment(\.appDatabase, appDatabase)
|
||||
.databaseContext(.readOnly { appDatabase.reader })
|
||||
}
|
||||
}
|
||||
@@ -7,26 +7,31 @@ extension AppDatabase {
|
||||
|
||||
private static func makeShared() -> AppDatabase {
|
||||
do {
|
||||
// Pick a folder for storing the SQLite database, as well as
|
||||
// the various temporary files created during normal database
|
||||
// operations (https://sqlite.org/tempfiles.html).
|
||||
let fileManager = FileManager()
|
||||
let folderURL = try fileManager
|
||||
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
.appendingPathComponent("database", isDirectory: true)
|
||||
|
||||
// Apply recommendations from
|
||||
// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
|
||||
//
|
||||
// Create the "Application Support/Database" directory if needed
|
||||
let fileManager = FileManager.default
|
||||
let appSupportURL = try fileManager.url(
|
||||
for: .applicationSupportDirectory, in: .userDomainMask,
|
||||
appropriateFor: nil, create: true)
|
||||
let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true)
|
||||
|
||||
// Support for tests: delete the database if requested
|
||||
if CommandLine.arguments.contains("-reset") {
|
||||
try? fileManager.removeItem(at: folderURL)
|
||||
try? fileManager.removeItem(at: directoryURL)
|
||||
}
|
||||
|
||||
// Create the database folder if needed
|
||||
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
|
||||
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
|
||||
|
||||
// Connect to a database on disk
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
let dbURL = folderURL.appendingPathComponent("db.sqlite")
|
||||
let dbPool = try DatabasePool(path: dbURL.path)
|
||||
// Open or create the database
|
||||
let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
|
||||
NSLog("Database stored at \(databaseURL.path)")
|
||||
let dbPool = try DatabasePool(
|
||||
path: databaseURL.path,
|
||||
// Use default AppDatabase configuration
|
||||
configuration: AppDatabase.makeConfiguration())
|
||||
|
||||
// Create the AppDatabase
|
||||
let appDatabase = try AppDatabase(dbPool)
|
||||
@@ -58,8 +63,8 @@ extension AppDatabase {
|
||||
/// Creates an empty database for SwiftUI previews
|
||||
static func empty() -> AppDatabase {
|
||||
// Connect to an in-memory database
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
let dbQueue = DatabaseQueue()
|
||||
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
|
||||
let dbQueue = try! DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
return try! AppDatabase(dbQueue)
|
||||
}
|
||||
|
||||
|
||||
@@ -60,8 +60,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
}
|
||||
|
||||
/// Updates a player id after it has been inserted in the database.
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,9 +69,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
|
||||
/// Define some player requests used by the application.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
extension DerivableRequest where RowDecoder == Player {
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
|
||||
extension DerivableRequest<Player> {
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
/// For example:
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import Combine
|
||||
import GRDB
|
||||
import GRDBQuery
|
||||
|
||||
@@ -14,37 +13,18 @@ import GRDBQuery
|
||||
/// List(players) { player in ... )
|
||||
/// }
|
||||
/// }
|
||||
struct PlayerRequest: Queryable {
|
||||
struct PlayerRequest: ValueObservationQueryable {
|
||||
enum Ordering {
|
||||
case byScore
|
||||
case byName
|
||||
}
|
||||
|
||||
static var defaultValue: [Player] { [] }
|
||||
|
||||
/// The ordering used by the player request.
|
||||
var ordering: Ordering
|
||||
|
||||
// MARK: - Queryable Implementation
|
||||
|
||||
static var defaultValue: [Player] { [] }
|
||||
|
||||
func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> {
|
||||
// Build the publisher from the general-purpose read-only access
|
||||
// granted by `appDatabase.databaseReader`.
|
||||
// Some apps will prefer to call a dedicated method of `appDatabase`.
|
||||
ValueObservation
|
||||
.tracking(fetchValue(_:))
|
||||
.publisher(
|
||||
in: appDatabase.databaseReader,
|
||||
// The `.immediate` scheduling feeds the view right on
|
||||
// subscription, and avoids an undesired animation when the
|
||||
// application starts.
|
||||
scheduling: .immediate)
|
||||
.eraseToAnyPublisher()
|
||||
}
|
||||
|
||||
// This method is not required by Queryable, but it makes it easier
|
||||
// to test PlayerRequest.
|
||||
func fetchValue(_ db: Database) throws -> [Player] {
|
||||
func fetch(_ db: Database) throws -> [Player] {
|
||||
switch ordering {
|
||||
case .byScore:
|
||||
return try Player.all().orderedByScore().fetchAll(db)
|
||||
|
||||
@@ -43,7 +43,7 @@ struct AppView: View {
|
||||
stopEditing()
|
||||
}))
|
||||
.toolbar { toolbarContent }
|
||||
.onChange(of: players) { players in
|
||||
.onChange(of: players) {
|
||||
if players.isEmpty {
|
||||
stopEditing()
|
||||
}
|
||||
@@ -141,14 +141,14 @@ private struct ToggleOrderingButton: View {
|
||||
}
|
||||
}
|
||||
|
||||
struct AppView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
Group {
|
||||
// Preview the default, empty database
|
||||
AppView()
|
||||
|
||||
// Preview a database of random players
|
||||
AppView().environment(\.appDatabase, .random())
|
||||
}
|
||||
}
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview("Empty") {
|
||||
// Preview the default, empty database
|
||||
AppView()
|
||||
}
|
||||
|
||||
#Preview("Populated") {
|
||||
// Preview a database of random players
|
||||
AppView().appDatabase(.random())
|
||||
}
|
||||
@@ -43,8 +43,8 @@ struct PlayerCreationView: View {
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerCreationSheet_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
PlayerCreationView()
|
||||
}
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview {
|
||||
PlayerCreationView()
|
||||
}
|
||||
@@ -15,7 +15,7 @@ struct PlayerEditionView: View {
|
||||
|
||||
var body: some View {
|
||||
PlayerFormView(form: $form)
|
||||
.onChange(of: isPresented) { isPresented in
|
||||
.onChange(of: isPresented) {
|
||||
// Save when back button is pressed
|
||||
if !isPresented {
|
||||
Task {
|
||||
@@ -30,11 +30,11 @@ struct PlayerEditionView: View {
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerEditionView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
NavigationView {
|
||||
PlayerEditionView(player: Player.makeRandom())
|
||||
.navigationBarTitle("Player Edition")
|
||||
}
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview {
|
||||
NavigationView {
|
||||
PlayerEditionView(player: Player.makeRandom())
|
||||
.navigationBarTitle("Player Edition")
|
||||
}
|
||||
}
|
||||
@@ -33,15 +33,16 @@ extension PlayerForm {
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerFormView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
Group {
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: "",
|
||||
score: "")))
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: Player.randomName(),
|
||||
score: "\(Player.randomScore())")))
|
||||
}
|
||||
}
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview("Empty") {
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: "",
|
||||
score: "")))
|
||||
}
|
||||
|
||||
#Preview("Prefilled") {
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: Player.randomName(),
|
||||
score: "\(Player.randomScore())")))
|
||||
}
|
||||
@@ -46,14 +46,14 @@ private struct PlayerRow: View {
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerList_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
NavigationView {
|
||||
PlayerList(players: [
|
||||
Player(id: 1, name: "Arthur", score: 100),
|
||||
Player(id: 2, name: "Barbara", score: 1000),
|
||||
])
|
||||
.navigationTitle("Preview")
|
||||
}
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview {
|
||||
NavigationView {
|
||||
PlayerList(players: [
|
||||
Player(id: 1, name: "Arthur", score: 100),
|
||||
Player(id: 2, name: "Barbara", score: 1000),
|
||||
])
|
||||
.navigationTitle("Preview")
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import GRDB
|
||||
class AppDatabaseTests: XCTestCase {
|
||||
func test_database_schema() throws {
|
||||
// Given an empty database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
|
||||
// When we instantiate an AppDatabase
|
||||
_ = try AppDatabase(dbQueue)
|
||||
@@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_savePlayer_inserts() async throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we save a new player
|
||||
@@ -29,12 +29,13 @@ class AppDatabaseTests: XCTestCase {
|
||||
try await appDatabase.savePlayer(&player)
|
||||
|
||||
// Then the player exists in the database
|
||||
try XCTAssertTrue(dbQueue.read(player.exists))
|
||||
let playerExists = try await dbQueue.read { [player] in try player.exists($0) }
|
||||
XCTAssertTrue(playerExists)
|
||||
}
|
||||
|
||||
func test_savePlayer_updates() async throws {
|
||||
// Given a players database that contains a player
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player = try await dbQueue.write { db in
|
||||
try Player(id: nil, name: "Arthur", score: 100).inserted(db)
|
||||
@@ -54,14 +55,14 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_deletePlayers() async throws {
|
||||
// Given a players database that contains four players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
let playerIds: [Int64] = try await dbQueue.write { db in
|
||||
_ = try Player(id: nil, name: "Arthur", score: 100).inserted(db)
|
||||
_ = try Player(id: nil, name: "Barbara", score: 200).inserted(db)
|
||||
_ = try Player(id: nil, name: "Craig", score: 150).inserted(db)
|
||||
_ = try Player(id: nil, name: "David", score: 120).inserted(db)
|
||||
return try Player.selectID().fetchAll(db)
|
||||
return try Player.selectPrimaryKey().fetchAll(db)
|
||||
}
|
||||
|
||||
// When we delete two players
|
||||
@@ -76,12 +77,13 @@ class AppDatabaseTests: XCTestCase {
|
||||
}
|
||||
|
||||
// Then the database still contains two players
|
||||
try XCTAssertEqual(dbQueue.read(Player.fetchCount), 2)
|
||||
let count = try await dbQueue.read { try Player.fetchCount($0) }
|
||||
XCTAssertEqual(count, 2)
|
||||
}
|
||||
|
||||
func test_deleteAllPlayers() async throws {
|
||||
// Given a players database that contains players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
try await dbQueue.write { db in
|
||||
_ = try Player(id: nil, name: "Arthur", score: 100).inserted(db)
|
||||
@@ -94,24 +96,26 @@ class AppDatabaseTests: XCTestCase {
|
||||
try await appDatabase.deleteAllPlayers()
|
||||
|
||||
// Then the database does not contain any player
|
||||
try XCTAssertEqual(dbQueue.read(Player.fetchCount), 0)
|
||||
let count = try await dbQueue.read { try Player.fetchCount($0) }
|
||||
XCTAssertEqual(count, 0)
|
||||
}
|
||||
|
||||
func test_refreshPlayers_populates_an_empty_database() async throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we refresh players
|
||||
try await appDatabase.refreshPlayers()
|
||||
|
||||
// Then the database is not empty
|
||||
try XCTAssert(dbQueue.read(Player.fetchCount) > 0)
|
||||
let count = try await dbQueue.read { try Player.fetchCount($0) }
|
||||
XCTAssert(count > 0)
|
||||
}
|
||||
|
||||
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we create random players
|
||||
@@ -123,7 +127,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
|
||||
// Given a players database that contains one player
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try dbQueue.write { db in
|
||||
|
||||
@@ -5,7 +5,7 @@ import GRDB
|
||||
class PlayerRequestTests: XCTestCase {
|
||||
func test_PlayerRequest_byName_fetches_well_ordered_players() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
@@ -16,7 +16,7 @@ class PlayerRequestTests: XCTestCase {
|
||||
|
||||
// When we fetch players ordered by name
|
||||
let playerRequest = PlayerRequest(ordering: .byName)
|
||||
let players = try dbQueue.read(playerRequest.fetchValue)
|
||||
let players = try dbQueue.read(playerRequest.fetch)
|
||||
|
||||
// Then the players are the two players ordered by name
|
||||
XCTAssertEqual(players, [player1, player2])
|
||||
@@ -24,7 +24,7 @@ class PlayerRequestTests: XCTestCase {
|
||||
|
||||
func test_PlayerRequest_byScore_fetches_well_ordered_players() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
@@ -35,7 +35,7 @@ class PlayerRequestTests: XCTestCase {
|
||||
|
||||
// When we fetch players ordered by score
|
||||
let playerRequest = PlayerRequest(ordering: .byScore)
|
||||
let players = try dbQueue.read(playerRequest.fetchValue)
|
||||
let players = try dbQueue.read(playerRequest.fetch)
|
||||
|
||||
// Then the players are the two players ordered by score descending
|
||||
XCTAssertEqual(players, [player2, player1])
|
||||
|
||||
@@ -8,7 +8,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testInsert() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player
|
||||
@@ -23,7 +23,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testRoundtrip() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player and fetch the player with the same id
|
||||
@@ -42,7 +42,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByScore() throws {
|
||||
// Given a players database that contains players with distinct scores
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
@@ -64,7 +64,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByScoreSortsIdenticalScoresByName() throws {
|
||||
// Given a players database that contains players with common scores
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
@@ -86,7 +86,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByName() throws {
|
||||
// Given a players database that contains players with distinct names
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
//
|
||||
// GRDBAsyncDemoUITests.swift
|
||||
// GRDBAsyncDemoUITests
|
||||
//
|
||||
// Created by Peter Steinberger on 08.04.21.
|
||||
//
|
||||
|
||||
import XCTest
|
||||
|
||||
class GRDBAsyncDemoUITests: XCTestCase {
|
||||
|
||||
override func setUpWithError() throws {
|
||||
// In UI tests it is usually best to stop immediately when a failure occurs.
|
||||
continueAfterFailure = false
|
||||
}
|
||||
|
||||
override func tearDownWithError() throws {
|
||||
}
|
||||
|
||||
func runApp() -> XCUIApplication {
|
||||
// UI tests must launch the application that they test.
|
||||
let app = XCUIApplication()
|
||||
// We enforce a fresh database to ensure 8 random players.
|
||||
app.launchArguments = ["-reset", "-fixedTestData"]
|
||||
app.launch()
|
||||
return app
|
||||
}
|
||||
|
||||
// This test, introduced in 481f6e93, tests the @Query fix added in
|
||||
// 68874412. The fix expresses itself when a view defines an @Query
|
||||
// property that is replaced in the view initializer, as in 481f6e93.
|
||||
//
|
||||
// It happens that I did not find that this particular view setup was suited
|
||||
// for a demo app. The demo has to find a delicate balance, not too trivial,
|
||||
// but without gratuitous complexity.
|
||||
//
|
||||
// I simplified the demo app in a5ffc52d, and we no longer have any view
|
||||
// that defines an @Query property which is replaced in the view
|
||||
// initializer. This means that this test no longer checks against
|
||||
// 68874412 regressions!
|
||||
//
|
||||
// Whenever the @Query property wrapper ships with GRDB itself, make sure
|
||||
// we test for those regressions!
|
||||
func testInitialSortingIsByScore() throws {
|
||||
let app = runApp()
|
||||
|
||||
let getFirstCell = { () -> XCUIElement in
|
||||
app.tables.element(boundBy: 0).cells.element(boundBy: 0)
|
||||
}
|
||||
|
||||
// Given default sorting, Henriette must be on top
|
||||
XCTAssertEqual(getFirstCell().label, "Craig, 8 points")
|
||||
|
||||
// Reverse sorting will bring Arthur on top (sort by name)
|
||||
app.buttons["Score"].tap()
|
||||
XCTAssertEqual(getFirstCell().label, "Arthur, 5 points")
|
||||
}
|
||||
|
||||
func testListAndAddPlayer() throws {
|
||||
let app = runApp()
|
||||
|
||||
// Ensure we have 8 players visible
|
||||
XCTAssert(app.tables.cells.count == 8)
|
||||
|
||||
// add a player
|
||||
app.buttons["New Player"].tap()
|
||||
|
||||
let playerNameField = app.textFields["Player Name"]
|
||||
playerNameField.tap()
|
||||
playerNameField.typeText("Tim Apple")
|
||||
|
||||
app.buttons["Save"].tap()
|
||||
|
||||
// This is suboptimal, but we need to wait for the animation to finish
|
||||
// A better way could be to disable animations globally,
|
||||
// and/or a hook to detect when the async fetch completes.
|
||||
sleep(2)
|
||||
|
||||
XCTAssert(app.tables.cells.count == 9)
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
<?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>CFBundleDevelopmentRegion</key>
|
||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -7,14 +7,15 @@ Async/Await + SwiftUI Demo Application
|
||||
|
||||
**Requirements**: iOS 15.0+ / Xcode 13.1+
|
||||
|
||||
> :point_up: **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration.
|
||||
> **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration.
|
||||
|
||||
The topics covered in this demo are:
|
||||
|
||||
- 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 SwiftUI List with an async sequence built from [ValueObservation](../../../README.md#valueobservation).
|
||||
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
|
||||
- How to track database changes and animate a SwiftUI List with [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) Combine publishers.
|
||||
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
|
||||
- How to perform `async` database accesses.
|
||||
- How to feed SwiftUI previews with a transient database.
|
||||
|
||||
**Files of interest:**
|
||||
@@ -25,7 +26,7 @@ The topics covered in this demo are:
|
||||
|
||||
- [AppDatabase.swift](GRDBAsyncDemo/AppDatabase.swift)
|
||||
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema.
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasemigrator) in order to setup the database schema.
|
||||
|
||||
- [Persistence.swift](GRDBAsyncDemo/Persistence.swift)
|
||||
|
||||
|
||||
@@ -26,7 +26,6 @@
|
||||
567C3E7A2520BB650011F6E9 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */; };
|
||||
56B6D1092619EC1B003CC455 /* PlayerRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D1082619EC1B003CC455 /* PlayerRequest.swift */; };
|
||||
56F8A1202735989D0011ACBE /* GRDB in Frameworks */ = {isa = PBXBuildFile; productRef = 56F8A11F2735989D0011ACBE /* GRDB */; };
|
||||
78E2F9E6261EEC22005D1F7F /* GRDBCombineDemoUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78E2F9E5261EEC22005D1F7F /* GRDBCombineDemoUITests.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
@@ -37,13 +36,6 @@
|
||||
remoteGlobalIDString = 567C3E152520B6DE0011F6E9;
|
||||
remoteInfo = GRDBCombineDemo;
|
||||
};
|
||||
78E2F9E8261EEC22005D1F7F /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 567C3E0E2520B6DE0011F6E9 /* Project object */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 567C3E152520B6DE0011F6E9;
|
||||
remoteInfo = GRDBCombineDemo;
|
||||
};
|
||||
/* End PBXContainerItemProxy section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
@@ -82,9 +74,6 @@
|
||||
567C3E782520BB650011F6E9 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
|
||||
56B6D1082619EC1B003CC455 /* PlayerRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequest.swift; sourceTree = "<group>"; };
|
||||
56F8A11C2735988F0011ACBE /* GRDB.swift */ = {isa = PBXFileReference; lastKnownFileType = folder; name = GRDB.swift; path = ../../..; sourceTree = "<group>"; };
|
||||
78E2F9E3261EEC22005D1F7F /* GRDBCombineDemoUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCombineDemoUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
78E2F9E5261EEC22005D1F7F /* GRDBCombineDemoUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GRDBCombineDemoUITests.swift; sourceTree = "<group>"; };
|
||||
78E2F9E7261EEC22005D1F7F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
@@ -104,13 +93,6 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
78E2F9E0261EEC22005D1F7F /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
@@ -140,7 +122,6 @@
|
||||
children = (
|
||||
567C3E182520B6DE0011F6E9 /* GRDBCombineDemo */,
|
||||
56026C9925B8A7D000D1DF3F /* GRDBCombineDemoTests */,
|
||||
78E2F9E4261EEC22005D1F7F /* GRDBCombineDemoUITests */,
|
||||
567C3E172520B6DE0011F6E9 /* Products */,
|
||||
567C3E4D2520B70E0011F6E9 /* Frameworks */,
|
||||
56F8A11C2735988F0011ACBE /* GRDB.swift */,
|
||||
@@ -152,7 +133,6 @@
|
||||
children = (
|
||||
567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */,
|
||||
56026C9825B8A7D000D1DF3F /* GRDBCombineDemoTests.xctest */,
|
||||
78E2F9E3261EEC22005D1F7F /* GRDBCombineDemoUITests.xctest */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
@@ -200,15 +180,6 @@
|
||||
path = Views;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
78E2F9E4261EEC22005D1F7F /* GRDBCombineDemoUITests */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
78E2F9E5261EEC22005D1F7F /* GRDBCombineDemoUITests.swift */,
|
||||
78E2F9E7261EEC22005D1F7F /* Info.plist */,
|
||||
);
|
||||
path = GRDBCombineDemoUITests;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
@@ -253,30 +224,13 @@
|
||||
productReference = 567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */;
|
||||
productType = "com.apple.product-type.application";
|
||||
};
|
||||
78E2F9E2261EEC22005D1F7F /* GRDBCombineDemoUITests */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 78E2F9F3261EEC22005D1F7F /* Build configuration list for PBXNativeTarget "GRDBCombineDemoUITests" */;
|
||||
buildPhases = (
|
||||
78E2F9DF261EEC22005D1F7F /* Sources */,
|
||||
78E2F9E0261EEC22005D1F7F /* Frameworks */,
|
||||
78E2F9E1261EEC22005D1F7F /* Resources */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
78E2F9E9261EEC22005D1F7F /* PBXTargetDependency */,
|
||||
);
|
||||
name = GRDBCombineDemoUITests;
|
||||
productName = GRDBCombineDemoUITests;
|
||||
productReference = 78E2F9E3261EEC22005D1F7F /* GRDBCombineDemoUITests.xctest */;
|
||||
productType = "com.apple.product-type.bundle.ui-testing";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
567C3E0E2520B6DE0011F6E9 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = YES;
|
||||
LastSwiftUpdateCheck = 1250;
|
||||
LastUpgradeCheck = 1200;
|
||||
TargetAttributes = {
|
||||
@@ -287,10 +241,6 @@
|
||||
567C3E152520B6DE0011F6E9 = {
|
||||
CreatedOnToolsVersion = 12.0;
|
||||
};
|
||||
78E2F9E2261EEC22005D1F7F = {
|
||||
CreatedOnToolsVersion = 12.5;
|
||||
TestTargetID = 567C3E152520B6DE0011F6E9;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = 567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBCombineDemo" */;
|
||||
@@ -311,7 +261,6 @@
|
||||
targets = (
|
||||
567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */,
|
||||
56026C9725B8A7D000D1DF3F /* GRDBCombineDemoTests */,
|
||||
78E2F9E2261EEC22005D1F7F /* GRDBCombineDemoUITests */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
@@ -335,13 +284,6 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
78E2F9E1261EEC22005D1F7F /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
@@ -372,14 +314,6 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
78E2F9DF261EEC22005D1F7F /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
78E2F9E6261EEC22005D1F7F /* GRDBCombineDemoUITests.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXTargetDependency section */
|
||||
@@ -392,11 +326,6 @@
|
||||
isa = PBXTargetDependency;
|
||||
productRef = 56F8A11D273598960011ACBE /* GRDB */;
|
||||
};
|
||||
78E2F9E9261EEC22005D1F7F /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
target = 567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */;
|
||||
targetProxy = 78E2F9E8261EEC22005D1F7F /* PBXContainerItemProxy */;
|
||||
};
|
||||
/* End PBXTargetDependency section */
|
||||
|
||||
/* Begin PBXVariantGroup section */
|
||||
@@ -425,6 +354,7 @@
|
||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
INFOPLIST_FILE = GRDBCombineDemoTests/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -444,6 +374,7 @@
|
||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
INFOPLIST_FILE = GRDBCombineDemoTests/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -583,6 +514,7 @@
|
||||
DEVELOPMENT_TEAM = "";
|
||||
ENABLE_PREVIEWS = YES;
|
||||
INFOPLIST_FILE = GRDBCombineDemo/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -604,6 +536,7 @@
|
||||
DEVELOPMENT_TEAM = "";
|
||||
ENABLE_PREVIEWS = YES;
|
||||
INFOPLIST_FILE = GRDBCombineDemo/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -615,44 +548,6 @@
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
78E2F9EA261EEC22005D1F7F /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_TEAM = "";
|
||||
INFOPLIST_FILE = GRDBCombineDemoUITests/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.groue.GRDBCombineDemoUITests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_TARGET_NAME = GRDBCombineDemo;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
78E2F9EB261EEC22005D1F7F /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_TEAM = "";
|
||||
INFOPLIST_FILE = GRDBCombineDemoUITests/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.groue.GRDBCombineDemoUITests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_TARGET_NAME = GRDBCombineDemo;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
@@ -683,15 +578,6 @@
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
78E2F9F3261EEC22005D1F7F /* Build configuration list for PBXNativeTarget "GRDBCombineDemoUITests" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
78E2F9EA261EEC22005D1F7F /* Debug */,
|
||||
78E2F9EB261EEC22005D1F7F /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
|
||||
/* Begin XCRemoteSwiftPackageReference section */
|
||||
@@ -700,7 +586,7 @@
|
||||
repositoryURL = "https://github.com/groue/GRDBQuery";
|
||||
requirement = {
|
||||
kind = upToNextMajorVersion;
|
||||
minimumVersion = 0.1.0;
|
||||
minimumVersion = 0.6.0;
|
||||
};
|
||||
};
|
||||
/* End XCRemoteSwiftPackageReference section */
|
||||
|
||||
+11
-13
@@ -1,16 +1,14 @@
|
||||
{
|
||||
"object": {
|
||||
"pins": [
|
||||
{
|
||||
"package": "GRDBQuery",
|
||||
"repositoryURL": "https://github.com/groue/GRDBQuery",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "4301166cd2aee9ce37b4057c9a58f5cc3bbeae06",
|
||||
"version": "0.1.0"
|
||||
}
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "grdbquery",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/groue/GRDBQuery",
|
||||
"state" : {
|
||||
"revision" : "a6c46dd38ecf11a5c37732870dc03a384d582fba",
|
||||
"version" : "0.9.0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 1
|
||||
}
|
||||
],
|
||||
"version" : 2
|
||||
}
|
||||
+10
-12
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1230"
|
||||
LastUpgradeVersion = "1400"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -29,7 +29,8 @@
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
skipped = "NO"
|
||||
parallelizable = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56026C9725B8A7D000D1DF3F"
|
||||
@@ -38,16 +39,6 @@
|
||||
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "78E2F9E2261EEC22005D1F7F"
|
||||
BuildableName = "GRDBCombineDemoUITests.xctest"
|
||||
BlueprintName = "GRDBCombineDemoUITests"
|
||||
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
@@ -70,6 +61,13 @@
|
||||
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
<EnvironmentVariables>
|
||||
<EnvironmentVariable
|
||||
key = "SQL_TRACE"
|
||||
value = "1"
|
||||
isEnabled = "NO">
|
||||
</EnvironmentVariable>
|
||||
</EnvironmentVariables>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
|
||||
@@ -1,14 +1,30 @@
|
||||
import Combine
|
||||
import Foundation
|
||||
import GRDB
|
||||
import os.log
|
||||
|
||||
/// AppDatabase lets the application access the database.
|
||||
/// A database of players.
|
||||
///
|
||||
/// It applies the pratices recommended at
|
||||
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
/// You create an `AppDatabase` with a connection to an SQLite database
|
||||
/// (see <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>).
|
||||
///
|
||||
/// Create those connections with a configuration returned from
|
||||
/// `AppDatabase/makeConfiguration(_:)`.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create an in-memory AppDatabase
|
||||
/// let config = AppDatabase.makeConfiguration()
|
||||
/// let dbQueue = try DatabaseQueue(configuration: config)
|
||||
/// let appDatabase = try AppDatabase(dbQueue)
|
||||
/// ```
|
||||
struct AppDatabase {
|
||||
/// Creates an `AppDatabase`, and make sure the database schema is ready.
|
||||
init(_ dbWriter: DatabaseWriter) throws {
|
||||
/// Creates an `AppDatabase`, and makes sure the database schema
|
||||
/// is ready.
|
||||
///
|
||||
/// - important: Create the `DatabaseWriter` with a configuration
|
||||
/// returned by ``makeConfiguration(_:)``.
|
||||
init(_ dbWriter: any DatabaseWriter) throws {
|
||||
self.dbWriter = dbWriter
|
||||
try migrator.migrate(dbWriter)
|
||||
}
|
||||
@@ -18,24 +34,73 @@ struct AppDatabase {
|
||||
/// Application can use a `DatabasePool`, while SwiftUI previews and tests
|
||||
/// can use a fast in-memory `DatabaseQueue`.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections>
|
||||
private let dbWriter: DatabaseWriter
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
|
||||
private let dbWriter: any DatabaseWriter
|
||||
}
|
||||
|
||||
// MARK: - Database Configuration
|
||||
|
||||
extension AppDatabase {
|
||||
private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
|
||||
|
||||
/// Returns a database configuration suited for `PlayerRepository`.
|
||||
///
|
||||
/// SQL statements are logged if the `SQL_TRACE` environment variable
|
||||
/// is set.
|
||||
///
|
||||
/// - parameter base: A base configuration.
|
||||
public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration {
|
||||
var config = base
|
||||
|
||||
// An opportunity to add required custom SQL functions or
|
||||
// collations, if needed:
|
||||
// config.prepareDatabase { db in
|
||||
// db.add(function: ...)
|
||||
// }
|
||||
|
||||
// Log SQL statements if the `SQL_TRACE` environment variable is set.
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/trace(options:_:)>
|
||||
if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil {
|
||||
config.prepareDatabase { db in
|
||||
db.trace {
|
||||
// It's ok to log statements publicly. Sensitive
|
||||
// information (statement arguments) are not logged
|
||||
// unless config.publicStatementArguments is set
|
||||
// (see below).
|
||||
os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
// Protect sensitive information by enabling verbose debugging in
|
||||
// DEBUG builds only.
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/publicstatementarguments>
|
||||
config.publicStatementArguments = true
|
||||
#endif
|
||||
|
||||
return config
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Database Migrations
|
||||
|
||||
extension AppDatabase {
|
||||
/// The DatabaseMigrator that defines the database schema.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md>
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
|
||||
private var migrator: DatabaseMigrator {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
#if DEBUG
|
||||
#if DEBUG
|
||||
// Speed up development by nuking the database when migrations change
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md#the-erasedatabaseonschemachange-option
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
#endif
|
||||
#endif
|
||||
|
||||
migrator.registerMigration("createPlayer") { db in
|
||||
// Create a table
|
||||
// See https://github.com/groue/GRDB.swift#create-tables
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema>
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
@@ -53,6 +118,7 @@ struct AppDatabase {
|
||||
}
|
||||
|
||||
// MARK: - Database Access: Writes
|
||||
// The write methods execute invariant-preserving database transactions.
|
||||
|
||||
extension AppDatabase {
|
||||
/// A validation error that prevents some players from being saved into
|
||||
@@ -128,8 +194,8 @@ extension AppDatabase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static let uiTestPlayers = [
|
||||
|
||||
private static let uiTestPlayers = [
|
||||
Player(id: nil, name: "Arthur", score: 5),
|
||||
Player(id: nil, name: "Barbara", score: 6),
|
||||
Player(id: nil, name: "Craig", score: 8),
|
||||
@@ -138,7 +204,7 @@ extension AppDatabase {
|
||||
Player(id: nil, name: "Frederik", score: 2),
|
||||
Player(id: nil, name: "Gilbert", score: 7),
|
||||
Player(id: nil, name: "Henriette", score: 3)]
|
||||
|
||||
|
||||
func createPlayersForUITests() throws {
|
||||
try dbWriter.write { db in
|
||||
try AppDatabase.uiTestPlayers.forEach { player in
|
||||
@@ -163,7 +229,7 @@ extension AppDatabase {
|
||||
// reading methods.
|
||||
extension AppDatabase {
|
||||
/// Provides a read-only access to the database
|
||||
var databaseReader: DatabaseReader {
|
||||
var reader: DatabaseReader {
|
||||
dbWriter
|
||||
}
|
||||
}
|
||||
@@ -5,17 +5,12 @@ import SwiftUI
|
||||
struct GRDBCombineDemoApp: App {
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
AppView().environment(\.appDatabase, .shared)
|
||||
AppView().appDatabase(.shared)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Give SwiftUI access to the database
|
||||
//
|
||||
// Define a new environment key that grants access to an AppDatabase.
|
||||
//
|
||||
// The technique is documented at
|
||||
// <https://developer.apple.com/documentation/swiftui/environmentkey>.
|
||||
|
||||
private struct AppDatabaseKey: EnvironmentKey {
|
||||
static var defaultValue: AppDatabase { .empty() }
|
||||
@@ -28,13 +23,10 @@ extension EnvironmentValues {
|
||||
}
|
||||
}
|
||||
|
||||
// In this demo app, views observe the database with the @Query property
|
||||
// wrapper, defined in the GRDBQuery package. Its documentation recommends to
|
||||
// define a dedicated initializer for `appDatabase` access, so we comply:
|
||||
|
||||
extension Query where Request.DatabaseContext == AppDatabase {
|
||||
/// Convenience initializer for requests that feed from `AppDatabase`.
|
||||
init(_ request: Request) {
|
||||
self.init(request, in: \.appDatabase)
|
||||
extension View {
|
||||
func appDatabase(_ appDatabase: AppDatabase) -> some View {
|
||||
self
|
||||
.environment(\.appDatabase, appDatabase)
|
||||
.databaseContext(.readOnly { appDatabase.reader })
|
||||
}
|
||||
}
|
||||
@@ -7,26 +7,31 @@ extension AppDatabase {
|
||||
|
||||
private static func makeShared() -> AppDatabase {
|
||||
do {
|
||||
// Pick a folder for storing the SQLite database, as well as
|
||||
// the various temporary files created during normal database
|
||||
// operations (https://sqlite.org/tempfiles.html).
|
||||
let fileManager = FileManager()
|
||||
let folderURL = try fileManager
|
||||
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
.appendingPathComponent("database", isDirectory: true)
|
||||
|
||||
// Apply recommendations from
|
||||
// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
|
||||
//
|
||||
// Create the "Application Support/Database" directory if needed
|
||||
let fileManager = FileManager.default
|
||||
let appSupportURL = try fileManager.url(
|
||||
for: .applicationSupportDirectory, in: .userDomainMask,
|
||||
appropriateFor: nil, create: true)
|
||||
let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true)
|
||||
|
||||
// Support for tests: delete the database if requested
|
||||
if CommandLine.arguments.contains("-reset") {
|
||||
try? fileManager.removeItem(at: folderURL)
|
||||
try? fileManager.removeItem(at: directoryURL)
|
||||
}
|
||||
|
||||
// Create the database folder if needed
|
||||
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
|
||||
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
|
||||
|
||||
// Connect to a database on disk
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
let dbURL = folderURL.appendingPathComponent("db.sqlite")
|
||||
let dbPool = try DatabasePool(path: dbURL.path)
|
||||
// Open or create the database
|
||||
let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
|
||||
NSLog("Database stored at \(databaseURL.path)")
|
||||
let dbPool = try DatabasePool(
|
||||
path: databaseURL.path,
|
||||
// Use default AppDatabase configuration
|
||||
configuration: AppDatabase.makeConfiguration())
|
||||
|
||||
// Create the AppDatabase
|
||||
let appDatabase = try AppDatabase(dbPool)
|
||||
@@ -58,8 +63,8 @@ extension AppDatabase {
|
||||
/// Creates an empty database for SwiftUI previews
|
||||
static func empty() -> AppDatabase {
|
||||
// Connect to an in-memory database
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
let dbQueue = DatabaseQueue()
|
||||
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
|
||||
let dbQueue = try! DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
return try! AppDatabase(dbQueue)
|
||||
}
|
||||
|
||||
|
||||
@@ -60,8 +60,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
}
|
||||
|
||||
/// Updates a player id after it has been inserted in the database.
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,9 +69,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
|
||||
/// Define some player requests used by the application.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
extension DerivableRequest where RowDecoder == Player {
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
|
||||
extension DerivableRequest<Player> {
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
/// For example:
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import Combine
|
||||
import GRDB
|
||||
import GRDBQuery
|
||||
|
||||
@@ -14,37 +13,18 @@ import GRDBQuery
|
||||
/// List(players) { player in ... )
|
||||
/// }
|
||||
/// }
|
||||
struct PlayerRequest: Queryable {
|
||||
struct PlayerRequest: ValueObservationQueryable {
|
||||
enum Ordering {
|
||||
case byScore
|
||||
case byName
|
||||
}
|
||||
|
||||
static var defaultValue: [Player] { [] }
|
||||
|
||||
/// The ordering used by the player request.
|
||||
var ordering: Ordering
|
||||
|
||||
// MARK: - Queryable Implementation
|
||||
|
||||
static var defaultValue: [Player] { [] }
|
||||
|
||||
func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> {
|
||||
// Build the publisher from the general-purpose read-only access
|
||||
// granted by `appDatabase.databaseReader`.
|
||||
// Some apps will prefer to call a dedicated method of `appDatabase`.
|
||||
ValueObservation
|
||||
.tracking(fetchValue(_:))
|
||||
.publisher(
|
||||
in: appDatabase.databaseReader,
|
||||
// The `.immediate` scheduling feeds the view right on
|
||||
// subscription, and avoids an undesired animation when the
|
||||
// application starts.
|
||||
scheduling: .immediate)
|
||||
.eraseToAnyPublisher()
|
||||
}
|
||||
|
||||
// This method is not required by Queryable, but it makes it easier
|
||||
// to test PlayerRequest.
|
||||
func fetchValue(_ db: Database) throws -> [Player] {
|
||||
func fetch(_ db: Database) throws -> [Player] {
|
||||
switch ordering {
|
||||
case .byScore:
|
||||
return try Player.all().orderedByScore().fetchAll(db)
|
||||
|
||||
@@ -43,7 +43,7 @@ struct AppView: View {
|
||||
stopEditing()
|
||||
}))
|
||||
.toolbar { toolbarContent }
|
||||
.onChange(of: players) { players in
|
||||
.onChange(of: players) {
|
||||
if players.isEmpty {
|
||||
stopEditing()
|
||||
}
|
||||
@@ -132,14 +132,14 @@ private struct ToggleOrderingButton: View {
|
||||
}
|
||||
}
|
||||
|
||||
struct AppView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
Group {
|
||||
// Preview the default, empty database
|
||||
AppView()
|
||||
|
||||
// Preview a database of random players
|
||||
AppView().environment(\.appDatabase, .random())
|
||||
}
|
||||
}
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview("Empty") {
|
||||
// Preview the default, empty database
|
||||
AppView()
|
||||
}
|
||||
|
||||
#Preview("Populated") {
|
||||
// Preview a database of random players
|
||||
AppView().appDatabase(.random())
|
||||
}
|
||||
+4
-4
@@ -43,8 +43,8 @@ struct PlayerCreationView: View {
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerCreationSheet_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
PlayerCreationView()
|
||||
}
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview {
|
||||
PlayerCreationView()
|
||||
}
|
||||
+7
-7
@@ -15,7 +15,7 @@ struct PlayerEditionView: View {
|
||||
|
||||
var body: some View {
|
||||
PlayerFormView(form: $form)
|
||||
.onChange(of: isPresented) { isPresented in
|
||||
.onChange(of: isPresented) {
|
||||
// Save when back button is pressed
|
||||
if !isPresented {
|
||||
var savedPlayer = player
|
||||
@@ -28,11 +28,11 @@ struct PlayerEditionView: View {
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerEditionView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
NavigationView {
|
||||
PlayerEditionView(player: Player.makeRandom())
|
||||
.navigationBarTitle("Player Edition")
|
||||
}
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview {
|
||||
NavigationView {
|
||||
PlayerEditionView(player: Player.makeRandom())
|
||||
.navigationBarTitle("Player Edition")
|
||||
}
|
||||
}
|
||||
@@ -33,15 +33,16 @@ extension PlayerForm {
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerFormView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
Group {
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: "",
|
||||
score: "")))
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: Player.randomName(),
|
||||
score: "\(Player.randomScore())")))
|
||||
}
|
||||
}
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview("Empty") {
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: "",
|
||||
score: "")))
|
||||
}
|
||||
|
||||
#Preview("Prefilled") {
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: Player.randomName(),
|
||||
score: "\(Player.randomScore())")))
|
||||
}
|
||||
@@ -44,14 +44,14 @@ private struct PlayerRow: View {
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerList_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
NavigationView {
|
||||
PlayerList(players: [
|
||||
Player(id: 1, name: "Arthur", score: 100),
|
||||
Player(id: 2, name: "Barbara", score: 1000),
|
||||
])
|
||||
.navigationTitle("Preview")
|
||||
}
|
||||
// MARK: - Previews
|
||||
|
||||
#Preview {
|
||||
NavigationView {
|
||||
PlayerList(players: [
|
||||
Player(id: 1, name: "Arthur", score: 100),
|
||||
Player(id: 2, name: "Barbara", score: 1000),
|
||||
])
|
||||
.navigationTitle("Preview")
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import GRDB
|
||||
class AppDatabaseTests: XCTestCase {
|
||||
func test_database_schema() throws {
|
||||
// Given an empty database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
|
||||
// When we instantiate an AppDatabase
|
||||
_ = try AppDatabase(dbQueue)
|
||||
@@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_savePlayer_inserts() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we save a new player
|
||||
@@ -34,7 +34,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_savePlayer_updates() throws {
|
||||
// Given a players database that contains a player
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try dbQueue.write { db in
|
||||
@@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_deletePlayers() throws {
|
||||
// Given a players database that contains four players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 200)
|
||||
@@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_deleteAllPlayers() throws {
|
||||
// Given a players database that contains players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 200)
|
||||
@@ -105,7 +105,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_refreshPlayers_populates_an_empty_database() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we refresh players
|
||||
@@ -117,7 +117,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we create random players
|
||||
@@ -129,7 +129,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
|
||||
// Given a players database that contains one player
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try dbQueue.write { db in
|
||||
|
||||
+4
-4
@@ -5,7 +5,7 @@ import GRDB
|
||||
class PlayerRequestTests: XCTestCase {
|
||||
func test_PlayerRequest_byName_fetches_well_ordered_players() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
@@ -16,7 +16,7 @@ class PlayerRequestTests: XCTestCase {
|
||||
|
||||
// When we fetch players ordered by name
|
||||
let playerRequest = PlayerRequest(ordering: .byName)
|
||||
let players = try dbQueue.read(playerRequest.fetchValue)
|
||||
let players = try dbQueue.read(playerRequest.fetch)
|
||||
|
||||
// Then the players are the two players ordered by name
|
||||
XCTAssertEqual(players, [player1, player2])
|
||||
@@ -24,7 +24,7 @@ class PlayerRequestTests: XCTestCase {
|
||||
|
||||
func test_PlayerRequest_byScore_fetches_well_ordered_players() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
@@ -35,7 +35,7 @@ class PlayerRequestTests: XCTestCase {
|
||||
|
||||
// When we fetch players ordered by score
|
||||
let playerRequest = PlayerRequest(ordering: .byScore)
|
||||
let players = try dbQueue.read(playerRequest.fetchValue)
|
||||
let players = try dbQueue.read(playerRequest.fetch)
|
||||
|
||||
// Then the players are the two players ordered by score descending
|
||||
XCTAssertEqual(players, [player2, player1])
|
||||
|
||||
@@ -8,7 +8,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testInsert() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player
|
||||
@@ -23,7 +23,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testRoundtrip() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player and fetch the player with the same id
|
||||
@@ -42,7 +42,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByScore() throws {
|
||||
// Given a players database that contains players with distinct scores
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
@@ -64,7 +64,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByScoreSortsIdenticalScoresByName() throws {
|
||||
// Given a players database that contains players with common scores
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
@@ -86,7 +86,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByName() throws {
|
||||
// Given a players database that contains players with distinct names
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
|
||||
-81
@@ -1,81 +0,0 @@
|
||||
//
|
||||
// GRDBCombineDemoUITests.swift
|
||||
// GRDBCombineDemoUITests
|
||||
//
|
||||
// Created by Peter Steinberger on 08.04.21.
|
||||
//
|
||||
|
||||
import XCTest
|
||||
|
||||
class GRDBCombineDemoUITests: XCTestCase {
|
||||
|
||||
override func setUpWithError() throws {
|
||||
// In UI tests it is usually best to stop immediately when a failure occurs.
|
||||
continueAfterFailure = false
|
||||
}
|
||||
|
||||
override func tearDownWithError() throws {
|
||||
}
|
||||
|
||||
func runApp() -> XCUIApplication {
|
||||
// UI tests must launch the application that they test.
|
||||
let app = XCUIApplication()
|
||||
// We enforce a fresh database to ensure 8 random players.
|
||||
app.launchArguments = ["-reset", "-fixedTestData"]
|
||||
app.launch()
|
||||
return app
|
||||
}
|
||||
|
||||
// This test, introduced in 481f6e93, tests the @Query fix added in
|
||||
// 68874412. The fix expresses itself when a view defines an @Query
|
||||
// property that is replaced in the view initializer, as in 481f6e93.
|
||||
//
|
||||
// It happens that I did not find that this particular view setup was suited
|
||||
// for a demo app. The demo has to find a delicate balance, not too trivial,
|
||||
// but without gratuitous complexity.
|
||||
//
|
||||
// I simplified the demo app in a5ffc52d, and we no longer have any view
|
||||
// that defines an @Query property which is replaced in the view
|
||||
// initializer. This means that this test no longer checks against
|
||||
// 68874412 regressions!
|
||||
//
|
||||
// Whenever the @Query property wrapper ships with GRDB itself, make sure
|
||||
// we test for those regressions!
|
||||
func testInitialSortingIsByScore() throws {
|
||||
let app = runApp()
|
||||
|
||||
let getFirstCell = { () -> XCUIElement in
|
||||
app.tables.element(boundBy: 0).cells.element(boundBy: 0)
|
||||
}
|
||||
|
||||
// Given default sorting, Henriette must be on top
|
||||
XCTAssertEqual(getFirstCell().label, "Craig, 8 points")
|
||||
|
||||
// Reverse sorting will bring Arthur on top (sort by name)
|
||||
app.buttons["Score"].tap()
|
||||
XCTAssertEqual(getFirstCell().label, "Arthur, 5 points")
|
||||
}
|
||||
|
||||
func testListAndAddPlayer() throws {
|
||||
let app = runApp()
|
||||
|
||||
// Ensure we have 8 players visible
|
||||
XCTAssert(app.tables.cells.count == 8)
|
||||
|
||||
// add a player
|
||||
app.buttons["New Player"].tap()
|
||||
|
||||
let playerNameField = app.textFields["Player Name"]
|
||||
playerNameField.tap()
|
||||
playerNameField.typeText("Tim Apple")
|
||||
|
||||
app.buttons["Save"].tap()
|
||||
|
||||
// This is suboptimal, but we need to wait for the animation to finish
|
||||
// A better way could be to disable animations globally,
|
||||
// and/or a hook to detect when the async fetch completes.
|
||||
sleep(2)
|
||||
|
||||
XCTAssert(app.tables.cells.count == 9)
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
<?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>CFBundleDevelopmentRegion</key>
|
||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -7,14 +7,14 @@ Combine + SwiftUI Demo Application
|
||||
|
||||
**Requirements**: iOS 15.0+ / Xcode 12+
|
||||
|
||||
> :point_up: **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration.
|
||||
> **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration.
|
||||
|
||||
The topics covered in this demo are:
|
||||
|
||||
- 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 SwiftUI List with [ValueObservation](../../../README.md#valueobservation) Combine publishers.
|
||||
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
|
||||
- How to track database changes and animate a SwiftUI List with [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) Combine publishers.
|
||||
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
|
||||
- How to feed SwiftUI previews with a transient database.
|
||||
|
||||
**Files of interest:**
|
||||
@@ -25,7 +25,7 @@ The topics covered in this demo are:
|
||||
|
||||
- [AppDatabase.swift](GRDBCombineDemo/AppDatabase.swift)
|
||||
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema.
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasemigrator) in order to setup the database schema.
|
||||
|
||||
- [Persistence.swift](GRDBCombineDemo/Persistence.swift)
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
<key>NSExtensionAttributes</key>
|
||||
<dict>
|
||||
<key>WKAppBundleIdentifier</key>
|
||||
<string>com.github.groue.GRDBDemoiOS.watchkitapp</string>
|
||||
<string>com.github.groue.GRDBDemoiOS2.watchkitapp</string>
|
||||
</dict>
|
||||
<key>NSExtensionPointIdentifier</key>
|
||||
<string>com.apple.watchkit</string>
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
<string>UIInterfaceOrientationPortraitUpsideDown</string>
|
||||
</array>
|
||||
<key>WKCompanionAppBundleIdentifier</key>
|
||||
<string>com.github.groue.GRDBDemoiOS</string>
|
||||
<string>com.github.groue.GRDBDemoiOS2</string>
|
||||
<key>WKWatchKitApp</key>
|
||||
<true/>
|
||||
</dict>
|
||||
|
||||
@@ -10,13 +10,13 @@
|
||||
56185BBF25B8036100B9C30F /* Persistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56185BBE25B8036100B9C30F /* Persistence.swift */; };
|
||||
56185BF325B80B8900B9C30F /* AppDatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56185BF225B80B8900B9C30F /* AppDatabaseTests.swift */; };
|
||||
56185C0725B80CEC00B9C30F /* PlayerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56185C0625B80CEC00B9C30F /* PlayerTests.swift */; };
|
||||
56606D202355938A00185962 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D142355931F00185962 /* GRDB.framework */; };
|
||||
56606D212355938A00185962 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D142355931F00185962 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
|
||||
56606D24235593AB00185962 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D182355931F00185962 /* GRDB.framework */; };
|
||||
56606D25235593AB00185962 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D182355931F00185962 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
|
||||
567940C528BA33D2004A0298 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D0A2355931F00185962 /* GRDB.framework */; };
|
||||
567940C628BA33D2004A0298 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D0A2355931F00185962 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
|
||||
567940C728BA33DE004A0298 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D0A2355931F00185962 /* GRDB.framework */; };
|
||||
567940C828BA33DE004A0298 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D0A2355931F00185962 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
|
||||
568E5FC31E926430002582E0 /* Interface.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FC11E926430002582E0 /* Interface.storyboard */; };
|
||||
568E5FC51E926430002582E0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FC41E926430002582E0 /* Assets.xcassets */; };
|
||||
568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = 568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
|
||||
568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
|
||||
568E5FD11E926430002582E0 /* InterfaceController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568E5FD01E926430002582E0 /* InterfaceController.swift */; };
|
||||
568E5FD31E926430002582E0 /* ExtensionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568E5FD21E926430002582E0 /* ExtensionDelegate.swift */; };
|
||||
568E5FD51E926430002582E0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FD41E926430002582E0 /* Assets.xcassets */; };
|
||||
@@ -40,6 +40,20 @@
|
||||
remoteGlobalIDString = 56B036021E8D9EBE003B6DA4;
|
||||
remoteInfo = GRDBDemoiOS;
|
||||
};
|
||||
5642252F29A2390800D714BF /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = DC3773F219C8CBB3004FCF85;
|
||||
remoteInfo = GRDB;
|
||||
};
|
||||
5642253329A2391900D714BF /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = DC3773F219C8CBB3004FCF85;
|
||||
remoteInfo = GRDB;
|
||||
};
|
||||
56606D092355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
@@ -54,62 +68,6 @@
|
||||
remoteGlobalIDString = 56E5D7F91B4D422D00430942;
|
||||
remoteInfo = GRDBOSXTests;
|
||||
};
|
||||
56606D112355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56553C181C3E906C00522B5C;
|
||||
remoteInfo = GRDBOSXCrashTests;
|
||||
};
|
||||
56606D132355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56E5D7CA1B4D3FED00430942;
|
||||
remoteInfo = GRDBiOS;
|
||||
};
|
||||
56606D152355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56E5D7D31B4D3FEE00430942;
|
||||
remoteInfo = GRDBiOSTests;
|
||||
};
|
||||
56606D172355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 565490A01D5A4798005622CB;
|
||||
remoteInfo = GRDBWatchOS;
|
||||
};
|
||||
56606D192355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = AAA4DCFE230F1E0600C74B15;
|
||||
remoteInfo = GRDBtvOS;
|
||||
};
|
||||
56606D1B2355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = AAA4DDD4230F262000C74B15;
|
||||
remoteInfo = GRDBtvOSTests;
|
||||
};
|
||||
56606D1D2355937900185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 56E5D7C91B4D3FED00430942;
|
||||
remoteInfo = GRDBiOS;
|
||||
};
|
||||
56606D22235593A300185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 5654909F1D5A4798005622CB;
|
||||
remoteInfo = GRDBWatchOS;
|
||||
};
|
||||
568E5FCD1E926430002582E0 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B035FB1E8D9EBE003B6DA4 /* Project object */;
|
||||
@@ -127,15 +85,15 @@
|
||||
/* End PBXContainerItemProxy section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
568E5FDD1E926430002582E0 /* Embed App Extensions */ = {
|
||||
568E5FDD1E926430002582E0 /* Embed Foundation Extensions */ = {
|
||||
isa = PBXCopyFilesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
dstPath = "";
|
||||
dstSubfolderSpec = 13;
|
||||
files = (
|
||||
568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed App Extensions */,
|
||||
568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed Foundation Extensions */,
|
||||
);
|
||||
name = "Embed App Extensions";
|
||||
name = "Embed Foundation Extensions";
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
568E5FE11E926430002582E0 /* Embed Watch Content */ = {
|
||||
@@ -155,7 +113,7 @@
|
||||
dstPath = "";
|
||||
dstSubfolderSpec = 10;
|
||||
files = (
|
||||
56606D25235593AB00185962 /* GRDB.framework in Embed Frameworks */,
|
||||
567940C828BA33DE004A0298 /* GRDB.framework in Embed Frameworks */,
|
||||
);
|
||||
name = "Embed Frameworks";
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
@@ -166,7 +124,7 @@
|
||||
dstPath = "";
|
||||
dstSubfolderSpec = 10;
|
||||
files = (
|
||||
56606D212355938A00185962 /* GRDB.framework in Embed Frameworks */,
|
||||
567940C628BA33D2004A0298 /* GRDB.framework in Embed Frameworks */,
|
||||
);
|
||||
name = "Embed Frameworks";
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
@@ -214,7 +172,7 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
56606D24235593AB00185962 /* GRDB.framework in Frameworks */,
|
||||
567940C728BA33DE004A0298 /* GRDB.framework in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -222,7 +180,7 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
56606D202355938A00185962 /* GRDB.framework in Frameworks */,
|
||||
567940C528BA33D2004A0298 /* GRDB.framework in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -243,13 +201,7 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56606D0A2355931F00185962 /* GRDB.framework */,
|
||||
56606D0C2355931F00185962 /* GRDBOSXTests.xctest */,
|
||||
56606D122355931F00185962 /* GRDBOSXCrashTests.xctest */,
|
||||
56606D142355931F00185962 /* GRDB.framework */,
|
||||
56606D162355931F00185962 /* GRDBiOSTests.xctest */,
|
||||
56606D182355931F00185962 /* GRDB.framework */,
|
||||
56606D1A2355931F00185962 /* GRDB.framework */,
|
||||
56606D1C2355931F00185962 /* GRDBtvOSTests.xctest */,
|
||||
56606D0C2355931F00185962 /* GRDBTests.xctest */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
@@ -366,7 +318,7 @@
|
||||
buildConfigurationList = 568E5FDE1E926430002582E0 /* Build configuration list for PBXNativeTarget "GRDBDemoWatchOS" */;
|
||||
buildPhases = (
|
||||
568E5FBD1E926430002582E0 /* Resources */,
|
||||
568E5FDD1E926430002582E0 /* Embed App Extensions */,
|
||||
568E5FDD1E926430002582E0 /* Embed Foundation Extensions */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
@@ -390,7 +342,7 @@
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
56606D23235593A300185962 /* PBXTargetDependency */,
|
||||
5642253429A2391900D714BF /* PBXTargetDependency */,
|
||||
);
|
||||
name = "GRDBDemoWatchOS Extension";
|
||||
productName = "GRDBDemoWatchOS Extension";
|
||||
@@ -410,7 +362,7 @@
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
56606D1E2355937900185962 /* PBXTargetDependency */,
|
||||
5642253029A2390800D714BF /* PBXTargetDependency */,
|
||||
568E5FD81E926430002582E0 /* PBXTargetDependency */,
|
||||
);
|
||||
name = GRDBDemoiOS;
|
||||
@@ -425,7 +377,7 @@
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastSwiftUpdateCheck = 1230;
|
||||
LastUpgradeCheck = 1200;
|
||||
LastUpgradeCheck = 1400;
|
||||
ORGANIZATIONNAME = "Gwendal Roué";
|
||||
TargetAttributes = {
|
||||
56185BEF25B80B8900B9C30F = {
|
||||
@@ -488,55 +440,13 @@
|
||||
remoteRef = 56606D092355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56606D0C2355931F00185962 /* GRDBOSXTests.xctest */ = {
|
||||
56606D0C2355931F00185962 /* GRDBTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBOSXTests.xctest;
|
||||
path = GRDBTests.xctest;
|
||||
remoteRef = 56606D0B2355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56606D122355931F00185962 /* GRDBOSXCrashTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBOSXCrashTests.xctest;
|
||||
remoteRef = 56606D112355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56606D142355931F00185962 /* GRDB.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDB.framework;
|
||||
remoteRef = 56606D132355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56606D162355931F00185962 /* GRDBiOSTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBiOSTests.xctest;
|
||||
remoteRef = 56606D152355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56606D182355931F00185962 /* GRDB.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDB.framework;
|
||||
remoteRef = 56606D172355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56606D1A2355931F00185962 /* GRDB.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDB.framework;
|
||||
remoteRef = 56606D192355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56606D1C2355931F00185962 /* GRDBtvOSTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBtvOSTests.xctest;
|
||||
remoteRef = 56606D1B2355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
/* End PBXReferenceProxy section */
|
||||
|
||||
/* Begin PBXResourcesBuildPhase section */
|
||||
@@ -617,15 +527,15 @@
|
||||
target = 56B036021E8D9EBE003B6DA4 /* GRDBDemoiOS */;
|
||||
targetProxy = 56185BF525B80B8900B9C30F /* PBXContainerItemProxy */;
|
||||
};
|
||||
56606D1E2355937900185962 /* PBXTargetDependency */ = {
|
||||
5642253029A2390800D714BF /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = GRDBiOS;
|
||||
targetProxy = 56606D1D2355937900185962 /* PBXContainerItemProxy */;
|
||||
name = GRDB;
|
||||
targetProxy = 5642252F29A2390800D714BF /* PBXContainerItemProxy */;
|
||||
};
|
||||
56606D23235593A300185962 /* PBXTargetDependency */ = {
|
||||
5642253429A2391900D714BF /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = GRDBWatchOS;
|
||||
targetProxy = 56606D22235593A300185962 /* PBXContainerItemProxy */;
|
||||
name = GRDB;
|
||||
targetProxy = 5642253329A2391900D714BF /* PBXContainerItemProxy */;
|
||||
};
|
||||
568E5FCE1E926430002582E0 /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
@@ -678,6 +588,7 @@
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu11;
|
||||
INFOPLIST_FILE = GRDBDemoiOSTests/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -704,6 +615,7 @@
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu11;
|
||||
INFOPLIST_FILE = GRDBDemoiOSTests/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
@@ -730,7 +642,7 @@
|
||||
"@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;
|
||||
@@ -750,7 +662,7 @@
|
||||
"@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;
|
||||
@@ -767,7 +679,7 @@
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
IBSC_MODULE = GRDBDemoWatchOS_Extension;
|
||||
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
@@ -784,7 +696,7 @@
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
IBSC_MODULE = GRDBDemoWatchOS_Extension;
|
||||
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
@@ -918,11 +830,12 @@
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
};
|
||||
name = Debug;
|
||||
@@ -935,11 +848,12 @@
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
};
|
||||
name = Release;
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1200"
|
||||
LastUpgradeVersion = "1400"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
+10
-2
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1230"
|
||||
LastUpgradeVersion = "1400"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -29,7 +29,8 @@
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
skipped = "NO"
|
||||
parallelizable = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56185BEF25B80B8900B9C30F"
|
||||
@@ -60,6 +61,13 @@
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
<EnvironmentVariables>
|
||||
<EnvironmentVariable
|
||||
key = "SQL_TRACE"
|
||||
value = "1"
|
||||
isEnabled = "NO">
|
||||
</EnvironmentVariable>
|
||||
</EnvironmentVariables>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
|
||||
@@ -1,12 +1,29 @@
|
||||
import GRDB
|
||||
import os.log
|
||||
|
||||
/// AppDatabase lets the application access the database.
|
||||
/// `AppDatabase` lets the application access the database.
|
||||
///
|
||||
/// It applies the pratices recommended at
|
||||
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
final class AppDatabase {
|
||||
/// Creates an `AppDatabase`, and make sure the database schema is ready.
|
||||
init(_ dbWriter: DatabaseWriter) throws {
|
||||
/// You create an `AppDatabase` with a connection to an SQLite database
|
||||
/// (see <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>).
|
||||
///
|
||||
/// Create those connections with a configuration returned from
|
||||
/// `AppDatabase/makeConfiguration(_:)`.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create an in-memory AppDatabase
|
||||
/// let config = AppDatabase.makeConfiguration()
|
||||
/// let dbQueue = try DatabaseQueue(configuration: config)
|
||||
/// let appDatabase = try AppDatabase(dbQueue)
|
||||
/// ```
|
||||
struct AppDatabase {
|
||||
/// Creates an `AppDatabase`, and makes sure the database schema
|
||||
/// is ready.
|
||||
///
|
||||
/// - important: Create the `DatabaseWriter` with a configuration
|
||||
/// returned by ``makeConfiguration(_:)``.
|
||||
init(_ dbWriter: any DatabaseWriter) throws {
|
||||
self.dbWriter = dbWriter
|
||||
try migrator.migrate(dbWriter)
|
||||
}
|
||||
@@ -16,24 +33,73 @@ final class AppDatabase {
|
||||
/// Application can use a `DatabasePool`, and tests can use a fast
|
||||
/// in-memory `DatabaseQueue`.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections>
|
||||
private let dbWriter: DatabaseWriter
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
|
||||
private let dbWriter: any DatabaseWriter
|
||||
}
|
||||
|
||||
// MARK: - Database Configuration
|
||||
|
||||
extension AppDatabase {
|
||||
private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
|
||||
|
||||
/// Returns a database configuration suited for `PlayerRepository`.
|
||||
///
|
||||
/// SQL statements are logged if the `SQL_TRACE` environment variable
|
||||
/// is set.
|
||||
///
|
||||
/// - parameter base: A base configuration.
|
||||
public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration {
|
||||
var config = base
|
||||
|
||||
// An opportunity to add required custom SQL functions or
|
||||
// collations, if needed:
|
||||
// config.prepareDatabase { db in
|
||||
// db.add(function: ...)
|
||||
// }
|
||||
|
||||
// Log SQL statements if the `SQL_TRACE` environment variable is set.
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/trace(options:_:)>
|
||||
if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil {
|
||||
config.prepareDatabase { db in
|
||||
db.trace {
|
||||
// It's ok to log statements publicly. Sensitive
|
||||
// information (statement arguments) are not logged
|
||||
// unless config.publicStatementArguments is set
|
||||
// (see below).
|
||||
os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
// Protect sensitive information by enabling verbose debugging in
|
||||
// DEBUG builds only.
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/publicstatementarguments>
|
||||
config.publicStatementArguments = true
|
||||
#endif
|
||||
|
||||
return config
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Database Migrations
|
||||
|
||||
extension AppDatabase {
|
||||
/// The DatabaseMigrator that defines the database schema.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md>
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
|
||||
private var migrator: DatabaseMigrator {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
#if DEBUG
|
||||
#if DEBUG
|
||||
// Speed up development by nuking the database when migrations change
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md#the-erasedatabaseonschemachange-option
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
#endif
|
||||
#endif
|
||||
|
||||
migrator.registerMigration("createPlayer") { db in
|
||||
// Create a table
|
||||
// See https://github.com/groue/GRDB.swift#create-tables
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema>
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
@@ -51,6 +117,7 @@ final class AppDatabase {
|
||||
}
|
||||
|
||||
// MARK: - Database Access: Writes
|
||||
// The write methods execute invariant-preserving database transactions.
|
||||
|
||||
extension AppDatabase {
|
||||
/// Saves (inserts or updates) a player. When the method returns, the
|
||||
@@ -127,7 +194,7 @@ extension AppDatabase {
|
||||
// reading methods.
|
||||
extension AppDatabase {
|
||||
/// Provides a read-only access to the database
|
||||
var databaseReader: DatabaseReader {
|
||||
var reader: DatabaseReader {
|
||||
dbWriter
|
||||
}
|
||||
}
|
||||
@@ -7,19 +7,24 @@ extension AppDatabase {
|
||||
|
||||
private static func makeShared() -> AppDatabase {
|
||||
do {
|
||||
// Create a folder for storing the SQLite database, as well as
|
||||
// the various temporary files created during normal database
|
||||
// operations (https://sqlite.org/tempfiles.html).
|
||||
let fileManager = FileManager()
|
||||
let folderURL = try fileManager
|
||||
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
.appendingPathComponent("database", isDirectory: true)
|
||||
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
|
||||
// Apply recommendations from
|
||||
// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
|
||||
//
|
||||
// Create the "Application Support/Database" directory if needed
|
||||
let fileManager = FileManager.default
|
||||
let appSupportURL = try fileManager.url(
|
||||
for: .applicationSupportDirectory, in: .userDomainMask,
|
||||
appropriateFor: nil, create: true)
|
||||
let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true)
|
||||
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
|
||||
|
||||
// Connect to a database on disk
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
let dbURL = folderURL.appendingPathComponent("db.sqlite")
|
||||
let dbPool = try DatabasePool(path: dbURL.path)
|
||||
// Open or create the database
|
||||
let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
|
||||
NSLog("Database stored at \(databaseURL.path)")
|
||||
let dbPool = try DatabasePool(
|
||||
path: databaseURL.path,
|
||||
// Use default AppDatabase configuration
|
||||
configuration: AppDatabase.makeConfiguration())
|
||||
|
||||
// Create the AppDatabase
|
||||
let appDatabase = try AppDatabase(dbPool)
|
||||
|
||||
@@ -59,8 +59,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
}
|
||||
|
||||
/// Updates a player id after it has been inserted in the database.
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,9 +68,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
|
||||
/// Define some player requests used by the application.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
extension DerivableRequest where RowDecoder == Player {
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
|
||||
extension DerivableRequest<Player> {
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
/// For example:
|
||||
|
||||
+2
-2
@@ -138,13 +138,13 @@ class PlayerListViewController: UITableViewController {
|
||||
playersCancellable = ValueObservation
|
||||
.tracking(request.fetchAll(_:))
|
||||
.start(
|
||||
in: AppDatabase.shared.databaseReader,
|
||||
in: AppDatabase.shared.reader,
|
||||
// Immediate scheduling feeds the data source right on subscription,
|
||||
// and avoids an undesired animation when the application starts.
|
||||
scheduling: .immediate,
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
guard let self else { return }
|
||||
self.configureTitle(from: players)
|
||||
self.configureDataSource(from: players)
|
||||
})
|
||||
|
||||
@@ -5,7 +5,7 @@ import GRDB
|
||||
class AppDatabaseTests: XCTestCase {
|
||||
func test_database_schema() throws {
|
||||
// Given an empty database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
|
||||
// When we instantiate an AppDatabase
|
||||
_ = try AppDatabase(dbQueue)
|
||||
@@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_savePlayer_inserts() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we save a new player
|
||||
@@ -34,7 +34,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_savePlayer_updates() throws {
|
||||
// Given a players database that contains a player
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try dbQueue.write { db in
|
||||
@@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_deletePlayers() throws {
|
||||
// Given a players database that contains four players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 200)
|
||||
@@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_deleteAllPlayers() throws {
|
||||
// Given a players database that contains players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 200)
|
||||
@@ -105,7 +105,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_refreshPlayers_populates_an_empty_database() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we refresh players
|
||||
@@ -117,7 +117,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we create random players
|
||||
@@ -129,7 +129,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
|
||||
// Given a players database that contains one player
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try dbQueue.write { db in
|
||||
|
||||
@@ -8,7 +8,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testInsert() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player
|
||||
@@ -23,7 +23,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testRoundtrip() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player and fetch the player with the same id
|
||||
@@ -42,7 +42,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByScore() throws {
|
||||
// Given a players database that contains players with distinct scores
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
@@ -64,7 +64,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByScoreSortsIdenticalScoresByName() throws {
|
||||
// Given a players database that contains players with common scores
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
@@ -86,7 +86,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByName() throws {
|
||||
// Given a players database that contains players with distinct names
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
|
||||
@@ -7,20 +7,20 @@ UIKit Demo Application
|
||||
|
||||
**Requirements**: iOS 15.0+ / Xcode 12+
|
||||
|
||||
> :point_up: **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration.
|
||||
> **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration.
|
||||
|
||||
The topics covered in this demo are:
|
||||
|
||||
- How to setup a database in an iOS app.
|
||||
- How to define a simple [Codable Record](../../../README.md#codable-records).
|
||||
- How to track database changes and animate a table view with [ValueObservation](../../../README.md#valueobservation).
|
||||
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
|
||||
- How to track database changes and animate a table view with [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation).
|
||||
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
|
||||
|
||||
**Files of interest:**
|
||||
|
||||
- [AppDatabase.swift](GRDBDemoiOS/AppDatabase.swift)
|
||||
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema, and [ValueObservation](../../../README.md#valueobservation) in order to let the application observe database changes.
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasemigrator) in order to setup the database schema, and [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) in order to let the application observe database changes.
|
||||
|
||||
- [Persistence.swift](GRDBDemoiOS/Persistence.swift)
|
||||
|
||||
|
||||
@@ -186,7 +186,7 @@ A FTS5WrapperTokenizer lets the hard tokenization job to another tokenizer, the
|
||||
|
||||
```swift
|
||||
protocol FTS5WrapperTokenizer : FTS5CustomTokenizer {
|
||||
var wrappedTokenizer: FTS5Tokenizer { get }
|
||||
var wrappedTokenizer: any FTS5Tokenizer { get }
|
||||
func accept(
|
||||
token: String,
|
||||
flags: FTS5TokenFlags,
|
||||
@@ -207,7 +207,7 @@ The `wrappedTokenizer` property is the mandatory wrapped tokenizer. You instanti
|
||||
|
||||
```swift
|
||||
final class MyTokenizer : FTS5WrapperTokenizer {
|
||||
let wrappedTokenizer: FTS5Tokenizer
|
||||
let wrappedTokenizer: any FTS5Tokenizer
|
||||
|
||||
init(db: Database, arguments: [String]) throws {
|
||||
// Wrap the unicode61 tokenizer
|
||||
@@ -255,7 +255,7 @@ For example, your custom tokenizer can wrap [unicode61](https://www.sqlite.org/f
|
||||
```swift
|
||||
final class MyTokenizer : FTS5WrapperTokenizer {
|
||||
static let name = "custom"
|
||||
let wrappedTokenizer: FTS5Tokenizer
|
||||
let wrappedTokenizer: any FTS5Tokenizer
|
||||
|
||||
init(db: Database, arguments: [String]) throws {
|
||||
if arguments.isEmpty {
|
||||
@@ -309,7 +309,7 @@ We'll also take care of the SQLite advice:
|
||||
```swift
|
||||
final class SynonymsTokenizer : FTS5WrapperTokenizer {
|
||||
static let name = "synonyms"
|
||||
let wrappedTokenizer: FTS5Tokenizer
|
||||
let wrappedTokenizer: any FTS5Tokenizer
|
||||
let synonyms: [Set<String>] = [["first", "1st"]]
|
||||
|
||||
init(db: Database, arguments: [String]) throws {
|
||||
@@ -361,7 +361,7 @@ The tokenizer wrapping is provided by the [FTS5WrapperTokenizer](#fts5wrappertok
|
||||
```swift
|
||||
final class LatinAsciiTokenizer : FTS5WrapperTokenizer {
|
||||
static let name = "latinascii"
|
||||
let wrappedTokenizer: FTS5Tokenizer
|
||||
let wrappedTokenizer: any FTS5Tokenizer
|
||||
|
||||
init(db: Database, arguments: [String]) throws {
|
||||
wrappedTokenizer = try db.makeTokenizer(.unicode61())
|
||||
@@ -375,8 +375,6 @@ final class LatinAsciiTokenizer : FTS5WrapperTokenizer {
|
||||
}
|
||||
```
|
||||
|
||||
> :point_up: **Note**: String.applyingTransform is not available before macOS 10.11. Use the Core Foundation function [CFStringTransform](https://developer.apple.com/reference/corefoundation/1542411-cfstringtransform) instead.
|
||||
|
||||
Remember to register LatinAsciiTokenizer before using it:
|
||||
|
||||
```swift
|
||||
|
||||
@@ -2,4 +2,4 @@
|
||||
|
||||
FetchedRecordsController has been removed in GRDB 5.
|
||||
|
||||
The [Database Observation](../README.md#database-changes-observation) chapter describes the other ways to observe the database.
|
||||
See [Database Observation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation) for other ways to observe the database.
|
||||
@@ -28,7 +28,6 @@ let books = try Book.fetchAll(db,
|
||||
```
|
||||
|
||||
- **[Choosing the Full-Text Engine](#choosing-the-full-text-engine)**
|
||||
- **[Enabling FTS5 Support](#enabling-fts5-support)**
|
||||
- **Create Full-Text Virtual Tables**: [FTS3/4](#create-fts3-and-fts4-virtual-tables), [FTS5](#create-fts5-virtual-tables)
|
||||
- **Choosing a Tokenizer**: [FTS3/4](#fts3-and-fts4-tokenizers), [FTS5](#fts5-tokenizers)
|
||||
- **Tokenization**: [FTS3/4](#fts3-and-fts4-tokenization), [FTS5](#fts5-tokenization)
|
||||
@@ -83,11 +82,9 @@ Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this do
|
||||
|
||||
- **The location of the indexed text in your database schema.** Only FTS4 and FTS5 support "contentless" and "external content" tables.
|
||||
|
||||
- **The SQLite library integrated in your application.** The version of SQLite that ships with iOS, macOS, tvOS and watchOS supports FTS3 and FTS4 out of the box, but not always FTS5. To use FTS5, see [Enabling FTS5 Support](#enabling-fts5-support).
|
||||
|
||||
- See [FST3 vs. FTS4](https://www.sqlite.org/fts3.html#differences_between_fts3_and_fts4) and [FTS5 vs. FTS3/4](https://www.sqlite.org/fts5.html#appendix_a) for more differences.
|
||||
|
||||
> :point_up: **Note**: In case you were still wondering, it is recommended to read the SQLite documentation: [FTS3 & FTS4](https://www.sqlite.org/fts3.html) and [FTS5](https://www.sqlite.org/fts5.html).
|
||||
> **Note**: In case you were still wondering, it is recommended to read the SQLite documentation: [FTS3 & FTS4](https://www.sqlite.org/fts3.html) and [FTS5](https://www.sqlite.org/fts5.html).
|
||||
|
||||
|
||||
## Create FTS3 and FTS4 Virtual Tables
|
||||
@@ -304,7 +301,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html):
|
||||
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statementarguments):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -323,40 +320,6 @@ let documents = try Document.filter(Column("content").match(pattern)).fetchAll(d
|
||||
```
|
||||
|
||||
|
||||
## Enabling FTS5 Support
|
||||
|
||||
When the FTS3 and FTS4 full-text engines don't suit your needs, you may want to use FTS5. See [Choosing the Full-Text Engine](#choosing-the-full-text-engine) to help you make a decision.
|
||||
|
||||
The version of SQLite that ships with iOS, macOS, tvOS and watchOS does not always support the FTS5 engine. To enable FTS5 support, you'll need to install GRDB with one of those installation techniques:
|
||||
|
||||
1. Use the GRDB.swift CocoaPod with a custom compilation option, as below. It uses the system SQLite, which is compiled with FTS5 support, but only on iOS 11.4+ / macOS 10.13+ / tvOS 11.4+ / watchOS 4.3+:
|
||||
|
||||
```ruby
|
||||
pod 'GRDB.swift'
|
||||
platform :ios, '11.4' # or above
|
||||
|
||||
post_install do |installer|
|
||||
installer.pods_project.targets.select { |target| target.name == "GRDB.swift" }.each do |target|
|
||||
target.build_configurations.each do |config|
|
||||
config.build_settings['OTHER_SWIFT_FLAGS'] = "$(inherited) -D SQLITE_ENABLE_FTS5"
|
||||
end
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
> :warning: **Warning**: make sure you use the right platform version! You will get runtime errors on devices with a lower version.
|
||||
|
||||
> :point_up: **Note**: there used to be a GRDBPlus CocoaPod with pre-enabled FTS5 support. This CocoaPod is deprecated: please switch to the above technique.
|
||||
|
||||
2. Use the GRDB.swift/SQLCipher CocoaPod subspec (see [encryption](../README.md#encryption)):
|
||||
|
||||
```ruby
|
||||
pod 'GRDB.swift/SQLCipher'
|
||||
```
|
||||
|
||||
3. Use a [custom SQLite build] and activate the `SQLITE_ENABLE_FTS5` compilation option.
|
||||
|
||||
|
||||
## Create FTS5 Virtual Tables
|
||||
|
||||
**FTS5 full-text tables store and index textual content.**
|
||||
@@ -587,7 +550,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html):
|
||||
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statementarguments):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -683,7 +646,7 @@ try db.drop(table: "book_ft")
|
||||
try db.dropFTS4SynchronizationTriggers(forTable: "book_ft")
|
||||
```
|
||||
|
||||
> :warning: **Warning**: there was a bug in GRDB up to version 2.3.1 included, which created triggers with a wrong name. If it is possible that the full-text table was created by an old version of GRDB, then delete the synchronization triggers **twice**: once with the name of the deleted full-text table, and once with the name of the content table:
|
||||
> **Warning**: there was a bug in GRDB up to version 2.3.1 included, which created triggers with a wrong name. If it is possible that the full-text table was created by an old version of GRDB, then delete the synchronization triggers **twice**: once with the name of the deleted full-text table, and once with the name of the content table:
|
||||
>
|
||||
> ```swift
|
||||
> // Drop full-text table
|
||||
@@ -726,10 +689,7 @@ let books = Book.fetchAll(db, sql: sql, arguments: [pattern])
|
||||
|
||||
**You can define [record](../README.md#records) types around the full-text virtual tables.**
|
||||
|
||||
However these tables don't have any explicit primary key. Instead, they use the [implicit rowid primary key](../README.md#the-implicit-rowid-primary-key): a special hidden column named `rowid`.
|
||||
|
||||
You will have to [expose this hidden column](../README.md#exposing-the-rowid-column) in order to fetch, delete, and update full-text records by primary key.
|
||||
|
||||
The primary key of those tables is the hidden `rowid` column. If you need to fetch, delete, and update full-text records by primary key, you will have to expose this column to the record type. See [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) for more information.
|
||||
|
||||
## Unicode Full-Text Gotchas
|
||||
|
||||
|
||||
@@ -197,7 +197,7 @@ The changes can quite impact your application. We'll describe them below, as wel
|
||||
scheduling: .immediate,
|
||||
onError: { error in ... },
|
||||
onChange: { [weak self] (players: [Player]) in
|
||||
guard let self = self else { return }
|
||||
guard let self else { return }
|
||||
self.updateView(players)
|
||||
})
|
||||
// <- Here the view has already been updated.
|
||||
@@ -397,7 +397,9 @@ let publisher = observation
|
||||
|
||||
// NEW: GRDB 5
|
||||
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
let (sql, arguments) = try dbQueue.read(query.build)
|
||||
let (sql, arguments) = try dbQueue.read { db in
|
||||
try query.build(db)
|
||||
}
|
||||
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
|
||||
print(arguments) // prints ["O'Brien", 42]
|
||||
```
|
||||
@@ -499,10 +501,10 @@ let publisher = observation
|
||||
This change is innocuous for database boolean values that are `0`, `1`, or `NULL`. However, it is a breaking change for all other database values.
|
||||
|
||||
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
|
||||
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
|
||||
[removeDuplicates]: ../README.md#valueobservationremoveduplicates
|
||||
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
|
||||
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation
|
||||
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
|
||||
[removeDuplicates]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/removeduplicates()
|
||||
[Custom SQL functions]: ../README.md#custom-sql-functions
|
||||
[Batch updates]: ../README.md#update-requests
|
||||
[SQL Interpolation]: SQLInterpolation.md
|
||||
@@ -510,4 +512,4 @@ let publisher = observation
|
||||
[SQLRequest]: ../README.md#custom-requests
|
||||
[QueryInterfaceRequest]: ../README.md#requests
|
||||
[Combine publishers]: Combine.md
|
||||
[Database Observation]: ../README.md#database-changes-observation
|
||||
[Database Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
|
||||
@@ -0,0 +1,383 @@
|
||||
Migrating From GRDB 5 to GRDB 6
|
||||
===============================
|
||||
|
||||
**This guide aims at helping you upgrading your applications from GRDB 5 to GRDB 6.**
|
||||
|
||||
- [Preparing the Migration to GRDB 6](#preparing-the-migration-to-grdb-6)
|
||||
- [New requirements](#new-requirements)
|
||||
- [Primary Associated Types](#primary-associated-types)
|
||||
- [Record Changes](#record-changes)
|
||||
- [Other Changes](#other-changes)
|
||||
|
||||
|
||||
## Preparing the Migration to GRDB 6
|
||||
|
||||
If you haven't made it yet, upgrade to the [latest GRDB 5 release](https://github.com/groue/GRDB.swift/tags) first, and fix any deprecation warning prior to the GRDB 6 upgrade.
|
||||
|
||||
You can then upgrade to GRDB 6. Due to the breaking changes, it is possible that your application code no longer compiles. Follow the fix-its that suggest simple syntactic changes. Other modifications that you need to apply are described below.
|
||||
|
||||
## New requirements
|
||||
|
||||
GRDB requirements have been bumped:
|
||||
|
||||
- **Swift 5.7+** (was Swift 5.3+)
|
||||
- **Xcode 14.0+** (was Xcode 12.0+)
|
||||
- iOS 11.0+ (unchanged)
|
||||
- **macOS 10.13+** (was macOS 10.10+)
|
||||
- **tvOS 11.0+** (was tvOS 11.0+)
|
||||
- **watchOS 4.0+** (was watchOS 2.0+)
|
||||
- **SQLite 3.19.3+** (was SQLite 3.8.5+)
|
||||
|
||||
## Primary Associated Types
|
||||
|
||||
Request protocols now come with a primary associated type, enabled by [SE-0346](https://github.com/apple/swift-evolution/blob/main/proposals/0346-light-weight-same-type-syntax.md). This is a great opportunity to simplify your extensions:
|
||||
|
||||
```diff
|
||||
-extension DerivableRequest where RowDecoder == Book {
|
||||
+extension DerivableRequest<Book> {
|
||||
/// Order books by title, in a localized case-insensitive fashion
|
||||
func orderByTitle() -> Self {
|
||||
order(Column("title").collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Your extensions to `QueryInterfaceRequest` can be streamlined as well, thanks to [SE-0361](https://github.com/apple/swift-evolution/blob/main/proposals/0361-bound-generic-extensions.md):
|
||||
|
||||
```diff
|
||||
-extension QueryInterfaceRequest where RowDecoder == Player {
|
||||
+extension QueryInterfaceRequest<Player> {
|
||||
func selectID() -> QueryInterfaceRequest<Int64> {
|
||||
selectPrimaryKey()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The `Cursor` protocol has also gained a primary associated type (the type of its elements).
|
||||
|
||||
## Record Changes
|
||||
|
||||
The record protocols have been refactored. We tried to keep the amount of modifications to your existing code as small as possible, but some changes could not be avoided.
|
||||
|
||||
- **The `FetchableRecord.init(row:)` initializer can now throw errors.**
|
||||
|
||||
```diff
|
||||
-let player = Player(row: row)
|
||||
+let player = try Player(row: row)
|
||||
```
|
||||
|
||||
Decodable records that derive their `FetchableRecord` implementation from the standard `Decodable` protocol now throw errors when they find unexpected database values (they used to crash in GRDB 5).
|
||||
|
||||
If you subclass the `Record` type, you have to update your override of `init(row:)`:
|
||||
|
||||
```diff
|
||||
class Player: Record {
|
||||
- required init(row: Row) {
|
||||
+ required init(row: Row) throws {
|
||||
self.id = row["id"]
|
||||
self.name = row["name"]
|
||||
- super.init(row: row)
|
||||
+ try super.init(row: row)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In record types that do not derive their `FetchableRecord.init(row:)` implementation from the standard `Decodable` protocol, you are responsible for throwing decoding errors, as in the sample code below:
|
||||
|
||||
<details>
|
||||
<summary>Handling untrusted input</summary>
|
||||
|
||||
For example:
|
||||
|
||||
```swift
|
||||
struct LogEntry: FetchableRecord {
|
||||
var date: Date
|
||||
|
||||
init(row: Row) throws {
|
||||
let dbValue: DatabaseValue = row["date"]
|
||||
if dbValue.isNull {
|
||||
// Handle NULL
|
||||
throw ...
|
||||
} else if let date = Date.fromDatabaseValue(dbValue) {
|
||||
self.date = date
|
||||
} else {
|
||||
// Handle invalid date
|
||||
throw ...
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
- **The `EncodableRecord.encode(to:)` method can now throw errors.**
|
||||
|
||||
Encodable records that derive their `EncodableRecord` implementation from the standard `Encodable` protocol now throw errors when they can't be encoded into database values (they used to crash in GRDB 5).
|
||||
|
||||
If you subclass the `Record` type, you have to update your override of `encode(to:)`:
|
||||
|
||||
```diff
|
||||
class Player: Record {
|
||||
- override func encode(to container: inout PersistenceContainer) {
|
||||
+ override func encode(to container: inout PersistenceContainer) throws {
|
||||
container["id"] = id
|
||||
container["name"] = name
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This change has an impact on a few other apis, that can now throw errors as well:
|
||||
|
||||
```diff
|
||||
-let dictionary = player.databaseDictionary
|
||||
-let changes = newPlayer.databaseChanges(from: oldPlayer)
|
||||
-let changes = player.databaseChanges // Record class only
|
||||
+let dictionary = try player.databaseDictionary
|
||||
+let changes = try newPlayer.databaseChanges(from: oldPlayer)
|
||||
+let changes = try player.databaseChanges // Record class only
|
||||
```
|
||||
|
||||
- **The signature of the `didInsert` method has changed**.
|
||||
|
||||
You have to update all the `didInsert` methods in your application:
|
||||
|
||||
```diff
|
||||
struct Player: MutablePersistableRecord {
|
||||
var id: Int64?
|
||||
|
||||
// Update auto-incremented id upon successful insertion
|
||||
- mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
- id = rowID
|
||||
+ mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
+ id = inserted.rowID
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If you subclass the `Record` class, you have to call `super` at some point of your implementation:
|
||||
|
||||
```diff
|
||||
class Player: Record {
|
||||
var id: Int64?
|
||||
|
||||
// Update auto-incremented id upon successful insertion
|
||||
- override func didInsert(with rowID: Int64, for column: String?) {
|
||||
- id = rowID
|
||||
+ override func didInsert(_ inserted: InsertionSuccess) {
|
||||
+ super.didInsert(inserted)
|
||||
+ id = inserted.rowID
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- **PersistableRecord types now customize persistence methods with "persistence callbacks"**.
|
||||
|
||||
It is no longer possible to override persistence methods such as `insert` or `update`. Customizing the persistence methods is now possible with callbacks such as `willSave`, `willInsert`, or `didDelete` (see [persistence callbacks] for the full list of callbacks).
|
||||
|
||||
**You have to remove the methods below from your own code base**:
|
||||
|
||||
```swift
|
||||
// GRDB 6: remove those methods from your code
|
||||
func insert(_ db: Database) throws
|
||||
func didInsert(with rowID: Int64, for column: String?)
|
||||
func update(_ db: Database, columns: Set<String>) throws
|
||||
func save(_ db: Database) throws
|
||||
func delete(_ db: Database) throws -> Bool
|
||||
func exists(_ db: Database) throws -> Bool
|
||||
```
|
||||
|
||||
- `insert(_:)`: customization is now made with [persistence callbacks].
|
||||
- `didInsert(with:for:)`: this method was renamed `didInsert(_:)` (see previous bullet point).
|
||||
- `update(_:columns:)`: customization is now made with [persistence callbacks].
|
||||
- `save(_:)`: customization is now made with [persistence callbacks].
|
||||
- `delete(_:)`: customization is now made with [persistence callbacks].
|
||||
- `exists(_:)`: this method is no longer customizable.
|
||||
|
||||
To help you update your applications with persistence callbacks, let's look at two examples.
|
||||
|
||||
First, check the updated [Single-Row Tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables) guide, if your application defines a "singleton record".
|
||||
|
||||
Next, let's consider a record that performs some validation before insertion and updates. In GRDB 5, this would look like:
|
||||
|
||||
```swift
|
||||
// GRDB 5
|
||||
struct Link: PersistableRecord {
|
||||
var url: URL
|
||||
|
||||
func insert(_ db: Database) throws {
|
||||
try validate()
|
||||
try performInsert(db)
|
||||
}
|
||||
|
||||
func update(_ db: Database, columns: Set<String>) throws {
|
||||
try validate()
|
||||
try performUpdate(db, columns: columns)
|
||||
}
|
||||
|
||||
func validate() throws {
|
||||
if url.host == nil {
|
||||
throw ValidationError("url must be absolute.")
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
With GRDB 6, record validation can be implemented with the `willSave` callback:
|
||||
|
||||
```swift
|
||||
// GRDB 6
|
||||
struct Link: PersistableRecord {
|
||||
var url: URL
|
||||
|
||||
func willSave(_ db: Database) throws {
|
||||
if url.host == nil {
|
||||
throw ValidationError("url must be absolute.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try link.insert(db) // Calls the willSave callback
|
||||
try link.update(db) // Calls the willSave callback
|
||||
try link.save(db) // Calls the willSave callback
|
||||
try link.upsert(db) // Calls the willSave callback
|
||||
```
|
||||
|
||||
If you subclass the `Record` class, you have to call `super` at some point of your implementation:
|
||||
|
||||
```swift
|
||||
// GRDB 6
|
||||
class Link: Record {
|
||||
var url: URL
|
||||
|
||||
override func willSave(_ db: Database) throws {
|
||||
try super.willSave(db)
|
||||
if url.host == nil {
|
||||
throw ValidationError("url must be absolute.")
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- **Handling of the `IGNORE` conflict policy**
|
||||
|
||||
The SQLite [IGNORE](https://www.sqlite.org/lang_conflict.html) conflict policy has SQLite skip insertions and updates that violate a schema constraint, without reporting any error. You can skip this paragraph if you do not use this policy.
|
||||
|
||||
GRDB 6 has slightly changed the handling of the `IGNORE` policy.
|
||||
|
||||
The `didInsert` callback is now always called on `INSERT OR IGNORE` insertions. In GRDB 5, `didInsert` was not called for record types that specify the `.ignore` conflict policy on inserts:
|
||||
|
||||
```swift
|
||||
// Given a record with ignore conflict policy for inserts...
|
||||
struct Player: TableRecord, FetchableRecord {
|
||||
static let persistenceConflictPolicy = PersistenceConflictPolicy(insert: .ignore)
|
||||
}
|
||||
|
||||
// GRDB 5: Does not call didInsert
|
||||
// GRDB 6: Calls didInsert
|
||||
try player.insert(db)
|
||||
```
|
||||
|
||||
Since `INSERT OR IGNORE` may silently fail, the `didInsert` method will be called with some random rowid in case of failed insert. You can detect failed insertions with the new method `insertAndFetch`:
|
||||
|
||||
```swift
|
||||
// How to detect failed `INSERT OR IGNORE`:
|
||||
// INSERT OR IGNORE INTO player ... RETURNING *
|
||||
if let insertedPlayer = try player.insertAndFetch(db) {
|
||||
// Succesful insertion
|
||||
} else {
|
||||
// Ignored failure
|
||||
}
|
||||
```
|
||||
|
||||
## Other Changes
|
||||
|
||||
- The initializer of in-memory databases can now throw errors:
|
||||
|
||||
```diff
|
||||
-let dbQueue = DatabaseQueue()
|
||||
+let dbQueue = try DatabaseQueue()
|
||||
```
|
||||
|
||||
- The `selectID()` method is removed. You can provide your own implementation, based on the new `selectPrimaryKey(as:)` method:
|
||||
|
||||
```swift
|
||||
extension QueryInterfaceRequest<Player> {
|
||||
func selectID() -> QueryInterfaceRequest<Int64> {
|
||||
selectPrimaryKey()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `Cursor.isEmpty` is now a throwing property, instead of a method:
|
||||
|
||||
```diff
|
||||
-if try cursor.isEmpty() { ... }
|
||||
+if try cursor.isEmpty { ... }
|
||||
```
|
||||
|
||||
- The `Record.copy()` method was removed, without replacement.
|
||||
|
||||
- The `DerivableRequest.limit(_:offset_:)` method was removed, without replacement.
|
||||
|
||||
You can still limit `QueryInterfaceRequest`, but associations can no longer be limited:
|
||||
|
||||
```swift
|
||||
// Still OK: a limited request of authors
|
||||
let request = Author.limit(10)
|
||||
|
||||
// Still OK: a limited request of books
|
||||
let request = author.request(for: Author.books).limit(10)
|
||||
|
||||
// No longer possible: including a limited association
|
||||
let request = Author.including(all: Author.books.limit(10))
|
||||
```
|
||||
|
||||
- `DatabaseRegionObservation.start(in:onError:onChange:)` now returns a cancellable.
|
||||
|
||||
```swift
|
||||
let observation = DatabaseRegionObservation.tracking(Player.all())
|
||||
|
||||
// GRDB 5
|
||||
do {
|
||||
let observer = try observation.start(in: dbQueue) { db in
|
||||
print("Players were modified")
|
||||
}
|
||||
} catch {
|
||||
// handle error
|
||||
}
|
||||
|
||||
// GRDB 6
|
||||
let cancellable = observation.start(
|
||||
in: dbQueue,
|
||||
onError: { error in /* handle error */ },
|
||||
onChange: { db in
|
||||
print("Players were modified")
|
||||
})
|
||||
```
|
||||
|
||||
The `DatabaseRegionObservation.extent` property was removed. You now control the duration of the observation with the cancellable returned from the `start` method.
|
||||
|
||||
- Database cursors no longer have a `statement` property. When you want information about the database statement used by a cursor, use dedicated cursor properties. For example:
|
||||
|
||||
```diff
|
||||
-let sql = cursor.statement.sql
|
||||
-let columns = cursor.statement.columnNames
|
||||
+let sql = cursor.sql
|
||||
+let columns = cursor.columnNames
|
||||
```
|
||||
|
||||
- The transaction hook `Database.afterNextTransactionCommit(_:)` was renamed `Database.afterNextTransaction(onCommit:onRollback:)`, and is now able to report rollbacks as well as commits.
|
||||
|
||||
```diff
|
||||
-db.afterNextTransactionCommit { db in
|
||||
+db.afterNextTransaction { db in
|
||||
print("Succesful commit")
|
||||
}
|
||||
```
|
||||
|
||||
- If your application directly embeds the `GRDB.xcodeproj` or `GRDBCustom.xcodeproj` project, then you have to update your dependencies. Those projects now define cross-platform targets, and you must perform the following actions:
|
||||
|
||||
- In the **Target Dependencies** section of the **Build Phases** tab of your **application targets**, replace the GRDB target with `GRDB` or `GRDBCustom`.
|
||||
- In the **Embedded Binaries** section of the **General** tab of your **application target**, replace the GRDB framework with `GRDB.framework` or `GRDBCustom.framework`.
|
||||
|
||||
[persistence callbacks]: ../README.md#persistence-callbacks
|
||||
@@ -1,832 +1,4 @@
|
||||
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]
|
||||
- [Record Types Hide Intimate Database Details]
|
||||
- [Singleton Records]
|
||||
- [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, Identifiable {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
var country: String?
|
||||
}
|
||||
|
||||
struct Book: Codable, Identifiable {
|
||||
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
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> :bulb: **Tip**: When the database table has a single-column primary key, have your record type adopt the standard [Identifiable] protocol. This allows GRDB to define type-safe id-related methods:
|
||||
>
|
||||
> ```swift
|
||||
> let authorID: Int64 = ...
|
||||
> let author: Author? = try dbQueue.read { db in
|
||||
> try Author.fetchOne(db, id: authorID)
|
||||
> }
|
||||
> ```
|
||||
|
||||
Now that `Author` and `Book` can read and write in their own database tables, they are responsible for it. Make sure each record type deals with one database table, and only one database table!
|
||||
|
||||
|
||||
## Record Types Hide Intimate Database Details
|
||||
|
||||
The application uses `Book` and `Author` as regular structs, using their properties. Each of those properties matches a column in the database (`Book.title`, `Author.id`), and is defined with a Swift type that is natively supported by SQLite (`String`, `Int`, etc.)
|
||||
|
||||
Sometimes, it happens that raw database column names and types are not a very good fit for the application.
|
||||
|
||||
Let's look at three examples:
|
||||
|
||||
1. Authors write books, and more specifically novels, poems, essays, or theatre plays. Let's add a `kind` column in the database. For easy debugging of the database contents, a book kind is represented as a string ("novel", "essay", etc.):
|
||||
|
||||
```swift
|
||||
try db.create(table: "book") { t in
|
||||
...
|
||||
t.column("kind", .text).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
In Swift, it is not a good practice to use `String` for the type of the `kind` property. We want an enum instead:
|
||||
|
||||
```swift
|
||||
struct Book: Codable {
|
||||
enum Kind: String, Codable {
|
||||
case novel, poems, essay, play
|
||||
}
|
||||
var id: Int64?
|
||||
var authorId: Int64
|
||||
var title: String
|
||||
var kind: Kind
|
||||
}
|
||||
```
|
||||
|
||||
In order to make it possible to use `Book.Kind` in book requests (see [Define Record Requests] below), we add this conformance:
|
||||
|
||||
```swift
|
||||
extension Book.Kind: DatabaseValueConvertible { }
|
||||
```
|
||||
|
||||
> :bulb: Records can pick the best suited [Value] type for their column properties (Bool, Int, String, Date, etc.) Thanks to its enum property, the `Book` record prevents unknown book kinds from entering the database.
|
||||
|
||||
2. GPS coordinates are usually stored in two distinct `latitude` and `longitude` columns. But the standard way to deal with such coordinate is a single `CLLocationCoordinate2D` struct.
|
||||
|
||||
When this happens, keep column properties private, and provide sensible accessors instead:
|
||||
|
||||
```swift
|
||||
struct Place: Codable {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
private var latitude: CLLocationDegrees
|
||||
private var longitude: CLLocationDegrees
|
||||
|
||||
var coordinate: CLLocationCoordinate2D {
|
||||
get {
|
||||
CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
|
||||
}
|
||||
set {
|
||||
latitude = newValue.latitude
|
||||
longitude = newValue.longitude
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: Private properties make it possible to hide raw columns from the rest of the application.
|
||||
|
||||
3. The record below exposes a `price: Decimal` property ($12.00), backed by an integer column that stores a quantity of cents (1200). An integer column is preferred because it allows SQLite to compute exact sums of prices.
|
||||
|
||||
```swift
|
||||
struct Product: Codable {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
private var priceCents: Int
|
||||
|
||||
var price: Decimal {
|
||||
get { Decimal(priceCents) / 100 }
|
||||
set { priceCents = NSDecimalNumber(decimal: newValue * 100).intValue }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: Private properties allow records to choose both their best database representation, and at the same time, their best Swift interface.
|
||||
|
||||
**Generally speaking**, record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. When needed, you can even [validate values](../README.md#customizing-the-persistence-methods) before they enter the database.
|
||||
|
||||
|
||||
## Singleton Records
|
||||
|
||||
**Singleton Records** are records that store configuration values, user preferences, and generally some global application state. They are backed by a database table that contains a single row.
|
||||
|
||||
The recommended setup for such records is described in the [Single-Row Tables](SingleRowTables.md) guide. Go check it, and come back when you're done!
|
||||
|
||||
|
||||
## 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
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Those columns let you define requests:
|
||||
|
||||
```swift
|
||||
try dbQueue.read { db in
|
||||
// Order authors by name, in a localized case-insensitive fashion
|
||||
let sortedAuthors: [Author] = try Author.all()
|
||||
.order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
.fetchAll(db)
|
||||
|
||||
// French authors
|
||||
let frenchAuthors: [Author] = try Author.all()
|
||||
.filter(Author.Columns.country == "France")
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: **Tip**: Define commonly used requests in a constrained extension of the `DerivableRequest` protocol.
|
||||
|
||||
When you find yourself build similar requests over and over in your application, you may want to define a reusable and composable request vocabulary. This will avoid repetition in your app, ease refactoring, and enable [testability](DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift).
|
||||
|
||||
To do so, extend the `DerivableRequest` protocol. It generally lets you filter, sort, leverage associations (we'll talk about associations in the [Compose Records] chapter below), etc:
|
||||
|
||||
```swift
|
||||
// Author requests ~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
extension DerivableRequest where RowDecoder == Author {
|
||||
/// Order authors by name, in a localized case-insensitive fashion
|
||||
func orderByName() -> Self {
|
||||
let name = Author.Columns.name
|
||||
return order(name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
|
||||
/// Filters authors from a country
|
||||
func filter(country: String) -> Self {
|
||||
filter(Author.Columns.country == country)
|
||||
}
|
||||
|
||||
/// Filters authors with at least one book
|
||||
func havingBooks() -> Self {
|
||||
having(Author.books.isEmpty == false)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Those methods encapsulate intimate database details, and allow you to compose database requests in a fluent and legible 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 sortedSpanishAuthorsHavingBooks: [Author] = try Author.all()
|
||||
.filter(country: "Spain")
|
||||
.havingBooks()
|
||||
.orderByName()
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
Because they are defined in an extension of the `DerivableRequest` protocol, our customized methods can decorate both requests and associations. See how the implementation of `filter(authorCountry:)` for books, below, uses the `filter(country:)` for authors:
|
||||
|
||||
```swift
|
||||
// Book requests ~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
extension DerivableRequest where RowDecoder == Book {
|
||||
/// Filters books by kind
|
||||
func filter(kind: Book.Kind) -> Self {
|
||||
filter(Book.Columns.kind == kind)
|
||||
}
|
||||
|
||||
/// Filters books from a country
|
||||
func filter(authorCountry: String) -> Self {
|
||||
// Books do not have any country column. But their author has one.
|
||||
// A book is from a country if it can be joined to an author from this country:
|
||||
joining(required: Book.author.filter(country: authorCountry))
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.read { db in
|
||||
let italianNovels: [Book] = try Book.all()
|
||||
.filter(kind: .novel)
|
||||
.filter(authorCountry: "Italy")
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
Extensions to the `DerivableRequest` protocol can not change the type of requests. This has to be expressed in an extension to `QueryInterfaceRequest`. For example:
|
||||
|
||||
```swift
|
||||
// Author requests ~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
extension QueryInterfaceRequest where RowDecoder == Author {
|
||||
// Selects author ids
|
||||
func id() -> QueryInterfaceRequest<Int64> {
|
||||
select(Author.Columns.id)
|
||||
}
|
||||
}
|
||||
|
||||
// IDs of French authors
|
||||
let ids: [Int64] = try Author.all().filter(country: "France").id().fetchAll(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(id: 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(id: 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> {
|
||||
request(for: Author.books)
|
||||
}
|
||||
}
|
||||
|
||||
extension Book {
|
||||
/// The request for the author of the book
|
||||
var author: QueryInterfaceRequest<Author> {
|
||||
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, id: 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, id: 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 developers 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, id: id)
|
||||
}
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func book(id: Int64) -> Book? {
|
||||
do {
|
||||
return try dbQueue.read { db in
|
||||
try Book.fetchOne(db, id: id)
|
||||
}
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func books(writtenBy author: Author) -> [Book] {
|
||||
do {
|
||||
return try dbQueue.read { db in
|
||||
try author.books.fetchAll(db)
|
||||
}
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**This manager can be improved in two ways.**
|
||||
|
||||
- [Embrace Errors]
|
||||
- [Thread-Safety is also an Application Concern]
|
||||
|
||||
### Embrace Errors
|
||||
|
||||
Have database managers throw database errors instead of catching them.
|
||||
|
||||
Consider Apple's [CNContactStore](https://developer.apple.com/documentation/contacts/cncontactstore), for example. Does it hide errors when you fetch or save address book contacts? No it does not. Keychain, Media assets, File system, Core Data? No they do not hide errors either. Follow the practices of Apple engineers: do not hide errors :muscle:
|
||||
|
||||
Exposing errors will help you building your application:
|
||||
|
||||
- You will be able to inspect errors during development, and fix bugs. `do { ... } catch { print(error) }` will save you hours of clueless questioning.
|
||||
- You will be able to opt in for advanced OS features like [data protection].
|
||||
|
||||
> :bulb: **Tip**: Don't hide database errors. Let the application handle them, because only application can decide how to handle them.
|
||||
|
||||
This gives the improved manager below. And it has less code, which means less bugs :bowtie:
|
||||
|
||||
```swift
|
||||
// An improved manager that does not hide errors
|
||||
class ImprovedLibraryManager {
|
||||
private let dbQueue: DatabaseQueue
|
||||
init(dbQueue: DatabaseQueue) {
|
||||
self.dbQueue = dbQueue
|
||||
}
|
||||
|
||||
func author(id: Int64) throws -> Author? {
|
||||
try dbQueue.read { db in
|
||||
try Author.fetchOne(db, id: id)
|
||||
}
|
||||
}
|
||||
|
||||
func book(id: Int64) throws -> Book? {
|
||||
try dbQueue.read { db in
|
||||
try Book.fetchOne(db, id: id)
|
||||
}
|
||||
}
|
||||
|
||||
func books(writtenBy author: Author) throws -> [Book] {
|
||||
try dbQueue.read { db in
|
||||
try author.books.fetchAll(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Thread-Safety is also an Application Concern
|
||||
|
||||
Now, let's make our database manager **thread-safe**.
|
||||
|
||||
This one is more subtle. In order to understand what is wrong in our naive manager, one has to consider how it is used by the application.
|
||||
|
||||
For example, in the screen that displays an author and her books, we would write:
|
||||
|
||||
```swift
|
||||
let authorId = 123
|
||||
if let author = libraryManager.author(id: authorId) {
|
||||
let books = libraryManager.books(writtenBy: author)
|
||||
// Use author and books
|
||||
}
|
||||
```
|
||||
|
||||
This code is not thread-safe, because other application threads may have modified the database between the two database accesses. You may end up with an author without any book, and this sure does not make a pretty application screen.
|
||||
|
||||
Such bugs are uneasy to reproduce. Sometimes your application will refresh the library content from the network, and delete an author right at the wrong time. The more users your application has, the more users will see weird screens. And of course, you'll be bitten right on the day of the demo in front of the boss.
|
||||
|
||||
Fortunately, GRDB has all the tools you need to prevent such nasty data races:
|
||||
|
||||
> :bulb: **Tip**: Make sure you fetch all the data your application needs at a given moment of time, in a **single database read**.
|
||||
|
||||
This gives a much safer manager:
|
||||
|
||||
```swift
|
||||
// A manager that actually manages
|
||||
class LibraryManager {
|
||||
private let dbQueue: DatabaseQueue
|
||||
init(dbQueue: DatabaseQueue) {
|
||||
self.dbQueue = dbQueue
|
||||
}
|
||||
}
|
||||
|
||||
// Feeds the list of authors
|
||||
extension LibraryManager {
|
||||
struct AuthorListItem: Decodable, FetchableRecord {
|
||||
let author: Author
|
||||
let bookCount: Int
|
||||
}
|
||||
|
||||
func authorList() throws -> [AuthorListItem] {
|
||||
try dbQueue.read { db in
|
||||
let request = Author
|
||||
.annotated(with: Author.books.count)
|
||||
.orderByName()
|
||||
return try AuthorListItem.fetchAll(db, request)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Feeds a book screen
|
||||
extension LibraryManager {
|
||||
struct BookInfo {
|
||||
var book: Book
|
||||
var author: Author
|
||||
}
|
||||
|
||||
func bookInfo(bookId: Int64) throws -> BookInfo? {
|
||||
try dbQueue.read { db in
|
||||
guard let book = try Book.fetchOne(db, id: bookId) else {
|
||||
return nil
|
||||
}
|
||||
guard let author = try book.author.fetchOne(db) else {
|
||||
return nil
|
||||
}
|
||||
return BookInfo(book: book, author: author)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Feeds an author screen
|
||||
extension LibraryManager {
|
||||
struct AuthorInfo {
|
||||
var author: Author
|
||||
var books: [Book]
|
||||
}
|
||||
|
||||
func authorInfo(authorId: Int64) throws -> AuthorInfo? {
|
||||
try dbQueue.read { db in
|
||||
guard let author = try Author.fetchOne(db, id: 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**: [Combine Support] allows 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 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]: Migrations.md
|
||||
[migration]: Migrations.md
|
||||
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
|
||||
[Concurrency Guide]: Concurrency.md
|
||||
[GRDB concurrency rules]: Concurrency.md#concurrency-rules
|
||||
[PersistableRecord]: ../README.md#persistablerecord-protocol
|
||||
[Database Observation]: ../README.md#database-changes-observation
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
|
||||
[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
|
||||
[Record Types Hide Intimate Database Details]: #record-types-hide-intimate-database-details
|
||||
[Singleton Records]: #singleton-records
|
||||
[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
|
||||
[Combine Support]: Combine.md
|
||||
[Value]: ../README.md#values
|
||||
[Identifiable]: https://developer.apple.com/documentation/swift/identifiable
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
|
||||
+1
-297
@@ -1,299 +1,3 @@
|
||||
# Migrations
|
||||
|
||||
**Migrations** are a convenient way to alter your database schema over time in a consistent and easy way.
|
||||
|
||||
- [Migrations Overview]
|
||||
- [The `eraseDatabaseOnSchemaChange` Option]
|
||||
- [Advanced Database Schema Changes]
|
||||
- [Foreign Key Checks]
|
||||
- [Asynchronous Migrations]
|
||||
|
||||
|
||||
## Migrations Overview
|
||||
|
||||
Migrations run in order, once and only once. When a user upgrades your application, only non-applied migrations are run.
|
||||
|
||||
Inside each migration, you typically [define and update your database tables](../README.md#database-schema) according to your evolving application needs:
|
||||
|
||||
```swift
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
// 1st migration
|
||||
migrator.registerMigration("v1") { db in
|
||||
try db.create(table: "author") { t in ... }
|
||||
try db.create(table: "book") { t in ... }
|
||||
try db.create(index: ...)
|
||||
}
|
||||
|
||||
// 2nd migration
|
||||
migrator.registerMigration("v2") { db in
|
||||
try db.alter(table: "author") { t in ... }
|
||||
}
|
||||
|
||||
// Migrations for future versions will be inserted here:
|
||||
//
|
||||
// // 3rd migration
|
||||
// migrator.registerMigration("...") { db in
|
||||
// ...
|
||||
// }
|
||||
```
|
||||
|
||||
**Each migration runs in a separate transaction.** Should one throw an error, its transaction is rollbacked, subsequent migrations do not run, and the error is eventually thrown by `migrator.migrate(dbQueue)`.
|
||||
|
||||
**Migrations run with deferred foreign key checks.** This means that eventual foreign key violations are only checked at the end of the migration (and they make the migration fail). See [Foreign Key Checks] below for more information.
|
||||
|
||||
**The memory of applied migrations is stored in the database itself** (in a reserved table).
|
||||
|
||||
You migrate the database up to the latest version with the `migrate(_:)` method:
|
||||
|
||||
```swift
|
||||
try migrator.migrate(dbQueue) // or migrator.migrate(dbPool)
|
||||
```
|
||||
|
||||
Migrate a database up to a specific version (useful for testing):
|
||||
|
||||
```swift
|
||||
try migrator.migrate(dbQueue, upTo: "v2")
|
||||
|
||||
// Migrations can only run forward:
|
||||
try migrator.migrate(dbQueue, upTo: "v2")
|
||||
try migrator.migrate(dbQueue, upTo: "v1")
|
||||
// ^ fatal error: database is already migrated beyond migration "v1"
|
||||
```
|
||||
|
||||
When several versions of your app are deployed in the wild, you may want to perform extra checks:
|
||||
|
||||
```swift
|
||||
try dbQueue.read { db in
|
||||
// Readonly apps may want to check if database lacks expected migrations:
|
||||
if try migrator.hasCompletedMigrations(db) == false {
|
||||
// database too old
|
||||
}
|
||||
|
||||
// All apps may want to check if database contains unknown (future) migrations:
|
||||
if try migrator.hasBeenSuperseded(db) {
|
||||
// database too new
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.26/Structs/DatabaseMigrator.html) for more migrator methods.
|
||||
|
||||
|
||||
## The `eraseDatabaseOnSchemaChange` Option
|
||||
|
||||
A DatabaseMigrator can automatically wipe out the full database content, and recreate the whole database from scratch, if it detects that migrations have changed their definition:
|
||||
|
||||
```swift
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
```
|
||||
|
||||
> :warning: **Warning**: This option can destroy your precious users' data!
|
||||
|
||||
Setting `eraseDatabaseOnSchemaChange` is useful during application development, as you are still designing migrations, and the schema changes often.
|
||||
|
||||
It is recommended that this option does not ship in the released application:
|
||||
|
||||
```swift
|
||||
var migrator = DatabaseMigrator()
|
||||
#if DEBUG
|
||||
// Speed up development by nuking the database when migrations change
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
#endif
|
||||
```
|
||||
|
||||
The `eraseDatabaseOnSchemaChange` option triggers a recreation of the database if and only if:
|
||||
|
||||
- A migration has been removed, or renamed.
|
||||
- A *schema change* is detected. A schema change is any difference in the `sqlite_master` table, which contains the SQL used to create database tables, indexes, triggers, and views.
|
||||
|
||||
|
||||
## Advanced Database Schema Changes
|
||||
|
||||
If SQLite does not directly support all kinds of schema alterations, you can make arbitrary changes to the schema design of any table using a sequence of operations, as in the example below:
|
||||
|
||||
```swift
|
||||
migrator.registerMigration("Add NOT NULL check on player.name") { db in
|
||||
try db.create(table: "new_player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
try db.execute(sql: "INSERT INTO new_player SELECT * FROM player")
|
||||
try db.drop(table: "player")
|
||||
try db.rename(table: "new_player", to: "player")
|
||||
}
|
||||
```
|
||||
|
||||
This technique is described in SQLite documentation: [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes).
|
||||
|
||||
The detailed sequence of operations is described below, some of them are performed by GRDB, and others by your code:
|
||||
|
||||
1. GRDB: If foreign key constraints are enabled, disable them using PRAGMA foreign_keys=OFF.
|
||||
|
||||
2. GRDB: Start a transaction.
|
||||
|
||||
3. **Your code**: Remember the format of all indexes, triggers, and views associated with table X. This information will be needed in step 8 below. One way to do this is to run a query like the following: `SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'`.
|
||||
|
||||
4. **Your code**: Use `CREATE TABLE` to construct a new table "new_X" that is in the desired revised format of table X. Make sure that the name "new_X" does not collide with any existing table name, of course.
|
||||
|
||||
5. **Your code**: Transfer content from X into new_X using a statement like: `INSERT INTO new_X SELECT ... FROM X`.
|
||||
|
||||
6. **Your code**: Drop the old table X: `DROP TABLE X`.
|
||||
|
||||
7. **Your code**: Change the name of new_X to X using: `ALTER TABLE new_X RENAME TO X`.
|
||||
|
||||
8. **Your code**: Use `CREATE INDEX`, `CREATE TRIGGER`, and `CREATE VIEW` to reconstruct indexes, triggers, and views associated with table X. Perhaps use the old format of the triggers, indexes, and views saved from step 3 above as a guide, making changes as appropriate for the alteration.
|
||||
|
||||
9. **Your code**: If any views refer to table X in a way that is affected by the schema change, then drop those views using `DROP VIEW` and recreate them with whatever changes are necessary to accommodate the schema change using `CREATE VIEW`.
|
||||
|
||||
10. GRDB: If foreign key constraints were originally enabled then run [`PRAGMA foreign_key_check`](https://www.sqlite.org/pragma.html#pragma_foreign_key_check) to verify that the schema change did not break any foreign key constraints.
|
||||
|
||||
11. GRDB: Commit the transaction started in step 2.
|
||||
|
||||
12. GRDB: If foreign keys constraints were originally enabled, reenable them now.
|
||||
|
||||
> :point_up: **Note**: Take care to follow the procedure above precisely, in the same order, or you might corrupt triggers, views, and foreign key constraints. Have a second look at [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes) if necessary.
|
||||
>
|
||||
> :point_up: **Note**: By default, all migrations perform, at step 10, a full check of all foreign keys in your database. When your database is big, those checks may have a noticeable impact on migration performances. See [Foreign Key Checks] for a discussion of your ways to avoid this toll.
|
||||
|
||||
|
||||
## Foreign Key Checks
|
||||
|
||||
SQLite makes it [difficult](https://www.sqlite.org/lang_altertable.html) to perform some schema changes, and this creates very undesired churn w.r.t. foreign keys. GRDB makes its best to hide those problems to you, but you might have to deal with them one day, especially if your database becomes *very big*:
|
||||
|
||||
You'll need to read this chapter if you are looking for a mitigation to the time spent by migrations performing foreign key checks. You'll know this by instrumenting your migrations, and looking for the time spent in the `checkForeignKeys` method. See [Advanced Database Schema Changes] right above to know what are those foreign key checks.
|
||||
|
||||
**Your first mitigation technique is immediate foreign key checks.**
|
||||
|
||||
If you register a migration with `.immediate` foreign key checks, the migration will not temporarily disable foreign keys, and won't need to perform a deferred full check of all foreign keys in your database:
|
||||
|
||||
```swift
|
||||
migrator.registerMigration("make it faster please", foreignKeyChecks: .immediate) { db in
|
||||
try db.create(table: ...) // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Such a migration is much faster, and it still guarantees that no foreign key constraint is broken. But it can not run the kind of migrations covered by [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes). In this case, you'll need to use the second mitigation technique:
|
||||
|
||||
**Your second mitigation technique is to disable deferred foreign key checks.**
|
||||
|
||||
You can ask the migrator to stop performing foreign key checks for all newly registered migrations.
|
||||
|
||||
:warning: If you use this technique, your app becomes responsible for preventing foreign key violations from being committed to disk!
|
||||
|
||||
```swift
|
||||
migrator = migrator.disablingDeferredForeignKeyChecks()
|
||||
|
||||
// From now on, migrations are unchecked!
|
||||
migrator.registerMigration("fast but unchecked") { db in ... }
|
||||
```
|
||||
|
||||
In order to prevent foreign key violations from being committed to disk, you can:
|
||||
|
||||
- Run migrations with immediate foreign key check, as long as they do not require the technique described by [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes):
|
||||
|
||||
```swift
|
||||
migrator = migrator.disablingDeferredForeignKeyChecks()
|
||||
migrator.registerMigration("unchecked") { db in ... }
|
||||
migrator.registerMigration("checked", foreignKeyChecks: .immediate) { db in ... }
|
||||
```
|
||||
|
||||
- Perform foreign key checks on some tables only:
|
||||
|
||||
```swift
|
||||
migrator = migrator.disablingDeferredForeignKeyChecks()
|
||||
migrator.registerMigration("partially checked") { db in
|
||||
...
|
||||
|
||||
// Throws an error and stops migrations if there exists a
|
||||
// foreign key violation in the 'player' table.
|
||||
try db.checkForeignKeys(in: "player")
|
||||
}
|
||||
```
|
||||
|
||||
- Perform a full check of foreign keys, eventually:
|
||||
|
||||
```swift
|
||||
try migrator.migrate(dbQueue)
|
||||
|
||||
// Throws an error if there exists any foreign key violation.
|
||||
try dbQueue.read { db in
|
||||
try db.checkForeignKeys()
|
||||
}
|
||||
```
|
||||
|
||||
In order to check for foreign key violations, the `checkForeignKeys()` and `checkForeignKeys(in:)` methods are recommended over the raw use of the [`PRAGMA foreign_key_check`](https://www.sqlite.org/pragma.html#pragma_foreign_key_check). Those methods throw a nicely detailed DatabaseError that contains a lot of debugging information:
|
||||
|
||||
```swift
|
||||
// SQLite error 19: FOREIGN KEY constraint violation - from player(teamId) to team(id),
|
||||
// in [id:1 teamId:2 name:"O'Brien" score:1000]
|
||||
try db.checkForeignKeys()
|
||||
```
|
||||
|
||||
You can also iterate a lazy [cursor](../README.md#cursors) of all individual foreign key violations found in the database:
|
||||
|
||||
```swift
|
||||
let violations = try db.foreignKeyViolations()
|
||||
while let violation = try violations.next() {
|
||||
// The name of the table that contains the `REFERENCES` clause
|
||||
violation.originTable
|
||||
|
||||
// The rowid of the row that contains the invalid `REFERENCES` clause, or
|
||||
// nil if the origin table is a `WITHOUT ROWID` table.
|
||||
violation.originRowID
|
||||
|
||||
// The name of the table that is referred to.
|
||||
violation.destinationTable
|
||||
|
||||
// The id of the specific foreign key constraint that failed. This id
|
||||
// matches `ForeignKeyInfo.id`. See `Database.foreignKeys(on:)` for more
|
||||
// information.
|
||||
violation.foreignKeyId
|
||||
|
||||
// Plain description:
|
||||
// "FOREIGN KEY constraint violation - from player to team, in rowid 1"
|
||||
String(describing: violation)
|
||||
|
||||
// Rich description:
|
||||
// "FOREIGN KEY constraint violation - from player(teamId) to team(id),
|
||||
// in [id:1 teamId:2 name:"O'Brien" score:1000]"
|
||||
try violation.failureDescription(db)
|
||||
|
||||
// Turn violation into a DatabaseError
|
||||
throw violation.databaseError(db)
|
||||
}
|
||||
```
|
||||
|
||||
## Asynchronous Migrations
|
||||
|
||||
`DatabaseMigrator` provides the following ways to migrate a database in an asynchronous way.
|
||||
|
||||
The `asyncMigrate(_:completion:)` method:
|
||||
|
||||
```swift
|
||||
// Completes in a protected dispatch queue that can write in the database
|
||||
migrator.asyncMigrate(dbQueue, completion: { db, error in
|
||||
if let error = error {
|
||||
// Some error occurred during migrations
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
The `migratePublisher(_:receiveOn:)` [Combine](https://developer.apple.com/documentation/combine) publisher:
|
||||
|
||||
```swift
|
||||
// DatabasePublishers.Migrate
|
||||
let publisher = migrator.migratePublisher(dbQueue)
|
||||
```
|
||||
|
||||
This publisher completes on the main queue, unless you provide a specific [scheduler](https://developer.apple.com/documentation/combine/scheduler) to the `receiveOn` argument.
|
||||
|
||||
|
||||
|
||||
[Migrations Overview]: #migrations-overview
|
||||
[The `eraseDatabaseOnSchemaChange` Option]: #the-erasedatabaseonschemachange-option
|
||||
[Advanced Database Schema Changes]: #advanced-database-schema-changes
|
||||
[Foreign Key Checks]: #foreign-key-checks
|
||||
[Asynchronous Migrations]: #asynchronous-migrations
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations).
|
||||
@@ -1,7 +1,7 @@
|
||||
//: To run this playground:
|
||||
//:
|
||||
//: - Open GRDB.xcworkspace
|
||||
//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX
|
||||
//: - Select the GRDB scheme: menu Product > Scheme > GRDB
|
||||
//: - Build: menu Product > Build
|
||||
//: - Select the playground in the Playgrounds Group
|
||||
//: - Run the playground
|
||||
@@ -14,7 +14,7 @@ var configuration = Configuration()
|
||||
configuration.prepareDatabase { db in
|
||||
db.trace { print("SQL> \($0)") }
|
||||
}
|
||||
let dbQueue = DatabaseQueue(configuration: configuration)
|
||||
let dbQueue = try DatabaseQueue(configuration: configuration)
|
||||
|
||||
//: Use a migrator to define the database schema
|
||||
|
||||
@@ -29,10 +29,7 @@ migrator.registerMigration("createLibrary") { db in
|
||||
try db.create(table: "book") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("title", .text).notNull()
|
||||
t.column("authorId", .integer)
|
||||
.notNull()
|
||||
.indexed()
|
||||
.references("author", onDelete: .cascade)
|
||||
t.belongsTo("author", onDelete: .cascade).notNull()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,8 +41,8 @@ struct Author: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,8 +51,8 @@ struct Book: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
var authorId: Int64
|
||||
var title: String
|
||||
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,7 +100,7 @@ let authorInfo: AuthorInfo? = try dbQueue.read { db in
|
||||
let books = try author.books.fetchAll(db)
|
||||
return AuthorInfo(author: author, books: books)
|
||||
}
|
||||
if let authorInfo = authorInfo {
|
||||
if let authorInfo {
|
||||
print("\(authorInfo.author.name) has written:")
|
||||
for book in authorInfo.books {
|
||||
print("- \(book.title)")
|
||||
@@ -126,7 +123,7 @@ let bookInfo: BookInfo? = try dbQueue.read { db in
|
||||
.including(required: Book.author)
|
||||
return try BookInfo.fetchOne(db, request)
|
||||
}
|
||||
if let bookInfo = bookInfo {
|
||||
if let bookInfo {
|
||||
print("\(bookInfo.book.title) was written by \(bookInfo.author.name)")
|
||||
}
|
||||
|
||||
|
||||
@@ -1,469 +0,0 @@
|
||||
//: # Customized Decoding of Database Rows
|
||||
//:
|
||||
//: To run this playground:
|
||||
//:
|
||||
//: - Open GRDB.xcworkspace
|
||||
//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX
|
||||
//: - Build: menu Product > Build
|
||||
//: - Select the playground in the Playgrounds Group
|
||||
//: - Run the playground
|
||||
|
||||
import GRDB
|
||||
|
||||
//: This playground demonstrates how one can implement **customized decoding of
|
||||
//: database rows**.
|
||||
//:
|
||||
//: Customized row decoding allows you to go beyond the built-in support for
|
||||
//: requests of raw rows, values, or types that adopt the
|
||||
//: FetchableRecord protocol.
|
||||
//:
|
||||
//: For example:
|
||||
//:
|
||||
//: - Your application needs polymorphic row decoding: it decodes some class or
|
||||
//: another, depending on the values contained in a database row.
|
||||
//:
|
||||
//: - Your application needs to decode rows with a context: each decoded value
|
||||
//: should be initialized with some extra value that does not come from
|
||||
//: the database.
|
||||
//:
|
||||
//: - Your application needs a record type that supports untrusted databases,
|
||||
//: and may fail at decoding database rows (throw an error when a row contains
|
||||
//: invalid values).
|
||||
//:
|
||||
//: None of those use cases can be handled by the built-in `FetchableRecord`
|
||||
//: protocol and its `init(row:)` initializer. They need *customized
|
||||
//: row decoding*.
|
||||
//:
|
||||
//: ## An Example: Polymorphic Decoding
|
||||
//:
|
||||
//: In this playground, we will provide some sample code that performs
|
||||
//: polymorphic row decoding. Given a base class, `Base`, and two subclasses
|
||||
//: `Foo` and `Bar`, we'd like to fetch Foo or Bar instances, depending on the
|
||||
//: value found in the `type` column of the `base` database table.
|
||||
//:
|
||||
//: From this sample code, we hope that you will be able to derive your own
|
||||
//: customized decoding.
|
||||
//:
|
||||
//: Everything starts from our class hierarchy:
|
||||
|
||||
class Base {
|
||||
var description: String { "Base" }
|
||||
init() { }
|
||||
}
|
||||
|
||||
class Foo: Base {
|
||||
var name: String
|
||||
override var description: String { "Foo: \(name)" }
|
||||
init(name: String) {
|
||||
self.name = name
|
||||
super.init()
|
||||
}
|
||||
}
|
||||
|
||||
class Bar: Base {
|
||||
var score: Int
|
||||
override var description: String { "Bar: \(score)" }
|
||||
init(score: Int) {
|
||||
self.score = score
|
||||
super.init()
|
||||
}
|
||||
}
|
||||
|
||||
//: We need a database, a table, and a few values so that we can do a real demo:
|
||||
|
||||
// An in-memory database is good enough
|
||||
let dbQueue = DatabaseQueue()
|
||||
|
||||
try dbQueue.write { db in
|
||||
// Database table
|
||||
try db.create(table: "base") { t in
|
||||
t.column("type", .text).notNull() // Contains "Foo" or "Bar"
|
||||
t.column("fooName", .text) // Contains a Foo's name
|
||||
t.column("barScore", .integer) // Contains a Bar's score
|
||||
}
|
||||
|
||||
// Demo values: two Foo and one Bar
|
||||
try db.execute(
|
||||
sql: """
|
||||
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
|
||||
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
|
||||
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
|
||||
""",
|
||||
arguments: [
|
||||
"Foo", "Arthur", nil,
|
||||
"Bar", nil, 100,
|
||||
"Foo", "Barbara", nil,
|
||||
])
|
||||
}
|
||||
|
||||
//: We also need a method that decodes database rows into `Foo` or `Bar`
|
||||
//: instances: let's call it `Base.decode(row:)`:
|
||||
|
||||
extension Base {
|
||||
static func decode(row: Row) -> Base {
|
||||
switch row["type"] as String {
|
||||
case "Foo":
|
||||
return Foo(name: row["fooName"])
|
||||
case "Bar":
|
||||
return Bar(score: row["barScore"])
|
||||
case let type:
|
||||
fatalError("Unknown Base type: \(type)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//: Now we are able to express the kind of request we'd like to write. For
|
||||
//: example, we could fetch all Base values from the database:
|
||||
//:
|
||||
//: try dbQueue.read { db in
|
||||
//: // An array [Base] that contains Foo and Bar instances
|
||||
//: let bases = try Base.fetchAll(db)
|
||||
//: }
|
||||
//:
|
||||
//: But so far, we have a compiler error:
|
||||
|
||||
// Compiler error: Type 'Base' has no member 'fetchAll'
|
||||
//try dbQueue.read { db in
|
||||
// let bases = try Base.fetchAll(db)
|
||||
//}
|
||||
|
||||
//: We'll see that this goal can be achieved by declaring a protocol, writing a
|
||||
//: few extensions that guarantee the most efficient use of GRDB, and have the
|
||||
//: Base class adopt this protocol.
|
||||
//:
|
||||
//: ### Keep It Simple, Stupid!
|
||||
//:
|
||||
//: But first, let's see how polymorphic decoding can be done as simply as
|
||||
//: possible. After all, it is useless to design a full-fledged protocol unless
|
||||
//: we need to use this protocol several times, or write code that is as
|
||||
//: streamlined as possible.
|
||||
//:
|
||||
//: Can we fetch Foo and Bar values from an SQL request? Sure:
|
||||
|
||||
try dbQueue.read { db in
|
||||
print("> KISS: Fetch from SQL")
|
||||
let rows = try Row.fetchAll(db, sql: "SELECT * FROM base") // Fetch database rows
|
||||
let bases = rows.map { row in // Decode database rows
|
||||
Base.decode(row: row)
|
||||
}
|
||||
for base in bases { // Use fetched values
|
||||
print(base.description)
|
||||
}
|
||||
}
|
||||
|
||||
//: Can we have GRDB generate SQL for us? Sure, we just need to adopt the
|
||||
//: `TableRecord` protocol:
|
||||
|
||||
extension Base: TableRecord {
|
||||
static let databaseTableName = "base"
|
||||
}
|
||||
|
||||
try dbQueue.read { db in
|
||||
print("> KISS: Fetch from query interface request")
|
||||
let request = Base.filter(Column("type") == "Foo") // Define a request
|
||||
let rows = try Row.fetchAll(db, request) // Fetch database rows
|
||||
let bases = rows.map { row in // Decode database rows
|
||||
Base.decode(row: row)
|
||||
}
|
||||
for base in bases { // Use fetched values
|
||||
print(base.description)
|
||||
}
|
||||
}
|
||||
|
||||
//: As seen above, we can perform polymorphic requests with the standard GRDB,
|
||||
//: by fetching raw rows and mapping them through a decoding method.
|
||||
//:
|
||||
//: The resulting code is not as streamlined as usual GRDB code, but we could
|
||||
//: already do what we needed without much effort.
|
||||
//:
|
||||
//: ### Custom Protocol: MyDatabaseDecoder
|
||||
//:
|
||||
//: In the rest of this playground, we will define a **new realm of requests**.
|
||||
//:
|
||||
//: GRDB ships with three built-in realms of requests: requests of raw rows,
|
||||
//: requests of values, and requests of record types that adopt the
|
||||
//: `FetchableRecord` protocol.
|
||||
//:
|
||||
//: We'll define requests of record types that adopt the custom
|
||||
//: `MyDatabaseDecoder` protocol:
|
||||
|
||||
protocol MyDatabaseDecoder {
|
||||
associatedtype DecodedType
|
||||
static func decode(row: Row) -> DecodedType
|
||||
}
|
||||
|
||||
//: Types that adopt the MyDatabaseDecoder protocol are able, among other
|
||||
//: things, to perform polymorphic decoding. Our Base class, for example:
|
||||
|
||||
extension Base: MyDatabaseDecoder {
|
||||
// Already declared above:
|
||||
// static func decode(row: Row) -> Base { ... }
|
||||
}
|
||||
|
||||
//: Now let's see how we can define a new realm of requests based on the
|
||||
//: `MyDatabaseDecoder` protocol. Our goal is to make them just as powerful as
|
||||
//: ready-made requests of rows, values and FetchableRecord.
|
||||
//:
|
||||
//: All we need is a set of *extensions* that define the classic GRDB fetching
|
||||
//: methods: `fetchOne`, `fetchAll`, and `fetchCursor`. The most fundamental one
|
||||
//: is `fetchCursor`, because from it we can derive the two others.
|
||||
//:
|
||||
//: The first extension is the most low-level one: fetching from SQLite
|
||||
//: **prepared statement**:
|
||||
//:
|
||||
//: try dbQueue.read { db in
|
||||
//: let statement = try db.makeStatement(sql: "SELECT ...")
|
||||
//: try Base.fetchCursor(statement) // Cursor of Base
|
||||
//: try Base.fetchAll(statement) // [Base]
|
||||
//: try Base.fetchOne(statement) // Base?
|
||||
//: }
|
||||
|
||||
extension MyDatabaseDecoder {
|
||||
// MARK: - Fetch from Prepared Statement
|
||||
|
||||
// Statement, StatementArguments, and RowAdapter are the fundamental
|
||||
// fetching parameters of GRDB. Make sure to accept them all:
|
||||
static func fetchCursor(_ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
|
||||
// Turn the cursor of raw rows into a cursor of decoded rows
|
||||
return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map {
|
||||
self.decode(row: $0)
|
||||
}
|
||||
}
|
||||
|
||||
static func fetchAll(_ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [DecodedType] {
|
||||
// Turn the cursor into an Array
|
||||
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
static func fetchOne(_ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DecodedType? {
|
||||
// Consume the first value of the cursor
|
||||
return try fetchCursor(statement, arguments: arguments, adapter: adapter).next()
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.read { db in
|
||||
print("> Fetch from prepared statement")
|
||||
let statement = try db.makeStatement(sql: "SELECT * FROM base")
|
||||
let bases = try Base.fetchAll(statement)
|
||||
for base in bases {
|
||||
print(base.description)
|
||||
}
|
||||
}
|
||||
|
||||
//: Now that we can fetch from prepared statements, we can fetch when given a
|
||||
//: **request**, as defined by the `FetchRequest` protocol. This is the
|
||||
//: protocol for query interface requests such as `Base.all()`, or
|
||||
//: `SQLRequest`, etc.
|
||||
//:
|
||||
//: try dbQueue.read { db in
|
||||
//: let request = Base.all()
|
||||
//: try Base.fetchCursor(db, request) // Cursor of Base
|
||||
//: try Base.fetchAll(db, request) // [Base]
|
||||
//: try Base.fetchOne(db, request) // Base?
|
||||
//: }
|
||||
extension MyDatabaseDecoder {
|
||||
// MARK: - Fetch from FetchRequest
|
||||
|
||||
static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> MapCursor<RowCursor, DecodedType> {
|
||||
let preparedRequest = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchCursor(preparedRequest.statement, adapter: preparedRequest.adapter)
|
||||
}
|
||||
|
||||
static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [DecodedType] {
|
||||
let preparedRequest = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchAll(preparedRequest.statement, adapter: preparedRequest.adapter)
|
||||
}
|
||||
|
||||
static func fetchOne<R: FetchRequest>(_ db: Database, _ request: R) throws -> DecodedType? {
|
||||
// The `forSingleResult: true` argument hints the request that a single
|
||||
// row will be consumed. Some requests will add a LIMIT SQL clause.
|
||||
let preparedRequest = try request.makePreparedRequest(db, forSingleResult: true)
|
||||
return try fetchOne(preparedRequest.statement, adapter: preparedRequest.adapter)
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.read { db in
|
||||
print("> Fetch given a request")
|
||||
let request = Base.all()
|
||||
let bases = try Base.fetchAll(db, request)
|
||||
for base in bases {
|
||||
print(base.description)
|
||||
}
|
||||
}
|
||||
|
||||
//: When it's fine to fetch given a request, it's even better when requests can
|
||||
//: fetch, too:
|
||||
//:
|
||||
//: try dbQueue.read { db in
|
||||
//: let request = Base.all()
|
||||
//: try request.fetchCursor(db) // Cursor of Base
|
||||
//: try request.fetchAll(db) // [Base]
|
||||
//: try request.fetchOne(db) // Base?
|
||||
//: }
|
||||
extension FetchRequest where RowDecoder: MyDatabaseDecoder {
|
||||
// MARK: - FetchRequest fetching methods
|
||||
|
||||
func fetchCursor(_ db: Database) throws -> MapCursor<RowCursor, RowDecoder.DecodedType> {
|
||||
try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
func fetchAll(_ db: Database) throws -> [RowDecoder.DecodedType] {
|
||||
try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
func fetchOne(_ db: Database) throws -> RowDecoder.DecodedType? {
|
||||
try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.read { db in
|
||||
print("> Fetch from request")
|
||||
let request = Base.all()
|
||||
let bases = try request.fetchAll(db)
|
||||
for base in bases {
|
||||
print(base.description)
|
||||
}
|
||||
}
|
||||
|
||||
//: Types that adopt both FetchableRecord and TableRecord are able to fetch
|
||||
//: right from the base type. Let's allow this as well for MyDatabaseDecoder:
|
||||
//:
|
||||
//: try dbQueue.read { db in
|
||||
//: try Base.fetchCursor(db) // Cursor of Base
|
||||
//: try Base.fetchAll(db) // [Base]
|
||||
//: try Base.fetchOne(db) // Base?
|
||||
//: }
|
||||
extension MyDatabaseDecoder where Self: TableRecord {
|
||||
// MARK: - Static fetching methods
|
||||
|
||||
static func fetchCursor(_ db: Database) throws -> MapCursor<RowCursor, DecodedType> {
|
||||
try all().fetchCursor(db)
|
||||
}
|
||||
|
||||
static func fetchAll(_ db: Database) throws -> [DecodedType] {
|
||||
try all().fetchAll(db)
|
||||
}
|
||||
|
||||
static func fetchOne(_ db: Database) throws -> DecodedType? {
|
||||
try all().fetchOne(db)
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.read { db in
|
||||
print("> Fetch from base type")
|
||||
let bases = try Base.fetchAll(db)
|
||||
for base in bases {
|
||||
print(base.description)
|
||||
}
|
||||
}
|
||||
|
||||
//: Finally, you can support raw SQL as well:
|
||||
//:
|
||||
//: try dbQueue.read { db in
|
||||
//: try Base.fetchAll(db,
|
||||
//: sql: "SELECT ... WHERE name = ?",
|
||||
//: arguments: ["O'Brien"]) // [Base]
|
||||
//: }
|
||||
extension MyDatabaseDecoder {
|
||||
// MARK: - Fetch from SQL
|
||||
|
||||
static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
|
||||
try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [DecodedType] {
|
||||
try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DecodedType? {
|
||||
try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.read { db in
|
||||
print("> Fetch from SQL")
|
||||
let bases = try Base.fetchAll(db, sql: "SELECT * FROM base")
|
||||
for base in bases {
|
||||
print(base.description)
|
||||
}
|
||||
}
|
||||
|
||||
//: Voilà! Our `MyDatabaseDecoder` protocol is now as able as the built-in
|
||||
//: `FetchableRecord` protocol.
|
||||
//:
|
||||
//: To sum up, you have learned:
|
||||
//:
|
||||
//: - how to keep things simple: as long as you can fetch rows, you can decode
|
||||
//: them the way you want.
|
||||
//: - how to define a whole new realm of requests based on a custom protocol.
|
||||
//: This involves writing a few extensions that give your protocol the same
|
||||
//: fluent interface that is ready-made for the built-in FetchableRecord
|
||||
//: protocol. This is more work, but you are granted with the full
|
||||
//: customization freedom.
|
||||
//:
|
||||
//: To end this tour, let's quickly look at two other possible customized
|
||||
//: row decoding strategies.
|
||||
//:
|
||||
//: ## An Example: Contextualized Records
|
||||
//:
|
||||
//: Your application needs to decode rows with a context: each decoded value
|
||||
//: should be initialized with some extra value that does not come from
|
||||
//: the database.
|
||||
//:
|
||||
//: In this case, you may define a `ContextFetchableRecord` protocol, and
|
||||
//: derive all other fetching methods from the most fundamental one, which
|
||||
//: fetches a cursor from a prepared statement (as we did for the
|
||||
//: MyDatabaseDecoder protocol, above):
|
||||
|
||||
protocol ContextFetchableRecord {
|
||||
associatedtype Context
|
||||
init(row: Row, context: Context)
|
||||
}
|
||||
|
||||
extension ContextFetchableRecord {
|
||||
static func fetchCursor(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil,
|
||||
context: Context)
|
||||
throws -> MapCursor<RowCursor, Self>
|
||||
{
|
||||
// Turn the cursor of raw rows into a cursor of decoded rows
|
||||
return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map {
|
||||
self.init(row: $0, context: context)
|
||||
}
|
||||
}
|
||||
|
||||
// Define fetchAll, fetchOne, and other extensions...
|
||||
}
|
||||
|
||||
//: ## An Example: Failable Records
|
||||
//:
|
||||
//: Your application needs a record type that supports untrusted databases,
|
||||
//: and may fail at decoding database rows (throw an error when a row contains
|
||||
//: invalid values).
|
||||
//:
|
||||
//: In this case, you may define a `FailableFetchableRecord` protocol, and
|
||||
//: derive all other fetching methods from the most fundamental one, which
|
||||
//: fetches a cursor from a prepared statement (as we did for the
|
||||
//: MyDatabaseDecoder protocol, above):
|
||||
|
||||
protocol FailableFetchableRecord {
|
||||
init(row: Row) throws
|
||||
}
|
||||
|
||||
extension FailableFetchableRecord {
|
||||
static func fetchCursor(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> MapCursor<RowCursor, Self>
|
||||
{
|
||||
// Turn the cursor of raw rows into a cursor of decoded rows
|
||||
return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map {
|
||||
try self.init(row: $0)
|
||||
}
|
||||
}
|
||||
|
||||
// Define fetchAll, fetchOne, and other extensions...
|
||||
}
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<playground version='5.0' target-platform='macos' display-mode='rendered' buildActiveScheme='true'>
|
||||
<timeline fileName='timeline.xctimeline'/>
|
||||
</playground>
|
||||
@@ -1,4 +1,4 @@
|
||||
// To run this playground, select and build the GRDBOSX scheme.
|
||||
// To run this playground, select and build the GRDB scheme.
|
||||
|
||||
import GRDB
|
||||
|
||||
@@ -6,15 +6,15 @@ var configuration = Configuration()
|
||||
configuration.prepareDatabase { db in
|
||||
db.trace { print("SQL> \($0)") }
|
||||
}
|
||||
let dbQueue = DatabaseQueue(configuration: configuration)
|
||||
let dbQueue = try DatabaseQueue(configuration: configuration)
|
||||
|
||||
struct Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
var score: Int
|
||||
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//: To run this playground:
|
||||
//:
|
||||
//: - Open GRDB.xcworkspace
|
||||
//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX
|
||||
//: - Select the GRDB scheme: menu Product > Scheme > GRDB
|
||||
//: - Build: menu Product > Build
|
||||
//: - Select the playground in the Playgrounds Group
|
||||
//: - Run the playground
|
||||
@@ -22,7 +22,7 @@ var configuration = Configuration()
|
||||
configuration.prepareDatabase { db in
|
||||
db.trace { print("SQL> \($0)") }
|
||||
}
|
||||
let dbQueue = DatabaseQueue(configuration: configuration)
|
||||
let dbQueue = try DatabaseQueue(configuration: configuration)
|
||||
|
||||
|
||||
//: Execute SQL queries
|
||||
@@ -92,7 +92,7 @@ extension Place : TableRecord {
|
||||
|
||||
// Adopt MutablePersistableRecord
|
||||
extension Place : MutablePersistableRecord {
|
||||
func encode(to container: inout PersistenceContainer) {
|
||||
func encode(to container: inout PersistenceContainer) throws {
|
||||
container["id"] = id
|
||||
container["title"] = title
|
||||
container["favorite"] = favorite
|
||||
@@ -100,8 +100,8 @@ extension Place : MutablePersistableRecord {
|
||||
container["longitude"] = coordinate.longitude
|
||||
}
|
||||
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//: To run this playground:
|
||||
//:
|
||||
//: - Open GRDB.xcworkspace
|
||||
//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX
|
||||
//: - Select the GRDB scheme: menu Product > Scheme > GRDB
|
||||
//: - Build: menu Product > Build
|
||||
//: - Select the playground in the Playgrounds Group
|
||||
//: - Run the playground
|
||||
@@ -11,7 +11,7 @@ import GRDB
|
||||
|
||||
// Create the database
|
||||
|
||||
let dbQueue = DatabaseQueue() // Memory database
|
||||
let dbQueue = try DatabaseQueue() // Memory database
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.registerMigration("createPerson") { db in
|
||||
try db.create(table: "person") { t in
|
||||
@@ -23,7 +23,7 @@ migrator.registerMigration("createPet") { db in
|
||||
try db.create(table: "pet") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
t.column("ownerId", .integer).references("person", onDelete: .cascade)
|
||||
t.belongsTo("owner", inTable: "person", onDelete: .cascade)
|
||||
}
|
||||
}
|
||||
try! migrator.migrate(dbQueue)
|
||||
|
||||
@@ -179,9 +179,9 @@ protocol DatabaseValueConvertible: SQLExpressible {
|
||||
`DerivableRequest` is the protocol for query interface requests and associations that can be refined. It is adopted by [QueryInterfaceRequest] and [Association].
|
||||
|
||||
```swift
|
||||
protocol DerivableRequest: AggregatingRequest, FilteredRequest,
|
||||
JoinableRequest, OrderedRequest,
|
||||
SelectionRequest, TableRequest
|
||||
protocol DerivableRequest<RowDecoder>: AggregatingRequest, FilteredRequest,
|
||||
JoinableRequest, OrderedRequest,
|
||||
SelectionRequest, TableRequest
|
||||
{
|
||||
func distinct() -> Self
|
||||
func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> Self
|
||||
@@ -195,14 +195,14 @@ protocol DerivableRequest: AggregatingRequest, FilteredRequest,
|
||||
- `SelectionRequest` provides selection methods such as `select(selection)` or `annotated(with: selection)`
|
||||
- `TableRequest` provides table targeting methods such as `aliased(tableAlias)`
|
||||
|
||||
DerivableRequest makes it possible to build reusable code snippets that apply to both requests and associations. You'll read more about it in the [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md) and [Associations](AssociationsBasics.md).
|
||||
DerivableRequest makes it possible to build reusable code snippets that apply to both requests and associations. You'll read more about it in the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) and [Associations](AssociationsBasics.md).
|
||||
|
||||
### FetchRequest
|
||||
|
||||
`FetchRequest` is the protocol for requests that can fetch. It is adopted by [QueryInterfaceRequest] and [SQLRequest]. It conforms to [SQLSubqueryable] and [DatabaseRegionConvertible].
|
||||
|
||||
```swift
|
||||
protocol FetchRequest: SQLSubqueryable, DatabaseRegionConvertible {
|
||||
protocol FetchRequest<RowDecoder>: SQLSubqueryable, DatabaseRegionConvertible {
|
||||
/// The type that tells how fetched database rows should be interpreted.
|
||||
associatedtype RowDecoder
|
||||
|
||||
@@ -607,8 +607,8 @@ myRequest(Player.select(...).filter(...))
|
||||
[association aggregates]: AssociationsBasics.md#association-aggregates
|
||||
[Column]: #column
|
||||
[ColumnExpression]: #columnexpression
|
||||
[DatabaseRegionConvertible]: #databaseregionconvertible
|
||||
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
|
||||
[DatabaseRegionConvertible]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionconvertible
|
||||
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation
|
||||
[DatabaseValue]: #databasevalue
|
||||
[DatabaseValueConvertible]: #databasevalueconvertible
|
||||
[DerivableRequest]: #derivablerequest
|
||||
|
||||
@@ -6,26 +6,23 @@ Release Process
|
||||
To release a new GRDB version:
|
||||
|
||||
- Tests
|
||||
- `make test`
|
||||
- `make distclean test`
|
||||
- Build and run GRDBDemoiOS in Release configuration on a device
|
||||
- Archive GRDBDemoiOS
|
||||
- Check for performance regression with GRDBOSXPerformanceTests
|
||||
- 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 Documentation/CustomSQLiteBuilds.md
|
||||
- Update GRDB version number and release date in:
|
||||
- Makefile
|
||||
- CHANGELOG.md
|
||||
- GRDB.swift.podspec
|
||||
- README.md
|
||||
- Documentation/FullTextSearch.md
|
||||
- Documentation/Migrations.md
|
||||
- Support/Info.plist
|
||||
- Commit and tag
|
||||
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
|
||||
- Push to the master & development branch
|
||||
- Look for undesired tags: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
|
||||
- Push to the `master` branch
|
||||
- Push to the `development` branch
|
||||
- Push to the `GRDB6` branch
|
||||
- `pod trunk push --allow-warnings GRDB.swift.podspec`
|
||||
- `make doc`, and update index.html in the `gh-pages` branch
|
||||
- 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`
|
||||
@@ -112,13 +112,15 @@ let components: [SQL] = [
|
||||
let query = components.joined(separator: " ")
|
||||
```
|
||||
|
||||
Extract the plain SQL string from a literal:
|
||||
To extract the plain SQL string from a literal, you need a `Database` connection such as the one provided by the `read` and `write` methods:
|
||||
|
||||
```swift
|
||||
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
let (sql, arguments) = try dbQueue.read(query.build)
|
||||
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
|
||||
print(arguments) // prints ["O'Brien", 42]
|
||||
try dbQueue.read { db in
|
||||
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
let (sql, arguments) = try query.build(db)
|
||||
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
|
||||
print(arguments) // prints ["O'Brien", 42]
|
||||
}
|
||||
```
|
||||
|
||||
Build a literal from a plain SQL string:
|
||||
@@ -363,7 +365,7 @@ Let's extend Player with database methods.
|
||||
|
||||
This chapter lists all kinds of supported interpolations.
|
||||
|
||||
- Types adopting the [TableRecord] protocol:
|
||||
- Types adopting the [TableRecord] protocol and [Table](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/table) instances:
|
||||
|
||||
```swift
|
||||
struct Player: TableRecord { ... }
|
||||
@@ -371,9 +373,13 @@ This chapter lists all kinds of supported interpolations.
|
||||
// SELECT * FROM player
|
||||
"SELECT * FROM \(Player.self)"
|
||||
|
||||
// INSERT INTO player ...
|
||||
// SELECT * FROM player
|
||||
let player: Player = ...
|
||||
"INSERT INTO \(tableOf: player) ..."
|
||||
"SELECT * FROM \(tableOf: player) ..."
|
||||
|
||||
// SELECT * FROM player
|
||||
let playerTable = Table("player")
|
||||
"SELECT * FROM \(playerTable)"
|
||||
```
|
||||
|
||||
- Columns selected by [TableRecord]:
|
||||
@@ -389,7 +395,7 @@ This chapter lists all kinds of supported interpolations.
|
||||
|
||||
struct AltPlayer: TableRecord {
|
||||
static let databaseTableName = "player"
|
||||
static let databaseSelection: [SQLSelectable] = [Column("id"), Column("name")]
|
||||
static let databaseSelection: [any SQLSelectable] = [Column("id"), Column("name")]
|
||||
}
|
||||
|
||||
// SELECT player.id, player.name FROM player
|
||||
|
||||
@@ -1,294 +1,4 @@
|
||||
Sharing a Database
|
||||
==================
|
||||
|
||||
**This guide describes a recommended setup that applies as soon as several processes want to access the same SQLite database.** It complements the [Concurrency](Concurrency.md) guide, that you should read first.
|
||||
|
||||
On iOS for example, you can share database files between multiple processes by storing them in an [App Group Container](https://developer.apple.com/documentation/foundation/nsfilemanager/1412643-containerurlforsecurityapplicati). On macOS as well, several processes may want to open the same database, according to their particular sandboxing contexts.
|
||||
|
||||
Accessing a shared database from several SQLite connections, from several processes, creates challenges at various levels:
|
||||
|
||||
1. **Database setup** may be attempted by multiple processes, concurrently.
|
||||
2. **SQLite** may throw `SQLITE_BUSY` errors, code 5, "database is locked".
|
||||
3. **iOS** may kill your application with a `0xDEAD10CC` exception.
|
||||
4. **GRDB** database observation misses changes performed by external processes.
|
||||
|
||||
We'll address all of those challenges below.
|
||||
|
||||
- [Use a Database Pool]
|
||||
- [How to limit the `SQLITE_BUSY` error]
|
||||
- [How to limit the `0xDEAD10CC` exception]
|
||||
- [How to perform cross-process database observation]
|
||||
|
||||
|
||||
## Use a Database Pool
|
||||
|
||||
In order to access a shared database, use a [Database Pool]. It opens the database in the [WAL mode](https://www.sqlite.org/wal.html), which helps sharing a database.
|
||||
|
||||
Since several processes may open the database at the same time, protect the creation of the database pool with an [NSFileCoordinator].
|
||||
|
||||
- In a process that can create and write in the database, use this sample code:
|
||||
|
||||
```swift
|
||||
/// Returns an initialized database pool at the shared location databaseURL
|
||||
func openSharedDatabase(at databaseURL: URL) throws -> DatabasePool {
|
||||
let coordinator = NSFileCoordinator(filePresenter: nil)
|
||||
var coordinatorError: NSError?
|
||||
var dbPool: DatabasePool?
|
||||
var dbError: Error?
|
||||
coordinator.coordinate(writingItemAt: databaseURL, options: .forMerging, error: &coordinatorError, byAccessor: { url in
|
||||
do {
|
||||
dbPool = try openDatabase(at: url)
|
||||
} catch {
|
||||
dbError = error
|
||||
}
|
||||
})
|
||||
if let error = dbError ?? coordinatorError {
|
||||
throw error
|
||||
}
|
||||
return dbPool!
|
||||
}
|
||||
|
||||
private func openDatabase(at databaseURL: URL) throws -> DatabasePool {
|
||||
var configuration = Configuration()
|
||||
configuration.prepareDatabase { db in
|
||||
// Activate the persistent WAL mode so that
|
||||
// readonly processes can access the database.
|
||||
//
|
||||
// See https://www.sqlite.org/walformat.html#operations_that_require_locks_and_which_locks_those_operations_use
|
||||
// and https://www.sqlite.org/c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntlpersistwal
|
||||
if db.configuration.readonly == false {
|
||||
var flag: CInt = 1
|
||||
let code = withUnsafeMutablePointer(to: &flag) { flagP in
|
||||
sqlite3_file_control(db.sqliteConnection, nil, SQLITE_FCNTL_PERSIST_WAL, flagP)
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: ResultCode(rawValue: code))
|
||||
}
|
||||
}
|
||||
}
|
||||
let dbPool = try DatabasePool(path: databaseURL.path, configuration: configuration)
|
||||
|
||||
// Perform here other database setups, such as defining
|
||||
// the database schema with a DatabaseMigrator, and
|
||||
// checking if the application can open the file:
|
||||
try migrator.migrate(dbPool)
|
||||
if try dbPool.read(migrator.hasBeenSuperseded) {
|
||||
// Database is too recent
|
||||
throw /* some error */
|
||||
}
|
||||
|
||||
return dbPool
|
||||
}
|
||||
```
|
||||
|
||||
- In a process that only reads in the database, use this sample code:
|
||||
|
||||
```swift
|
||||
/// Returns an initialized database pool at the shared location databaseURL,
|
||||
/// or nil if the database is not created yet, or does not have the required
|
||||
/// schema version.
|
||||
func openSharedReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
|
||||
let coordinator = NSFileCoordinator(filePresenter: nil)
|
||||
var coordinatorError: NSError?
|
||||
var dbPool: DatabasePool?
|
||||
var dbError: Error?
|
||||
coordinator.coordinate(readingItemAt: databaseURL, options: .withoutChanges, error: &coordinatorError, byAccessor: { url in
|
||||
do {
|
||||
dbPool = try openReadOnlyDatabase(at: url)
|
||||
} catch {
|
||||
dbError = error
|
||||
}
|
||||
})
|
||||
if let error = dbError ?? coordinatorError {
|
||||
throw error
|
||||
}
|
||||
return dbPool
|
||||
}
|
||||
|
||||
private func openReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
|
||||
do {
|
||||
var configuration = Configuration()
|
||||
configuration.readonly = true
|
||||
let dbPool = try DatabasePool(path: databaseURL.path, configuration: configuration)
|
||||
|
||||
// Check here if the database schema is the expected one,
|
||||
// for example with a DatabaseMigrator:
|
||||
return try dbPool.read { db in
|
||||
if try migrator.hasBeenSuperseded(db) {
|
||||
// Database is too recent
|
||||
return nil
|
||||
} else if try migrator.hasCompletedMigrations(db) == false {
|
||||
// Database is too old
|
||||
return nil
|
||||
}
|
||||
return dbPool
|
||||
}
|
||||
} catch {
|
||||
if FileManager.default.fileExists(atPath: databaseURL.path) {
|
||||
throw error
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
#### The specific case of readonly connections
|
||||
|
||||
Readonly connections will fail unless two extra files ending in `-shm` and `-wal` are present next to the database file ([source](https://www.sqlite.org/walformat.html#operations_that_require_locks_and_which_locks_those_operations_use)). Those files are regular companions of databases in the [WAL mode]. But they are deleted, under regular operations, when database connections are closed. Precisely speaking, they *may* be deleted: it depends on the SQLite and the operating system versions ([source](https://github.com/groue/GRDB.swift/issues/739#issuecomment-604363998)). And when they are deleted, readonly connections fail.
|
||||
|
||||
The solution is to enable the "persistent WAL mode", as shown in the sample code above, by setting the [SQLITE_FCNTL_PERSIST_WAL](https://www.sqlite.org/c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntlpersistwal) flag. This mode makes sure the `-shm` and `-wal` files are never deleted, and guarantees a database access to readonly connections.
|
||||
|
||||
|
||||
## How to limit the `SQLITE_BUSY` error
|
||||
|
||||
> The SQLITE_BUSY result code indicates that the database file could not be written (or in some cases read) because of concurrent activity by some other database connection, usually a database connection in a separate process.
|
||||
|
||||
See https://www.sqlite.org/rescode.html#busy for more information about this error.
|
||||
|
||||
If several processes want to write in the database, configure the database pool of each process that wants to write:
|
||||
|
||||
```swift
|
||||
var configuration = Configuration()
|
||||
configuration.busyMode = .timeout(/* a TimeInterval */)
|
||||
let dbPool = try DatabasePool(path: ..., configuration: configuration)
|
||||
```
|
||||
|
||||
With such a setup, you may still get `SQLITE_BUSY` (5, "database is locked") errors from all write operations. They will occur if the database remains locked by another process for longer than the specified timeout.
|
||||
|
||||
```swift
|
||||
do {
|
||||
try dbPool.write { db in ... }
|
||||
} catch DatabaseError.SQLITE_BUSY {
|
||||
// Another process won't let you write. Deal with it.
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: **Tip**: In order to be nice to other processes, measure the duration of your longest writes, and attempt at optimizing the ones that last for too long. See the [How do I monitor the duration of database statements execution?] FAQ.
|
||||
|
||||
|
||||
## How to limit the `0xDEAD10CC` exception
|
||||
|
||||
> The exception code 0xDEAD10CC indicates that an application has been terminated by the OS because it held on to a file lock or sqlite database lock during suspension.
|
||||
|
||||
See https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report for more information about this exception.
|
||||
|
||||
1. If you use SQLCipher, use SQLCipher 4+, and call the [`cipher_plaintext_header_size` pragma](https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_plaintext_header_size) from your database preparation function:
|
||||
|
||||
```swift
|
||||
var configuration = Configuration()
|
||||
configuration.prepareDatabase { (db: Database) in
|
||||
try db.usePassphrase("secret")
|
||||
try db.execute(sql: "PRAGMA cipher_plaintext_header_size = 32")
|
||||
}
|
||||
let dbPool = try DatabasePool(path: ..., configuration: configuration)
|
||||
```
|
||||
|
||||
This will avoid this issue: https://github.com/sqlcipher/sqlcipher/issues/255.
|
||||
|
||||
This will also disable a SQLCipher security feature: the salt. As described by https://www.zetetic.net/sqlcipher/design/:
|
||||
|
||||
> The salt is used for key derivation and it ensures that even if two databases are created using the same password, they will not have the same encryption key.
|
||||
|
||||
Applications are responsible for managing the salt themselves and providing it to SQLCipher. See https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_plaintext_header_size for instructions.
|
||||
|
||||
2. [**:fire: EXPERIMENTAL**](../README.md#what-are-experimental-features) In each process that wants to write in the database:
|
||||
|
||||
Set the `observesSuspensionNotifications` configuration flag:
|
||||
|
||||
```swift
|
||||
var configuration = Configuration()
|
||||
configuration.observesSuspensionNotifications = true
|
||||
let dbPool = try DatabasePool(path: ..., configuration: configuration)
|
||||
```
|
||||
|
||||
Post `Database.suspendNotification` when the application is about to be [suspended](https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle). You can for example post this notification from `UIApplicationDelegate.applicationDidEnterBackground(_:)`, or in the expiration handler of a [background task](https://forums.developer.apple.com/thread/85066).
|
||||
|
||||
```swift
|
||||
@UIApplicationMain
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
func applicationDidEnterBackground(_ application: UIApplication) {
|
||||
// Suspend databases
|
||||
NotificationCenter.default.post(name: Database.suspendNotification, object: self)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Post `Database.resumeNotification` from `UIApplicationDelegate.applicationWillEnterForeground(_:)` (or `SceneDelegate.sceneWillEnterForeground(_:)` for scene-based applications):
|
||||
|
||||
```swift
|
||||
@UIApplicationMain
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
func applicationWillEnterForeground(_ application: UIApplication) {
|
||||
// Resume databases
|
||||
NotificationCenter.default.post(name: Database.resumeNotification, object: self)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If the application uses the background modes supported by iOS, post `Database.resumeNotification` method from each and every background mode callback that may use the database. For example, if your application supports background fetches:
|
||||
|
||||
```swift
|
||||
@UIApplicationMain
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
|
||||
// Resume databases
|
||||
NotificationCenter.default.post(name: Database.resumeNotification, object: self)
|
||||
// Proceed with background fetch
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Suspended databases greatly reduce the odds of `0xDEAD10CC` exception occurring. If you see one in your crash logs, please open an issue!
|
||||
|
||||
In exchange, you will get `SQLITE_INTERRUPT` (9) or `SQLITE_ABORT` (4) errors, with messages "Database is suspended", "Transaction was aborted", or "interrupted", for any attempt at writing in the database when it is suspended.
|
||||
|
||||
You can catch those errors:
|
||||
|
||||
```swift
|
||||
do {
|
||||
try dbPool.write { db in ... }
|
||||
} catch DatabaseError.SQLITE_INTERRUPT, DatabaseError.SQLITE_ABORT {
|
||||
// Oops, the database is suspended.
|
||||
// Maybe try again after database is resumed?
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## How to perform cross-process database observation
|
||||
|
||||
GRDB [Database Observation] features, as well as its [Combine publishers] and [RxGRDB], are not able to notify database changes performed by other processes.
|
||||
|
||||
Whenever you need to notify other processes that the database has been changed, you will have to use a cross-process notification mechanism such as [NSFileCoordinator] or [CFNotificationCenterGetDarwinNotifyCenter].
|
||||
|
||||
You can trigger those notifications automatically with [DatabaseRegionObservation]:
|
||||
|
||||
```swift
|
||||
// Notify all changes made to the "player" and "team" database tables
|
||||
let observation = DatabaseRegionObservation(tracking: Player.all(), Team.all())
|
||||
let observer = try observation.start(in: dbPool) { (db: Database) in
|
||||
// Notify other processes
|
||||
}
|
||||
|
||||
// Notify all changes made to the database
|
||||
let observation = DatabaseRegionObservation(tracking: DatabaseRegion.fullDatabase)
|
||||
let observer = try observation.start(in: dbPool) { (db: Database) in
|
||||
// Notify other processes
|
||||
}
|
||||
```
|
||||
|
||||
[Use a Database Pool]: #use-a-database-pool
|
||||
[How to limit the `SQLITE_BUSY` error]: #how-to-limit-the-sqlite_busy-error
|
||||
[How to limit the `0xDEAD10CC` exception]: #how-to-limit-the-0xdead10cc-exception
|
||||
[How to perform cross-process database observation]: #how-to-perform-cross-process-database-observation
|
||||
[Database Pool]: ../README.md#database-pools
|
||||
[Database Observation]: ../README.md#database-changes-observation
|
||||
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
|
||||
[NSFileCoordinator]: https://developer.apple.com/documentation/foundation/nsfilecoordinator
|
||||
[CFNotificationCenterGetDarwinNotifyCenter]: https://developer.apple.com/documentation/corefoundation/1542572-cfnotificationcentergetdarwinnot
|
||||
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
|
||||
[WAL mode]: https://www.sqlite.org/wal.html
|
||||
[How do I monitor the duration of database statements execution?]: ../README.md#how-do-i-monitor-the-duration-of-database-statements-execution
|
||||
[Combine publishers]: Combine.md
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing).
|
||||
@@ -1,242 +1,4 @@
|
||||
Single-Row Tables
|
||||
=================
|
||||
|
||||
Let's talk about database tables that should contain a single row.
|
||||
|
||||
Such tables can store configuration values, user preferences, and generally some global application state. They are a suitable alternative to `UserDefaults` in some applications, especially when configuration refers to values found in other database tables, and database integrity is a concern.
|
||||
|
||||
An alternative way to store such configuration is a table of key-value pairs: two columns, and one row for each configuration value. This technique works, but it has a few drawbacks: you will have to deal with the various types of configuration values (strings, integers, dates, etc), and you won't be able to define foreign keys. This is why we won't explore key-value tables.
|
||||
|
||||
This guide helps you implementing a single-row table with GRDB, with recommendations on the database schema, migrations, and the design of a matching [record] type.
|
||||
|
||||
- [The Single-Row Table]
|
||||
- [The Single-Row Record]
|
||||
- [Wrap-Up]
|
||||
|
||||
|
||||
## The Single-Row Table
|
||||
|
||||
As always with GRDB, everything starts at the level of the database schema. Putting the robust SQLite on our side is always a good idea, because we have to write less code, and this helps shipping less bugs.
|
||||
|
||||
We want to instruct SQLite that our table must never contain more than one row. We will never have to wonder what to do if we were unlucky enough to find two rows with conflicting values in this table.
|
||||
|
||||
SQLite is not able to guarantee that the table is never empty, so we have to deal with two cases: either the table is empty, or it contains one row.
|
||||
|
||||
Those two cases can create a nagging question for the application. By default, inserts fail when the row already exists, and updates fail when the table is empty. In order to avoid those errors, we will have the app perform an insert in case of a failed update (in the [The Single-Row Record] chapter). And we instruct SQLite to just replace the eventual existing row in case of conflicting inserts:
|
||||
|
||||
```swift
|
||||
// CREATE TABLE appConfiguration (
|
||||
// id INTEGER PRIMARY KEY ON CONFLICT REPLACE CHECK (id = 1),
|
||||
// flag BOOLEAN NOT NULL,
|
||||
// ...)
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// Single row guarantee
|
||||
t.column("id", .integer)
|
||||
// Have inserts replace the existing row
|
||||
.primaryKey(onConflict: .replace)
|
||||
// Make sure the id column is always 1
|
||||
.check { $0 == 1 }
|
||||
|
||||
// The configuration columns
|
||||
t.column("flag", .boolean).notNull()
|
||||
// ... other columns
|
||||
}
|
||||
```
|
||||
|
||||
When you use [migrations], you may wonder if it is a good idea or not to perform an initial insert just after the table is created. Well, this is not recommended:
|
||||
|
||||
```swift
|
||||
// NOT RECOMMENDED
|
||||
migrator.registerMigration("appConfiguration") { db in
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// Single row guarantee
|
||||
t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 }
|
||||
|
||||
// Define sensible defaults for each column
|
||||
t.column("flag", .boolean).notNull()
|
||||
.defaults(to: false)
|
||||
// ... other columns
|
||||
}
|
||||
|
||||
// Populate the table
|
||||
try db.execute(sql: "INSERT INTO appConfiguration DEFAULT VALUES")
|
||||
}
|
||||
```
|
||||
|
||||
It is not a good idea to populate the table in a migration, for two reasons:
|
||||
|
||||
1. This is not a hard guarantee that the table will never be empty. As a consequence, this won't prevent your Swift code from dealing with the possibility of a missing row. On top of that, the Swift code that deals with the missing row may not use the same default values as the SQLite schema (a [DRY] violation), with unclear consequences.
|
||||
|
||||
2. Migrations that are shipped in the wild should *never* change, because you want to control the state of the databases installed on your users' devices, regardless of the application version they install first, regardless of how many application versions are skipped when they download an upgrade, etc. By inserting an initial row in a migration, you make it difficult for your application to adjust the sensible default values in the future, while keeping a clear idea of the various installation and upgrade scenarios.
|
||||
|
||||
The recommended migration creates the table, nothing more:
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
migrator.registerMigration("appConfiguration") { db in
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// Single row guarantee
|
||||
t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 }
|
||||
|
||||
// The configuration columns
|
||||
t.column("flag", .boolean).notNull()
|
||||
// ... other columns
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## The Single-Row Record
|
||||
|
||||
Now that the database schema has been defined, we can define the [record] type that will help the application access the single row:
|
||||
|
||||
```swift
|
||||
struct AppConfiguration: Codable {
|
||||
// Support for the single row guarantee
|
||||
private var id = 1
|
||||
|
||||
// The configuration properties
|
||||
var flag: Bool
|
||||
// ... other properties
|
||||
}
|
||||
```
|
||||
|
||||
In case the database table would be empty, we need a default configuration:
|
||||
|
||||
```swift
|
||||
extension AppConfiguration {
|
||||
/// The default configuration
|
||||
static let `default` = AppConfiguration(flag: false, ...)
|
||||
}
|
||||
```
|
||||
|
||||
We make our record able to access the database:
|
||||
|
||||
```swift
|
||||
extension AppConfiguration: FetchableRecord, PersistableRecord {
|
||||
```
|
||||
|
||||
We have seen in the [The Single-Row Table] chapter that by default, updates throw an error if the database table is empty. To avoid this error, we instruct GRDB to perform an insert in case of a failed update (see [Persistence Methods] for more information):
|
||||
|
||||
```swift
|
||||
// Customize the default PersistableRecord behavior
|
||||
func update(_ db: Database, columns: Set<String>) throws {
|
||||
do {
|
||||
try performUpdate(db, columns: columns)
|
||||
} catch PersistenceError.recordNotFound {
|
||||
// No row was updated: perform an insert
|
||||
try performInsert(db)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The standard GRDB method `fetchOne` returns an optional which is nil when the database table is empty. As a convenience, let's define a method that returns a non-optional (replacing the missing row with `default`):
|
||||
|
||||
```swift
|
||||
/// Returns the persisted configuration, or the default one if the
|
||||
/// database table is empty.
|
||||
static func fetch(_ db: Database) throws -> AppConfiguration {
|
||||
try fetchOne(db) ?? .default
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And that's it! Now we can use our singleton record:
|
||||
|
||||
```swift
|
||||
// READ
|
||||
let config = try dbQueue.read { db in
|
||||
try AppConfiguration.fetch(db)
|
||||
}
|
||||
if config.flag {
|
||||
// ...
|
||||
}
|
||||
|
||||
// WRITE
|
||||
try dbQueue.write { db in
|
||||
var config = try AppConfiguration.fetch(db)
|
||||
|
||||
// Update some config values
|
||||
try config.updateChanges(db) {
|
||||
$0.flag = true
|
||||
}
|
||||
|
||||
// Other possible ways to write config:
|
||||
try config.update(db)
|
||||
try config.save(db)
|
||||
try config.insert(db)
|
||||
}
|
||||
```
|
||||
|
||||
The three `update`, `save` and `insert` methods can be used interchangeably: all three make sure the configuration is stored in the database.
|
||||
|
||||
The `updateChanges` method only updates the values changed by its closure argument (and performs an insert if the database table is empty).
|
||||
|
||||
See [Persistence Methods] for more information.
|
||||
|
||||
|
||||
## Wrap-Up
|
||||
|
||||
We all love to copy and paste, don't we? Just customize the template code below:
|
||||
|
||||
```swift
|
||||
// Table creation
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// Single row guarantee
|
||||
t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 }
|
||||
|
||||
// The configuration columns
|
||||
t.column("flag", .boolean).notNull()
|
||||
// ... other columns
|
||||
}
|
||||
```
|
||||
|
||||
```swift
|
||||
//
|
||||
// AppConfiguration.swift
|
||||
//
|
||||
|
||||
import GRDB
|
||||
|
||||
struct AppConfiguration: Codable {
|
||||
// Support for the single row guarantee
|
||||
private var id = 1
|
||||
|
||||
// The configuration properties
|
||||
var flag: Bool
|
||||
// ... other properties
|
||||
}
|
||||
|
||||
extension AppConfiguration {
|
||||
/// The default configuration
|
||||
static let `default` = AppConfiguration(flag: false, ...)
|
||||
}
|
||||
|
||||
// Database Access
|
||||
extension AppConfiguration: FetchableRecord, PersistableRecord {
|
||||
// Customize the default PersistableRecord behavior
|
||||
func update(_ db: Database, columns: Set<String>) throws {
|
||||
do {
|
||||
try performUpdate(db, columns: columns)
|
||||
} catch PersistenceError.recordNotFound {
|
||||
// No row was updated: perform an insert
|
||||
try performInsert(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the persisted configuration, or the default one if the
|
||||
/// database table is empty.
|
||||
static func fetch(_ db: Database) throws -> AppConfiguration {
|
||||
try fetchOne(db) ?? .default
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
[migrations]: Migrations.md
|
||||
[record]: ../README.md#records
|
||||
[The Single-Row Table]: #the-single-row-table
|
||||
[The Single-Row Record]: #the-single-row-record
|
||||
[Wrap-Up]: #wrap-up
|
||||
[DRY]: https://en.wikipedia.org/wiki/Don%27t_repeat_yourself
|
||||
[Persistence Methods]: ../README.md#persistence-methods
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables).
|
||||
@@ -90,7 +90,7 @@ For your convenience, those record protocols can be derived from the [Decodable
|
||||
|
||||
Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with **database change notifications**, with many advantages.
|
||||
|
||||
See [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md) for some practical advice.
|
||||
See [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) for some practical advice.
|
||||
|
||||
|
||||
### Allow database records to cross threads
|
||||
@@ -149,16 +149,16 @@ Next, you choose the dispatch queue on which notifications happen (generally the
|
||||
|
||||
Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, or SQL triggers. GRDB roots its notification system in the rock-solid SQLite itself, so that high-level requests and raw SQL queries are equally supported.
|
||||
|
||||
See [Database Observation](../README.md#database-changes-observation) for further information.
|
||||
See [Database Observation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation) for further information.
|
||||
|
||||
|
||||
### Non-blocking database reads
|
||||
|
||||
GRDB ships with two ways to access databases, [database queues](../README.md#database-queues) and [pools](../README.md#database-pools).
|
||||
GRDB ships with two ways to access databases, [database queues](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue) and [pools](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool).
|
||||
|
||||
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).
|
||||
[Database pools](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool) 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
|
||||
@@ -190,7 +190,7 @@ Finally, raw FMDatabase, SQLite.swift, and Core Data are the hardest tools, and
|
||||
|
||||
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).
|
||||
For practical advice on designing the database access layer of your application, see the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
|
||||
|
||||
|
||||
### Never pay for using raw SQL
|
||||
@@ -285,23 +285,22 @@ If this little tour of GRDB has convinced you, the real trip starts here: [GRDB]
|
||||
|
||||
Happy GRDB! :gift:
|
||||
|
||||
[Concurrency Guide]: Concurrency.md
|
||||
[Concurrency Guide]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency
|
||||
[Core Data]: https://developer.apple.com/documentation/coredata
|
||||
[DatabasePool]: ../README.md#database-pools
|
||||
[DatabasePool]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool
|
||||
[Diesel]: http://diesel.rs
|
||||
[FCModel]: https://github.com/marcoarment/FCModel
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
|
||||
[Fluent]: https://github.com/vapor/fluent
|
||||
[FMDB]: http://github.com/ccgus/fmdb
|
||||
[GRDB]: http://github.com/groue/GRDB.swift
|
||||
[FMDB]: https://github.com/ccgus/fmdb
|
||||
[GRDB]: https://github.com/groue/GRDB.swift
|
||||
[PersistableRecord]: ../README.md#records
|
||||
[Realm]: http://realm.io
|
||||
[FetchableRecord]: ../README.md#records
|
||||
[SQLite.swift]: http://github.com/stephencelis/SQLite.swift
|
||||
[SQLite.swift]: https://github.com/stephencelis/SQLite.swift
|
||||
[StORM]: https://www.perfect.org/docs/StORM.html
|
||||
[Swift-Kuery]: http://github.com/IBM-Swift/Swift-Kuery
|
||||
[Swift-Kuery]: https://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
|
||||
|
||||
+9
-6
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '5.26.1'
|
||||
s.version = '6.29.3'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
@@ -9,23 +9,26 @@ Pod::Spec.new do |s|
|
||||
s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" }
|
||||
s.module_name = 'GRDB'
|
||||
|
||||
s.swift_versions = ['5.3', '5.4', '5.5']
|
||||
s.swift_versions = ['5.7']
|
||||
s.ios.deployment_target = '11.0'
|
||||
s.osx.deployment_target = '10.10'
|
||||
s.watchos.deployment_target = '2.0'
|
||||
s.tvos.deployment_target = '9.0'
|
||||
s.osx.deployment_target = '10.13'
|
||||
s.watchos.deployment_target = '4.0'
|
||||
s.tvos.deployment_target = '11.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'
|
||||
ss.xcconfig = {
|
||||
'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_ENABLE_FTS5',
|
||||
}
|
||||
end
|
||||
|
||||
s.subspec 'SQLCipher' do |ss|
|
||||
ss.source_files = 'GRDB/**/*.swift', 'Support/SQLCipher_config.h'
|
||||
ss.framework = 'Foundation'
|
||||
ss.dependency 'SQLCipher', '>= 3.4.0'
|
||||
ss.dependency 'SQLCipher', '>= 3.4.2'
|
||||
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',
|
||||
|
||||
+299
-2579
File diff suppressed because it is too large.
Load diff
+10
-9
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1230"
|
||||
LastUpgradeVersion = "1400"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -16,7 +16,7 @@
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "DC3773F219C8CBB3004FCF85"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBOSX"
|
||||
BlueprintName = "GRDB"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
@@ -29,8 +29,8 @@
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56E5D7F81B4D422D00430942"
|
||||
BuildableName = "GRDBOSXTests.xctest"
|
||||
BlueprintName = "GRDBOSXTests"
|
||||
BuildableName = "GRDBTests.xctest"
|
||||
BlueprintName = "GRDBTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
@@ -44,12 +44,13 @@
|
||||
codeCoverageEnabled = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
skipped = "NO"
|
||||
parallelizable = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56E5D7F81B4D422D00430942"
|
||||
BuildableName = "GRDBOSXTests.xctest"
|
||||
BlueprintName = "GRDBOSXTests"
|
||||
BuildableName = "GRDBTests.xctest"
|
||||
BlueprintName = "GRDBTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
@@ -70,7 +71,7 @@
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "DC3773F219C8CBB3004FCF85"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBOSX"
|
||||
BlueprintName = "GRDB"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
@@ -86,7 +87,7 @@
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "DC3773F219C8CBB3004FCF85"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBOSX"
|
||||
BlueprintName = "GRDB"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
@@ -1,76 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1230"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "5654909F1D5A4798005622CB"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBWatchOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "5654909F1D5A4798005622CB"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBWatchOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "5654909F1D5A4798005622CB"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBWatchOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -1,87 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1230"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56E5D7C91B4D3FED00430942"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBiOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
codeCoverageEnabled = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56E5D7D21B4D3FEE00430942"
|
||||
BuildableName = "GRDBiOSTests.xctest"
|
||||
BlueprintName = "GRDBiOSTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56E5D7C91B4D3FED00430942"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBiOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56E5D7C91B4D3FED00430942"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBiOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -1,87 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1230"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBtvOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
codeCoverageEnabled = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "AAA4DD07230F262000C74B15"
|
||||
BuildableName = "GRDBtvOSTests.xctest"
|
||||
BlueprintName = "GRDBtvOSTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBtvOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBtvOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
+3
-3
@@ -10,9 +10,6 @@
|
||||
<FileRef
|
||||
location = "group:TransactionObserver.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:CustomizedDecodingOfDatabaseRows.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Associations.playground">
|
||||
</FileRef>
|
||||
@@ -20,6 +17,9 @@
|
||||
location = "group:MyPlayground.playground">
|
||||
</FileRef>
|
||||
</Group>
|
||||
<FileRef
|
||||
location = "group:BRAG.md">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:CHANGELOG.md">
|
||||
</FileRef>
|
||||
|
||||
+299
-143
@@ -1,37 +1,48 @@
|
||||
import Dispatch
|
||||
import Foundation
|
||||
|
||||
/// Configuration for a DatabaseQueue or DatabasePool.
|
||||
public struct Configuration {
|
||||
|
||||
// MARK: - Misc options
|
||||
|
||||
/// If true (the default), support for foreign keys is enabled.
|
||||
/// See <https://www.sqlite.org/foreignkeys.html> for more information.
|
||||
/// A boolean value indicating whether foreign key support is enabled.
|
||||
///
|
||||
/// Default: true
|
||||
/// The default is true.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/foreignkeys.html>.
|
||||
public var foreignKeysEnabled = true
|
||||
|
||||
/// If true, database modifications are disallowed.
|
||||
/// A boolean value indicating whether an SQLite connection is read-only.
|
||||
///
|
||||
/// Default: false
|
||||
/// The default is false.
|
||||
///
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.readonly = true
|
||||
///
|
||||
/// let dbQueue = try DatabaseQueue( // or DatabasePool
|
||||
/// path: "/path/to/database.sqlite",
|
||||
/// configuration: config)
|
||||
/// ```
|
||||
public var readonly = false
|
||||
|
||||
/// The configuration label.
|
||||
/// A label that describes a database connection.
|
||||
///
|
||||
/// You can query this label at runtime:
|
||||
///
|
||||
/// var configuration = Configuration()
|
||||
/// configuration.label = "MyDatabase"
|
||||
/// let dbQueue = try DatabaseQueue(path: ..., configuration: configuration)
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.label = "MyDatabase"
|
||||
/// let dbQueue = try DatabaseQueue(configuration: config)
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// print(db.configuration.label) // Prints "MyDatabase"
|
||||
/// }
|
||||
/// try dbQueue.read { db in
|
||||
/// print(db.configuration.label) // Prints "MyDatabase"
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The configuration label is also used to name Database connections (the
|
||||
/// `Database.description` property), and the various dispatch queues
|
||||
/// created by GRDB, visible in debugging sessions and crash logs.
|
||||
/// The configuration label is also used to name ``Database`` connections
|
||||
/// (their ``Database/description`` property), and the various dispatch
|
||||
/// queues created by GRDB, visible in debugging sessions and crash logs.
|
||||
///
|
||||
/// Those connection names and dispatch queue labels are intended for
|
||||
/// debugging only. Their format may change between GRDB releases.
|
||||
@@ -66,62 +77,68 @@ public struct Configuration {
|
||||
/// The default configuration label is nil.
|
||||
public var label: String? = nil
|
||||
|
||||
/// If false, SQLite from version 3.29.0 will not interpret a double-quoted
|
||||
/// string as a string literal if it does not match any valid identifier.
|
||||
/// A boolean value indicating whether SQLite 3.29+ interprets
|
||||
/// double-quoted strings as string literals when they does not match any
|
||||
/// valid identifier.
|
||||
///
|
||||
/// For example:
|
||||
/// The default and recommended value is false:
|
||||
///
|
||||
/// // Error: no such column: foo
|
||||
/// let name = try String.fetchOne(db, sql: """
|
||||
/// SELECT "foo" FROM "player"
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// // Error: no such column: missingColumn
|
||||
/// let name = try String.fetchOne(db, sql: """
|
||||
/// SELECT "missingColumn" FROM "player"
|
||||
/// """)
|
||||
/// ```
|
||||
///
|
||||
/// When true, or before version 3.29.0, such strings are interpreted as
|
||||
/// string literals, as in the example below. This is a well known SQLite
|
||||
/// [misfeature](https://sqlite.org/quirks.html#dblquote).
|
||||
/// When true, or before SQLite version 3.29.0, double-quoted strings that
|
||||
/// do not match any valid identifier are interpreted as string literals,
|
||||
/// as in the example below. This is an SQLite
|
||||
/// [misfeature](https://sqlite.org/quirks.html#double_quoted_string_literals_are_accepted):
|
||||
///
|
||||
/// // Success: "foo"
|
||||
/// let name = try String.fetchOne(db, sql: """
|
||||
/// SELECT "foo" FROM "player"
|
||||
/// """)
|
||||
///
|
||||
/// - Recommended value: false
|
||||
/// - Default value: false
|
||||
/// ```swift
|
||||
/// // MISFEATURE: This query succeeds with result "missingColumn"
|
||||
/// let name = try String.fetchOne(db, sql: """
|
||||
/// SELECT "missingColumn" FROM "player"
|
||||
/// """)
|
||||
/// ```
|
||||
public var acceptsDoubleQuotedStringLiterals = false
|
||||
|
||||
/// When true, the `Database.suspendNotification` and
|
||||
/// `Database.resumeNotification` suspend and resume the database. Database
|
||||
/// suspension helps avoiding the [`0xdead10cc`
|
||||
/// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report).
|
||||
/// A boolean value indicating whether the database connection listens to
|
||||
/// the ``Database/suspendNotification`` and ``Database/resumeNotification``
|
||||
/// notifications.
|
||||
///
|
||||
/// During suspension, all database accesses but reads in WAL mode may throw
|
||||
/// a DatabaseError of code `SQLITE_INTERRUPT`, or `SQLITE_ABORT`. You can
|
||||
/// check for those error codes with the
|
||||
/// `DatabaseError.isInterruptionError` property.
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// Set this flag to true when you apply the technique described in
|
||||
/// <doc:DatabaseSharing#How-to-limit-the-0xDEAD10CC-exception>. See
|
||||
/// ``Database/suspendNotification`` for more informations about
|
||||
/// suspended databases.
|
||||
public var observesSuspensionNotifications = false
|
||||
|
||||
/// If false (the default), statement arguments are not visible in the
|
||||
/// description of database errors and trace events, preventing sensitive
|
||||
/// information from leaking in unexpected places.
|
||||
/// A boolean value indicating whether statement arguments are visible in
|
||||
/// the description of database errors and trace events.
|
||||
///
|
||||
/// For example:
|
||||
/// The default and recommended value is false: statement arguments are not
|
||||
/// visible in database errors and trace events, preventing sensitive
|
||||
/// information from leaking in unexpected places. For example:
|
||||
///
|
||||
/// // Error: sensitive information is not printed when an error occurs:
|
||||
/// do {
|
||||
/// let email = "..." // sensitive information
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// print(error)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// db.trace { event in
|
||||
/// // By default, sensitive information is NOT printed
|
||||
/// // when a statement is traced:
|
||||
/// print(event)
|
||||
/// }
|
||||
///
|
||||
/// // Trace: sensitive information is not printed when a statement is traced:
|
||||
/// db.trace { event in
|
||||
/// print(event)
|
||||
/// }
|
||||
/// let email = "..." // sensitive information
|
||||
/// do {
|
||||
/// // The sensitive information to protect
|
||||
/// let email = "..."
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// // By default, sensitive information is NOT printed
|
||||
/// // when an error occurs:
|
||||
/// print(error)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// For debugging purpose, you can set this flag to true, and get more
|
||||
/// precise database reports. It is your responsibility to prevent sensitive
|
||||
@@ -129,175 +146,314 @@ public struct Configuration {
|
||||
/// this flag in release builds (think about GDPR and other
|
||||
/// privacy-related rules):
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// #if DEBUG
|
||||
/// // Protect sensitive information by enabling verbose debugging in DEBUG builds only
|
||||
/// config.publicStatementArguments = true
|
||||
/// #endif
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// #if DEBUG
|
||||
/// // Enable verbose debugging in DEBUG builds only
|
||||
/// config.publicStatementArguments = true
|
||||
/// #endif
|
||||
///
|
||||
/// // The descriptions of trace events and errors now contain the
|
||||
/// // sensitive information:
|
||||
/// db.trace { event in
|
||||
/// print(event)
|
||||
/// }
|
||||
/// do {
|
||||
/// let email = "..."
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// print(error)
|
||||
/// }
|
||||
/// db.trace { event in
|
||||
/// // Sensitive information is printed in DEBUG builds:
|
||||
/// print(event)
|
||||
/// }
|
||||
///
|
||||
/// do {
|
||||
/// // The sensitive information to protect
|
||||
/// let email = "..."
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// // Sensitive information is printed in DEBUG builds:
|
||||
/// print(error)
|
||||
/// }
|
||||
/// ```
|
||||
public var publicStatementArguments = false
|
||||
|
||||
/// The clock that feeds ``Database/transactionDate``.
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// The default clock is ``DefaultTransactionClock`` (which returns the
|
||||
/// start date of the current transaction).
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.transactionClock = .custom { db in /* return some Date */ }
|
||||
/// ```
|
||||
public var transactionClock: any TransactionClock = .default
|
||||
|
||||
// MARK: - Managing SQLite Connections
|
||||
|
||||
private var setups: [(Database) throws -> Void] = []
|
||||
|
||||
/// The function argument is run when an SQLite connection is opened,
|
||||
/// before the connection is made available for database access methods.
|
||||
/// Defines a function to run whenever an SQLite connection is opened.
|
||||
///
|
||||
/// The preparation function is run before the connection is made available
|
||||
/// for database access methods.
|
||||
///
|
||||
/// This method can be called several times. The preparation functions are
|
||||
/// run in the same order.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// try db.execute(sql: "PRAGMA kdf_iter = 10000")
|
||||
/// }
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// // Prints all SQL statements
|
||||
/// db.trace { print("SQL >", $0) }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When you use a `DatabasePool`, preparation functions are called for
|
||||
/// When you use a ``DatabasePool``, preparation functions are called for
|
||||
/// the writer connection and all reader connections. You can distinguish
|
||||
/// them by querying `db.configuration.readonly`:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// if db.configuration.readonly {
|
||||
/// // reader connection
|
||||
/// } else {
|
||||
/// // writer connection
|
||||
/// }
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// if db.configuration.readonly {
|
||||
/// // reader connection
|
||||
/// } else {
|
||||
/// // writer connection
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// On newly created databases, `DatabasePool` the WAL mode is activated
|
||||
/// after the preparation functions have run.
|
||||
/// On newly created databases files, ``DatabasePool`` activates the WAL
|
||||
/// mode after the preparation functions have run.
|
||||
public mutating func prepareDatabase(_ setup: @escaping (Database) throws -> Void) {
|
||||
setups.append(setup)
|
||||
}
|
||||
|
||||
// MARK: - Transactions
|
||||
|
||||
/// The default kind of transaction.
|
||||
/// The default kind of write transactions.
|
||||
///
|
||||
/// Default: deferred
|
||||
/// The default is ``Database/TransactionKind/deferred``.
|
||||
///
|
||||
/// You can change the default transaction kind. For example, you can force
|
||||
/// all write transactions to be `IMMEDIATE`:
|
||||
///
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.defaultTransactionKind = .immediate
|
||||
/// let dbQueue = try DatabaseQueue(configuration: config)
|
||||
///
|
||||
/// // BEGIN IMMEDIATE TRANSACTION; ...; COMMIT TRANSACTION;
|
||||
/// try dbQueue.write { db in ... }
|
||||
/// ```
|
||||
///
|
||||
/// This property is ignored for read-only transactions. Those always open
|
||||
/// `DEFERRED` SQLite transactions.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>
|
||||
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.
|
||||
/// A boolean value indicating whether it is valid to leave a transaction
|
||||
/// opened at the end of a database access method.
|
||||
///
|
||||
/// For example:
|
||||
/// The default value is false: not completing a transaction is a
|
||||
/// programmer error:
|
||||
///
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
/// ```swift
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
///
|
||||
/// // fatal error: A transaction has been left opened at the end of a database access
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.beginTransaction()
|
||||
/// }
|
||||
/// // 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:
|
||||
/// When true, one can leave opened transaction at the end of database
|
||||
/// access method:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.allowsUnsafeTransactions = true
|
||||
/// let dbQueue = DatabaseQueue(configuration: config)
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.allowsUnsafeTransactions = true
|
||||
/// let dbQueue = try DatabaseQueue(configuration: config)
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.beginTransaction()
|
||||
/// }
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.beginTransaction()
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.commit()
|
||||
/// }
|
||||
/// 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
|
||||
/// This configuration flag has no effect on ``DatabasePool`` reader
|
||||
/// connections: those never allow leaving a transaction opened at the end
|
||||
/// of a read access.
|
||||
public var allowsUnsafeTransactions = false
|
||||
|
||||
// MARK: - Journal Mode
|
||||
|
||||
/// Defines how the journal mode is configured when the database
|
||||
/// connection is opened.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_journal_mode>
|
||||
public enum JournalModeConfiguration: Sendable {
|
||||
/// The default setup has ``DatabaseQueue`` perform no specific
|
||||
/// configuration of the journal mode, and ``DatabasePool``
|
||||
/// configure the database for the WAL mode (just like the
|
||||
/// ``wal`` case).
|
||||
case `default`
|
||||
|
||||
/// The journal mode is set to WAL (plus extra configurations that
|
||||
/// make life easier with WAL databases).
|
||||
case wal
|
||||
}
|
||||
|
||||
/// Defines how the journal mode is configured when the database
|
||||
/// connection is opened.
|
||||
///
|
||||
/// This configuration is ignored when ``readonly`` is true.
|
||||
///
|
||||
/// The default value has ``DatabaseQueue`` perform no specific
|
||||
/// configuration of the journal mode, and ``DatabasePool`` configure
|
||||
/// the database for the WAL mode.
|
||||
///
|
||||
/// Applications that need to open a WAL database with a
|
||||
/// ``DatabaseQueue`` should set the `journalMode` to `wal`:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Open a WAL database with DatabaseQueue
|
||||
/// var config = Configuration()
|
||||
/// config.journalMode = .wal
|
||||
/// let dbQueue = try DatabaseQueue(path: "...", configuration: config)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_journal_mode>
|
||||
public var journalMode = JournalModeConfiguration.default
|
||||
|
||||
// MARK: - Concurrency
|
||||
|
||||
/// The behavior in case of SQLITE_BUSY error. See <https://www.sqlite.org/rescode.html#busy>
|
||||
/// Defines the how `SQLITE_BUSY` errors are handled.
|
||||
///
|
||||
/// Default: immediateError
|
||||
/// The default is ``Database/BusyMode/immediateError``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/rescode.html#busy>
|
||||
public var busyMode: Database.BusyMode = .immediateError
|
||||
|
||||
/// The behavior in case of SQLITE_BUSY error, for read-only connections.
|
||||
/// If nil, GRDB picks a default one.
|
||||
var readonlyBusyMode: Database.BusyMode? = nil
|
||||
|
||||
/// The maximum number of concurrent readers (applies to database
|
||||
/// pools only).
|
||||
/// The maximum number of concurrent reader connections.
|
||||
///
|
||||
/// Default: 5
|
||||
/// This configuration has effect on ``DatabasePool`` and
|
||||
/// ``DatabaseSnapshotPool`` only. The default value is 5.
|
||||
///
|
||||
/// You can query this value at runtime in order to get the actual capacity
|
||||
/// for concurrent reads of any ``DatabaseReader``. In this context,
|
||||
/// ``DatabaseQueue`` and ``DatabaseSnapshot`` have a capacity of 1,
|
||||
/// because they can't perform two concurrent reads. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.maximumReaderCount = 5
|
||||
///
|
||||
/// let path = "/path/to/database.sqlite"
|
||||
/// let dbQueue = try DatabaseQueue(path: path, configuration: config)
|
||||
/// let dbPool = try DatabasePool(path: path, configuration: config)
|
||||
/// let dbSnapshot = try dbPool.makeSnapshot()
|
||||
///
|
||||
/// print(dbQueue.configuration.maximumReaderCount) // 1
|
||||
/// print(dbPool.configuration.maximumReaderCount) // 5
|
||||
/// print(dbSnapshot.configuration.maximumReaderCount) // 1
|
||||
/// ```
|
||||
public var maximumReaderCount: Int = 5
|
||||
|
||||
/// The quality of service class for the work performed by the database.
|
||||
/// The quality of service of database accesses.
|
||||
///
|
||||
/// The quality of service is ignored if you supply a target queue.
|
||||
/// The quality of service is ignored if you supply a ``targetQueue``.
|
||||
///
|
||||
/// Default: .userInitiated
|
||||
/// The default is `userInitiated`.
|
||||
public var qos: DispatchQoS = .userInitiated
|
||||
|
||||
/// The quality of service of read accesses
|
||||
var readQoS: DispatchQoS {
|
||||
/// The effective quality of service of read-only database accesses.
|
||||
public var readQoS: DispatchQoS {
|
||||
targetQueue?.qos ?? self.qos
|
||||
}
|
||||
|
||||
/// A target queue for database accesses.
|
||||
/// The effective quality of service of write database accesses.
|
||||
public var writeQoS: DispatchQoS {
|
||||
writeTargetQueue?.qos ?? targetQueue?.qos ?? self.qos
|
||||
}
|
||||
|
||||
/// The target dispatch queue for database accesses.
|
||||
///
|
||||
/// Database connections which are not read-only will prefer
|
||||
/// `writeTargetQueue` instead, if it is not nil.
|
||||
/// ``writeTargetQueue`` instead, if it is not nil.
|
||||
///
|
||||
/// When you use a database pool, make sure this queue is concurrent. This
|
||||
/// When you use ``DatabasePool``, make sure this queue is concurrent. This
|
||||
/// is because in a serial dispatch queue, no concurrent database access can
|
||||
/// happen, and you may experience deadlocks.
|
||||
///
|
||||
/// If the queue is nil, all database accesses happen in unspecified
|
||||
/// dispatch queues whose quality of service is determined by the
|
||||
/// `qos` property.
|
||||
/// ``qos`` property.
|
||||
///
|
||||
/// Default: nil
|
||||
/// The default is nil.
|
||||
public var targetQueue: DispatchQueue? = nil
|
||||
|
||||
/// The target queue for database connections which are not read-only.
|
||||
/// The target dispatch queue for write database accesses.
|
||||
///
|
||||
/// If this queue is nil, writer connections are controlled by `targetQueue`.
|
||||
/// If this queue is nil, writer connections are controlled
|
||||
/// by ``targetQueue``.
|
||||
///
|
||||
/// Default: nil
|
||||
/// The default is nil.
|
||||
public var writeTargetQueue: DispatchQueue? = nil
|
||||
|
||||
#if os(iOS)
|
||||
/// Sets whether GRDB will release memory when entering the background or
|
||||
/// upon receiving a memory warning in iOS.
|
||||
/// A boolean value indicating whether the database connection releases
|
||||
/// memory when entering the background or upon receiving a memory warning
|
||||
/// in iOS.
|
||||
///
|
||||
/// Default: true
|
||||
/// The default is true.
|
||||
public var automaticMemoryManagement = true
|
||||
#endif
|
||||
|
||||
|
||||
/// A boolean value indicating whether read-only connections should be
|
||||
/// kept open.
|
||||
///
|
||||
/// This configuration flag applies to ``DatabasePool`` only. The
|
||||
/// default value is false.
|
||||
///
|
||||
/// When the flag is false, a `DatabasePool` closes read-only
|
||||
/// connections when requested to dispose non-essential memory with
|
||||
/// ``DatabasePool/releaseMemory()``. When true, those connections are
|
||||
/// kept open.
|
||||
///
|
||||
/// Consider setting this flag to true when profiling your application
|
||||
/// reveals that a lot of time is spent opening new SQLite connections.
|
||||
public var persistentReadOnlyConnections = false
|
||||
|
||||
// MARK: - Factory Configuration
|
||||
|
||||
/// Creates a factory configuration
|
||||
/// Creates a factory configuration.
|
||||
public init() { }
|
||||
|
||||
// MARK: - Not Public
|
||||
|
||||
var threadingMode: Database.ThreadingMode = .`default`
|
||||
/// The SQLite [threading mode](https://www.sqlite.org/threadsafe.html).
|
||||
///
|
||||
/// - Note: Only the multi-thread mode (`SQLITE_OPEN_NOMUTEX`) is currently
|
||||
/// supported, since all <doc:DatabaseConnections> access SQLite connections
|
||||
/// through a `SerializedDatabase`.
|
||||
var threadingMode = Database.ThreadingMode.default
|
||||
|
||||
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
|
||||
var SQLiteOpenFlags: CInt {
|
||||
var flags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE)
|
||||
if sqlite3_libversion_number() >= 3037000 {
|
||||
flags |= 0x02000000 // SQLITE_OPEN_EXRESCODE
|
||||
}
|
||||
return threadingMode.SQLiteOpenFlags | flags
|
||||
}
|
||||
|
||||
func setUp(_ db: Database) throws {
|
||||
@@ -323,7 +479,7 @@ public struct Configuration {
|
||||
/// Creates a DispatchQueue which has the quality of service and target
|
||||
/// queue of read accesses.
|
||||
func makeReaderDispatchQueue(label: String) -> DispatchQueue {
|
||||
if let targetQueue = targetQueue {
|
||||
if let targetQueue {
|
||||
return DispatchQueue(label: label, target: targetQueue)
|
||||
} else {
|
||||
return DispatchQueue(label: label, qos: qos)
|
||||
|
||||
+213
-95
@@ -19,12 +19,9 @@ extension RangeReplaceableCollection {
|
||||
/// let strings = try Array(cursor)
|
||||
///
|
||||
/// - parameter cursor: The cursor whose elements feed the collection.
|
||||
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
|
||||
public init(_ cursor: some Cursor<Element>) throws {
|
||||
self.init()
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
// database cursors.
|
||||
try cursor.forEach { append($0) }
|
||||
try append(contentsOf: cursor)
|
||||
}
|
||||
|
||||
/// Creates a collection containing the elements of a cursor.
|
||||
@@ -36,13 +33,23 @@ extension RangeReplaceableCollection {
|
||||
/// - parameter cursor: The cursor whose elements feed the collection.
|
||||
/// - parameter minimumCapacity: Prepares the returned collection to store
|
||||
/// the specified number of elements.
|
||||
public init<C: Cursor>(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element {
|
||||
public init(_ cursor: some Cursor<Element>, minimumCapacity: Int) throws {
|
||||
self.init()
|
||||
reserveCapacity(minimumCapacity)
|
||||
try append(contentsOf: cursor)
|
||||
}
|
||||
|
||||
/// Adds the elements of a cursor to the end of this collection.
|
||||
///
|
||||
/// In case of error, an unspecified amount of elements have been added to
|
||||
/// the collection.
|
||||
///
|
||||
/// - parameter newElements: The elements to append to the collection.
|
||||
public mutating func append(contentsOf newElements: some Cursor<Element>) throws {
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
// database cursors.
|
||||
try cursor.forEach { append($0) }
|
||||
try newElements.forEach { append($0) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,9 +119,7 @@ extension Dictionary {
|
||||
/// - parameter keysAndValues: A cursor of key-value pairs to use for the
|
||||
/// new dictionary. Every key in `keysAndValues` must be unique.
|
||||
/// - precondition: The cursor must not have duplicate keys.
|
||||
public init<C: Cursor>(uniqueKeysWithValues keysAndValues: C)
|
||||
throws where C.Element == (Key, Value)
|
||||
{
|
||||
public init(uniqueKeysWithValues keysAndValues: some Cursor<(Key, Value)>) throws {
|
||||
self.init()
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
@@ -144,9 +149,7 @@ extension Dictionary {
|
||||
/// - parameter keysAndValues: A cursor of key-value pairs to use for the
|
||||
/// new dictionary. Every key in `keysAndValues` must be unique.
|
||||
/// - precondition: The cursor must not have duplicate keys.
|
||||
public init<C: Cursor>(minimumCapacity: Int, uniqueKeysWithValues keysAndValues: C)
|
||||
throws where C.Element == (Key, Value)
|
||||
{
|
||||
public init(minimumCapacity: Int, uniqueKeysWithValues keysAndValues: some Cursor<(Key, Value)>) throws {
|
||||
self.init(minimumCapacity: minimumCapacity)
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
@@ -167,7 +170,7 @@ extension Set {
|
||||
/// let strings = try Set(cursor)
|
||||
///
|
||||
/// - parameter cursor: A cursor of values to gather into a set.
|
||||
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
|
||||
public init(_ cursor: some Cursor<Element>) throws {
|
||||
self.init()
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
@@ -185,13 +188,63 @@ extension Set {
|
||||
/// - parameter minimumCapacity: The minimum number of elements that the
|
||||
/// newly created set should be able to store without reallocating its
|
||||
/// storage buffer.
|
||||
public init<C: Cursor>(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element {
|
||||
public init(_ cursor: some Cursor<Element>, minimumCapacity: Int) throws {
|
||||
self.init(minimumCapacity: minimumCapacity)
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
// database cursors.
|
||||
try cursor.forEach { insert($0) }
|
||||
}
|
||||
|
||||
/// Returns a new set with the elements of both this set and the
|
||||
/// given cursor.
|
||||
///
|
||||
/// If the set already contains one or more elements that are also in
|
||||
/// the cursor, the existing members are kept. If the cursor contains
|
||||
/// multiple instances of equivalent elements, only the first instance
|
||||
/// is kept.
|
||||
///
|
||||
/// - parameter cursor: A cursor of elements.
|
||||
/// - returns: A new set with the unique elements of this set
|
||||
/// and `cursor`.
|
||||
public func union(_ cursor: some Cursor<Element>) throws -> Set<Element> {
|
||||
var result = self
|
||||
try result.formUnion(cursor)
|
||||
return result
|
||||
}
|
||||
|
||||
/// Inserts the elements of the given cursor into the set.
|
||||
///
|
||||
/// If the set already contains one or more elements that are also in
|
||||
/// the cursor, the existing members are kept. If the cursor contains
|
||||
/// multiple instances of equivalent elements, only the first instance
|
||||
/// is kept.
|
||||
///
|
||||
/// - parameter cursor: A cursor of elements.
|
||||
public mutating func formUnion(_ cursor: some Cursor<Element>) throws {
|
||||
while let element = try cursor.next() {
|
||||
insert(element)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a new set with the elements that are common to both this set
|
||||
/// and the given cursor.
|
||||
///
|
||||
/// - parameter cursor: A cursor of elements.
|
||||
/// - returns: A new set.
|
||||
public func intersection(_ cursor: some Cursor<Element>) throws -> Set<Element> {
|
||||
var result = self
|
||||
try result.formIntersection(cursor)
|
||||
return result
|
||||
}
|
||||
|
||||
/// Removes the elements of the set that aren’t also in the
|
||||
/// given cursor.
|
||||
///
|
||||
/// - parameter cursor: A cursor of elements.
|
||||
public mutating func formIntersection(_ cursor: some Cursor<Element>) throws {
|
||||
try formIntersection(Set(cursor))
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
@@ -211,13 +264,13 @@ extension Sequence {
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// The most common way to iterate over the elements of a cursor is to use a
|
||||
/// `while` loop:
|
||||
/// To iterate over the elements of a cursor, use a `while` loop:
|
||||
///
|
||||
/// let cursor = ...
|
||||
/// while let element = try cursor.next() {
|
||||
/// ...
|
||||
/// }
|
||||
/// ```swift
|
||||
/// while let element = try cursor.next() {
|
||||
/// print(element)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ## Relationship with standard Sequence and IteratorProtocol
|
||||
///
|
||||
@@ -234,12 +287,28 @@ extension Sequence {
|
||||
/// `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`,
|
||||
/// `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`,
|
||||
/// `suffix`.
|
||||
public protocol Cursor: AnyObject {
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``AnyCursor``
|
||||
/// - ``DropFirstCursor``
|
||||
/// - ``DropWhileCursor``
|
||||
/// - ``EnumeratedCursor``
|
||||
/// - ``FilterCursor``
|
||||
/// - ``FlattenCursor``
|
||||
/// - ``MapCursor``
|
||||
/// - ``PrefixCursor``
|
||||
/// - ``PrefixWhileCursor``
|
||||
public protocol Cursor<Element>: AnyObject {
|
||||
/// The type of element traversed by the cursor.
|
||||
associatedtype Element
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next element
|
||||
/// exists. Once nil has been returned, all subsequent calls return nil.
|
||||
/// exists.
|
||||
///
|
||||
/// Once nil has been returned, all subsequent calls return nil.
|
||||
func next() throws -> Element?
|
||||
|
||||
/// Calls the given closure on each element in the cursor.
|
||||
@@ -247,10 +316,12 @@ public protocol Cursor: AnyObject {
|
||||
}
|
||||
|
||||
extension Cursor {
|
||||
/// Returns a Boolean value indicating whether the cursor contains
|
||||
/// an element.
|
||||
public func isEmpty() throws -> Bool {
|
||||
try next() == nil
|
||||
/// Returns a Boolean value indicating whether the cursor does not contain
|
||||
/// any element.
|
||||
///
|
||||
/// - important: This property may consume elements.
|
||||
public var isEmpty: Bool {
|
||||
get throws { try next() == nil }
|
||||
}
|
||||
|
||||
/// Returns a Boolean value indicating whether the cursor contains an
|
||||
@@ -311,7 +382,7 @@ extension Cursor {
|
||||
/// Returns a cursor that skips any initial elements that satisfy
|
||||
/// `predicate`.
|
||||
///
|
||||
/// - Parameter predicate: A closure that takes an element of the cursir as
|
||||
/// - Parameter predicate: A closure that takes an element of the cursor 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.
|
||||
@@ -667,36 +738,37 @@ extension Cursor where Element: StringProtocol {
|
||||
|
||||
// MARK: Specialized Cursors
|
||||
|
||||
/// A type-erased cursor of Element.
|
||||
/// A type-erased cursor.
|
||||
///
|
||||
/// This cursor forwards its next() method to an arbitrary underlying cursor
|
||||
/// having the same Element type, hiding the specifics of the underlying
|
||||
/// cursor.
|
||||
/// An instance of `AnyCursor` forwards its operations to an underlying base
|
||||
/// cursor having the same `Element` type, hiding the specifics of the
|
||||
/// underlying cursor.
|
||||
public final class AnyCursor<Element>: Cursor {
|
||||
private let _next: () throws -> Element?
|
||||
private let _forEach: ((Element) throws -> Void) throws -> Void
|
||||
|
||||
/// Creates a cursor that wraps a base cursor but whose type depends only on
|
||||
/// the base cursor’s element type
|
||||
/// Creates a new cursor that wraps and forwards operations to `base`.
|
||||
public init<C: Cursor>(_ base: C) where C.Element == Element {
|
||||
_next = base.next
|
||||
_forEach = base.forEach
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
/// Creates a new cursor whose elements are elements of `iterator`.
|
||||
public convenience init<I>(iterator: I)
|
||||
where I: IteratorProtocol, 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 new cursor whose elements are elements of `sequence`.
|
||||
public convenience init<S>(_ sequence: S)
|
||||
where S: Sequence, S.Element == Element
|
||||
{
|
||||
self.init(iterator: sequence.makeIterator())
|
||||
}
|
||||
|
||||
/// Creates a cursor that wraps the given closure in its next() method
|
||||
/// Creates a cursor that wraps the given closure in its ``next()`` method.
|
||||
public init(_ next: @escaping () throws -> Element?) {
|
||||
_next = next
|
||||
_forEach = {
|
||||
@@ -711,8 +783,14 @@ public final class AnyCursor<Element>: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public final class DropFirstCursor<Base: Cursor>: Cursor {
|
||||
// Explicit non-conformance to Sendable: a type-erased cursor can't be more
|
||||
// sendable than non-sendable cursors (such as `DatabaseCursor`).
|
||||
@available(*, unavailable)
|
||||
extension AnyCursor: Sendable { }
|
||||
|
||||
/// A `Cursor` that consumes and drops n elements from an underlying `Base`
|
||||
/// cursor before possibly returning the first available element.
|
||||
public final class DropFirstCursor<Base: Cursor> {
|
||||
private let base: Base
|
||||
private let limit: Int
|
||||
private var dropped: Int = 0
|
||||
@@ -722,7 +800,14 @@ public final class DropFirstCursor<Base: Cursor>: Cursor {
|
||||
self.base = base
|
||||
self.limit = limit
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `DropFirstCursor` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension DropFirstCursor: Sendable { }
|
||||
|
||||
extension DropFirstCursor: Cursor {
|
||||
public func next() throws -> Base.Element? {
|
||||
while dropped < limit {
|
||||
if try base.next() == nil {
|
||||
@@ -735,11 +820,9 @@ public final class DropFirstCursor<Base: Cursor>: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
/// A `Cursor` whose elements consist of the elements that follow the initial
|
||||
/// consecutive elements of some `Base` cursor that satisfy a given predicate.
|
||||
public final class DropWhileCursor<Base: Cursor> {
|
||||
private let base: Base
|
||||
private let predicate: (Base.Element) throws -> Bool
|
||||
private var predicateHasFailed = false
|
||||
@@ -748,7 +831,14 @@ public final class DropWhileCursor<Base: Cursor>: Cursor {
|
||||
self.base = base
|
||||
self.predicate = predicate
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `DropWhileCursor` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension DropWhileCursor: Sendable { }
|
||||
|
||||
extension DropWhileCursor: Cursor {
|
||||
public func next() throws -> Base.Element? {
|
||||
if predicateHasFailed {
|
||||
return try base.next()
|
||||
@@ -766,19 +856,24 @@ public final class DropWhileCursor<Base: Cursor>: Cursor {
|
||||
|
||||
/// An enumeration of the elements of a cursor.
|
||||
///
|
||||
/// To create an instance of `EnumeratedCursor`, call the `enumerated()` method
|
||||
/// on a cursor:
|
||||
/// `EnumeratedCursor` is a cursor of pairs _(n, x)_, where _ns_ are consecutive
|
||||
/// `Int` values starting at zero, and _xs_ are the elements of a `Base` cursor.
|
||||
///
|
||||
/// 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"
|
||||
/// To create an instance of `EnumeratedCursor`, call `enumerated()` on a
|
||||
/// cursor. For example:
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class EnumeratedCursor<Base: Cursor>: Cursor {
|
||||
/// ```swift
|
||||
/// let base = try String.fetchCursor(db, sql: """
|
||||
/// SELECT 'foo' UNION ALL SELECT 'bar'
|
||||
/// """)
|
||||
/// let cursor = base.enumerated()
|
||||
/// while let (n, x) = cursor.next() {
|
||||
/// print("\(n): \(x)")
|
||||
/// }
|
||||
/// // Prints: "0: foo"
|
||||
/// // Prints: "1: bar"
|
||||
/// ```
|
||||
public final class EnumeratedCursor<Base: Cursor> {
|
||||
private let base: Base
|
||||
private var index: Int
|
||||
|
||||
@@ -786,7 +881,14 @@ public final class EnumeratedCursor<Base: Cursor>: Cursor {
|
||||
self.base = base
|
||||
self.index = 0
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `EnumeratedCursor` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension EnumeratedCursor: Sendable { }
|
||||
|
||||
extension EnumeratedCursor: Cursor {
|
||||
public func next() throws -> (Int, Base.Element)? {
|
||||
guard let element = try base.next() else { return nil }
|
||||
defer { index += 1 }
|
||||
@@ -801,11 +903,9 @@ public final class EnumeratedCursor<Base: Cursor>: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor whose elements consist of the elements of some base cursor that
|
||||
/// A `Cursor` whose elements consist of the elements of some `Base` cursor that
|
||||
/// also satisfy a given predicate.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class FilterCursor<Base: Cursor>: Cursor {
|
||||
public final class FilterCursor<Base: Cursor> {
|
||||
private let base: Base
|
||||
private let isIncluded: (Base.Element) throws -> Bool
|
||||
|
||||
@@ -813,7 +913,9 @@ public final class FilterCursor<Base: Cursor>: Cursor {
|
||||
self.base = base
|
||||
self.isIncluded = isIncluded
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension FilterCursor: Cursor {
|
||||
public func next() throws -> Base.Element? {
|
||||
while let element = try base.next() {
|
||||
if try isIncluded(element) {
|
||||
@@ -832,20 +934,23 @@ public final class FilterCursor<Base: Cursor>: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor consisting of all the elements contained in each segment contained
|
||||
/// in some Base cursor.
|
||||
///
|
||||
/// See Cursor.joined(), Cursor.flatMap(_:), Sequence.flatMap(_:)
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class FlattenCursor<Base: Cursor>: Cursor where Base.Element: Cursor {
|
||||
/// A `Cursor` consisting of all the elements contained in each segment
|
||||
/// contained in some `Base` cursor.
|
||||
public final class FlattenCursor<Base: Cursor> where Base.Element: Cursor {
|
||||
private let base: Base
|
||||
private var inner: Base.Element?
|
||||
|
||||
init(_ base: Base) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `EnumeratedCursor` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension FlattenCursor: Sendable { }
|
||||
|
||||
extension FlattenCursor: Cursor {
|
||||
public func next() throws -> Base.Element.Element? {
|
||||
while true {
|
||||
if let element = try inner?.next() {
|
||||
@@ -859,13 +964,9 @@ public final class FlattenCursor<Base: Cursor>: Cursor where Base.Element: Curso
|
||||
}
|
||||
}
|
||||
|
||||
/// A Cursor whose elements consist of those in a Base Cursor passed through a
|
||||
/// transform function returning Element.
|
||||
///
|
||||
/// See Cursor.map(_:)
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class MapCursor<Base: Cursor, Element>: Cursor {
|
||||
/// A `Cursor` whose elements consist of those in a `Base` cursor passed through
|
||||
/// a transform function returning Element.
|
||||
public final class MapCursor<Base: Cursor, Element> {
|
||||
private let base: Base
|
||||
private let transform: (Base.Element) throws -> Element
|
||||
|
||||
@@ -873,7 +974,14 @@ public final class MapCursor<Base: Cursor, Element>: Cursor {
|
||||
self.base = base
|
||||
self.transform = transform
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: There is no known reason for making
|
||||
// it thread-safe (`transform` a Sendable closure).
|
||||
@available(*, unavailable)
|
||||
extension MapCursor: Sendable { }
|
||||
|
||||
extension MapCursor: Cursor {
|
||||
public func next() throws -> Element? {
|
||||
guard let element = try base.next() else { return nil }
|
||||
return try transform(element)
|
||||
@@ -886,11 +994,9 @@ public final class MapCursor<Base: Cursor, Element>: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor that only consumes up to `n` elements from an underlying
|
||||
/// A `Cursor` that only consumes up to `n` elements from an underlying
|
||||
/// `Base` cursor.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class PrefixCursor<Base: Cursor>: Cursor {
|
||||
public final class PrefixCursor<Base: Cursor> {
|
||||
private let base: Base
|
||||
private let maxLength: Int
|
||||
private var taken = 0
|
||||
@@ -899,7 +1005,14 @@ public final class PrefixCursor<Base: Cursor>: Cursor {
|
||||
self.base = base
|
||||
self.maxLength = maxLength
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `PrefixCursor` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension PrefixCursor: Sendable { }
|
||||
|
||||
extension PrefixCursor: Cursor {
|
||||
public func next() throws -> Base.Element? {
|
||||
if taken >= maxLength { return nil }
|
||||
taken += 1
|
||||
@@ -913,11 +1026,9 @@ public final class PrefixCursor<Base: Cursor>: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
/// A `Cursor` whose elements consist of the initial consecutive elements of
|
||||
/// some `Base` cursor that satisfy a given predicate.
|
||||
public final class PrefixWhileCursor<Base: Cursor> {
|
||||
private let base: Base
|
||||
private let predicate: (Base.Element) throws -> Bool
|
||||
private var predicateHasFailed = false
|
||||
@@ -926,7 +1037,14 @@ public final class PrefixWhileCursor<Base: Cursor>: Cursor {
|
||||
self.base = base
|
||||
self.predicate = predicate
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `PrefixCursor` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension PrefixWhileCursor: Sendable { }
|
||||
|
||||
extension PrefixWhileCursor: Cursor {
|
||||
public func next() throws -> Base.Element? {
|
||||
if !predicateHasFailed, let nextElement = try base.next() {
|
||||
if try predicate(nextElement) {
|
||||
|
||||
+768
-294
File diff suppressed because it is too large.
Load diff
+266
-351
@@ -6,50 +6,61 @@ extension Database {
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
/// For example:
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```swift
|
||||
/// let statement = try db.makeStatement(sql: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// let statement = try db.makeStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```
|
||||
///
|
||||
/// - parameter sql: An SQL string.
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func makeStatement(sql: String) throws -> Statement {
|
||||
try makeStatement(sql: sql, prepFlags: 0)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeStatement(literal: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
/// For example:
|
||||
///
|
||||
/// let statement = try db.makeStatement(literal: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```swift
|
||||
/// let statement = try db.makeStatement(literal: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
/// let statement = try db.makeStatement(literal: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```
|
||||
///
|
||||
/// // OK
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
/// In the provided literal, no argument must be set, or all arguments must
|
||||
/// be set. An error is raised otherwise. For example:
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// // OK
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK (first argument is not set, but second is)
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter sqlLiteral: An ``SQL`` literal.
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func makeStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
let (sql, arguments) = try sqlLiteral.build(self)
|
||||
let statement = try makeStatement(sql: sql)
|
||||
@@ -62,56 +73,18 @@ extension Database {
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
@available(*, deprecated, renamed: "makeStatement(sql:)")
|
||||
public func makeSelectStatement(sql: String) throws -> Statement {
|
||||
try makeStatement(sql: sql)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try makeSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try makeSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try makeSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
@available(*, deprecated, renamed: "makeStatement(literal:)")
|
||||
public func makeSelectStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
try makeStatement(literal: sqlLiteral)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
/// For example:
|
||||
///
|
||||
/// let statement = try db.makeStatement(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 sql: An SQL string.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see <http://www.sqlite.org/c3ref/prepare.html>)
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
func makeStatement(sql: String, prepFlags: Int32) throws -> Statement {
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
func makeStatement(sql: String, prepFlags: CUnsignedInt) throws -> Statement {
|
||||
let statements = SQLStatementCursor(database: self, sql: sql, arguments: nil, prepFlags: prepFlags)
|
||||
guard let statement = try statements.next() else {
|
||||
throw DatabaseError(
|
||||
@@ -145,53 +118,64 @@ extension Database {
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedStatement(sql: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
/// For example:
|
||||
///
|
||||
/// let statement = try db.cachedStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```swift
|
||||
/// let statement = try db.cachedStatement(sql: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// let statement = try db.cachedStatement(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: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - parameter sql: An SQL string.
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func cachedStatement(sql: String) throws -> Statement {
|
||||
try publicStatementCache.statement(sql)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedStatement(literal: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
/// For example:
|
||||
///
|
||||
/// let statement = try db.cachedStatement(literal: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```swift
|
||||
/// let statement = try db.cachedStatement(literal: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
/// let statement = try db.cachedStatement(literal: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```
|
||||
///
|
||||
/// // OK
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
/// In the provided literal, no argument must be set, or all arguments must
|
||||
/// be set. An error is raised otherwise. For example:
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// // OK
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK (first argument is not set, but second is)
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter sqlLiteral: An ``SQL`` literal.
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func cachedStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
let (sql, arguments) = try sqlLiteral.build(self)
|
||||
let statement = try cachedStatement(sql: sql)
|
||||
@@ -202,213 +186,100 @@ extension Database {
|
||||
return statement
|
||||
}
|
||||
|
||||
/// 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: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
@available(*, deprecated, renamed: "cachedStatement(sql:)")
|
||||
public func cachedSelectStatement(sql: String) throws -> Statement {
|
||||
try cachedStatement(sql: sql)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedSelectStatement(literal: "SELECT COUNT(*) FROM player WHERE score > \(20)")
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement)!
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try cachedSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try cachedSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try cachedSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
@available(*, deprecated, renamed: "cachedStatement(literal:)")
|
||||
public func cachedSelectStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
try cachedStatement(literal: sqlLiteral)
|
||||
}
|
||||
|
||||
/// Returns a cached statement that does not conflict with user's cached statements.
|
||||
func internalCachedStatement(sql: String) throws -> Statement {
|
||||
try internalStatementCache.statement(sql)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
/// Returns a cursor of prepared statements.
|
||||
///
|
||||
/// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// For example:
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
@available(*, deprecated, renamed: "makeStatement(sql:)")
|
||||
public func makeUpdateStatement(sql: String) throws -> Statement {
|
||||
try makeStatement(sql: sql)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
/// ```swift
|
||||
/// let statements = try db.allStatements(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// """, arguments: ["Arthur", "Barbara", "O'Brien"])
|
||||
/// while let statement = try statements.next() {
|
||||
/// try statement.execute()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
/// The `arguments` parameter must be nil, or all arguments must be set. The
|
||||
/// returned cursor will throw an error otherwise. For example:
|
||||
///
|
||||
/// // OK
|
||||
/// try makeUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = ?
|
||||
/// """)
|
||||
/// try makeUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = \("O'Brien")
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// // OK
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try makeUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = ?, score = \(10)
|
||||
/// """)
|
||||
@available(*, deprecated, renamed: "makeStatement(literal:)")
|
||||
public func makeUpdateStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
try makeStatement(literal: sqlLiteral)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """, arguments: [1000, 1000])
|
||||
///
|
||||
/// 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: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
@available(*, deprecated, renamed: "cachedStatement(sql:)")
|
||||
public func cachedUpdateStatement(sql: String) throws -> Statement {
|
||||
try cachedStatement(sql: sql)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try cachedUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = ?
|
||||
/// """)
|
||||
/// try cachedUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = \("O'Brien")
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try cachedUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = ?, score = \(10)
|
||||
/// """)
|
||||
@available(*, deprecated, renamed: "cachedStatement(sql:)")
|
||||
public func cachedUpdateStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
try cachedStatement(literal: sqlLiteral)
|
||||
}
|
||||
|
||||
/// Returns a cursor of all SQL statements separated by semi-colons.
|
||||
///
|
||||
/// let statements = try db.allStatements(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// """, arguments: ["Arthur", "Barbara", "O'Brien"])
|
||||
/// while let statement = try statements.next() {
|
||||
/// try statement.execute()
|
||||
/// }
|
||||
/// // NOT OK (first argument is set, but second is not)
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """, arguments: [1000])
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - sql: An SQL string.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - returns: A cursor of `Statement`
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
/// - precondition: Arguments must be nil, or all arguments must be set.
|
||||
/// The returned cursor will throw an error otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """, arguments: [1000, 1000])
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """, arguments: [1000])
|
||||
/// - returns: A cursor of prepared ``Statement``.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func allStatements(sql: String, arguments: StatementArguments? = nil)
|
||||
throws -> SQLStatementCursor
|
||||
{
|
||||
SQLStatementCursor(database: self, sql: sql, arguments: arguments)
|
||||
}
|
||||
|
||||
/// Returns a cursor of all SQL statements separated by semi-colons.
|
||||
/// Returns a cursor of prepared statements.
|
||||
///
|
||||
/// Literals allow you to safely embed raw values in your SQL, without any
|
||||
/// risk of syntax errors or SQL injection:
|
||||
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// let statements = try db.allStatements(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"));
|
||||
/// INSERT INTO player (name) VALUES (\("Barbara"));
|
||||
/// INSERT INTO player (name) VALUES (\("O'Brien"));
|
||||
/// """)
|
||||
/// while let statement = try statements.next() {
|
||||
/// try statement.execute()
|
||||
/// }
|
||||
/// ```swift
|
||||
/// let statements = try db.allStatements(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"));
|
||||
/// INSERT INTO player (name) VALUES (\("Barbara"));
|
||||
/// INSERT INTO player (name) VALUES (\("O'Brien"));
|
||||
/// """)
|
||||
/// while let statement = try statements.next() {
|
||||
/// try statement.execute()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A cursor of `Statement`
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// The returned cursor will throw an error otherwise.
|
||||
/// In the provided literal, no argument must be set, or all arguments must
|
||||
/// be set. The returned cursor will throw an error otherwise. For example:
|
||||
///
|
||||
/// // OK
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < \(1000);
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000);
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// // OK
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < \(1000);
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < \(1000);
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000);
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK (first argument is set, but second is not)
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < \(1000);
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter sqlLiteral: An ``SQL`` literal.
|
||||
/// - returns: A cursor of prepared ``Statement``.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func allStatements(literal sqlLiteral: SQL) throws -> SQLStatementCursor {
|
||||
let context = SQLGenerationContext(self)
|
||||
let sql = try sqlLiteral.sql(context)
|
||||
@@ -418,47 +289,49 @@ extension Database {
|
||||
return SQLStatementCursor(database: self, sql: sql, arguments: arguments)
|
||||
}
|
||||
|
||||
/// Executes one or several SQL statements, separated by semi-colons.
|
||||
/// Executes one or several SQL statements.
|
||||
///
|
||||
/// try db.execute(
|
||||
/// sql: "INSERT INTO player (name) VALUES (:name)",
|
||||
/// arguments: ["name": "Arthur"])
|
||||
/// For example:
|
||||
///
|
||||
/// try db.execute(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// """, arguments: ["Arthur", "Barbara", "O'Brien"])
|
||||
/// ```swift
|
||||
/// try db.execute(
|
||||
/// sql: "INSERT INTO player (name) VALUES (:name)",
|
||||
/// arguments: ["name": "Arthur"])
|
||||
///
|
||||
/// This method may throw a DatabaseError.
|
||||
/// try db.execute(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// """, arguments: ["Arthur", "Barbara", "O'Brien"])
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - sql: An SQL string.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func execute(sql: String, arguments: StatementArguments = StatementArguments()) throws {
|
||||
try execute(literal: SQL(sql: sql, arguments: arguments))
|
||||
}
|
||||
|
||||
/// Executes one or several SQL statements, separated by semi-colons.
|
||||
/// Executes one or several SQL statements.
|
||||
///
|
||||
/// Literals allow you to safely embed raw values in your SQL, without any
|
||||
/// risk of syntax errors or SQL injection:
|
||||
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// try db.execute(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"))
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// try db.execute(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"))
|
||||
/// """)
|
||||
///
|
||||
/// try db.execute(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"));
|
||||
/// INSERT INTO player (name) VALUES (\("Barbara"));
|
||||
/// INSERT INTO player (name) VALUES (\("O'Brien"));
|
||||
/// """)
|
||||
/// 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 `SQL` literal.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
/// - parameter sqlLiteral: An ``SQL`` literal.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func execute(literal sqlLiteral: SQL) throws {
|
||||
let statements = try allStatements(literal: sqlLiteral)
|
||||
while let statement = try statements.next() {
|
||||
@@ -467,17 +340,18 @@ extension Database {
|
||||
}
|
||||
}
|
||||
|
||||
public class SQLStatementCursor: Cursor {
|
||||
/// A cursor over all statements in an SQL string.
|
||||
public class SQLStatementCursor {
|
||||
private let database: Database
|
||||
private let cString: ContiguousArray<CChar>
|
||||
private let prepFlags: CInt
|
||||
private let prepFlags: CUnsignedInt
|
||||
private let initialArgumentCount: Int?
|
||||
|
||||
// Mutated by iteration
|
||||
private var offset: Int // offset in the C string
|
||||
private var arguments: StatementArguments? // Nil when arguments are set later
|
||||
|
||||
init(database: Database, sql: String, arguments: StatementArguments?, prepFlags: CInt = 0) {
|
||||
init(database: Database, sql: String, arguments: StatementArguments?, prepFlags: CUnsignedInt = 0) {
|
||||
self.database = database
|
||||
self.cString = sql.utf8CString
|
||||
self.prepFlags = prepFlags
|
||||
@@ -485,30 +359,37 @@ public class SQLStatementCursor: Cursor {
|
||||
self.offset = 0
|
||||
self.arguments = arguments
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: database cursors must be used from
|
||||
// a serialized database access dispatch queue.
|
||||
@available(*, unavailable)
|
||||
extension SQLStatementCursor: Sendable { }
|
||||
|
||||
extension SQLStatementCursor: Cursor {
|
||||
public func next() throws -> Statement? {
|
||||
guard offset < cString.count - 1 /* trailing \0 */ else {
|
||||
// End of C string -> end of cursor.
|
||||
try checkArgumentsAreEmpty()
|
||||
return nil
|
||||
}
|
||||
|
||||
return try cString.withUnsafeBufferPointer { buffer in
|
||||
guard let baseAddress = buffer.baseAddress else {
|
||||
// Should never happen since buffer contains at least
|
||||
// the trailing \0
|
||||
return nil
|
||||
}
|
||||
let baseAddress = buffer.baseAddress! // never nil because the buffer contains the trailing \0.
|
||||
|
||||
var statementEnd: UnsafePointer<Int8>? = nil
|
||||
let compiledStatement = try Statement(
|
||||
// Compile next statement
|
||||
var statementEnd: UnsafePointer<CChar>? = nil
|
||||
let statement = try Statement(
|
||||
database: database,
|
||||
statementStart: baseAddress + offset,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: prepFlags)
|
||||
|
||||
offset = statementEnd! - baseAddress
|
||||
// Advance to next statement
|
||||
offset = statementEnd! - baseAddress // never nil because statement compilation did not fail.
|
||||
|
||||
guard let statement = compiledStatement else {
|
||||
guard let statement else {
|
||||
// No statement found -> end of cursor.
|
||||
try checkArgumentsAreEmpty()
|
||||
return nil
|
||||
}
|
||||
@@ -530,8 +411,8 @@ public class SQLStatementCursor: Cursor {
|
||||
/// Check that all arguments were consumed: it is a programmer error to
|
||||
/// provide arguments that do not match the statements.
|
||||
private func checkArgumentsAreEmpty() throws {
|
||||
if let arguments = arguments,
|
||||
let initialArgumentCount = initialArgumentCount,
|
||||
if let arguments,
|
||||
let initialArgumentCount,
|
||||
arguments.values.isEmpty == false
|
||||
{
|
||||
throw DatabaseError(
|
||||
@@ -545,18 +426,20 @@ extension Database {
|
||||
/// Makes sure statement can be executed, and prepares database observation.
|
||||
@usableFromInline
|
||||
func statementWillExecute(_ statement: Statement) throws {
|
||||
// Two things must prevent the statement from executing: aborted
|
||||
// transactions, and database suspension.
|
||||
// Aborted transactions prevent statement execution (see the
|
||||
// documentation of this method for more information).
|
||||
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
|
||||
|
||||
// Suspended databases must not execute statements that create the risk
|
||||
// of `0xdead10cc` exception (see the documentation of this method for
|
||||
// more information).
|
||||
try checkForSuspensionViolation(from: statement)
|
||||
|
||||
// Database observation: record what the statement is looking at.
|
||||
if isRecordingSelectedRegion {
|
||||
selectedRegion.formUnion(statement.databaseRegion)
|
||||
}
|
||||
// Record the database region selected by the statement execution.
|
||||
try registerAccess(to: statement.databaseRegion)
|
||||
|
||||
// Database observation: prepare transaction observers.
|
||||
observationBroker.statementWillExecute(statement)
|
||||
observationBroker?.statementWillExecute(statement)
|
||||
}
|
||||
|
||||
/// May throw a cancelled commit error, if a transaction observer cancels
|
||||
@@ -567,13 +450,16 @@ extension Database {
|
||||
clearSchemaCache()
|
||||
}
|
||||
|
||||
try observationBroker.statementDidExecute(statement)
|
||||
checkForAutocommitTransition()
|
||||
|
||||
// Database observation: cleanup
|
||||
try observationBroker?.statementDidExecute(statement)
|
||||
}
|
||||
|
||||
/// Always throws an error
|
||||
@usableFromInline
|
||||
func statementDidFail(_ statement: Statement, withResultCode resultCode: Int32) throws -> Never {
|
||||
// Failed statements can not be reused, because sqlite3_reset won't
|
||||
func statementDidFail(_ statement: Statement, withResultCode resultCode: CInt) throws -> Never {
|
||||
// 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
|
||||
//
|
||||
@@ -581,17 +467,48 @@ extension Database {
|
||||
internalStatementCache.remove(statement)
|
||||
publicStatementCache.remove(statement)
|
||||
|
||||
/// Exposes the user-provided cancelled commit error, if a transaction
|
||||
/// observer has cancelled a transaction.
|
||||
try observationBroker.statementDidFail(statement)
|
||||
checkForAutocommitTransition()
|
||||
|
||||
// Extract values that may be modified by the user in their
|
||||
// `TransactionObserver.databaseDidRollback(_:)` implementation
|
||||
// (see below).
|
||||
let message = lastErrorMessage
|
||||
let arguments = statement.arguments
|
||||
|
||||
// Database observation: cleanup.
|
||||
//
|
||||
// If the statement failure is due to a transaction observer that has
|
||||
// cancelled a transaction, this calls `TransactionObserver.databaseDidRollback(_:)`,
|
||||
// and throws the user-provided cancelled commit error.
|
||||
try observationBroker?.statementDidFail(statement)
|
||||
|
||||
// Throw statement failure
|
||||
throw DatabaseError(
|
||||
resultCode: resultCode,
|
||||
message: lastErrorMessage,
|
||||
message: message,
|
||||
sql: statement.sql,
|
||||
arguments: statement.arguments,
|
||||
arguments: arguments,
|
||||
publicStatementArguments: configuration.publicStatementArguments)
|
||||
}
|
||||
|
||||
private func checkForAutocommitTransition() {
|
||||
if sqlite3_get_autocommit(sqliteConnection) == 0 {
|
||||
if autocommitState == .on {
|
||||
// Record transaction date as soon as the connection leaves
|
||||
// auto-commit mode.
|
||||
// We grab a result, so that this failure is later reported
|
||||
// whenever the user calls `Database.transactionDate`.
|
||||
transactionDateResult = Result { try configuration.transactionClock.now(self) }
|
||||
}
|
||||
autocommitState = .off
|
||||
} else {
|
||||
if autocommitState == .off {
|
||||
// Reset transaction date
|
||||
transactionDateResult = nil
|
||||
}
|
||||
autocommitState = .on
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A thread-unsafe statement cache
|
||||
@@ -618,14 +535,12 @@ struct StatementCache {
|
||||
// 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.makeStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
|
||||
let statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT))
|
||||
#else
|
||||
let statement: Statement
|
||||
if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) {
|
||||
// SQLite 3.24.0 or more
|
||||
statement = try db.makeStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
|
||||
if #available(iOS 12, macOS 10.14, watchOS 5, *) { // SQLite 3.20+
|
||||
statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT))
|
||||
} else {
|
||||
// SQLite 3.19.3 or less
|
||||
statement = try db.makeStatement(sql: sql)
|
||||
}
|
||||
#endif
|
||||
|
||||
+869
-445
File diff suppressed because it is too large.
Load diff
@@ -1,22 +1,27 @@
|
||||
/// An instance of `DatabaseBackupProgress` is passed to a callback of the
|
||||
/// `DatabaseReader.backup` or `Database.backup` methods to report
|
||||
/// database backup progress to the caller.
|
||||
/// Describe the progress of a database backup.
|
||||
///
|
||||
/// This is an advanced API for expert users. It is based directly on the SQLite
|
||||
/// [online backup API](https://www.sqlite.org/c3ref/backup_finish.html).
|
||||
public struct DatabaseBackupProgress {
|
||||
/// Total page count is defined by the `sqlite3_backup_remaining` function
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/backup_finish.html>
|
||||
public struct DatabaseBackupProgress: Sendable {
|
||||
/// The number of pages still to be backed up.
|
||||
///
|
||||
/// It is the result of the `sqlite3_backup_remaining` function.
|
||||
public let remainingPageCount: Int
|
||||
|
||||
/// Total page count is defined by the `sqlite3_backup_pagecount` function
|
||||
|
||||
/// The number of pages in the source database.
|
||||
///
|
||||
/// It is the result of the `sqlite3_backup_pagecount` function.
|
||||
public let totalPageCount: Int
|
||||
|
||||
/// Completed page count is defined as `sqlite3_backup_pagecount() - sqlite3_backup_remaining()`
|
||||
|
||||
/// The number of of backed up pages.
|
||||
///
|
||||
/// It is equal to `totalPageCount - remainingPageCount`.
|
||||
public var completedPageCount: Int {
|
||||
totalPageCount - remainingPageCount
|
||||
}
|
||||
|
||||
/// This property is true if and only if `sqlite3_backup_step()` returns
|
||||
/// `SQLITE_DONE`
|
||||
|
||||
/// A boolean value indicating whether the backup is complete.
|
||||
///
|
||||
/// It is true if and only if the last call the `sqlite3_backup_step` has
|
||||
/// returned `SQLITE_DONE`.
|
||||
public let isCompleted: Bool
|
||||
}
|
||||
@@ -1,21 +1,44 @@
|
||||
import Foundation
|
||||
|
||||
/// A Collation is a string comparison function used by SQLite.
|
||||
/// `DatabaseCollation` is a custom string comparison function used by SQLite.
|
||||
///
|
||||
/// See also ``Database/CollationName``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/datatype3.html#collating_sequences>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a Custom Collation
|
||||
///
|
||||
/// - ``init(_:function:)``
|
||||
/// - ``name``
|
||||
///
|
||||
/// ### Built-in Collations
|
||||
///
|
||||
/// - ``caseInsensitiveCompare``
|
||||
/// - ``localizedCaseInsensitiveCompare``
|
||||
/// - ``localizedCompare``
|
||||
/// - ``localizedStandardCompare``
|
||||
/// - ``unicodeCompare``
|
||||
public final class DatabaseCollation {
|
||||
/// The name of the collation
|
||||
/// The name of the collation.
|
||||
public let name: String
|
||||
let function: (Int32, UnsafeRawPointer?, Int32, UnsafeRawPointer?) -> ComparisonResult
|
||||
let function: (CInt, UnsafeRawPointer?, CInt, 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")
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// 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.
|
||||
/// - name: The collation name.
|
||||
/// - function: A function that compares two strings.
|
||||
public init(_ name: String, function: @escaping (String, String) -> ComparisonResult) {
|
||||
self.name = name
|
||||
@@ -43,13 +66,11 @@ extension DatabaseCollation: Hashable {
|
||||
// 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
|
||||
|
||||
+172
-76
@@ -2,9 +2,9 @@ import Foundation
|
||||
|
||||
/// An SQLite result code.
|
||||
///
|
||||
/// See <https://www.sqlite.org/rescode.html>
|
||||
public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
|
||||
/// The raw SQLite result code
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/rescode.html>
|
||||
public struct ResultCode: RawRepresentable, Equatable {
|
||||
/// The raw SQLite result code.
|
||||
public let rawValue: CInt
|
||||
|
||||
/// Creates a `ResultCode` from a raw SQLite result code.
|
||||
@@ -12,11 +12,14 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
/// A result code limited to the least significant 8 bits of the receiver.
|
||||
/// See <https://www.sqlite.org/rescode.html> for more information.
|
||||
/// A primary result code limited to the least significant 8 bits.
|
||||
///
|
||||
/// let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY
|
||||
/// resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY
|
||||
/// resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true
|
||||
/// ```
|
||||
public var primaryResultCode: ResultCode {
|
||||
ResultCode(rawValue: rawValue & 0xFF)
|
||||
}
|
||||
@@ -28,11 +31,15 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
|
||||
/// Primary result codes match themselves and their extended result codes,
|
||||
/// while extended result codes match only themselves:
|
||||
///
|
||||
/// switch error.extendedResultCode {
|
||||
/// case .SQLITE_CONSTRAINT_FOREIGNKEY: // foreign key constraint error
|
||||
/// case .SQLITE_CONSTRAINT: // any other constraint error
|
||||
/// default: // any other database error
|
||||
/// }
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// switch error.extendedResultCode {
|
||||
/// case .SQLITE_CONSTRAINT_FOREIGNKEY: // foreign key constraint error
|
||||
/// case .SQLITE_CONSTRAINT: // any other constraint error
|
||||
/// default: // any other database error
|
||||
/// }
|
||||
/// ```
|
||||
public static func ~= (pattern: ResultCode, code: ResultCode) -> Bool {
|
||||
if pattern.isPrimary {
|
||||
return pattern == code.primaryResultCode
|
||||
@@ -166,30 +173,32 @@ extension ResultCode {
|
||||
/// Primary result codes match themselves and their extended result codes,
|
||||
/// while extended result codes match only themselves.
|
||||
///
|
||||
/// do {
|
||||
/// try ...
|
||||
/// } catch ResultCode.SQLITE_CONSTRAINT_FOREIGNKEY {
|
||||
/// // foreign key constraint error
|
||||
/// } catch ResultCode.SQLITE_CONSTRAINT {
|
||||
/// // any other constraint error
|
||||
/// } catch {
|
||||
/// // any other database error
|
||||
/// }
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// try ...
|
||||
/// } catch ResultCode.SQLITE_CONSTRAINT_FOREIGNKEY {
|
||||
/// // foreign key constraint error
|
||||
/// } catch ResultCode.SQLITE_CONSTRAINT {
|
||||
/// // any other constraint error
|
||||
/// } catch {
|
||||
/// // any other database error
|
||||
/// }
|
||||
/// ```
|
||||
public static func ~= (lhs: Self, rhs: Error) -> Bool {
|
||||
guard let error = rhs as? DatabaseError else { return false }
|
||||
return lhs ~= error.extendedResultCode
|
||||
}
|
||||
}
|
||||
|
||||
// CustomStringConvertible
|
||||
extension ResultCode {
|
||||
extension ResultCode: CustomStringConvertible {
|
||||
var errorString: String? {
|
||||
String(cString: sqlite3_errstr(rawValue))
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
if let errorString = errorString {
|
||||
if let errorString {
|
||||
return "\(rawValue) (\(errorString))"
|
||||
} else {
|
||||
return "\(rawValue)"
|
||||
@@ -197,63 +206,147 @@ extension ResultCode {
|
||||
}
|
||||
}
|
||||
|
||||
extension ResultCode: GRDBSendable { }
|
||||
extension ResultCode: Sendable { }
|
||||
|
||||
/// DatabaseError wraps an SQLite error.
|
||||
public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
|
||||
/// The SQLite error code (see
|
||||
/// <https://www.sqlite.org/rescode.html#primary_result_code_list>).
|
||||
///
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch let error as DatabaseError where error.resultCode == .SQL_CONSTRAINT {
|
||||
/// // A constraint error
|
||||
/// }
|
||||
/// A `DatabaseError` describes an SQLite error.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// try player.insert(db)
|
||||
/// } catch let error as DatabaseError {
|
||||
/// print(error) // prints debugging information
|
||||
///
|
||||
/// switch error {
|
||||
/// case DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY:
|
||||
/// // foreign key constraint error
|
||||
/// case DatabaseError.SQLITE_CONSTRAINT:
|
||||
/// // any other constraint error
|
||||
/// default:
|
||||
/// // any other database error
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The above example can also be written in a shorter way:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// try player.insert(db)
|
||||
/// } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY {
|
||||
/// // foreign key constraint error
|
||||
/// } catch DatabaseError.SQLITE_CONSTRAINT {
|
||||
/// // any other constraint error
|
||||
/// } catch {
|
||||
/// // any other database error
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/rescode.html>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating DatabaseError
|
||||
///
|
||||
/// - ``init(resultCode:message:sql:arguments:publicStatementArguments:)``
|
||||
/// - ``ResultCode``
|
||||
///
|
||||
/// ### Error Information
|
||||
///
|
||||
/// - ``arguments``
|
||||
/// - ``extendedResultCode``
|
||||
/// - ``isInterruptionError``
|
||||
/// - ``message``
|
||||
/// - ``resultCode``
|
||||
/// - ``sql``
|
||||
///
|
||||
/// ### Converting DatabaseError to String
|
||||
///
|
||||
/// - ``description``
|
||||
/// - ``expandedDescription``
|
||||
public struct DatabaseError: Error {
|
||||
/// The SQLite primary result code.
|
||||
///
|
||||
/// This property returns a "primary result code", that is to say the least
|
||||
/// significant 8 bits of any SQLite result code. See
|
||||
/// <https://www.sqlite.org/rescode.html> for more information.
|
||||
/// significant 8 bits of any SQLite result code.
|
||||
///
|
||||
/// See also `extendedResultCode`.
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch let error as DatabaseError where error.resultCode == .SQL_CONSTRAINT {
|
||||
/// // A constraint error
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The above example can also be written in a shorter way:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch DatabaseError.SQL_CONSTRAINT {
|
||||
/// // A constraint error
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See also ``extendedResultCode``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/rescode.html>
|
||||
public var resultCode: ResultCode {
|
||||
extendedResultCode.primaryResultCode
|
||||
}
|
||||
|
||||
/// The SQLite extended error code (see
|
||||
/// <https://www.sqlite.org/rescode.html#extended_result_code_list>).
|
||||
/// The SQLite extended error code.
|
||||
///
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch let error as DatabaseError where error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY {
|
||||
/// // A foreign key constraint error
|
||||
/// }
|
||||
/// For example:
|
||||
///
|
||||
/// See also `resultCode`.
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch let error as DatabaseError where error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY {
|
||||
/// // A foreign key constraint error
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The above example can also be written in a shorter way:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY {
|
||||
/// // A foreign key constraint error
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See also ``resultCode``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/rescode.html>
|
||||
public let extendedResultCode: ResultCode
|
||||
|
||||
/// The SQLite error message.
|
||||
public let message: String?
|
||||
|
||||
/// The SQL query that yielded the error (if relevant).
|
||||
/// The SQL query that yielded the error.
|
||||
public let sql: String?
|
||||
|
||||
/// The query arguments that yielded the error (if relevant).
|
||||
/// The query arguments that yielded the error.
|
||||
public let arguments: StatementArguments?
|
||||
|
||||
/// See Configuration.publicStatementArguments
|
||||
var publicStatementArguments: Bool
|
||||
|
||||
/// Creates a DatabaseError.
|
||||
/// Creates a `DatabaseError`.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - resultCode: A ResultCode (defaults to .SQLITE_ERROR).
|
||||
/// - message: An eventual error message. If nil, the error message is
|
||||
/// derived from the result code.
|
||||
/// - sql: An eventual SQL string.
|
||||
/// - arguments: Eventual Statement arguments.
|
||||
/// - arguments: Eventual statement arguments.
|
||||
/// - publicStatementArguments: If false (the default), statement
|
||||
/// arguments are not visible in the error's `description` property.
|
||||
/// arguments are not visible in the error's ``description`` property.
|
||||
public init(
|
||||
resultCode: ResultCode = .SQLITE_ERROR,
|
||||
message: String? = nil,
|
||||
@@ -303,6 +396,10 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
static func noSuchTable(_ tableName: String) -> Self {
|
||||
DatabaseError(message: "no such table: \(tableName)")
|
||||
}
|
||||
|
||||
static func noSuchSchema(_ schemaName: String) -> Self {
|
||||
DatabaseError(message: "no such schema: \(schemaName)")
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseError {
|
||||
@@ -422,13 +519,14 @@ extension DatabaseError {
|
||||
}
|
||||
|
||||
extension DatabaseError {
|
||||
/// Returns true if the error has code `SQLITE_ABORT` or `SQLITE_INTERRUPT`.
|
||||
/// A boolean value indicating if the error has code
|
||||
/// `SQLITE_ABORT` or `SQLITE_INTERRUPT`.
|
||||
///
|
||||
/// Such an error can be thrown when a database has been interrupted, or
|
||||
/// when the database is suspended.
|
||||
///
|
||||
/// See `DatabaseReader.interrupt()` and `DatabaseReader.suspend()` for
|
||||
/// more information.
|
||||
/// See ``DatabaseReader/interrupt()`` and ``Database/suspendNotification``
|
||||
/// for more information.
|
||||
public var isInterruptionError: Bool {
|
||||
switch resultCode {
|
||||
case .SQLITE_ABORT, .SQLITE_INTERRUPT:
|
||||
@@ -439,8 +537,7 @@ extension DatabaseError {
|
||||
}
|
||||
}
|
||||
|
||||
// CustomStringConvertible
|
||||
extension DatabaseError {
|
||||
extension DatabaseError: CustomStringConvertible {
|
||||
/// The error description.
|
||||
///
|
||||
/// For example:
|
||||
@@ -452,13 +549,13 @@ extension DatabaseError {
|
||||
/// without notice: don't have your application rely on any specific format.
|
||||
public var description: String {
|
||||
var description = "SQLite error \(resultCode.rawValue)"
|
||||
if let message = message {
|
||||
if let message {
|
||||
description += ": \(message)"
|
||||
}
|
||||
if let sql = sql {
|
||||
description += " - while executing `\(sql)`"
|
||||
if let sql {
|
||||
description += " - while executing `\(sql.trimmedSQLStatement)`"
|
||||
}
|
||||
if publicStatementArguments, let arguments = arguments, !arguments.isEmpty {
|
||||
if publicStatementArguments, let arguments, !arguments.isEmpty {
|
||||
description += " with arguments \(arguments)"
|
||||
}
|
||||
return description
|
||||
@@ -480,35 +577,34 @@ extension DatabaseError {
|
||||
/// property with care.
|
||||
public var expandedDescription: String {
|
||||
var description = "SQLite error \(resultCode.rawValue)"
|
||||
if let message = message {
|
||||
if let message {
|
||||
description += ": \(message)"
|
||||
}
|
||||
if let sql = sql {
|
||||
description += " - while executing `\(sql)`"
|
||||
if let sql {
|
||||
description += " - while executing `\(sql.trimmedSQLStatement)`"
|
||||
}
|
||||
if let arguments = arguments, !arguments.isEmpty {
|
||||
if let arguments, !arguments.isEmpty {
|
||||
description += " with arguments \(arguments)"
|
||||
}
|
||||
return description
|
||||
}
|
||||
}
|
||||
|
||||
// CustomNSError
|
||||
extension DatabaseError {
|
||||
|
||||
/// NSError bridging: the domain of the error.
|
||||
/// :nodoc:
|
||||
extension DatabaseError: CustomNSError {
|
||||
/// Part of the `CustomNSError` conformance.
|
||||
///
|
||||
/// Returns `GRDB.DatabaseError`.
|
||||
public static var errorDomain: String { "GRDB.DatabaseError" }
|
||||
|
||||
/// NSError bridging: the error code within the given domain.
|
||||
/// :nodoc:
|
||||
/// Part of the `CustomNSError` conformance.
|
||||
///
|
||||
/// Returns the ``extendedResultCode``.
|
||||
public var errorCode: Int { Int(extendedResultCode.rawValue) }
|
||||
|
||||
/// NSError bridging: the user-info dictionary.
|
||||
/// :nodoc:
|
||||
/// Part of the `CustomNSError` conformance.
|
||||
public var errorUserInfo: [String: Any] {
|
||||
var userInfo = [NSLocalizedDescriptionKey: description]
|
||||
if let message = message {
|
||||
if let message {
|
||||
userInfo[NSLocalizedFailureReasonErrorKey] = message
|
||||
}
|
||||
return userInfo
|
||||
|
||||
@@ -1,30 +1,60 @@
|
||||
/// An SQL function or aggregate.
|
||||
/// A custom SQL function or aggregate.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a Custom SQL Function or Aggregate
|
||||
///
|
||||
/// - ``init(_:argumentCount:pure:function:)``
|
||||
/// - ``init(_:argumentCount:pure:aggregate:)``
|
||||
/// - ``DatabaseAggregate``
|
||||
///
|
||||
/// ### Calling an SQL Function or Aggregate
|
||||
///
|
||||
/// - ``callAsFunction(_:)``
|
||||
///
|
||||
/// ### Built-in Functions
|
||||
///
|
||||
/// - ``capitalize``
|
||||
/// - ``localizedCapitalize``
|
||||
/// - ``localizedLowercase``
|
||||
/// - ``localizedUppercase``
|
||||
/// - ``lowercase``
|
||||
/// - ``uppercase``
|
||||
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
|
||||
let nArg: CInt // -1 for variadic functions
|
||||
}
|
||||
|
||||
/// The name of the SQL function
|
||||
public var name: String { identity.name }
|
||||
private let identity: Identity
|
||||
let pure: Bool
|
||||
let isPure: Bool
|
||||
private let kind: Kind
|
||||
private var eTextRep: Int32 { (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
|
||||
private var eTextRep: CInt { (SQLITE_UTF8 | (isPure ? SQLITE_DETERMINISTIC : 0)) }
|
||||
|
||||
/// Creates an SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int + 1
|
||||
/// ```swift
|
||||
/// let succ = DatabaseFunction("succ", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// db.add(function: fn)
|
||||
/// return int + 1
|
||||
/// }
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// try dbQueue.read { db in
|
||||
/// db.add(function: succ)
|
||||
/// try Int.fetchOne(db, sql: "SELECT succ(1)")! // 2
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ### Related APIs
|
||||
///
|
||||
/// - ``Database/add(function:)``
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The function name.
|
||||
@@ -34,19 +64,19 @@ public final class DatabaseFunction: Hashable {
|
||||
/// only depends on its inputs. When a function is pure, SQLite has
|
||||
/// the opportunity to perform additional optimizations. Default value
|
||||
/// is false.
|
||||
/// - function: A function that takes an array of DatabaseValue
|
||||
/// arguments, and returns an optional DatabaseValueConvertible such
|
||||
/// as Int, String, NSDate, etc. The array is guaranteed to have
|
||||
/// exactly *argumentCount* elements, provided *argumentCount* is
|
||||
/// - function: A function that takes an array of ``DatabaseValue``
|
||||
/// arguments, and returns an optional ``DatabaseValueConvertible``
|
||||
/// such as `Int`, `String`, `Date`, etc. The array is guaranteed to
|
||||
/// have exactly `argumentCount` elements, provided `argumentCount` is
|
||||
/// not nil.
|
||||
public init(
|
||||
_ name: String,
|
||||
argumentCount: Int32? = nil,
|
||||
argumentCount: Int? = nil,
|
||||
pure: Bool = false,
|
||||
function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?)
|
||||
function: @escaping ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
|
||||
{
|
||||
self.identity = Identity(name: name, nArg: argumentCount ?? -1)
|
||||
self.pure = pure
|
||||
self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
|
||||
self.isPure = pure
|
||||
self.kind = .function{ (argc, argv) in
|
||||
let arguments = (0..<Int(argc)).map { index in
|
||||
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
|
||||
@@ -59,29 +89,35 @@ public final class DatabaseFunction: Hashable {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct MySum: DatabaseAggregate {
|
||||
/// var sum: Int = 0
|
||||
/// ```swift
|
||||
/// struct MySum: DatabaseAggregate {
|
||||
/// var sum: Int = 0
|
||||
///
|
||||
/// mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
/// if let int = Int.fromDatabaseValue(dbValues[0]) {
|
||||
/// sum += int
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// func finalize() -> DatabaseValueConvertible? {
|
||||
/// return sum
|
||||
/// mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
/// if let int = Int.fromDatabaseValue(dbValues[0]) {
|
||||
/// sum += int
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// try dbQueue.write { db in
|
||||
/// db.add(function: fn)
|
||||
/// 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
|
||||
/// func finalize() -> (any DatabaseValueConvertible)? {
|
||||
/// return sum
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// let mySum = DatabaseFunction("mySum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// try dbQueue.write { db in
|
||||
/// db.add(function: mySum)
|
||||
/// 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
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ### Related APIs
|
||||
///
|
||||
/// - ``Database/add(function:)``
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The function name.
|
||||
@@ -91,34 +127,68 @@ public final class DatabaseFunction: Hashable {
|
||||
/// results only depends on its inputs. When an aggregate is pure,
|
||||
/// SQLite has the opportunity to perform additional optimizations.
|
||||
/// Default value is false.
|
||||
/// - aggregate: A type that implements the DatabaseAggregate protocol.
|
||||
/// For each step of the aggregation, its `step` method is called with
|
||||
/// an array of DatabaseValue arguments. The array is guaranteed to
|
||||
/// have exactly *argumentCount* elements, provided *argumentCount* is
|
||||
/// - aggregate: A type that implements the ``DatabaseAggregate``
|
||||
/// protocol. For each step of the aggregation, its
|
||||
/// ``DatabaseAggregate/step(_:)`` method is called with 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,
|
||||
argumentCount: Int? = nil,
|
||||
pure: Bool = false,
|
||||
aggregate: Aggregate.Type)
|
||||
{
|
||||
self.identity = Identity(name: name, nArg: argumentCount ?? -1)
|
||||
self.pure = pure
|
||||
self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
|
||||
self.isPure = pure
|
||||
self.kind = .aggregate { Aggregate() }
|
||||
}
|
||||
|
||||
// TODO: GRDB7 -> expose ORDER BY and FILTER when we have distinct types for simple functions and aggregates.
|
||||
/// Returns an SQL expression that applies the function.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/#sql-functions>
|
||||
public func callAsFunction(_ arguments: SQLExpressible...) -> SQLExpression {
|
||||
/// You can use a `DatabaseFunction` as a regular Swift function. It returns
|
||||
/// an SQL expression that you can use in the query interface.
|
||||
///
|
||||
/// In the example below, `square(Column("score"))` generates the
|
||||
/// `square(score)` SQL expression:
|
||||
///
|
||||
/// ```swift
|
||||
/// let square = DatabaseFunction("square", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int * int
|
||||
/// }
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// try dbQueue.read { db in
|
||||
/// db.add(function: square)
|
||||
///
|
||||
/// // SELECT square(score) FROM player
|
||||
/// let squaredScores = let Player
|
||||
/// .select(square(Column("score")), as: Int.self)
|
||||
/// .fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
public func callAsFunction(_ arguments: any SQLExpressible...) -> SQLExpression {
|
||||
switch kind {
|
||||
case .aggregate:
|
||||
return .function(name, arguments.map(\.sqlExpression))
|
||||
case .function:
|
||||
return .aggregate(name, arguments.map(\.sqlExpression))
|
||||
return .simpleFunction(
|
||||
name,
|
||||
arguments.map(\.sqlExpression),
|
||||
isPure: isPure,
|
||||
isJSONValue: false)
|
||||
case .aggregate:
|
||||
return .aggregateFunction(
|
||||
name,
|
||||
arguments.map(\.sqlExpression),
|
||||
isDistinct: false,
|
||||
ordering: nil,
|
||||
filter: nil,
|
||||
isJSONValue: false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Calls sqlite3_create_function_v2
|
||||
/// See <https://sqlite.org/c3ref/create_function.html>
|
||||
func install(in db: Database) {
|
||||
@@ -166,8 +236,10 @@ public final class DatabaseFunction: Hashable {
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
private class FunctionDefinition {
|
||||
let compute: (Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?
|
||||
init(compute: @escaping (Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?) {
|
||||
let compute: (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?
|
||||
init(compute: @escaping (CInt, UnsafeMutablePointer<OpaquePointer?>?)
|
||||
throws -> (any DatabaseValueConvertible)?)
|
||||
{
|
||||
self.compute = compute
|
||||
}
|
||||
}
|
||||
@@ -176,17 +248,17 @@ public final class DatabaseFunction: Hashable {
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
private class AggregateDefinition {
|
||||
let makeAggregate: () -> DatabaseAggregate
|
||||
init(makeAggregate: @escaping () -> DatabaseAggregate) {
|
||||
let makeAggregate: () -> any DatabaseAggregate
|
||||
init(makeAggregate: @escaping () -> any DatabaseAggregate) {
|
||||
self.makeAggregate = makeAggregate
|
||||
}
|
||||
}
|
||||
|
||||
/// The current state of an aggregate, storable in SQLite
|
||||
private class AggregateContext {
|
||||
var aggregate: DatabaseAggregate
|
||||
var aggregate: any DatabaseAggregate
|
||||
var hasErrored = false
|
||||
init(aggregate: DatabaseAggregate) {
|
||||
init(aggregate: some DatabaseAggregate) {
|
||||
self.aggregate = aggregate
|
||||
}
|
||||
}
|
||||
@@ -195,10 +267,10 @@ public final class DatabaseFunction: Hashable {
|
||||
/// See <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
private enum Kind {
|
||||
/// A regular function: SELECT f(1)
|
||||
case function((Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?)
|
||||
case function((CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?)
|
||||
|
||||
/// An aggregate: SELECT f(foo) FROM bar GROUP BY baz
|
||||
case aggregate(() -> DatabaseAggregate)
|
||||
case aggregate(() -> any DatabaseAggregate)
|
||||
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
@@ -213,7 +285,7 @@ public final class DatabaseFunction: Hashable {
|
||||
|
||||
/// Feeds the `xFunc` parameter of sqlite3_create_function_v2
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
var xFunc: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
|
||||
var xFunc: (@convention(c) (OpaquePointer?, CInt, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
|
||||
guard case .function = self else { return nil }
|
||||
return { (sqliteContext, argc, argv) in
|
||||
let definition = Unmanaged<FunctionDefinition>
|
||||
@@ -231,7 +303,7 @@ public final class DatabaseFunction: Hashable {
|
||||
|
||||
/// Feeds the `xStep` parameter of sqlite3_create_function_v2
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
var xStep: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
|
||||
var xStep: (@convention(c) (OpaquePointer?, CInt, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
|
||||
guard case .aggregate = self else { return nil }
|
||||
return { (sqliteContext, argc, argv) in
|
||||
let aggregateContextU = DatabaseFunction.unmanagedAggregateContext(sqliteContext)
|
||||
@@ -288,7 +360,7 @@ public final class DatabaseFunction: Hashable {
|
||||
// > the same aggregate function instance, the same buffer is returned.
|
||||
let stride = MemoryLayout<Unmanaged<AggregateContext>>.stride
|
||||
let aggregateContextBufferP = UnsafeMutableRawBufferPointer(
|
||||
start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!,
|
||||
start: sqlite3_aggregate_context(sqliteContext, CInt(stride))!,
|
||||
count: stride)
|
||||
|
||||
if aggregateContextBufferP.contains(where: { $0 != 0 }) {
|
||||
@@ -314,7 +386,7 @@ public final class DatabaseFunction: Hashable {
|
||||
}
|
||||
}
|
||||
|
||||
private static func report(result: DatabaseValueConvertible?, in sqliteContext: OpaquePointer?) {
|
||||
private static func report(result: (any DatabaseValueConvertible)?, in sqliteContext: OpaquePointer?) {
|
||||
switch result?.databaseValue.storage ?? .null {
|
||||
case .null:
|
||||
sqlite3_result_null(sqliteContext)
|
||||
@@ -326,7 +398,7 @@ public final class DatabaseFunction: Hashable {
|
||||
sqlite3_result_text(sqliteContext, string, -1, SQLITE_TRANSIENT)
|
||||
case .blob(let data):
|
||||
data.withUnsafeBytes {
|
||||
sqlite3_result_blob(sqliteContext, $0.baseAddress, Int32($0.count), SQLITE_TRANSIENT)
|
||||
sqlite3_result_blob(sqliteContext, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -344,13 +416,11 @@ public final class DatabaseFunction: Hashable {
|
||||
}
|
||||
|
||||
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 {
|
||||
lhs.identity == rhs.identity
|
||||
}
|
||||
@@ -360,47 +430,53 @@ extension DatabaseFunction {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct MySum : DatabaseAggregate {
|
||||
/// var sum: Int = 0
|
||||
/// ```swift
|
||||
/// struct MySum : DatabaseAggregate {
|
||||
/// var sum: Int = 0
|
||||
///
|
||||
/// mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
/// if let int = Int.fromDatabaseValue(dbValues[0]) {
|
||||
/// sum += int
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// func finalize() -> DatabaseValueConvertible? {
|
||||
/// return sum
|
||||
/// mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
/// if let int = Int.fromDatabaseValue(dbValues[0]) {
|
||||
/// sum += int
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// try dbQueue.write { db in
|
||||
/// db.add(function: fn)
|
||||
/// 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
|
||||
/// func finalize() -> (any DatabaseValueConvertible)? {
|
||||
/// return sum
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// let mySum = DatabaseFunction("mySum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// try dbQueue.write { db in
|
||||
/// db.add(function: mySum)
|
||||
/// 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.
|
||||
///
|
||||
/// A new instance is created for each aggregation.
|
||||
init()
|
||||
|
||||
/// This method is called at each step of the aggregation.
|
||||
/// Updates the aggregated value for one step of the aggregation.
|
||||
///
|
||||
/// The dbValues argument contains as many values as given to the SQL
|
||||
/// aggregate function.
|
||||
/// This method is called once for each step of the aggregation.
|
||||
///
|
||||
/// -- One value
|
||||
/// SELECT maxLength(name) FROM player
|
||||
/// The `dbValues` argument contains as many values as given to the SQL
|
||||
/// aggregate function:
|
||||
///
|
||||
/// -- Two values
|
||||
/// SELECT maxFullNameLength(firstName, lastName) FROM player
|
||||
/// ```sql
|
||||
/// -- One value
|
||||
/// SELECT maxLength(name) FROM player
|
||||
///
|
||||
/// This method is never called after the finalize() method has been called.
|
||||
/// -- Two values
|
||||
/// SELECT maxFullNameLength(firstName, lastName) FROM player
|
||||
/// ```
|
||||
mutating func step(_ dbValues: [DatabaseValue]) throws
|
||||
|
||||
/// Returns the final result
|
||||
func finalize() throws -> DatabaseValueConvertible?
|
||||
/// Returns the aggregated value.
|
||||
func finalize() throws -> (any DatabaseValueConvertible)?
|
||||
}
|
||||
+288
-249
@@ -4,8 +4,7 @@ import Foundation
|
||||
import UIKit
|
||||
#endif
|
||||
|
||||
/// A DatabasePool grants concurrent accesses to an SQLite database.
|
||||
public final class DatabasePool: DatabaseWriter {
|
||||
public final class DatabasePool {
|
||||
private let writer: SerializedDatabase
|
||||
|
||||
/// The pool of reader connections.
|
||||
@@ -14,9 +13,11 @@ public final class DatabasePool: DatabaseWriter {
|
||||
|
||||
@LockedBox var databaseSnapshotCount = 0
|
||||
|
||||
/// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers.
|
||||
private var suspensionObservers: [NSObjectProtocol] = []
|
||||
|
||||
// MARK: - Database Information
|
||||
|
||||
/// The database configuration
|
||||
public var configuration: Configuration {
|
||||
writer.configuration
|
||||
}
|
||||
@@ -28,16 +29,21 @@ public final class DatabasePool: DatabaseWriter {
|
||||
|
||||
// MARK: - Initializer
|
||||
|
||||
/// Opens the SQLite database at path *path*.
|
||||
/// Opens or creates an SQLite database.
|
||||
///
|
||||
/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
/// For example:
|
||||
///
|
||||
/// Database connections get closed when the database pool gets deallocated.
|
||||
/// ```swift
|
||||
/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
/// ```
|
||||
///
|
||||
/// The SQLite connections are closed when the database pool
|
||||
/// gets deallocated.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - path: The path to the database file.
|
||||
/// - configuration: A configuration.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public init(path: String, configuration: Configuration = Configuration()) throws {
|
||||
GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1")
|
||||
|
||||
@@ -69,31 +75,12 @@ public final class DatabasePool: DatabaseWriter {
|
||||
purpose: "reader.\(readerCount)")
|
||||
})
|
||||
|
||||
// Activate WAL Mode unless readonly
|
||||
// Set up journal mode unless readonly
|
||||
if !configuration.readonly {
|
||||
try writer.sync { db in
|
||||
let journalMode = try String.fetchOne(db, sql: "PRAGMA journal_mode = WAL")
|
||||
guard journalMode == "wal" else {
|
||||
throw DatabaseError(message: "could not activate WAL Mode at path: \(path)")
|
||||
}
|
||||
|
||||
// https://www.sqlite.org/pragma.html#pragma_synchronous
|
||||
// > Many applications choose NORMAL when in WAL mode
|
||||
try db.execute(sql: "PRAGMA synchronous = NORMAL")
|
||||
|
||||
if !FileManager.default.fileExists(atPath: path + "-wal") {
|
||||
// Create the -wal file if it does not exist yet. This
|
||||
// avoids an SQLITE_CANTOPEN (14) error whenever a user
|
||||
// opens a pool to an existing non-WAL database, and
|
||||
// attempts to read from it.
|
||||
// See https://github.com/groue/GRDB.swift/issues/102
|
||||
try db.inSavepoint {
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY);
|
||||
DROP TABLE grdb_issue_102;
|
||||
""")
|
||||
return .commit
|
||||
}
|
||||
switch configuration.journalMode {
|
||||
case .default, .wal:
|
||||
try writer.sync {
|
||||
try $0.setUpWALMode()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -110,10 +97,13 @@ public final class DatabasePool: DatabaseWriter {
|
||||
}
|
||||
|
||||
deinit {
|
||||
// Remove block-based Notification observers.
|
||||
suspensionObservers.forEach(NotificationCenter.default.removeObserver(_:))
|
||||
|
||||
// Undo job done in setupMemoryManagement()
|
||||
//
|
||||
// https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error
|
||||
// Explicit unregistration is required before OS X 10.11.
|
||||
// Explicit unregistration is required before macOS 10.11.
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
|
||||
// Close reader connections before the writer connection.
|
||||
@@ -123,7 +113,7 @@ public final class DatabasePool: DatabaseWriter {
|
||||
|
||||
/// Returns a Configuration suitable for readonly connections on a
|
||||
/// WAL database.
|
||||
static func readerConfiguration(_ configuration: Configuration) -> Configuration {
|
||||
private static func readerConfiguration(_ configuration: Configuration) -> Configuration {
|
||||
var configuration = configuration
|
||||
|
||||
configuration.readonly = true
|
||||
@@ -132,7 +122,7 @@ public final class DatabasePool: DatabaseWriter {
|
||||
// Other transaction kinds are forbidden by SQLite in read-only connections.
|
||||
configuration.defaultTransactionKind = .deferred
|
||||
|
||||
// https://www.sqlite.org/wal.html#sometimes_queries_return_sqlite_busy_in_wal_mode
|
||||
// <https://www.sqlite.org/wal.html#sometimes_queries_return_sqlite_busy_in_wal_mode>
|
||||
// > But there are some obscure cases where a query against a WAL-mode
|
||||
// > database can return SQLITE_BUSY, so applications should be prepared
|
||||
// > for that happenstance.
|
||||
@@ -158,21 +148,22 @@ public final class DatabasePool: DatabaseWriter {
|
||||
}
|
||||
}
|
||||
|
||||
#if swift(>=5.6) && canImport(_Concurrency)
|
||||
// @unchecked because of databaseSnapshotCount and readerPool
|
||||
// @unchecked because of databaseSnapshotCount, readerPool and suspensionObservers
|
||||
extension DatabasePool: @unchecked Sendable { }
|
||||
#endif
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
// MARK: - Memory management
|
||||
|
||||
/// Frees as much memory as possible, by disposing non-essential memory from
|
||||
/// the writer connection, and closing all reader connections.
|
||||
/// Frees as much memory as possible, by disposing non-essential memory.
|
||||
///
|
||||
/// This method is synchronous, and blocks the current thread until all
|
||||
/// database accesses are completed.
|
||||
///
|
||||
/// This method closes all read-only connections, unless the
|
||||
/// ``Configuration/persistentReadOnlyConnections`` configuration flag
|
||||
/// is set.
|
||||
///
|
||||
/// - warning: This method can prevent concurrent reads from executing,
|
||||
/// until it returns. Prefer ``releaseMemoryEventually()`` if you intend
|
||||
/// to keep on using the database while releasing memory.
|
||||
@@ -180,34 +171,50 @@ extension DatabasePool {
|
||||
// Release writer memory
|
||||
writer.sync { $0.releaseMemory() }
|
||||
|
||||
// Release readers memory by closing all connections.
|
||||
//
|
||||
// We must use a barrier in order to guarantee that memory has been
|
||||
// freed (reader connections closed) when the method exits, as
|
||||
// documented.
|
||||
//
|
||||
// Without the barrier, connections would only close _eventually_ (after
|
||||
// their eventual concurrent jobs have completed).
|
||||
readerPool?.barrier {
|
||||
readerPool?.removeAll()
|
||||
if configuration.persistentReadOnlyConnections {
|
||||
// Keep existing readers
|
||||
readerPool?.forEach { reader in
|
||||
reader.sync { $0.releaseMemory() }
|
||||
}
|
||||
} else {
|
||||
// Release readers memory by closing all connections.
|
||||
//
|
||||
// We must use a barrier in order to guarantee that memory has been
|
||||
// freed (reader connections closed) when the method exits, as
|
||||
// documented.
|
||||
//
|
||||
// Without the barrier, connections would only close _eventually_ (after
|
||||
// their eventual concurrent jobs have completed).
|
||||
readerPool?.barrier {
|
||||
readerPool?.removeAll()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Eventually frees as much memory as possible, by disposing non-essential
|
||||
/// memory from the writer connection, and closing all reader connections.
|
||||
/// Eventually frees as much memory as possible, by disposing
|
||||
/// non-essential memory.
|
||||
///
|
||||
/// This method eventually closes all read-only connections, unless the
|
||||
/// ``Configuration/persistentReadOnlyConnections`` configuration flag
|
||||
/// is set.
|
||||
///
|
||||
/// Unlike ``releaseMemory()``, this method does not prevent concurrent
|
||||
/// database accesses when it is executing. But it does not notify when
|
||||
/// non-essential memory has been freed.
|
||||
public func releaseMemoryEventually() {
|
||||
// Release readers memory by eventually closing all reader connections
|
||||
// (they will close after their current jobs have completed).
|
||||
readerPool?.removeAll()
|
||||
if configuration.persistentReadOnlyConnections {
|
||||
// Keep existing readers
|
||||
readerPool?.forEach { reader in
|
||||
reader.async { $0.releaseMemory() }
|
||||
}
|
||||
} else {
|
||||
// Release readers memory by eventually closing all reader connections
|
||||
// (they will close after their current jobs have completed).
|
||||
readerPool?.removeAll()
|
||||
}
|
||||
|
||||
// Release writer memory eventually.
|
||||
writer.async { db in
|
||||
db.releaseMemory()
|
||||
}
|
||||
writer.async { $0.releaseMemory() }
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
@@ -216,20 +223,15 @@ extension DatabasePool {
|
||||
/// as much memory as possible.
|
||||
private func setupMemoryManagement() {
|
||||
let center = NotificationCenter.default
|
||||
|
||||
// Use raw notification names because of
|
||||
// FB9801372 (UIApplication.didReceiveMemoryWarningNotification should not be declared @MainActor)
|
||||
// TODO: Reuse UIApplication.didReceiveMemoryWarningNotification when possible.
|
||||
// TODO: Reuse UIApplication.didEnterBackgroundNotification when possible.
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabasePool.applicationDidReceiveMemoryWarning(_:)),
|
||||
name: NSNotification.Name(rawValue: "UIApplicationDidReceiveMemoryWarningNotification"),
|
||||
name: UIApplication.didReceiveMemoryWarningNotification,
|
||||
object: nil)
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabasePool.applicationDidEnterBackground(_:)),
|
||||
name: NSNotification.Name(rawValue: "UIApplicationDidEnterBackgroundNotification"),
|
||||
name: UIApplication.didEnterBackgroundNotification,
|
||||
object: nil)
|
||||
}
|
||||
|
||||
@@ -322,35 +324,27 @@ extension DatabasePool: DatabaseReader {
|
||||
private func setupSuspension() {
|
||||
if configuration.observesSuspensionNotifications {
|
||||
let center = NotificationCenter.default
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabasePool.suspend(_:)),
|
||||
name: Database.suspendNotification,
|
||||
object: nil)
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabasePool.resume(_:)),
|
||||
name: Database.resumeNotification,
|
||||
object: nil)
|
||||
suspensionObservers.append(center.addObserver(
|
||||
forName: Database.suspendNotification,
|
||||
object: nil,
|
||||
queue: nil,
|
||||
using: { [weak self] _ in self?.suspend() }
|
||||
))
|
||||
suspensionObservers.append(center.addObserver(
|
||||
forName: Database.resumeNotification,
|
||||
object: nil,
|
||||
queue: nil,
|
||||
using: { [weak self] _ in self?.resume() }
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@objc
|
||||
private func suspend(_ notification: Notification) {
|
||||
suspend()
|
||||
}
|
||||
|
||||
@objc
|
||||
private func resume(_ notification: Notification) {
|
||||
resume()
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func read<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
guard let readerPool = readerPool else {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
return try readerPool.get { reader in
|
||||
@@ -364,8 +358,8 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
guard let readerPool = self.readerPool else {
|
||||
value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")))
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -376,7 +370,7 @@ extension DatabasePool: DatabaseReader {
|
||||
reader.async { db in
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader()
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
do {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
@@ -396,7 +390,7 @@ extension DatabasePool: DatabaseReader {
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
guard let readerPool = readerPool else {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
return try readerPool.get { reader in
|
||||
@@ -408,8 +402,8 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
guard let readerPool = self.readerPool else {
|
||||
value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")))
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -419,10 +413,9 @@ extension DatabasePool: DatabaseReader {
|
||||
// Second async jump because that's how `Pool.async` has to be used.
|
||||
reader.async { db in
|
||||
defer {
|
||||
releaseReader()
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
do {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
value(.success(db))
|
||||
} catch {
|
||||
@@ -438,8 +431,10 @@ extension DatabasePool: DatabaseReader {
|
||||
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
if let reader = currentReader {
|
||||
return try reader.reentrantSync(value)
|
||||
} else if writer.onValidQueue {
|
||||
return try writer.execute(value)
|
||||
} else {
|
||||
guard let readerPool = readerPool else {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
return try readerPool.get { reader in
|
||||
@@ -469,48 +464,46 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
/// Performs the same job as asyncConcurrentRead.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
asyncConcurrentRead(value)
|
||||
}
|
||||
|
||||
/// Asynchronously executes a read-only function in a protected
|
||||
/// dispatch queue.
|
||||
/// Performs an asynchronous read access.
|
||||
///
|
||||
/// This method must be called from a writing dispatch queue, outside of any
|
||||
/// transaction. You'll get a fatal error otherwise.
|
||||
/// This method must be called from the writer dispatch queue, outside of
|
||||
/// any transaction. You'll get a fatal error otherwise.
|
||||
///
|
||||
/// The `value` function 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 from the function.
|
||||
///
|
||||
/// This method returns as soon as the isolation guarantees described above
|
||||
/// are established.
|
||||
/// This method returns as soon as the isolation guarantee described above
|
||||
/// has been established.
|
||||
///
|
||||
/// In the example below, the number of players is fetched concurrently with
|
||||
/// the player insertion. Yet the future is guaranteed to return zero:
|
||||
/// the player insertion. Yet it is guaranteed to be zero:
|
||||
///
|
||||
/// try writer.asyncWriteWithoutTransaction { db in
|
||||
/// // Delete all players
|
||||
/// try Player.deleteAll()
|
||||
/// ```swift
|
||||
/// try writer.asyncWriteWithoutTransaction { db in
|
||||
/// // Delete all players
|
||||
/// try Player.deleteAll()
|
||||
///
|
||||
/// // Count players concurrently
|
||||
/// writer.asyncConcurrentRead { dbResult in
|
||||
/// do {
|
||||
/// let db = try dbResult.get()
|
||||
/// // Guaranteed to be zero
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // Handle error
|
||||
/// }
|
||||
/// // Count players concurrently
|
||||
/// writer.asyncConcurrentRead { dbResult in
|
||||
/// do {
|
||||
/// let db = try dbResult.get()
|
||||
/// // Guaranteed to be zero
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // Handle error
|
||||
/// }
|
||||
///
|
||||
/// // Insert a player
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
///
|
||||
/// // Insert a player
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter value: A function that accesses the database.
|
||||
public func asyncConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
// Check that we're on the writer queue...
|
||||
@@ -529,14 +522,14 @@ extension DatabasePool: DatabaseReader {
|
||||
let isolationSemaphore = DispatchSemaphore(value: 0)
|
||||
|
||||
do {
|
||||
guard let readerPool = readerPool else {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
reader.async { db in
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader()
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
do {
|
||||
// https://www.sqlite.org/isolation.html
|
||||
@@ -613,8 +606,12 @@ extension DatabasePool: DatabaseReader {
|
||||
/// After this method is called, read-only database access methods will use
|
||||
/// new SQLite connections.
|
||||
///
|
||||
/// Eventual concurrent read-only accesses are not invalidated: they will
|
||||
/// Eventual concurrent read-only accesses are not interrupted, and
|
||||
/// proceed until completion.
|
||||
///
|
||||
/// - This method closes all read-only connections, even if the
|
||||
/// ``Configuration/persistentReadOnlyConnections`` configuration flag
|
||||
/// is set.
|
||||
public func invalidateReadOnlyConnections() {
|
||||
readerPool?.removeAll()
|
||||
}
|
||||
@@ -622,7 +619,7 @@ extension DatabasePool: DatabaseReader {
|
||||
/// Returns a reader that can be used from the current dispatch queue,
|
||||
/// if any.
|
||||
private var currentReader: SerializedDatabase? {
|
||||
guard let readerPool = readerPool else {
|
||||
guard let readerPool else {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -645,89 +642,57 @@ extension DatabasePool: DatabaseReader {
|
||||
return readers.first { $0.onValidQueue }
|
||||
}
|
||||
|
||||
// MARK: - Writing in Database
|
||||
// MARK: - WAL Snapshot Transactions
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.sync(updates)
|
||||
// swiftlint:disable:next line_length
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
/// Returns a long-lived WAL snapshot transaction on a reader connection.
|
||||
func walSnapshotTransaction() throws -> WALSnapshotTransaction {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
return try WALSnapshotTransaction(onReader: reader, release: { isInsideTransaction in
|
||||
// Discard the connection if the transaction could not be
|
||||
// properly ended. If we'd reuse it, the next read would
|
||||
// fail because we'd fail starting a read transaction.
|
||||
releaseReader(isInsideTransaction ? .discard : .reuse)
|
||||
})
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
// TODO: throw instead of crashing when the database is closed
|
||||
try readerPool!.barrier {
|
||||
try writer.sync(updates)
|
||||
/// Returns a long-lived WAL snapshot transaction on a reader connection.
|
||||
///
|
||||
/// - important: The `completion` argument is executed in a serial
|
||||
/// dispatch queue, so make sure you use the transaction asynchronously.
|
||||
func asyncWALSnapshotTransaction(_ completion: @escaping (Result<WALSnapshotTransaction, Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
completion(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
}
|
||||
|
||||
readerPool.asyncGet { result in
|
||||
completion(result.flatMap { reader, releaseReader in
|
||||
Result {
|
||||
try WALSnapshotTransaction(onReader: reader, release: { isInsideTransaction in
|
||||
// Discard the connection if the transaction could not be
|
||||
// properly ended. If we'd reuse it, the next read would
|
||||
// fail because we'd fail starting a read transaction.
|
||||
releaseReader(isInsideTransaction ? .discard : .reuse)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
// TODO: throw instead of crashing when the database is closed
|
||||
readerPool!.asyncBarrier {
|
||||
self.writer.sync(updates)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 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.
|
||||
///
|
||||
/// try dbPool.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 writeInTransaction(
|
||||
_ kind: Database.TransactionKind? = nil,
|
||||
_ updates: (Database) throws -> Database.TransactionCompletion)
|
||||
throws
|
||||
{
|
||||
try writer.sync { db in
|
||||
try db.inTransaction(kind) {
|
||||
try updates(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.reentrantSync(updates)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
writer.async(updates)
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// :nodoc:
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
// The easy case: the database does not change
|
||||
@@ -756,9 +721,9 @@ extension DatabasePool: DatabaseReader {
|
||||
/// the writer.
|
||||
private func _addConcurrent<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
|
||||
assert(!observation.requiresWriteAccess, "Use _addWriteOnly(observation:) instead")
|
||||
@@ -773,68 +738,121 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabasePool: DatabaseWriter {
|
||||
// MARK: - Writing in Database
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
return try readerPool.barrier {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
updates(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
}
|
||||
readerPool.asyncBarrier {
|
||||
self.writer.sync { updates(.success($0)) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps database operations inside a database transaction.
|
||||
///
|
||||
/// The `updates` function runs in the writer dispatch queue, serialized
|
||||
/// with all database updates.
|
||||
///
|
||||
/// If `updates` throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If it returns
|
||||
/// ``Database/TransactionCompletion/rollback``, the transaction is also
|
||||
/// rollbacked, but no error is thrown.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbPool.writeInTransaction { db in
|
||||
/// try Player(name: "Arthur").insert(db)
|
||||
/// try Player(name: "Barbara").insert(db)
|
||||
/// return .commit
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - precondition: This method is not reentrant.
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is the ``Configuration/defaultTransactionKind`` of the
|
||||
/// the ``configuration``.
|
||||
/// - updates: A function that updates the database.
|
||||
/// - throws: The error thrown by `updates`, or by the wrapping transaction.
|
||||
public func writeInTransaction(
|
||||
_ kind: Database.TransactionKind? = nil,
|
||||
_ updates: (Database) throws -> Database.TransactionCompletion)
|
||||
throws
|
||||
{
|
||||
try writer.sync { db in
|
||||
try db.inTransaction(kind) {
|
||||
try updates(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.reentrantSync(updates)
|
||||
}
|
||||
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
writer.async(updates)
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
// MARK: - Snapshots
|
||||
|
||||
/// Creates a database snapshot.
|
||||
/// Creates a database snapshot that serializes accesses to an unchanging
|
||||
/// database content, as it exists at the moment the snapshot is created.
|
||||
///
|
||||
/// The snapshot sees an unchanging database content, as it existed at the
|
||||
/// moment it was created.
|
||||
/// It is a programmer error to create a snapshot from the writer dispatch
|
||||
/// queue when a transaction is opened:
|
||||
///
|
||||
/// When you want to control the latest committed changes seen by a
|
||||
/// snapshot, create it from the pool's writer protected dispatch queue:
|
||||
/// ```swift
|
||||
/// try dbPool.write { db in
|
||||
/// try Player.deleteAll()
|
||||
///
|
||||
/// let snapshot1 = try dbPool.write { db -> DatabaseSnapshot in
|
||||
/// // fatal error: makeSnapshot() must not be called from inside a transaction
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// To avoid this fatal error, create the snapshot *before* or *after*
|
||||
/// the transaction:
|
||||
///
|
||||
/// ```swift
|
||||
/// let snapshot = try dbPool.makeSnapshot() // OK
|
||||
///
|
||||
/// try dbPool.writeWithoutTransaction { db in
|
||||
/// let snapshot = try dbPool.makeSnapshot() // OK
|
||||
///
|
||||
/// try db.inTransaction {
|
||||
/// try Player.deleteAll()
|
||||
/// return try dbPool.makeSnapshot()
|
||||
/// }
|
||||
/// // <- Other threads may modify the database here
|
||||
/// let snapshot2 = try dbPool.makeSnapshot()
|
||||
///
|
||||
/// try snapshot1.read { db in
|
||||
/// // Guaranteed to be zero
|
||||
/// try Player.fetchCount(db)
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// try snapshot2.read { db in
|
||||
/// // Could be anything
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// // OK
|
||||
/// let snapshot = try dbPool.makeSnapshot() // OK
|
||||
/// }
|
||||
///
|
||||
/// It is forbidden to create a snapshot from the writer protected dispatch
|
||||
/// queue when a transaction is opened, though, because it is likely a
|
||||
/// programmer error:
|
||||
///
|
||||
/// try dbPool.write { db in
|
||||
/// try db.inTransaction {
|
||||
/// try Player.deleteAll()
|
||||
/// // fatal error: makeSnapshot() must not be called from inside a transaction
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
/// return .commit
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// To avoid this fatal error, create the snapshot *before* or *after* the
|
||||
/// transaction:
|
||||
///
|
||||
/// try dbPool.writeWithoutTransaction { db in
|
||||
/// // OK
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
///
|
||||
/// try db.inTransaction {
|
||||
/// try Player.deleteAll()
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// // OK
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
/// }
|
||||
///
|
||||
/// You can create as many snapshots as you need, regardless of the maximum
|
||||
/// number of reader connections in the pool.
|
||||
///
|
||||
/// For more information, read about "snapshot isolation" at <https://sqlite.org/isolation.html>
|
||||
/// let snapshot = try dbPool.makeSnapshot() // OK
|
||||
/// ```
|
||||
public func makeSnapshot() throws -> DatabaseSnapshot {
|
||||
// Sanity check
|
||||
if writer.onValidQueue {
|
||||
@@ -847,8 +865,29 @@ extension DatabasePool {
|
||||
|
||||
return try DatabaseSnapshot(
|
||||
path: path,
|
||||
configuration: writer.configuration,
|
||||
configuration: DatabasePool.readerConfiguration(writer.configuration),
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "snapshot.\($databaseSnapshotCount.increment())")
|
||||
}
|
||||
|
||||
// swiftlint:disable:next line_length
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
/// Creates a database snapshot that allows concurrent accesses to an
|
||||
/// unchanging database content, as it exists at the moment the snapshot
|
||||
/// is created.
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// A ``DatabaseError`` of code `SQLITE_ERROR` is thrown if the SQLite
|
||||
/// database is not in the [WAL mode](https://www.sqlite.org/wal.html),
|
||||
/// or if this method is called from a write transaction, or if the
|
||||
/// wal file is missing or truncated (size zero).
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/snapshot_get.html>
|
||||
public func makeSnapshotPool() throws -> DatabaseSnapshotPool {
|
||||
try unsafeReentrantRead { db in
|
||||
try DatabaseSnapshotPool(db)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
Loaded 100 of 542 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user