mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-03 04:58:44 +00:00
Compare commits
651
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 |
No files matched your search
+86
-36
@@ -1,3 +1,5 @@
|
||||
# https://github.com/actions/runner-images/blob/main/images/macos/macos-12-Readme.md
|
||||
|
||||
name: "GRDB CI"
|
||||
|
||||
on:
|
||||
@@ -9,13 +11,17 @@ on:
|
||||
- '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 }}
|
||||
@@ -24,116 +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_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 14.0.1, Swift 5.7"
|
||||
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:
|
||||
destination: "platform=macOS"
|
||||
name: "macOS"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 14.0.1, Swift 5.7"
|
||||
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_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 14.0.1, Swift 5.7"
|
||||
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_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 14.0.1, Swift 5.7"
|
||||
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_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 14.0.1, Swift 5.7"
|
||||
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_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 14.0.1, Swift 5.7"
|
||||
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_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 14.0.1, Swift 5.7"
|
||||
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!
|
||||
|
||||
+361
-26
@@ -7,19 +7,45 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 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)
|
||||
- `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.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)
|
||||
@@ -34,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)
|
||||
@@ -80,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)
|
||||
|
||||
@@ -101,6 +127,315 @@ 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)
|
||||
@@ -3623,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:**
|
||||
|
||||
@@ -5431,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 {
|
||||
@@ -5491,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**
|
||||
|
||||
@@ -5624,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
|
||||
@@ -5667,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
|
||||
@@ -6566,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**
|
||||
|
||||
+2
-2
@@ -61,7 +61,7 @@ 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.
|
||||
|
||||
|
||||
@@ -69,7 +69,7 @@ How you can Contribute
|
||||
|
||||
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. Use Xcode > Product > Build Documentation in order to control the quality of your reference documentation.
|
||||
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.
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -720,6 +708,22 @@ Sometimes the database schema does not define any foreign key. And sometimes, th
|
||||
|
||||

|
||||
|
||||
```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:
|
||||
@@ -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
|
||||
@@ -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>
|
||||
@@ -2860,7 +2864,7 @@ extension DerivableRequest<Book> {
|
||||
}
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,14 +382,14 @@ 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
|
||||
@@ -400,7 +398,7 @@ let cancellable = hallOfFamePublisher.sink(
|
||||
[`writePublisher(receiveOn:updates:thenRead:)`]: #databasewriterwritepublisherreceiveonupdatesthenread
|
||||
[`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 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
|
||||
@@ -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>`.
|
||||
|
||||
@@ -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.39.3](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.
|
||||
|
||||
|
||||
@@ -230,6 +230,7 @@
|
||||
567C3E0E2520B6DE0011F6E9 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = YES;
|
||||
LastSwiftUpdateCheck = 1250;
|
||||
LastUpgradeCheck = 1200;
|
||||
TargetAttributes = {
|
||||
@@ -353,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",
|
||||
@@ -372,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",
|
||||
@@ -511,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",
|
||||
@@ -533,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",
|
||||
@@ -583,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
|
||||
}
|
||||
+7
@@ -61,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,12 +1,29 @@
|
||||
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.
|
||||
/// 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>
|
||||
/// 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://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://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 = try! DatabaseQueue()
|
||||
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
|
||||
let dbQueue = try! DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
return try! AppDatabase(dbQueue)
|
||||
}
|
||||
|
||||
|
||||
@@ -69,8 +69,7 @@ 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>
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
|
||||
extension DerivableRequest<Player> {
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
|
||||
@@ -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 = try 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 = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we save a new player
|
||||
@@ -35,7 +35,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_savePlayer_updates() async throws {
|
||||
// Given a players database that contains a player
|
||||
let dbQueue = try 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)
|
||||
@@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_deletePlayers() async throws {
|
||||
// Given a players database that contains four players
|
||||
let dbQueue = try 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)
|
||||
@@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_deleteAllPlayers() async throws {
|
||||
// Given a players database that contains players
|
||||
let dbQueue = try 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)
|
||||
@@ -102,7 +102,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_refreshPlayers_populates_an_empty_database() async throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we refresh players
|
||||
@@ -115,7 +115,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we create random players
|
||||
@@ -127,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 = try 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 = try 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 = try 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 = try 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 = try 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 = try 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 = try 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 = try 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)
|
||||
|
||||
@@ -13,8 +13,9 @@ 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:**
|
||||
|
||||
@@ -230,6 +230,7 @@
|
||||
567C3E0E2520B6DE0011F6E9 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = YES;
|
||||
LastSwiftUpdateCheck = 1250;
|
||||
LastUpgradeCheck = 1200;
|
||||
TargetAttributes = {
|
||||
@@ -353,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",
|
||||
@@ -372,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",
|
||||
@@ -511,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",
|
||||
@@ -532,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",
|
||||
@@ -581,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
|
||||
}
|
||||
+7
@@ -61,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,13 +1,29 @@
|
||||
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.
|
||||
/// 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>
|
||||
/// 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://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://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 = try! DatabaseQueue()
|
||||
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
|
||||
let dbQueue = try! DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
return try! AppDatabase(dbQueue)
|
||||
}
|
||||
|
||||
|
||||
@@ -69,8 +69,7 @@ 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>
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
|
||||
extension DerivableRequest<Player> {
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
|
||||
@@ -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 = try 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 = try 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 = try 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 = try 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 = try 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 = try 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 = try 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 = try 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 = try 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 = try 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 = try 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 = try 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 = try 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 = try 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 = try 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)
|
||||
|
||||
@@ -13,8 +13,8 @@ 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 @@
|
||||
<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>
|
||||
|
||||
@@ -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 */;
|
||||
@@ -328,6 +342,7 @@
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
5642253429A2391900D714BF /* PBXTargetDependency */,
|
||||
);
|
||||
name = "GRDBDemoWatchOS Extension";
|
||||
productName = "GRDBDemoWatchOS Extension";
|
||||
@@ -347,6 +362,7 @@
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
5642253029A2390800D714BF /* PBXTargetDependency */,
|
||||
568E5FD81E926430002582E0 /* PBXTargetDependency */,
|
||||
);
|
||||
name = GRDBDemoiOS;
|
||||
@@ -511,6 +527,16 @@
|
||||
target = 56B036021E8D9EBE003B6DA4 /* GRDBDemoiOS */;
|
||||
targetProxy = 56185BF525B80B8900B9C30F /* PBXContainerItemProxy */;
|
||||
};
|
||||
5642253029A2390800D714BF /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = GRDB;
|
||||
targetProxy = 5642252F29A2390800D714BF /* PBXContainerItemProxy */;
|
||||
};
|
||||
5642253429A2391900D714BF /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = GRDB;
|
||||
targetProxy = 5642253329A2391900D714BF /* PBXContainerItemProxy */;
|
||||
};
|
||||
568E5FCE1E926430002582E0 /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
target = 568E5FCA1E926430002582E0 /* GRDBDemoWatchOS Extension */;
|
||||
@@ -562,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",
|
||||
@@ -588,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",
|
||||
@@ -614,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;
|
||||
@@ -634,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;
|
||||
@@ -651,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;
|
||||
@@ -668,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;
|
||||
@@ -802,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;
|
||||
@@ -819,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;
|
||||
|
||||
+7
@@ -61,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,11 +1,28 @@
|
||||
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.
|
||||
/// 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>
|
||||
/// 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://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://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)
|
||||
|
||||
@@ -68,8 +68,7 @@ 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>
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
|
||||
extension DerivableRequest<Player> {
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
|
||||
+1
-1
@@ -138,7 +138,7 @@ 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,
|
||||
|
||||
@@ -5,7 +5,7 @@ import GRDB
|
||||
class AppDatabaseTests: XCTestCase {
|
||||
func test_database_schema() throws {
|
||||
// Given an empty database
|
||||
let dbQueue = try 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 = try 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 = try 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 = try 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 = try 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 = try 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 = try 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 = try 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 = try 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 = try 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 = try 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 = try 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 = try 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)
|
||||
|
||||
@@ -13,14 +13,14 @@ 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](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasemigrator) 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)
|
||||
|
||||
|
||||
@@ -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,8 +82,6 @@ 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.
|
||||
|
||||
> **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).
|
||||
@@ -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**: make sure you use the right platform version! You will get runtime errors on devices with a lower version.
|
||||
|
||||
> **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.**
|
||||
@@ -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
|
||||
@@ -1,836 +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
|
||||
}
|
||||
```
|
||||
|
||||
We add database powers to our types with [record protocols]. Since our records use auto-incremented ids, we provide an implementation of the `didInsert` method:
|
||||
|
||||
```swift
|
||||
// Add Database access
|
||||
|
||||
extension Author: FetchableRecord, MutablePersistableRecord {
|
||||
// Update auto-incremented id upon successful insertion
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
extension Book: FetchableRecord, MutablePersistableRecord {
|
||||
// Update auto-incremented id upon successful insertion
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
That's it. The `Author` type can read and write in the `author` database table. `Book` as well, in `book`.
|
||||
|
||||
> :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(_:)` 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#persistence-callbacks) 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](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables) 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<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<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<Author> {
|
||||
// Selects author ids
|
||||
func selectId() -> QueryInterfaceRequest<Int64> {
|
||||
selectPrimaryKey(as: Int64.self)
|
||||
}
|
||||
}
|
||||
|
||||
// IDs of French authors
|
||||
let ids: [Int64] = try Author.all().filter(country: "France").selectId().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].
|
||||
|
||||
> **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.
|
||||
|
||||
> **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]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations
|
||||
[migration]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations
|
||||
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
|
||||
[Concurrency Guide]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency
|
||||
[GRDB concurrency rules]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency
|
||||
[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).
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)")
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -195,7 +195,7 @@ protocol DerivableRequest<RowDecoder>: 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
|
||||
|
||||
@@ -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,7 +6,7 @@ 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
|
||||
@@ -18,10 +18,11 @@ To release a new GRDB version:
|
||||
- README.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`
|
||||
- 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]:
|
||||
|
||||
@@ -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
|
||||
@@ -287,21 +287,20 @@ Happy GRDB! :gift:
|
||||
|
||||
[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
|
||||
|
||||
+4
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '6.3.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.'
|
||||
@@ -20,6 +20,9 @@ Pod::Spec.new do |s|
|
||||
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|
|
||||
|
||||
+203
-17
@@ -13,6 +13,10 @@
|
||||
56012B9F257404DF00B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B742574048B00B4925B /* CommonTableExpression.swift */; };
|
||||
560233C42724234F00529DF3 /* SharedValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C32724234F00529DF3 /* SharedValueObservation.swift */; };
|
||||
560233C92724338800529DF3 /* SharedValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C82724338800529DF3 /* SharedValueObservationTests.swift */; };
|
||||
5603CEBA2AC862EC00CF097D /* SQLJSONFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */; };
|
||||
5603CEBB2AC862EC00CF097D /* SQLJSONExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB72AC862EC00CF097D /* SQLJSONExpressible.swift */; };
|
||||
5603CEBC2AC862EC00CF097D /* JSONColumn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB82AC862EC00CF097D /* JSONColumn.swift */; };
|
||||
5603CED42AC8642F00CF097D /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEC92AC8631600CF097D /* JSONExpressionsTests.swift */; };
|
||||
560432A0228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */; };
|
||||
560432A3228F1668009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */; };
|
||||
5604484925DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */; };
|
||||
@@ -54,6 +58,9 @@
|
||||
561CFA7823735016000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */; };
|
||||
561CFA982376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; };
|
||||
561CFA9C2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA9B2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift */; };
|
||||
561F38D82AC88A550051EEE9 /* JSONColumnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */; };
|
||||
561F38EF2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */; };
|
||||
561F38F42AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; };
|
||||
562205F11E420E47005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */; };
|
||||
562205F21E420E47005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */; };
|
||||
562205F31E420E47005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */; };
|
||||
@@ -68,9 +75,12 @@
|
||||
562393601DEE06D300A6B01F /* CursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623935F1DEE06D300A6B01F /* CursorTests.swift */; };
|
||||
562393691DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */; };
|
||||
562393721DEE104400A6B01F /* MapCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393711DEE104400A6B01F /* MapCursorTests.swift */; };
|
||||
5623B6142AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623B6122AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift */; };
|
||||
5623B6152AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623B6132AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift */; };
|
||||
56256ED025D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; };
|
||||
56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; };
|
||||
562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
|
||||
562B58CB2A29BBEF00E8C75D /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */; };
|
||||
562EA8261F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
|
||||
562EA82F1F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
|
||||
56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; };
|
||||
@@ -93,6 +103,7 @@
|
||||
563B8FB524A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */; };
|
||||
563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */; };
|
||||
563C67B324628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; };
|
||||
563CBBE12A595131008905CE /* SQLIndexGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563CBBE02A595131008905CE /* SQLIndexGenerator.swift */; };
|
||||
563DE4F3231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */; };
|
||||
563EF415215F87EB007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF414215F87EB007DAACD /* OrderedDictionary.swift */; };
|
||||
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF42C2161180D007DAACD /* AssociationAggregate.swift */; };
|
||||
@@ -114,6 +125,7 @@
|
||||
56419C6D24A519A2004967E1 /* ValueObservationPublisherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */; };
|
||||
56419C7824A51A38004967E1 /* Recorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A5E24A51601004967E1 /* Recorder.swift */; };
|
||||
56419C7924A51A38004967E1 /* RecordingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A5F24A51601004967E1 /* RecordingError.swift */; };
|
||||
5642A3182AD66DFE0065F717 /* LineDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5642A3172AD66DFE0065F717 /* LineDumpFormat.swift */; };
|
||||
564448831EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
|
||||
564CE43121AA901800652B19 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */; };
|
||||
564CE4E921B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; };
|
||||
@@ -145,6 +157,7 @@
|
||||
5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; };
|
||||
5653EB2120944C7C00F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */; };
|
||||
5653EC122098738B00F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */; };
|
||||
565498612B8B815500585804 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */; };
|
||||
5656A7FF22946B34001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A7F822946B33001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; };
|
||||
5656A81E2295B12F001FF3FF /* SQLAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A81D2295B12F001FF3FF /* SQLAssociation.swift */; };
|
||||
5656A8AD2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8A92295BFD5001FF3FF /* TableRecord+Association.swift */; };
|
||||
@@ -193,15 +206,27 @@
|
||||
5676FBA622F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */; };
|
||||
56781B0B243F86E600650A83 /* Refinable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56781B0A243F86E600650A83 /* Refinable.swift */; };
|
||||
5679533327E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */; };
|
||||
567B5BE72AD3284100629622 /* DatabaseReader+dump.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE02AD3284100629622 /* DatabaseReader+dump.swift */; };
|
||||
567B5BE82AD3284100629622 /* DumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE12AD3284100629622 /* DumpFormat.swift */; };
|
||||
567B5BE92AD3284100629622 /* QuoteDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE32AD3284100629622 /* QuoteDumpFormat.swift */; };
|
||||
567B5BEA2AD3284100629622 /* JSONDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE42AD3284100629622 /* JSONDumpFormat.swift */; };
|
||||
567B5BEB2AD3284100629622 /* DebugDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE52AD3284100629622 /* DebugDumpFormat.swift */; };
|
||||
567B5BEC2AD3284100629622 /* Database+Dump.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE62AD3284100629622 /* Database+Dump.swift */; };
|
||||
567B5C532AD32FF100629622 /* DatabaseDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BDC2AD3283500629622 /* DatabaseDumpTests.swift */; };
|
||||
567B5C542AD32FF100629622 /* DatabaseReaderDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BDB2AD3283500629622 /* DatabaseReaderDumpTests.swift */; };
|
||||
567DAF1C1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
|
||||
567DAF351EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; };
|
||||
567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
|
||||
568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
|
||||
5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */; };
|
||||
56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */; };
|
||||
5685C1932AD52EE600DA4B7A /* ListDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */; };
|
||||
56894F752606576600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F742606576600268F4D /* FoundationDecimalTests.swift */; };
|
||||
56894FB72606589700268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F94260657D600268F4D /* Decimal.swift */; };
|
||||
568C3F7A2A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F792A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift */; };
|
||||
568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLQueryGenerator.swift */; };
|
||||
568EB71929211E0800E59445 /* DatabaseSnapshotPool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */; };
|
||||
568EB71E2921234800E59445 /* DatabaseSnapshotPoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */; };
|
||||
568ECA8A25D7013000B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA8925D7013000B71526 /* SQLSelection.swift */; };
|
||||
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */; };
|
||||
568ECB1825D9161600B71526 /* SQLSubquery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB1725D9161500B71526 /* SQLSubquery.swift */; };
|
||||
@@ -248,7 +273,10 @@
|
||||
56AACAA822ACED7100A40F2A /* Fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AACAA722ACED7100A40F2A /* Fetch.swift */; };
|
||||
56AE64122229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */; };
|
||||
56AE6424222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE6423222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift */; };
|
||||
56AFEF2F29969F6E00CA1E51 /* TransactionClock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */; };
|
||||
56AFEF372996B9DC00CA1E51 /* TransactionDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF362996B9DC00CA1E51 /* TransactionDateTests.swift */; };
|
||||
56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; };
|
||||
56B6AB062BD3DCAC009A0B71 /* SingletonUserDefaultsTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6AB052BD3DCAC009A0B71 /* SingletonUserDefaultsTest.swift */; };
|
||||
56B6EF56208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */; };
|
||||
56B7EE832863781300C0525F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7EE822863781300C0525F /* WALSnapshot.swift */; };
|
||||
56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; };
|
||||
@@ -277,6 +305,7 @@
|
||||
56D110D828AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */; };
|
||||
56D110DD28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */; };
|
||||
56D110FA28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */; };
|
||||
56D3332029C38D6700430680 /* WALSnapshotTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */; };
|
||||
56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */; };
|
||||
56D496551D812F83008276D7 /* FoundationDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */; };
|
||||
56D496571D81303E008276D7 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; };
|
||||
@@ -373,6 +402,14 @@
|
||||
56F34FC224B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */; };
|
||||
56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
|
||||
56F61DD5283D344E00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DD4283D344E00AF9884 /* getThreadsCount.c */; };
|
||||
56F89DF72A57EAA9002FE2AA /* ColumnDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89DF62A57EAA9002FE2AA /* ColumnDefinition.swift */; };
|
||||
56F89DFC2A57EAEA002FE2AA /* ForeignKeyDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89DFB2A57EAEA002FE2AA /* ForeignKeyDefinition.swift */; };
|
||||
56F89DFE2A57EB19002FE2AA /* IndexDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89DFD2A57EB19002FE2AA /* IndexDefinition.swift */; };
|
||||
56F89E002A57EB5C002FE2AA /* TableAlteration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89DFF2A57EB5C002FE2AA /* TableAlteration.swift */; };
|
||||
56F89E022A57EB87002FE2AA /* Database+SchemaDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E012A57EB87002FE2AA /* Database+SchemaDefinition.swift */; };
|
||||
56F89E0C2A57EC16002FE2AA /* SQLTableGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E0B2A57EC16002FE2AA /* SQLTableGenerator.swift */; };
|
||||
56F89E0E2A57EC2B002FE2AA /* SQLColumnGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E0D2A57EC2B002FE2AA /* SQLColumnGenerator.swift */; };
|
||||
56F89E152A585C0B002FE2AA /* SQLTableAlterationGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */; };
|
||||
56FA0C3028B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */; };
|
||||
56FA0C3928B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */; };
|
||||
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
|
||||
@@ -402,6 +439,10 @@
|
||||
56012B742574048B00B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = "<group>"; };
|
||||
560233C32724234F00529DF3 /* SharedValueObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservation.swift; sourceTree = "<group>"; };
|
||||
560233C82724338800529DF3 /* SharedValueObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservationTests.swift; sourceTree = "<group>"; };
|
||||
5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONFunctions.swift; sourceTree = "<group>"; };
|
||||
5603CEB72AC862EC00CF097D /* SQLJSONExpressible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONExpressible.swift; sourceTree = "<group>"; };
|
||||
5603CEB82AC862EC00CF097D /* JSONColumn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumn.swift; sourceTree = "<group>"; };
|
||||
5603CEC92AC8631600CF097D /* JSONExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONExpressionsTests.swift; sourceTree = "<group>"; };
|
||||
56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = "<group>"; };
|
||||
560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = "<group>"; };
|
||||
5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = "<group>"; };
|
||||
@@ -442,6 +483,9 @@
|
||||
561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordUpdateTests.swift; sourceTree = "<group>"; };
|
||||
561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = "<group>"; };
|
||||
561CFA9B2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = "<group>"; };
|
||||
561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONColumnTests.swift; sourceTree = "<group>"; };
|
||||
561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = "<group>"; };
|
||||
5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = "<group>"; };
|
||||
5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = "<group>"; };
|
||||
@@ -449,10 +493,13 @@
|
||||
5623935F1DEE06D300A6B01F /* CursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CursorTests.swift; sourceTree = "<group>"; };
|
||||
562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FlattenCursorTests.swift; sourceTree = "<group>"; };
|
||||
562393711DEE104400A6B01F /* MapCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MapCursorTests.swift; sourceTree = "<group>"; };
|
||||
5623B6122AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueInMemoryCopyTests.swift; sourceTree = "<group>"; };
|
||||
5623B6132AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueTemporaryCopyTests.swift; sourceTree = "<group>"; };
|
||||
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = "<group>"; };
|
||||
56256ECF25D1ACD0008C2BDD /* Table.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = "<group>"; };
|
||||
56256ED825D1B316008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = "<group>"; };
|
||||
562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = "<group>"; };
|
||||
562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = "<group>"; };
|
||||
562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = "<group>"; };
|
||||
562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = "<group>"; };
|
||||
56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = "<group>"; };
|
||||
@@ -486,6 +533,7 @@
|
||||
563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReceiveValuesOn.swift; sourceTree = "<group>"; };
|
||||
563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OnDemandFuture.swift; sourceTree = "<group>"; };
|
||||
563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = "<group>"; };
|
||||
563CBBE02A595131008905CE /* SQLIndexGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLIndexGenerator.swift; sourceTree = "<group>"; };
|
||||
563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = "<group>"; };
|
||||
563EF414215F87EB007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = "<group>"; };
|
||||
563EF42C2161180D007DAACD /* AssociationAggregate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociationAggregate.swift; sourceTree = "<group>"; };
|
||||
@@ -507,7 +555,7 @@
|
||||
56419A6C24A51601004967E1 /* Support.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Support.swift; sourceTree = "<group>"; };
|
||||
56419A6D24A51601004967E1 /* DatabaseRegionObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationPublisherTests.swift; sourceTree = "<group>"; };
|
||||
56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationPublisherTests.swift; sourceTree = "<group>"; };
|
||||
5643676D272EDF2400C718C7 /* Scripts */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Scripts; sourceTree = "<group>"; };
|
||||
5642A3172AD66DFE0065F717 /* LineDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LineDumpFormat.swift; sourceTree = "<group>"; };
|
||||
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
|
||||
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
|
||||
564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueConcurrentObserver.swift; sourceTree = "<group>"; };
|
||||
@@ -606,16 +654,28 @@
|
||||
56781B0A243F86E600650A83 /* Refinable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Refinable.swift; sourceTree = "<group>"; };
|
||||
5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueWriteOnlyObserver.swift; sourceTree = "<group>"; };
|
||||
567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = "<group>"; };
|
||||
567B5BDB2AD3283500629622 /* DatabaseReaderDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderDumpTests.swift; sourceTree = "<group>"; };
|
||||
567B5BDC2AD3283500629622 /* DatabaseDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDumpTests.swift; sourceTree = "<group>"; };
|
||||
567B5BE02AD3284100629622 /* DatabaseReader+dump.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseReader+dump.swift"; sourceTree = "<group>"; };
|
||||
567B5BE12AD3284100629622 /* DumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DumpFormat.swift; sourceTree = "<group>"; };
|
||||
567B5BE32AD3284100629622 /* QuoteDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QuoteDumpFormat.swift; sourceTree = "<group>"; };
|
||||
567B5BE42AD3284100629622 /* JSONDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONDumpFormat.swift; sourceTree = "<group>"; };
|
||||
567B5BE52AD3284100629622 /* DebugDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DebugDumpFormat.swift; sourceTree = "<group>"; };
|
||||
567B5BE62AD3284100629622 /* Database+Dump.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Database+Dump.swift"; sourceTree = "<group>"; };
|
||||
567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = "<group>"; };
|
||||
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = "<group>"; };
|
||||
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
|
||||
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
|
||||
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = "<group>"; };
|
||||
56848972242DE36F002F9702 /* ValueObservationScheduler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationScheduler.swift; sourceTree = "<group>"; };
|
||||
5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ListDumpFormat.swift; sourceTree = "<group>"; };
|
||||
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
|
||||
56894F742606576600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = "<group>"; };
|
||||
56894F94260657D600268F4D /* Decimal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = "<group>"; };
|
||||
568C3F792A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = "<group>"; };
|
||||
568D13182207213E00674B58 /* SQLQueryGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQueryGenerator.swift; sourceTree = "<group>"; };
|
||||
568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPool.swift; sourceTree = "<group>"; };
|
||||
568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPoolTests.swift; sourceTree = "<group>"; };
|
||||
568ECA8925D7013000B71526 /* SQLSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelection.swift; sourceTree = "<group>"; };
|
||||
568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOrdering.swift; sourceTree = "<group>"; };
|
||||
568ECB1725D9161500B71526 /* SQLSubquery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSubquery.swift; sourceTree = "<group>"; };
|
||||
@@ -707,8 +767,11 @@
|
||||
56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HasOneThroughAssociation.swift; sourceTree = "<group>"; };
|
||||
56AE6423222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLTests.swift; sourceTree = "<group>"; };
|
||||
56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEscapingTests.swift; sourceTree = "<group>"; };
|
||||
56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionClock.swift; sourceTree = "<group>"; };
|
||||
56AFEF362996B9DC00CA1E51 /* TransactionDateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionDateTests.swift; sourceTree = "<group>"; };
|
||||
56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = "<group>"; };
|
||||
56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = "<group>"; };
|
||||
56B6AB052BD3DCAC009A0B71 /* SingletonUserDefaultsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SingletonUserDefaultsTest.swift; sourceTree = "<group>"; };
|
||||
56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = "<group>"; };
|
||||
56B7EE822863781300C0525F /* WALSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshot.swift; sourceTree = "<group>"; };
|
||||
56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = "<group>"; };
|
||||
@@ -745,6 +808,7 @@
|
||||
56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Insert.swift"; sourceTree = "<group>"; };
|
||||
56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Save.swift"; sourceTree = "<group>"; };
|
||||
56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+DAO.swift"; sourceTree = "<group>"; };
|
||||
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshotTransaction.swift; sourceTree = "<group>"; };
|
||||
56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = "<group>"; };
|
||||
56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = "<group>"; };
|
||||
56D91AA12205E03700770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = "<group>"; };
|
||||
@@ -774,6 +838,14 @@
|
||||
56F61DD0283D344D00AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "GRDBTests-Bridging-Header.h"; path = "GRDBTests/GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
|
||||
56F61DD3283D344E00AF9884 /* getThreadsCount.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = getThreadsCount.h; sourceTree = "<group>"; };
|
||||
56F61DD4283D344E00AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
|
||||
56F89DF62A57EAA9002FE2AA /* ColumnDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnDefinition.swift; sourceTree = "<group>"; };
|
||||
56F89DFB2A57EAEA002FE2AA /* ForeignKeyDefinition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinition.swift; sourceTree = "<group>"; };
|
||||
56F89DFD2A57EB19002FE2AA /* IndexDefinition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IndexDefinition.swift; sourceTree = "<group>"; };
|
||||
56F89DFF2A57EB5C002FE2AA /* TableAlteration.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableAlteration.swift; sourceTree = "<group>"; };
|
||||
56F89E012A57EB87002FE2AA /* Database+SchemaDefinition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+SchemaDefinition.swift"; sourceTree = "<group>"; };
|
||||
56F89E0B2A57EC16002FE2AA /* SQLTableGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLTableGenerator.swift; sourceTree = "<group>"; };
|
||||
56F89E0D2A57EC2B002FE2AA /* SQLColumnGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLColumnGenerator.swift; sourceTree = "<group>"; };
|
||||
56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLTableAlterationGenerator.swift; sourceTree = "<group>"; };
|
||||
56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Upsert.swift"; sourceTree = "<group>"; };
|
||||
56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Upsert.swift"; sourceTree = "<group>"; };
|
||||
56FBFED82210731A00945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = "<group>"; };
|
||||
@@ -783,6 +855,7 @@
|
||||
56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordDeleteTests.swift; sourceTree = "<group>"; };
|
||||
56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = "<group>"; };
|
||||
6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = "<group>"; };
|
||||
648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
|
||||
C96C0F242084A442006B2981 /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = "<group>"; };
|
||||
D263F40926C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseColumnEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = "<group>"; };
|
||||
@@ -811,6 +884,25 @@
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
5603CEB52AC862EC00CF097D /* JSON */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5603CEB82AC862EC00CF097D /* JSONColumn.swift */,
|
||||
5603CEB72AC862EC00CF097D /* SQLJSONExpressible.swift */,
|
||||
5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */,
|
||||
);
|
||||
path = JSON;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
5603CEC82AC8630300CF097D /* JSON */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */,
|
||||
5603CEC92AC8631600CF097D /* JSONExpressionsTests.swift */,
|
||||
);
|
||||
name = JSON;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
5605F1471C672E4000235C62 /* Support */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -890,6 +982,7 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
D263F40926C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift */,
|
||||
561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */,
|
||||
5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */,
|
||||
56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */,
|
||||
566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */,
|
||||
@@ -906,11 +999,10 @@
|
||||
children = (
|
||||
563082E32430B6BE00C14A05 /* DatabaseCancellable.swift */,
|
||||
560233C32724234F00529DF3 /* SharedValueObservation.swift */,
|
||||
564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */,
|
||||
563B06AA217EF0CC00B38F35 /* ValueObservation.swift */,
|
||||
56848972242DE36F002F9702 /* ValueObservationScheduler.swift */,
|
||||
5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */,
|
||||
56AACAA022ACEC9700A40F2A /* ValueReducer */,
|
||||
566BD72F2927AFC300595649 /* Observers */,
|
||||
56AACAA022ACEC9700A40F2A /* Reducers */,
|
||||
);
|
||||
path = ValueObservation;
|
||||
sourceTree = "<group>";
|
||||
@@ -918,12 +1010,14 @@
|
||||
56176C581EACC2D8000F3F2B /* GRDBTests */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56677C14241D14450050755D /* FailureTestCase.swift */,
|
||||
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
|
||||
562EA81E1F17B26F00FA528C /* Compilation */,
|
||||
56A238111B9C74A90082EB20 /* Core */,
|
||||
56677C14241D14450050755D /* FailureTestCase.swift */,
|
||||
567B5BDA2AD3281B00629622 /* Dump */,
|
||||
5698AC3E1DA2BEBB0056AF8C /* FTS */,
|
||||
56176CA01EACEE2A000F3F2B /* GRDBCipher */,
|
||||
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
|
||||
5603CEC82AC8630300CF097D /* JSON */,
|
||||
56A238231B9C74A90082EB20 /* Migrations */,
|
||||
569978D31B539038005EBEED /* Private */,
|
||||
56300B5C1C53C38F005A543B /* QueryInterface */,
|
||||
@@ -999,6 +1093,7 @@
|
||||
56012B542573EED000B4925B /* CommonTableExpressionTests.swift */,
|
||||
56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */,
|
||||
56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */,
|
||||
568C3F792A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift */,
|
||||
56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */,
|
||||
5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */,
|
||||
563EF45221631E21007DAACD /* QueryInterfacePromiseTests.swift */,
|
||||
@@ -1038,8 +1133,10 @@
|
||||
5687359E1CEDE16C009B9116 /* Betty.jpeg */,
|
||||
5672DE581CDB72520022BA81 /* DatabaseQueueBackupTests.swift */,
|
||||
563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */,
|
||||
5623B6122AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift */,
|
||||
56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */,
|
||||
567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */,
|
||||
5623B6132AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift */,
|
||||
569178451CED9B6000E179EA /* DatabaseQueueTests.swift */,
|
||||
);
|
||||
name = DatabaseQueue;
|
||||
@@ -1048,6 +1145,7 @@
|
||||
563B06BF2185CD1700B38F35 /* ValueObservation */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */,
|
||||
560233C82724338800529DF3 /* SharedValueObservationTests.swift */,
|
||||
563B06F621861D8300B38F35 /* ValueObservationCountTests.swift */,
|
||||
563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */,
|
||||
@@ -1104,13 +1202,6 @@
|
||||
path = GRDBCombineTests;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
564390D42414FC2C00BA61E6 /* Frameworks */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
);
|
||||
name = Frameworks;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
5653EABF20944B1300F46237 /* Association */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -1168,6 +1259,11 @@
|
||||
5656A8142295AF75001FF3FF /* Schema */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56F89DF62A57EAA9002FE2AA /* ColumnDefinition.swift */,
|
||||
56F89E012A57EB87002FE2AA /* Database+SchemaDefinition.swift */,
|
||||
56F89DFB2A57EAEA002FE2AA /* ForeignKeyDefinition.swift */,
|
||||
56F89DFD2A57EB19002FE2AA /* IndexDefinition.swift */,
|
||||
56F89DFF2A57EB5C002FE2AA /* TableAlteration.swift */,
|
||||
566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */,
|
||||
5698AC771DA37DCB0056AF8C /* VirtualTableModule.swift */,
|
||||
);
|
||||
@@ -1177,8 +1273,12 @@
|
||||
5656A8162295AFD6001FF3FF /* SQLGeneration */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56F89E0D2A57EC2B002FE2AA /* SQLColumnGenerator.swift */,
|
||||
5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */,
|
||||
563CBBE02A595131008905CE /* SQLIndexGenerator.swift */,
|
||||
568D13182207213E00674B58 /* SQLQueryGenerator.swift */,
|
||||
56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */,
|
||||
56F89E0B2A57EC16002FE2AA /* SQLTableGenerator.swift */,
|
||||
);
|
||||
path = SQLGeneration;
|
||||
sourceTree = "<group>";
|
||||
@@ -1232,9 +1332,19 @@
|
||||
path = Utils;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
566BD72F2927AFC300595649 /* Observers */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */,
|
||||
5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */,
|
||||
);
|
||||
path = Observers;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
5674A7251F30A8EF0095F066 /* FetchableRecord */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */,
|
||||
5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */,
|
||||
5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */,
|
||||
565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */,
|
||||
@@ -1242,6 +1352,38 @@
|
||||
name = FetchableRecord;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
567B5BDA2AD3281B00629622 /* Dump */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567B5BDC2AD3283500629622 /* DatabaseDumpTests.swift */,
|
||||
567B5BDB2AD3283500629622 /* DatabaseReaderDumpTests.swift */,
|
||||
);
|
||||
name = Dump;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
567B5BDF2AD3284100629622 /* Dump */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567B5BE62AD3284100629622 /* Database+Dump.swift */,
|
||||
567B5BE02AD3284100629622 /* DatabaseReader+dump.swift */,
|
||||
567B5BE12AD3284100629622 /* DumpFormat.swift */,
|
||||
567B5BE22AD3284100629622 /* DumpFormats */,
|
||||
);
|
||||
path = Dump;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
567B5BE22AD3284100629622 /* DumpFormats */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567B5BE32AD3284100629622 /* QuoteDumpFormat.swift */,
|
||||
567B5BE42AD3284100629622 /* JSONDumpFormat.swift */,
|
||||
5642A3172AD66DFE0065F717 /* LineDumpFormat.swift */,
|
||||
5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */,
|
||||
567B5BE52AD3284100629622 /* DebugDumpFormat.swift */,
|
||||
);
|
||||
path = DumpFormats;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
569530FA1C9067CC00CF1A2B /* Crash */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -1334,6 +1476,7 @@
|
||||
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */,
|
||||
564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */,
|
||||
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */,
|
||||
568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */,
|
||||
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */,
|
||||
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */,
|
||||
56A238131B9C74A90082EB20 /* DatabaseTests.swift */,
|
||||
@@ -1355,6 +1498,7 @@
|
||||
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */,
|
||||
56A238201B9C74A90082EB20 /* Statement */,
|
||||
56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */,
|
||||
56AFEF362996B9DC00CA1E51 /* TransactionDateTests.swift */,
|
||||
5607EFD11BB8253300605DE3 /* TransactionObserver */,
|
||||
);
|
||||
name = Core;
|
||||
@@ -1410,6 +1554,7 @@
|
||||
children = (
|
||||
564E73DE203D50B9000C443C /* JoinSupportTests.swift */,
|
||||
5616B4FA28B5F5220052017E /* SingletonRecordTest.swift */,
|
||||
56B6AB052BD3DCAC009A0B71 /* SingletonUserDefaultsTest.swift */,
|
||||
5674A7251F30A8EF0095F066 /* FetchableRecord */,
|
||||
560B3FA41C19DFF800C58EC7 /* PersistableRecord */,
|
||||
56176C9E1EACEDF9000F3F2B /* Record */,
|
||||
@@ -1438,6 +1583,7 @@
|
||||
564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */,
|
||||
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
|
||||
566A84192041146100E50BFD /* DatabaseSnapshot.swift */,
|
||||
568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */,
|
||||
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
|
||||
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
|
||||
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
|
||||
@@ -1447,12 +1593,14 @@
|
||||
566B9C1F25C6CC24004542CF /* RowDecodingError.swift */,
|
||||
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
|
||||
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
|
||||
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */,
|
||||
56E9FAD7221053DC00C703A8 /* SQL.swift */,
|
||||
569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */,
|
||||
56FBFED82210731A00945324 /* SQLRequest.swift */,
|
||||
56A238781B9C75030082EB20 /* Statement.swift */,
|
||||
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
|
||||
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
|
||||
56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */,
|
||||
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
|
||||
56B7EE822863781300C0525F /* WALSnapshot.swift */,
|
||||
5605F1471C672E4000235C62 /* Support */,
|
||||
@@ -1494,7 +1642,7 @@
|
||||
path = Record;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56AACAA022ACEC9700A40F2A /* ValueReducer */ = {
|
||||
56AACAA022ACEC9700A40F2A /* Reducers */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56AACAA722ACED7100A40F2A /* Fetch.swift */,
|
||||
@@ -1503,7 +1651,7 @@
|
||||
563B8F91249E6171007A48C9 /* Trace.swift */,
|
||||
5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */,
|
||||
);
|
||||
path = ValueReducer;
|
||||
path = Reducers;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56DAA2C41DE99D8D006E10C8 /* Cursor */ = {
|
||||
@@ -1565,8 +1713,6 @@
|
||||
DC37742D19C8CC90004FCF85 /* GRDB */,
|
||||
DC10500F19C904DD00D8CA30 /* Tests */,
|
||||
DC3773F419C8CBB3004FCF85 /* Products */,
|
||||
564390D42414FC2C00BA61E6 /* Frameworks */,
|
||||
5643676D272EDF2400C718C7 /* Scripts */,
|
||||
);
|
||||
indentWidth = 4;
|
||||
sourceTree = "<group>";
|
||||
@@ -1596,8 +1742,11 @@
|
||||
children = (
|
||||
56A2FA3524424D2A00E97D23 /* Export.swift */,
|
||||
566DDE0C288D763C0000DCFB /* Fixits.swift */,
|
||||
648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */,
|
||||
56A2386F1B9C75030082EB20 /* Core */,
|
||||
567B5BDF2AD3284100629622 /* Dump */,
|
||||
5698AC291D9E5A480056AF8C /* FTS */,
|
||||
5603CEB52AC862EC00CF097D /* JSON */,
|
||||
56A238911B9C750B0082EB20 /* Migration */,
|
||||
56300B6D1C53F592005A543B /* QueryInterface */,
|
||||
56A2389F1B9C753B0082EB20 /* Record */,
|
||||
@@ -1720,6 +1869,7 @@
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
562B58CB2A29BBEF00E8C75D /* Issue1383.sqlite in Resources */,
|
||||
569BBA4622906A8200478429 /* InflectionsTests.json in Resources */,
|
||||
56D496C21D81374C008276D7 /* Betty.jpeg in Resources */,
|
||||
);
|
||||
@@ -1729,6 +1879,7 @@
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
565498612B8B815500585804 /* PrivacyInfo.xcprivacy in Resources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -1781,16 +1932,19 @@
|
||||
56DA7CF7260FA9D400A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */,
|
||||
56D496691D813086008276D7 /* QueryInterfaceExpressionsTests.swift in Sources */,
|
||||
562393691DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */,
|
||||
567B5C532AD32FF100629622 /* DatabaseDumpTests.swift in Sources */,
|
||||
562205F21E420E47005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */,
|
||||
56D496B01D813385008276D7 /* DatabaseErrorTests.swift in Sources */,
|
||||
56176C5C1EACCCC7000F3F2B /* FTS5TableBuilderTests.swift in Sources */,
|
||||
562206061E420EA4005860AC /* DatabasePoolBackupTests.swift in Sources */,
|
||||
568EB71E2921234800E59445 /* DatabaseSnapshotPoolTests.swift in Sources */,
|
||||
56D496B51D813413008276D7 /* DatabaseCollationTests.swift in Sources */,
|
||||
563DE4F3231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */,
|
||||
56BF2282241781C5003D86EB /* UtilsTests.swift in Sources */,
|
||||
56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */,
|
||||
560714E3227DD0810091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */,
|
||||
56D496841D813147008276D7 /* SelectStatementTests.swift in Sources */,
|
||||
561F38D82AC88A550051EEE9 /* JSONColumnTests.swift in Sources */,
|
||||
56D496B11D8133BC008276D7 /* DatabaseQueueReadOnlyTests.swift in Sources */,
|
||||
56D4968C1D81316E008276D7 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */,
|
||||
56419C6D24A519A2004967E1 /* ValueObservationPublisherTests.swift in Sources */,
|
||||
@@ -1805,6 +1959,7 @@
|
||||
56D496BF1D8135D4008276D7 /* TableDefinitionTests.swift in Sources */,
|
||||
5674A7171F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */,
|
||||
56D496801D813131008276D7 /* StatementColumnConvertibleFetchTests.swift in Sources */,
|
||||
5603CED42AC8642F00CF097D /* JSONExpressionsTests.swift in Sources */,
|
||||
563B0705218627F800B38F35 /* ValueObservationRowTests.swift in Sources */,
|
||||
56D4966E1D81309E008276D7 /* RecordPrimaryKeyMultipleTests.swift in Sources */,
|
||||
56D496891D81316E008276D7 /* DatabaseValueConvertibleFetchTests.swift in Sources */,
|
||||
@@ -1864,6 +2019,7 @@
|
||||
56419C6B24A519A2004967E1 /* Support.swift in Sources */,
|
||||
56D496871D81316E008276D7 /* DatabaseTimestampTests.swift in Sources */,
|
||||
5615B26A222AFE8F00061C1C /* AssociationHasOneThroughRowScopeTests.swift in Sources */,
|
||||
5623B6152AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift in Sources */,
|
||||
561CFA9C2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */,
|
||||
56176C5A1EACCCC7000F3F2B /* FTS5PatternTests.swift in Sources */,
|
||||
56D496581D81304E008276D7 /* FoundationDateTests.swift in Sources */,
|
||||
@@ -1882,6 +2038,7 @@
|
||||
56D496B81D813465008276D7 /* DataMemoryTests.swift in Sources */,
|
||||
563B06CA2185D2E500B38F35 /* ValueObservationFetchTests.swift in Sources */,
|
||||
56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */,
|
||||
561F38F42AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */,
|
||||
56D496961D81317B008276D7 /* PersistableRecordTests.swift in Sources */,
|
||||
5616B4FB28B5F5220052017E /* SingletonRecordTest.swift in Sources */,
|
||||
56419C5724A51998004967E1 /* Inverted.swift in Sources */,
|
||||
@@ -1892,6 +2049,7 @@
|
||||
56057C552291B16A00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */,
|
||||
56FEB8F8248403000081AF83 /* DatabaseTraceTests.swift in Sources */,
|
||||
56419C5124A51998004967E1 /* Finished.swift in Sources */,
|
||||
561F38EF2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */,
|
||||
56176C5E1EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */,
|
||||
564D4F7E261C6DC200F55856 /* CaseInsensitiveIdentifierTests.swift in Sources */,
|
||||
56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */,
|
||||
@@ -1908,6 +2066,7 @@
|
||||
562393601DEE06D300A6B01F /* CursorTests.swift in Sources */,
|
||||
5653EAE420944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */,
|
||||
56D4968F1D81316E008276D7 /* RowFromDictionaryTests.swift in Sources */,
|
||||
567B5C542AD32FF100629622 /* DatabaseReaderDumpTests.swift in Sources */,
|
||||
56915782231BF28B00E1D237 /* PoolTests.swift in Sources */,
|
||||
56419C6C24A519A2004967E1 /* DatabaseRegionObservationPublisherTests.swift in Sources */,
|
||||
56D4968E1D81316E008276D7 /* RowCopiedFromStatementTests.swift in Sources */,
|
||||
@@ -1930,11 +2089,14 @@
|
||||
562393181DECC02000A6B01F /* RowFetchTests.swift in Sources */,
|
||||
56677C0D241CD0D00050755D /* ValueObservationRecorder.swift in Sources */,
|
||||
5653EADA20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
|
||||
56B6AB062BD3DCAC009A0B71 /* SingletonUserDefaultsTest.swift in Sources */,
|
||||
563B5336267E2F90009549B5 /* TableTests.swift in Sources */,
|
||||
56D4965A1D81304E008276D7 /* FoundationNSDataTests.swift in Sources */,
|
||||
56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */,
|
||||
56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
|
||||
564CE5BE21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */,
|
||||
5623B6142AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift in Sources */,
|
||||
56AFEF372996B9DC00CA1E51 /* TransactionDateTests.swift in Sources */,
|
||||
564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */,
|
||||
D263F40A26C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift in Sources */,
|
||||
5653EAEE20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */,
|
||||
@@ -1944,6 +2106,7 @@
|
||||
56D496C11D81373A008276D7 /* DatabaseQueueBackupTests.swift in Sources */,
|
||||
562393721DEE104400A6B01F /* MapCursorTests.swift in Sources */,
|
||||
56D496571D81303E008276D7 /* FoundationDateComponentsTests.swift in Sources */,
|
||||
568C3F7A2A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift in Sources */,
|
||||
56D496701D81309E008276D7 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
|
||||
5622060C1E420EB3005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */,
|
||||
56E5D8041B4D424400430942 /* GRDBTestCase.swift in Sources */,
|
||||
@@ -1999,6 +2162,7 @@
|
||||
files = (
|
||||
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */,
|
||||
56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
5685C1932AD52EE600DA4B7A /* ListDumpFormat.swift in Sources */,
|
||||
56158780288D875E00A67323 /* Optional.swift in Sources */,
|
||||
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */,
|
||||
5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
|
||||
@@ -2032,9 +2196,11 @@
|
||||
563082E42430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */,
|
||||
564CE59D21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */,
|
||||
5698AD351DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
|
||||
56F89DFE2A57EB19002FE2AA /* IndexDefinition.swift in Sources */,
|
||||
566B91131FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
|
||||
5605F1591C672E4000235C62 /* CGFloat.swift in Sources */,
|
||||
5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
|
||||
568EB71929211E0800E59445 /* DatabaseSnapshotPool.swift in Sources */,
|
||||
5605F1631C672E4000235C62 /* Date.swift in Sources */,
|
||||
5605F1711C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
|
||||
56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */,
|
||||
@@ -2045,11 +2211,13 @@
|
||||
563B8FB524A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
|
||||
564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */,
|
||||
564CE5AC21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
|
||||
567B5BE72AD3284100629622 /* DatabaseReader+dump.swift in Sources */,
|
||||
5659F4981EA8D989004A4992 /* Pool.swift in Sources */,
|
||||
56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */,
|
||||
5674A6F41F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */,
|
||||
5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */,
|
||||
56D110DD28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */,
|
||||
56F89E022A57EB87002FE2AA /* Database+SchemaDefinition.swift in Sources */,
|
||||
567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */,
|
||||
5653EB0320944C7C00F46237 /* BelongsToAssociation.swift in Sources */,
|
||||
563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */,
|
||||
@@ -2063,6 +2231,8 @@
|
||||
4E13D2F32769B87F0037588C /* DatabaseBackupProgress.swift in Sources */,
|
||||
560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
|
||||
563B8FAC24A1CE43007A48C9 /* DatabasePublishers.swift in Sources */,
|
||||
56F89E0C2A57EC16002FE2AA /* SQLTableGenerator.swift in Sources */,
|
||||
56F89DFC2A57EAEA002FE2AA /* ForeignKeyDefinition.swift in Sources */,
|
||||
56FA0C3028B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */,
|
||||
5605F1691C672E4000235C62 /* NSString.swift in Sources */,
|
||||
560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */,
|
||||
@@ -2070,6 +2240,7 @@
|
||||
56CEB5011EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
|
||||
56D110C928AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */,
|
||||
56AE64122229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */,
|
||||
567B5BEA2AD3284100629622 /* JSONDumpFormat.swift in Sources */,
|
||||
56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */,
|
||||
56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */,
|
||||
56D51D001EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
|
||||
@@ -2078,10 +2249,13 @@
|
||||
56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */,
|
||||
5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
|
||||
56A238A41B9C753B0082EB20 /* Record.swift in Sources */,
|
||||
567B5BE92AD3284100629622 /* QuoteDumpFormat.swift in Sources */,
|
||||
56CEB5451EAA359A00BFAF62 /* Column.swift in Sources */,
|
||||
5657AB0F1D10899D006283EF /* URL.swift in Sources */,
|
||||
560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */,
|
||||
56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */,
|
||||
56F89E152A585C0B002FE2AA /* SQLTableAlterationGenerator.swift in Sources */,
|
||||
56AFEF2F29969F6E00CA1E51 /* TransactionClock.swift in Sources */,
|
||||
5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */,
|
||||
56D91AA92205F2F100770D8D /* DatabasePromise.swift in Sources */,
|
||||
56959629222C462D002CB7C9 /* HasManyThroughAssociation.swift in Sources */,
|
||||
@@ -2094,8 +2268,11 @@
|
||||
56D110C428AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */,
|
||||
5690C3401D23E82A00E59934 /* Data.swift in Sources */,
|
||||
5659F4881EA8D94E004A4992 /* Utils.swift in Sources */,
|
||||
567B5BE82AD3284100629622 /* DumpFormat.swift in Sources */,
|
||||
566BE71E2342542F00A8254B /* LockedBox.swift in Sources */,
|
||||
56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
|
||||
5603CEBB2AC862EC00CF097D /* SQLJSONExpressible.swift in Sources */,
|
||||
56F89DF72A57EAA9002FE2AA /* ColumnDefinition.swift in Sources */,
|
||||
5611620825757583007AAF99 /* JoinAssociation.swift in Sources */,
|
||||
5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */,
|
||||
560233C42724234F00529DF3 /* SharedValueObservation.swift in Sources */,
|
||||
@@ -2103,8 +2280,10 @@
|
||||
568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */,
|
||||
5605F15D1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */,
|
||||
56894FB72606589700268F4D /* Decimal.swift in Sources */,
|
||||
56F89E002A57EB5C002FE2AA /* TableAlteration.swift in Sources */,
|
||||
56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
|
||||
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */,
|
||||
56F89E0E2A57EC2B002FE2AA /* SQLColumnGenerator.swift in Sources */,
|
||||
563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */,
|
||||
564CE43121AA901800652B19 /* ValueConcurrentObserver.swift in Sources */,
|
||||
5605F1651C672E4000235C62 /* NSNull.swift in Sources */,
|
||||
@@ -2121,10 +2300,14 @@
|
||||
56D110BF28AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */,
|
||||
566B9C2025C6CC24004542CF /* RowDecodingError.swift in Sources */,
|
||||
5698AD211DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
|
||||
5603CEBC2AC862EC00CF097D /* JSONColumn.swift in Sources */,
|
||||
56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */,
|
||||
5642A3182AD66DFE0065F717 /* LineDumpFormat.swift in Sources */,
|
||||
5605F1671C672E4000235C62 /* NSNumber.swift in Sources */,
|
||||
56E9FADA221053DD00C703A8 /* SQL.swift in Sources */,
|
||||
5603CEBA2AC862EC00CF097D /* SQLJSONFunctions.swift in Sources */,
|
||||
56717271261C68E900423B6F /* CaseInsensitiveIdentifier.swift in Sources */,
|
||||
563CBBE12A595131008905CE /* SQLIndexGenerator.swift in Sources */,
|
||||
C96C0F2B2084A442006B2981 /* SQLiteDateParser.swift in Sources */,
|
||||
56781B0B243F86E600650A83 /* Refinable.swift in Sources */,
|
||||
56A238871B9C75030082EB20 /* Row.swift in Sources */,
|
||||
@@ -2133,10 +2316,13 @@
|
||||
5653EC122098738B00F46237 /* SQLGenerationContext.swift in Sources */,
|
||||
560D92471C672C4B00F4F92B /* MutablePersistableRecord.swift in Sources */,
|
||||
5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
|
||||
56D3332029C38D6700430680 /* WALSnapshotTransaction.swift in Sources */,
|
||||
5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
|
||||
5657AAB91D107001006283EF /* NSData.swift in Sources */,
|
||||
560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */,
|
||||
567B5BEC2AD3284100629622 /* Database+Dump.swift in Sources */,
|
||||
56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */,
|
||||
567B5BEB2AD3284100629622 /* DebugDumpFormat.swift in Sources */,
|
||||
56B9649D1DA51B4C0002DA19 /* FTS5.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
|
||||
+3
@@ -17,6 +17,9 @@
|
||||
location = "group:MyPlayground.playground">
|
||||
</FileRef>
|
||||
</Group>
|
||||
<FileRef
|
||||
location = "group:BRAG.md">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:CHANGELOG.md">
|
||||
</FileRef>
|
||||
|
||||
+171
-67
@@ -1,24 +1,6 @@
|
||||
import Dispatch
|
||||
import Foundation
|
||||
|
||||
/// The configuration of a database connection.
|
||||
///
|
||||
/// You create a `Configuration` before opening a database connection:
|
||||
///
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.readonly = true
|
||||
/// config.maximumReaderCount = 2 // (DatabasePool only) The default is 5
|
||||
/// config.prepareDatabase { db in // A function to run on connection
|
||||
/// db.trace { print("SQL >", $0) }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = try DatabaseQueue( // or DatabasePool
|
||||
/// path: "/path/to/database.sqlite",
|
||||
/// configuration: config)
|
||||
/// ```
|
||||
///
|
||||
/// See <doc:DatabaseConnections>.
|
||||
public struct Configuration {
|
||||
|
||||
// MARK: - Misc options
|
||||
@@ -33,6 +15,15 @@ public struct Configuration {
|
||||
/// A boolean value indicating whether an SQLite connection is read-only.
|
||||
///
|
||||
/// 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
|
||||
|
||||
/// A label that describes a database connection.
|
||||
@@ -40,9 +31,9 @@ public struct Configuration {
|
||||
/// You can query this label at runtime:
|
||||
///
|
||||
/// ```swift
|
||||
/// var configuration = Configuration()
|
||||
/// configuration.label = "MyDatabase"
|
||||
/// let dbQueue = try DatabaseQueue(path: ..., configuration: configuration)
|
||||
/// var config = Configuration()
|
||||
/// config.label = "MyDatabase"
|
||||
/// let dbQueue = try DatabaseQueue(configuration: config)
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// print(db.configuration.label) // Prints "MyDatabase"
|
||||
@@ -90,25 +81,24 @@ public struct Configuration {
|
||||
/// double-quoted strings as string literals when they does not match any
|
||||
/// valid identifier.
|
||||
///
|
||||
/// The default and recommended value is false.
|
||||
///
|
||||
/// For example:
|
||||
/// The default and recommended value is false:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Error: no such column: foo
|
||||
/// // Error: no such column: missingColumn
|
||||
/// let name = try String.fetchOne(db, sql: """
|
||||
/// SELECT "foo" FROM "player"
|
||||
/// SELECT "missingColumn" FROM "player"
|
||||
/// """)
|
||||
/// ```
|
||||
///
|
||||
/// When true, or before SQLite 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):
|
||||
///
|
||||
/// ```swift
|
||||
/// // Success: "foo"
|
||||
/// // MISFEATURE: This query succeeds with result "missingColumn"
|
||||
/// let name = try String.fetchOne(db, sql: """
|
||||
/// SELECT "foo" FROM "player"
|
||||
/// SELECT "missingColumn" FROM "player"
|
||||
/// """)
|
||||
/// ```
|
||||
public var acceptsDoubleQuotedStringLiterals = false
|
||||
@@ -119,13 +109,10 @@ public struct Configuration {
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// Database suspension helps avoiding the
|
||||
/// [`0xdead10cc` exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report).
|
||||
///
|
||||
/// 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.
|
||||
/// 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
|
||||
|
||||
/// A boolean value indicating whether statement arguments are visible in
|
||||
@@ -133,25 +120,24 @@ public struct Configuration {
|
||||
///
|
||||
/// 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:
|
||||
/// information from leaking in unexpected places. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // 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)
|
||||
/// }
|
||||
///
|
||||
/// // Trace: sensitive information is not printed when a statement is traced:
|
||||
/// db.trace { event in
|
||||
/// // By default, sensitive information is NOT printed
|
||||
/// // when a statement is traced:
|
||||
/// print(event)
|
||||
/// }
|
||||
/// let email = "..." // sensitive information
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
///
|
||||
/// 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
|
||||
@@ -163,24 +149,41 @@ public struct Configuration {
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// #if DEBUG
|
||||
/// // Protect sensitive information by enabling verbose debugging in DEBUG builds only
|
||||
/// // 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
|
||||
/// // 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] = []
|
||||
@@ -198,7 +201,8 @@ public struct Configuration {
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// try db.execute(sql: "PRAGMA kdf_iter = 10000")
|
||||
/// // Prints all SQL statements
|
||||
/// db.trace { print("SQL >", $0) }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
@@ -225,10 +229,25 @@ public struct Configuration {
|
||||
|
||||
// MARK: - Transactions
|
||||
|
||||
/// The default kind of transaction.
|
||||
/// The default kind of write transactions.
|
||||
///
|
||||
/// 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
|
||||
|
||||
@@ -269,6 +288,46 @@ public struct Configuration {
|
||||
/// 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
|
||||
|
||||
/// Defines the how `SQLITE_BUSY` errors are handled.
|
||||
@@ -282,24 +341,48 @@ public struct Configuration {
|
||||
/// If nil, GRDB picks a default one.
|
||||
var readonlyBusyMode: Database.BusyMode? = nil
|
||||
|
||||
/// The maximum number of concurrent readers.
|
||||
/// The maximum number of concurrent reader connections.
|
||||
///
|
||||
/// This configuration applies to ``DatabasePool`` only. The default value
|
||||
/// is 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, or the execution priority, or database accesses.
|
||||
/// The quality of service of database accesses.
|
||||
///
|
||||
/// The quality of service is ignored if you supply a ``targetQueue``.
|
||||
///
|
||||
/// 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
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -316,7 +399,7 @@ public struct Configuration {
|
||||
/// The default is nil.
|
||||
public var targetQueue: DispatchQueue? = nil
|
||||
|
||||
/// The target dispatch queue for database accesses which are not read-only.
|
||||
/// The target dispatch queue for write database accesses.
|
||||
///
|
||||
/// If this queue is nil, writer connections are controlled
|
||||
/// by ``targetQueue``.
|
||||
@@ -332,7 +415,22 @@ public struct Configuration {
|
||||
/// 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.
|
||||
@@ -340,7 +438,13 @@ public struct Configuration {
|
||||
|
||||
// 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)?
|
||||
@@ -375,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)
|
||||
|
||||
@@ -195,6 +195,56 @@ extension Set {
|
||||
// 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 {
|
||||
@@ -733,6 +783,11 @@ public final class AnyCursor<Element>: 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> {
|
||||
@@ -747,6 +802,11 @@ public final class DropFirstCursor<Base: Cursor> {
|
||||
}
|
||||
}
|
||||
|
||||
// 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 {
|
||||
@@ -773,6 +833,11 @@ public final class DropWhileCursor<Base: Cursor> {
|
||||
}
|
||||
}
|
||||
|
||||
// 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 {
|
||||
@@ -818,6 +883,11 @@ public final class EnumeratedCursor<Base: Cursor> {
|
||||
}
|
||||
}
|
||||
|
||||
// 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 }
|
||||
@@ -875,6 +945,11 @@ public final class FlattenCursor<Base: Cursor> where Base.Element: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
// 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 {
|
||||
@@ -901,6 +976,11 @@ public final class MapCursor<Base: Cursor, Element> {
|
||||
}
|
||||
}
|
||||
|
||||
// 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 }
|
||||
@@ -927,6 +1007,11 @@ public final class PrefixCursor<Base: Cursor> {
|
||||
}
|
||||
}
|
||||
|
||||
// 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 }
|
||||
@@ -954,6 +1039,11 @@ public final class PrefixWhileCursor<Base: Cursor> {
|
||||
}
|
||||
}
|
||||
|
||||
// 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() {
|
||||
|
||||
+286
-86
@@ -57,6 +57,14 @@ extension Database {
|
||||
case let .attached(name): return "\(name).sqlite_master"
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of the master sqlite table, without the schema name.
|
||||
var unqualifiedMasterTableName: String { // swiftlint:disable:this inclusive_language
|
||||
switch self {
|
||||
case .main, .attached: return "sqlite_master"
|
||||
case .temp: return "sqlite_temp_master"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The identifier of a database table or view.
|
||||
@@ -79,6 +87,13 @@ extension Database {
|
||||
|
||||
// MARK: - Database Schema
|
||||
|
||||
/// Returns the current schema version.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_schema_version>
|
||||
public func schemaVersion() throws -> Int32 {
|
||||
try Int32.fetchOne(internalCachedStatement(sql: "PRAGMA schema_version"))!
|
||||
}
|
||||
|
||||
/// Clears the database schema cache.
|
||||
///
|
||||
/// If the database schema is modified by another SQLite connection to the
|
||||
@@ -106,7 +121,7 @@ extension Database {
|
||||
// at offset 40 of the database header:
|
||||
// <https://sqlite.org/pragma.html#pragma_schema_version>
|
||||
// <https://sqlite.org/fileformat2.html#database_header>
|
||||
let schemaVersion = try Int32.fetchOne(internalCachedStatement(sql: "PRAGMA schema_version"))
|
||||
let schemaVersion = try self.schemaVersion()
|
||||
if lastSchemaVersion != schemaVersion {
|
||||
lastSchemaVersion = schemaVersion
|
||||
clearSchemaCache()
|
||||
@@ -139,6 +154,19 @@ extension Database {
|
||||
return schemaIdentifiers
|
||||
}
|
||||
|
||||
/// The `SchemaIdentifier` named `schemaName` if it exists.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
|
||||
/// if no such schema exists.
|
||||
private func schemaIdentifier(named schemaName: String) throws -> SchemaIdentifier {
|
||||
let allIdentifiers = try schemaIdentifiers()
|
||||
if let result = allIdentifiers.first(where: { $0.sql.lowercased() == schemaName.lowercased() }) {
|
||||
return result
|
||||
} else {
|
||||
throw DatabaseError.noSuchSchema(schemaName)
|
||||
}
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// Returns information about a table or a view
|
||||
func table(_ tableName: String) throws -> TableInfo? {
|
||||
@@ -195,10 +223,19 @@ extension Database {
|
||||
return tableInfo
|
||||
}
|
||||
|
||||
/// Returns whether a table exists, in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func tableExists(_ name: String) throws -> Bool {
|
||||
try schemaIdentifiers().contains {
|
||||
/// Returns whether a table exists
|
||||
///
|
||||
/// When `schemaName` is not specified, known schemas are iterated in
|
||||
/// SQLite resolution order and the first matching result is returned.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
|
||||
/// if the specified schema does not exist
|
||||
public func tableExists(_ name: String, in schemaName: String? = nil) throws -> Bool {
|
||||
if let schemaName {
|
||||
return try exists(type: .table, name: name, in: schemaName)
|
||||
}
|
||||
|
||||
return try schemaIdentifiers().contains {
|
||||
try exists(type: .table, name: name, in: $0)
|
||||
}
|
||||
}
|
||||
@@ -231,20 +268,57 @@ extension Database {
|
||||
|
||||
/// Returns whether a view exists, in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func viewExists(_ name: String) throws -> Bool {
|
||||
try schemaIdentifiers().contains {
|
||||
///
|
||||
/// When `schemaName` is not specified, known schemas are iterated in
|
||||
/// SQLite resolution order and the first matching result is returned.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
|
||||
/// if the specified schema does not exist
|
||||
public func viewExists(_ name: String, in schemaName: String? = nil) throws -> Bool {
|
||||
if let schemaName {
|
||||
return try exists(type: .view, name: name, in: schemaName)
|
||||
}
|
||||
|
||||
return try schemaIdentifiers().contains {
|
||||
try exists(type: .view, name: name, in: $0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether a trigger exists, in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func triggerExists(_ name: String) throws -> Bool {
|
||||
try schemaIdentifiers().contains {
|
||||
///
|
||||
/// When `schemaName` is not specified, known schemas are iterated in
|
||||
/// SQLite resolution order and the first matching result is returned.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
|
||||
/// if the specified schema does not exist
|
||||
public func triggerExists(_ name: String, in schemaName: String? = nil) throws -> Bool {
|
||||
if let schemaName {
|
||||
return try exists(type: .trigger, name: name, in: schemaName)
|
||||
}
|
||||
|
||||
return try schemaIdentifiers().contains {
|
||||
try exists(type: .trigger, name: name, in: $0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks if an entity exists in a given schema
|
||||
///
|
||||
/// This is checking for the existence of the entity specified by
|
||||
/// `type` and `name`. It is assumed that the existence of a schema
|
||||
/// named `schemaName` is already known and will throw an error if it
|
||||
/// cannot be found.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
|
||||
/// if the specified schema does not exist
|
||||
private func exists(type: SchemaObjectType, name: String, in schemaName: String) throws -> Bool {
|
||||
if let schemaID = try schemaIdentifiers().first(where: { $0.sql.lowercased() == schemaName.lowercased() }) {
|
||||
return try exists(type: type, name: name, in: schemaID)
|
||||
} else {
|
||||
throw DatabaseError.noSuchSchema(schemaName)
|
||||
}
|
||||
}
|
||||
|
||||
private func exists(type: SchemaObjectType, name: String, in schemaID: SchemaIdentifier) throws -> Bool {
|
||||
// SQLite identifiers are case-insensitive, case-preserving:
|
||||
// http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html
|
||||
@@ -257,10 +331,17 @@ extension Database {
|
||||
/// table has no explicit primary key, the result is the hidden
|
||||
/// "rowid" column.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
|
||||
/// such table exists in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo {
|
||||
/// When `schemaName` is not specified, known schemas are iterated in
|
||||
/// SQLite resolution order and the first matching result is returned.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
|
||||
/// the specified schema does not exist, or if no such table exists in
|
||||
/// the main or temp schema, or in an attached database.
|
||||
public func primaryKey(_ tableName: String, in schemaName: String? = nil) throws -> PrimaryKeyInfo {
|
||||
if let schemaName {
|
||||
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: primaryKey(_:))
|
||||
}
|
||||
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try primaryKey(TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
return result
|
||||
@@ -347,13 +428,13 @@ extension Database {
|
||||
// FIXME: We ignore the exception, and consider all INTEGER primary
|
||||
// keys as aliases for the rowid:
|
||||
if pkColumn.type.uppercased() == "INTEGER" {
|
||||
primaryKey = .rowID(pkColumn.name)
|
||||
primaryKey = .rowID(pkColumn)
|
||||
} else {
|
||||
primaryKey = try .regular([pkColumn.name], tableHasRowID: tableHasRowID(table))
|
||||
primaryKey = try .regular([pkColumn], tableHasRowID: tableHasRowID(table))
|
||||
}
|
||||
default:
|
||||
// Multi-columns primary key
|
||||
primaryKey = try .regular(pkColumns.map(\.name), tableHasRowID: tableHasRowID(table))
|
||||
primaryKey = try .regular(pkColumns, tableHasRowID: tableHasRowID(table))
|
||||
}
|
||||
|
||||
schemaCache[table.schemaID].set(primaryKey: .value(primaryKey), forTable: table.name)
|
||||
@@ -380,7 +461,7 @@ extension Database {
|
||||
return try self.table(for: table)!.hasRowID
|
||||
}
|
||||
#else
|
||||
if #available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) {
|
||||
if #available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) { // SQLite 3.37+
|
||||
return try self.table(for: table)!.hasRowID
|
||||
}
|
||||
#endif
|
||||
@@ -419,10 +500,18 @@ extension Database {
|
||||
/// the columns contain the primary key or a unique index, use
|
||||
/// ``table(_:hasUniqueKey:)``.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
|
||||
/// such table exists in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func indexes(on tableName: String) throws -> [IndexInfo] {
|
||||
/// When `schemaName` is not specified, known schemas are iterated in
|
||||
/// SQLite resolution order and the first matching result is returned.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
|
||||
/// the specified schema does not exist, or if no such table or view
|
||||
/// with this name exists in the main or temp schema, or in an attached
|
||||
/// database.
|
||||
public func indexes(on tableName: String, in schemaName: String? = nil) throws -> [IndexInfo] {
|
||||
if let schemaName {
|
||||
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: indexes(on:))
|
||||
}
|
||||
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try indexes(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
return result
|
||||
@@ -511,10 +600,18 @@ extension Database {
|
||||
|
||||
/// Returns the foreign keys defined on table named `tableName`.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
|
||||
/// such table exists in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo] {
|
||||
/// When `schemaName` is not specified, known schemas are iterated in
|
||||
/// SQLite resolution order and the first matching result is returned.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
|
||||
/// the specified schema does not exist, or if no such table or view
|
||||
/// with this name exists in the main or temp schema, or in an attached
|
||||
/// database.
|
||||
public func foreignKeys(on tableName: String, in schemaName: String? = nil) throws -> [ForeignKeyInfo] {
|
||||
if let schemaName {
|
||||
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: foreignKeys(on:))
|
||||
}
|
||||
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try foreignKeys(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
return result
|
||||
@@ -595,10 +692,27 @@ extension Database {
|
||||
|
||||
/// Returns a cursor over foreign key violations in the table.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
|
||||
/// such table exists in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func foreignKeyViolations(in tableName: String) throws -> RecordCursor<ForeignKeyViolation> {
|
||||
/// When `schemaName` is not specified, known schemas are checked in
|
||||
/// SQLite resolution order and the first matching table is used.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
|
||||
/// the specified schema does not exist, or if no such table or view
|
||||
/// with this name exists in the main or temp schema, or in an attached
|
||||
/// database.
|
||||
public func foreignKeyViolations(
|
||||
in tableName: String,
|
||||
in schemaName: String? = nil)
|
||||
throws -> RecordCursor<ForeignKeyViolation>
|
||||
{
|
||||
if let schemaName {
|
||||
let schemaID = try schemaIdentifier(named: schemaName)
|
||||
if try exists(type: .table, name: tableName, in: schemaID) {
|
||||
return try foreignKeyViolations(in: TableIdentifier(schemaID: schemaID, name: tableName))
|
||||
} else {
|
||||
throw DatabaseError.noSuchTable(tableName)
|
||||
}
|
||||
}
|
||||
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if try exists(type: .table, name: tableName, in: schemaIdentifier) {
|
||||
return try foreignKeyViolations(in: TableIdentifier(schemaID: schemaIdentifier, name: tableName))
|
||||
@@ -627,14 +741,21 @@ extension Database {
|
||||
|
||||
/// Throws an error if there exists a foreign key violation in the table.
|
||||
///
|
||||
/// When `schemaName` is not specified, known schemas are checked in
|
||||
/// SQLite resolution order and the first matching table is used.
|
||||
///
|
||||
/// On the first foreign key violation found in the table, this method
|
||||
/// throws a ``DatabaseError`` with extended code
|
||||
/// `SQLITE_CONSTRAINT_FOREIGNKEY`.
|
||||
///
|
||||
/// If you are looking for the list of foreign key violations, prefer
|
||||
/// ``foreignKeyViolations(in:)`` instead.
|
||||
public func checkForeignKeys(in tableName: String) throws {
|
||||
try checkForeignKeys(from: foreignKeyViolations(in: tableName))
|
||||
/// ``foreignKeyViolations(in:in:)`` instead.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` as described above; when a
|
||||
/// specified schema does not exist; if no such table or view with this
|
||||
/// name exists in the main or temp schema or in an attached database.
|
||||
public func checkForeignKeys(in tableName: String, in schemaName: String? = nil) throws {
|
||||
try checkForeignKeys(from: foreignKeyViolations(in: tableName, in: schemaName))
|
||||
}
|
||||
|
||||
private func checkForeignKeys(from violations: RecordCursor<ForeignKeyViolation>) throws {
|
||||
@@ -651,9 +772,17 @@ extension Database {
|
||||
/// attached database.
|
||||
func canonicalTableName(_ tableName: String) throws -> String? {
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
// Regular tables
|
||||
if let result = try schema(schemaIdentifier).canonicalName(tableName, ofType: .table) {
|
||||
return result
|
||||
}
|
||||
|
||||
// Master table (sqlite_master, sqlite_temp_master)
|
||||
// swiftlint:disable:next inclusive_language
|
||||
let masterTableName = schemaIdentifier.unqualifiedMasterTableName
|
||||
if tableName.lowercased() == masterTableName.lowercased() {
|
||||
return masterTableName
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -666,16 +795,44 @@ extension Database {
|
||||
schemaCache[schemaID].schemaInfo = schemaInfo
|
||||
return schemaInfo
|
||||
}
|
||||
|
||||
/// Attempts to perform a table introspection function on a given
|
||||
/// table and schema
|
||||
///
|
||||
/// - parameter tableName: The name of the table to examine
|
||||
/// - parameter schemaName: The name of the schema to check
|
||||
/// - parameter introspector: An introspection function taking a
|
||||
/// `TableIdentifier` as the only parameter
|
||||
private func introspect<T>(
|
||||
tableNamed tableName: String,
|
||||
inSchemaNamed schemaName: String,
|
||||
using introspector: (TableIdentifier) throws -> T?
|
||||
) throws -> T {
|
||||
let schemaIdentifier = try schemaIdentifier(named: schemaName)
|
||||
if let result = try introspector(TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
return result
|
||||
} else {
|
||||
throw DatabaseError.noSuchTable(tableName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
/// Returns the columns in a table or a view.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
|
||||
/// such table or view with this name exists in the main or temp schema, or
|
||||
/// in an attached database.
|
||||
public func columns(in tableName: String) throws -> [ColumnInfo] {
|
||||
/// When `schemaName` is not specified, known schemas are iterated in
|
||||
/// SQLite resolution order and the first matching result is returned.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
|
||||
/// the specified schema does not exist,or if no such table or view
|
||||
/// with this name exists in the main or temp schema, or in an attached
|
||||
/// database.
|
||||
public func columns(in tableName: String, in schemaName: String? = nil) throws -> [ColumnInfo] {
|
||||
if let schemaName {
|
||||
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: columns(in:))
|
||||
}
|
||||
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try columns(in: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
return result
|
||||
@@ -833,14 +990,14 @@ extension Database {
|
||||
|
||||
/// Information about a column of a database table.
|
||||
///
|
||||
/// You get `ColumnInfo` instances with the ``Database/columns(in:)``
|
||||
/// You get `ColumnInfo` instances with the ``Database/columns(in:in:)``
|
||||
/// `Database` method.
|
||||
///
|
||||
/// Related SQLite documentation:
|
||||
///
|
||||
/// - [pragma `table_info`](https://www.sqlite.org/pragma.html#pragma_table_info)
|
||||
/// - [pragma `table_xinfo`](https://www.sqlite.org/pragma.html#pragma_table_xinfo)
|
||||
public struct ColumnInfo: FetchableRecord {
|
||||
public struct ColumnInfo: FetchableRecord, Sendable {
|
||||
let cid: Int
|
||||
let hidden: Int?
|
||||
|
||||
@@ -851,8 +1008,22 @@ public struct ColumnInfo: FetchableRecord {
|
||||
///
|
||||
/// The casing of this string depends on the SQLite version: make sure you
|
||||
/// process this string in a case-insensitive way.
|
||||
///
|
||||
/// The type is the empty string when the column has no declared type.
|
||||
public let type: String
|
||||
|
||||
/// The column data type (nil when the column has no declared type).
|
||||
///
|
||||
/// The casing of the raw value depends on the SQLite version: make sure
|
||||
/// you process the result in a case-insensitive way.
|
||||
var columnType: Database.ColumnType? {
|
||||
if type.isEmpty {
|
||||
return nil
|
||||
} else {
|
||||
return Database.ColumnType(rawValue: type)
|
||||
}
|
||||
}
|
||||
|
||||
/// A boolean value indicating if the column is constrained to be not null.
|
||||
public let isNotNull: Bool
|
||||
|
||||
@@ -905,16 +1076,16 @@ public struct ColumnInfo: FetchableRecord {
|
||||
|
||||
/// Information about an index.
|
||||
///
|
||||
/// You get `ForeignKeyInfo` instances with the ``Database/indexes(on:)``
|
||||
/// You get `IndexInfo` instances with the ``Database/indexes(on:in:)``
|
||||
/// `Database` method.
|
||||
///
|
||||
/// Related SQLite documentation:
|
||||
///
|
||||
/// - [pragma `index_list`](https://www.sqlite.org/pragma.html#pragma_index_list)
|
||||
/// - [pragma `index_info`](https://www.sqlite.org/pragma.html#pragma_index_info)
|
||||
public struct IndexInfo {
|
||||
public struct IndexInfo: Sendable{
|
||||
/// The origin of an index.
|
||||
public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible {
|
||||
public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible, Sendable {
|
||||
public var rawValue: String
|
||||
|
||||
public init(rawValue: String) {
|
||||
@@ -948,7 +1119,7 @@ public struct IndexInfo {
|
||||
///
|
||||
/// You get instances of `ForeignKeyViolation` from the `Database` methods
|
||||
/// ``Database/foreignKeyViolations()`` and
|
||||
/// ``Database/foreignKeyViolations(in:)`` methods.
|
||||
/// ``Database/foreignKeyViolations(in:in:)`` methods.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -987,7 +1158,7 @@ public struct IndexInfo {
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_foreign_key_check>
|
||||
public struct ForeignKeyViolation {
|
||||
public struct ForeignKeyViolation: Sendable {
|
||||
/// The name of the table that contains the foreign key.
|
||||
public var originTable: String
|
||||
|
||||
@@ -1002,7 +1173,7 @@ public struct ForeignKeyViolation {
|
||||
/// The id of the foreign key constraint that failed.
|
||||
///
|
||||
/// This id matches the ``ForeignKeyInfo/id`` property in
|
||||
/// ``ForeignKeyInfo``. See ``Database/foreignKeys(on:)``.
|
||||
/// ``ForeignKeyInfo``. See ``Database/foreignKeys(on:in:)``.
|
||||
public var foreignKeyId: Int
|
||||
|
||||
/// A precise description of the foreign key violation.
|
||||
@@ -1025,7 +1196,7 @@ public struct ForeignKeyViolation {
|
||||
})
|
||||
|
||||
var description: String
|
||||
if let foreignKey = foreignKey {
|
||||
if let foreignKey {
|
||||
description = """
|
||||
FOREIGN KEY constraint violation - \
|
||||
from \(originTable)(\(foreignKey.originColumns.joined(separator: ", "))) \
|
||||
@@ -1035,9 +1206,9 @@ public struct ForeignKeyViolation {
|
||||
description = "FOREIGN KEY constraint violation - from \(originTable) to \(destinationTable)"
|
||||
}
|
||||
|
||||
if let originRow = originRow {
|
||||
if let originRow {
|
||||
description += ", in \(String(describing: originRow))"
|
||||
} else if let originRowID = originRowID {
|
||||
} else if let originRowID {
|
||||
description += ", in rowid \(originRowID)"
|
||||
}
|
||||
|
||||
@@ -1077,7 +1248,7 @@ extension ForeignKeyViolation: CustomStringConvertible {
|
||||
///
|
||||
/// See also ``failureDescription(_:)``.
|
||||
public var description: String {
|
||||
if let originRowID = originRowID {
|
||||
if let originRowID {
|
||||
return """
|
||||
FOREIGN KEY constraint violation - from \(originTable) to \(destinationTable), \
|
||||
in rowid \(originRowID)
|
||||
@@ -1092,7 +1263,7 @@ extension ForeignKeyViolation: CustomStringConvertible {
|
||||
|
||||
/// Information about a primary key.
|
||||
///
|
||||
/// You get `PrimaryKeyInfo` instances with the ``Database/primaryKey(_:)``
|
||||
/// You get `PrimaryKeyInfo` instances with the ``Database/primaryKey(_:in:)``
|
||||
/// `Database` method.
|
||||
///
|
||||
/// When the table's primary key is the rowid:
|
||||
@@ -1136,29 +1307,29 @@ extension ForeignKeyViolation: CustomStringConvertible {
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // false
|
||||
/// ```
|
||||
public struct PrimaryKeyInfo {
|
||||
public struct PrimaryKeyInfo: Sendable {
|
||||
private enum Impl {
|
||||
/// The hidden rowID.
|
||||
case hiddenRowID
|
||||
|
||||
/// An INTEGER PRIMARY KEY column that aliases the Row ID.
|
||||
/// Associated string is the column name.
|
||||
case rowID(String)
|
||||
case rowID(ColumnInfo)
|
||||
|
||||
/// Any primary key, but INTEGER PRIMARY KEY.
|
||||
/// Associated strings are column names.
|
||||
case regular(columns: [String], tableHasRowID: Bool)
|
||||
case regular(columnInfos: [ColumnInfo], tableHasRowID: Bool)
|
||||
}
|
||||
|
||||
private let impl: Impl
|
||||
|
||||
static func rowID(_ column: String) -> PrimaryKeyInfo {
|
||||
PrimaryKeyInfo(impl: .rowID(column))
|
||||
static func rowID(_ columnInfo: ColumnInfo) -> PrimaryKeyInfo {
|
||||
PrimaryKeyInfo(impl: .rowID(columnInfo))
|
||||
}
|
||||
|
||||
static func regular(_ columns: [String], tableHasRowID: Bool) -> PrimaryKeyInfo {
|
||||
assert(!columns.isEmpty)
|
||||
return PrimaryKeyInfo(impl: .regular(columns: columns, tableHasRowID: tableHasRowID))
|
||||
static func regular(_ columnInfos: [ColumnInfo], tableHasRowID: Bool) -> PrimaryKeyInfo {
|
||||
assert(!columnInfos.isEmpty)
|
||||
return PrimaryKeyInfo(impl: .regular(columnInfos: columnInfos, tableHasRowID: tableHasRowID))
|
||||
}
|
||||
|
||||
static let hiddenRowID = PrimaryKeyInfo(impl: .hiddenRowID)
|
||||
@@ -1168,21 +1339,34 @@ public struct PrimaryKeyInfo {
|
||||
switch impl {
|
||||
case .hiddenRowID:
|
||||
return [Column.rowID.name]
|
||||
case let .rowID(column):
|
||||
return [column]
|
||||
case let .regular(columns: columns, tableHasRowID: _):
|
||||
return columns
|
||||
case let .rowID(columnInfo):
|
||||
return [columnInfo.name]
|
||||
case let .regular(columnInfos: columnInfos, tableHasRowID: _):
|
||||
return columnInfos.map(\.name)
|
||||
}
|
||||
}
|
||||
|
||||
/// The columns in the primary key. Nil if the primary key is the
|
||||
/// hidden rowID. Never empty otherwise.
|
||||
var columnInfos: [ColumnInfo]? {
|
||||
switch impl {
|
||||
case .hiddenRowID:
|
||||
return nil
|
||||
case let .rowID(columnInfo):
|
||||
return [columnInfo]
|
||||
case let .regular(columnInfos: columnInfos, tableHasRowID: _):
|
||||
return columnInfos
|
||||
}
|
||||
}
|
||||
|
||||
/// When not nil, the name of the column that contains the
|
||||
/// `INTEGER PRIMARY KEY`.
|
||||
public var rowIDColumn: String? {
|
||||
switch impl {
|
||||
case .hiddenRowID:
|
||||
return nil
|
||||
case .rowID(let column):
|
||||
return column
|
||||
case .rowID(let columnInfo):
|
||||
return columnInfo.name
|
||||
case .regular:
|
||||
return nil
|
||||
}
|
||||
@@ -1209,7 +1393,7 @@ public struct PrimaryKeyInfo {
|
||||
return true
|
||||
case .rowID:
|
||||
return true
|
||||
case let .regular(columns: _, tableHasRowID: tableHasRowID):
|
||||
case let .regular(columnInfos: _, tableHasRowID: tableHasRowID):
|
||||
return tableHasRowID
|
||||
}
|
||||
}
|
||||
@@ -1245,11 +1429,11 @@ public struct PrimaryKeyInfo {
|
||||
|
||||
/// Information about a foreign key.
|
||||
///
|
||||
/// You get `ForeignKeyInfo` instances with the ``Database/foreignKeys(on:)``
|
||||
/// You get `ForeignKeyInfo` instances with the ``Database/foreignKeys(on:in:)``
|
||||
/// `Database` method.
|
||||
///
|
||||
/// Related SQLite documentation: [pragma `foreign_key_list`](https://www.sqlite.org/pragma.html#pragma_foreign_key_list).
|
||||
public struct ForeignKeyInfo {
|
||||
public struct ForeignKeyInfo: Sendable {
|
||||
/// The first column in the output of the `foreign_key_list` pragma.
|
||||
public var id: Int
|
||||
|
||||
@@ -1306,29 +1490,39 @@ struct TableInfo: FetchableRecord {
|
||||
}
|
||||
}
|
||||
|
||||
enum SchemaObjectType: String {
|
||||
case index
|
||||
case table
|
||||
case trigger
|
||||
case view
|
||||
/// A value in the `type` column of `sqlite_master`.
|
||||
struct SchemaObjectType: Hashable, RawRepresentable, DatabaseValueConvertible {
|
||||
var rawValue: String
|
||||
static let index = SchemaObjectType(rawValue: "index")
|
||||
static let table = SchemaObjectType(rawValue: "table")
|
||||
static let trigger = SchemaObjectType(rawValue: "trigger")
|
||||
static let view = SchemaObjectType(rawValue: "view")
|
||||
}
|
||||
|
||||
/// A row in `sqlite_master`.
|
||||
struct SchemaObject: Hashable, FetchableRecord {
|
||||
var type: SchemaObjectType
|
||||
var name: String
|
||||
var tbl_name: String?
|
||||
var sql: String?
|
||||
|
||||
init(row: Row) throws {
|
||||
// "rootpage" column is not always there: avoid using numerical indexes
|
||||
type = row["type"]
|
||||
name = row["name"]
|
||||
tbl_name = row["tbl_name"]
|
||||
sql = row["sql"]
|
||||
}
|
||||
}
|
||||
|
||||
/// All objects in a database schema (tables, views, indexes, triggers).
|
||||
struct SchemaInfo: Equatable {
|
||||
private var objects: Set<SchemaObject>
|
||||
|
||||
/// - parameter masterTable: "sqlite_master" or "sqlite_temp_master"
|
||||
init(_ db: Database, masterTableName: String) throws { // swiftlint:disable:this inclusive_language
|
||||
objects = try SchemaObject.fetchSet(db, sql: """
|
||||
SELECT type, name, tbl_name, sql FROM \(masterTableName)
|
||||
""")
|
||||
}
|
||||
let objects: Set<SchemaObject>
|
||||
|
||||
/// Returns whether there exists a object of given type with this name
|
||||
/// (case-insensitive).
|
||||
func containsObjectNamed(_ name: String, ofType type: SchemaObjectType) -> Bool {
|
||||
let name = name.lowercased()
|
||||
let type = type.rawValue
|
||||
return objects.contains {
|
||||
$0.type == type && $0.name.lowercased() == name
|
||||
}
|
||||
@@ -1341,14 +1535,20 @@ struct SchemaInfo: Equatable {
|
||||
func canonicalName(_ name: String, ofType type: SchemaObjectType) -> String? {
|
||||
let name = name.lowercased()
|
||||
return objects
|
||||
.first { $0.type == type.rawValue && $0.name.lowercased() == name }?
|
||||
.first { $0.type == type && $0.name.lowercased() == name }?
|
||||
.name
|
||||
}
|
||||
|
||||
private struct SchemaObject: Codable, Hashable, FetchableRecord {
|
||||
var type: String
|
||||
var name: String
|
||||
var tbl_name: String?
|
||||
var sql: String?
|
||||
func filter(_ isIncluded: (SchemaObject) -> Bool) -> Self {
|
||||
SchemaInfo(objects: objects.filter(isIncluded))
|
||||
}
|
||||
}
|
||||
|
||||
extension SchemaInfo {
|
||||
/// - parameter masterTable: "sqlite_master" or "sqlite_temp_master"
|
||||
init(_ db: Database, masterTableName: String) throws { // swiftlint:disable:this inclusive_language
|
||||
objects = try SchemaObject.fetchSet(db, sql: """
|
||||
SELECT type, name, tbl_name, sql FROM \(masterTableName)
|
||||
""")
|
||||
}
|
||||
}
|
||||
@@ -361,6 +361,11 @@ public class SQLStatementCursor {
|
||||
}
|
||||
}
|
||||
|
||||
// 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 {
|
||||
@@ -373,7 +378,7 @@ extension SQLStatementCursor: Cursor {
|
||||
let baseAddress = buffer.baseAddress! // never nil because the buffer contains the trailing \0.
|
||||
|
||||
// Compile next statement
|
||||
var statementEnd: UnsafePointer<Int8>? = nil
|
||||
var statementEnd: UnsafePointer<CChar>? = nil
|
||||
let statement = try Statement(
|
||||
database: database,
|
||||
statementStart: baseAddress + offset,
|
||||
@@ -406,8 +411,8 @@ extension 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(
|
||||
@@ -431,9 +436,7 @@ extension Database {
|
||||
try checkForSuspensionViolation(from: statement)
|
||||
|
||||
// Record the database region selected by the statement execution.
|
||||
if isRecordingSelectedRegion {
|
||||
selectedRegion.formUnion(statement.databaseRegion)
|
||||
}
|
||||
try registerAccess(to: statement.databaseRegion)
|
||||
|
||||
// Database observation: prepare transaction observers.
|
||||
observationBroker?.statementWillExecute(statement)
|
||||
@@ -447,6 +450,8 @@ extension Database {
|
||||
clearSchemaCache()
|
||||
}
|
||||
|
||||
checkForAutocommitTransition()
|
||||
|
||||
// Database observation: cleanup
|
||||
try observationBroker?.statementDidExecute(statement)
|
||||
}
|
||||
@@ -462,6 +467,8 @@ extension Database {
|
||||
internalStatementCache.remove(statement)
|
||||
publicStatementCache.remove(statement)
|
||||
|
||||
checkForAutocommitTransition()
|
||||
|
||||
// Extract values that may be modified by the user in their
|
||||
// `TransactionObserver.databaseDidRollback(_:)` implementation
|
||||
// (see below).
|
||||
@@ -483,6 +490,25 @@ extension Database {
|
||||
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
|
||||
@@ -512,7 +538,7 @@ struct StatementCache {
|
||||
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, *) {
|
||||
if #available(iOS 12, macOS 10.14, watchOS 5, *) { // SQLite 3.20+
|
||||
statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT))
|
||||
} else {
|
||||
statement = try db.makeStatement(sql: sql)
|
||||
|
||||
+381
-138
@@ -60,15 +60,29 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// - ``inSavepoint(_:)``
|
||||
/// - ``inTransaction(_:_:)``
|
||||
/// - ``isInsideTransaction``
|
||||
/// - ``readOnly(_:)``
|
||||
/// - ``rollback()``
|
||||
/// - ``transactionDate``
|
||||
/// - ``TransactionCompletion``
|
||||
/// - ``TransactionKind``
|
||||
///
|
||||
/// ### Observing Database Transactions
|
||||
/// ### Printing Database Content
|
||||
///
|
||||
/// - ``dumpContent(format:to:)``
|
||||
/// - ``dumpRequest(_:format:to:)``
|
||||
/// - ``dumpSchema(to:)``
|
||||
/// - ``dumpSQL(_:format:to:)``
|
||||
/// - ``dumpTables(_:format:tableHeader:stableOrder:to:)``
|
||||
/// - ``DumpFormat``
|
||||
/// - ``DumpTableHeaderOptions``
|
||||
///
|
||||
/// ### Database Observation
|
||||
///
|
||||
/// - ``add(transactionObserver:extent:)``
|
||||
/// - ``afterNextTransaction(onCommit:onRollback:)``
|
||||
/// - ``remove(transactionObserver:)``
|
||||
/// - ``afterNextTransaction(onCommit:onRollback:)``
|
||||
/// - ``notifyChanges(in:)``
|
||||
/// - ``registerAccess(to:)``
|
||||
///
|
||||
/// ### Collations
|
||||
///
|
||||
@@ -92,6 +106,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
///
|
||||
/// ### Other Database Operations
|
||||
///
|
||||
/// - ``add(tokenizer:)``
|
||||
/// - ``backup(to:pagesPerStep:progress:)``
|
||||
/// - ``checkpoint(_:on:)``
|
||||
/// - ``clearSchemaCache()``
|
||||
@@ -100,21 +115,15 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// - ``trace(options:_:)``
|
||||
/// - ``CheckpointMode``
|
||||
/// - ``DatabaseBackupProgress``
|
||||
/// - ``StorageClass``
|
||||
/// - ``TraceEvent``
|
||||
/// - ``TracingOptions``
|
||||
///
|
||||
/// ### Sunsetted Methods
|
||||
///
|
||||
/// - ``create(index:on:columns:unique:ifNotExists:condition:)``
|
||||
/// - ``create(table:temporary:ifNotExists:withoutRowID:body:)``
|
||||
public final class Database: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
// The Database class is not thread-safe. An instance should always be
|
||||
// used through a SerializedDatabase.
|
||||
|
||||
// MARK: - SQLite C API
|
||||
|
||||
// TODO: make it non optional, since one can't get a `Database` instance
|
||||
// after `close()`.
|
||||
/// The raw SQLite connection, suitable for the SQLite C API.
|
||||
///
|
||||
/// The result is nil after the database has been successfully closed with
|
||||
@@ -216,6 +225,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// MARK: - Internal properties
|
||||
|
||||
let path: String
|
||||
|
||||
/// Support for schema changes performed with ``DatabasePool``: each read
|
||||
/// access needs to clear the schema cache if the schema has been modified
|
||||
/// by the writer connection since the previous read. This property is reset
|
||||
@@ -259,9 +270,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
|
||||
/// Whether the database region selected by statement execution is
|
||||
/// recorded into `selectedRegion`.
|
||||
/// recorded into `selectedRegion` by `track(_:)`.
|
||||
///
|
||||
/// To record the selected region, use `recordingSelection(_:_:)`.
|
||||
/// To start recording the selected region, use `recordingSelection(_:_:)`.
|
||||
private(set) var isRecordingSelectedRegion = false
|
||||
|
||||
/// The database region selected by statement execution, when
|
||||
@@ -278,6 +289,60 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// This cache is never cleared: we assume journal mode never changes.
|
||||
var journalModeCache: String?
|
||||
|
||||
// MARK: - Transaction Date
|
||||
|
||||
enum AutocommitState {
|
||||
case off
|
||||
case on
|
||||
}
|
||||
|
||||
/// The state of the auto-commit mode, as left by the last
|
||||
/// executed statement.
|
||||
///
|
||||
/// The goal of this property is to detect changes in the auto-commit mode.
|
||||
/// When you need to know if the database is currently in the auto-commit
|
||||
/// mode, always prefer ``isInsideTransaction``.
|
||||
var autocommitState = AutocommitState.on
|
||||
|
||||
/// The date of the current transaction, wrapped in a result that is an
|
||||
/// error if there was an error grabbing this date when the transaction has
|
||||
/// started.
|
||||
///
|
||||
/// Invariant: `transactionDateResult` is nil iff connection is not
|
||||
/// inside a transaction.
|
||||
var transactionDateResult: Result<Date, Error>?
|
||||
|
||||
/// The date of the current transaction.
|
||||
///
|
||||
/// The returned date is constant at any point during a transaction. It is
|
||||
/// set when the database leaves the
|
||||
/// [autocommit mode](https://www.sqlite.org/c3ref/get_autocommit.html) with
|
||||
/// a `BEGIN` statement.
|
||||
///
|
||||
/// When the database is not currently in a transaction, a new date is
|
||||
/// returned on each call.
|
||||
///
|
||||
/// See <doc:RecordTimestamps> for an example of usage.
|
||||
///
|
||||
/// The transaction date, by default, is the start date of the current
|
||||
/// transaction. You can override this default behavior by configuring
|
||||
/// ``Configuration/transactionClock``.
|
||||
public var transactionDate: Date {
|
||||
get throws {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
|
||||
// Check invariant: `transactionDateResult` is nil iff connection
|
||||
// is not inside a transaction.
|
||||
assert(isInsideTransaction || transactionDateResult == nil)
|
||||
|
||||
if let transactionDateResult {
|
||||
return try transactionDateResult.get()
|
||||
} else {
|
||||
return try configuration.transactionClock.now(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Private properties
|
||||
|
||||
/// Support for ``Configuration/busyMode``.
|
||||
@@ -305,6 +370,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
|
||||
self.description = description
|
||||
self.configuration = configuration
|
||||
self.path = path
|
||||
|
||||
// We do not report read-only transactions to transaction observers, so
|
||||
// don't bother installing the observation broker for read-only connections.
|
||||
@@ -336,10 +402,10 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
_ = sqlite3_close(sqliteConnection) // ignore result code
|
||||
throw DatabaseError(resultCode: code)
|
||||
}
|
||||
if let sqliteConnection = sqliteConnection {
|
||||
return sqliteConnection
|
||||
guard let sqliteConnection else {
|
||||
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
|
||||
}
|
||||
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
|
||||
return sqliteConnection
|
||||
}
|
||||
|
||||
// MARK: - Database Setup
|
||||
@@ -366,6 +432,41 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
configuration.SQLiteConnectionDidOpen?()
|
||||
}
|
||||
|
||||
/// Performs ``Configuration/JournalModeConfiguration/wal``.
|
||||
func setUpWALMode() throws {
|
||||
let journalMode = try String.fetchOne(self, 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 execute(sql: "PRAGMA synchronous = NORMAL")
|
||||
|
||||
// Make sure a non-empty wal file exists.
|
||||
//
|
||||
// The presence of the wal file avoids an SQLITE_CANTOPEN (14)
|
||||
// error when the user opens a pool and reads from it.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/102>.
|
||||
//
|
||||
// The non-empty wal file avoids an SQLITE_ERROR (1) error
|
||||
// when the user opens a pool and creates a wal snapshot
|
||||
// (which happens when starting a ValueObservation).
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1383>.
|
||||
let walPath = path + "-wal"
|
||||
if try FileManager.default.fileExists(atPath: walPath) == false
|
||||
|| (URL(fileURLWithPath: walPath).resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0) == 0
|
||||
{
|
||||
try inSavepoint {
|
||||
try execute(sql: """
|
||||
CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY);
|
||||
DROP TABLE grdb_issue_102;
|
||||
""")
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func setupDoubleQuotedStringLiterals() {
|
||||
if configuration.acceptsDoubleQuotedStringLiterals {
|
||||
_enableDoubleQuotedStringLiterals(sqliteConnection)
|
||||
@@ -672,11 +773,38 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
/// Grants read-only access in the wrapped closure.
|
||||
func readOnly<T>(_ block: () throws -> T) throws -> T {
|
||||
/// Executes read-only database operations, and returns their result
|
||||
/// after they have finished executing.
|
||||
///
|
||||
/// Attempts to write throw a ``DatabaseError`` with
|
||||
/// resultCode `SQLITE_READONLY`.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write do { db in
|
||||
/// // Write OK
|
||||
/// try Player(...).insert(db)
|
||||
///
|
||||
/// try db.readOnly {
|
||||
/// // Read OK
|
||||
/// let players = try Player.fetchAll(db)
|
||||
///
|
||||
/// // Throws SQLITE_READONLY
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This method is reentrant.
|
||||
///
|
||||
/// - parameter value: A closure that reads from the database.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or the
|
||||
/// error thrown by `value`.
|
||||
public func readOnly<T>(_ value: () throws -> T) throws -> T {
|
||||
try beginReadOnly()
|
||||
return try throwingFirstError(
|
||||
execute: block,
|
||||
execute: value,
|
||||
finally: endReadOnly)
|
||||
}
|
||||
|
||||
@@ -686,27 +814,127 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
readOnlyDepth > 0 || configuration.readonly
|
||||
}
|
||||
|
||||
// MARK: - Recording of the selected region
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// Extends the `region` argument with the database region selected by all
|
||||
/// statements executed by the closure.
|
||||
/// Reports the database region to ``ValueObservation``.
|
||||
///
|
||||
/// Calling this method does not fetch any database values. It just
|
||||
/// helps optimizing `ValueObservation`. See
|
||||
/// ``ValueObservation/trackingConstantRegion(_:)`` for more
|
||||
/// information, and some examples of usage.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// var region = DatabaseRegion()
|
||||
/// try db.recordingSelection(®ion) {
|
||||
/// let players = try Player.fetchAll(db)
|
||||
/// let team = try Team.fetchOne(db, id: 42)
|
||||
/// }
|
||||
/// print(region) // player(*),team(*)[42]
|
||||
/// ```swift
|
||||
/// let observation = ValueObservation.tracking { db in
|
||||
/// // All changes to the 'player' and 'team' tables
|
||||
/// // will trigger the observation.
|
||||
/// try db.registerAccess(to: Player.all())
|
||||
/// try db.registerAccess(to: Team.all())
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This method has no effect on a `ValueObservation` created with
|
||||
/// ``ValueObservation/tracking(regions:fetch:)``. In the example below,
|
||||
/// only the `player` table is tracked:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Observes the 'player' table only
|
||||
/// let observation = ValueObservation.tracking(region: Player.all()) { db in
|
||||
/// // Ignored
|
||||
/// try db.registerAccess(to: Team.all())
|
||||
/// }
|
||||
/// ```
|
||||
public func registerAccess(to region: @autoclosure () -> some DatabaseRegionConvertible) throws {
|
||||
if isRecordingSelectedRegion {
|
||||
try selectedRegion.formUnion(region().databaseRegion(self))
|
||||
}
|
||||
}
|
||||
|
||||
/// Notifies that some changes were performed in the provided
|
||||
/// database region.
|
||||
///
|
||||
/// This method makes it possible to notify undetected changes, such as
|
||||
/// changes performed by another process, changes performed by
|
||||
/// direct calls to SQLite C functions, or changes to the
|
||||
/// database schema.
|
||||
/// See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes>
|
||||
/// for a detailed list of undetected database modifications.
|
||||
///
|
||||
/// It triggers active transaction observers (``TransactionObserver``).
|
||||
/// In particular, ``ValueObservation`` that observe the input `region`
|
||||
/// will fetch and notify a fresh value.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// // Notify observers that some changes were performed in the database
|
||||
/// try db.notifyChanges(in: .fullDatabase)
|
||||
///
|
||||
/// // Notify observers that some changes were performed in the player table
|
||||
/// try db.notifyChanges(in: Player.all())
|
||||
///
|
||||
/// // Equivalent alternative
|
||||
/// try db.notifyChanges(in: Table("player"))
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This method has no effect when called from a read-only
|
||||
/// database access.
|
||||
///
|
||||
/// > Caveat: Individual rowids in the input region are ignored.
|
||||
/// > Notifying a change to a specific rowid is the same as notifying a
|
||||
/// > change in the whole table:
|
||||
/// >
|
||||
/// > ```swift
|
||||
/// > try dbQueue.write { db in
|
||||
/// > // Equivalent
|
||||
/// > try db.notifyChanges(in: Player.all())
|
||||
/// > try db.notifyChanges(in: Player.filter(id: 1))
|
||||
/// > }
|
||||
/// > ```
|
||||
public func notifyChanges(in region: some DatabaseRegionConvertible) throws {
|
||||
// Don't do anything when read-only, because read-only transactions
|
||||
// are not notified. We don't want to notify transactions observers
|
||||
// of changes, and have them wait for a commit notification that
|
||||
// will never come.
|
||||
if !isReadOnly, let observationBroker {
|
||||
let eventKinds = try region
|
||||
.databaseRegion(self)
|
||||
// Use canonical table names for case insensitivity of the input.
|
||||
.canonicalTables(self)
|
||||
.impactfulEventKinds(self)
|
||||
|
||||
try observationBroker.notifyChanges(withEventsOfKind: eventKinds)
|
||||
}
|
||||
}
|
||||
|
||||
/// Extends the `region` argument with the database region selected by all
|
||||
/// statements executed by the closure, and all regions explicitly tracked
|
||||
/// with the ``registerAccess(to:)`` method.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// var region = DatabaseRegion()
|
||||
/// try db.recordingSelection(®ion) {
|
||||
/// let players = try Player.fetchAll(db)
|
||||
/// let team = try Team.fetchOne(db, id: 42)
|
||||
/// try db.registerAccess(to: Table("awards"))
|
||||
/// }
|
||||
/// print(region) // awards,player(*),team(*)[42]
|
||||
/// ```
|
||||
///
|
||||
/// This method is used by ``ValueObservation``:
|
||||
///
|
||||
/// let playersObservation = ValueObservation.tracking { db in
|
||||
/// // Here all fetches are recorded, so that we know what is the
|
||||
/// // database region that must be observed.
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// let playersObservation = ValueObservation.tracking { db in
|
||||
/// // Here all fetches are recorded, so that we know what is the
|
||||
/// // database region that must be observed.
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
func recordingSelection<T>(_ region: inout DatabaseRegion, _ block: () throws -> T) rethrows -> T {
|
||||
if region.isFullDatabase {
|
||||
return try block()
|
||||
@@ -766,31 +994,16 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
self.trace = trace
|
||||
|
||||
if options.isEmpty || trace == nil {
|
||||
#if os(Linux)
|
||||
sqlite3_trace(sqliteConnection, nil)
|
||||
#else
|
||||
sqlite3_trace_v2(sqliteConnection, 0, nil, nil)
|
||||
#endif
|
||||
return
|
||||
}
|
||||
|
||||
// sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0
|
||||
// http://www.sqlite.org/changes.html#version_3_14
|
||||
#if os(Linux)
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
|
||||
guard let sql = sql.map(String.init(cString:)) else { return }
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
|
||||
db.trace?(Database.TraceEvent.statement(TraceEvent.Statement(impl: .trace_v1(sql))))
|
||||
}, dbPointer)
|
||||
#else
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
sqlite3_trace_v2(sqliteConnection, CUnsignedInt(bitPattern: options.rawValue), { (mask, dbPointer, p, x) in
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
|
||||
db.trace_v2(CInt(bitPattern: mask), p, x, sqlite3_expanded_sql)
|
||||
return SQLITE_OK
|
||||
}, dbPointer)
|
||||
#endif
|
||||
}
|
||||
|
||||
// Precondition: configuration.trace != nil
|
||||
@@ -798,7 +1011,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
_ mask: CInt,
|
||||
_ p: UnsafeMutableRawPointer?,
|
||||
_ x: UnsafeMutableRawPointer?,
|
||||
_ sqlite3_expanded_sql: @escaping @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
|
||||
_ sqlite3_expanded_sql: @escaping @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<CChar>?)
|
||||
{
|
||||
guard let trace else { return }
|
||||
|
||||
@@ -806,26 +1019,22 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
case SQLITE_TRACE_STMT:
|
||||
if let sqliteStatement = p, let unexpandedSQL = x {
|
||||
let statement = TraceEvent.Statement(
|
||||
impl: .trace_v2(
|
||||
sqliteStatement: OpaquePointer(sqliteStatement),
|
||||
unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)),
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql,
|
||||
publicStatementArguments: configuration.publicStatementArguments))
|
||||
sqliteStatement: OpaquePointer(sqliteStatement),
|
||||
unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)),
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql,
|
||||
publicStatementArguments: configuration.publicStatementArguments)
|
||||
trace(TraceEvent.statement(statement))
|
||||
}
|
||||
case SQLITE_TRACE_PROFILE:
|
||||
if let sqliteStatement = p, let durationP = x?.assumingMemoryBound(to: Int64.self) {
|
||||
let statement = TraceEvent.Statement(
|
||||
impl: .trace_v2(
|
||||
sqliteStatement: OpaquePointer(sqliteStatement),
|
||||
unexpandedSQL: nil,
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql,
|
||||
publicStatementArguments: configuration.publicStatementArguments))
|
||||
sqliteStatement: OpaquePointer(sqliteStatement),
|
||||
unexpandedSQL: nil,
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql,
|
||||
publicStatementArguments: configuration.publicStatementArguments)
|
||||
let duration = TimeInterval(durationP.pointee) / 1.0e9
|
||||
|
||||
#if !os(Linux)
|
||||
trace(TraceEvent.profile(statement: statement, duration: duration))
|
||||
#endif
|
||||
}
|
||||
default:
|
||||
break
|
||||
@@ -878,6 +1087,13 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// are suspended.
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// A suspended database makes everything to avoid acquiring a lock on the
|
||||
/// database. All database operations may throw a ``DatabaseError`` of code
|
||||
/// `SQLITE_INTERRUPT` or `SQLITE_ABORT`, except reads in WAL mode.
|
||||
///
|
||||
/// See <doc:DatabaseSharing#How-to-limit-the-0xDEAD10CC-exception> for
|
||||
/// more information.
|
||||
public static let suspendNotification = Notification.Name("GRDB.Database.Suspend")
|
||||
|
||||
/// When this notification is posted, databases which were opened with the
|
||||
@@ -1039,7 +1255,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.writeWithoutTransaction do {
|
||||
/// try dbQueue.writeWithoutTransaction do { db in
|
||||
/// try db.inTransaction {
|
||||
/// try db.execute(sql: "INSERT ...")
|
||||
/// return .commit
|
||||
@@ -1118,7 +1334,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
if let firstError = firstError {
|
||||
if let firstError {
|
||||
throw firstError
|
||||
}
|
||||
}
|
||||
@@ -1267,7 +1483,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
if let firstError = firstError {
|
||||
if let firstError {
|
||||
throw firstError
|
||||
}
|
||||
}
|
||||
@@ -1359,7 +1575,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// Frees as much memory as possible.
|
||||
public func releaseMemory() {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
sqlite3_db_release_memory(sqliteConnection)
|
||||
if let sqliteConnection {
|
||||
sqlite3_db_release_memory(sqliteConnection)
|
||||
}
|
||||
schemaCache.clear()
|
||||
internalStatementCache.clear()
|
||||
publicStatementCache.clear()
|
||||
@@ -1515,6 +1733,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `Database` must be used from a
|
||||
// serialized database access dispatch queue (see `SerializedDatabase`).
|
||||
@available(*, unavailable)
|
||||
extension Database: Sendable { }
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
extension Database {
|
||||
|
||||
@@ -1640,7 +1863,7 @@ extension Database {
|
||||
/// The available checkpoint modes.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/wal_checkpoint_v2.html>
|
||||
public enum CheckpointMode: CInt {
|
||||
public enum CheckpointMode: CInt, Sendable {
|
||||
/// The `SQLITE_CHECKPOINT_PASSIVE` mode.
|
||||
case passive = 0
|
||||
|
||||
@@ -1659,7 +1882,7 @@ extension Database {
|
||||
/// Related SQLite documentation:
|
||||
/// - <https://www.sqlite.org/datatype3.html#collating_sequences>
|
||||
/// - <https://www.sqlite.org/datatype3.html#collation>
|
||||
public struct CollationName: RawRepresentable, Hashable {
|
||||
public struct CollationName: RawRepresentable, Hashable, Sendable {
|
||||
public let rawValue: String
|
||||
|
||||
/// Creates a collation name.
|
||||
@@ -1679,27 +1902,24 @@ extension Database {
|
||||
|
||||
/// An SQL column type.
|
||||
///
|
||||
/// You use column types when you modify the database schema. For example,
|
||||
/// the code below create a `player` table with a `name` column whose type
|
||||
/// is ``text`` (`TEXT` in SQL):
|
||||
/// You use column types when you modify the database schema. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE TABLE player(
|
||||
/// // id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
/// // name TEXT
|
||||
/// // id INTEGER PRIMARY KEY,
|
||||
/// // name TEXT,
|
||||
/// // creationDate DATETIME,
|
||||
/// // )
|
||||
/// try db.create(table: "player") { t in
|
||||
/// t.autoIncrementedPrimaryKey("id")
|
||||
/// t.primaryKey("id", .integer)
|
||||
/// t.column("name", .text)
|
||||
/// t.column("creationDate", .datetime)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// A `ColumnType` is an element of the SQL language, as is `TEXT` in the
|
||||
/// example above. The type comes with many built-in constants for
|
||||
/// frequently used types: ``text``, ``integer``, etc.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/datatype3.html>
|
||||
public struct ColumnType: RawRepresentable, Hashable {
|
||||
/// For more information, see
|
||||
/// [Datatypes In SQLite](https://www.sqlite.org/datatype3.html).
|
||||
public struct ColumnType: RawRepresentable, Hashable, Sendable {
|
||||
/// The SQL for the column type (`"TEXT"`, `"BLOB"`, etc.)
|
||||
public let rawValue: String
|
||||
|
||||
@@ -1708,41 +1928,49 @@ extension Database {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
/// The `TEXT` SQL column type.
|
||||
/// The `TEXT` column type.
|
||||
public static let text = ColumnType(rawValue: "TEXT")
|
||||
|
||||
/// The `INTEGER` SQL column type.
|
||||
/// The `TEXT` column type, suitable for JSON columns.
|
||||
///
|
||||
/// SQLite JSON functions and operators are
|
||||
/// [documented](https://www.sqlite.org/json1.html#interface_overview)
|
||||
/// to throw errors if any of their arguments are binary blobs.
|
||||
/// That's the reason why it is recommended to store JSON as text.
|
||||
public static let jsonText = ColumnType(rawValue: "TEXT")
|
||||
|
||||
/// The `INTEGER` column type.
|
||||
public static let integer = ColumnType(rawValue: "INTEGER")
|
||||
|
||||
/// The `DOUBLE` SQL column type.
|
||||
/// The `DOUBLE` column type.
|
||||
public static let double = ColumnType(rawValue: "DOUBLE")
|
||||
|
||||
/// The `REAL` SQL column type.
|
||||
/// The `REAL` column type.
|
||||
public static let real = ColumnType(rawValue: "REAL")
|
||||
|
||||
/// The `NUMERIC` SQL column type.
|
||||
/// The `NUMERIC` column type.
|
||||
public static let numeric = ColumnType(rawValue: "NUMERIC")
|
||||
|
||||
/// The `BOOLEAN` SQL column type.
|
||||
/// The `BOOLEAN` column type.
|
||||
public static let boolean = ColumnType(rawValue: "BOOLEAN")
|
||||
|
||||
/// The `BLOB` SQL column type.
|
||||
/// The `BLOB` column type.
|
||||
public static let blob = ColumnType(rawValue: "BLOB")
|
||||
|
||||
/// The `DATE` SQL column type.
|
||||
/// The `DATE` column type.
|
||||
public static let date = ColumnType(rawValue: "DATE")
|
||||
|
||||
/// The `DATETIME` SQL column type.
|
||||
/// The `DATETIME` column type.
|
||||
public static let datetime = ColumnType(rawValue: "DATETIME")
|
||||
|
||||
/// The `ANY` SQL column type.
|
||||
/// The `ANY` column type.
|
||||
public static let any = ColumnType(rawValue: "ANY")
|
||||
}
|
||||
|
||||
/// An SQLite conflict resolution.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_conflict.html>
|
||||
public enum ConflictResolution: String {
|
||||
public enum ConflictResolution: String, Sendable {
|
||||
/// The `ROLLBACK` conflict resolution.
|
||||
case rollback = "ROLLBACK"
|
||||
|
||||
@@ -1762,7 +1990,7 @@ extension Database {
|
||||
/// A foreign key action.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/foreignkeys.html>
|
||||
public enum ForeignKeyAction: String {
|
||||
public enum ForeignKeyAction: String, Sendable {
|
||||
/// The `CASCADE` foreign key action.
|
||||
case cascade = "CASCADE"
|
||||
|
||||
@@ -1779,13 +2007,39 @@ extension Database {
|
||||
/// An error log function that takes an error code and message.
|
||||
public typealias LogErrorFunction = (_ resultCode: ResultCode, _ message: String) -> Void
|
||||
|
||||
/// An SQLite storage class.
|
||||
///
|
||||
/// For more information, see
|
||||
/// [Datatypes In SQLite](https://www.sqlite.org/datatype3.html).
|
||||
public struct StorageClass: RawRepresentable, Hashable, Sendable {
|
||||
/// The SQL for the storage class (`"INTEGER"`, `"REAL"`, etc.)
|
||||
public let rawValue: String
|
||||
|
||||
/// Creates an SQL storage class.
|
||||
public init(rawValue: String) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
/// The `INTEGER` storage class.
|
||||
public static let integer = StorageClass(rawValue: "INTEGER")
|
||||
|
||||
/// The `REAL` storage class.
|
||||
public static let real = StorageClass(rawValue: "REAL")
|
||||
|
||||
/// The `TEXT` storage class.
|
||||
public static let text = StorageClass(rawValue: "TEXT")
|
||||
|
||||
/// The `BLOB` storage class.
|
||||
public static let blob = StorageClass(rawValue: "BLOB")
|
||||
}
|
||||
|
||||
/// An option for the SQLite tracing feature.
|
||||
///
|
||||
/// You use `TracingOptions` with the `Database`
|
||||
/// ``Database/trace(options:_:)`` method.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/c_trace.html>
|
||||
public struct TracingOptions: OptionSet {
|
||||
public struct TracingOptions: OptionSet, Sendable {
|
||||
/// The raw trace event code.
|
||||
public let rawValue: CInt
|
||||
|
||||
@@ -1799,13 +2053,11 @@ extension Database {
|
||||
/// Trace event code: `SQLITE_TRACE_STMT`.
|
||||
public static let statement = TracingOptions(rawValue: SQLITE_TRACE_STMT)
|
||||
|
||||
#if !os(Linux)
|
||||
/// The option that reports executed statements and the estimated
|
||||
/// duration that the statement took to run.
|
||||
///
|
||||
/// Trace event code: `SQLITE_TRACE_PROFILE`.
|
||||
public static let profile = TracingOptions(rawValue: SQLITE_TRACE_PROFILE)
|
||||
#endif
|
||||
}
|
||||
|
||||
/// A trace event.
|
||||
@@ -1816,17 +2068,11 @@ extension Database {
|
||||
|
||||
/// Information about an executed statement.
|
||||
public struct Statement: CustomStringConvertible {
|
||||
enum Impl {
|
||||
case trace_v1(String)
|
||||
case trace_v2(
|
||||
sqliteStatement: SQLiteStatement,
|
||||
unexpandedSQL: UnsafePointer<CChar>?,
|
||||
sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?,
|
||||
publicStatementArguments: Bool) // See Configuration.publicStatementArguments
|
||||
}
|
||||
var impl: Impl
|
||||
var sqliteStatement: SQLiteStatement
|
||||
var unexpandedSQL: UnsafePointer<CChar>?
|
||||
var sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<CChar>?
|
||||
var publicStatementArguments: Bool // See Configuration.publicStatementArguments
|
||||
|
||||
#if !os(Linux)
|
||||
/// The executed SQL, where bound parameters are not expanded.
|
||||
///
|
||||
/// For example:
|
||||
@@ -1834,21 +2080,12 @@ extension Database {
|
||||
/// ```sql
|
||||
/// SELECT * FROM player WHERE email = ?
|
||||
/// ```
|
||||
public var sql: String { _sql }
|
||||
#endif
|
||||
|
||||
var _sql: String {
|
||||
switch impl {
|
||||
case .trace_v1:
|
||||
// Likely a GRDB bug: this api is not supposed to be available
|
||||
fatalError("Unavailable statement SQL")
|
||||
|
||||
case let .trace_v2(sqliteStatement, unexpandedSQL, _, _):
|
||||
if let unexpandedSQL = unexpandedSQL {
|
||||
return String(cString: unexpandedSQL).trimmedSQLStatement
|
||||
} else {
|
||||
return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
|
||||
}
|
||||
public var sql: String {
|
||||
if let unexpandedSQL {
|
||||
let sql = String(cString: unexpandedSQL)
|
||||
return sql.hasPrefix("--") ? sql : sql.trimmedSQLStatement
|
||||
} else {
|
||||
return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1864,30 +2101,22 @@ extension Database {
|
||||
/// information from leaking in unexpected locations, so use this
|
||||
/// property with care.
|
||||
public var expandedSQL: String {
|
||||
switch impl {
|
||||
case let .trace_v1(expandedSQL):
|
||||
return expandedSQL
|
||||
|
||||
case let .trace_v2(sqliteStatement, _, sqlite3_expanded_sql, _):
|
||||
guard let cString = sqlite3_expanded_sql(sqliteStatement) else {
|
||||
return ""
|
||||
}
|
||||
defer { sqlite3_free(cString) }
|
||||
return String(cString: cString).trimmedSQLStatement
|
||||
if let unexpandedSQL {
|
||||
let sql = String(cString: unexpandedSQL)
|
||||
if sql.hasPrefix("--") { return sql }
|
||||
}
|
||||
guard let cString = sqlite3_expanded_sql(sqliteStatement) else {
|
||||
return ""
|
||||
}
|
||||
defer { sqlite3_free(cString) }
|
||||
return String(cString: cString).trimmedSQLStatement
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
switch impl {
|
||||
case let .trace_v1(expandedSQL):
|
||||
if publicStatementArguments {
|
||||
return expandedSQL
|
||||
|
||||
case let .trace_v2(_, _, _, publicStatementArguments):
|
||||
if publicStatementArguments {
|
||||
return expandedSQL
|
||||
} else {
|
||||
return _sql
|
||||
}
|
||||
} else {
|
||||
return sql
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1948,7 +2177,7 @@ extension Database {
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
|
||||
@frozen
|
||||
public enum TransactionCompletion {
|
||||
public enum TransactionCompletion: Sendable {
|
||||
case commit
|
||||
case rollback
|
||||
}
|
||||
@@ -1956,7 +2185,7 @@ extension Database {
|
||||
/// A transaction kind.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
|
||||
public enum TransactionKind: String {
|
||||
public enum TransactionKind: String, Sendable {
|
||||
/// The `DEFERRED` transaction kind.
|
||||
case deferred = "DEFERRED"
|
||||
|
||||
@@ -1968,6 +2197,10 @@ extension Database {
|
||||
}
|
||||
|
||||
/// An SQLite threading mode. See <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`.
|
||||
enum ThreadingMode {
|
||||
case `default`
|
||||
case multiThread
|
||||
@@ -1985,3 +2218,13 @@ extension Database {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: a trace event contains transient
|
||||
// information.
|
||||
@available(*, unavailable)
|
||||
extension Database.TraceEvent: Sendable { }
|
||||
|
||||
// Explicit non-conformance to Sendable: a trace event contains transient
|
||||
// information.
|
||||
@available(*, unavailable)
|
||||
extension Database.TraceEvent.Statement: Sendable { }
|
||||
@@ -1,7 +1,7 @@
|
||||
/// Describe the progress of a database backup.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/backup_finish.html>
|
||||
public struct DatabaseBackupProgress {
|
||||
public struct DatabaseBackupProgress: Sendable {
|
||||
/// The number of pages still to be backed up.
|
||||
///
|
||||
/// It is the result of the `sqlite3_backup_remaining` function.
|
||||
|
||||
@@ -198,7 +198,7 @@ extension ResultCode: CustomStringConvertible {
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
if let errorString = errorString {
|
||||
if let errorString {
|
||||
return "\(rawValue) (\(errorString))"
|
||||
} else {
|
||||
return "\(rawValue)"
|
||||
@@ -216,10 +216,12 @@ extension ResultCode: Sendable { }
|
||||
/// do {
|
||||
/// try player.insert(db)
|
||||
/// } catch let error as DatabaseError {
|
||||
/// switch error.resultCode {
|
||||
/// case ResultCode.SQLITE_CONSTRAINT_FOREIGNKEY:
|
||||
/// print(error) // prints debugging information
|
||||
///
|
||||
/// switch error {
|
||||
/// case DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY:
|
||||
/// // foreign key constraint error
|
||||
/// case ResultCode.SQLITE_CONSTRAINT:
|
||||
/// case DatabaseError.SQLITE_CONSTRAINT:
|
||||
/// // any other constraint error
|
||||
/// default:
|
||||
/// // any other database error
|
||||
@@ -394,6 +396,10 @@ public struct DatabaseError: Error {
|
||||
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 {
|
||||
@@ -543,13 +549,13 @@ extension DatabaseError: CustomStringConvertible {
|
||||
/// 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
|
||||
@@ -571,13 +577,13 @@ extension DatabaseError: CustomStringConvertible {
|
||||
/// 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
|
||||
@@ -598,7 +604,7 @@ extension DatabaseError: CustomNSError {
|
||||
/// 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
|
||||
|
||||
@@ -30,9 +30,9 @@ public final class DatabaseFunction: Hashable {
|
||||
/// 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: CInt { (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
|
||||
private var eTextRep: CInt { (SQLITE_UTF8 | (isPure ? SQLITE_DETERMINISTIC : 0)) }
|
||||
|
||||
/// Creates an SQL function.
|
||||
///
|
||||
@@ -76,7 +76,7 @@ public final class DatabaseFunction: Hashable {
|
||||
function: @escaping ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
|
||||
{
|
||||
self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
|
||||
self.pure = pure
|
||||
self.isPure = pure
|
||||
self.kind = .function{ (argc, argv) in
|
||||
let arguments = (0..<Int(argc)).map { index in
|
||||
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
|
||||
@@ -140,10 +140,11 @@ public final class DatabaseFunction: Hashable {
|
||||
aggregate: Aggregate.Type)
|
||||
{
|
||||
self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
|
||||
self.pure = pure
|
||||
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.
|
||||
///
|
||||
/// You can use a `DatabaseFunction` as a regular Swift function. It returns
|
||||
@@ -171,13 +172,23 @@ public final class DatabaseFunction: Hashable {
|
||||
/// ```
|
||||
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) {
|
||||
|
||||
+154
-144
@@ -4,65 +4,6 @@ import Foundation
|
||||
import UIKit
|
||||
#endif
|
||||
|
||||
/// A database connection that allows concurrent accesses to an SQLite database.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// Unless ``Configuration/readonly``, a `DatabasePool` opens an SQLite database
|
||||
/// in the [WAL mode](https://sqlite.org/wal.html).
|
||||
///
|
||||
/// It creates one writer SQLite connection, and a pool of up to
|
||||
/// ``Configuration/maximumReaderCount`` read-only SQLite connections. All
|
||||
/// write accesses are executed in a serial **writer dispatch queue**. All
|
||||
/// read accesses are executed in **reader dispatch queues** (one per read-only
|
||||
/// SQLite connection). SQLite connections are closed when the `DatabasePool`
|
||||
/// is deallocated.
|
||||
///
|
||||
/// See <doc:Concurrency> for more information about concurrent
|
||||
/// database accesses.
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// ```swift
|
||||
/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
///
|
||||
/// let playerCount = try dbPool.read { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// let newPlayerCount = try dbPool.write { db -> Int in
|
||||
/// try Player(name: "Arthur").insert(db)
|
||||
/// return try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// `DatabasePool` inherits most of its database access methods from the
|
||||
/// ``DatabaseReader`` and ``DatabaseWriter`` protocols. It defines a few
|
||||
/// specific database access methods as well.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a DatabasePool
|
||||
///
|
||||
/// - ``init(path:configuration:)``
|
||||
///
|
||||
/// ### Creating a DatabaseSnapshot
|
||||
///
|
||||
/// - ``makeSnapshot()``
|
||||
///
|
||||
/// ### Accessing the Database
|
||||
///
|
||||
/// See ``DatabaseReader`` and ``DatabaseWriter`` for more database
|
||||
/// access methods.
|
||||
///
|
||||
/// - ``asyncConcurrentRead(_:)``
|
||||
/// - ``writeInTransaction(_:_:)``
|
||||
///
|
||||
/// ### Managing SQLite Connections
|
||||
///
|
||||
/// - ``invalidateReadOnlyConnections()``
|
||||
/// - ``releaseMemory()``
|
||||
/// - ``releaseMemoryEventually()``
|
||||
public final class DatabasePool {
|
||||
private let writer: SerializedDatabase
|
||||
|
||||
@@ -72,6 +13,9 @@ public final class DatabasePool {
|
||||
|
||||
@LockedBox var databaseSnapshotCount = 0
|
||||
|
||||
/// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers.
|
||||
private var suspensionObservers: [NSObjectProtocol] = []
|
||||
|
||||
// MARK: - Database Information
|
||||
|
||||
public var configuration: Configuration {
|
||||
@@ -131,31 +75,12 @@ public final class DatabasePool {
|
||||
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()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -172,10 +97,13 @@ public final class DatabasePool {
|
||||
}
|
||||
|
||||
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.
|
||||
@@ -185,7 +113,7 @@ public final class DatabasePool {
|
||||
|
||||
/// 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
|
||||
@@ -194,7 +122,7 @@ public final class DatabasePool {
|
||||
// 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.
|
||||
@@ -220,19 +148,22 @@ public final class DatabasePool {
|
||||
}
|
||||
}
|
||||
|
||||
// @unchecked because of databaseSnapshotCount and readerPool
|
||||
// @unchecked because of databaseSnapshotCount, readerPool and suspensionObservers
|
||||
extension DatabasePool: @unchecked Sendable { }
|
||||
|
||||
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.
|
||||
@@ -240,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)
|
||||
@@ -377,29 +324,21 @@ 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
|
||||
@@ -420,7 +359,7 @@ extension DatabasePool: DatabaseReader {
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")))
|
||||
value(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -431,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.
|
||||
@@ -464,7 +403,7 @@ extension DatabasePool: DatabaseReader {
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")))
|
||||
value(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -474,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 {
|
||||
@@ -493,6 +431,8 @@ 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 else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
@@ -589,7 +529,7 @@ extension DatabasePool: DatabaseReader {
|
||||
reader.async { db in
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader()
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
do {
|
||||
// https://www.sqlite.org/isolation.html
|
||||
@@ -666,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()
|
||||
}
|
||||
@@ -698,11 +642,55 @@ extension DatabasePool: DatabaseReader {
|
||||
return readers.first { $0.onValidQueue }
|
||||
}
|
||||
|
||||
// MARK: - WAL Snapshot Transactions
|
||||
|
||||
// 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)
|
||||
})
|
||||
}
|
||||
|
||||
/// 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)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
@@ -733,7 +721,7 @@ 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)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
@@ -830,10 +818,8 @@ extension DatabasePool {
|
||||
|
||||
// MARK: - Snapshots
|
||||
|
||||
/// Creates a database snapshot.
|
||||
///
|
||||
/// The returned snapshot sees an unchanging database content, as it existed
|
||||
/// at the moment it was created.
|
||||
/// Creates a database snapshot that serializes accesses to an unchanging
|
||||
/// database content, as it exists at the moment the snapshot is created.
|
||||
///
|
||||
/// It is a programmer error to create a snapshot from the writer dispatch
|
||||
/// queue when a transaction is opened:
|
||||
@@ -851,9 +837,10 @@ extension DatabasePool {
|
||||
/// the transaction:
|
||||
///
|
||||
/// ```swift
|
||||
/// let snapshot = try dbPool.makeSnapshot() // OK
|
||||
///
|
||||
/// try dbPool.writeWithoutTransaction { db in
|
||||
/// // OK
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
/// let snapshot = try dbPool.makeSnapshot() // OK
|
||||
///
|
||||
/// try db.inTransaction {
|
||||
/// try Player.deleteAll()
|
||||
@@ -861,8 +848,10 @@ extension DatabasePool {
|
||||
/// }
|
||||
///
|
||||
/// // OK
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
/// let snapshot = try dbPool.makeSnapshot() // OK
|
||||
/// }
|
||||
///
|
||||
/// let snapshot = try dbPool.makeSnapshot() // OK
|
||||
/// ```
|
||||
public func makeSnapshot() throws -> DatabaseSnapshot {
|
||||
// Sanity check
|
||||
@@ -876,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
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
#if canImport(Combine)
|
||||
/// A namespace for database Combine publishers.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public enum DatabasePublishers { }
|
||||
#endif
|
||||
+193
-99
@@ -4,63 +4,18 @@ import Foundation
|
||||
import UIKit
|
||||
#endif
|
||||
|
||||
/// A database connection that serializes accesses to an SQLite database.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// A `DatabaseQueue` creates one single SQLite connection. All database
|
||||
/// accesses are executed in a serial **writer dispatch queue**. The SQLite
|
||||
/// connection is closed when the `DatabaseQueue` is deallocated.
|
||||
///
|
||||
/// ```swift
|
||||
/// let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
|
||||
///
|
||||
/// let playerCount = try dbQueue.read { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// let newPlayerCount = try dbQueue.write { db -> Int in
|
||||
/// try Player(name: "Arthur").insert(db)
|
||||
/// return try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// `DatabaseQueue` inherits most of its database access methods from the
|
||||
/// ``DatabaseReader`` and ``DatabaseWriter`` protocols. It defines a few
|
||||
/// specific database access methods as well.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a DatabaseQueue
|
||||
///
|
||||
/// - ``init(configuration:)``
|
||||
/// - ``init(path:configuration:)``
|
||||
///
|
||||
/// ### Accessing the Database
|
||||
///
|
||||
/// See ``DatabaseReader`` and ``DatabaseWriter`` for more database
|
||||
/// access methods.
|
||||
///
|
||||
/// - ``inDatabase(_:)``
|
||||
/// - ``inTransaction(_:_:)``
|
||||
///
|
||||
/// ### Managing the SQLite Connection
|
||||
///
|
||||
/// - ``releaseMemory()``
|
||||
public final class DatabaseQueue {
|
||||
private let writer: SerializedDatabase
|
||||
|
||||
/// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers.
|
||||
private var suspensionObservers: [NSObjectProtocol] = []
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
public var configuration: Configuration {
|
||||
writer.configuration
|
||||
}
|
||||
|
||||
/// The path to the database file.
|
||||
///
|
||||
/// The path is `:memory:` for in-memory databases.
|
||||
public var path: String {
|
||||
writer.path
|
||||
}
|
||||
@@ -83,11 +38,27 @@ public final class DatabaseQueue {
|
||||
/// - configuration: A configuration.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public init(path: String, configuration: Configuration = Configuration()) throws {
|
||||
// DatabaseQueue can't perform parallel reads
|
||||
var configuration = configuration
|
||||
configuration.maximumReaderCount = 1
|
||||
|
||||
writer = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
defaultLabel: "GRDB.DatabaseQueue")
|
||||
|
||||
// Set up journal mode unless readonly
|
||||
if !configuration.readonly {
|
||||
switch configuration.journalMode {
|
||||
case .default:
|
||||
break
|
||||
case .wal:
|
||||
try writer.sync {
|
||||
try $0.setUpWALMode()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setupSuspension()
|
||||
|
||||
// Be a nice iOS citizen, and don't consume too much memory
|
||||
@@ -101,26 +72,60 @@ public final class DatabaseQueue {
|
||||
|
||||
/// Opens an in-memory SQLite database.
|
||||
///
|
||||
/// The database memory is released when the database queue
|
||||
/// gets deallocated.
|
||||
/// To create an independent in-memory database, don't pass any name. The
|
||||
/// database memory is released when the database queue is deallocated:
|
||||
///
|
||||
/// ```swift
|
||||
/// // An independent in-memory database
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// ```
|
||||
///
|
||||
/// When you need to open several connections to the same in-memory
|
||||
/// database, give it a name:
|
||||
///
|
||||
/// ```swift
|
||||
/// // A shared in-memory database
|
||||
/// let dbQueue = try DatabaseQueue(named: "myDatabase")
|
||||
/// ```
|
||||
///
|
||||
/// In this case, the database is automatically deleted and memory is
|
||||
/// reclaimed when the last connection to the database of the given
|
||||
/// name closes.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/inmemorydb.html>
|
||||
///
|
||||
/// - parameter name: When nil, an independent in-memory database opens.
|
||||
/// Otherwise, the shared in-memory database of the given name opens.
|
||||
/// - parameter configuration: A configuration.
|
||||
public init(configuration: Configuration = Configuration()) throws {
|
||||
public init(named name: String? = nil, configuration: Configuration = Configuration()) throws {
|
||||
let path: String
|
||||
if let name {
|
||||
path = "file:\(name)?mode=memory&cache=shared"
|
||||
} else {
|
||||
path = ":memory:"
|
||||
}
|
||||
|
||||
writer = try SerializedDatabase(
|
||||
path: ":memory:",
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
defaultLabel: "GRDB.DatabaseQueue")
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// @unchecked because of suspensionObservers
|
||||
extension DatabaseQueue: @unchecked Sendable { }
|
||||
|
||||
extension DatabaseQueue {
|
||||
|
||||
// MARK: - Memory management
|
||||
@@ -202,29 +207,21 @@ extension DatabaseQueue: DatabaseReader {
|
||||
private func setupSuspension() {
|
||||
if configuration.observesSuspensionNotifications {
|
||||
let center = NotificationCenter.default
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabaseQueue.suspend(_:)),
|
||||
name: Database.suspendNotification,
|
||||
object: nil)
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabaseQueue.resume(_:)),
|
||||
name: Database.resumeNotification,
|
||||
object: nil)
|
||||
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
|
||||
@@ -238,21 +235,22 @@ extension DatabaseQueue: DatabaseReader {
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
writer.async { db in
|
||||
do {
|
||||
// The transaction guarantees snapshot isolation against eventual
|
||||
// external connection.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.beginReadOnly()
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
return
|
||||
defer {
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.commit()
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
|
||||
value(.success(db))
|
||||
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.endReadOnly()
|
||||
try? db.commit()
|
||||
do {
|
||||
// Enter read-only mode before starting a transaction, so that the
|
||||
// transaction commit does not trigger database observation.
|
||||
// See <https://github.com/groue/GRDB.swift/pull/1213>.
|
||||
try db.beginReadOnly()
|
||||
try db.beginTransaction(.deferred)
|
||||
value(.success(db))
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,20 +284,23 @@ extension DatabaseQueue: DatabaseReader {
|
||||
writer.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
|
||||
|
||||
do {
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.beginReadOnly()
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
return
|
||||
|
||||
defer {
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.commit()
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
|
||||
value(.success(db))
|
||||
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.endReadOnly()
|
||||
try? db.commit()
|
||||
do {
|
||||
// Enter read-only mode before starting a transaction, so that the
|
||||
// transaction commit does not trigger database observation.
|
||||
// See <https://github.com/groue/GRDB.swift/pull/1213>.
|
||||
try db.beginReadOnly()
|
||||
try db.beginTransaction(.deferred)
|
||||
value(.success(db))
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,7 +308,7 @@ extension DatabaseQueue: DatabaseReader {
|
||||
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
@@ -428,3 +429,96 @@ extension DatabaseQueue: DatabaseWriter {
|
||||
writer.async(updates)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Temp Copy
|
||||
|
||||
extension DatabaseQueue {
|
||||
/// Returns a connection to an in-memory copy of the database at `path`.
|
||||
///
|
||||
/// Changes performed on the returned connection do not impact the
|
||||
/// original database at `path`.
|
||||
///
|
||||
/// The database memory is released when the returned connection
|
||||
/// is deallocated.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let path = "/path/to/database.sqlite"
|
||||
/// let dbQueue = try DatabaseQueue.inMemoryCopy(fromPath: path)
|
||||
/// ```
|
||||
public static func inMemoryCopy(
|
||||
fromPath path: String,
|
||||
configuration: Configuration = Configuration())
|
||||
throws -> DatabaseQueue
|
||||
{
|
||||
var sourceConfig = configuration
|
||||
sourceConfig.readonly = true
|
||||
let source = try DatabaseQueue(path: path, configuration: sourceConfig)
|
||||
|
||||
var copyConfig = configuration
|
||||
copyConfig.readonly = false
|
||||
let result = try DatabaseQueue(configuration: copyConfig)
|
||||
|
||||
try source.backup(to: result)
|
||||
|
||||
if configuration.readonly {
|
||||
// Result was not opened read-only so that we could perform the
|
||||
// copy. And SQLITE_OPEN_READONLY has no effect on in-memory
|
||||
// databases anyway.
|
||||
//
|
||||
// So let's simulate read-only with PRAGMA query_only.
|
||||
try result.inDatabase { db in
|
||||
try db.beginReadOnly()
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/// Returns a connection to a private, temporary, on-disk copy of the
|
||||
/// database at `path`.
|
||||
///
|
||||
/// Changes performed on the returned connection do not impact the
|
||||
/// original database at `path`.
|
||||
///
|
||||
/// The on-disk copy will be automatically deleted from disk as soon as
|
||||
/// the returned connection is closed or deallocated.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let path = "/path/to/database.sqlite"
|
||||
/// let dbQueue = try DatabaseQueue.temporaryCopy(fromPath: path)
|
||||
/// ```
|
||||
public static func temporaryCopy(
|
||||
fromPath path: String,
|
||||
configuration: Configuration = Configuration())
|
||||
throws -> DatabaseQueue
|
||||
{
|
||||
var sourceConfig = configuration
|
||||
sourceConfig.readonly = true
|
||||
let source = try DatabaseQueue(path: path, configuration: sourceConfig)
|
||||
|
||||
// <https://www.sqlite.org/c3ref/open.html>
|
||||
// > If the filename is an empty string, then a private, temporary
|
||||
// > on-disk database will be created. This private database will be
|
||||
// > automatically deleted as soon as the database connection
|
||||
// > is closed.
|
||||
var copyConfig = configuration
|
||||
copyConfig.readonly = false
|
||||
let result = try DatabaseQueue(path: "", configuration: copyConfig)
|
||||
|
||||
try source.backup(to: result)
|
||||
|
||||
if configuration.readonly {
|
||||
// Result was not opened read-only so that we could perform the
|
||||
// copy. So let's simulate read-only with PRAGMA query_only.
|
||||
try result.inDatabase { db in
|
||||
try db.beginReadOnly()
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
}
|
||||
+112
-25
@@ -5,9 +5,8 @@ import Dispatch
|
||||
|
||||
/// A type that reads from an SQLite database.
|
||||
///
|
||||
/// Do not declare new conformances to `DatabaseReader`. Only the
|
||||
/// ``DatabaseQueue``, ``DatabasePool``, and ``DatabaseSnapshot`` types are
|
||||
/// valid conforming types.
|
||||
/// Do not declare new conformances to `DatabaseReader`. Only the built-in
|
||||
/// conforming types are valid.
|
||||
///
|
||||
/// The protocol comes with isolation guarantees that describe the behavior of
|
||||
/// conforming types in a multithreaded application. See <doc:Concurrency> for
|
||||
@@ -18,6 +17,7 @@ import Dispatch
|
||||
/// ### Database Information
|
||||
///
|
||||
/// - ``configuration``
|
||||
/// - ``path``
|
||||
///
|
||||
/// ### Reading from the Database
|
||||
///
|
||||
@@ -33,6 +33,16 @@ import Dispatch
|
||||
/// - ``unsafeReentrantRead(_:)``
|
||||
/// - ``asyncUnsafeRead(_:)``
|
||||
///
|
||||
/// ### Printing Database Content
|
||||
///
|
||||
/// - ``dumpContent(format:to:)``
|
||||
/// - ``dumpRequest(_:format:to:)``
|
||||
/// - ``dumpSchema(to:)``
|
||||
/// - ``dumpSQL(_:format:to:)``
|
||||
/// - ``dumpTables(_:format:tableHeader:stableOrder:to:)``
|
||||
/// - ``DumpFormat``
|
||||
/// - ``DumpTableHeaderOptions``
|
||||
///
|
||||
/// ### Other Database Operations
|
||||
///
|
||||
/// - ``backup(to:pagesPerStep:progress:)``
|
||||
@@ -47,6 +57,12 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// The database configuration.
|
||||
var configuration: Configuration { get }
|
||||
|
||||
/// The path to the database file.
|
||||
///
|
||||
/// In-memory databases also have a path:
|
||||
/// see [In-Memory Databases](https://www.sqlite.org/inmemorydb.html).
|
||||
var path: String { get }
|
||||
|
||||
/// Closes the database connection.
|
||||
///
|
||||
/// - note: You do not have to call this method, and you should not call
|
||||
@@ -206,7 +222,9 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// This method is "unsafe" because the database reader does nothing more
|
||||
/// than providing a database connection. When you use this method, you
|
||||
/// become responsible for the thread-safety of your application, and
|
||||
/// responsible for database accesses performed by other processes.
|
||||
/// responsible for database accesses performed by other processes. See
|
||||
/// <doc:Concurrency#Safe-and-Unsafe-Database-Accesses> for
|
||||
/// more information.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -224,8 +242,8 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// access method. Doing so raises a "Database methods are not reentrant"
|
||||
/// fatal error at runtime.
|
||||
///
|
||||
/// - warning: Database operations are not wrapped in a transaction. They
|
||||
/// can see changes performed by concurrent writes or writes performed by
|
||||
/// - warning: Database operations may not be wrapped in a transaction. They
|
||||
/// may see changes performed by concurrent writes or writes performed by
|
||||
/// other processes: two identical requests performed by the `value`
|
||||
/// closure may not return the same value.
|
||||
/// - warning: Attempts to write in the database may succeed.
|
||||
@@ -241,7 +259,9 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// This method is "unsafe" because the database reader does nothing more
|
||||
/// than providing a database connection. When you use this method, you
|
||||
/// become responsible for the thread-safety of your application, and
|
||||
/// responsible for database accesses performed by other processes.
|
||||
/// responsible for database accesses performed by other processes. See
|
||||
/// <doc:Concurrency#Safe-and-Unsafe-Database-Accesses> for
|
||||
/// more information.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -256,8 +276,8 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - warning: Database operations are not wrapped in a transaction. They
|
||||
/// can see changes performed by concurrent writes or writes performed by
|
||||
/// - warning: Database operations may not be wrapped in a transaction. They
|
||||
/// may see changes performed by concurrent writes or writes performed by
|
||||
/// other processes: two identical requests performed by the `value`
|
||||
/// closure may not return the same value.
|
||||
/// - warning: Attempts to write in the database may succeed.
|
||||
@@ -273,10 +293,16 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// This method is "unsafe" because the database reader does nothing more
|
||||
/// than providing a database connection. When you use this method, you
|
||||
/// become responsible for the thread-safety of your application, and
|
||||
/// responsible for database accesses performed by other processes.
|
||||
/// responsible for database accesses performed by other processes. See
|
||||
/// <doc:Concurrency#Safe-and-Unsafe-Database-Accesses> for
|
||||
/// more information.
|
||||
///
|
||||
/// This method can be called from other database access methods. Reentrant
|
||||
/// database accesses are discouraged, though, because they muddle
|
||||
/// This method can be called from other database access methods. If called
|
||||
/// from the dispatch queue of a current database access (read or write),
|
||||
/// the `Database` argument to `value` is the same as the current
|
||||
/// database access.
|
||||
///
|
||||
/// Reentrant database accesses are discouraged because they muddle
|
||||
/// transaction boundaries
|
||||
/// (see <doc:Concurrency#Rule-2:-Mind-your-transactions> for
|
||||
/// more information).
|
||||
@@ -293,8 +319,8 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// of the closure. Do not store or return the database connection for
|
||||
/// later use.
|
||||
///
|
||||
/// - warning: Database operations are not wrapped in a transaction. They
|
||||
/// can see changes performed by concurrent writes or writes performed by
|
||||
/// - warning: Database operations may not be wrapped in a transaction. They
|
||||
/// may see changes performed by concurrent writes or writes performed by
|
||||
/// other processes: two identical requests performed by the `value`
|
||||
/// closure may not return the same value.
|
||||
/// - warning: Attempts to write in the database may succeed.
|
||||
@@ -316,7 +342,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// - returns: A DatabaseCancellable that can stop the observation.
|
||||
func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
}
|
||||
@@ -432,7 +458,7 @@ extension DatabaseReader {
|
||||
/// - parameter value: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
|
||||
/// would happen while establishing the database access.
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func read<T>(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
asyncRead { result in
|
||||
@@ -453,7 +479,9 @@ extension DatabaseReader {
|
||||
/// This method is "unsafe" because the database reader does nothing more
|
||||
/// than providing a database connection. When you use this method, you
|
||||
/// become responsible for the thread-safety of your application, and
|
||||
/// responsible for database accesses performed by other processes.
|
||||
/// responsible for database accesses performed by other processes. See
|
||||
/// <doc:Concurrency#Safe-and-Unsafe-Database-Accesses> for
|
||||
/// more information.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -467,8 +495,8 @@ extension DatabaseReader {
|
||||
/// of the closure. Do not store or return the database connection for
|
||||
/// later use.
|
||||
///
|
||||
/// - warning: Database operations are not wrapped in a transaction. They
|
||||
/// can see changes performed by concurrent writes or writes performed by
|
||||
/// - warning: Database operations may not be wrapped in a transaction. They
|
||||
/// may see changes performed by concurrent writes or writes performed by
|
||||
/// other processes: two identical requests performed by the `value`
|
||||
/// closure may not return the same value.
|
||||
/// - warning: Attempts to write in the database may succeed.
|
||||
@@ -476,7 +504,7 @@ extension DatabaseReader {
|
||||
/// - parameter value: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
|
||||
/// would happen while establishing the database access.
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func unsafeRead<T>(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
asyncUnsafeRead { result in
|
||||
@@ -521,7 +549,7 @@ extension DatabaseReader {
|
||||
///
|
||||
/// - parameter scheduler: A Combine Scheduler.
|
||||
/// - parameter value: A closure which accesses the database.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func readPublisher<Output>(
|
||||
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
|
||||
value: @escaping (Database) throws -> Output)
|
||||
@@ -539,7 +567,7 @@ extension DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
extension DatabasePublishers {
|
||||
/// A publisher that reads from the database.
|
||||
///
|
||||
@@ -558,7 +586,7 @@ extension DatabasePublishers {
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
extension Publisher where Failure == Error {
|
||||
fileprivate func eraseToReadPublisher() -> DatabasePublishers.Read<Output> {
|
||||
.init(upstream: eraseToAnyPublisher())
|
||||
@@ -573,7 +601,7 @@ extension DatabaseReader {
|
||||
/// initial value.
|
||||
func _addReadOnly<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
@@ -633,6 +661,10 @@ extension AnyDatabaseReader: DatabaseReader {
|
||||
base.configuration
|
||||
}
|
||||
|
||||
public var path: String {
|
||||
base.path
|
||||
}
|
||||
|
||||
public func close() throws {
|
||||
try base.close()
|
||||
}
|
||||
@@ -665,7 +697,7 @@ extension AnyDatabaseReader: DatabaseReader {
|
||||
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
@@ -675,3 +707,58 @@ extension AnyDatabaseReader: DatabaseReader {
|
||||
onChange: onChange)
|
||||
}
|
||||
}
|
||||
|
||||
/// A type that sees an unchanging database content.
|
||||
///
|
||||
/// Do not declare new conformances to `DatabaseSnapshotReader`. Only the
|
||||
/// built-in conforming types are valid.
|
||||
///
|
||||
/// The protocol comes with the same features and guarantees as
|
||||
/// ``DatabaseReader``. On top of them, a `DatabaseSnapshotReader` always sees
|
||||
/// the same state of the database.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Reading from the Database
|
||||
///
|
||||
/// - ``reentrantRead(_:)``
|
||||
public protocol DatabaseSnapshotReader: DatabaseReader { }
|
||||
|
||||
extension DatabaseSnapshotReader {
|
||||
/// Executes database operations, and returns their result after they have
|
||||
/// finished executing.
|
||||
///
|
||||
/// This method can be called from other database access methods. If called
|
||||
/// from the dispatch queue of a current database access, the `Database`
|
||||
/// argument to `value` is the same as the current database access.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let count = try snapshot.reentrantRead { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The ``Database`` argument to `value` is valid only during the execution
|
||||
/// of the closure. Do not store or return the database connection for
|
||||
/// later use.
|
||||
///
|
||||
/// - parameter value: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
|
||||
/// would happen while establishing the database access.
|
||||
public func reentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
// Reentrant reads are safe in a snapshot
|
||||
try unsafeReentrantRead(value)
|
||||
}
|
||||
|
||||
// There is no such thing as an unsafe access to a snapshot.
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try read(value)
|
||||
}
|
||||
|
||||
// There is no such thing as an unsafe access to a snapshot.
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
asyncRead(value)
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,7 @@
|
||||
///
|
||||
/// - ``isModified(byEventsOfKind:)``
|
||||
/// - ``isModified(by:)``
|
||||
public struct DatabaseRegion {
|
||||
public struct DatabaseRegion: Sendable {
|
||||
private let tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
|
||||
|
||||
private init(tableRegions: [CaseInsensitiveIdentifier: TableRegion]?) {
|
||||
@@ -169,16 +169,16 @@ public struct DatabaseRegion {
|
||||
// the observed region, we optimize database observation.
|
||||
//
|
||||
// And by canonicalizing table names, we remove views, and help the
|
||||
// `isModified` methods.
|
||||
// `isModified` methods. (TODO: is this comment still accurate?
|
||||
// Isn't it about providing TransactionObserver.observes() with
|
||||
// real tables names, instead?)
|
||||
try ignoringInternalSQLiteTables().canonicalTables(db)
|
||||
}
|
||||
|
||||
/// Returns a region only made of actual tables with their canonical names.
|
||||
/// Canonical names help the `isModified` methods.
|
||||
///
|
||||
/// This method removes views (assuming no table exists with the same name
|
||||
/// as a view).
|
||||
private func canonicalTables(_ db: Database) throws -> DatabaseRegion {
|
||||
/// This method removes views.
|
||||
func canonicalTables(_ db: Database) throws -> DatabaseRegion {
|
||||
guard let tableRegions else { return .fullDatabase }
|
||||
var region = DatabaseRegion()
|
||||
for (table, tableRegion) in tableRegions {
|
||||
@@ -233,6 +233,44 @@ extension DatabaseRegion {
|
||||
}
|
||||
return tableRegion.contains(rowID: event.rowID)
|
||||
}
|
||||
|
||||
/// Returns an array of all event kinds that can impact this region.
|
||||
///
|
||||
/// - precondition: the region is canonical.
|
||||
func impactfulEventKinds(_ db: Database) throws -> [DatabaseEventKind] {
|
||||
if let tableRegions {
|
||||
return try tableRegions.flatMap { (table, tableRegion) -> [DatabaseEventKind] in
|
||||
let tableName = table.rawValue // canonical table name
|
||||
let columnNames: Set<String>
|
||||
if let columns = tableRegion.columns {
|
||||
columnNames = Set(columns.map(\.rawValue))
|
||||
} else {
|
||||
columnNames = try Set(db.columns(in: tableName).map(\.name))
|
||||
}
|
||||
|
||||
return [
|
||||
DatabaseEventKind.delete(tableName: tableName),
|
||||
DatabaseEventKind.insert(tableName: tableName),
|
||||
DatabaseEventKind.update(tableName: tableName, columnNames: columnNames),
|
||||
]
|
||||
}
|
||||
} else {
|
||||
// full database
|
||||
return try db.schemaIdentifiers().flatMap { schemaIdentifier in
|
||||
let schema = try db.schema(schemaIdentifier)
|
||||
return try schema.objects
|
||||
.filter { $0.type == .table }
|
||||
.flatMap { table in
|
||||
let columnNames = try Set(db.columns(in: table.name).map(\.name))
|
||||
return [
|
||||
DatabaseEventKind.delete(tableName: table.name),
|
||||
DatabaseEventKind.insert(tableName: table.name),
|
||||
DatabaseEventKind.update(tableName: table.name, columnNames: columnNames),
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseRegion: Equatable {
|
||||
@@ -287,8 +325,8 @@ private struct TableRegion: Equatable {
|
||||
var rowIds: Set<Int64>? // nil means "all rowids"
|
||||
|
||||
var isEmpty: Bool {
|
||||
if let columns = columns, columns.isEmpty { return true }
|
||||
if let rowIds = rowIds, rowIds.isEmpty { return true }
|
||||
if let columns, columns.isEmpty { return true }
|
||||
if let rowIds, rowIds.isEmpty { return true }
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -344,8 +382,37 @@ private struct TableRegion: Equatable {
|
||||
|
||||
/// A type that operates on a specific ``DatabaseRegion``.
|
||||
///
|
||||
/// A `DatabaseRegionConvertible` instance feeds database observation tools such
|
||||
/// as ``DatabaseRegionObservation`` and ``ValueObservation``:
|
||||
///
|
||||
/// ```swift
|
||||
/// // An observation triggered by all changes to the database
|
||||
/// DatabaseRegionObservation(tracking: .fullDatabase)
|
||||
///
|
||||
/// // An observation triggered by all changes to the 'player' table
|
||||
/// DatabaseRegionObservation(tracking: Table("player"))
|
||||
///
|
||||
/// // An observation triggered by all changes to the row
|
||||
/// // with rowid 1 in the 'player' table
|
||||
/// DatabaseRegionObservation(tracking: Player.filter(id: 1))
|
||||
///
|
||||
/// // An observation triggered by all changes to the 'score' column
|
||||
/// // of the 'player' table
|
||||
/// DatabaseRegionObservation(tracking: SQLRequest("SELECT score FROM player"))
|
||||
/// ```
|
||||
///
|
||||
/// Specifying a region from a ``FetchRequest`` does not execute the request.
|
||||
/// In the above example, `Player.filter(id: 1)` and `SELECT score FROM player`
|
||||
/// are only compiled by SQLite, so that GRDB can understand the tables, rows,
|
||||
/// and columns that constitute the database region.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a DatabaseRegion
|
||||
///
|
||||
/// - ``fullDatabase``
|
||||
/// - ``databaseRegion(_:)``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``AnyDatabaseRegionConvertible``
|
||||
|
||||
@@ -3,33 +3,6 @@ import Combine
|
||||
#endif
|
||||
import Foundation
|
||||
|
||||
/// `DatabaseRegionObservation` tracks transactions that modify a
|
||||
/// database region.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Track the player table
|
||||
/// let observation = DatabaseRegionObservation(tracking: Player.all())
|
||||
///
|
||||
/// let cancellable = try observation.start(in: dbQueue) { error in
|
||||
/// // handle error
|
||||
/// } onChange: { (db: Database) in
|
||||
/// print("A modification of the player table has just been committed.")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating DatabaseRegionObservation
|
||||
///
|
||||
/// - ``init(tracking:)-5ldbe``
|
||||
/// - ``init(tracking:)-2nqjd``
|
||||
///
|
||||
/// ### Observing Database Transactions
|
||||
///
|
||||
/// - ``publisher(in:)``
|
||||
/// - ``start(in:onError:onChange:)``
|
||||
public struct DatabaseRegionObservation {
|
||||
/// A closure that is evaluated when the observation starts, and returns
|
||||
/// the observed database region.
|
||||
@@ -155,7 +128,7 @@ extension DatabaseRegionObservation {
|
||||
}
|
||||
|
||||
#if canImport(Combine)
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
extension DatabaseRegionObservation {
|
||||
// MARK: - Publishing Impactful Transactions
|
||||
|
||||
@@ -167,7 +140,7 @@ extension DatabaseRegionObservation {
|
||||
///
|
||||
/// Do not reschedule the publisher with `receive(on:options:)` or any
|
||||
/// `Publisher` method that schedules publisher elements.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func publisher(in writer: some DatabaseWriter) -> DatabasePublishers.DatabaseRegion {
|
||||
DatabasePublishers.DatabaseRegion(self, in: writer)
|
||||
}
|
||||
@@ -188,6 +161,11 @@ private class DatabaseRegionObserver: TransactionObserver {
|
||||
region.isModified(byEventsOfKind: eventKind)
|
||||
}
|
||||
|
||||
func databaseDidChange() {
|
||||
isChanged = true
|
||||
stopObservingDatabaseChangesUntilNextTransaction()
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
if region.isModified(by: event) {
|
||||
isChanged = true
|
||||
@@ -208,7 +186,7 @@ private class DatabaseRegionObserver: TransactionObserver {
|
||||
}
|
||||
|
||||
#if canImport(Combine)
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
extension DatabasePublishers {
|
||||
/// A publisher that tracks transactions that modify a database region.
|
||||
///
|
||||
|
||||
@@ -1,25 +1,31 @@
|
||||
import Dispatch
|
||||
|
||||
/// A database connection that sees an unchanging database content, as it
|
||||
/// existed at the moment it was created.
|
||||
/// A database connection that serializes accesses to an unchanging
|
||||
/// database content, as it existed at the moment the snapshot was created.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// A `DatabaseSnapshot` creates one single SQLite connection. All database
|
||||
/// A `DatabaseSnapshot` never sees any database modification during all its
|
||||
/// lifetime. All database accesses performed from a snapshot always see the
|
||||
/// same identical database content.
|
||||
///
|
||||
/// A snapshot creates one single SQLite connection. All database
|
||||
/// accesses are executed in a serial **reader dispatch queue**. The SQLite
|
||||
/// connection is closed when the `DatabaseSnapshot` is deallocated.
|
||||
///
|
||||
/// `DatabaseSnapshot` never sees any database modification 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) for
|
||||
/// more information.
|
||||
/// A snapshot created on a [WAL](https://sqlite.org/wal.html) database doesn't
|
||||
/// prevent database modifications performed by other connections (but it won't
|
||||
/// see them). Refer to [Isolation In SQLite](https://sqlite.org/isolation.html)
|
||||
/// for more information.
|
||||
///
|
||||
/// On non-WAL databases, a snapshot prevents all database modifications as long
|
||||
/// as it exists, because of the
|
||||
/// [SHARED lock](https://www.sqlite.org/lockingv3.html) it holds.
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// You create instances of `DatabaseSnapshot` from a ``DatabasePool``, with
|
||||
/// ``DatabasePool/makeSnapshot()``. The number of snapshots is unlimited,
|
||||
/// regardless of the ``Configuration/maximumReaderCount`` configuration:
|
||||
/// You create instances of `DatabaseSnapshot` from a ``DatabasePool``,
|
||||
/// with ``DatabasePool/makeSnapshot()``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
@@ -29,8 +35,8 @@ import Dispatch
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When you want to control the database state seen by a snapshot,
|
||||
/// create the snapshot from within a write access, outside of any transaction.
|
||||
/// When you want to control the database state seen by a snapshot, create the
|
||||
/// snapshot from within a write access, outside of any transaction.
|
||||
///
|
||||
/// For example, compare the two snapshots below. The first one is guaranteed to
|
||||
/// see an empty table of players, because is is created after all players have
|
||||
@@ -46,100 +52,129 @@ import Dispatch
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// return dbPool.makeSnapshot()
|
||||
/// return try dbPool.makeSnapshot()
|
||||
/// }
|
||||
///
|
||||
/// // <- Other threads may have created some players here
|
||||
/// let snapshot2 = try dbPool.makeSnapshot()
|
||||
///
|
||||
/// // Guaranteed to be zero
|
||||
/// let count1 = try snapshot1.read(Player.fetchCount)
|
||||
/// let count1 = try snapshot1.read { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// // Could be anything
|
||||
/// let count2 = try snapshot2.read(Player.fetchCount)
|
||||
/// let count2 = try snapshot2.read { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// `DatabaseSnapshot` inherits its database access methods from the
|
||||
/// ``DatabaseReader`` protocols.
|
||||
///
|
||||
/// `DatabaseSnapshot` serializes database accesses and can't perform concurrent
|
||||
/// reads. For concurrent reads, see ``DatabaseSnapshotPool``.
|
||||
public final class DatabaseSnapshot {
|
||||
private let serializedDatabase: SerializedDatabase
|
||||
private let reader: SerializedDatabase
|
||||
|
||||
/// The database configuration
|
||||
public var configuration: Configuration {
|
||||
serializedDatabase.configuration
|
||||
reader.configuration
|
||||
}
|
||||
|
||||
init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws {
|
||||
var configuration = DatabasePool.readerConfiguration(configuration)
|
||||
configuration.allowsUnsafeTransactions = true // Snapshot keeps a long-lived transaction
|
||||
/// The path to the database file.
|
||||
public var path: String {
|
||||
reader.path
|
||||
}
|
||||
|
||||
init(
|
||||
path: String,
|
||||
configuration: Configuration,
|
||||
defaultLabel: String = "GRDB.DatabaseSnapshot",
|
||||
purpose: String? = nil)
|
||||
throws
|
||||
{
|
||||
let configuration = Self.configure(configuration)
|
||||
|
||||
serializedDatabase = try SerializedDatabase(
|
||||
reader = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
defaultLabel: defaultLabel,
|
||||
purpose: purpose)
|
||||
|
||||
try serializedDatabase.sync { db in
|
||||
// Assert WAL mode
|
||||
let journalMode = try String.fetchOne(db, sql: "PRAGMA journal_mode")
|
||||
guard journalMode == "wal" else {
|
||||
throw DatabaseError(message: "WAL mode is not activated at path: \(path)")
|
||||
}
|
||||
|
||||
try reader.sync { db in
|
||||
// Open transaction
|
||||
try db.beginTransaction(.deferred)
|
||||
|
||||
// Acquire snapshot isolation
|
||||
try db.internalCachedStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next()
|
||||
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
// Leave snapshot isolation
|
||||
serializedDatabase.reentrantSync { db in
|
||||
reader.reentrantSync { db in
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
|
||||
private static func configure(_ configuration: Configuration) -> Configuration {
|
||||
var configuration = configuration
|
||||
|
||||
// DatabaseSnapshot can't perform parallel reads.
|
||||
configuration.maximumReaderCount = 1
|
||||
|
||||
// DatabaseSnapshot is read-only.
|
||||
configuration.readonly = true
|
||||
|
||||
// DatabaseSnapshot uses deferred transactions by default.
|
||||
// Other transaction kinds are forbidden by SQLite in read-only connections.
|
||||
configuration.defaultTransactionKind = .deferred
|
||||
|
||||
// DatabaseSnapshot keeps a long-lived transaction.
|
||||
configuration.allowsUnsafeTransactions = true
|
||||
|
||||
return configuration
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseSnapshot: DatabaseReader {
|
||||
extension DatabaseSnapshot: DatabaseSnapshotReader {
|
||||
public func close() throws {
|
||||
try serializedDatabase.sync { try $0.close() }
|
||||
try reader.sync { try $0.close() }
|
||||
}
|
||||
|
||||
// MARK: - Interrupting Database Operations
|
||||
|
||||
public func interrupt() {
|
||||
serializedDatabase.interrupt()
|
||||
reader.interrupt()
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
try serializedDatabase.sync(block)
|
||||
try reader.sync(block)
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
serializedDatabase.async { value(.success($0)) }
|
||||
reader.async { value(.success($0)) }
|
||||
}
|
||||
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) rethrows -> T {
|
||||
try serializedDatabase.sync(value)
|
||||
try reader.sync(value)
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
serializedDatabase.async { value(.success($0)) }
|
||||
reader.async { value(.success($0)) }
|
||||
}
|
||||
|
||||
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try serializedDatabase.reentrantSync(value)
|
||||
try reader.reentrantSync(value)
|
||||
}
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
// swiftlint:disable:next line_length
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
/// A database connection that allows concurrent accesses to an unchanging
|
||||
/// database content, as it existed at the moment the snapshot was created.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// A `DatabaseSnapshotPool` never sees any database modification during all its
|
||||
/// lifetime. All database accesses performed from a snapshot always see the
|
||||
/// same identical database content.
|
||||
///
|
||||
/// It creates a pool of up to ``Configuration/maximumReaderCount`` read-only
|
||||
/// SQLite connections. All read accesses are executed in **reader dispatch
|
||||
/// queues** (one per read-only SQLite connection). SQLite connections are
|
||||
/// closed when the `DatabasePool` is deallocated.
|
||||
///
|
||||
/// An SQLite database in the [WAL mode](https://www.sqlite.org/wal.html) is
|
||||
/// required for creating a `DatabaseSnapshotPool`.
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// You create a `DatabaseSnapshotPool` from a
|
||||
/// [WAL mode](https://www.sqlite.org/wal.html) database, such as databases
|
||||
/// created from a ``DatabasePool``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
/// let snapshot = try dbPool.makeSnapshotPool()
|
||||
/// ```
|
||||
///
|
||||
/// When you want to control the database state seen by a snapshot, create the
|
||||
/// snapshot from a database connection, outside of a write transaction. You can
|
||||
/// for example take snapshots from a ``ValueObservation``:
|
||||
///
|
||||
/// ```swift
|
||||
/// // An observation of the 'player' table
|
||||
/// // that notifies fresh database snapshots:
|
||||
/// let observation = ValueObservation.tracking { db in
|
||||
/// // Don't fetch players now, and return a snapshot instead.
|
||||
/// // Register an access to the player table so that the
|
||||
/// // observation tracks changes to this table.
|
||||
/// try db.registerAccess(to: Player.all())
|
||||
/// return try DatabaseSnapshotPool(db)
|
||||
/// }
|
||||
///
|
||||
/// // Start observing the 'player' table
|
||||
/// let cancellable = try observation.start(in: dbPool) { error in
|
||||
/// // Handle error
|
||||
/// } onChange: { (snapshot: DatabaseSnapshotPool) in
|
||||
/// // Handle a fresh snapshot
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// `DatabaseSnapshotPool` inherits its database access methods from the
|
||||
/// ``DatabaseReader`` protocols.
|
||||
///
|
||||
/// Related SQLite documentation:
|
||||
///
|
||||
/// - <https://www.sqlite.org/c3ref/snapshot_get.html>
|
||||
/// - <https://www.sqlite.org/c3ref/snapshot_open.html>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a DatabaseSnapshotPool
|
||||
///
|
||||
/// See also ``DatabasePool/makeSnapshotPool()``.
|
||||
///
|
||||
/// - ``init(_:configuration:)``
|
||||
/// - ``init(path:configuration:)``
|
||||
public final class DatabaseSnapshotPool {
|
||||
public let configuration: Configuration
|
||||
|
||||
/// The path to the database file.
|
||||
public let path: String
|
||||
|
||||
/// The pool of reader connections.
|
||||
/// It is constant, until close() sets it to nil.
|
||||
private var readerPool: Pool<SerializedDatabase>?
|
||||
|
||||
/// The WAL snapshot
|
||||
private let walSnapshot: WALSnapshot
|
||||
|
||||
/// A connection that prevents checkpoints and keeps the WAL snapshot valid.
|
||||
/// It is never used.
|
||||
private let snapshotHolder: DatabaseQueue
|
||||
|
||||
/// Creates a snapshot of the database.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
/// let snapshot = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshotPool in
|
||||
/// try db.inTransaction {
|
||||
/// try Player.deleteAll()
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// // Create the snapshot after all players have been deleted.
|
||||
/// return DatabaseSnapshotPool(db)
|
||||
/// }
|
||||
///
|
||||
/// // Later... Maybe some players have been created.
|
||||
/// // The snapshot is guaranteed to see an empty table of players, though:
|
||||
/// let count = try snapshot.read { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// assert(count == 0)
|
||||
/// ```
|
||||
///
|
||||
/// 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>
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter configuration: A configuration. If nil, the configuration of
|
||||
/// `db` is used.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public init(_ db: Database, configuration: Configuration? = nil) throws {
|
||||
var configuration = Self.configure(configuration ?? db.configuration)
|
||||
|
||||
// Acquire and hold WAL snapshot
|
||||
let walSnapshot = try db.isolated(readOnly: true) {
|
||||
try WALSnapshot(db)
|
||||
}
|
||||
var holderConfig = Configuration()
|
||||
holderConfig.allowsUnsafeTransactions = true
|
||||
snapshotHolder = try DatabaseQueue(path: db.path, configuration: holderConfig)
|
||||
try snapshotHolder.inDatabase { db in
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
|
||||
let code = sqlite3_snapshot_open(db.sqliteConnection, "main", walSnapshot.sqliteSnapshot)
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code)
|
||||
}
|
||||
}
|
||||
|
||||
configuration.prepareDatabase { db in
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
|
||||
let code = sqlite3_snapshot_open(db.sqliteConnection, "main", walSnapshot.sqliteSnapshot)
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code)
|
||||
}
|
||||
}
|
||||
|
||||
self.configuration = configuration
|
||||
self.path = db.path
|
||||
self.walSnapshot = walSnapshot
|
||||
|
||||
var readerCount = 0
|
||||
readerPool = Pool(
|
||||
maximumCount: configuration.maximumReaderCount,
|
||||
qos: configuration.readQoS,
|
||||
makeElement: {
|
||||
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
|
||||
return try SerializedDatabase(
|
||||
path: db.path,
|
||||
configuration: configuration,
|
||||
defaultLabel: "GRDB.DatabaseSnapshotPool",
|
||||
purpose: "snapshot.\(readerCount)")
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates a snapshot of the database.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let snapshot = try DatabaseSnapshotPool(path: "/path/to/database.sqlite")
|
||||
/// ```
|
||||
///
|
||||
/// 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 the wal file is missing or truncated (size zero).
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/snapshot_get.html>
|
||||
///
|
||||
/// - parameters:
|
||||
/// - path: The path to the database file.
|
||||
/// - configuration: A configuration.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public init(path: String, configuration: Configuration = Configuration()) throws {
|
||||
var configuration = Self.configure(configuration)
|
||||
|
||||
// Acquire and hold WAL snapshot
|
||||
var holderConfig = Configuration()
|
||||
holderConfig.allowsUnsafeTransactions = true
|
||||
snapshotHolder = try DatabaseQueue(path: path, configuration: holderConfig)
|
||||
let walSnapshot = try snapshotHolder.inDatabase { db in
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
|
||||
return try WALSnapshot(db)
|
||||
}
|
||||
|
||||
configuration.prepareDatabase { db in
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
|
||||
let code = sqlite3_snapshot_open(db.sqliteConnection, "main", walSnapshot.sqliteSnapshot)
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code)
|
||||
}
|
||||
}
|
||||
|
||||
self.configuration = configuration
|
||||
self.path = path
|
||||
self.walSnapshot = walSnapshot
|
||||
|
||||
var readerCount = 0
|
||||
readerPool = Pool(
|
||||
maximumCount: configuration.maximumReaderCount,
|
||||
qos: configuration.readQoS,
|
||||
makeElement: {
|
||||
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
|
||||
return try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
defaultLabel: "GRDB.DatabaseSnapshotPool",
|
||||
purpose: "snapshot.\(readerCount)")
|
||||
})
|
||||
}
|
||||
|
||||
private static func configure(_ configuration: Configuration) -> Configuration {
|
||||
var configuration = configuration
|
||||
|
||||
// DatabaseSnapshotPool needs a non-empty pool of connections.
|
||||
GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1")
|
||||
|
||||
// DatabaseSnapshotPool is read-only.
|
||||
configuration.readonly = true
|
||||
|
||||
// DatabaseSnapshotPool uses deferred transactions by default.
|
||||
// Other transaction kinds are forbidden by SQLite in read-only connections.
|
||||
configuration.defaultTransactionKind = .deferred
|
||||
|
||||
// DatabaseSnapshotPool keeps a long-lived transaction.
|
||||
configuration.allowsUnsafeTransactions = true
|
||||
|
||||
// DatabaseSnapshotPool requires the WAL mode.
|
||||
// See <https://www.sqlite.org/wal.html#sometimes_queries_return_sqlite_busy_in_wal_mode>
|
||||
if configuration.readonlyBusyMode == nil {
|
||||
configuration.readonlyBusyMode = .timeout(10)
|
||||
}
|
||||
|
||||
return configuration
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseSnapshotPool: @unchecked Sendable { }
|
||||
|
||||
extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
public func close() throws {
|
||||
try readerPool?.barrier {
|
||||
defer { readerPool = nil }
|
||||
|
||||
try readerPool?.forEach { reader in
|
||||
try reader.sync { try $0.close() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func interrupt() {
|
||||
readerPool?.forEach { $0.interrupt() }
|
||||
}
|
||||
|
||||
@_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 else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
var completion: PoolCompletion!
|
||||
defer {
|
||||
releaseReader(completion)
|
||||
}
|
||||
return try reader.sync { db in
|
||||
do {
|
||||
let value = try value(db)
|
||||
completion = poolCompletion(db)
|
||||
return value
|
||||
} catch {
|
||||
completion = poolCompletion(db)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
}
|
||||
|
||||
readerPool.asyncGet { result in
|
||||
do {
|
||||
let (reader, releaseReader) = try result.get()
|
||||
// Second async jump because that's how `Pool.async` has to be used.
|
||||
reader.async { db in
|
||||
value(.success(db))
|
||||
releaseReader(self.poolCompletion(db))
|
||||
}
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
if let reader = currentReader {
|
||||
return try reader.reentrantSync { db in
|
||||
let result = try value(db)
|
||||
if snapshotIsLost(db) {
|
||||
throw DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.")
|
||||
}
|
||||
return result
|
||||
}
|
||||
} else {
|
||||
// There is no unsafe access to a snapshot.
|
||||
return try read(value)
|
||||
}
|
||||
}
|
||||
|
||||
public func _add<Reducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable where Reducer: ValueReducer
|
||||
{
|
||||
_addReadOnly(observation: observation, scheduling: scheduler, onChange: onChange)
|
||||
}
|
||||
|
||||
/// Returns a reader that can be used from the current dispatch queue,
|
||||
/// if any.
|
||||
private var currentReader: SerializedDatabase? {
|
||||
guard let readerPool else {
|
||||
return nil
|
||||
}
|
||||
|
||||
var readers: [SerializedDatabase] = []
|
||||
readerPool.forEach { reader in
|
||||
// We can't check for reader.onValidQueue here because
|
||||
// Pool.forEach() runs its closure argument in some arbitrary
|
||||
// dispatch queue. We thus extract the reader so that we can query
|
||||
// it below.
|
||||
readers.append(reader)
|
||||
}
|
||||
|
||||
// Now the readers array contains some readers. The pool readers may
|
||||
// already be different, because some other thread may have started
|
||||
// a new read, for example.
|
||||
//
|
||||
// This doesn't matter: the reader we are looking for is already on
|
||||
// its own dispatch queue. If it exists, is still in use, thus still
|
||||
// in the pool, and thus still relevant for our check:
|
||||
return readers.first { $0.onValidQueue }
|
||||
}
|
||||
|
||||
private func poolCompletion(_ db: Database) -> PoolCompletion {
|
||||
snapshotIsLost(db) ? .discard : .reuse
|
||||
}
|
||||
|
||||
private func snapshotIsLost(_ db: Database) -> Bool {
|
||||
do {
|
||||
let currentSnapshot = try WALSnapshot(db)
|
||||
if currentSnapshot.compare(walSnapshot) == 0 {
|
||||
return false
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
} catch {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -44,6 +44,7 @@ import Foundation
|
||||
/// ### Creating a DatabaseValue
|
||||
///
|
||||
/// - ``init(value:)``
|
||||
/// - ``init(sqliteStatement:index:)``
|
||||
/// - ``null``
|
||||
///
|
||||
/// ### Accessing the SQLite storage
|
||||
@@ -149,7 +150,7 @@ public struct DatabaseValue: Hashable {
|
||||
}
|
||||
|
||||
/// Creates a `DatabaseValue` initialized from a raw SQLite statement pointer.
|
||||
init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
public init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_NULL:
|
||||
storage = .null
|
||||
@@ -188,6 +189,34 @@ extension DatabaseValue: StatementBinding {
|
||||
return data.bind(to: sqliteStatement, at: index)
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls the given closure after binding a statement argument.
|
||||
///
|
||||
/// The binding is valid only during the execution of this method.
|
||||
///
|
||||
/// - parameter sqliteStatement: An SQLite statement.
|
||||
/// - parameter index: 1-based index to statement arguments.
|
||||
/// - parameter body: The closure to execute when argument is bound.
|
||||
func withBinding<T>(to sqliteStatement: SQLiteStatement, at index: CInt, do body: () throws -> T) throws -> T {
|
||||
switch storage {
|
||||
case .null:
|
||||
let code = sqlite3_bind_null(sqliteStatement, index)
|
||||
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
|
||||
return try body()
|
||||
case .int64(let int64):
|
||||
let code = int64.bind(to: sqliteStatement, at: index)
|
||||
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
|
||||
return try body()
|
||||
case .double(let double):
|
||||
let code = double.bind(to: sqliteStatement, at: index)
|
||||
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
|
||||
return try body()
|
||||
case .string(let string):
|
||||
return try string.withBinding(to: sqliteStatement, at: index, do: body)
|
||||
case .blob(let data):
|
||||
return try data.withBinding(to: sqliteStatement, at: index, do: body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValue: Sendable { }
|
||||
|
||||
@@ -1,49 +1,40 @@
|
||||
/// A type that can convert itself into and out of a database value.
|
||||
///
|
||||
/// `DatabaseValueConvertible` is adopted by `Bool`, `Int`, `String`,
|
||||
/// `Date`, etc.
|
||||
///
|
||||
/// To conform to `DatabaseValueConvertible`, provide custom implementations
|
||||
/// for ``fromDatabaseValue(_:)-21zzv`` and ``databaseValue-1ob9k``. These
|
||||
/// implementations are ready-made for `RawRepresentable` types whose
|
||||
/// `RawValue` is `StatementColumnConvertible`, and for `Codable` types.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a Value
|
||||
///
|
||||
/// - ``fromDatabaseValue(_:)-21zzv``
|
||||
/// - ``fromMissingColumn()-7iamp``
|
||||
///
|
||||
/// ### Accessing the DatabaseValue
|
||||
///
|
||||
/// - ``databaseValue-1ob9k``
|
||||
///
|
||||
/// ### Fetching Values from Raw SQL
|
||||
///
|
||||
/// - ``fetchCursor(_:sql:arguments:adapter:)-6elcz``
|
||||
/// - ``fetchAll(_:sql:arguments:adapter:)-1cqyb``
|
||||
/// - ``fetchSet(_:sql:arguments:adapter:)-5jene``
|
||||
/// - ``fetchOne(_:sql:arguments:adapter:)-qvqp``
|
||||
///
|
||||
/// ### Fetching Values from a Prepared Statement
|
||||
///
|
||||
/// - ``fetchCursor(_:arguments:adapter:)-4l6af``
|
||||
/// - ``fetchAll(_:arguments:adapter:)-3abuc``
|
||||
/// - ``fetchSet(_:arguments:adapter:)-6y54n``
|
||||
/// - ``fetchOne(_:arguments:adapter:)-3d7ax``
|
||||
///
|
||||
/// ### Fetching Values from a Request
|
||||
///
|
||||
/// - ``fetchCursor(_:_:)-8q4r6``
|
||||
/// - ``fetchAll(_:_:)-9hkqs``
|
||||
/// - ``fetchSet(_:_:)-1foke``
|
||||
/// - ``fetchOne(_:_:)-o6yj``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``DatabaseValueCursor``
|
||||
/// - ``StatementBinding``
|
||||
import Foundation
|
||||
|
||||
// Standard collections `Array`, `Set`, and `Dictionary` do not conform to
|
||||
// `DatabaseValueConvertible`, on purpose.
|
||||
//
|
||||
// Adding `DatabaseValueConvertible` conformance to those collection types
|
||||
// would litter JSON values in unexpected places, and foster misuse. For
|
||||
// example, it is better when the code below *does not compile*:
|
||||
//
|
||||
// ```swift
|
||||
// // MISUSE: if Array would conform to DatabaseValueConvertible, this
|
||||
// // code would compile, and run the incorrect SQLite query
|
||||
// // `SELECT ... WHERE id IN ('[1,2,3]')`, instead of the expected
|
||||
// // `SELECT ... WHERE id IN (1, 2, 3)`.
|
||||
// let ids = [1, 2, 3]
|
||||
// let players = try Player.fetchAll(db, sql: """
|
||||
// SELECT * FROM player WHERE id IN (?)
|
||||
// """, arguments: [ids])
|
||||
// ```
|
||||
//
|
||||
// Correct and fostered versions of the code above are:
|
||||
//
|
||||
// ```swift
|
||||
// // CORRECT (explicit SQLite arguments):
|
||||
// let ids = [1, 2, 3]
|
||||
// let questionMarks = databaseQuestionMarks(count: ids.count) // "?,?,?"
|
||||
// let players = try Player.fetchAll(db, sql: """
|
||||
// SELECT * FROM player WHERE id IN (\(questionMarks))
|
||||
// """, arguments: StatementArguments(ids))
|
||||
//
|
||||
// // CORRECT (SQL interpolation):
|
||||
// let ids = [1, 2, 3]
|
||||
// let request: SQLRequest<Player> = """
|
||||
// SELECT * FROM player WHERE id IN \(ids)
|
||||
// """
|
||||
// let players = try request.fetchAll(db)
|
||||
// ```
|
||||
public protocol DatabaseValueConvertible: SQLExpressible, StatementBinding {
|
||||
/// A database value.
|
||||
var databaseValue: DatabaseValue { get }
|
||||
@@ -70,6 +61,18 @@ public protocol DatabaseValueConvertible: SQLExpressible, StatementBinding {
|
||||
///
|
||||
/// - returns: A decoded value, or, if decoding is impossible, nil.
|
||||
static func fromMissingColumn() -> Self?
|
||||
|
||||
/// Returns the `JSONDecoder` that decodes the value.
|
||||
///
|
||||
/// This method is dedicated to ``DatabaseValueConvertible`` types that
|
||||
/// also conform to the standard `Decodable` protocol.
|
||||
static func databaseJSONDecoder() -> JSONDecoder
|
||||
|
||||
/// Returns the `JSONEncoder` that encodes the value.
|
||||
///
|
||||
/// This method is dedicated to ``DatabaseValueConvertible`` types that
|
||||
/// also conform to the standard `Encodable` protocol.
|
||||
static func databaseJSONEncoder() -> JSONEncoder
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible {
|
||||
@@ -86,6 +89,41 @@ extension DatabaseValueConvertible {
|
||||
public static func fromMissingColumn() -> Self? {
|
||||
nil // failure.
|
||||
}
|
||||
|
||||
/// Returns the `JSONDecoder` that decodes the value.
|
||||
///
|
||||
/// The default implementation returns a `JSONDecoder` with the
|
||||
/// following properties:
|
||||
///
|
||||
/// - `dataDecodingStrategy`: `.base64`
|
||||
/// - `dateDecodingStrategy`: `.millisecondsSince1970`
|
||||
/// - `nonConformingFloatDecodingStrategy`: `.throw`
|
||||
public static func databaseJSONDecoder() -> JSONDecoder {
|
||||
let decoder = JSONDecoder()
|
||||
decoder.dataDecodingStrategy = .base64
|
||||
decoder.dateDecodingStrategy = .millisecondsSince1970
|
||||
decoder.nonConformingFloatDecodingStrategy = .throw
|
||||
return decoder
|
||||
}
|
||||
|
||||
/// Returns the `JSONEncoder` that encodes the value.
|
||||
///
|
||||
/// The default implementation returns a `JSONEncoder` with the
|
||||
/// following properties:
|
||||
///
|
||||
/// - `dataEncodingStrategy`: `.base64`
|
||||
/// - `dateEncodingStrategy`: `.millisecondsSince1970`
|
||||
/// - `nonConformingFloatEncodingStrategy`: `.throw`
|
||||
/// - `outputFormatting`: `.sortedKeys`
|
||||
public static func databaseJSONEncoder() -> JSONEncoder {
|
||||
let encoder = JSONEncoder()
|
||||
encoder.dataEncodingStrategy = .base64
|
||||
encoder.dateEncodingStrategy = .millisecondsSince1970
|
||||
encoder.nonConformingFloatEncodingStrategy = .throw
|
||||
// guarantee some stability in order to ease value comparison
|
||||
encoder.outputFormatting = .sortedKeys
|
||||
return encoder
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Conversions
|
||||
@@ -159,7 +197,7 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
|
||||
self._statement = statement
|
||||
if let adapter = adapter {
|
||||
if let adapter {
|
||||
// adapter may redefine the index of the leftmost column
|
||||
columnIndex = try CInt(adapter.baseColumnIndex(atIndex: 0, layout: statement))
|
||||
} else {
|
||||
@@ -167,7 +205,7 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
|
||||
}
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
try statement.reset(withArguments: arguments)
|
||||
try statement.prepareExecution(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -184,6 +222,11 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: database cursors must be used from
|
||||
// a serialized database access dispatch queue.
|
||||
@available(*, unavailable)
|
||||
extension DatabaseValueCursor: Sendable { }
|
||||
|
||||
/// DatabaseValueConvertible comes with built-in methods that allow to fetch
|
||||
/// cursors, arrays, or single values:
|
||||
///
|
||||
|
||||
@@ -5,8 +5,8 @@ import Dispatch
|
||||
|
||||
/// A type that writes into an SQLite database.
|
||||
///
|
||||
/// Do not declare new conformances to `DatabaseWriter`. Only the
|
||||
/// ``DatabaseQueue`` and ``DatabasePool`` types are valid conforming types.
|
||||
/// Do not declare new conformances to `DatabaseWriter`. Only the built-in
|
||||
/// conforming types are valid.
|
||||
///
|
||||
/// A database writer creates one single SQLite connection dedicated to database
|
||||
/// updates. All updates are executed in a serial **writer dispatch queue**.
|
||||
@@ -42,15 +42,15 @@ import Dispatch
|
||||
/// - ``spawnConcurrentRead(_:)``
|
||||
/// - ``DatabaseFuture``
|
||||
///
|
||||
/// ### Unsafe Methods
|
||||
///
|
||||
/// - ``unsafeReentrantWrite(_:)``
|
||||
///
|
||||
/// ### Observing Database Transactions
|
||||
///
|
||||
/// - ``add(transactionObserver:extent:)``
|
||||
/// - ``remove(transactionObserver:)``
|
||||
///
|
||||
/// ### Unsafe Methods
|
||||
///
|
||||
/// - ``unsafeReentrantWrite(_:)``
|
||||
///
|
||||
/// ### Other Database Operations
|
||||
///
|
||||
/// - ``erase()-w5n7``
|
||||
@@ -94,7 +94,8 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// can see changes performed by concurrent writes or writes performed by
|
||||
/// other processes: two identical requests performed by the `updates`
|
||||
/// closure may not return the same value. Concurrent database accesses
|
||||
/// can see partial updates performed by the `updates` closure.
|
||||
/// can see partial updates performed by the `updates` closure. See
|
||||
/// <doc:Concurrency#Rule-2:-Mind-your-transactions> for more information.
|
||||
///
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `updates`.
|
||||
@@ -133,7 +134,8 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// can see changes performed by concurrent writes or writes performed by
|
||||
/// other processes: two identical requests performed by the `updates`
|
||||
/// closure may not return the same value. Concurrent database accesses
|
||||
/// can see partial updates performed by the `updates` closure.
|
||||
/// can see partial updates performed by the `updates` closure. See
|
||||
/// <doc:Concurrency#Rule-2:-Mind-your-transactions> for more information.
|
||||
///
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `updates`.
|
||||
@@ -173,7 +175,8 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// can see changes performed by concurrent writes or writes performed by
|
||||
/// other processes: two identical requests performed by the `updates`
|
||||
/// closure may not return the same value. Concurrent database accesses
|
||||
/// can see partial updates performed by the `updates` closure.
|
||||
/// can see partial updates performed by the `updates` closure. See
|
||||
/// <doc:Concurrency#Rule-2:-Mind-your-transactions> for more information.
|
||||
///
|
||||
/// - parameter updates: A closure which accesses the database. Its argument
|
||||
/// is a `Result` that provides the database connection, or the failure
|
||||
@@ -206,7 +209,8 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// can see changes performed by concurrent writes or writes performed by
|
||||
/// other processes: two identical requests performed by the `updates`
|
||||
/// closure may not return the same value. Concurrent database accesses
|
||||
/// can see partial updates performed by the `updates` closure.
|
||||
/// can see partial updates performed by the `updates` closure. See
|
||||
/// <doc:Concurrency#Rule-2:-Mind-your-transactions> for more information.
|
||||
///
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
|
||||
@@ -215,10 +219,9 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// finished executing.
|
||||
///
|
||||
/// This method can be called from other database access methods. Reentrant
|
||||
/// database accesses are discouraged, though, because they muddle
|
||||
/// transaction boundaries.
|
||||
/// (see <doc:Concurrency#Rule-2:-Mind-your-transactions> for
|
||||
/// more information).
|
||||
/// database accesses are discouraged because they muddle transaction
|
||||
/// boundaries. See <doc:Concurrency#Rule-2:-Mind-your-transactions> for
|
||||
/// more information.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -286,14 +289,13 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// ```
|
||||
///
|
||||
/// - note: Usage of this method is discouraged, because waiting on the
|
||||
/// returned ``DatabaseFuture`` blocks a thread. You may prefer the
|
||||
/// asynchronous version of this method: ``spawnConcurrentRead(_:)``.
|
||||
/// returned ``DatabaseFuture`` blocks a thread. You may prefer
|
||||
/// ``spawnConcurrentRead(_:)`` instead.
|
||||
/// - parameter value: A closure which accesses the database.
|
||||
func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T>
|
||||
|
||||
// Exposed for RxGRDB and GRBCombine. Naming is not stabilized.
|
||||
/// Schedules read-only database operations for execution, and
|
||||
/// returns immediately.
|
||||
/// Schedules read-only database operations for execution.
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
@@ -308,7 +310,7 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// by the database writer.
|
||||
///
|
||||
/// 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 return zero:
|
||||
///
|
||||
/// ```swift
|
||||
/// try writer.writeWithoutTransaction { db in
|
||||
@@ -331,6 +333,10 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - important: The database operations are executed immediately,
|
||||
/// or asynchronously, depending on the actual class
|
||||
/// of `DatabaseWriter`.
|
||||
///
|
||||
/// - parameter value: A closure which accesses the database. Its argument
|
||||
/// is a `Result` that provides the database connection, or the failure
|
||||
/// that would prevent establishing the read access to the database.
|
||||
@@ -439,10 +445,21 @@ extension DatabaseWriter {
|
||||
|
||||
// MARK: - Transaction Observers
|
||||
|
||||
/// Adds a transaction observer, so that it gets notified of
|
||||
/// database changes and transactions.
|
||||
/// Adds a transaction observer to the writer connection, so that it
|
||||
/// gets notified of database changes and transactions.
|
||||
///
|
||||
/// This method has no effect on read-only database connections.
|
||||
/// This method waits until all currently executing database accesses
|
||||
/// performed by the writer dispatch queue finish executing.
|
||||
/// At that point, database observation begins.
|
||||
///
|
||||
/// It has no effect on read-only database connections.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let myObserver = MyObserver()
|
||||
/// try dbQueue.add(transactionObserver: myObserver)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter transactionObserver: A transaction observer.
|
||||
/// - parameter extent: The duration of the observation. The default is
|
||||
@@ -455,14 +472,25 @@ extension DatabaseWriter {
|
||||
writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) }
|
||||
}
|
||||
|
||||
/// Removes a transaction observer.
|
||||
/// Removes a transaction observer from the writer connection.
|
||||
///
|
||||
/// This method waits until all currently executing database accesses
|
||||
/// performed by the writer dispatch queue finish executing.
|
||||
/// At that point, database observation stops.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let myObserver = MyObserver()
|
||||
/// try dbQueue.remove(transactionObserver: myObserver)
|
||||
/// ```
|
||||
public func remove(transactionObserver: some TransactionObserver) {
|
||||
writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) }
|
||||
}
|
||||
|
||||
// MARK: - Erasing the content of the database
|
||||
|
||||
/// Erases the content of the database.
|
||||
/// Erase the database: delete all content, drop all tables, etc.
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func erase() throws {
|
||||
try barrierWriteWithoutTransaction { try $0.erase() }
|
||||
@@ -513,7 +541,7 @@ extension DatabaseWriter {
|
||||
///
|
||||
/// - Parameter filePath: file path for new database
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
@available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *)
|
||||
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *)
|
||||
public func vacuum(into filePath: String) throws {
|
||||
try writeWithoutTransaction {
|
||||
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
|
||||
@@ -528,7 +556,7 @@ extension DatabaseWriter {
|
||||
/// was modified.
|
||||
func _addWriteOnly<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
@@ -579,7 +607,7 @@ extension DatabaseWriter {
|
||||
/// - throws: The error thrown by `updates`, or any ``DatabaseError`` that
|
||||
/// would happen while establishing the database access or committing
|
||||
/// the transaction.
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func write<T>(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
asyncWrite(updates, completion: { _, result in
|
||||
@@ -617,7 +645,7 @@ extension DatabaseWriter {
|
||||
///
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `updates`.
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func writeWithoutTransaction<T>(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
asyncWriteWithoutTransaction { db in
|
||||
@@ -669,7 +697,7 @@ extension DatabaseWriter {
|
||||
///
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `updates`.
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func barrierWriteWithoutTransaction<T>(
|
||||
_ updates: @Sendable @escaping (Database) throws -> T)
|
||||
async throws -> T
|
||||
@@ -681,10 +709,10 @@ extension DatabaseWriter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Erases the content of the database.
|
||||
/// Erase the database: delete all content, drop all tables, etc.
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func erase() async throws {
|
||||
try await writeWithoutTransaction { try $0.erase() }
|
||||
}
|
||||
@@ -695,7 +723,7 @@ extension DatabaseWriter {
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_vacuum.html>
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func vacuum() async throws {
|
||||
try await writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
|
||||
}
|
||||
@@ -712,7 +740,7 @@ extension DatabaseWriter {
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_vacuum.html#vacuuminto>
|
||||
///
|
||||
/// - Parameter filePath: file path for new database
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func vacuum(into filePath: String) async throws {
|
||||
try await writeWithoutTransaction {
|
||||
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
|
||||
@@ -727,7 +755,7 @@ extension DatabaseWriter {
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_vacuum.html#vacuuminto>
|
||||
///
|
||||
/// - Parameter filePath: file path for new database
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func vacuum(into filePath: String) async throws {
|
||||
try await writeWithoutTransaction {
|
||||
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
|
||||
@@ -772,7 +800,7 @@ extension DatabaseWriter {
|
||||
///
|
||||
/// - parameter scheduler: A Combine Scheduler.
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func writePublisher<Output>(
|
||||
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
|
||||
updates: @escaping (Database) throws -> Output)
|
||||
@@ -837,7 +865,7 @@ extension DatabaseWriter {
|
||||
/// - parameter scheduler: A Combine Scheduler.
|
||||
/// - parameter updates: A closure which writes in the database.
|
||||
/// - parameter value: A closure which reads from the database.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func writePublisher<S, T, Output>(
|
||||
receiveOn scheduler: S = DispatchQueue.main,
|
||||
updates: @escaping (Database) throws -> T,
|
||||
@@ -869,7 +897,7 @@ extension DatabaseWriter {
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
extension DatabasePublishers {
|
||||
/// A publisher that writes into the database.
|
||||
///
|
||||
@@ -888,7 +916,7 @@ extension DatabasePublishers {
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
extension Publisher where Failure == Error {
|
||||
fileprivate func eraseToWritePublisher() -> DatabasePublishers.Write<Output> {
|
||||
.init(upstream: self.eraseToAnyPublisher())
|
||||
@@ -958,6 +986,10 @@ extension AnyDatabaseWriter: DatabaseReader {
|
||||
base.configuration
|
||||
}
|
||||
|
||||
public var path: String {
|
||||
base.path
|
||||
}
|
||||
|
||||
public func close() throws {
|
||||
try base.close()
|
||||
}
|
||||
@@ -990,7 +1022,7 @@ extension AnyDatabaseWriter: DatabaseReader {
|
||||
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
|
||||
@@ -58,10 +58,6 @@
|
||||
/// - ``makePreparedRequest(_:forSingleResult:)``
|
||||
/// - ``PreparedRequest``
|
||||
///
|
||||
/// ### Database Observation Support
|
||||
///
|
||||
/// - ``databaseRegion(_:)``
|
||||
///
|
||||
/// ### Adapting the Fetched Rows
|
||||
///
|
||||
/// - ``adapted(_:)``
|
||||
@@ -111,6 +107,28 @@ extension FetchRequest {
|
||||
|
||||
// MARK: - PreparedRequest
|
||||
|
||||
/// A closure executed before a supplementary fetch is performed.
|
||||
///
|
||||
/// Support for `Database.dumpRequest`.
|
||||
///
|
||||
/// - parameter request: The supplementary request
|
||||
/// - parameter keyPath: The key path target of the supplementary fetch.
|
||||
typealias WillExecuteSupplementaryRequest = (_ request: AnyFetchRequest<Row>, _ keyPath: [String]) throws -> Void
|
||||
|
||||
/// A closure that performs supplementary fetches.
|
||||
///
|
||||
/// Support for eager loading of hasMany associations.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter rows: The rows that are modified by the supplementary fetch.
|
||||
/// - parameter willExecuteSupplementaryRequest: A closure to execute before
|
||||
/// performing supplementary fetches.
|
||||
typealias SupplementaryFetch = (
|
||||
_ db: Database,
|
||||
_ rows: [Row],
|
||||
_ willExecuteSupplementaryRequest: WillExecuteSupplementaryRequest?)
|
||||
throws -> Void
|
||||
|
||||
/// A `PreparedRequest` is a request that is ready to be executed.
|
||||
public struct PreparedRequest {
|
||||
/// A prepared statement with bound parameters.
|
||||
@@ -119,13 +137,14 @@ public struct PreparedRequest {
|
||||
/// An eventual adapter for rows fetched by the select statement.
|
||||
public var adapter: (any RowAdapter)?
|
||||
|
||||
/// A closure that performs supplementary fetches.
|
||||
/// Support for eager loading of hasMany associations.
|
||||
var supplementaryFetch: ((Database, [Row]) throws -> Void)?
|
||||
var supplementaryFetch: SupplementaryFetch?
|
||||
|
||||
init(
|
||||
statement: Statement,
|
||||
adapter: (any RowAdapter)?,
|
||||
supplementaryFetch: ((Database, [Row]) throws -> Void)? = nil)
|
||||
supplementaryFetch: SupplementaryFetch? = nil)
|
||||
{
|
||||
self.statement = statement
|
||||
self.adapter = adapter
|
||||
@@ -133,6 +152,11 @@ public struct PreparedRequest {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `PreparedRequest` contains
|
||||
// a statement.
|
||||
@available(*, unavailable)
|
||||
extension PreparedRequest: Sendable { }
|
||||
|
||||
extension PreparedRequest: Refinable { }
|
||||
|
||||
// MARK: - AdaptedFetchRequest
|
||||
@@ -141,7 +165,9 @@ extension FetchRequest {
|
||||
/// Returns an adapted request.
|
||||
///
|
||||
/// The returned request performs an identical database query, but adapts
|
||||
/// the fetched rows. See ``RowAdapter``.
|
||||
/// the fetched rows. See ``RowAdapter``, and
|
||||
/// ``splittingRowAdapters(columnCounts:)`` for a sample code that uses
|
||||
/// `adapted(_:)`.
|
||||
///
|
||||
/// - parameter adapter: A closure that accepts a database connection and
|
||||
/// returns a row adapter.
|
||||
@@ -215,8 +241,8 @@ public struct AnyFetchRequest<RowDecoder> {
|
||||
///
|
||||
/// // AnyFetchRequest<Row>
|
||||
/// let rowRequest = playerRequest.asRequest(of: Row.self)
|
||||
public func asRequest<RowDecoder>(of type: RowDecoder.Type) -> AnyFetchRequest<RowDecoder> {
|
||||
AnyFetchRequest<RowDecoder>(request: request)
|
||||
public func asRequest<T>(of type: T.Type) -> AnyFetchRequest<T> {
|
||||
AnyFetchRequest<T>(request: request)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+21
-12
@@ -245,6 +245,12 @@ public final class Row {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: a row contains transient
|
||||
// information. TODO GRDB7: split non sendable statement rows from sendable
|
||||
// copied rows.
|
||||
@available(*, unavailable)
|
||||
extension Row: Sendable { }
|
||||
|
||||
extension Row {
|
||||
|
||||
// MARK: - Columns
|
||||
@@ -682,7 +688,7 @@ extension Row {
|
||||
/// ``JoinableRequest/including(optional:)`` request methods define scopes
|
||||
/// named after the key of included associations between record types.
|
||||
///
|
||||
/// A depth-first search is performed in all available scopes in the row,
|
||||
/// A breadth-first search is performed in all available scopes in the row,
|
||||
/// recursively.
|
||||
///
|
||||
/// A fatal error is raised if the scope is not available, or contains only
|
||||
@@ -726,7 +732,7 @@ extension Row {
|
||||
/// ``JoinableRequest/including(optional:)`` request methods define scopes
|
||||
/// named after the key of included associations between record types.
|
||||
///
|
||||
/// A depth-first search is performed in all available scopes in the row,
|
||||
/// A breadth-first search is performed in all available scopes in the row,
|
||||
/// recursively.
|
||||
///
|
||||
/// The result is nil if the scope is not available, or contains only
|
||||
@@ -879,7 +885,7 @@ extension Row {
|
||||
/// A view on the scopes tree defined by row adapters.
|
||||
///
|
||||
/// The returned object provides an access to all available scopes in
|
||||
/// the row, recursively. For any given scope identifier, a depth-first
|
||||
/// the row, recursively. For any given scope identifier, a breadth-first
|
||||
/// search is performed.
|
||||
///
|
||||
/// Row scopes can be defined manually, with ``ScopeAdapter``.
|
||||
@@ -1152,8 +1158,7 @@ extension Row {
|
||||
/// Nil is returned if the scope is not available, or contains only
|
||||
/// null values.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support>
|
||||
/// for more information.
|
||||
/// See ``splittingRowAdapters(columnCounts:)`` for a sample code.
|
||||
func decodeIfPresent<Record: FetchableRecord>(
|
||||
_ type: Record.Type = Record.self,
|
||||
forKey scope: String)
|
||||
@@ -1194,8 +1199,7 @@ extension Row {
|
||||
/// A fatal error is raised if the scope is not available, or contains only
|
||||
/// null values.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support>
|
||||
/// for more information.
|
||||
/// See ``splittingRowAdapters(columnCounts:)`` for a sample code.
|
||||
func decode<Record: FetchableRecord>(
|
||||
_ type: Record.Type = Record.self,
|
||||
forKey scope: String)
|
||||
@@ -1366,7 +1370,7 @@ public final class RowCursor: DatabaseCursor {
|
||||
self._row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
try statement.reset(withArguments: arguments)
|
||||
try statement.prepareExecution(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -1379,6 +1383,11 @@ public final class RowCursor: DatabaseCursor {
|
||||
public func _element(sqliteStatement: SQLiteStatement) -> Row { _row }
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: database cursors must be used from
|
||||
// a serialized database access dispatch queue.
|
||||
@available(*, unavailable)
|
||||
extension RowCursor: Sendable { }
|
||||
|
||||
extension Row {
|
||||
|
||||
// MARK: - Fetching From Prepared Statement
|
||||
@@ -1741,7 +1750,7 @@ extension Row {
|
||||
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Row] {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
let rows = try fetchAll(request.statement, adapter: request.adapter)
|
||||
try request.supplementaryFetch?(db, rows)
|
||||
try request.supplementaryFetch?(db, rows, nil)
|
||||
return rows
|
||||
}
|
||||
|
||||
@@ -1774,7 +1783,7 @@ extension Row {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
if let supplementaryFetch = request.supplementaryFetch {
|
||||
let rows = try fetchAll(request.statement, adapter: request.adapter)
|
||||
try supplementaryFetch(db, rows)
|
||||
try supplementaryFetch(db, rows, nil)
|
||||
return Set(rows)
|
||||
} else {
|
||||
return try fetchSet(request.statement, adapter: request.adapter)
|
||||
@@ -1811,7 +1820,7 @@ extension Row {
|
||||
guard let row = try fetchOne(request.statement, adapter: request.adapter) else {
|
||||
return nil
|
||||
}
|
||||
try request.supplementaryFetch?(db, [row])
|
||||
try request.supplementaryFetch?(db, [row], nil)
|
||||
return row
|
||||
}
|
||||
}
|
||||
@@ -2061,7 +2070,7 @@ typealias RowIndex = Row.Index
|
||||
|
||||
extension Row {
|
||||
/// An index to a (column, value) pair in a ``Row``.
|
||||
public struct Index {
|
||||
public struct Index: Sendable {
|
||||
let index: Int
|
||||
init(_ index: Int) { self.index = index }
|
||||
}
|
||||
|
||||
+299
-72
@@ -1,27 +1,137 @@
|
||||
import Foundation
|
||||
|
||||
/// Returns an array of row adapters that split a row according to the input
|
||||
/// number of columns.
|
||||
/// Returns an array of row adapters that split a row according to the
|
||||
/// provided numbers of columns.
|
||||
///
|
||||
/// For example:
|
||||
/// This method is useful for splitting a row into chunks.
|
||||
///
|
||||
/// For example, let's consider the following SQL query:
|
||||
///
|
||||
/// ```swift
|
||||
/// let sql = "SELECT 1, 2,3,4, 5,6, 7,8"
|
||||
/// // <.><. . .><. .><. .>
|
||||
/// let adapters = splittingRowAdapters([1, 3, 2])
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "a": adapters[0],
|
||||
/// "b": adapters[1],
|
||||
/// "c": adapters[2],
|
||||
/// "d": adapters[3]])
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// row.scopes["a"] // [1]
|
||||
/// row.scopes["b"] // [2, 3, 4]
|
||||
/// row.scopes["c"] // [5, 6]
|
||||
/// row.scopes["d"] // [7, 8]
|
||||
/// let sql = """
|
||||
/// SELECT player.*, team.*
|
||||
/// FROM player
|
||||
/// LEFT JOIN team ON team.id = player.teamId
|
||||
/// WHERE player.id = ?
|
||||
/// """
|
||||
/// ```
|
||||
///
|
||||
/// The resulting rows contains columns from both player and team tables:
|
||||
///
|
||||
/// ```swift
|
||||
/// // [id: 1, name: "Arthur", teamId: 42, id: 42, name: "Reds"]
|
||||
/// // <---------------------------------><-------------------->
|
||||
/// // player columns team columns
|
||||
/// let row = try Row.fetchOne(db, sql: sql, arguments: [1])
|
||||
/// ```
|
||||
///
|
||||
/// Because some columns have the same name (`id` and `name`), it is
|
||||
/// difficult to access the team columns.
|
||||
///
|
||||
/// `splittingRowAdapters` and ``ScopeAdapter`` make it possible to
|
||||
/// access player and team columns independently, with row ``Row/scopes``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let adapters = try splittingRowAdapters([
|
||||
/// db.columns(in: "player").count,
|
||||
/// db.columns(in: "team").count,
|
||||
/// ])
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "player": adapters[0],
|
||||
/// "team": adapters[1],
|
||||
/// ])
|
||||
/// if let row = try Row.fetchOne(db, sql: sql, arguments: [1], adapter: adapter) {
|
||||
/// // A Row that only contains player columns
|
||||
/// // [id: 1, name: "Arthur", teamId: 42]
|
||||
/// row.scopes["player"]
|
||||
///
|
||||
/// // A Row that only contains team columns
|
||||
/// // [id: 42, name: "Reds"]
|
||||
/// row.scopes["team"]
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Decoding ``FetchableRecord`` types is easy:
|
||||
///
|
||||
/// ```swift
|
||||
/// if let row = try Row.fetchOne(db, sql: sql, arguments: [1], adapter: adapter) {
|
||||
/// // Player(id: 1, name: "Arthur", teamId: 42)
|
||||
/// let player: Player = row["player"]
|
||||
///
|
||||
/// // Team(id: 42, name: "Reds")
|
||||
/// // nil if the LEFT JOIN has fetched NULL team columns
|
||||
/// if let team: Team? = row["team"]
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// You can package this technique in a dedicated type, as in the next
|
||||
/// example. It enhances the previous sample codes with:
|
||||
///
|
||||
/// - Support for record types that customize their fetched columns
|
||||
/// with ``TableRecord/databaseSelection-7iphs``.
|
||||
/// - ``SQLRequest`` and its support for [SQL Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md).
|
||||
/// - ``FetchRequest/adapted(_:)`` for building a request that embeds the
|
||||
/// row adapters.
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord, FetchableRecord { ... }
|
||||
/// struct Team: TableRecord, FetchableRecord { ... }
|
||||
///
|
||||
/// struct PlayerInfo {
|
||||
/// var player: Player
|
||||
/// var team: Team?
|
||||
/// }
|
||||
///
|
||||
/// extension PlayerInfo: FetchableRecord {
|
||||
/// init(row: Row) {
|
||||
/// player = row["player"]
|
||||
/// team = row["team"]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// extension PlayerInfo {
|
||||
/// /// The request for the player info, given a player id
|
||||
/// static func filter(playerId: Int64) -> some FetchRequest<PlayerInfo> {
|
||||
/// // Build SQL request with SQL interpolation
|
||||
/// let request: SQLRequest<PlayerInfo> = """
|
||||
/// SELECT
|
||||
/// \(columnsOf: Player.self), -- Instead of player.*
|
||||
/// \(columnsOf: Team.self), -- Instead of team.*
|
||||
/// FROM player
|
||||
/// LEFT JOIN team ON team.id = player.teamId
|
||||
/// WHERE player.id = \(playerId)
|
||||
/// """
|
||||
///
|
||||
/// // Returns an adapted request that defines the player and team
|
||||
/// // scopes in the fetched row
|
||||
/// return request.adapted { db in
|
||||
/// let adapters = try splittingRowAdapters(columnCounts: [
|
||||
/// Player.numberOfSelectedColumns(db),
|
||||
/// Team.numberOfSelectedColumns(db),
|
||||
/// ])
|
||||
/// return ScopeAdapter([
|
||||
/// "player": adapters[0],
|
||||
/// "team": adapters[1],
|
||||
/// ])
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Usage
|
||||
/// try dbQueue.read { db in
|
||||
/// if let playerInfo = try PlayerInfo.filter(playerId: 1).fetchOne(db) {
|
||||
/// print(playerInfo.player) // Player(id: 1, name: "Arthur", teamId: 42)
|
||||
/// print(playerInfo.team) // Team(id: 42, name: "Reds")
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter columnCounts: An array of row chunk lengths.
|
||||
/// - returns: An array of row adapters that split a row into as many chunks
|
||||
/// as the number of elements in `columnCounts`, plus one (the row adapter
|
||||
/// for all columns that remain on the right of the last chunk).
|
||||
public func splittingRowAdapters(columnCounts: [Int]) -> [any RowAdapter] {
|
||||
guard !columnCounts.isEmpty else {
|
||||
if columnCounts.isEmpty {
|
||||
// Identity adapter
|
||||
return [SuffixRowAdapter(fromIndex: 0)]
|
||||
}
|
||||
@@ -149,25 +259,57 @@ extension Statement: _RowLayout {
|
||||
|
||||
/// A type that helps two incompatible row interfaces working together.
|
||||
///
|
||||
/// You provide row adapters to methods that fetch. For example:
|
||||
/// Row adapters present database rows in the way expected by the
|
||||
/// row consumers.
|
||||
///
|
||||
/// For example, when a row consumer expects a column named "consumed", but
|
||||
/// the raw row has a column named "produced", the ``ColumnMapping`` row
|
||||
/// adapter comes in handy:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read {
|
||||
/// // An adapter that ignores the first two columns
|
||||
/// let adapter = SuffixRowAdapter(fromIndex: 2)
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
|
||||
/// // Feeds the "consumed" column from "produced":
|
||||
/// let adapter = ColumnMapping(["consumed": "produced"])
|
||||
/// let sql = "SELECT 'Hello' AS produced"
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
///
|
||||
/// // [baz:3]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// }
|
||||
/// // [consumed:"Hello"]
|
||||
/// print(row)
|
||||
///
|
||||
/// // "Hello"
|
||||
/// print(row["consumed"])
|
||||
/// ```
|
||||
///
|
||||
/// The raw fetched columns are not lost (see ``Row/unadapted``):
|
||||
///
|
||||
/// ```swift
|
||||
/// // ▿ [consumed:"Hello"]
|
||||
/// // unadapted: [produced:"Hello"]
|
||||
/// print(row.debugDescription)
|
||||
///
|
||||
/// // [produced:"Hello"]
|
||||
/// print(row.unadapted)
|
||||
/// ```
|
||||
///
|
||||
/// There are several situations where row adapters are useful. Among them:
|
||||
///
|
||||
/// - Adapters help disambiguate columns with identical names, which may
|
||||
/// happen when you select columns from several tables.
|
||||
/// See ``splittingRowAdapters(columnCounts:)`` for some sample code.
|
||||
///
|
||||
/// - Adapters help when SQLite outputs unexpected column names, which may
|
||||
/// happen with some subqueries. See ``RenameColumnAdapter`` for
|
||||
/// an example.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Splitting a Row
|
||||
/// ### Splitting a Row into Chunks
|
||||
///
|
||||
/// - ``splittingRowAdapters(columnCounts:)``
|
||||
///
|
||||
/// ### Adding Scopes to an Adapter
|
||||
///
|
||||
/// - ``addingScopes(_:)``
|
||||
///
|
||||
/// ### Built-in Adapters
|
||||
///
|
||||
/// - ``ColumnMapping``
|
||||
@@ -222,9 +364,22 @@ extension RowAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/// EmptyRowAdapter is a row adapter that hides all columns.
|
||||
public struct EmptyRowAdapter: RowAdapter {
|
||||
/// Creates an EmptyRowAdapter
|
||||
/// `EmptyRowAdapter` is a row adapter that hides all columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let adapter = EmptyRowAdapter()
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c"
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
/// row.isEmpty // true
|
||||
/// ```
|
||||
///
|
||||
/// This limit adapter may turn out useful in some narrow use cases. You'll
|
||||
/// be happy to find it when you need it.
|
||||
public struct EmptyRowAdapter: RowAdapter, Sendable {
|
||||
/// Creates an `EmptyRowAdapter`.
|
||||
public init() { }
|
||||
|
||||
public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter {
|
||||
@@ -232,19 +387,28 @@ public struct EmptyRowAdapter: RowAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/// ColumnMapping is a row adapter that maps column names.
|
||||
/// `ColumnMapping` is a row adapter that maps column names.
|
||||
///
|
||||
/// let adapter = ColumnMapping(["foo": "bar"])
|
||||
/// let sql = "SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz"
|
||||
/// Build a `ColumnMapping` with a dictionary whose keys
|
||||
/// are adapted column names, and values the column names in the base row:
|
||||
///
|
||||
/// // [foo:"bar"]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
public struct ColumnMapping: RowAdapter {
|
||||
/// ```swift
|
||||
/// // Feeds "newA" from "a", and "newB" from "b":
|
||||
/// let adapter = ColumnMapping(["newA": "a", "newB": "b"])
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c"
|
||||
///
|
||||
/// // [newA:0, newB:1]
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
/// ```
|
||||
///
|
||||
/// Note that columns that are not present in the dictionary are not present
|
||||
/// in the resulting adapted row.
|
||||
public struct ColumnMapping: RowAdapter, Sendable {
|
||||
/// A dictionary from mapped column names to column names in a base row.
|
||||
let mapping: [String: String]
|
||||
|
||||
/// Creates a ColumnMapping with a dictionary from mapped column names to
|
||||
/// column names in a base row.
|
||||
/// Creates a `ColumnMapping` with a dictionary from mapped column names
|
||||
/// to column names in a base row.
|
||||
public init(_ mapping: [String: String]) {
|
||||
self.mapping = mapping
|
||||
}
|
||||
@@ -269,14 +433,18 @@ public struct ColumnMapping: RowAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/// SuffixRowAdapter is a row adapter that hides the first columns in a row.
|
||||
/// `SuffixRowAdapter` hides the leftmost columns in a row.
|
||||
///
|
||||
/// let adapter = SuffixRowAdapter(fromIndex: 2)
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
|
||||
/// For example:
|
||||
///
|
||||
/// // [baz:3]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
public struct SuffixRowAdapter: RowAdapter {
|
||||
/// ```swift
|
||||
/// let adapter = SuffixRowAdapter(fromIndex: 2)
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d"
|
||||
///
|
||||
/// // [c:2, d: 3]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
/// ```
|
||||
public struct SuffixRowAdapter: RowAdapter, Sendable {
|
||||
/// The suffix index
|
||||
let index: Int
|
||||
|
||||
@@ -294,14 +462,18 @@ public struct SuffixRowAdapter: RowAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/// RangeRowAdapter is a row adapter that only exposes a range of columns.
|
||||
/// `RangeRowAdapter` is a row adapter that only exposes a range of columns.
|
||||
///
|
||||
/// let adapter = RangeRowAdapter(1..<3)
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz, 4 as qux"
|
||||
/// For example:
|
||||
///
|
||||
/// // [bar:2 baz:3]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
public struct RangeRowAdapter: RowAdapter {
|
||||
/// ```swift
|
||||
/// let adapter = RangeRowAdapter(1..<3)
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d"
|
||||
///
|
||||
/// // [b:1 c:2]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// ```
|
||||
public struct RangeRowAdapter: RowAdapter, Sendable {
|
||||
/// The range
|
||||
let range: CountableRange<Int>
|
||||
|
||||
@@ -322,28 +494,65 @@ public struct RangeRowAdapter: RowAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/// `ScopeAdapter` is a row adapter that lets you define scopes on rows.
|
||||
/// `ScopeAdapter` is a row adapter that defines row scopes.
|
||||
///
|
||||
/// // Two adapters
|
||||
/// let fooAdapter = ColumnMapping(["value": "foo"])
|
||||
/// let barAdapter = ColumnMapping(["value": "bar"])
|
||||
/// `ScopeAdapter` does not change the columns and values of the fetched
|
||||
/// row. Instead, it defines *scopes* based on other adapter, which you
|
||||
/// access through the ``Row/scopes`` property of the fetched rows.
|
||||
///
|
||||
/// // Define scopes
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "foo": fooAdapter,
|
||||
/// "bar": barAdapter])
|
||||
/// For example:
|
||||
///
|
||||
/// // Fetch
|
||||
/// let sql = "SELECT 'foo' AS foo, 'bar' AS bar"
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
/// ```swift
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "left": RangeRowAdapter(0..<2),
|
||||
/// "right": RangeRowAdapter(2..<4)])
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d"
|
||||
///
|
||||
/// // Scoped rows:
|
||||
/// if let fooRow = row.scopes["foo"] {
|
||||
/// fooRow["value"] // "foo"
|
||||
/// }
|
||||
/// if let barRow = row.scopes["bar"] {
|
||||
/// barRow["value"] // "bar"
|
||||
/// }
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
///
|
||||
/// row // [a:0 b:1 c:2 d:3]
|
||||
/// row.scopes["left"] // [a:0 b:1]
|
||||
/// row.scopes["right"] // [c:2 d:3]
|
||||
/// row.scopes["missing"] // nil
|
||||
/// ```
|
||||
///
|
||||
/// Scopes can be nested:
|
||||
///
|
||||
/// ```swift
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "left": ScopeAdapter([
|
||||
/// "left": RangeRowAdapter(0..<1),
|
||||
/// "right": RangeRowAdapter(1..<2)]),
|
||||
/// "right": ScopeAdapter([
|
||||
/// "left": RangeRowAdapter(2..<3),
|
||||
/// "right": RangeRowAdapter(3..<4)])
|
||||
/// ])
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d"
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
///
|
||||
/// let leftRow = row.scopes["left"]!
|
||||
/// leftRow.scopes["left"] // [a:0]
|
||||
/// leftRow.scopes["right"] // [b:1]
|
||||
///
|
||||
/// let rightRow = row.scopes["right"]!
|
||||
/// rightRow.scopes["left"] // [c:2]
|
||||
/// rightRow.scopes["right"] // [d:3]
|
||||
/// ```
|
||||
///
|
||||
/// Any adapter can be extended with scopes, with
|
||||
/// ``RowAdapter/addingScopes(_:)``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let baseAdapter = RangeRowAdapter(0..<2)
|
||||
/// let adapter = baseAdapter.addingScopes([
|
||||
/// "remainder": SuffixRowAdapter(fromIndex: 2)
|
||||
/// ])
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d"
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
///
|
||||
/// row // [a:0 b:1]
|
||||
/// row.scopes["remainder"] // [c:2 d:3]
|
||||
/// ```
|
||||
public struct ScopeAdapter: RowAdapter {
|
||||
|
||||
/// The base adapter
|
||||
@@ -363,7 +572,7 @@ public struct ScopeAdapter: RowAdapter {
|
||||
///
|
||||
/// - parameter scopes: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
public init(_ scopes: [String: RowAdapter]) {
|
||||
public init(_ scopes: [String: any RowAdapter]) {
|
||||
// Use SuffixRowAdapter(fromIndex: 0) as the identity adapter
|
||||
self.init(base: SuffixRowAdapter(fromIndex: 0), scopes: scopes)
|
||||
}
|
||||
@@ -423,11 +632,29 @@ struct ChainedAdapter: RowAdapter {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let adapter = RenameColumnAdapter { $0 + "rrr" }
|
||||
/// let sql = "SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz"
|
||||
/// ```swift
|
||||
/// let adapter = RenameColumnAdapter { column in column + "rrr" }
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c"
|
||||
///
|
||||
/// // [foorrr:"foo", barrrr:"bar", bazrrr:"baz"]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// // [arrr:0, brrr:1, crrr:2]
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
/// ```
|
||||
///
|
||||
/// This adapter is useful when subqueries contain duplicated column names:
|
||||
///
|
||||
/// ```swift
|
||||
/// let sql = "SELECT * FROM (SELECT 1 AS id, 2 AS id)"
|
||||
///
|
||||
/// // Prints ["id", "id:1"]
|
||||
/// // Note the "id:1" column, generated by SQLite.
|
||||
/// let row = try Row.fetchOne(db, sql: sql)!
|
||||
/// print(Array(row.columnNames))
|
||||
///
|
||||
/// // Drop the `:...` suffix, and prints ["id", "id"]
|
||||
/// let adapter = RenameColumnAdapter { String($0.prefix(while: { $0 != ":" })) }
|
||||
/// let adaptedRow = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
/// print(Array(adaptedRow.columnNames))
|
||||
/// ```
|
||||
public struct RenameColumnAdapter: RowAdapter {
|
||||
let transform: (String) -> String
|
||||
|
||||
|
||||
+2
-2
@@ -121,8 +121,8 @@ public struct SQL {
|
||||
fileprivate func qualified(with alias: TableAlias) -> Element {
|
||||
switch self {
|
||||
case .sql:
|
||||
/// A raw SQL string can't be qualified with a table alias,
|
||||
/// because we can't parse it.
|
||||
// A raw SQL string can't be qualified with a table alias,
|
||||
// because we can't parse it.
|
||||
return self
|
||||
case .subquery:
|
||||
// Subqueries don't need table alias
|
||||
|
||||
@@ -206,9 +206,9 @@ extension SQLRequest: FetchRequest {
|
||||
switch cache {
|
||||
case .none:
|
||||
statement = try db.makeStatement(sql: sql)
|
||||
case .public?:
|
||||
case .public:
|
||||
statement = try db.cachedStatement(sql: sql)
|
||||
case .internal?:
|
||||
case .internal:
|
||||
statement = try db.internalCachedStatement(sql: sql)
|
||||
}
|
||||
try statement.setArguments(context.arguments)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import Foundation
|
||||
|
||||
/// A class that serializes accesses to a database.
|
||||
/// A class that serializes accesses to an SQLite connection.
|
||||
final class SerializedDatabase {
|
||||
/// The database connection
|
||||
private let db: Database
|
||||
@@ -14,6 +14,9 @@ final class SerializedDatabase {
|
||||
/// The dispatch queue
|
||||
private let queue: DispatchQueue
|
||||
|
||||
/// If true, overrides `configuration.allowsUnsafeTransactions`.
|
||||
private var allowsUnsafeTransactions = false
|
||||
|
||||
init(
|
||||
path: String,
|
||||
configuration: Configuration = Configuration(),
|
||||
@@ -76,10 +79,25 @@ final class SerializedDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a block the serialized dispatch queue, and
|
||||
/// returns its result.
|
||||
/// Executes database operations, returns their result after they have
|
||||
/// finished executing, and allows or forbids long-lived transactions.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
/// This method is not reentrant.
|
||||
///
|
||||
/// - parameter allowingLongLivedTransaction: When true, the
|
||||
/// ``Configuration/allowsUnsafeTransactions`` configuration flag is
|
||||
/// ignored until this method is called again with false.
|
||||
func sync<T>(allowingLongLivedTransaction: Bool, _ body: (Database) throws -> T) rethrows -> T {
|
||||
try sync { db in
|
||||
self.allowsUnsafeTransactions = allowingLongLivedTransaction
|
||||
return try body(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes database operations, and returns their result after they
|
||||
/// have finished executing.
|
||||
///
|
||||
/// This method is not reentrant.
|
||||
func sync<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
// Three different cases:
|
||||
//
|
||||
@@ -122,8 +140,23 @@ final class SerializedDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a block the serialized dispatch queue, and
|
||||
/// returns its result.
|
||||
/// Executes database operations, returns their result after they have
|
||||
/// finished executing, and allows or forbids long-lived transactions.
|
||||
///
|
||||
/// This method is reentrant.
|
||||
///
|
||||
/// - parameter allowingLongLivedTransaction: When true, the
|
||||
/// ``Configuration/allowsUnsafeTransactions`` configuration flag is
|
||||
/// ignored until this method is called again with false.
|
||||
func reentrantSync<T>(allowingLongLivedTransaction: Bool, _ body: (Database) throws -> T) rethrows -> T {
|
||||
try reentrantSync { db in
|
||||
self.allowsUnsafeTransactions = allowingLongLivedTransaction
|
||||
return try body(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes database operations, and returns their result after they
|
||||
/// have finished executing.
|
||||
///
|
||||
/// This method is reentrant.
|
||||
func reentrantSync<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
@@ -189,7 +222,7 @@ final class SerializedDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Asynchronously executes a block in the serialized dispatch queue.
|
||||
/// Schedules database operations for execution, and returns immediately.
|
||||
func async(_ block: @escaping (Database) -> Void) {
|
||||
queue.async {
|
||||
block(self.db)
|
||||
@@ -242,7 +275,7 @@ final class SerializedDatabase {
|
||||
line: UInt = #line)
|
||||
{
|
||||
GRDBPrecondition(
|
||||
configuration.allowsUnsafeTransactions || !db.isInsideTransaction,
|
||||
allowsUnsafeTransactions || configuration.allowsUnsafeTransactions || !db.isInsideTransaction,
|
||||
message(),
|
||||
file: file,
|
||||
line: line)
|
||||
|
||||
+355
-146
@@ -25,59 +25,6 @@ extension String {
|
||||
}
|
||||
}
|
||||
|
||||
/// A prepared statement.
|
||||
///
|
||||
/// You create prepared statements from a ``Database`` instance. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// DELETE FROM player WHERE id = ?
|
||||
/// """)
|
||||
/// try statement.execute(arguments: [1])!
|
||||
/// try statement.execute(arguments: [12])!
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// To fetch rows and values from a prepared statement, use a fetching method of
|
||||
///``Row``, ``DatabaseValueConvertible``, or ``FetchableRecord``:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// SELECT name FROM player WHERE id = ?
|
||||
/// """)
|
||||
/// let name1 = try String.fetchOne(statement, arguments: [1])!
|
||||
/// let name2 = try String.fetchOne(statement, arguments: [12])!
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/stmt.html>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Executing a Prepared Statement
|
||||
///
|
||||
/// - ``execute(arguments:)``
|
||||
///
|
||||
/// ### Arguments
|
||||
///
|
||||
/// - ``arguments``
|
||||
/// - ``setArguments(_:)``
|
||||
/// - ``setUncheckedArguments(_:)``
|
||||
/// - ``validateArguments(_:)``
|
||||
/// - ``StatementArguments``
|
||||
///
|
||||
/// ### Statement Informations
|
||||
///
|
||||
/// - ``columnCount``
|
||||
/// - ``columnNames``
|
||||
/// - ``databaseRegion``
|
||||
/// - ``index(ofColumn:)``
|
||||
/// - ``isReadonly``
|
||||
/// - ``sql``
|
||||
/// - ``sqliteStatement``
|
||||
/// - ``SQLiteStatement``
|
||||
public final class Statement {
|
||||
enum TransactionEffect {
|
||||
case beginTransaction
|
||||
@@ -95,20 +42,35 @@ public final class Statement {
|
||||
public var sql: String {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
|
||||
// trim white space and semicolumn for homogeneous output
|
||||
// trim white space and semicolon for homogeneous output
|
||||
return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
|
||||
}
|
||||
|
||||
/// The column names, ordered from left to right.
|
||||
public lazy var columnNames: [String] = {
|
||||
// swiftlint:disable:next redundant_self_in_closure
|
||||
let sqliteStatement = self.sqliteStatement
|
||||
return (0..<CInt(self.columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
|
||||
return (0..<CInt(columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
|
||||
}()
|
||||
|
||||
// The database region is reported by `sqlite3_set_authorizer`, and maybe
|
||||
// refined in `SQLQueryGenerator.makeStatement(_:)` when we have enough
|
||||
// information about the statement.
|
||||
/// The database region that the statement looks into.
|
||||
///
|
||||
/// The returned region describes the tables and columns read by
|
||||
/// the statement. It does not describe the columns that the statement
|
||||
/// writes into. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Reads score, writes bonus
|
||||
/// let statement = db.makeStatement(sql: """
|
||||
/// UPDATE player SET bonus = 0 WHERE score = 0
|
||||
/// """)
|
||||
///
|
||||
/// // Prints "player(score)"
|
||||
/// print(statement.databaseRegion)
|
||||
/// ```
|
||||
public internal(set) var databaseRegion = DatabaseRegion()
|
||||
|
||||
/// If true, the database schema cache gets invalidated after this statement
|
||||
@@ -129,8 +91,8 @@ public final class Statement {
|
||||
sqlite3_stmt_readonly(sqliteStatement) != 0
|
||||
}
|
||||
|
||||
/// A boolean value indicating if the statement deletes some rows.
|
||||
var isDeleteStatement: Bool {
|
||||
/// A boolean value indicating if the statement can delete some rows.
|
||||
var canDeleteRows: Bool {
|
||||
authorizerEventKinds.contains(where: \.isDelete)
|
||||
}
|
||||
|
||||
@@ -140,7 +102,7 @@ public final class Statement {
|
||||
/// Cache for index(ofColumn:). Keys are lowercase.
|
||||
private lazy var columnIndexes: [String: Int] = {
|
||||
Dictionary(
|
||||
self.columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
|
||||
columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
|
||||
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
|
||||
}()
|
||||
|
||||
@@ -157,8 +119,8 @@ public final class Statement {
|
||||
/// - throws: DatabaseError in case of compilation error.
|
||||
required init?(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
statementStart: UnsafePointer<CChar>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<CChar>?>,
|
||||
prepFlags: CUnsignedInt) throws
|
||||
{
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
@@ -175,7 +137,7 @@ public final class Statement {
|
||||
database.sqliteConnection, statementStart, -1, prepFlags,
|
||||
&sqliteStatement, statementEnd)
|
||||
#else
|
||||
if #available(iOS 12.0, OSX 10.14, tvOS 12.0, watchOS 5.0, *) {
|
||||
if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { // SQLite 3.20+
|
||||
code = sqlite3_prepare_v3(
|
||||
database.sqliteConnection, statementStart, -1, prepFlags,
|
||||
&sqliteStatement, statementEnd)
|
||||
@@ -209,25 +171,100 @@ public final class Statement {
|
||||
|
||||
// MARK: Arguments
|
||||
|
||||
private var argumentsNeedValidation = true
|
||||
/// Whether arguments are valid and bound inside the SQLite statement.
|
||||
///
|
||||
/// If true, arguments are considered valid, and they are bound in
|
||||
/// the SQLite statement:
|
||||
///
|
||||
/// - **Valid**: Arguments match the statement expectations, or the user has
|
||||
/// called ``setUncheckedArguments(_:)``.
|
||||
/// - **Bound**: The SQLite bindings are set. String and blob arguments
|
||||
/// are bound with SQLITE_TRANSIENT (copied and managed by SQLite).
|
||||
///
|
||||
/// When false, arguments have not been validated yet, or they are
|
||||
/// not bound.
|
||||
///
|
||||
/// - Not validated yet: this is the initial default (non-validated
|
||||
/// empty arguments)
|
||||
///
|
||||
/// ```swift
|
||||
/// // Default arguments are empty, argumentsAreValidAndBound is
|
||||
/// // false. The statement needs one argument.
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// INSERT INTO t VALUES (?)
|
||||
/// """)
|
||||
///
|
||||
/// // Because argumentsAreValidAndBound is false, we validate the
|
||||
/// // empty arguments, and throw SQLITE_MISUSE: wrong number
|
||||
/// // of statement arguments.
|
||||
/// try statement.execute()
|
||||
/// ```
|
||||
///
|
||||
/// - Not bound: this is the case after we have performed an optimized
|
||||
/// execution with temporary bindings that avoid copying strings
|
||||
/// and blobs:
|
||||
///
|
||||
/// ```swift
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// INSERT INTO t VALUES (?)
|
||||
/// """)
|
||||
/// // Arguments are set, and execution is performed with
|
||||
/// // temporary bindings.
|
||||
/// try statement.execute(arguments: ["Hello"])
|
||||
/// // <- Here statement.arguments is ["Hello"]
|
||||
/// // <- Here statement.argumentsAreValidAndBound is false
|
||||
/// ```
|
||||
///
|
||||
/// See `withArguments(_:do:)`.
|
||||
private var argumentsAreValidAndBound = false
|
||||
|
||||
/// The statement arguments. They may be bound, or not, in the SQLite
|
||||
/// statement. See `argumentsAreValidAndBound`.
|
||||
private var _arguments = StatementArguments()
|
||||
|
||||
lazy var sqliteArgumentCount: Int = {
|
||||
Int(sqlite3_bind_parameter_count(self.sqliteStatement))
|
||||
Int(sqlite3_bind_parameter_count(sqliteStatement))
|
||||
}()
|
||||
|
||||
// Returns ["id", nil", "name"] for "INSERT INTO table VALUES (:id, ?, :name)"
|
||||
// Returns ["id", nil, "name"] for "INSERT INTO table VALUES (:id, ?, :name)"
|
||||
fileprivate lazy var sqliteArgumentNames: [String?] = {
|
||||
(0..<CInt(self.sqliteArgumentCount)).map {
|
||||
guard let cString = sqlite3_bind_parameter_name(self.sqliteStatement, $0 + 1) else {
|
||||
(1..<CInt(sqliteArgumentCount + 1)).map {
|
||||
guard let cString = sqlite3_bind_parameter_name(sqliteStatement, $0) else {
|
||||
return nil
|
||||
}
|
||||
return String(String(cString: cString).dropFirst()) // Drop initial ":", "@", "$"
|
||||
return String(cString: cString + 1) // Drop initial ":", "@", "$"
|
||||
}
|
||||
}()
|
||||
|
||||
/// The statement arguments.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // This statement expects two arguments
|
||||
/// let statement = try db.makeUpdateArgument(sql: """
|
||||
/// INSERT INTO player (id, name) VALUES (?, ?)
|
||||
/// """)
|
||||
///
|
||||
/// // Set arguments
|
||||
/// statement.arguments = [1, "Arthur"]
|
||||
///
|
||||
/// // Prints [1, "Arthur"]
|
||||
/// print(statement.arguments)
|
||||
/// ```
|
||||
///
|
||||
/// If is a programmer error to set arguments that do not provide all
|
||||
/// values expected by the statement:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Fatal error
|
||||
/// statement.arguments = [1]
|
||||
/// statement.arguments = [1, "Arthur", Date()]
|
||||
/// ```
|
||||
///
|
||||
/// Prefer ``setArguments(_:)`` when you are not sure that
|
||||
/// arguments match, because it throws an error instead of raising a
|
||||
/// fatal error.
|
||||
public var arguments: StatementArguments {
|
||||
get { _arguments }
|
||||
set {
|
||||
@@ -237,12 +274,13 @@ public final class Statement {
|
||||
}
|
||||
}
|
||||
|
||||
/// Throws a ``DatabaseError`` of code `SQLITE_ERROR` if arguments don't
|
||||
/// fill all statement arguments.
|
||||
/// Throws a ``DatabaseError`` of code `SQLITE_ERROR` if the provided
|
||||
/// arguments do not provide all values expected by the statement.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // This statement expects two arguments
|
||||
/// let statement = try db.makeUpdateArgument(sql: """
|
||||
/// INSERT INTO player (id, name) VALUES (?, ?)
|
||||
/// """)
|
||||
@@ -251,7 +289,8 @@ public final class Statement {
|
||||
/// statement.validateArguments([1, "Arthur"])
|
||||
///
|
||||
/// // Throws
|
||||
/// statement.validateArguments([1])
|
||||
/// try statement.setArguments([1])
|
||||
/// try statement.setArguments([1, "Arthur", Date()])
|
||||
/// ```
|
||||
///
|
||||
/// See also ``setArguments(_:)``.
|
||||
@@ -264,12 +303,13 @@ public final class Statement {
|
||||
|
||||
/// Set arguments without any validation. Trades safety for performance.
|
||||
///
|
||||
/// Only call this method if you are sure input arguments match all expected
|
||||
/// arguments of the statement.
|
||||
/// Only call this method if you are sure input arguments provide all
|
||||
/// values expected by the statement.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // This statement expects two arguments
|
||||
/// let statement = try db.makeUpdateArgument(sql: """
|
||||
/// INSERT INTO player (id, name) VALUES (?, ?)
|
||||
/// """)
|
||||
@@ -278,23 +318,24 @@ public final class Statement {
|
||||
/// statement.setUncheckedArguments([1, "Arthur"])
|
||||
///
|
||||
/// // OK
|
||||
/// let arguments: StatementArguments = ... // some untrusted arguments
|
||||
/// let arguments = ... // some untrusted arguments
|
||||
/// try statement.validateArguments(arguments)
|
||||
/// statement.setUncheckedArguments(arguments)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// statement.setUncheckedArguments([1])
|
||||
/// statement.setUncheckedArguments([1, "Arthur", Date()])
|
||||
/// ```
|
||||
public func setUncheckedArguments(_ arguments: StatementArguments) {
|
||||
_arguments = arguments
|
||||
argumentsNeedValidation = false
|
||||
|
||||
// Reset and bind arguments
|
||||
try! reset()
|
||||
_arguments = arguments
|
||||
argumentsAreValidAndBound = true
|
||||
clearBindings()
|
||||
|
||||
var valuesIterator = arguments.values.makeIterator()
|
||||
for (index, argumentName) in zip(CInt(1)..., sqliteArgumentNames) {
|
||||
if let argumentName = argumentName, let value = arguments.namedValues[argumentName] {
|
||||
if let argumentName, let value = arguments.namedValues[argumentName] {
|
||||
bind(value, at: index)
|
||||
} else if let value = valuesIterator.next() {
|
||||
bind(value, at: index)
|
||||
@@ -302,14 +343,16 @@ public final class Statement {
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the statement arguments.
|
||||
/// Validates and sets the statement arguments.
|
||||
///
|
||||
/// This method throws a ``DatabaseError`` of code `SQLITE_ERROR` if
|
||||
/// arguments don't fill all statement arguments.
|
||||
/// This method throws a ``DatabaseError`` of code `SQLITE_MISUSE` if
|
||||
/// the provided arguments do not provide all values expected by
|
||||
/// the statement.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // This statement expects two arguments
|
||||
/// let statement = try db.makeUpdateArgument(sql: """
|
||||
/// INSERT INTO player (id, name) VALUES (?, ?)
|
||||
/// """)
|
||||
@@ -319,6 +362,7 @@ public final class Statement {
|
||||
///
|
||||
/// // Throws
|
||||
/// try statement.setArguments([1])
|
||||
/// try statement.setArguments([1, "Arthur", Date()])
|
||||
/// ```
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` if `arguments` don't fit the expected ones.
|
||||
@@ -327,16 +371,43 @@ public final class Statement {
|
||||
var consumedArguments = arguments
|
||||
let bindings = try consumedArguments.extractBindings(forStatement: self, allowingRemainingValues: false)
|
||||
|
||||
// Apply
|
||||
_arguments = arguments
|
||||
argumentsNeedValidation = false
|
||||
// Reset and bind arguments
|
||||
try reset()
|
||||
_arguments = arguments
|
||||
argumentsAreValidAndBound = true
|
||||
clearBindings()
|
||||
|
||||
for (index, dbValue) in zip(CInt(1)..., bindings) {
|
||||
bind(dbValue, at: index)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets, sets arguments, and calls the given closure after performing
|
||||
/// temporary bindings that avoid copying strings and blobs.
|
||||
///
|
||||
/// The bindings are valid only during the execution of this method.
|
||||
/// After it returns, the SQLite statement bindings are cleared (but the
|
||||
/// statement arguments are set).
|
||||
func withArguments<T>(_ arguments: StatementArguments, do body: () throws -> T) throws -> T {
|
||||
// Validate
|
||||
var consumedArguments = arguments
|
||||
let bindings = try consumedArguments.extractBindings(forStatement: self, allowingRemainingValues: false)
|
||||
|
||||
// Reset and bind arguments (temporarily)
|
||||
try reset()
|
||||
_arguments = arguments
|
||||
argumentsAreValidAndBound = false
|
||||
clearBindings()
|
||||
|
||||
defer {
|
||||
// Don't leave the SQLite statement in an invalid state
|
||||
// (temporary bindings that point to undefined memory).
|
||||
clearBindings()
|
||||
}
|
||||
|
||||
return try withBindings(bindings, to: sqliteStatement, do: body)
|
||||
}
|
||||
|
||||
// 1-based index
|
||||
func bind(_ value: some StatementBinding, at index: CInt) {
|
||||
let code = value.bind(to: sqliteStatement, at: index)
|
||||
@@ -369,14 +440,44 @@ public final class Statement {
|
||||
}
|
||||
}
|
||||
|
||||
func reset(withArguments arguments: StatementArguments?) throws {
|
||||
// Force arguments validity: it is a programmer error to provide
|
||||
// arguments that do not match the statement.
|
||||
if let arguments = arguments {
|
||||
try setArguments(arguments)
|
||||
} else if argumentsNeedValidation {
|
||||
/// Convenience method that resets, sets arguments if needed, and checks
|
||||
/// arguments validity.
|
||||
///
|
||||
/// - parameter newArguments: if not nil, this method sets arguments.
|
||||
func prepareExecution(withArguments newArguments: StatementArguments? = nil) throws {
|
||||
if let newArguments {
|
||||
try setArguments(newArguments) // calls reset()
|
||||
return
|
||||
}
|
||||
|
||||
if argumentsAreValidAndBound {
|
||||
try reset()
|
||||
try validateArguments(self.arguments)
|
||||
} else {
|
||||
// Arguments needs to be validated, or bound.
|
||||
if arguments.isEmpty {
|
||||
// Only reset and perform validation.
|
||||
try reset()
|
||||
try validateArguments(arguments)
|
||||
} else {
|
||||
// The `setArguments` method binds and validates, and that's
|
||||
// exactly what we want to do.
|
||||
//
|
||||
// To get there, perform statement.execute() after
|
||||
// statement.execute(arguments:):
|
||||
//
|
||||
// // Step 1
|
||||
// // Optimized execution with temporary bindings in order
|
||||
// // to avoid copying strings and blobs: after execution,
|
||||
// // arguments are set, but bindings have been cleared,
|
||||
// // and argumentsAreValidAndBound is false.
|
||||
// try statement.execute(arguments: StatementArguments(person)!)
|
||||
//
|
||||
// // Step 2 (we are here). Stop using temporary
|
||||
// // bindings because user explicitly opt ins for
|
||||
// // permanent ones.
|
||||
// try statement.execute()
|
||||
try setArguments(arguments) // calls reset()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -385,35 +486,83 @@ public final class Statement {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// try dbQueue.write { db in
|
||||
/// // Statement without argument
|
||||
/// let createTableStatement = try db.makeStatement(sql: """
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// CREATE TABLE player (
|
||||
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
/// name TEXT NOT NULL
|
||||
/// )
|
||||
/// """)
|
||||
/// try createTableStatement.execute()
|
||||
/// try statement.execute()
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// // Statement with argument
|
||||
/// let insertStatement = try db.makeStatement(sql: """
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?)
|
||||
/// """)
|
||||
///
|
||||
/// // Set argument and execute
|
||||
/// try insertStatement.setArguments(["Arthur"])
|
||||
/// try insertStatement.execute()
|
||||
/// try statement.setArguments(["Arthur"])
|
||||
/// try statement.execute()
|
||||
///
|
||||
/// // Set argument and execute in one shot
|
||||
/// try insertStatement.execute(arguments: ["Barbara"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When arguments are set at the moment of execution, with an non-nil
|
||||
/// `arguments` parameter, it is assumed that the statement won't be
|
||||
/// reused with the same arguments. When the number of arguments is
|
||||
/// small, execution is performed with temporary SQLite bindings that
|
||||
/// avoid copying strings and blobs arguments.
|
||||
///
|
||||
/// For more information, see [`SQLITE_STATIC` and `SQLITE_TRANSIENT`](https://www.sqlite.org/c3ref/c_static.html).
|
||||
/// Compare:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Uses SQLITE_STATIC if there are few arguments,
|
||||
/// // SQLITE_TRANSIENT otherwise.
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// // Always uses SQLITE_TRANSIENT
|
||||
/// try statement.setArguments(["Arthur"])
|
||||
/// try statement.execute()
|
||||
/// ```
|
||||
///
|
||||
/// Both techniques have the same results, but when you care about
|
||||
/// performances, monitor your application in order to make the
|
||||
/// best choice.
|
||||
///
|
||||
/// - parameter arguments: Optional statement arguments.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func execute(arguments: StatementArguments? = nil) throws {
|
||||
try reset(withArguments: arguments)
|
||||
if let arguments {
|
||||
// Assume that the statement won't be reused with the same arguments.
|
||||
//
|
||||
// Avoid a stack overflow, and don't perform an unbounded nesting
|
||||
// of `withBinding(to:at:do:)` methods: only use temporary bindings
|
||||
// for less than 20 arguments. This number 20 is completely
|
||||
// arbitrary!
|
||||
// See <https://forums.swift.org/t/avoiding-stack-overflow-when-nesting-string-withcstring-how-to-handle-an-arbitrary-number-of-temp-values-in-general/63663>
|
||||
if sqliteArgumentCount <= 20 {
|
||||
// Perform an optimized execution with temporary bindings
|
||||
// in order to avoid copying strings and blobs.
|
||||
try withArguments(arguments) {
|
||||
try executeAllSteps()
|
||||
}
|
||||
} else {
|
||||
try setArguments(arguments)
|
||||
try executeAllSteps()
|
||||
}
|
||||
} else {
|
||||
try prepareExecution()
|
||||
try executeAllSteps()
|
||||
}
|
||||
}
|
||||
|
||||
private func executeAllSteps() throws {
|
||||
try database.statementWillExecute(self)
|
||||
|
||||
// Iterate all rows, since they may execute side effects.
|
||||
@@ -474,6 +623,11 @@ public final class Statement {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: statements must be used from
|
||||
// a serialized database access dispatch queue.
|
||||
@available(*, unavailable)
|
||||
extension Statement: Sendable { }
|
||||
|
||||
extension Statement: CustomStringConvertible {
|
||||
public var description: String {
|
||||
SchedulingWatchdog.allows(database) ? sql : "Statement"
|
||||
@@ -507,37 +661,47 @@ extension Statement {
|
||||
|
||||
/// A cursor that lazily iterates the results of a prepared ``Statement``.
|
||||
///
|
||||
/// To get a `DatabaseCursor` instance, use a fetching method of
|
||||
/// ``Row``, ``DatabaseValueConvertible``, ``FetchableRecord``,
|
||||
/// or ``FetchRequest``. For example:
|
||||
/// ## Overview
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// // A cursor of database rows,
|
||||
/// // built from a prepared statement
|
||||
/// let statement = try db.makeStatement(sql: "SELECT * FROM player")
|
||||
/// let rows = try Row.fetchCursor(statement)
|
||||
/// while let row = try rows.next() {
|
||||
/// let id: Int64 = row["id"]
|
||||
/// let name: String = row["name"]
|
||||
/// }
|
||||
/// To get a `DatabaseCursor` instance, use one of the `fetchCursor` methods.
|
||||
/// For example:
|
||||
///
|
||||
/// // A cursor of values,
|
||||
/// // built from an SQL string
|
||||
/// let scores = try Int.fetchCursor(db, sql: "SELECT score FROM player")
|
||||
/// while let score = try scores.next() {
|
||||
/// print(score)
|
||||
/// }
|
||||
/// - A cursor of ``Row`` built from a prepared ``Statement``:
|
||||
///
|
||||
/// // A cursor of players,
|
||||
/// // built from a QueryInterfaceRequest:
|
||||
/// let request = Player.all()
|
||||
/// let players = try request.fetchCursor(db)
|
||||
/// while let player = try players.next() {
|
||||
/// print(player.name, player.score)
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let statement = try db.makeStatement(sql: "SELECT * FROM player")
|
||||
/// let rows = try Row.fetchCursor(statement)
|
||||
/// while let row = try rows.next() {
|
||||
/// let id: Int64 = row["id"]
|
||||
/// let name: String = row["name"]
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
/// ```
|
||||
///
|
||||
/// - A cursor of `Int` built from an SQL string (see ``DatabaseValueConvertible``):
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let sql = "SELECT score FROM player"
|
||||
/// let scores = try Int.fetchCursor(db, sql: sql)
|
||||
/// while let score = try scores.next() {
|
||||
/// print(score)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - A cursor of `Player` records built from a request (see ``FetchableRecord`` and ``FetchRequest``):
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let request = Player.all()
|
||||
/// let players = try request.fetchCursor(db)
|
||||
/// while let player = try players.next() {
|
||||
/// print(player.name, player.score)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// A database cursor is valid only during the current database access (read or
|
||||
/// write). Do not store or escape a cursor for later use.
|
||||
@@ -624,7 +788,7 @@ final class StatementCursor: DatabaseCursor {
|
||||
self._statement = statement
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
try statement.reset(withArguments: arguments)
|
||||
try statement.prepareExecution(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -669,11 +833,50 @@ public protocol StatementBinding {
|
||||
/// Binds a statement argument.
|
||||
///
|
||||
/// - parameter sqliteStatement: An SQLite statement.
|
||||
/// - parameter index: 1-based index to statement arguments
|
||||
/// - parameter index: 1-based index to statement arguments.
|
||||
/// - returns: the code returned by the `sqlite3_bind_xxx` function.
|
||||
func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt
|
||||
}
|
||||
|
||||
/// Helper function for `withBinding(to:at:do:)` methods.
|
||||
func checkBindingSuccess(code: CInt, sqliteStatement: SQLiteStatement) throws {
|
||||
if code == SQLITE_OK { return }
|
||||
let message = String(cString: sqlite3_errmsg(sqlite3_db_handle(sqliteStatement)))
|
||||
let sql = String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
|
||||
throw DatabaseError(resultCode: code, message: message, sql: sql)
|
||||
}
|
||||
|
||||
/// Calls the given closure after performing temporary bindings that avoid
|
||||
/// copying strings and blobs.
|
||||
///
|
||||
/// The bindings are valid only during the execution of this method.
|
||||
///
|
||||
/// - parameter bindings: The bindings
|
||||
/// - parameter sqliteStatement: The SQLite statement
|
||||
/// - parameter index: The index of the first binding.
|
||||
/// - parameter body: The closure to execute when arguments are bound.
|
||||
@usableFromInline
|
||||
func withBindings<C, T>(
|
||||
_ bindings: C,
|
||||
to sqliteStatement: SQLiteStatement,
|
||||
from index: CInt = 1,
|
||||
do body: () throws -> T)
|
||||
throws -> T
|
||||
where C: Collection, C.Element == DatabaseValue
|
||||
{
|
||||
guard let binding = bindings.first else {
|
||||
return try body()
|
||||
}
|
||||
|
||||
return try binding.withBinding(to: sqliteStatement, at: index) {
|
||||
try withBindings(
|
||||
bindings.dropFirst(),
|
||||
to: sqliteStatement,
|
||||
from: index + 1,
|
||||
do: body)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - StatementArguments
|
||||
|
||||
/// An instance of `StatementArguments` provides the values for argument
|
||||
@@ -689,9 +892,9 @@ public protocol StatementBinding {
|
||||
/// - `@AAAA` (e.g. `@name`): named argument
|
||||
/// - `$AAAA` (e.g. `$name`): named argument
|
||||
///
|
||||
/// GRDB does not allow to distinguish between the `:AAAA`, `@AAAA`, and `$AAAA`
|
||||
/// syntaxes. You are encouraged to write named arguments with a
|
||||
/// colon prefix: `:name`.
|
||||
/// All forms are supported, but GRDB does not allow to distinguish between
|
||||
/// the `:AAAA`, `@AAAA`, and `$AAAA` syntaxes. You are encouraged to write
|
||||
/// named arguments with a colon prefix: `:name`.
|
||||
///
|
||||
/// ## Positional Arguments
|
||||
///
|
||||
@@ -833,7 +1036,7 @@ public struct StatementArguments: Hashable {
|
||||
/// The result is nil unless all array elements conform to the
|
||||
/// ``DatabaseValueConvertible`` protocol.
|
||||
public init?(_ array: [Any]) {
|
||||
var values = [DatabaseValueConvertible?]()
|
||||
var values = [(any DatabaseValueConvertible)?]()
|
||||
for value in array {
|
||||
guard let dbValue = DatabaseValue(value: value) else {
|
||||
return nil
|
||||
@@ -1110,36 +1313,42 @@ public struct StatementArguments: Hashable {
|
||||
allowingRemainingValues: Bool)
|
||||
throws -> [DatabaseValue]
|
||||
{
|
||||
let initialValuesCount = values.count
|
||||
var iterator = values.makeIterator()
|
||||
var consumedValuesCount = 0
|
||||
let bindings = try statement.sqliteArgumentNames.map { argumentName -> DatabaseValue in
|
||||
if let argumentName = argumentName {
|
||||
if let argumentName {
|
||||
if let dbValue = namedValues[argumentName] {
|
||||
return dbValue
|
||||
} else if values.isEmpty {
|
||||
} else if let value = iterator.next() {
|
||||
consumedValuesCount += 1
|
||||
return value
|
||||
} else {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: "missing statement argument: \(argumentName)",
|
||||
sql: statement.sql)
|
||||
} else {
|
||||
return values.removeFirst()
|
||||
}
|
||||
} else if let value = iterator.next() {
|
||||
consumedValuesCount += 1
|
||||
return value
|
||||
} else {
|
||||
if values.isEmpty {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: "wrong number of statement arguments: \(initialValuesCount)",
|
||||
sql: statement.sql)
|
||||
} else {
|
||||
return values.removeFirst()
|
||||
}
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: "wrong number of statement arguments: \(values.count)",
|
||||
sql: statement.sql)
|
||||
}
|
||||
}
|
||||
if !allowingRemainingValues && !values.isEmpty {
|
||||
if !allowingRemainingValues && iterator.next() != nil {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: "wrong number of statement arguments: \(initialValuesCount)",
|
||||
message: "wrong number of statement arguments: \(values.count)",
|
||||
sql: statement.sql)
|
||||
}
|
||||
if consumedValuesCount == values.count {
|
||||
values.removeAll()
|
||||
} else {
|
||||
values = Array(values[consumedValuesCount...])
|
||||
}
|
||||
return bindings
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#if os(Linux)
|
||||
#if canImport(string_h)
|
||||
import string_h
|
||||
#elseif os(Linux)
|
||||
import Glibc
|
||||
#elseif os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(visionOS)
|
||||
import Darwin
|
||||
#endif
|
||||
|
||||
/// `StatementAuthorizer` provides information about compiled database
|
||||
@@ -57,10 +61,10 @@ final class StatementAuthorizer {
|
||||
|
||||
private func authorize(
|
||||
_ actionCode: CInt,
|
||||
_ cString1: UnsafePointer<Int8>?,
|
||||
_ cString2: UnsafePointer<Int8>?,
|
||||
_ cString3: UnsafePointer<Int8>?,
|
||||
_ cString4: UnsafePointer<Int8>?)
|
||||
_ cString1: UnsafePointer<CChar>?,
|
||||
_ cString2: UnsafePointer<CChar>?,
|
||||
_ cString3: UnsafePointer<CChar>?,
|
||||
_ cString4: UnsafePointer<CChar>?)
|
||||
-> CInt
|
||||
{
|
||||
// Uncomment when debugging
|
||||
@@ -107,7 +111,7 @@ final class StatementAuthorizer {
|
||||
|
||||
case SQLITE_DELETE:
|
||||
if isDropStatement { return SQLITE_OK }
|
||||
guard let cString1 = cString1 else { return SQLITE_OK }
|
||||
guard let cString1 else { return SQLITE_OK }
|
||||
|
||||
// Deletions from sqlite_master and sqlite_temp_master are not like
|
||||
// other deletions: `sqlite3_update_hook` does not notify them, and
|
||||
@@ -137,7 +141,7 @@ final class StatementAuthorizer {
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_TRANSACTION:
|
||||
guard let cString1 = cString1 else { return SQLITE_OK }
|
||||
guard let cString1 else { return SQLITE_OK }
|
||||
if strcmp(cString1, "BEGIN") == 0 {
|
||||
transactionEffect = .beginTransaction
|
||||
} else if strcmp(cString1, "COMMIT") == 0 {
|
||||
@@ -148,7 +152,7 @@ final class StatementAuthorizer {
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_SAVEPOINT:
|
||||
guard let cString1 = cString1 else { return SQLITE_OK }
|
||||
guard let cString1 else { return SQLITE_OK }
|
||||
guard let name = cString2.map(String.init) else { return SQLITE_OK }
|
||||
if strcmp(cString1, "BEGIN") == 0 {
|
||||
transactionEffect = .beginSavepoint(name)
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
/// // Optimized
|
||||
/// let scores = Int.fetchAll(db, sql: "SELECT score FROM player")
|
||||
///
|
||||
/// let rows = Row.fetchCursor(db, sql: "SELECT * FROM player")
|
||||
/// let rows = try Row.fetchCursor(db, sql: "SELECT * FROM player")
|
||||
/// while let row = try rows.next() {
|
||||
/// // Optimized
|
||||
/// let int: Int = row[0]
|
||||
@@ -89,7 +89,7 @@ public protocol StatementColumnConvertible {
|
||||
///
|
||||
/// Do not check for `NULL` in your implementation of this method. Null
|
||||
/// database values are handled
|
||||
/// in ``fromStatement(_:atUncheckedIndex:)-2i8y6``.
|
||||
/// in ``StatementColumnConvertible/fromStatement(_:atUncheckedIndex:)-2i8y6``.
|
||||
///
|
||||
/// For example, here is the how Int64 adopts StatementColumnConvertible:
|
||||
///
|
||||
@@ -215,7 +215,7 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
|
||||
self._statement = statement
|
||||
if let adapter = adapter {
|
||||
if let adapter {
|
||||
// adapter may redefine the index of the leftmost column
|
||||
columnIndex = try CInt(adapter.baseColumnIndex(atIndex: 0, layout: statement))
|
||||
} else {
|
||||
@@ -223,7 +223,7 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
}
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
try statement.reset(withArguments: arguments)
|
||||
try statement.prepareExecution(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -241,6 +241,11 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: database cursors must be used from
|
||||
// a serialized database access dispatch queue.
|
||||
@available(*, unavailable)
|
||||
extension FastDatabaseValueCursor: Sendable { }
|
||||
|
||||
/// Types that adopt both DatabaseValueConvertible and
|
||||
/// StatementColumnConvertible can be efficiently initialized from
|
||||
/// database values.
|
||||
|
||||
@@ -42,6 +42,23 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
sqlite3_bind_blob(sqliteStatement, index, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls the given closure after binding a statement argument.
|
||||
///
|
||||
/// The binding is valid only during the execution of this method.
|
||||
///
|
||||
/// - parameter sqliteStatement: An SQLite statement.
|
||||
/// - parameter index: 1-based index to statement arguments.
|
||||
/// - parameter body: The closure to execute when argument is bound.
|
||||
func withBinding<T>(to sqliteStatement: SQLiteStatement, at index: CInt, do body: () throws -> T) throws -> T {
|
||||
try withUnsafeBytes {
|
||||
let code = sqlite3_bind_blob(
|
||||
sqliteStatement, index,
|
||||
$0.baseAddress, CInt($0.count), nil /* SQLITE_STATIC */)
|
||||
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
|
||||
return try body()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Conversions
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import Foundation
|
||||
|
||||
/// A database value that holds date components.
|
||||
public struct DatabaseDateComponents {
|
||||
public struct DatabaseDateComponents: Sendable {
|
||||
|
||||
/// The SQLite formats for date components.
|
||||
public enum Format: String {
|
||||
public enum Format: String, Sendable {
|
||||
|
||||
/// The format "yyyy-MM-dd".
|
||||
case YMD = "yyyy-MM-dd"
|
||||
@@ -75,7 +75,7 @@ extension DatabaseDateComponents: StatementColumnConvertible {
|
||||
}
|
||||
let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen
|
||||
let components = cString.withMemoryRebound(
|
||||
to: Int8.self,
|
||||
to: CChar.self,
|
||||
capacity: length + 1 /* trailing \0 */) { cString in
|
||||
SQLiteDateParser().components(cString: cString, length: length)
|
||||
}
|
||||
|
||||
@@ -136,7 +136,7 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer {
|
||||
/// cannot be converted to the requested type.
|
||||
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
|
||||
func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
|
||||
if let type = T.self as? DatabaseValueConvertible.Type {
|
||||
if let type = T.self as? any DatabaseValueConvertible.Type {
|
||||
// Prefer DatabaseValueConvertible decoding over Decodable.
|
||||
// This allows custom database decoding, such as decoding Date from
|
||||
// String, for example.
|
||||
@@ -179,11 +179,7 @@ extension DatabaseValueConvertible where Self: Decodable {
|
||||
guard let data = Data.fromDatabaseValue(databaseValue) else {
|
||||
return nil
|
||||
}
|
||||
let decoder = JSONDecoder()
|
||||
decoder.dataDecodingStrategy = .base64
|
||||
decoder.dateDecodingStrategy = .millisecondsSince1970
|
||||
decoder.nonConformingFloatDecodingStrategy = .throw
|
||||
return try? decoder.decode(Self.self, from: data)
|
||||
return try? databaseJSONDecoder().decode(Self.self, from: data)
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
|
||||
Loaded 100 of 406 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user