mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-06 05:28:44 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
786ab176c9 | ||
|
|
973af107da | ||
|
|
1911ef0172 | ||
|
|
d2e9b340c9 | ||
|
|
5b487d1722 | ||
|
|
a91da59448 | ||
|
|
2846254304 | ||
|
|
5fe765dd29 | ||
|
|
9815f44134 | ||
|
|
3f8969b88f | ||
|
|
4fc7a44a9d | ||
|
|
e132688e00 | ||
|
|
588df57840 | ||
|
|
4a8ca6fdc1 | ||
|
|
2bb2493731 | ||
|
|
c61949ceaf | ||
|
|
3fce1e00c9 | ||
|
|
2f2add1c49 | ||
|
|
697acb103f | ||
|
|
c830e43e8f | ||
|
|
834ef45ca6 | ||
|
|
279faa13e9 | ||
|
|
0309abca6f | ||
|
|
fedee67bda | ||
|
|
a6c3566aa5 | ||
|
|
52fa24e1c4 | ||
|
|
a7ecf41e3b | ||
|
|
e68e5f6265 | ||
|
|
aad5a9b060 | ||
|
|
aa064029ec | ||
|
|
e84060e01c | ||
|
|
f4f72ebb43 | ||
|
|
da51e81e38 | ||
|
|
247cbdd0d0 | ||
|
|
c528740154 | ||
|
|
37b357b050 | ||
|
|
18c376979d | ||
|
|
9cc4357a70 | ||
|
|
f2d35a052f | ||
|
|
221f378d10 | ||
|
|
06a8c8b940 | ||
|
|
eee80b421a | ||
|
|
f6e22c3636 | ||
|
|
20d77fbba5 | ||
|
|
0393ebe012 | ||
|
|
2beddcf77b | ||
|
|
e784ebbcdd | ||
|
|
30ee538dbd | ||
|
|
7939ba6e05 | ||
|
|
2785e69fc1 | ||
|
|
d472c1696d | ||
|
|
d9cfa71fc7 | ||
|
|
715e12912b | ||
|
|
b182fe27f6 | ||
|
|
5594b33933 | ||
|
|
059b8800f6 | ||
|
|
9f687b1848 | ||
|
|
a4a05b1f0a | ||
|
|
1a7b0b0626 | ||
|
|
4c467e46cf | ||
|
|
fa71edeb07 | ||
|
|
4ff436371d | ||
|
|
9d8fa0bc5a | ||
|
|
1a8ecd7889 | ||
|
|
f6614fdfda | ||
|
|
a6055df756 | ||
|
|
5af91c5eab | ||
|
|
41974c4a46 | ||
|
|
f001b5bd76 | ||
|
|
28cf457853 | ||
|
|
8ccc23333d | ||
|
|
d95954d980 | ||
|
|
3506881c2a | ||
|
|
51d127c378 | ||
|
|
2d5dd7ef63 | ||
|
|
ef23ba55a1 | ||
|
|
ffdbf2f3f1 | ||
|
|
56cad83f55 | ||
|
|
719f33f7a7 | ||
|
|
700ffacdb1 | ||
|
|
a6ef4ed55c | ||
|
|
c5da564fb3 | ||
|
|
a6b04ebb64 | ||
|
|
99ba6db257 | ||
|
|
a3cddb72b9 | ||
|
|
2a9e896095 | ||
|
|
89d522d325 | ||
|
|
3c4ff587ca | ||
|
|
e111529035 | ||
|
|
cae1f97032 | ||
|
|
20419834a6 | ||
|
|
5dabc2a20b | ||
|
|
c700f5fc68 | ||
|
|
0b71cf86f2 | ||
|
|
96159bd09c | ||
|
|
bcff802ccb | ||
|
|
376d295853 | ||
|
|
0030ad1804 | ||
|
|
4ec3e0f7d8 | ||
|
|
e36219e408 | ||
|
|
8f8f53a697 | ||
|
|
567292c72f | ||
|
|
b744f73a76 | ||
|
|
da440a5e16 | ||
|
|
017af1d5c3 | ||
|
|
1f5d75d8e9 | ||
|
|
8b80abc701 | ||
|
|
dc75ca4caf | ||
|
|
d7d4c0a54d | ||
|
|
823b094b60 | ||
|
|
06a6c982aa | ||
|
|
1d15ef01f9 | ||
|
|
f72ffcbb43 | ||
|
|
e0f2305cd9 | ||
|
|
210939d2c1 | ||
|
|
2fd071d90e | ||
|
|
badec62cdd | ||
|
|
895cda4de7 | ||
|
|
21fdc9f350 | ||
|
|
398c0ef687 | ||
|
|
3b0a9aef3c | ||
|
|
48ec0916bf | ||
|
|
10af87a7d0 | ||
|
|
96e7996f37 | ||
|
|
0f7af931a9 | ||
|
|
cfd2d80b78 | ||
|
|
0386c01aa9 | ||
|
|
2c39c91ac6 | ||
|
|
0eb51e3e8b | ||
|
|
bb931e9da7 | ||
|
|
7b2e672496 | ||
|
|
cdc6370ee5 | ||
|
|
cc762e4e1d | ||
|
|
ed525bd1d8 | ||
|
|
2b2e92c810 | ||
|
|
44d31ead76 | ||
|
|
ec163e94eb | ||
|
|
ec2ac33fec | ||
|
|
20bda2af26 | ||
|
|
7a49f6293d | ||
|
|
81b21010f1 | ||
|
|
2526e0a2f7 | ||
|
|
af1e8470c9 | ||
|
|
dfd9da68a7 | ||
|
|
5e702234f4 | ||
|
|
9020dcca9a | ||
|
|
930a4e4c1d | ||
|
|
4db77f96b7 | ||
|
|
cc12c046b9 | ||
|
|
f5c63e0997 | ||
|
|
29a26800b7 | ||
|
|
bc5eeb3b3a | ||
|
|
40d02518b0 | ||
|
|
a2556edc69 | ||
|
|
111970fda9 | ||
|
|
ebeb7bc969 | ||
|
|
6ccac5f69c | ||
|
|
cc41b8b259 | ||
|
|
db1a3456b7 | ||
|
|
1b9305c073 | ||
|
|
a33814ef40 | ||
|
|
581bc9f27c | ||
|
|
40cff0053f | ||
|
|
cc33b12b0d | ||
|
|
2add1c68ea | ||
|
|
380b6676a6 | ||
|
|
f133a36477 | ||
|
|
5f2d6f8e2f | ||
|
|
a72c207ec5 | ||
|
|
ae3c28dee1 | ||
|
|
bd919e5209 | ||
|
|
d1697756e9 | ||
|
|
83c3745165 | ||
|
|
56a4a964b7 | ||
|
|
c9a02faf08 | ||
|
|
e59388738e | ||
|
|
c8368d98eb | ||
|
|
d12dad2e34 | ||
|
|
1ee8c73562 | ||
|
|
ad8de84257 | ||
|
|
48398b4913 | ||
|
|
d719fe4612 | ||
|
|
034a30b444 | ||
|
|
9609e2ac4c | ||
|
|
66c2b72a28 | ||
|
|
da48b0880e | ||
|
|
4134b1549a | ||
|
|
7265b2535b | ||
|
|
bb638377ac | ||
|
|
466113fc4a | ||
|
|
31aea350cb | ||
|
|
56869577d4 | ||
|
|
ed3c597a92 | ||
|
|
cbb607b6b0 | ||
|
|
7f64abe820 | ||
|
|
b43dc1ba37 | ||
|
|
59962e5e88 | ||
|
|
8eabcecb69 | ||
|
|
a3ad726111 | ||
|
|
a46b4edb0a | ||
|
|
7059fe3815 | ||
|
|
780f1afe91 | ||
|
|
2459b4e56f | ||
|
|
f750cee594 | ||
|
|
1c3824f4b9 | ||
|
|
5ba1fa856d | ||
|
|
f40a685ac9 | ||
|
|
bf3b6577d5 | ||
|
|
7b0659332b | ||
|
|
19812cb015 | ||
|
|
b283c80776 | ||
|
|
49838c67ee | ||
|
|
4a40bddd82 | ||
|
|
208b7860aa | ||
|
|
05e7c9470b | ||
|
|
2f79d5f805 | ||
|
|
1f120a04f9 | ||
|
|
90a46f6556 | ||
|
|
4dff14a02a | ||
|
|
d9a9acb616 | ||
|
|
8ea215931e | ||
|
|
6caed6aacc | ||
|
|
0c192fcb57 | ||
|
|
3e819a5051 | ||
|
|
b31983cc3a | ||
|
|
e24cb1783c | ||
|
|
a913aba018 | ||
|
|
35d34ab524 | ||
|
|
604cf6b522 | ||
|
|
e987695732 | ||
|
|
09f37a86ad | ||
|
|
ff32f99610 | ||
|
|
4cd099ef30 | ||
|
|
54d3b0eabc | ||
|
|
b3d731b040 | ||
|
|
6629ec48a3 | ||
|
|
19c273771d | ||
|
|
e7b6919bc1 | ||
|
|
60e6c7d250 | ||
|
|
4feeb0e608 | ||
|
|
b3243efdf5 | ||
|
|
60a23bb280 | ||
|
|
973f38727d | ||
|
|
deaac5808d | ||
|
|
22dc01610e | ||
|
|
fe702d8fea | ||
|
|
10e669423f | ||
|
|
fbf146657e | ||
|
|
8667fab206 | ||
|
|
e974cd4b33 | ||
|
|
43c96803be | ||
|
|
70b42a5633 | ||
|
|
9f989f7706 | ||
|
|
4d976ef803 | ||
|
|
02257fd78f | ||
|
|
929c8f49a6 | ||
|
|
a6ec38c805 | ||
|
|
e5ec8ea3b2 | ||
|
|
36ac5a2802 | ||
|
|
b5beff5030 | ||
|
|
d1d1a5da77 | ||
|
|
713d58612e | ||
|
|
bd0990deb4 | ||
|
|
35e8d9c12b | ||
|
|
1fb7f9ff5b | ||
|
|
7eecb059e6 | ||
|
|
ba8375adb1 | ||
|
|
2ef547c461 | ||
|
|
a34784ca73 | ||
|
|
5594d46c2d | ||
|
|
dc7a1e3f41 | ||
|
|
68732487f9 | ||
|
|
5ea1d4376d | ||
|
|
9cb8b205c5 | ||
|
|
a35c453423 | ||
|
|
e7f91d7c25 | ||
|
|
4886f43463 | ||
|
|
929c8ac2b5 | ||
|
|
1438934aa6 | ||
|
|
ec65335fcd | ||
|
|
39d31dbd11 | ||
|
|
6c5be7a169 | ||
|
|
b45894fd51 | ||
|
|
a660b4e5c4 | ||
|
|
e11c88cf05 | ||
|
|
40f930f08a | ||
|
|
0c55e7819d | ||
|
|
3c17ee941f | ||
|
|
5a67ca0411 | ||
|
|
63d04a6707 | ||
|
|
676a116cda | ||
|
|
55435fd324 | ||
|
|
612f8059b8 | ||
|
|
ffd16f7639 | ||
|
|
528860161e | ||
|
|
1fe6094da5 | ||
|
|
399c51b1ee | ||
|
|
55e4abd534 | ||
|
|
e9d02f441b | ||
|
|
f858bcbe5b | ||
|
|
cd107711a9 | ||
|
|
ce4c20b112 | ||
|
|
0b8ba1ccfa | ||
|
|
c72c97fd53 | ||
|
|
1e12068e64 | ||
|
|
1799fe1ff9 | ||
|
|
ae5175c5b4 | ||
|
|
86d5b0b23d | ||
|
|
341044356f | ||
|
|
5eb7a62062 | ||
|
|
74f96c0766 | ||
|
|
49b62cb27a | ||
|
|
798588c54b | ||
|
|
f1a9cdaa8e | ||
|
|
c66c0a11b6 | ||
|
|
b1cdd1360b | ||
|
|
7c8b48e08a | ||
|
|
64df5c6b41 | ||
|
|
a5c1361dc9 | ||
|
|
798b1a7d2e | ||
|
|
e484e4c6de | ||
|
|
31299a529a | ||
|
|
53ac681d49 | ||
|
|
828ef48441 | ||
|
|
63e8742fb1 | ||
|
|
192a958fdc | ||
|
|
f606e633da | ||
|
|
e2d2b031a5 | ||
|
|
c203a972ff | ||
|
|
44df1aa0bd | ||
|
|
d010587f44 | ||
|
|
840525c11a | ||
|
|
a0881d851c | ||
|
|
ac00e05a72 | ||
|
|
4938568ea7 | ||
|
|
cb4c07a5fb | ||
|
|
4edd76341e | ||
|
|
bb8aee8965 | ||
|
|
5d97d2d680 | ||
|
|
3eb2646cad | ||
|
|
96c3dadb7b | ||
|
|
4d9a238c27 | ||
|
|
a475cfa340 | ||
|
|
e54cec9123 | ||
|
|
3edad29501 | ||
|
|
392a004bd1 | ||
|
|
7f8ec17511 | ||
|
|
d9e6fd3b89 | ||
|
|
6cf59838a6 | ||
|
|
3efa60ce8a | ||
|
|
7a90cd2562 | ||
|
|
4cdbe4f0f4 | ||
|
|
595408b351 | ||
|
|
4ee1fd9f65 | ||
|
|
f16f4d557a | ||
|
|
27314d1af3 | ||
|
|
4f14fb0ccd | ||
|
|
9b2a8f847f | ||
|
|
dae4ae1c6b | ||
|
|
c8023adff1 | ||
|
|
c34ac0f17b | ||
|
|
2222a1bfe2 | ||
|
|
3134809c22 | ||
|
|
203e8c41ce | ||
|
|
5804c044d5 | ||
|
|
80c378df21 | ||
|
|
0f3bc5922d | ||
|
|
1810edfa6e | ||
|
|
362b8d3243 | ||
|
|
b06f76512d | ||
|
|
6c2b421b57 | ||
|
|
63b3b4225a | ||
|
|
5b7ad40163 | ||
|
|
1751fb38e5 | ||
|
|
184a2bcf18 | ||
|
|
57fce9d20f | ||
|
|
d354157c0e | ||
|
|
de78e065cb | ||
|
|
17a49b5d8c | ||
|
|
6c6bbf6294 | ||
|
|
72f04367d9 | ||
|
|
7395305f87 | ||
|
|
1c62a665c7 | ||
|
|
518919aeee | ||
|
|
da798b3748 | ||
|
|
441e936d88 | ||
|
|
23def44101 | ||
|
|
35fafdb476 | ||
|
|
0e20e6a0bb | ||
|
|
04654a5c85 | ||
|
|
e17c4e5271 | ||
|
|
4d79b35c47 | ||
|
|
26aeb7dcbd | ||
|
|
7bc3582525 | ||
|
|
1ad00e1102 | ||
|
|
311ad6b940 | ||
|
|
c65f3289a3 | ||
|
|
cfeaf2f376 | ||
|
|
8434e856f4 | ||
|
|
35a700027c | ||
|
|
2196158f58 | ||
|
|
56d5ca180a | ||
|
|
60326b8f65 | ||
|
|
363943583d | ||
|
|
4348889865 | ||
|
|
50e50e82e1 | ||
|
|
fd30f16364 | ||
|
|
21879db549 | ||
|
|
313b9d64f6 | ||
|
|
87be97a38d | ||
|
|
4f5054d792 | ||
|
|
51545c4db0 | ||
|
|
98fb48eb1d | ||
|
|
fa2817ab52 | ||
|
|
2a35601ff4 | ||
|
|
ed70058a1f | ||
|
|
79a1b65547 | ||
|
|
cccddd8455 | ||
|
|
9a4d9f7f1f | ||
|
|
c532f40b7d | ||
|
|
d7e68c340c | ||
|
|
42a985112a | ||
|
|
16a653ed9d | ||
|
|
91f18323be | ||
|
|
09bbb50e1f | ||
|
|
a4eebfeeb2 | ||
|
|
62d19c9d11 | ||
|
|
07142b3052 | ||
|
|
a304bc0eed | ||
|
|
857b7e53d9 | ||
|
|
2987bb129c | ||
|
|
8da9ad696b | ||
|
|
8720d6937a | ||
|
|
9262834ffb | ||
|
|
a41b1a5a2d | ||
|
|
1e362fdd53 | ||
|
|
8dfe166944 | ||
|
|
8d0feea2c2 | ||
|
|
47d9f5920f | ||
|
|
25eca4146c | ||
|
|
61938601fd | ||
|
|
61d114f297 | ||
|
|
eddebfbba5 | ||
|
|
323d828eb7 | ||
|
|
bb763f7315 | ||
|
|
b1d93112da | ||
|
|
56bd3513a3 | ||
|
|
ddcf26058b | ||
|
|
ba4ee3f1fc | ||
|
|
dedfd5cd33 | ||
|
|
b5296f4206 | ||
|
|
e2e2c58d9f | ||
|
|
7a90b9ce23 | ||
|
|
ae0928e686 | ||
|
|
b815ad7a8c | ||
|
|
06cca9033a | ||
|
|
5302364139 | ||
|
|
78b7fc6169 | ||
|
|
b159c30cf1 | ||
|
|
5c7712bf6c | ||
|
|
e64b766599 | ||
|
|
89a852286c | ||
|
|
1e312cfbb1 | ||
|
|
8d4522227c | ||
|
|
eee39a7c0b | ||
|
|
bd58c18bb0 | ||
|
|
685b3a4f21 | ||
|
|
4e82a482d1 | ||
|
|
1214e28563 | ||
|
|
9170ed6e3a | ||
|
|
f2bb8bb8af | ||
|
|
24d74698ef | ||
|
|
ba615c15cb | ||
|
|
88f206e7f5 | ||
|
|
511740ccd7 | ||
|
|
7a2fab1126 | ||
|
|
fd435f0941 | ||
|
|
ffd5a8b321 | ||
|
|
5454e43bc4 | ||
|
|
a94fd2d127 | ||
|
|
14c53c5e3e | ||
|
|
b25648eea1 | ||
|
|
10d0d162b5 | ||
|
|
e5b2be4346 | ||
|
|
4cea442b59 | ||
|
|
532f682fc7 | ||
|
|
c2cd689c32 | ||
|
|
c3e986eb56 | ||
|
|
d91f4c244f | ||
|
|
22b768963f | ||
|
|
57354cd1ef | ||
|
|
c74cc40d5c | ||
|
|
b867a74b6b | ||
|
|
7a10486492 | ||
|
|
f36b833654 | ||
|
|
ef9206088e | ||
|
|
e141b26411 | ||
|
|
1f4da13060 | ||
|
|
4ec85e2f25 | ||
|
|
842831d729 | ||
|
|
39a0b5672b | ||
|
|
2729892676 | ||
|
|
50318354a6 | ||
|
|
77593c8031 | ||
|
|
3bfb9adb99 | ||
|
|
deebf289de | ||
|
|
d4e777900c | ||
|
|
1b44683cfe | ||
|
|
0ff53f0bd7 | ||
|
|
a5cbf08a76 | ||
|
|
023fa8afc9 | ||
|
|
a721748de1 | ||
|
|
ad112285e6 | ||
|
|
fe05ac9753 | ||
|
|
b873162a6f | ||
|
|
846604cce5 | ||
|
|
b1ea970f62 | ||
|
|
5bcfb7f488 | ||
|
|
1908f1b4f6 | ||
|
|
b0bf8e81aa | ||
|
|
4866ba0c84 | ||
|
|
8dadf42504 | ||
|
|
fc18b15106 | ||
|
|
9b4e55be28 | ||
|
|
8a4686984a | ||
|
|
42ebffc4fc | ||
|
|
2d2c596f75 | ||
|
|
fa464b489d | ||
|
|
b531504912 | ||
|
|
e4a346995b | ||
|
|
f0d1f2387d | ||
|
|
7eb592df79 | ||
|
|
a704c0ad35 | ||
|
|
acf4077878 | ||
|
|
ba50771007 | ||
|
|
898db8b7d4 | ||
|
|
d452a00592 | ||
|
|
4ab8fb359b | ||
|
|
29e6082663 | ||
|
|
7c6197b1fc | ||
|
|
1e0e40912b | ||
|
|
ff84638df8 | ||
|
|
90dee9c171 | ||
|
|
53873c7864 | ||
|
|
f60a9708b2 | ||
|
|
84497bfba7 | ||
|
|
4dfd672c04 | ||
|
|
d8b64aa2f4 | ||
|
|
4968100420 | ||
|
|
b52687f356 | ||
|
|
71d4565aa5 | ||
|
|
42ff295092 | ||
|
|
f0758e2a6c | ||
|
|
33e93ea156 | ||
|
|
9f212184fd | ||
|
|
1c16d4bd3f | ||
|
|
0008ffc735 | ||
|
|
e5dce929bb | ||
|
|
40bcf96c2b | ||
|
|
519d4470e3 | ||
|
|
cdf18b5480 | ||
|
|
dbe4965438 | ||
|
|
899b9b07dd | ||
|
|
54d8a03e87 | ||
|
|
052ad87da0 | ||
|
|
2a515b1d8d | ||
|
|
dad48df039 | ||
|
|
ee798df57d | ||
|
|
eed21b8f8f | ||
|
|
29938f5703 | ||
|
|
52bcf97d73 | ||
|
|
9934184f5f | ||
|
|
fdf33cbf81 | ||
|
|
34458bc86e | ||
|
|
9b061b3aa7 | ||
|
|
2fa6acef1c | ||
|
|
3afb1f145a | ||
|
|
b03b75d125 | ||
|
|
b9756f0bdc | ||
|
|
c3234cb79f | ||
|
|
828ab97837 | ||
|
|
ac66510f32 | ||
|
|
599397b6f7 | ||
|
|
e230f5d358 | ||
|
|
91486f1b70 | ||
|
|
95e6de8654 | ||
|
|
784baaec46 | ||
|
|
6adaca568f | ||
|
|
bcdcceb809 | ||
|
|
de3d075ff2 | ||
|
|
c5f3aa21b3 | ||
|
|
9831b0e3d4 | ||
|
|
24a8df801f | ||
|
|
e0cfd404a1 | ||
|
|
0e62c3455b | ||
|
|
9cd5a7926a | ||
|
|
8e4995c8d9 | ||
|
|
ca5fc1e8fc | ||
|
|
14dca4667a | ||
|
|
ebff14adac | ||
|
|
51f02ed46e | ||
|
|
03740d0918 | ||
|
|
c83a16e22e | ||
|
|
e1bf662884 | ||
|
|
d866bc9044 | ||
|
|
fd0e4c20ee | ||
|
|
55ca0a80b6 | ||
|
|
eeaf3dc2cf | ||
|
|
467b948349 | ||
|
|
f368af3d02 | ||
|
|
0f34ee7d16 | ||
|
|
2fe89fc41b | ||
|
|
968942f128 | ||
|
|
b5fae096a9 | ||
|
|
5cad9a1071 | ||
|
|
f4a350c3d0 | ||
|
|
89885ed4d9 | ||
|
|
612878d3b1 | ||
|
|
65d0bb6a90 | ||
|
|
484b440816 | ||
|
|
92d78515c4 | ||
|
|
341bedd7ca | ||
|
|
e9f54f1841 | ||
|
|
4c4af5f1fc | ||
|
|
2558cd9356 | ||
|
|
4670026c92 | ||
|
|
302b9c2ac5 | ||
|
|
000f1d02c3 | ||
|
|
63ce8429f2 | ||
|
|
61993c4a50 | ||
|
|
c248efc9fe | ||
|
|
ec64ca2865 | ||
|
|
d4fe7467b6 | ||
|
|
e8a229103a | ||
|
|
e6cdab37b0 | ||
|
|
26c88ffaec | ||
|
|
abf1c144c5 | ||
|
|
c4e04d6e07 | ||
|
|
ed4826a67f | ||
|
|
dee2df9e45 | ||
|
|
acabd11d40 | ||
|
|
8adea6ba1e | ||
|
|
c36be55c2f | ||
|
|
5355555568 | ||
|
|
176735d4cf | ||
|
|
3e01bca690 | ||
|
|
dd99d96c24 | ||
|
|
22e8c59031 | ||
|
|
44cefc89e4 | ||
|
|
df15249f23 | ||
|
|
b737321cbd | ||
|
|
319380ec6c | ||
|
|
cae7cad5d4 | ||
|
|
d4c7b41897 | ||
|
|
0ecf6b5aa1 | ||
|
|
cb51c03992 | ||
|
|
5dca5fe3cb | ||
|
|
a7acd50159 | ||
|
|
e732ec9fe4 | ||
|
|
e4070c8b5e | ||
|
|
b171b5904b | ||
|
|
cc89c994c8 | ||
|
|
fc2689e207 | ||
|
|
a5979b2e47 | ||
|
|
2eb8e32705 | ||
|
|
b32984b1d6 | ||
|
|
7e2fd9e690 | ||
|
|
a96dac8205 | ||
|
|
6afc2fd75a | ||
|
|
e44bd4684b | ||
|
|
115158a70e | ||
|
|
63577feca4 | ||
|
|
e8b91bf617 | ||
|
|
567e6f1d82 | ||
|
|
2b9b8ce536 | ||
|
|
a0f4cb9271 | ||
|
|
46f24c582c | ||
|
|
2068710a30 | ||
|
|
0568b5c6de | ||
|
|
a0d9b9fbe8 | ||
|
|
2190e449c1 | ||
|
|
f665b56e2b | ||
|
|
041b6abd59 | ||
|
|
fb7ace729c | ||
|
|
a68ed01003 | ||
|
|
95af80acde | ||
|
|
18664b7e7e | ||
|
|
37f9634389 | ||
|
|
a995b76f24 | ||
|
|
cb81e50f71 | ||
|
|
f8ba151b76 | ||
|
|
a0af67fce8 | ||
|
|
1467936c89 | ||
|
|
0d3008b839 | ||
|
|
517821632a | ||
|
|
0ed3e540c2 | ||
|
|
c96bb16db6 | ||
|
|
bd82441883 | ||
|
|
18421cde49 | ||
|
|
6dea26932e | ||
|
|
258768505e | ||
|
|
8caa20b746 | ||
|
|
5efc39af6a | ||
|
|
66daa2eb29 | ||
|
|
02687991e0 | ||
|
|
1e64592a39 | ||
|
|
9d2b074bec | ||
|
|
384a6f3d36 | ||
|
|
754d972253 | ||
|
|
9a29a6de5a | ||
|
|
f6513932b0 | ||
|
|
368f91c4c5 | ||
|
|
f1f40f0289 | ||
|
|
1d6671c11a | ||
|
|
9a0fa2f8b3 | ||
|
|
9b6ec9ffd3 | ||
|
|
e9b8fe5018 | ||
|
|
4a5cec8ed5 | ||
|
|
fa6f0ba77c | ||
|
|
a8fc58e143 | ||
|
|
57961e04b3 | ||
|
|
6628aa7eaf | ||
|
|
b7e492e03d | ||
|
|
2f2dc86c9d | ||
|
|
bfb2ff9390 | ||
|
|
cbd14c4b8c | ||
|
|
cb08660a78 | ||
|
|
87e1b075e0 | ||
|
|
26a3682c6e | ||
|
|
be30a2463a | ||
|
|
cc1df37725 | ||
|
|
3510032050 | ||
|
|
07aecd3a95 | ||
|
|
0e2a96b402 | ||
|
|
603c121874 | ||
|
|
9e634196bf | ||
|
|
4f20ea4570 | ||
|
|
c851708b3d | ||
|
|
fd6a693bc8 | ||
|
|
bab56b4c9d | ||
|
|
970da50910 | ||
|
|
0008e4b645 | ||
|
|
89e7a62d99 | ||
|
|
74e89c542a | ||
|
|
d441483201 | ||
|
|
f11d4fa613 | ||
|
|
11f9880ccf | ||
|
|
8c440961c5 | ||
|
|
8f5d7da934 | ||
|
|
807347da80 | ||
|
|
9364491316 | ||
|
|
255e12849e | ||
|
|
5c0fe81dcf | ||
|
|
e34dee8852 | ||
|
|
a803420576 | ||
|
|
a1939bc295 | ||
|
|
8c7bbd937f | ||
|
|
c87b2eaf7b | ||
|
|
f156718d86 | ||
|
|
9cabfacb99 | ||
|
|
377237d7c0 | ||
|
|
13f2611b25 | ||
|
|
519dfd3be7 | ||
|
|
c9c8d23ed5 | ||
|
|
ed4ceb41b5 | ||
|
|
fb4643630b | ||
|
|
999c3be21a | ||
|
|
0793a0638e | ||
|
|
8ad1d93cc6 | ||
|
|
afb4c9a00d | ||
|
|
93d9516a07 | ||
|
|
7950f23b6d | ||
|
|
178e206d19 | ||
|
|
d157308306 | ||
|
|
261eb19fea | ||
|
|
6a973421e3 | ||
|
|
325110c0cd | ||
|
|
184360925d | ||
|
|
58710196ca | ||
|
|
a3c57a01d6 | ||
|
|
63d26c2a51 | ||
|
|
8cd824f66f | ||
|
|
1652990324 | ||
|
|
28221e398e | ||
|
|
49fde8158f | ||
|
|
59d1526a88 | ||
|
|
36fdf1f67b | ||
|
|
a2771c262b | ||
|
|
de4e753429 | ||
|
|
cac9104769 | ||
|
|
f56cb03a09 | ||
|
|
911d3ad722 | ||
|
|
72a1984331 | ||
|
|
67035b8422 | ||
|
|
1c9416fbed | ||
|
|
cf25ced2e6 | ||
|
|
4003697850 | ||
|
|
7f48c7abbe | ||
|
|
b8d924ab6f | ||
|
|
b58a4e90da | ||
|
|
f781da41a4 | ||
|
|
c0695e80a8 | ||
|
|
019363e56b | ||
|
|
bf76567fdf | ||
|
|
e64250c519 | ||
|
|
4d190cd055 | ||
|
|
fe02fd7284 | ||
|
|
d73ced98ad | ||
|
|
ee5f915cca | ||
|
|
d801f1f5fb | ||
|
|
bd32afbed2 | ||
|
|
226d98cf6b | ||
|
|
dc3b4d3770 | ||
|
|
409169061e | ||
|
|
c539166747 | ||
|
|
2bb199bc25 | ||
|
|
6da9c50b9d | ||
|
|
8118f781d9 | ||
|
|
2e2f28d1bb | ||
|
|
316bb91625 | ||
|
|
263adb157c | ||
|
|
18937bdcc4 | ||
|
|
948d7498bd | ||
|
|
59ff18b508 | ||
|
|
baa9501c65 | ||
|
|
5c44f55ef6 | ||
|
|
095778cf0f | ||
|
|
2cec3f29d1 | ||
|
|
9523b88d77 | ||
|
|
6bcab179d1 | ||
|
|
fc1fdab51a | ||
|
|
f9bb3defde | ||
|
|
6075a92905 | ||
|
|
f495edfb3a | ||
|
|
6af47fa6ee | ||
|
|
972789dba3 | ||
|
|
cec1ed8d3d | ||
|
|
374963167a | ||
|
|
ccb5826a25 | ||
|
|
527aed0ea3 | ||
|
|
a8e266377c | ||
|
|
de57dc9410 | ||
|
|
617f0c8c17 | ||
|
|
2e73199153 | ||
|
|
5b0b674988 | ||
|
|
d85a74570d | ||
|
|
bb1f8aab24 | ||
|
|
0c4fb36827 | ||
|
|
ec2017ff72 | ||
|
|
f3cc0a07bc | ||
|
|
5e2dc95331 | ||
|
|
ee99abc266 | ||
|
|
cbf4ab797d | ||
|
|
bbe0bfadd9 | ||
|
|
35414e0afd | ||
|
|
90e99aac3b | ||
|
|
59506a97d6 | ||
|
|
ebf9b0e4f1 | ||
|
|
b85a8b8b0b | ||
|
|
f8029a6dc9 | ||
|
|
95eb9afeef | ||
|
|
87024f0426 | ||
|
|
09697f2593 | ||
|
|
e99e9f3e40 | ||
|
|
b8c05e551d | ||
|
|
829eb7d3a2 | ||
|
|
268080cbc5 | ||
|
|
8d9d0dd826 | ||
|
|
195c201f87 | ||
|
|
ceb0fc4db9 | ||
|
|
6121a9b48c | ||
|
|
e3138154f1 | ||
|
|
ac6c7f6a35 | ||
|
|
af6e31dcdf | ||
|
|
6f158e3382 | ||
|
|
81504bba1e | ||
|
|
66bedf46a1 | ||
|
|
a196ac03b1 | ||
|
|
ae1010166a | ||
|
|
a548212f27 | ||
|
|
1aeb6d0d9e | ||
|
|
612c963105 | ||
|
|
173a60eac6 | ||
|
|
8411efc8ef | ||
|
|
af8fe35222 | ||
|
|
a0e5f64ddf | ||
|
|
c80f0d317a | ||
|
|
e5a9159282 | ||
|
|
8215791051 | ||
|
|
ab62abed79 | ||
|
|
b31356aada | ||
|
|
b0db219aeb | ||
|
|
20a7c550fe | ||
|
|
2eb190dbbb | ||
|
|
d97360ef52 | ||
|
|
fab64c61c4 | ||
|
|
b9fea2ea12 | ||
|
|
adc4ae48d6 | ||
|
|
e7549a2887 | ||
|
|
f28507a366 | ||
|
|
a1b2c011f5 | ||
|
|
b8ee051f8f | ||
|
|
06e34c88b5 | ||
|
|
9866b92405 | ||
|
|
d1846217fd | ||
|
|
aa82f3637b | ||
|
|
731684f22f | ||
|
|
48b84270c4 | ||
|
|
acc4bbf628 | ||
|
|
1718c3bc16 | ||
|
|
235fa57423 | ||
|
|
90f0ebde1d | ||
|
|
e016725814 | ||
|
|
3f449a40ad | ||
|
|
e92726bdb3 | ||
|
|
45fe70d8ed | ||
|
|
e833e5d86d | ||
|
|
3dff5cb99f | ||
|
|
666d09e296 | ||
|
|
6e1e49a185 | ||
|
|
15c13ece27 | ||
|
|
754efefd32 | ||
|
|
f81e69f73c | ||
|
|
dd8e73e8f2 | ||
|
|
660520b939 | ||
|
|
a1c3096556 | ||
|
|
8cd9dea821 | ||
|
|
0cf64a7dde | ||
|
|
53aff4fbbb | ||
|
|
78789fad1c | ||
|
|
3c54d844b2 | ||
|
|
d8e27abff9 | ||
|
|
b7b8f9caa6 | ||
|
|
7e1cd47a4e | ||
|
|
badbd846c2 | ||
|
|
e08089ba3e | ||
|
|
27f57ce0b3 | ||
|
|
8aa773df9a | ||
|
|
8fb19d24e8 | ||
|
|
fd1376be53 | ||
|
|
051f0fd377 | ||
|
|
954644a001 | ||
|
|
19fcbf8f25 | ||
|
|
c1e2c20ace | ||
|
|
09dbbc17e4 | ||
|
|
4d9db3665f | ||
|
|
625f19ae00 | ||
|
|
dcc715d75d | ||
|
|
e8717498b5 | ||
|
|
ecfbbb39bd | ||
|
|
2cd8f56842 | ||
|
|
588b9737bf | ||
|
|
22d540caaa | ||
|
|
2dead0306a | ||
|
|
b77fa9f627 | ||
|
|
6a29eecf8d | ||
|
|
049e9f1a55 | ||
|
|
dcb995c626 | ||
|
|
6200f5fb62 | ||
|
|
cc27c19c66 | ||
|
|
23dc818eac | ||
|
|
311d40a9f1 | ||
|
|
ad4d2831c9 | ||
|
|
ee9c959262 | ||
|
|
b739603a3c | ||
|
|
153701133d | ||
|
|
d8704edc7f | ||
|
|
57f6b2d122 | ||
|
|
21c41fb145 | ||
|
|
12d35a39c7 | ||
|
|
11aa9f7b79 | ||
|
|
23ae3ad8ad | ||
|
|
84d468ad2f | ||
|
|
0459612632 | ||
|
|
7dfa4bcdb5 | ||
|
|
a3e73508f4 | ||
|
|
df120ec4a3 | ||
|
|
6dfa6a3710 | ||
|
|
7ae39a00cb | ||
|
|
0cbcbe3e69 | ||
|
|
47debc0223 | ||
|
|
5953f08495 | ||
|
|
43276582ed | ||
|
|
2c3d7871ff | ||
|
|
112f10a16d | ||
|
|
28beefcbb8 | ||
|
|
edcff1068b | ||
|
|
266f23d1e6 | ||
|
|
c4dfd24782 | ||
|
|
9ae2de6dc1 | ||
|
|
45fd6f89c0 | ||
|
|
b1ba4b505a | ||
|
|
99e6cf4796 | ||
|
|
4df5752df7 | ||
|
|
7a2837b6c9 | ||
|
|
dc08805307 | ||
|
|
2ffebb9c0b | ||
|
|
2553a51408 | ||
|
|
e2a338c3c9 | ||
|
|
795f4cd7a7 | ||
|
|
932fa22701 | ||
|
|
5c746ad3d4 | ||
|
|
d0c8a80e5e | ||
|
|
da40f7ab07 | ||
|
|
f4c42a5d39 | ||
|
|
7b3a752ad9 | ||
|
|
ad861e7da1 | ||
|
|
17e8cf8aaa | ||
|
|
6773f1e152 | ||
|
|
928b95861d | ||
|
|
f274abcc8d | ||
|
|
5a725af1bb | ||
|
|
b0d5c8870a | ||
|
|
fb14a49dd5 | ||
|
|
b6d2ec3bea | ||
|
|
3fd5b77de8 | ||
|
|
b060039a28 | ||
|
|
ba84e8bc33 | ||
|
|
cba111c055 | ||
|
|
a1f4c3506d | ||
|
|
a4e0abf7bc | ||
|
|
7058bb5e12 | ||
|
|
43d4d3cddc | ||
|
|
c4804f427f | ||
|
|
430ef5d1a6 | ||
|
|
d8fb4304b7 | ||
|
|
caf5ee7412 | ||
|
|
2acfbcdce6 | ||
|
|
c687c5df24 | ||
|
|
f63db81268 | ||
|
|
00de9bbbc5 | ||
|
|
825db1158c | ||
|
|
b5bff64cf0 | ||
|
|
c5255872ca | ||
|
|
9920f44a90 | ||
|
|
f5bbc43c87 | ||
|
|
7076809b71 | ||
|
|
34b7cda2ec | ||
|
|
f2cd90a999 | ||
|
|
2c35c63a09 | ||
|
|
7832a6eb6f | ||
|
|
e1c3dda6e0 | ||
|
|
f11c015522 | ||
|
|
9cd23bc02b | ||
|
|
8c0ab4285b | ||
|
|
3cbc5aaf2d | ||
|
|
c43aae15ff | ||
|
|
2fd3ded6e2 | ||
|
|
cb6d727664 | ||
|
|
3be2047c9c | ||
|
|
b3ec9a0900 | ||
|
|
50cf830404 | ||
|
|
72e58a7f0d | ||
|
|
36781c0bc6 | ||
|
|
12ca7d0fe2 | ||
|
|
b85066eb06 | ||
|
|
456705de54 | ||
|
|
31b500cc7f | ||
|
|
03d0011c2f | ||
|
|
101088cadc | ||
|
|
638702728c | ||
|
|
015a0888d4 | ||
|
|
361eaeca07 | ||
|
|
6850c2a9ee | ||
|
|
12af387e50 | ||
|
|
55216be46b | ||
|
|
7630642c56 | ||
|
|
ad8fe7923a | ||
|
|
f06b4f70f9 | ||
|
|
408ecda944 | ||
|
|
95844cd6c0 | ||
|
|
cf4824e588 | ||
|
|
c99aaf763d | ||
|
|
1156027587 | ||
|
|
46c6d43556 | ||
|
|
07fccd0479 | ||
|
|
10e4fe7a71 | ||
|
|
5f37891eae | ||
|
|
f09644be00 | ||
|
|
96e573b356 | ||
|
|
bed63b55fe | ||
|
|
0a8ac5cb05 | ||
|
|
590d7cc79b | ||
|
|
aeeaa18b28 | ||
|
|
d6a6f1ed51 | ||
|
|
68bf5d5105 | ||
|
|
78d5f6f598 | ||
|
|
fa8c6dfa6f | ||
|
|
15d3bc70d2 | ||
|
|
c37b52645c | ||
|
|
e6f61699d7 | ||
|
|
6cdf61d6cf | ||
|
|
60dee64fa0 | ||
|
|
21f4ba4f3a | ||
|
|
df4777dca4 | ||
|
|
03b8e98cb2 | ||
|
|
fafe2374b7 | ||
|
|
1840fac000 | ||
|
|
ec460ff07a | ||
|
|
b0e68366d4 | ||
|
|
99266e4ea9 | ||
|
|
34025599a0 | ||
|
|
21f34b8039 | ||
|
|
30b3a4c9c7 | ||
|
|
7ca2f7d6b1 | ||
|
|
7a6ac1f6d0 | ||
|
|
e53f0a3191 | ||
|
|
54b28ae356 | ||
|
|
22b7181c40 | ||
|
|
daf6a856c7 | ||
|
|
4e2baa0868 | ||
|
|
6b48084c9c | ||
|
|
1e48959c0a | ||
|
|
088c37d1ea | ||
|
|
18dcc21340 | ||
|
|
e03c1d4c85 | ||
|
|
9fb85f252e | ||
|
|
c7601c9921 | ||
|
|
eab2bd3565 | ||
|
|
4454c6be73 | ||
|
|
0adf8a0a05 | ||
|
|
bdf59c1a5f | ||
|
|
e317926fcb | ||
|
|
1487a0ecd2 | ||
|
|
950d2689c7 | ||
|
|
8687ed6697 | ||
|
|
ab9c0dab04 | ||
|
|
45e2819694 | ||
|
|
0187a0cace | ||
|
|
9d714ba9e0 | ||
|
|
a614434c04 | ||
|
|
0fbfee521f | ||
|
|
d2233acc44 | ||
|
|
4b86741683 | ||
|
|
26bf91e1da | ||
|
|
37eab31b40 | ||
|
|
39aa548586 | ||
|
|
a228b36e8e | ||
|
|
7d33a1572e | ||
|
|
5ccbf0042c | ||
|
|
0313ea636a | ||
|
|
d7a5db3dbb | ||
|
|
82435bf6ff | ||
|
|
e56a4ed9e2 | ||
|
|
52ef16dba5 | ||
|
|
e4713edd75 | ||
|
|
5abe72f7e7 | ||
|
|
fdeb07f82b | ||
|
|
44b59eea58 | ||
|
|
f8bf2f38d3 | ||
|
|
091854a6d0 | ||
|
|
fd55aa61cf | ||
|
|
7bd014f9de | ||
|
|
793ef35c95 | ||
|
|
d8eb8499ef | ||
|
|
ad98339de7 | ||
|
|
d121326382 | ||
|
|
bd9e689885 | ||
|
|
79dcf6d63b | ||
|
|
3390a26588 | ||
|
|
93d1cd3ee7 | ||
|
|
4b3cfc5de1 | ||
|
|
f9d38fdd69 | ||
|
|
628c375b8c | ||
|
|
714c884732 | ||
|
|
f6dffe9845 | ||
|
|
a28b3cc268 | ||
|
|
388dd99986 | ||
|
|
1081b6a1c0 | ||
|
|
80d93b1fc9 | ||
|
|
3980fe5de1 | ||
|
|
b374b1ef7a | ||
|
|
09a7865e7d | ||
|
|
2f9a399d18 | ||
|
|
bbda3955c3 | ||
|
|
ba42932024 | ||
|
|
f7c8bd6d1c | ||
|
|
35479575ec | ||
|
|
23a4aab3c4 | ||
|
|
ec5bd18b67 | ||
|
|
d5750bf329 | ||
|
|
ac55d35b13 | ||
|
|
a1c27049d6 | ||
|
|
8b36b29126 | ||
|
|
c0e75ac6b4 | ||
|
|
897f3a86c5 | ||
|
|
58025d3b01 | ||
|
|
591197422d | ||
|
|
027b1f711c | ||
|
|
5f15a0f555 | ||
|
|
c46238301a | ||
|
|
7c282d28df | ||
|
|
587251e73c | ||
|
|
12dbafd0c9 | ||
|
|
3c822399b1 | ||
|
|
ae7252fbec | ||
|
|
13dfde1862 | ||
|
|
3a0aef3779 | ||
|
|
a82cc8cbd4 | ||
|
|
6e6701a644 | ||
|
|
b6b74e292f | ||
|
|
db0dfdcd59 | ||
|
|
fc49643860 | ||
|
|
7968c1dcd2 | ||
|
|
b9180798ca | ||
|
|
8ed0888ea8 | ||
|
|
e5d941f98b | ||
|
|
62f434f0e0 | ||
|
|
829451486e | ||
|
|
0da1a293e6 | ||
|
|
a51ccad560 | ||
|
|
b8ab30fc22 | ||
|
|
915bc6c7cd | ||
|
|
0bc55a5185 | ||
|
|
07c2973459 | ||
|
|
2bc8722049 | ||
|
|
84259fd9d8 | ||
|
|
31474b581b | ||
|
|
2fc71c762a | ||
|
|
a541e6db1f | ||
|
|
a4aab9f4c2 | ||
|
|
2d6abc088f | ||
|
|
a1f3d42fd0 | ||
|
|
915e72584c | ||
|
|
22ef3c8b2a | ||
|
|
0936793b23 | ||
|
|
8bbdf56cb0 | ||
|
|
25fd939bc6 | ||
|
|
5e4f31fe84 | ||
|
|
5638b4f889 | ||
|
|
2f28a7f3f2 | ||
|
|
9f3137e509 | ||
|
|
32c91f56f3 | ||
|
|
c81284754f | ||
|
|
e300546a32 | ||
|
|
ce0f62d598 | ||
|
|
18e1987a6a | ||
|
|
626c12c8a3 | ||
|
|
8e8fb9cfe8 | ||
|
|
c0c3f2c9ba | ||
|
|
7e4846b83c | ||
|
|
adcd0e2936 | ||
|
|
2a02a2e40b | ||
|
|
8b8953b98c | ||
|
|
05baa544bc | ||
|
|
95aee6eb37 | ||
|
|
d348c0e794 | ||
|
|
bdc25e4fb5 | ||
|
|
f864fba78b | ||
|
|
ec34261674 | ||
|
|
119965a7fb | ||
|
|
24c672ddc9 | ||
|
|
56578c7c0c | ||
|
|
fdc78b5c32 | ||
|
|
3585223827 | ||
|
|
13bdb881c7 | ||
|
|
12c46c794f | ||
|
|
3b839ebd1f | ||
|
|
04d5c98756 | ||
|
|
2cce4bf2a8 | ||
|
|
15560229ce | ||
|
|
20317e5830 | ||
|
|
2bf1de5a43 | ||
|
|
7306ce09b4 | ||
|
|
846bcf3ef5 | ||
|
|
69b69da52a | ||
|
|
7a7be6e454 | ||
|
|
3587e450a3 | ||
|
|
0b8001eac2 | ||
|
|
8235c6d4fc | ||
|
|
aed88bd857 | ||
|
|
8fcca219b4 | ||
|
|
4b16ed6bdd | ||
|
|
3ad7901edb | ||
|
|
a684823f25 | ||
|
|
90a03c5096 | ||
|
|
46f8f3c27e | ||
|
|
3569a85488 | ||
|
|
9a0942e9b2 | ||
|
|
26725bd878 | ||
|
|
ae01148b76 | ||
|
|
1269959265 | ||
|
|
a471d68d6c | ||
|
|
2eb8859080 | ||
|
|
038fe07fd4 | ||
|
|
578b899653 | ||
|
|
32e0151f7d | ||
|
|
43cf02d5b8 | ||
|
|
d60a1193b2 | ||
|
|
806e0b6d7f | ||
|
|
74434e87c5 | ||
|
|
41935d8b48 | ||
|
|
8a93c7472f | ||
|
|
687737f71a | ||
|
|
c4296f0127 | ||
|
|
933e8d4409 | ||
|
|
28950473b2 | ||
|
|
6a478ca315 | ||
|
|
03d4175bea | ||
|
|
25abdef96a | ||
|
|
a01d8548e3 | ||
|
|
c1946e57b7 | ||
|
|
811ed6efe5 | ||
|
|
6855a0afbe | ||
|
|
f9e68a0c9c | ||
|
|
f1ecdfc9df | ||
|
|
01fc9f6130 | ||
|
|
a2c3f74ab2 | ||
|
|
11301d7b63 | ||
|
|
1d2e1d9950 | ||
|
|
47938a2278 | ||
|
|
6922ad04a9 | ||
|
|
cc24e73483 | ||
|
|
59fed5c756 | ||
|
|
f93e7579bc | ||
|
|
a617053d97 | ||
|
|
3ebd5a95d4 | ||
|
|
4f4ecbf819 | ||
|
|
cb81b63524 | ||
|
|
8bd3512bc8 | ||
|
|
7f0d3c89bd | ||
|
|
f4d87458dd | ||
|
|
2c3c80e45c | ||
|
|
1a24193d2c | ||
|
|
92ac40e4da | ||
|
|
fcc316674e | ||
|
|
a0237d4259 | ||
|
|
bf061b9d4f | ||
|
|
6f3b5b1c61 | ||
|
|
1244b6b283 | ||
|
|
b01303f5ae | ||
|
|
3a9d5730e5 | ||
|
|
17a8a5984b | ||
|
|
0cd2c067b6 | ||
|
|
b4342492d5 | ||
|
|
ccbbdd280d | ||
|
|
ada209dc75 | ||
|
|
a602e3c88a | ||
|
|
b507d527e3 | ||
|
|
6d1ce4bca2 | ||
|
|
36eda331d1 | ||
|
|
a2eca89fb8 | ||
|
|
a555ba09f1 | ||
|
|
313104a01b | ||
|
|
744d2a535f | ||
|
|
f08d9d2775 | ||
|
|
224cf9b88d | ||
|
|
5ba06a74a0 | ||
|
|
1f14cc35dd | ||
|
|
4953307e1e | ||
|
|
b33d429212 | ||
|
|
d3a17b64f4 | ||
|
|
5a572b25a0 | ||
|
|
03187804c4 | ||
|
|
99b005f0cc | ||
|
|
7bf5d027bf | ||
|
|
e6f7cc8d74 | ||
|
|
4224c01925 | ||
|
|
ea85d577d8 | ||
|
|
add0e43723 | ||
|
|
e7378cbba0 | ||
|
|
dc58ff19d4 | ||
|
|
7bce331eb1 | ||
|
|
141dc247d6 | ||
|
|
dda8df678a | ||
|
|
e06abbc354 | ||
|
|
26938c245b | ||
|
|
54e9803080 | ||
|
|
bf30c7cb01 | ||
|
|
32f063fd2b | ||
|
|
e4c27a31fa | ||
|
|
365e44e376 | ||
|
|
7e55a8558a | ||
|
|
e38b007743 | ||
|
|
f2dd248200 | ||
|
|
ce8673e7e2 | ||
|
|
aaf4deee2c | ||
|
|
7a0895f872 | ||
|
|
d052c32f7a | ||
|
|
07dbee52cd | ||
|
|
aa8b1f39b3 | ||
|
|
849c550191 | ||
|
|
41cdb4911c | ||
|
|
15c4efcbe4 | ||
|
|
6b776f0b92 | ||
|
|
b8005deaa4 | ||
|
|
2fc35e2543 | ||
|
|
e7fcfff370 | ||
|
|
4bc9033205 | ||
|
|
8673550b69 | ||
|
|
e47ed9c012 | ||
|
|
bdd58a50b1 | ||
|
|
e3d8deba0c | ||
|
|
b386832256 | ||
|
|
26564cfeda | ||
|
|
78e560318d | ||
|
|
7a88044edb | ||
|
|
cc06968c42 | ||
|
|
ae7c89d746 | ||
|
|
0c525a8e52 | ||
|
|
4ac562a55a | ||
|
|
5180673b6d | ||
|
|
f573046107 | ||
|
|
a24878209b | ||
|
|
f12d69a4f6 | ||
|
|
4a1706ede6 | ||
|
|
f5cb34f506 | ||
|
|
2f1e758eb4 | ||
|
|
f825f43528 | ||
|
|
8f1844921e | ||
|
|
1cd887d3ec | ||
|
|
0bb53a73a8 | ||
|
|
6ede5dda6b | ||
|
|
3dbf92bb58 | ||
|
|
f447d7f423 | ||
|
|
a3f6a330e2 | ||
|
|
0c26670bf6 | ||
|
|
97884af83d | ||
|
|
946df5f8d6 | ||
|
|
e98a12c797 | ||
|
|
7444870741 | ||
|
|
2bcf6a5da8 | ||
|
|
b77fa8d57b | ||
|
|
cfd6f063e1 | ||
|
|
a8906da890 | ||
|
|
b63046b20a | ||
|
|
df91e31397 | ||
|
|
b40622c093 | ||
|
|
a925aac1df | ||
|
|
2081b6a4a8 | ||
|
|
7b66f5afb3 | ||
|
|
a14da417a7 | ||
|
|
5af4e1db67 | ||
|
|
e90e0f7d57 | ||
|
|
eac0901af0 | ||
|
|
79f3f69827 | ||
|
|
7c0ca54249 | ||
|
|
d10d4220a8 | ||
|
|
ab8ef25f89 | ||
|
|
8ff60854ac | ||
|
|
41938a5f16 | ||
|
|
10f8a2e807 | ||
|
|
2d8de7009b | ||
|
|
88cc17b530 | ||
|
|
df09d0c8bb | ||
|
|
749aa28b9a | ||
|
|
912ec6a9e9 | ||
|
|
e49957b2b2 | ||
|
|
06e74ffb47 | ||
|
|
4ebbc638da | ||
|
|
757fbbdd88 | ||
|
|
c73965f69a | ||
|
|
2af0f73473 | ||
|
|
305ecf8a7c | ||
|
|
da56090604 | ||
|
|
98eb5640ed | ||
|
|
1e1b1baad5 | ||
|
|
a68103e8ba | ||
|
|
3438addf6c | ||
|
|
6fc7c4e2c0 | ||
|
|
dc7537ac0a | ||
|
|
d7a83f3361 | ||
|
|
5e75b1e7dc | ||
|
|
a11a16a700 | ||
|
|
a3de8281ef | ||
|
|
7960528464 | ||
|
|
a8b067885f | ||
|
|
945fabbdd6 | ||
|
|
c12bf0aead | ||
|
|
12f25ddafd | ||
|
|
55f07e913a | ||
|
|
0bd22281f7 | ||
|
|
72ab62b21b | ||
|
|
796d30d863 | ||
|
|
b191323e2b | ||
|
|
e4ae0988a4 | ||
|
|
238ebdeed8 | ||
|
|
68ebe1a4ff | ||
|
|
8a89be6999 | ||
|
|
0620fc9f17 | ||
|
|
1e95e38505 | ||
|
|
5b4e5f9d1d | ||
|
|
6285fd9f98 | ||
|
|
401d5cab66 | ||
|
|
d7e2df5ca9 | ||
|
|
b38177bb32 | ||
|
|
27b9cbda38 | ||
|
|
a71e08ad2a | ||
|
|
5e0c9165ba | ||
|
|
cb2a6cd3b5 | ||
|
|
81c0e73751 | ||
|
|
6f12594b3e | ||
|
|
5a296b1238 | ||
|
|
249456c916 | ||
|
|
5aa2554584 | ||
|
|
9999ced817 | ||
|
|
6c137b29c2 | ||
|
|
854c070b82 | ||
|
|
6a5a4664e9 | ||
|
|
5aaecd3946 | ||
|
|
425310710f | ||
|
|
af990fb666 | ||
|
|
c0b2669c46 | ||
|
|
edc615f487 | ||
|
|
04b8b8dd5a | ||
|
|
34ef36544e | ||
|
|
4a9deadcf4 | ||
|
|
e1eb1d705a | ||
|
|
ab035a3887 | ||
|
|
c92f0f3edf | ||
|
|
ceb73730c2 | ||
|
|
60e0a731ad | ||
|
|
d9e77284c1 | ||
|
|
4d9c7d0dcb | ||
|
|
936d2e56ea | ||
|
|
4be1923921 | ||
|
|
7bb5866164 | ||
|
|
0f2854fe17 | ||
|
|
548b2f4b77 | ||
|
|
cd776e4b64 | ||
|
|
aeca4c0f9c | ||
|
|
d96b1bb9f8 | ||
|
|
944bdd5bba | ||
|
|
e61550841b | ||
|
|
ff5e171d4a | ||
|
|
b5bb92459d | ||
|
|
b9ea94e9be | ||
|
|
f42186f7c9 | ||
|
|
b510bff195 | ||
|
|
c1b85c0d21 | ||
|
|
08f84bdc07 | ||
|
|
187c93377f | ||
|
|
eb4b85dc79 | ||
|
|
36d7bf77e3 | ||
|
|
2a47e5f32c | ||
|
|
b522abffb5 | ||
|
|
ba272061b7 | ||
|
|
142542da1e | ||
|
|
c79c4d265c | ||
|
|
95289f1715 | ||
|
|
a35d5c4c3a | ||
|
|
c6fd36b75d | ||
|
|
985eb69c50 | ||
|
|
17912ebffe | ||
|
|
a9b41d4a21 | ||
|
|
0b020ce1ac | ||
|
|
580532aeca | ||
|
|
8c43047c95 | ||
|
|
05aeef0ea0 | ||
|
|
ced9493069 | ||
|
|
76ab3fd1ab | ||
|
|
7d6fcda03e | ||
|
|
a7d2c1137c | ||
|
|
033ad18779 | ||
|
|
404706a3db | ||
|
|
2c3bf06740 | ||
|
|
a132b58227 | ||
|
|
8d91141d6a | ||
|
|
a8ac895998 | ||
|
|
ee8aa1d9c6 | ||
|
|
206e45214f | ||
|
|
ba2aef0468 | ||
|
|
7642b522f9 | ||
|
|
b8960c4549 | ||
|
|
358b823e00 | ||
|
|
aa3a95f528 | ||
|
|
00a1eebf60 | ||
|
|
b6587da081 | ||
|
|
bcd6e6767a | ||
|
|
7d21772f87 | ||
|
|
949d706eaa | ||
|
|
c8445b9b5f | ||
|
|
d3c901678c | ||
|
|
1549affd5c | ||
|
|
f9e875a7cc | ||
|
|
5b65279a0a | ||
|
|
ccd58d2909 | ||
|
|
714f56c17c | ||
|
|
a820a96996 | ||
|
|
1d77523e41 | ||
|
|
107c1529ff | ||
|
|
a7f80ef144 | ||
|
|
9274864a83 | ||
|
|
f51bbd8a39 | ||
|
|
1534e1a1ee | ||
|
|
0c9c176223 | ||
|
|
e58ed7a3dc | ||
|
|
adde65f757 | ||
|
|
b45939ed26 | ||
|
|
3de4920385 | ||
|
|
0ab4df99b7 | ||
|
|
adaabcb8e5 | ||
|
|
68403ee142 | ||
|
|
1eb0040126 | ||
|
|
6cca2fd991 | ||
|
|
f276ab830a | ||
|
|
2d3f45bad5 | ||
|
|
30259c4360 | ||
|
|
cfa091dbc4 | ||
|
|
eb18f474c8 | ||
|
|
6554a027d7 | ||
|
|
0e83f0b217 | ||
|
|
b45d6945b1 | ||
|
|
c2e32c0bf2 | ||
|
|
926b9b1d1a | ||
|
|
57b51cec9c | ||
|
|
ebfcc2e23a | ||
|
|
980b3234d5 | ||
|
|
a25b914085 | ||
|
|
c936000d62 | ||
|
|
e1f3adafb7 | ||
|
|
4745eb190a | ||
|
|
d78784e45e | ||
|
|
6e60ff2062 | ||
|
|
b8c1c1ef1e | ||
|
|
d918f0fb03 | ||
|
|
91d6880218 | ||
|
|
ea30075602 | ||
|
|
a00ca647f5 | ||
|
|
f6260087c3 | ||
|
|
81e1d86047 | ||
|
|
988ac8e60b | ||
|
|
cc624f9ed2 | ||
|
|
8d2984c572 | ||
|
|
29d4396956 | ||
|
|
0ba0023099 | ||
|
|
2ef26e9681 | ||
|
|
3be6b6966b | ||
|
|
415aeb1ef5 | ||
|
|
2fc25e9b13 | ||
|
|
00a032e6b0 | ||
|
|
04ab95ab76 | ||
|
|
2f3c7eb550 | ||
|
|
dce6d50350 | ||
|
|
6ac63436f7 | ||
|
|
03979d8665 | ||
|
|
8991232681 | ||
|
|
31a0604341 | ||
|
|
8b6ac9c736 | ||
|
|
ac5279fa70 | ||
|
|
ed2ea88cb5 | ||
|
|
f2a7706bdf | ||
|
|
b88d2fe111 | ||
|
|
9b9b4d4bdf | ||
|
|
41037eb425 | ||
|
|
ba126f1f1a | ||
|
|
88894a6d54 | ||
|
|
61cb276b94 | ||
|
|
f83f5455c2 | ||
|
|
09e409cb79 | ||
|
|
39e3cba80e | ||
|
|
8246f1c990 | ||
|
|
10c32381d4 | ||
|
|
5b6efbbb5f | ||
|
|
5edb5276f8 | ||
|
|
b1109780ed | ||
|
|
62070c50ff | ||
|
|
8332dc188a | ||
|
|
3e28fd69b3 | ||
|
|
4cf6f7bd7c | ||
|
|
a2b0a57971 | ||
|
|
df7d5c6075 | ||
|
|
e6f9811162 | ||
|
|
7625c75dc7 | ||
|
|
07ab79d8dd | ||
|
|
54f8550229 | ||
|
|
f6ae7587ea | ||
|
|
2d78d04d52 | ||
|
|
5a26ee2ca9 | ||
|
|
8971d7b876 | ||
|
|
158894c7cc | ||
|
|
589f98bcc2 | ||
|
|
9b250b0dda | ||
|
|
ebe147ee34 | ||
|
|
4cd0334ed1 | ||
|
|
c49506e588 | ||
|
|
238f5a9af3 | ||
|
|
5d81d0e640 | ||
|
|
4baa0b102d | ||
|
|
0cd17f15d7 | ||
|
|
1fa08bbbc3 | ||
|
|
9e06242c1d | ||
|
|
5b7006d695 | ||
|
|
cd3273bb51 | ||
|
|
917ad5f750 | ||
|
|
29ee22f6cc | ||
|
|
4ad8157ba0 | ||
|
|
69a8bd1761 | ||
|
|
2bdeae0ddb | ||
|
|
0fb1eec3cd | ||
|
|
243d6ebd2c | ||
|
|
6b2882fe47 | ||
|
|
6ad8dc7f3e | ||
|
|
fcedab74c0 | ||
|
|
7404c642e3 | ||
|
|
d922961112 | ||
|
|
c679970832 | ||
|
|
8393cd4b86 | ||
|
|
42125c756e | ||
|
|
447df0af17 | ||
|
|
38d5646975 | ||
|
|
b16656bd23 | ||
|
|
0f987916b7 | ||
|
|
21e419ff8a | ||
|
|
d2acc351a2 | ||
|
|
faa076c1e9 | ||
|
|
1eac28a145 | ||
|
|
df7791a3e7 | ||
|
|
176a23fe97 | ||
|
|
548ff068fd | ||
|
|
50ce433bcb | ||
|
|
d8ada8c9d3 | ||
|
|
f04972a902 | ||
|
|
0b2ec35324 | ||
|
|
77278e77eb | ||
|
|
c6f2c8a3f5 | ||
|
|
e037972dbb | ||
|
|
ba24c55d41 | ||
|
|
034a24dfe3 | ||
|
|
9f7851a178 | ||
|
|
7ea2d7d1ab | ||
|
|
8ecfb872b6 | ||
|
|
2a91ab07b9 | ||
|
|
111d11a71b | ||
|
|
6aeee05e8a | ||
|
|
472586e772 | ||
|
|
4f15322cec | ||
|
|
0e46ff2b6d | ||
|
|
fcf90a053a | ||
|
|
b9e19e84d4 | ||
|
|
1fc60cf410 | ||
|
|
21bc1fd5a6 | ||
|
|
3989f0c332 | ||
|
|
23ffef8943 | ||
|
|
c3105fa66f | ||
|
|
8b09b2cdba | ||
|
|
315426a4b6 | ||
|
|
51d948fc29 | ||
|
|
68f4f011b7 | ||
|
|
ebdd6c5a4d | ||
|
|
deda8dcd97 | ||
|
|
f19f29a4bd | ||
|
|
0677a8a21a | ||
|
|
b3c12c33b7 | ||
|
|
09f57d3bb6 | ||
|
|
6b9b249e22 | ||
|
|
78327f648d | ||
|
|
df32c1c5d5 | ||
|
|
e93f13f6b0 | ||
|
|
02d2b89a4d | ||
|
|
34ff64b103 | ||
|
|
827dc3da8b | ||
|
|
1cd9c8f817 | ||
|
|
e8a9035e68 | ||
|
|
a288c8d7fb | ||
|
|
88e8c2ba33 | ||
|
|
252ec6fe59 | ||
|
|
e664ab18ee | ||
|
|
b78c5b32c6 | ||
|
|
4ddc8f950e | ||
|
|
0260a33678 | ||
|
|
358c3ab0c3 | ||
|
|
a658599406 | ||
|
|
d0b1bde521 | ||
|
|
b24075ca1c | ||
|
|
88fb4051a4 | ||
|
|
0c7cff5602 | ||
|
|
f872f17d39 | ||
|
|
70917c19d1 | ||
|
|
4353e997fc | ||
|
|
e5bf8a8e75 | ||
|
|
d3928b30de | ||
|
|
ec2bc5e8cb | ||
|
|
b74e3d389b | ||
|
|
e567668346 | ||
|
|
6e31480ed9 | ||
|
|
d35b65c9d2 | ||
|
|
0f27299586 | ||
|
|
baff716ef6 | ||
|
|
1141676223 | ||
|
|
a6ce80d39b | ||
|
|
6d3e0eaa22 | ||
|
|
18c1333496 | ||
|
|
ab00d73d7a | ||
|
|
5bc574025d | ||
|
|
71e7d92d75 | ||
|
|
723c7a97fc | ||
|
|
16a3b88db5 | ||
|
|
19ed31a2c2 | ||
|
|
93fd430863 | ||
|
|
c1ac810ff2 | ||
|
|
e785085d0d | ||
|
|
334133ea61 | ||
|
|
82b801498a | ||
|
|
83c74cf9e1 | ||
|
|
3dc4dcf874 | ||
|
|
aaf184ddb3 | ||
|
|
21e9e64b3d | ||
|
|
48c431c0a9 | ||
|
|
8992b4a284 | ||
|
|
c9d7da5951 | ||
|
|
f76744fc98 | ||
|
|
b624874768 | ||
|
|
ed84727938 | ||
|
|
10f8318883 | ||
|
|
7dd7f1a32c | ||
|
|
a06fa75419 | ||
|
|
7e0ca09bf7 | ||
|
|
cae3d7b321 | ||
|
|
1c30a93da1 | ||
|
|
03d30d7f99 | ||
|
|
6e4aecb3dc | ||
|
|
660d01c59a | ||
|
|
81cccadf80 | ||
|
|
e0ea5af18e | ||
|
|
4544759cff | ||
|
|
6a466fcb12 | ||
|
|
a07c09b3d4 | ||
|
|
2c3bee16c9 | ||
|
|
9a397c1ff8 | ||
|
|
c627363fca | ||
|
|
219899fc9b | ||
|
|
d987d99913 | ||
|
|
985c32510c | ||
|
|
01ab19a263 | ||
|
|
0ba6d5de28 | ||
|
|
e6031addf5 | ||
|
|
8845babb28 | ||
|
|
ed34a59a0c | ||
|
|
767cd877b8 | ||
|
|
fd7c4a0653 | ||
|
|
26f08a59ad | ||
|
|
841b6f68dd | ||
|
|
dbe835912a | ||
|
|
6b9182645d | ||
|
|
16c1ca0bba | ||
|
|
181aea9aec | ||
|
|
422971d229 | ||
|
|
2010a3169d | ||
|
|
397b538c9d | ||
|
|
1d1d843dc7 | ||
|
|
abd6fe9f2d | ||
|
|
f5db3c08e3 | ||
|
|
0b568b2d28 | ||
|
|
42885a3df0 | ||
|
|
cd820c2dbe | ||
|
|
0944ed331b | ||
|
|
f45b9a3757 | ||
|
|
d52c552721 | ||
|
|
2a5bdbcbdc | ||
|
|
2606f7196e | ||
|
|
09a672561d | ||
|
|
cbabdf02de | ||
|
|
a65d7cdc15 | ||
|
|
1a17efcf8e | ||
|
|
9f60d63a6b | ||
|
|
4426166f1d | ||
|
|
d97ceeaa6c | ||
|
|
a7ac615bb2 | ||
|
|
90fc23205c | ||
|
|
c233fec9b9 | ||
|
|
a8df726bff | ||
|
|
ff3f26f935 | ||
|
|
a882a5f346 | ||
|
|
1b318154c2 | ||
|
|
390cf44a88 | ||
|
|
3e71253ffb | ||
|
|
748e2a81ad | ||
|
|
d3ebe43cbd | ||
|
|
7a13b9c4b7 | ||
|
|
15f9aabaf0 | ||
|
|
c617a8f354 | ||
|
|
6ac2cd4686 | ||
|
|
2833da3b2d | ||
|
|
8058a79ed0 | ||
|
|
93755a62aa | ||
|
|
d4c7e00a19 | ||
|
|
70deb7b388 | ||
|
|
c229439dec | ||
|
|
cb2dda8421 | ||
|
|
4558321ef7 | ||
|
|
9376f048be | ||
|
|
d038227941 | ||
|
|
2c885cb347 | ||
|
|
01bf13189c | ||
|
|
f92d433a3e | ||
|
|
25476f2973 | ||
|
|
1d4bff1add | ||
|
|
30864a16a2 | ||
|
|
7b492fe7ed | ||
|
|
7186c9a3a0 | ||
|
|
a5760a7462 | ||
|
|
aa5c6283a7 | ||
|
|
280955801c | ||
|
|
adc3f6d184 | ||
|
|
c9ebb6da00 | ||
|
|
a8f04a1ba5 | ||
|
|
d478e4b1f4 | ||
|
|
ac9b2e8ba4 | ||
|
|
770ee6aaec | ||
|
|
003a6ef4d2 | ||
|
|
f9e43fae29 | ||
|
|
7e1eb5a970 | ||
|
|
f231218a69 | ||
|
|
e21c9cb8f0 | ||
|
|
8597808a61 | ||
|
|
1871eed0ab | ||
|
|
8f2685b335 | ||
|
|
cd85b54dd7 | ||
|
|
6dd04142b3 | ||
|
|
0618054968 | ||
|
|
e11673d15c | ||
|
|
066a4de15f | ||
|
|
5ffac12f5b | ||
|
|
b24631345b | ||
|
|
ab3332ed8f | ||
|
|
58084c6a65 | ||
|
|
6664733650 | ||
|
|
f7a537ab91 | ||
|
|
0506d47a4f | ||
|
|
e06bcab62b | ||
|
|
90061a4b25 | ||
|
|
5a17fa53cd | ||
|
|
88c284dbf1 | ||
|
|
dd98fdbee1 | ||
|
|
af43079e33 | ||
|
|
aa6097dff8 | ||
|
|
7fa4346cd1 | ||
|
|
d286041e04 | ||
|
|
bf0f9e1fa2 | ||
|
|
d4c0dd824b | ||
|
|
528ce8c9de | ||
|
|
7c4ff7677d | ||
|
|
cb36991cb2 | ||
|
|
f15a4df79e | ||
|
|
901b7a0f12 | ||
|
|
687bcc3469 | ||
|
|
a239e435a6 | ||
|
|
75728418af | ||
|
|
893714c968 | ||
|
|
5cb4044408 | ||
|
|
4966ce447f | ||
|
|
8213bf5b6d | ||
|
|
280d90cdc4 | ||
|
|
df5a327da4 | ||
|
|
e736923312 | ||
|
|
fe4f932be4 | ||
|
|
fe7e39776b | ||
|
|
da33e480c3 | ||
|
|
19a0a7098d | ||
|
|
74d46f201a | ||
|
|
0eec061d01 | ||
|
|
7c1ad9abab | ||
|
|
3ad99011f2 | ||
|
|
cb8331f213 | ||
|
|
ffa2858d82 | ||
|
|
1cf20da416 | ||
|
|
30bc7e4f6c | ||
|
|
9f406c6725 | ||
|
|
b1ff790e43 | ||
|
|
90f304a881 | ||
|
|
99cbfa13cb | ||
|
|
ce7736a4b8 | ||
|
|
c36ed7b660 | ||
|
|
d6c4705626 | ||
|
|
9df4455f07 | ||
|
|
5e4923b5bc | ||
|
|
9d00189ac0 | ||
|
|
3af2d7c0df | ||
|
|
521222ad19 | ||
|
|
e0f5a1c1a1 | ||
|
|
fa393a53b2 | ||
|
|
43e81781a3 | ||
|
|
b03e9922a4 | ||
|
|
7206e46377 | ||
|
|
554b9a03b5 | ||
|
|
20278d23e1 | ||
|
|
81607da632 | ||
|
|
c1ec74a5b7 | ||
|
|
eaed0c098b | ||
|
|
886fb6b5a1 | ||
|
|
9fe92bc669 | ||
|
|
098e9fee8c | ||
|
|
1d0f670100 | ||
|
|
ee7f505cde | ||
|
|
4581850b05 | ||
|
|
bc757016af | ||
|
|
d3259a8430 | ||
|
|
d57107ca2a | ||
|
|
2cf606bdbd | ||
|
|
32cd559379 | ||
|
|
ad8551b746 | ||
|
|
a26bef8813 | ||
|
|
34dad07393 | ||
|
|
5453aec1d0 | ||
|
|
03a5671bb0 | ||
|
|
37c16fbb48 | ||
|
|
92431f20d7 | ||
|
|
9b6b66d22d | ||
|
|
83477c67d7 | ||
|
|
ac31392b90 | ||
|
|
201485eed6 | ||
|
|
87992f9e75 | ||
|
|
0b24721b4a | ||
|
|
8d540751e1 | ||
|
|
fc8b2ee679 | ||
|
|
bc512e775c | ||
|
|
7b9d54183c | ||
|
|
85d640c4f8 | ||
|
|
a0275aa413 | ||
|
|
7d1c4a9991 | ||
|
|
ade05d5d1b | ||
|
|
6e259f9a0e | ||
|
|
02a21b8050 | ||
|
|
5fe7c5d888 | ||
|
|
1ee4437970 | ||
|
|
a8cebfe06c | ||
|
|
0b73275933 | ||
|
|
04fec2c2f0 | ||
|
|
ccd560cbc6 | ||
|
|
43df7f18be | ||
|
|
2f18d1ff8b | ||
|
|
6c816bfdeb | ||
|
|
afa8cfce5e | ||
|
|
49ad4bdb26 | ||
|
|
e76e8b1404 | ||
|
|
9794b72607 | ||
|
|
997a29e70b | ||
|
|
a478a1c888 | ||
|
|
5db11aa49a | ||
|
|
24a650f562 | ||
|
|
a1d9bf297f | ||
|
|
92682cb11f | ||
|
|
b51b02b1d3 | ||
|
|
df410d2444 | ||
|
|
ec07380055 | ||
|
|
3a766cd826 | ||
|
|
eef7fa5b40 | ||
|
|
eb726e47c3 | ||
|
|
5378cd07bf | ||
|
|
d8b935369b | ||
|
|
4e2f396b4a | ||
|
|
34c43a2bbe | ||
|
|
f7fddbc162 | ||
|
|
4c2a53ac26 | ||
|
|
ffe1021c2a | ||
|
|
3fcbcb9455 | ||
|
|
19fbce4479 | ||
|
|
b2e0874efa | ||
|
|
ca81422c4b | ||
|
|
6bdf433e95 | ||
|
|
daba5b2102 | ||
|
|
9dbf992c40 | ||
|
|
7772749e88 | ||
|
|
0c0fd48700 | ||
|
|
41f2cdc6e6 | ||
|
|
cf572ea931 | ||
|
|
da372fbb93 | ||
|
|
92e1336db0 | ||
|
|
a9d3dffd3c | ||
|
|
5fac4abc07 | ||
|
|
28a795eddb | ||
|
|
06b824928b | ||
|
|
5b57707b86 | ||
|
|
a348febf3e | ||
|
|
7f8a7ac628 | ||
|
|
a5fab4e0f6 | ||
|
|
2724e90981 | ||
|
|
26fc80213e | ||
|
|
47890fa74e | ||
|
|
49b35a9216 | ||
|
|
a08bbbad29 | ||
|
|
3b93cf8e28 | ||
|
|
75258afb6c | ||
|
|
fca37601dd | ||
|
|
55301efa3e | ||
|
|
82052848ee | ||
|
|
25dd52fdda | ||
|
|
c891c3cff8 | ||
|
|
917e75050e | ||
|
|
a46b3aa816 | ||
|
|
60fafd399f | ||
|
|
f3d3eb43dc | ||
|
|
5ff030607e | ||
|
|
71492c5d37 | ||
|
|
f553f2d2b0 | ||
|
|
5fdff2dc6f | ||
|
|
4185de77e0 | ||
|
|
aa51a6c54e | ||
|
|
092509b3c3 | ||
|
|
695279e784 | ||
|
|
5c6bccd7b3 | ||
|
|
45c8b48b0a | ||
|
|
51130c354b | ||
|
|
79d1845266 | ||
|
|
4f1173e609 | ||
|
|
23178a2727 | ||
|
|
60ab73d8a4 | ||
|
|
2a39120b38 | ||
|
|
c5bc699c26 | ||
|
|
9cc225dede | ||
|
|
5f743f4cad | ||
|
|
a7266e38c4 | ||
|
|
ea2f202e4d | ||
|
|
c1169f0d2c | ||
|
|
37d7c178f5 | ||
|
|
c34d64b3bb | ||
|
|
8934596527 | ||
|
|
c13ac87a5b | ||
|
|
09ea2dcd10 | ||
|
|
1dd6707070 | ||
|
|
d5367fc2b2 | ||
|
|
0333406fbc | ||
|
|
6f779faa05 | ||
|
|
82fa559962 | ||
|
|
eca93cb43f | ||
|
|
04e648b3f9 | ||
|
|
6de0debb49 | ||
|
|
84929771be | ||
|
|
3b00230580 | ||
|
|
959b11d19e | ||
|
|
2ad59f1aa5 | ||
|
|
494682c2af | ||
|
|
d48d0e621f | ||
|
|
1a3382aa24 | ||
|
|
5c065d3f8a | ||
|
|
4799957d08 | ||
|
|
307f43ce12 | ||
|
|
b13fc99797 | ||
|
|
1f30f8dcf3 | ||
|
|
fbb40e1232 | ||
|
|
1d5999e50b | ||
|
|
04713d9652 | ||
|
|
050f432c10 | ||
|
|
1201f4e008 | ||
|
|
5614f57f43 | ||
|
|
f9d82b8ead | ||
|
|
fba181bfea | ||
|
|
10d20748ad | ||
|
|
25fc832ae5 | ||
|
|
fe5ef03bc8 | ||
|
|
fe158d20ed | ||
|
|
95cb311f6c | ||
|
|
e1bb98ec94 | ||
|
|
d7e0e44de0 | ||
|
|
8a54e4cd76 | ||
|
|
b89c4f95e8 | ||
|
|
087a1a1af5 | ||
|
|
db86ceca0e | ||
|
|
a54b0389ae | ||
|
|
6c826b6ecf | ||
|
|
8e864b9df4 | ||
|
|
6e0837325c | ||
|
|
b237df4b6d | ||
|
|
96f8a57f44 | ||
|
|
f5575510f5 | ||
|
|
745a72a0c4 | ||
|
|
c34b9e77a1 | ||
|
|
7e8a47cd92 | ||
|
|
a0ecab10ac | ||
|
|
185c2575b6 | ||
|
|
565f627429 | ||
|
|
ef4f483a9e | ||
|
|
92538de969 | ||
|
|
88fe1cae08 | ||
|
|
fbb59d2d6c | ||
|
|
3b9688eb2f | ||
|
|
03debbf434 | ||
|
|
f3bc909a02 | ||
|
|
c3c20acb80 | ||
|
|
eccb4530a1 | ||
|
|
3dd81071a5 | ||
|
|
d95f98f67d | ||
|
|
94797986a9 | ||
|
|
ac5e7e8973 | ||
|
|
2684c4a735 | ||
|
|
bd67f86769 | ||
|
|
e2765a3fd6 | ||
|
|
73714933d7 | ||
|
|
d3da0bf860 | ||
|
|
dc011d522f | ||
|
|
3d1ecc1881 | ||
|
|
7676f10e0c | ||
|
|
c83bdfa810 | ||
|
|
282677b8fc | ||
|
|
b2d0080637 | ||
|
|
5f1be7c815 | ||
|
|
d5e2d6b88b | ||
|
|
39a2efbcd9 | ||
|
|
063b367951 | ||
|
|
37ce59af6e | ||
|
|
2d0cd5d186 | ||
|
|
dbbded56cf | ||
|
|
67d6ac1760 | ||
|
|
48d2ce5a98 | ||
|
|
96a8a0f1fa | ||
|
|
4253a46282 | ||
|
|
660c255532 | ||
|
|
3956f1d183 | ||
|
|
234e1e6810 | ||
|
|
e9e2d0bf10 | ||
|
|
5d8a380f86 | ||
|
|
a9a06a0652 | ||
|
|
9f4b03c14f | ||
|
|
a8f93a5a9c | ||
|
|
4c52d51aa2 | ||
|
|
663b89a4a5 | ||
|
|
0a4779ed8c | ||
|
|
c09463e529 | ||
|
|
f93b029b82 | ||
|
|
929122934e | ||
|
|
dfd38150f2 | ||
|
|
11bb86a8ed | ||
|
|
05dad7e0d6 | ||
|
|
541316cd89 | ||
|
|
08c75a2d06 | ||
|
|
15a4aa3d1b | ||
|
|
acb46d3e86 | ||
|
|
000bd1b200 | ||
|
|
baf87f837a | ||
|
|
0bcc8639c1 | ||
|
|
e75b25c0c1 | ||
|
|
2cc6d17014 | ||
|
|
404bb0eafd | ||
|
|
284f0e7ccb | ||
|
|
081df4cad9 | ||
|
|
13d25939ec | ||
|
|
9b6c05ca04 | ||
|
|
8b9e78e158 | ||
|
|
a974f311d9 | ||
|
|
b034137516 | ||
|
|
b819271441 | ||
|
|
b898391124 | ||
|
|
4c57436fe8 | ||
|
|
f0479a656a | ||
|
|
41e0537eca | ||
|
|
dd04990143 | ||
|
|
d0d9344c8a | ||
|
|
64ee2ef045 | ||
|
|
061d444a8f | ||
|
|
d4cb690b8b | ||
|
|
bd50f1ce59 | ||
|
|
944cae53de | ||
|
|
17b43d021a | ||
|
|
059af3a621 | ||
|
|
524701caad | ||
|
|
34111df889 | ||
|
|
5dfca74327 | ||
|
|
12cfdac1b0 | ||
|
|
5ccf66bd9b | ||
|
|
4f344ab1a6 | ||
|
|
624ac5b81c | ||
|
|
7c2fb3506c | ||
|
|
dc4ac5568c | ||
|
|
460cfd05c6 | ||
|
|
40525d9bcf | ||
|
|
8dbf8c92cf | ||
|
|
92d417dc0c | ||
|
|
43e9a63210 | ||
|
|
4483d748e9 | ||
|
|
48f2581d07 | ||
|
|
f074f1ab36 | ||
|
|
42bea06b93 | ||
|
|
6550454d1e | ||
|
|
0a80316d09 | ||
|
|
64b98a8330 | ||
|
|
992c63480d | ||
|
|
6566f3f83d | ||
|
|
973da2de61 | ||
|
|
bf7fdd68f2 | ||
|
|
1136d367c7 | ||
|
|
e7b1c9b7cd | ||
|
|
9a03e0866b | ||
|
|
a5d26bdc81 | ||
|
|
e9cca9657f | ||
|
|
8498dd927f | ||
|
|
ccc8d2ba33 | ||
|
|
1098b0254e | ||
|
|
9eda86eb29 | ||
|
|
2d126010bc | ||
|
|
30f4744199 | ||
|
|
e26892ad90 | ||
|
|
4976b7e648 | ||
|
|
a539b629e7 | ||
|
|
8bd22b545c | ||
|
|
8d3796324d | ||
|
|
af53fe8e79 | ||
|
|
4bcff181c7 | ||
|
|
783da0c45d | ||
|
|
6ef4a6eb08 | ||
|
|
9e52513138 | ||
|
|
e9043d1e93 | ||
|
|
3dd821a975 | ||
|
|
18ba7ed086 | ||
|
|
0128385195 | ||
|
|
4c3efab946 | ||
|
|
858d427690 | ||
|
|
486666279d | ||
|
|
24d2ddada7 | ||
|
|
023d757964 | ||
|
|
e4b12d6a2d | ||
|
|
d67625a966 | ||
|
|
608f671c48 | ||
|
|
9ef1c70eb2 | ||
|
|
b7e236a693 | ||
|
|
d519a92719 | ||
|
|
a83d7c6140 | ||
|
|
d74a8636b3 | ||
|
|
d010271f5d | ||
|
|
f868d3eead | ||
|
|
166ae08465 | ||
|
|
15f3450f8c | ||
|
|
b2bc2700b3 | ||
|
|
8183f57b85 | ||
|
|
79ffb7b9b8 | ||
|
|
af108e1ac9 | ||
|
|
627bca09c0 | ||
|
|
08de2cc920 | ||
|
|
f1c87b6604 | ||
|
|
9f6c5ccccb | ||
|
|
41fab091d0 | ||
|
|
484d5a5968 | ||
|
|
eabacfafb2 | ||
|
|
2ec2e85679 | ||
|
|
e0bb6d106c | ||
|
|
20a16de9de | ||
|
|
e3d8c06ad0 | ||
|
|
7e3563f64b | ||
|
|
f188db2dab | ||
|
|
0473d232ed | ||
|
|
861e43a25b | ||
|
|
3e0fcc4b87 | ||
|
|
a355892ce5 | ||
|
|
52c0f31578 | ||
|
|
e132b54c9f | ||
|
|
dc942c5734 | ||
|
|
a7038a9eaf | ||
|
|
7664e0b187 | ||
|
|
e8ccc48815 | ||
|
|
eda40621c4 | ||
|
|
5b4c6b62a7 | ||
|
|
b7bab76232 | ||
|
|
bd3c39eaaf | ||
|
|
2fb1d6f731 | ||
|
|
ef299acbe8 | ||
|
|
005c4ded24 | ||
|
|
cfceabb4ec | ||
|
|
06095ec343 | ||
|
|
a753a654ca | ||
|
|
2dfd6c79c0 | ||
|
|
abbf0cd856 | ||
|
|
83ec50e4ab | ||
|
|
d51b6fd61d | ||
|
|
894bb05cba | ||
|
|
669720c6dc | ||
|
|
fdcbc2db86 | ||
|
|
37f0e4af3e | ||
|
|
7c14e63fef | ||
|
|
7b5088b921 | ||
|
|
66fe22d716 | ||
|
|
d2339cc7c2 | ||
|
|
d53c7f5d2d | ||
|
|
efdc6053ff | ||
|
|
ab3ec443d2 | ||
|
|
f5873ae0e4 | ||
|
|
e9197817f5 | ||
|
|
c04c8ef815 | ||
|
|
c5d1181d72 | ||
|
|
4b479ad327 | ||
|
|
be4497f768 | ||
|
|
6ad79b12a6 | ||
|
|
24fe6b3c4d | ||
|
|
f4d5f1c584 | ||
|
|
9a18ab44a6 | ||
|
|
a97530bde8 | ||
|
|
ec176bbec5 | ||
|
|
76e194ab1a | ||
|
|
460e1c87d9 | ||
|
|
66db3fd6d6 | ||
|
|
15ec342519 | ||
|
|
136d262d4c | ||
|
|
582dafd50d | ||
|
|
a827a1b105 | ||
|
|
50a62edbaf | ||
|
|
4924b39f93 | ||
|
|
afe2c9db2f | ||
|
|
d18b30da10 | ||
|
|
d6b07185ae | ||
|
|
1a32753ce9 | ||
|
|
0bab743936 | ||
|
|
6f82912701 | ||
|
|
827ffa88fe | ||
|
|
83534e2848 | ||
|
|
a7dcbea8ef | ||
|
|
36a35ef303 | ||
|
|
91eced4b26 | ||
|
|
ec5f33179a | ||
|
|
e180ae4cbd | ||
|
|
98bc81cdd5 | ||
|
|
2b549c358d | ||
|
|
d170b0d0e1 | ||
|
|
5fbdd03acb | ||
|
|
3e3ba6e7ed | ||
|
|
ea929a78e0 | ||
|
|
c845c19477 | ||
|
|
ef0d2c6234 | ||
|
|
8af5f54767 | ||
|
|
fb601ee80f | ||
|
|
72fa9d1a4a | ||
|
|
d1b21708e6 | ||
|
|
703aa07407 | ||
|
|
6e2ed61743 | ||
|
|
c9ce98c5d5 | ||
|
|
f0c23b7244 | ||
|
|
00e49e76be | ||
|
|
05eb7b35f8 | ||
|
|
f6df412350 | ||
|
|
f952b9bbcb | ||
|
|
9160021442 | ||
|
|
77e245aec3 | ||
|
|
eaf8193d37 | ||
|
|
8257b05c8f | ||
|
|
0912139fc5 | ||
|
|
4592566748 | ||
|
|
22851dd9e8 | ||
|
|
87bab96097 | ||
|
|
81ed566467 | ||
|
|
336220d998 | ||
|
|
859e71d976 | ||
|
|
deb25d916d | ||
|
|
c412a01fa6 | ||
|
|
2a9be8a28c | ||
|
|
310704e0c5 | ||
|
|
03f89c9131 | ||
|
|
8ed39f43b4 | ||
|
|
84292beef9 | ||
|
|
d612b86d7f | ||
|
|
93180d6843 | ||
|
|
644ec3caec | ||
|
|
bb5aa47d7b | ||
|
|
b9338b31bc | ||
|
|
5ed3b39219 | ||
|
|
ee55afe8c0 | ||
|
|
6bfab3d04a | ||
|
|
5f84f1378b | ||
|
|
18a63504ed | ||
|
|
44f80dc385 | ||
|
|
fe5af8308c | ||
|
|
197fc48d92 | ||
|
|
293268a004 | ||
|
|
c558d8fcaa | ||
|
|
b13ad57ea5 | ||
|
|
eba839b58e | ||
|
|
36a480a5fc | ||
|
|
68c83ea156 | ||
|
|
9102c94db2 | ||
|
|
26d6330771 | ||
|
|
c123d27b89 | ||
|
|
8aa5324892 | ||
|
|
fb448e27ad | ||
|
|
b24c872b52 | ||
|
|
fdb31f37ba | ||
|
|
87733729b1 | ||
|
|
09cbbb4570 | ||
|
|
cc2489e4ed | ||
|
|
82d71b637d | ||
|
|
c4c0e67407 | ||
|
|
d0c5e98366 | ||
|
|
83c5afdd2d | ||
|
|
c46663007b | ||
|
|
df748e5e75 | ||
|
|
e98685b6cc | ||
|
|
2374c67975 | ||
|
|
30f288a6b9 | ||
|
|
aea7609e0b | ||
|
|
700b256cad | ||
|
|
64b4372a18 | ||
|
|
32461d221a | ||
|
|
b9190e116a | ||
|
|
2d6247d48a | ||
|
|
4aaf001885 | ||
|
|
cc5726577e | ||
|
|
626ae53057 | ||
|
|
ff69f6fdfc | ||
|
|
3178af0074 | ||
|
|
98a93346fc | ||
|
|
01eea12f4e | ||
|
|
1b78881f78 | ||
|
|
a0b5f87b7d | ||
|
|
557fbc21ef | ||
|
|
7de27389aa | ||
|
|
049148305f | ||
|
|
90f468c329 | ||
|
|
cd7acbc4ce | ||
|
|
907f020bf6 | ||
|
|
a6af89755d | ||
|
|
e3ee49a868 | ||
|
|
af538c4feb | ||
|
|
4e5d5aac8c | ||
|
|
5c8526d197 | ||
|
|
4f13055a45 | ||
|
|
2d7a035297 | ||
|
|
cc6f2c00df | ||
|
|
3293a33f38 | ||
|
|
5e6dd56933 | ||
|
|
6104d6193c | ||
|
|
b45c711483 | ||
|
|
bebcefddcc | ||
|
|
68a9089d14 | ||
|
|
c6f96906ca | ||
|
|
9733fb22fd | ||
|
|
e6010e334a | ||
|
|
4f427601d4 | ||
|
|
a716a5788d | ||
|
|
a308ffebeb | ||
|
|
649667a403 | ||
|
|
97f9805afa | ||
|
|
6d0cdcd20b | ||
|
|
a8e85f2c41 | ||
|
|
2e11551bd7 | ||
|
|
ea7aae603d | ||
|
|
6c3976e657 | ||
|
|
09abd1e5cd | ||
|
|
d5d467192d | ||
|
|
d455e50a27 | ||
|
|
f7d9970842 | ||
|
|
b4a7ba239c | ||
|
|
86e3fc7075 | ||
|
|
be2ef28fad | ||
|
|
97fcdf9ce6 | ||
|
|
b9f7ea187d | ||
|
|
c8f5f1ae1d | ||
|
|
92b8b00a49 | ||
|
|
eeddb32ab6 | ||
|
|
c1a59a015c | ||
|
|
bc3b13d719 | ||
|
|
29dcbaeaa3 | ||
|
|
46f6e6d1ea | ||
|
|
c76b7a8b77 | ||
|
|
8514513af3 | ||
|
|
dc2ee92404 | ||
|
|
7cd5b881b2 | ||
|
|
63545c1f08 | ||
|
|
171862097e | ||
|
|
ab69f64957 | ||
|
|
91bf2a85d0 | ||
|
|
6315aad0bc | ||
|
|
613a0386bd | ||
|
|
a79565bb65 | ||
|
|
63213d7f10 | ||
|
|
218d7a7f15 | ||
|
|
4f5e87b1e1 | ||
|
|
8ef27ccbf6 | ||
|
|
b1e3aaf399 | ||
|
|
1af1c84132 | ||
|
|
c6a00d0e45 | ||
|
|
319556daec | ||
|
|
c096736e2b | ||
|
|
afea1c4175 | ||
|
|
f00dda7f43 | ||
|
|
8bc52b29e7 | ||
|
|
967b10311e | ||
|
|
09a600d955 | ||
|
|
a99e064c28 | ||
|
|
01f1043e1a | ||
|
|
c3316346ac | ||
|
|
19da676caf | ||
|
|
39a14d6528 | ||
|
|
198c4c7b5a | ||
|
|
698f3b4fad | ||
|
|
f3bee9e85f | ||
|
|
75f1b045c9 | ||
|
|
24bcee02c1 | ||
|
|
2b159dfb02 | ||
|
|
67f79f20dc | ||
|
|
a992871cb9 | ||
|
|
802e67d8ba | ||
|
|
5169ba8798 | ||
|
|
f41f9c2d87 | ||
|
|
d720433880 | ||
|
|
11747f43ee | ||
|
|
66b0163f7b | ||
|
|
e7006a9ac4 | ||
|
|
9ace4d7cc6 | ||
|
|
d3d8641053 | ||
|
|
2de46d7038 | ||
|
|
d1062ec050 | ||
|
|
079ba05b88 | ||
|
|
a47fef9d19 | ||
|
|
adbca4ba1a | ||
|
|
41ac9563ef | ||
|
|
9a48bcc013 | ||
|
|
aba08042ed | ||
|
|
9f9804c8a3 | ||
|
|
1f1ac06c91 | ||
|
|
d2f3f9d1b5 | ||
|
|
111688ff18 | ||
|
|
a81a29c952 | ||
|
|
9c3e677e0c | ||
|
|
02ce13c858 | ||
|
|
523d111ec6 | ||
|
|
dd6d186a08 | ||
|
|
9b8aae29dd | ||
|
|
cf406c280d | ||
|
|
7917343593 | ||
|
|
588e0c9bbc | ||
|
|
f054a0f4fd | ||
|
|
dac5b6cae8 | ||
|
|
4c1fe51786 | ||
|
|
bcafd3c9b9 | ||
|
|
318a485a92 | ||
|
|
1a46f37e92 | ||
|
|
f9484c1ba5 | ||
|
|
6f3a3c9514 | ||
|
|
2e9b009aa5 | ||
|
|
4458ebd03e | ||
|
|
84e5e488a9 | ||
|
|
1df41fbd29 | ||
|
|
b5d95fda22 | ||
|
|
3c5e144493 | ||
|
|
b1e467d34f | ||
|
|
390bc93e54 | ||
|
|
a7b2a1ed70 | ||
|
|
7e7fd97075 | ||
|
|
4bf97204d1 | ||
|
|
b9b2b179e1 | ||
|
|
e3ef424a41 | ||
|
|
387e7bc2f5 | ||
|
|
328d21e526 | ||
|
|
85579403e9 | ||
|
|
08358a52a7 | ||
|
|
6d1c190a13 | ||
|
|
4208c9f2ff | ||
|
|
a14c3a2a60 | ||
|
|
c8afca6485 | ||
|
|
eecaa2a394 | ||
|
|
62a37ac1f4 | ||
|
|
a8dd424211 | ||
|
|
9e9fafcc5c | ||
|
|
78dc8c3188 | ||
|
|
6ddcc74697 | ||
|
|
79c34eb6d2 | ||
|
|
cdf08821bb | ||
|
|
e54e9068dc | ||
|
|
2af32c76eb | ||
|
|
ae8ffeabc9 | ||
|
|
e818d40c2a | ||
|
|
e52a01abbe | ||
|
|
b81f57f1c9 | ||
|
|
8221ff520c | ||
|
|
b68f1e278e | ||
|
|
18b996e5bd | ||
|
|
50cc857a3a | ||
|
|
ea04588865 | ||
|
|
47d1202e57 | ||
|
|
1ab5b8ed9c | ||
|
|
61f944fdaa | ||
|
|
44dddd28ef | ||
|
|
d74cf435ed | ||
|
|
0808a10b03 | ||
|
|
3ec52fa83d | ||
|
|
46e44131d3 | ||
|
|
3c28277f15 | ||
|
|
2c7334b1c1 | ||
|
|
85e578f5ae | ||
|
|
7b31e75298 | ||
|
|
ccda6ba9ba | ||
|
|
042163eb58 | ||
|
|
3518b4d2de | ||
|
|
07afc8a130 | ||
|
|
9c7e13fc64 | ||
|
|
45b184b628 | ||
|
|
c589080ef2 | ||
|
|
34850a89fa | ||
|
|
469d398988 | ||
|
|
b127e90e93 | ||
|
|
0d49108cb1 | ||
|
|
629a98bbb5 | ||
|
|
0cea2b2e3c | ||
|
|
a336b44ddb | ||
|
|
16c26c09fb | ||
|
|
b0d60cc9da | ||
|
|
fe2be594be | ||
|
|
dce273f714 | ||
|
|
82813f57e1 | ||
|
|
f76cb3bcba | ||
|
|
9321bfa207 | ||
|
|
6ecd147aad | ||
|
|
dc24c1faad | ||
|
|
03ce9602ea | ||
|
|
35772ab786 | ||
|
|
0dad966d26 | ||
|
|
e43bbe79bd | ||
|
|
cec026495f | ||
|
|
0225f481de | ||
|
|
67f00e70a3 | ||
|
|
8146bbca65 | ||
|
|
e8d5d6a190 | ||
|
|
32f73fb816 | ||
|
|
e0dc84c14a | ||
|
|
65414f2b55 | ||
|
|
b3feaf91d4 | ||
|
|
587fc99023 | ||
|
|
e1396673d9 | ||
|
|
c490721d6a | ||
|
|
8fadc40656 | ||
|
|
5ee6ccdf48 | ||
|
|
81c22fcbc2 | ||
|
|
0139618f37 |
No files matched your search
@@ -0,0 +1,4 @@
|
||||
source 'https://rubygems.org'
|
||||
|
||||
gem 'xcpretty'
|
||||
gem 'xcpretty-travis-formatter'
|
||||
+16
@@ -95,3 +95,19 @@ xcuserdata
|
||||
|
||||
# Performance test baselines
|
||||
*.xcbaseline
|
||||
|
||||
# GRDBCustomSQLite USER configuration files
|
||||
SQLiteCustom/GRDBCustomSQLite-USER.h
|
||||
SQLiteCustom/GRDBCustomSQLite-USER.xcconfig
|
||||
|
||||
# CocoaPods test
|
||||
Podfile.lock
|
||||
Pods
|
||||
|
||||
# SPM
|
||||
.build
|
||||
Package.resolved
|
||||
Tests/SPM/Packages
|
||||
|
||||
# Ruby
|
||||
.ruby-version
|
||||
@@ -4,3 +4,12 @@
|
||||
[submodule "Tests/Performance/SQLite.swift"]
|
||||
path = Tests/Performance/SQLite.swift
|
||||
url = https://github.com/stephencelis/SQLite.swift.git
|
||||
[submodule "Tests/Performance/Realm"]
|
||||
path = Tests/Performance/Realm
|
||||
url = https://github.com/realm/realm-cocoa.git
|
||||
[submodule "SQLCipher/src"]
|
||||
path = SQLCipher/src
|
||||
url = https://github.com/groue/sqlcipher.git
|
||||
[submodule "SQLiteCustom/src"]
|
||||
path = SQLiteCustom/src
|
||||
url = https://github.com/swiftlyfalling/SQLiteLib
|
||||
@@ -0,0 +1 @@
|
||||
4.0
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
language: objective-c
|
||||
xcode_project: GRDB.xcodeproj
|
||||
|
||||
# Disable the default Travis-CI submodule logic
|
||||
# The various make commands ensure that the appropriate submodules are retrieved
|
||||
git:
|
||||
submodules: false
|
||||
|
||||
jobs:
|
||||
include:
|
||||
|
||||
###########################################
|
||||
## Test GRDB
|
||||
|
||||
# Test GRDBOSX (Xcode 9)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBOSX (Xcode 9, macOS 10.12)
|
||||
script: make test_framework_GRDBOSX
|
||||
|
||||
# Test GRDBWatchOS (Xcode 9)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBWatchOS (Xcode 9, watchOS)
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
# Test GRDBiOS (Xcode 9, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBiOS (Xcode 9, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget
|
||||
|
||||
# Test GRDBiOS (Xcode 9, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBiOS (Xcode 9, iOS <MIN>)
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
# Test GRDB [SPM] (Xcode 9, macOS 10.12)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDB [SPM] (Xcode 9, macOS 10.12)
|
||||
script: make test_SPM
|
||||
|
||||
###########################################
|
||||
## Test GRDB (Custom SQLite)
|
||||
|
||||
# Test GRDBCustomSQLiteOSX (Xcode 9)
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteOSX (Xcode 9, macOS 10.12)
|
||||
script: make test_framework_GRDBCustomSQLiteOSX
|
||||
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 9, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 9, iOS <MAX>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget
|
||||
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 9, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 9, iOS <MIN>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
|
||||
|
||||
###########################################
|
||||
## Test GRDB (SQLCipher)
|
||||
|
||||
# Test GRDBCipherOSX (Xcode 9)
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBCipherOSX (Xcode 9, macOS 10.12)
|
||||
script: make test_framework_GRDBCipherOSX
|
||||
|
||||
# Test GRDBCipheriOS (Xcode 9, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBCipheriOS (Xcode 9, iOS <MAX>)
|
||||
script: make test_framework_GRDBCipheriOS_maxTarget
|
||||
|
||||
# Test GRDBCipheriOS (Xcode 9, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBCipheriOS (Xcode 9, iOS <MIN>)
|
||||
script: make test_framework_GRDBCipheriOS_minTarget
|
||||
|
||||
###########################################
|
||||
## Test Installation Methods
|
||||
|
||||
# Manual Install
|
||||
- stage: Test Installation
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=Manual Install
|
||||
script: make test_install_manual
|
||||
|
||||
# Manual Install (GRDBCipher)
|
||||
- stage: Test Installation
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=Manual Install (GRDBCipher)
|
||||
script: make test_install_GRDBCipher
|
||||
|
||||
# Cocoapods Lint
|
||||
- stage: Test Installation
|
||||
osx_image: xcode9
|
||||
install:
|
||||
- gem install cocoapods # Since Travis is not always on latest version
|
||||
env:
|
||||
- TID=Cocoapods
|
||||
script: make test_CocoaPodsLint
|
||||
|
||||
# SPM Install
|
||||
- stage: Test Installation
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=SPM
|
||||
script: make test_install_SPM
|
||||
|
||||
## The following doesn’t work, as `make test_CarthageBuild` does not yet work.
|
||||
## Carthage Build
|
||||
#- stage: Carthage
|
||||
# osx_image: xcode9
|
||||
# before_install:
|
||||
# - brew update
|
||||
# - brew outdated carthage || brew upgrade carthage
|
||||
# script: make test_CarthageBuild
|
||||
+2779
-3
File diff suppressed because it is too large.
Load diff
+18
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"screenWidth" : "{130,145}",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"screenWidth" : "{146,165}",
|
||||
"scale" : "2x"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"version" : 1,
|
||||
"author" : "xcode"
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"assets" : [
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"filename" : "Circular.imageset",
|
||||
"role" : "circular"
|
||||
},
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"filename" : "Extra Large.imageset",
|
||||
"role" : "extra-large"
|
||||
},
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"filename" : "Modular.imageset",
|
||||
"role" : "modular"
|
||||
},
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"filename" : "Utilitarian.imageset",
|
||||
"role" : "utilitarian"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"version" : 1,
|
||||
"author" : "xcode"
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"screenWidth" : "{130,145}",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"screenWidth" : "{146,165}",
|
||||
"scale" : "2x"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"version" : 1,
|
||||
"author" : "xcode"
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"screenWidth" : "{130,145}",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"screenWidth" : "{146,165}",
|
||||
"scale" : "2x"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"version" : 1,
|
||||
"author" : "xcode"
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"screenWidth" : "{130,145}",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"screenWidth" : "{146,165}",
|
||||
"scale" : "2x"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"version" : 1,
|
||||
"author" : "xcode"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import WatchKit
|
||||
|
||||
class ExtensionDelegate: NSObject, WKExtensionDelegate {
|
||||
|
||||
func applicationDidFinishLaunching() {
|
||||
// Perform any final initialization of your application.
|
||||
}
|
||||
|
||||
func applicationDidBecomeActive() {
|
||||
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
|
||||
}
|
||||
|
||||
func applicationWillResignActive() {
|
||||
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
|
||||
// Use this method to pause ongoing tasks, disable timers, etc.
|
||||
}
|
||||
|
||||
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
|
||||
// Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one.
|
||||
for task in backgroundTasks {
|
||||
// Use a switch statement to check the task type
|
||||
switch task {
|
||||
case let backgroundTask as WKApplicationRefreshBackgroundTask:
|
||||
// Be sure to complete the background task once you’re done.
|
||||
backgroundTask.setTaskCompleted()
|
||||
case let snapshotTask as WKSnapshotRefreshBackgroundTask:
|
||||
// Snapshot tasks have a unique completion call, make sure to set your expiration date
|
||||
snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil)
|
||||
case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask:
|
||||
// Be sure to complete the connectivity task once you’re done.
|
||||
connectivityTask.setTaskCompleted()
|
||||
case let urlSessionTask as WKURLSessionRefreshBackgroundTask:
|
||||
// Be sure to complete the URL session task once you’re done.
|
||||
urlSessionTask.setTaskCompleted()
|
||||
default:
|
||||
// make sure to complete unhandled task types
|
||||
task.setTaskCompleted()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+15
-3
@@ -4,6 +4,8 @@
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>en</string>
|
||||
<key>CFBundleDisplayName</key>
|
||||
<string>GRDBDemoWatchOS Extension</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
@@ -13,12 +15,22 @@
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>BNDL</string>
|
||||
<string>XPC!</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>NSExtension</key>
|
||||
<dict>
|
||||
<key>NSExtensionAttributes</key>
|
||||
<dict>
|
||||
<key>WKAppBundleIdentifier</key>
|
||||
<string>com.github.groue.GRDBDemoiOS.watchkitapp</string>
|
||||
</dict>
|
||||
<key>NSExtensionPointIdentifier</key>
|
||||
<string>com.apple.watchkit</string>
|
||||
</dict>
|
||||
<key>WKExtensionDelegateClassName</key>
|
||||
<string>$(PRODUCT_MODULE_NAME).ExtensionDelegate</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,16 @@
|
||||
import WatchKit
|
||||
import Foundation
|
||||
import GRDB
|
||||
import SQLite3
|
||||
|
||||
class InterfaceController: WKInterfaceController {
|
||||
|
||||
@IBOutlet var versionLabel: WKInterfaceLabel!
|
||||
|
||||
override func awake(withContext context: Any?) {
|
||||
super.awake(withContext: context)
|
||||
|
||||
let sqliteVersion = String(cString: sqlite3_libversion(), encoding: .utf8)
|
||||
versionLabel.setText(sqliteVersion)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"size" : "24x24",
|
||||
"idiom" : "watch",
|
||||
"scale" : "2x",
|
||||
"role" : "notificationCenter",
|
||||
"subtype" : "38mm"
|
||||
},
|
||||
{
|
||||
"size" : "27.5x27.5",
|
||||
"idiom" : "watch",
|
||||
"scale" : "2x",
|
||||
"role" : "notificationCenter",
|
||||
"subtype" : "42mm"
|
||||
},
|
||||
{
|
||||
"size" : "29x29",
|
||||
"idiom" : "watch",
|
||||
"role" : "companionSettings",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"size" : "29x29",
|
||||
"idiom" : "watch",
|
||||
"role" : "companionSettings",
|
||||
"scale" : "3x"
|
||||
},
|
||||
{
|
||||
"size" : "40x40",
|
||||
"idiom" : "watch",
|
||||
"scale" : "2x",
|
||||
"role" : "appLauncher",
|
||||
"subtype" : "38mm"
|
||||
},
|
||||
{
|
||||
"size" : "86x86",
|
||||
"idiom" : "watch",
|
||||
"scale" : "2x",
|
||||
"role" : "quickLook",
|
||||
"subtype" : "38mm"
|
||||
},
|
||||
{
|
||||
"size" : "98x98",
|
||||
"idiom" : "watch",
|
||||
"scale" : "2x",
|
||||
"role" : "quickLook",
|
||||
"subtype" : "42mm"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"version" : 1,
|
||||
"author" : "xcode"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<document type="com.apple.InterfaceBuilder.WatchKit.Storyboard" version="3.0" toolsVersion="12118" systemVersion="16E195" targetRuntime="watchKit" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="AgC-eL-Hgc">
|
||||
<device id="watch38" orientation="portrait">
|
||||
<adaptation id="fullscreen"/>
|
||||
</device>
|
||||
<dependencies>
|
||||
<deployment identifier="watchOS"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12086"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBWatchKitPlugin" version="12029"/>
|
||||
</dependencies>
|
||||
<scenes>
|
||||
<!--Interface Controller-->
|
||||
<scene sceneID="aou-V4-d1y">
|
||||
<objects>
|
||||
<controller id="AgC-eL-Hgc" customClass="InterfaceController" customModule="GRDBDemoWatchOS" customModuleProvider="target">
|
||||
<items>
|
||||
<group width="1" alignment="left" verticalAlignment="center" layout="vertical" id="tkk-aG-QQF">
|
||||
<items>
|
||||
<label alignment="center" text="SQLite version" id="dGA-xX-x8V"/>
|
||||
<label alignment="center" text="Label" id="whi-N6-h8U"/>
|
||||
</items>
|
||||
</group>
|
||||
</items>
|
||||
<connections>
|
||||
<outlet property="versionLabel" destination="whi-N6-h8U" id="5xN-Gj-yNt"/>
|
||||
</connections>
|
||||
</controller>
|
||||
</objects>
|
||||
</scene>
|
||||
</scenes>
|
||||
</document>
|
||||
+12
-3
@@ -4,6 +4,8 @@
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>en</string>
|
||||
<key>CFBundleDisplayName</key>
|
||||
<string>GRDBDemoiOS</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
@@ -13,12 +15,19 @@
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>BNDL</string>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>UISupportedInterfaceOrientations</key>
|
||||
<array>
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
<string>UIInterfaceOrientationPortraitUpsideDown</string>
|
||||
</array>
|
||||
<key>WKCompanionAppBundleIdentifier</key>
|
||||
<string>com.github.groue.GRDBDemoiOS</string>
|
||||
<key>WKWatchKitApp</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
File diff suppressed because it is too large.
Load diff
+141
@@ -0,0 +1,141 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
BuildableName = "GRDBDemoWatchOS.app"
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56B036021E8D9EBE003B6DA4"
|
||||
BuildableName = "GRDBDemoiOS.app"
|
||||
BlueprintName = "GRDBDemoiOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FCA1E926430002582E0"
|
||||
BuildableName = "GRDBDemoWatchOS Extension.appex"
|
||||
BlueprintName = "GRDBDemoWatchOS Extension"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
BuildableName = "GRDBDemoWatchOS.app"
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<RemoteRunnable
|
||||
runnableDebuggingMode = "2"
|
||||
BundleIdentifier = "com.apple.carousel"
|
||||
RemotePath = "/GRDBDemoiOS">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
BuildableName = "GRDBDemoWatchOS.app"
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</RemoteRunnable>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
BuildableName = "GRDBDemoWatchOS.app"
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<RemoteRunnable
|
||||
runnableDebuggingMode = "2"
|
||||
BundleIdentifier = "com.apple.carousel"
|
||||
RemotePath = "/GRDBDemoiOS">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
BuildableName = "GRDBDemoWatchOS.app"
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</RemoteRunnable>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
BuildableName = "GRDBDemoWatchOS.app"
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56B036021E8D9EBE003B6DA4"
|
||||
BuildableName = "GRDBDemoiOS.app"
|
||||
BlueprintName = "GRDBDemoiOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56B036021E8D9EBE003B6DA4"
|
||||
BuildableName = "GRDBDemoiOS.app"
|
||||
BlueprintName = "GRDBDemoiOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Release"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56B036021E8D9EBE003B6DA4"
|
||||
BuildableName = "GRDBDemoiOS.app"
|
||||
BlueprintName = "GRDBDemoiOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56B036021E8D9EBE003B6DA4"
|
||||
BuildableName = "GRDBDemoiOS.app"
|
||||
BlueprintName = "GRDBDemoiOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -1,49 +1,11 @@
|
||||
import UIKit
|
||||
|
||||
@UIApplicationMain
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
var window: UIWindow?
|
||||
|
||||
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
|
||||
|
||||
// Set up database
|
||||
setupDatabase()
|
||||
|
||||
// Set up view controllers
|
||||
let splitViewController = self.window!.rootViewController as! UISplitViewController
|
||||
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
|
||||
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
|
||||
splitViewController.delegate = self
|
||||
|
||||
|
||||
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
|
||||
try! setupDatabase(application)
|
||||
return true
|
||||
}
|
||||
|
||||
func applicationDidReceiveMemoryWarning(application: UIApplication) {
|
||||
// Release as much memory as possible.
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
|
||||
dbQueue.releaseMemory()
|
||||
}
|
||||
}
|
||||
|
||||
func applicationDidEnterBackground(application: UIApplication) {
|
||||
let task = application.beginBackgroundTaskWithExpirationHandler(nil)
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
|
||||
// Release as much memory as possible.
|
||||
dbQueue.releaseMemory()
|
||||
application.endBackgroundTask(task)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Split view
|
||||
|
||||
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
|
||||
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
|
||||
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
|
||||
if topAsDetailController.person == nil {
|
||||
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,15 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"idiom" : "iphone",
|
||||
"size" : "20x20",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "iphone",
|
||||
"size" : "20x20",
|
||||
"scale" : "3x"
|
||||
},
|
||||
{
|
||||
"idiom" : "iphone",
|
||||
"size" : "29x29",
|
||||
@@ -21,15 +31,27 @@
|
||||
"scale" : "3x"
|
||||
},
|
||||
{
|
||||
"idiom" : "iphone",
|
||||
"size" : "60x60",
|
||||
"idiom" : "iphone",
|
||||
"filename" : "Icon-60@2x.png",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "iphone",
|
||||
"size" : "60x60",
|
||||
"idiom" : "iphone",
|
||||
"filename" : "Icon-60@3x.png",
|
||||
"scale" : "3x"
|
||||
},
|
||||
{
|
||||
"idiom" : "ipad",
|
||||
"size" : "20x20",
|
||||
"scale" : "1x"
|
||||
},
|
||||
{
|
||||
"idiom" : "ipad",
|
||||
"size" : "20x20",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "ipad",
|
||||
"size" : "29x29",
|
||||
@@ -59,6 +81,11 @@
|
||||
"idiom" : "ipad",
|
||||
"size" : "76x76",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "ipad",
|
||||
"size" : "83.5x83.5",
|
||||
"scale" : "2x"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.8 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 5.7 KiB |
@@ -1,8 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="8191" systemVersion="14F27" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" initialViewController="01J-lp-oVM">
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="8150" systemVersion="15A204g" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" initialViewController="01J-lp-oVM">
|
||||
<dependencies>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="8154"/>
|
||||
<capability name="Constraints with non-1.0 multipliers" minToolsVersion="5.1"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="8122"/>
|
||||
</dependencies>
|
||||
<scenes>
|
||||
<!--View Controller-->
|
||||
@@ -16,29 +15,8 @@
|
||||
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
|
||||
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<subviews>
|
||||
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text=" Copyright © 2015 Gwendal Roué. All rights reserved." textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" minimumFontSize="9" translatesAutoresizingMaskIntoConstraints="NO" id="obG-Y5-kRd">
|
||||
<rect key="frame" x="20" y="559" width="560" height="21"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="17"/>
|
||||
<color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="calibratedRGB"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="GRDBDemoiOS" textAlignment="center" lineBreakMode="middleTruncation" baselineAdjustment="alignBaselines" minimumFontSize="18" translatesAutoresizingMaskIntoConstraints="NO" id="GJd-Yh-RWb">
|
||||
<rect key="frame" x="20" y="180" width="560" height="43"/>
|
||||
<fontDescription key="fontDescription" type="boldSystem" pointSize="36"/>
|
||||
<color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="calibratedRGB"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
</subviews>
|
||||
<animations/>
|
||||
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
|
||||
<constraints>
|
||||
<constraint firstAttribute="centerX" secondItem="obG-Y5-kRd" secondAttribute="centerX" id="5cz-MP-9tL"/>
|
||||
<constraint firstAttribute="centerX" secondItem="GJd-Yh-RWb" secondAttribute="centerX" id="Q3B-4B-g5h"/>
|
||||
<constraint firstItem="obG-Y5-kRd" firstAttribute="leading" secondItem="Ze5-6b-2t3" secondAttribute="leading" constant="20" symbolic="YES" id="SfN-ll-jLj"/>
|
||||
<constraint firstAttribute="bottom" secondItem="obG-Y5-kRd" secondAttribute="bottom" constant="20" id="Y44-ml-fuU"/>
|
||||
<constraint firstItem="GJd-Yh-RWb" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="bottom" multiplier="1/3" constant="1" id="moa-c2-u7t"/>
|
||||
<constraint firstItem="GJd-Yh-RWb" firstAttribute="leading" secondItem="Ze5-6b-2t3" secondAttribute="leading" constant="20" symbolic="YES" id="x7j-FC-K8j"/>
|
||||
</constraints>
|
||||
</view>
|
||||
</viewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
|
||||
@@ -1,131 +1,114 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="8191" systemVersion="14F27" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="H1p-Uh-vWS">
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11129.15" systemVersion="15F34" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
|
||||
<dependencies>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="8154"/>
|
||||
<deployment identifier="iOS"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11103.10"/>
|
||||
<capability name="Constraints to layout margins" minToolsVersion="6.0"/>
|
||||
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
|
||||
</dependencies>
|
||||
<scenes>
|
||||
<!--Master-->
|
||||
<scene sceneID="pY4-Hu-kfo">
|
||||
<!--Hall Of Fame-->
|
||||
<scene sceneID="8jG-C9-QsI">
|
||||
<objects>
|
||||
<navigationController title="Master" id="RMx-3f-FxP" sceneMemberID="viewController">
|
||||
<navigationBar key="navigationBar" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" id="Pmd-2v-anx">
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
</navigationBar>
|
||||
<connections>
|
||||
<segue destination="7bK-jq-Zjz" kind="relationship" relationship="rootViewController" id="tsl-Nk-0bq"/>
|
||||
</connections>
|
||||
</navigationController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="8fS-aE-onr" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="-38" y="-630"/>
|
||||
</scene>
|
||||
<!--Detail-->
|
||||
<scene sceneID="yUG-lL-AsK">
|
||||
<objects>
|
||||
<viewController title="Detail" id="JEX-9P-axG" customClass="DetailViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<layoutGuides>
|
||||
<viewControllerLayoutGuide type="top" id="SYR-Wa-9uf"/>
|
||||
<viewControllerLayoutGuide type="bottom" id="GAO-Cl-Wes"/>
|
||||
</layoutGuides>
|
||||
<view key="view" contentMode="scaleToFill" id="svH-Pt-448">
|
||||
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
|
||||
<tableViewController id="cyv-nk-Plb" customClass="SimplePersonsViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="oON-zg-8kO">
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<subviews>
|
||||
<label clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleToFill" text="Detail view content goes here" textAlignment="center" lineBreakMode="tailTruncation" minimumFontSize="10" translatesAutoresizingMaskIntoConstraints="NO" id="0XM-y9-sOw">
|
||||
<rect key="frame" x="20" y="292" width="560" height="17"/>
|
||||
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
|
||||
<fontDescription key="fontDescription" type="system" size="system"/>
|
||||
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
</subviews>
|
||||
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
|
||||
<constraints>
|
||||
<constraint firstItem="0XM-y9-sOw" firstAttribute="leading" secondItem="svH-Pt-448" secondAttribute="leading" constant="20" symbolic="YES" id="Tsc-yG-G1q"/>
|
||||
<constraint firstItem="0XM-y9-sOw" firstAttribute="centerY" secondItem="svH-Pt-448" secondAttribute="centerY" id="jWN-iV-94e"/>
|
||||
<constraint firstAttribute="trailing" secondItem="0XM-y9-sOw" secondAttribute="trailing" constant="20" symbolic="YES" id="tHV-ZD-HQj"/>
|
||||
</constraints>
|
||||
</view>
|
||||
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<prototypes>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" reuseIdentifier="Person" textLabel="XIE-DF-pSO" detailTextLabel="vyz-CH-eMb" style="IBUITableViewCellStyleValue1" id="V5t-oJ-KD9">
|
||||
<frame key="frameInset" minY="92" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="V5t-oJ-KD9" id="Coo-th-ywF">
|
||||
<frame key="frameInset" width="342" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="XIE-DF-pSO">
|
||||
<frame key="frameInset" minX="15" minY="12" width="31.5" height="19.5"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<color key="textColor" white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Detail" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="vyz-CH-eMb">
|
||||
<frame key="frameInset" minX="298.5" minY="12" width="41.5" height="19.5"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<color key="textColor" red="0.55686274509803924" green="0.55686274509803924" blue="0.57647058823529407" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
</subviews>
|
||||
</tableViewCellContentView>
|
||||
<connections>
|
||||
<segue destination="iNr-Oe-muq" kind="show" identifier="EditPerson" id="czF-1h-sYn"/>
|
||||
</connections>
|
||||
</tableViewCell>
|
||||
</prototypes>
|
||||
<connections>
|
||||
<outlet property="dataSource" destination="cyv-nk-Plb" id="uBb-Bn-Lhg"/>
|
||||
<outlet property="delegate" destination="cyv-nk-Plb" id="nLb-Ak-ZXS"/>
|
||||
</connections>
|
||||
</tableView>
|
||||
<toolbarItems/>
|
||||
<navigationItem key="navigationItem" title="Detail" id="mOI-FS-AaM"/>
|
||||
<navigationItem key="navigationItem" title="Hall Of Fame" id="YLU-iz-PGw"/>
|
||||
<simulatedToolbarMetrics key="simulatedBottomBarMetrics"/>
|
||||
<connections>
|
||||
<outlet property="detailDescriptionLabel" destination="0XM-y9-sOw" id="deQ-Na-JPF"/>
|
||||
<segue destination="ein-Sr-i8w" kind="presentation" identifier="NewPerson" id="zii-bJ-cOA"/>
|
||||
</connections>
|
||||
</viewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="FJe-Yq-33r" sceneMemberID="firstResponder"/>
|
||||
</tableViewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="PrM-ex-2C8" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="709" y="129"/>
|
||||
<point key="canvasLocation" x="630" y="640"/>
|
||||
</scene>
|
||||
<!--Person Edition View Controller-->
|
||||
<scene sceneID="hZT-8U-F5G">
|
||||
<scene sceneID="Juk-Ad-tZ2">
|
||||
<objects>
|
||||
<tableViewController id="yMU-Wr-YuI" customClass="PersonEditionViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="static" style="grouped" separatorStyle="default" rowHeight="44" sectionHeaderHeight="18" sectionFooterHeight="18" id="W7Z-fg-c9y">
|
||||
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
|
||||
<tableViewController id="iNr-Oe-muq" customClass="PersonEditionViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="static" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="vlV-lc-eQA">
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<color key="backgroundColor" cocoaTouchSystemColor="groupTableViewBackgroundColor"/>
|
||||
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<sections>
|
||||
<tableViewSection id="jAm-13-xC3">
|
||||
<tableViewSection id="Nzq-eO-jT3">
|
||||
<cells>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="M9a-av-50p">
|
||||
<rect key="frame" x="0.0" y="99" width="600" height="44"/>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="2gb-gB-918">
|
||||
<rect key="frame" x="0.0" y="64" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="M9a-av-50p" id="z18-Cs-DYr">
|
||||
<rect key="frame" x="0.0" y="0.0" width="600" height="43"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="2gb-gB-918" id="iyM-TJ-JB4">
|
||||
<frame key="frameInset" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" textAlignment="right" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="BDD-vR-uvL">
|
||||
<rect key="frame" x="106" y="11" width="479" height="21"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="17"/>
|
||||
<textInputTraits key="textInputTraits" autocapitalizationType="words" autocorrectionType="no" spellCheckingType="no"/>
|
||||
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Name" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="m5m-Zs-j0z">
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<textInputTraits key="textInputTraits" autocapitalizationType="words" autocorrectionType="no" spellCheckingType="no" returnKeyType="next"/>
|
||||
<connections>
|
||||
<outlet property="delegate" destination="yMU-Wr-YuI" id="kl9-oG-bcm"/>
|
||||
<outlet property="delegate" destination="iNr-Oe-muq" id="K2p-7d-teD"/>
|
||||
</connections>
|
||||
</textField>
|
||||
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="1000" verticalHuggingPriority="251" horizontalCompressionResistancePriority="1000" text="First Name" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="fUF-iv-npM">
|
||||
<rect key="frame" x="15" y="11" width="83" height="21"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="17"/>
|
||||
<color key="textColor" red="0.1137254902" green="0.47843137250000001" blue="0.98039215690000003" alpha="1" colorSpace="calibratedRGB"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
</subviews>
|
||||
<constraints>
|
||||
<constraint firstItem="BDD-vR-uvL" firstAttribute="centerY" secondItem="z18-Cs-DYr" secondAttribute="centerY" id="9Rw-U2-gEE"/>
|
||||
<constraint firstAttribute="trailing" secondItem="BDD-vR-uvL" secondAttribute="trailing" constant="15" id="nQF-Sy-r5l"/>
|
||||
<constraint firstItem="fUF-iv-npM" firstAttribute="centerY" secondItem="z18-Cs-DYr" secondAttribute="centerY" id="ofb-oL-lAk"/>
|
||||
<constraint firstItem="BDD-vR-uvL" firstAttribute="leading" secondItem="fUF-iv-npM" secondAttribute="trailing" constant="8" symbolic="YES" id="pL4-Tm-5q7"/>
|
||||
<constraint firstItem="fUF-iv-npM" firstAttribute="leading" secondItem="z18-Cs-DYr" secondAttribute="leading" constant="15" id="tBn-VL-Q7E"/>
|
||||
<constraint firstItem="m5m-Zs-j0z" firstAttribute="leading" secondItem="iyM-TJ-JB4" secondAttribute="leadingMargin" constant="10" id="9cK-nj-70V"/>
|
||||
<constraint firstAttribute="trailingMargin" secondItem="m5m-Zs-j0z" secondAttribute="trailing" id="JsE-8v-XAS"/>
|
||||
<constraint firstItem="m5m-Zs-j0z" firstAttribute="centerY" secondItem="iyM-TJ-JB4" secondAttribute="centerY" id="psG-tW-QrM"/>
|
||||
</constraints>
|
||||
</tableViewCellContentView>
|
||||
</tableViewCell>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="TEu-C2-7tX">
|
||||
<rect key="frame" x="0.0" y="143" width="600" height="44"/>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="vp3-Ft-Gth">
|
||||
<rect key="frame" x="0.0" y="108" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="TEu-C2-7tX" id="awh-JA-Hz6">
|
||||
<rect key="frame" x="0.0" y="0.0" width="600" height="43"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="vp3-Ft-Gth" id="ccO-0O-u72">
|
||||
<frame key="frameInset" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" textAlignment="right" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="iqx-ux-kA0">
|
||||
<rect key="frame" x="105" y="11" width="480" height="21"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="17"/>
|
||||
<textInputTraits key="textInputTraits" autocapitalizationType="words" autocorrectionType="no" spellCheckingType="no"/>
|
||||
<connections>
|
||||
<outlet property="delegate" destination="yMU-Wr-YuI" id="pIN-qZ-ntI"/>
|
||||
</connections>
|
||||
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Score" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="rZ9-Fa-cyr">
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<textInputTraits key="textInputTraits" autocorrectionType="no" spellCheckingType="no" keyboardType="numberPad" returnKeyType="done"/>
|
||||
</textField>
|
||||
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="1000" verticalHuggingPriority="251" horizontalCompressionResistancePriority="1000" text="Last Name" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="7dD-VT-wdQ">
|
||||
<rect key="frame" x="15" y="11" width="82" height="21"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="17"/>
|
||||
<color key="textColor" red="0.1137254902" green="0.47843137250000001" blue="0.98039215690000003" alpha="1" colorSpace="calibratedRGB"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
</subviews>
|
||||
<constraints>
|
||||
<constraint firstAttribute="trailing" secondItem="iqx-ux-kA0" secondAttribute="trailing" constant="15" id="UVH-DD-pHC"/>
|
||||
<constraint firstItem="7dD-VT-wdQ" firstAttribute="centerY" secondItem="awh-JA-Hz6" secondAttribute="centerY" id="Vwn-I3-e7h"/>
|
||||
<constraint firstItem="iqx-ux-kA0" firstAttribute="centerY" secondItem="awh-JA-Hz6" secondAttribute="centerY" id="VzL-HK-apN"/>
|
||||
<constraint firstItem="iqx-ux-kA0" firstAttribute="leading" secondItem="7dD-VT-wdQ" secondAttribute="trailing" constant="8" symbolic="YES" id="fDY-Ju-iSw"/>
|
||||
<constraint firstItem="7dD-VT-wdQ" firstAttribute="leading" secondItem="awh-JA-Hz6" secondAttribute="leading" constant="15" id="j64-an-fjP"/>
|
||||
<constraint firstAttribute="trailingMargin" secondItem="rZ9-Fa-cyr" secondAttribute="trailing" id="Gso-FU-Ct1"/>
|
||||
<constraint firstItem="rZ9-Fa-cyr" firstAttribute="centerY" secondItem="ccO-0O-u72" secondAttribute="centerY" id="UqA-ea-emb"/>
|
||||
<constraint firstItem="rZ9-Fa-cyr" firstAttribute="leading" secondItem="ccO-0O-u72" secondAttribute="leadingMargin" constant="10" id="WrY-St-72v"/>
|
||||
</constraints>
|
||||
</tableViewCellContentView>
|
||||
</tableViewCell>
|
||||
@@ -133,129 +116,195 @@
|
||||
</tableViewSection>
|
||||
</sections>
|
||||
<connections>
|
||||
<outlet property="dataSource" destination="yMU-Wr-YuI" id="fDY-MJ-pJo"/>
|
||||
<outlet property="delegate" destination="yMU-Wr-YuI" id="Un1-A3-CJp"/>
|
||||
<outlet property="dataSource" destination="iNr-Oe-muq" id="67O-XE-MeV"/>
|
||||
<outlet property="delegate" destination="iNr-Oe-muq" id="vLD-QQ-zR2"/>
|
||||
</connections>
|
||||
</tableView>
|
||||
<toolbarItems/>
|
||||
<navigationItem key="navigationItem" id="Rwz-Rp-lmd">
|
||||
<barButtonItem key="rightBarButtonItem" style="done" systemItem="done" id="NJu-k4-mIi">
|
||||
<navigationItem key="navigationItem" id="U4g-xG-W8b">
|
||||
<barButtonItem key="leftBarButtonItem" systemItem="cancel" id="VIN-Hi-Twt">
|
||||
<connections>
|
||||
<segue destination="FMm-Lo-i3b" kind="unwind" identifier="commit" unwindAction="commitPersonEdition:" id="dkC-cp-6iC"/>
|
||||
<segue destination="lTz-K0-aRY" kind="unwind" unwindAction="cancelPersonEdition:" id="fOs-ol-qJL"/>
|
||||
</connections>
|
||||
</barButtonItem>
|
||||
<barButtonItem key="rightBarButtonItem" systemItem="done" id="2um-u5-BhV">
|
||||
<connections>
|
||||
<segue destination="lTz-K0-aRY" kind="unwind" identifier="" unwindAction="commitPersonEdition:" id="Y1E-dI-wcl"/>
|
||||
</connections>
|
||||
</barButtonItem>
|
||||
</navigationItem>
|
||||
<simulatedToolbarMetrics key="simulatedBottomBarMetrics"/>
|
||||
<connections>
|
||||
<outlet property="firstNameTableViewCell" destination="M9a-av-50p" id="vXh-ik-bqv"/>
|
||||
<outlet property="firstNameTextField" destination="BDD-vR-uvL" id="BYU-BL-kha"/>
|
||||
<outlet property="lastNameTableViewCell" destination="TEu-C2-7tX" id="wDv-if-Gkl"/>
|
||||
<outlet property="lastNameTextField" destination="iqx-ux-kA0" id="wOu-gU-WlV"/>
|
||||
<outlet property="cancelBarButtonItem" destination="VIN-Hi-Twt" id="dET-mF-ZXe"/>
|
||||
<outlet property="commitBarButtonItem" destination="2um-u5-BhV" id="Jym-us-zdP"/>
|
||||
<outlet property="nameCell" destination="2gb-gB-918" id="ch2-MB-uRm"/>
|
||||
<outlet property="nameTextField" destination="m5m-Zs-j0z" id="A6a-pw-q8s"/>
|
||||
<outlet property="scoreCell" destination="vp3-Ft-Gth" id="b8A-42-8Dw"/>
|
||||
<outlet property="scoreTextField" destination="rZ9-Fa-cyr" id="4kw-gV-uih"/>
|
||||
</connections>
|
||||
</tableViewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="23u-wY-35e" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
<exit id="FMm-Lo-i3b" userLabel="Exit" sceneMemberID="exit"/>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="fNC-Ls-uRw" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
<exit id="lTz-K0-aRY" userLabel="Exit" sceneMemberID="exit"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="2301" y="-630"/>
|
||||
<point key="canvasLocation" x="1450" y="1435"/>
|
||||
</scene>
|
||||
<!--GRDB Demo-->
|
||||
<scene sceneID="XjB-aQ-v94">
|
||||
<objects>
|
||||
<tableViewController id="9kw-c5-KTk" customClass="DemoViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="static" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="f4Y-o2-7VW">
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<sections>
|
||||
<tableViewSection id="dCg-qU-h2X">
|
||||
<cells>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" textLabel="clL-nG-zPX" style="IBUITableViewCellStyleDefault" id="kJB-sX-YAb">
|
||||
<rect key="frame" x="0.0" y="64" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="kJB-sX-YAb" id="f5l-ob-3DG">
|
||||
<frame key="frameInset" width="342" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Simple TableView" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="clL-nG-zPX">
|
||||
<frame key="frameInset" minX="15" width="325" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<color key="textColor" white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
</subviews>
|
||||
</tableViewCellContentView>
|
||||
<connections>
|
||||
<segue destination="cyv-nk-Plb" kind="show" id="Bgq-9t-jRc"/>
|
||||
</connections>
|
||||
</tableViewCell>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" textLabel="I78-c5-0kp" style="IBUITableViewCellStyleDefault" id="q4C-mT-5mi">
|
||||
<rect key="frame" x="0.0" y="108" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="q4C-mT-5mi" id="2Cu-K1-hiz">
|
||||
<frame key="frameInset" width="342" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="FetchedRecordsController" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="I78-c5-0kp">
|
||||
<frame key="frameInset" minX="15" width="325" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<color key="textColor" white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
</subviews>
|
||||
</tableViewCellContentView>
|
||||
<connections>
|
||||
<segue destination="PJp-Eq-ZjA" kind="show" id="1fk-ZR-6XN"/>
|
||||
</connections>
|
||||
</tableViewCell>
|
||||
</cells>
|
||||
</tableViewSection>
|
||||
</sections>
|
||||
<connections>
|
||||
<outlet property="dataSource" destination="9kw-c5-KTk" id="IK7-Os-Odc"/>
|
||||
<outlet property="delegate" destination="9kw-c5-KTk" id="U7E-yB-s8d"/>
|
||||
</connections>
|
||||
</tableView>
|
||||
<navigationItem key="navigationItem" title="GRDB Demo" id="z0z-02-Ucy"/>
|
||||
</tableViewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="OhY-4B-BcJ" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="-190" y="1435"/>
|
||||
</scene>
|
||||
<!--Navigation Controller-->
|
||||
<scene sceneID="GQC-vK-8JG">
|
||||
<scene sceneID="2KX-IU-Z5Q">
|
||||
<objects>
|
||||
<navigationController id="IJV-AU-xKl" sceneMemberID="viewController">
|
||||
<navigationBar key="navigationBar" contentMode="scaleToFill" id="y7A-ea-ZFU">
|
||||
<navigationController id="ein-Sr-i8w" sceneMemberID="viewController">
|
||||
<navigationBar key="navigationBar" contentMode="scaleToFill" id="zIT-dB-Mfo">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
</navigationBar>
|
||||
<connections>
|
||||
<segue destination="yMU-Wr-YuI" kind="relationship" relationship="rootViewController" id="1PW-hN-E5f"/>
|
||||
<segue destination="iNr-Oe-muq" kind="relationship" relationship="rootViewController" id="e5b-3U-9Vz"/>
|
||||
</connections>
|
||||
</navigationController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="4jR-xV-SBm" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="kNr-vk-I5l" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="1481" y="-630"/>
|
||||
</scene>
|
||||
<!--Split View Controller-->
|
||||
<scene sceneID="Nki-YV-4Qg">
|
||||
<objects>
|
||||
<splitViewController id="H1p-Uh-vWS" sceneMemberID="viewController">
|
||||
<toolbarItems/>
|
||||
<connections>
|
||||
<segue destination="RMx-3f-FxP" kind="relationship" relationship="masterViewController" id="BlO-5A-QYV"/>
|
||||
<segue destination="vC3-pB-5Vb" kind="relationship" relationship="detailViewController" id="Tll-UG-LXB"/>
|
||||
</connections>
|
||||
</splitViewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="cZU-Oi-B1e" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="-856" y="-330"/>
|
||||
</scene>
|
||||
<!--Master-->
|
||||
<scene sceneID="smW-Zh-WAh">
|
||||
<objects>
|
||||
<tableViewController title="Master" clearsSelectionOnViewWillAppear="NO" id="7bK-jq-Zjz" customClass="MasterViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="22" sectionFooterHeight="22" id="r7i-6Z-zg0">
|
||||
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
|
||||
<prototypes>
|
||||
<tableViewCell contentMode="scaleToFill" selectionStyle="blue" hidesAccessoryWhenEditing="NO" indentationLevel="1" indentationWidth="0.0" reuseIdentifier="Cell" textLabel="Arm-wq-HPj" style="IBUITableViewCellStyleDefault" id="WCw-Qf-5nD">
|
||||
<rect key="frame" x="0.0" y="86" width="600" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="WCw-Qf-5nD" id="37f-cq-3Eg">
|
||||
<rect key="frame" x="0.0" y="0.0" width="600" height="43"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" text="Title" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="Arm-wq-HPj">
|
||||
<rect key="frame" x="15" y="0.0" width="570" height="43"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<fontDescription key="fontDescription" type="boldSystem" pointSize="20"/>
|
||||
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
|
||||
<color key="highlightedColor" red="1" green="1" blue="1" alpha="1" colorSpace="calibratedRGB"/>
|
||||
</label>
|
||||
</subviews>
|
||||
</tableViewCellContentView>
|
||||
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
|
||||
<connections>
|
||||
<segue destination="vC3-pB-5Vb" kind="showDetail" identifier="showPerson" id="vhz-QC-pld"/>
|
||||
</connections>
|
||||
</tableViewCell>
|
||||
</prototypes>
|
||||
<sections/>
|
||||
<connections>
|
||||
<outlet property="dataSource" destination="7bK-jq-Zjz" id="Gho-Na-rnu"/>
|
||||
<outlet property="delegate" destination="7bK-jq-Zjz" id="RA6-mI-bju"/>
|
||||
</connections>
|
||||
</tableView>
|
||||
<navigationItem key="navigationItem" title="Master" id="Zdf-7t-Un8">
|
||||
<barButtonItem key="rightBarButtonItem" systemItem="add" id="q2y-Jp-QNL">
|
||||
<connections>
|
||||
<segue destination="IJV-AU-xKl" kind="popoverPresentation" identifier="editNewPerson" popoverAnchorBarButtonItem="q2y-Jp-QNL" id="KcV-Yc-DEu">
|
||||
<popoverArrowDirection key="popoverArrowDirection" up="YES" down="YES" left="YES" right="YES"/>
|
||||
</segue>
|
||||
</connections>
|
||||
</barButtonItem>
|
||||
</navigationItem>
|
||||
</tableViewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="Rux-fX-hf1" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="709" y="-630"/>
|
||||
<point key="canvasLocation" x="630" y="1435"/>
|
||||
</scene>
|
||||
<!--Navigation Controller-->
|
||||
<scene sceneID="r7l-gg-dq7">
|
||||
<scene sceneID="N1X-4j-Re4">
|
||||
<objects>
|
||||
<navigationController id="vC3-pB-5Vb" sceneMemberID="viewController">
|
||||
<navigationBar key="navigationBar" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" id="DjV-YW-jjY">
|
||||
<navigationController id="UAh-8N-CM8" sceneMemberID="viewController">
|
||||
<navigationBar key="navigationBar" contentMode="scaleToFill" id="U7d-1C-GnL">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
</navigationBar>
|
||||
<connections>
|
||||
<segue destination="JEX-9P-axG" kind="relationship" relationship="rootViewController" id="GKi-kA-LjT"/>
|
||||
<segue destination="9kw-c5-KTk" kind="relationship" relationship="rootViewController" id="qDW-qI-Hyg"/>
|
||||
</connections>
|
||||
</navigationController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="SLD-UC-DBI" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="sVt-e9-ghQ" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="-45" y="129"/>
|
||||
<point key="canvasLocation" x="-1006" y="1435"/>
|
||||
</scene>
|
||||
<!--Hall Of Fame-->
|
||||
<scene sceneID="9su-ms-vdJ">
|
||||
<objects>
|
||||
<tableViewController id="PJp-Eq-ZjA" customClass="PersonsViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="tX0-ON-WSI">
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<prototypes>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" reuseIdentifier="Person" textLabel="G8y-VE-YRu" detailTextLabel="NNc-J4-xiE" style="IBUITableViewCellStyleValue1" id="bFj-Hd-fwd">
|
||||
<frame key="frameInset" minY="92" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="bFj-Hd-fwd" id="kDf-TZ-xhb">
|
||||
<frame key="frameInset" width="342" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="G8y-VE-YRu">
|
||||
<frame key="frameInset" minX="15" minY="12" width="31.5" height="19.5"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<color key="textColor" white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Detail" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="NNc-J4-xiE">
|
||||
<frame key="frameInset" minX="298.5" minY="12" width="41.5" height="19.5"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<color key="textColor" red="0.5568627451" green="0.5568627451" blue="0.57647058819999997" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
</subviews>
|
||||
</tableViewCellContentView>
|
||||
<connections>
|
||||
<segue destination="iNr-Oe-muq" kind="show" identifier="EditPerson" id="Lgu-Yd-HSy"/>
|
||||
</connections>
|
||||
</tableViewCell>
|
||||
</prototypes>
|
||||
<connections>
|
||||
<outlet property="dataSource" destination="PJp-Eq-ZjA" id="MkQ-WQ-sTh"/>
|
||||
<outlet property="delegate" destination="PJp-Eq-ZjA" id="quj-Sp-DuL"/>
|
||||
</connections>
|
||||
</tableView>
|
||||
<toolbarItems>
|
||||
<barButtonItem title="Item" id="hMF-Rv-dAe"/>
|
||||
</toolbarItems>
|
||||
<navigationItem key="navigationItem" title="Hall Of Fame" id="QIv-M6-kT1">
|
||||
<barButtonItem key="rightBarButtonItem" systemItem="add" id="2bK-Fl-55Q"/>
|
||||
</navigationItem>
|
||||
<simulatedToolbarMetrics key="simulatedBottomBarMetrics"/>
|
||||
<connections>
|
||||
<segue destination="ein-Sr-i8w" kind="presentation" identifier="NewPerson" id="7PC-xN-zD4"/>
|
||||
</connections>
|
||||
</tableViewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="af5-Qo-AkD" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="630" y="2254"/>
|
||||
</scene>
|
||||
</scenes>
|
||||
<inferredMetricsTieBreakers>
|
||||
<segue reference="vhz-QC-pld"/>
|
||||
<segue reference="7PC-xN-zD4"/>
|
||||
<segue reference="czF-1h-sYn"/>
|
||||
</inferredMetricsTieBreakers>
|
||||
</document>
|
||||
@@ -1,60 +1,56 @@
|
||||
import GRDB
|
||||
import UIKit
|
||||
|
||||
// The columns for the GRDB Query Interface
|
||||
//
|
||||
// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
|
||||
struct Col {
|
||||
static let id = SQLColumn("id")
|
||||
static let firstName = SQLColumn("firstName")
|
||||
static let lastName = SQLColumn("lastName")
|
||||
}
|
||||
|
||||
|
||||
// The shared database queue, stored in a global.
|
||||
// It is initialized in setupDatabase()
|
||||
|
||||
// The shared database queue
|
||||
var dbQueue: DatabaseQueue!
|
||||
|
||||
func setupDatabase() {
|
||||
func setupDatabase(_ application: UIApplication) throws {
|
||||
|
||||
// Connect to the database
|
||||
//
|
||||
// See https://github.com/groue/GRDB.swift/#database-queues
|
||||
// See https://github.com/groue/GRDB.swift/#database-connections
|
||||
|
||||
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as NSString
|
||||
let databasePath = documentsPath.stringByAppendingPathComponent("db.sqlite")
|
||||
dbQueue = try! DatabaseQueue(path: databasePath)
|
||||
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString
|
||||
let databasePath = documentsPath.appendingPathComponent("db.sqlite")
|
||||
dbQueue = try DatabaseQueue(path: databasePath)
|
||||
|
||||
|
||||
// SQLite does not support Unicode: let's add a custom collation which will
|
||||
// allow us to sort persons by name.
|
||||
//
|
||||
// See https://github.com/groue/GRDB.swift/#string-comparison
|
||||
// Be a nice iOS citizen, and don't consume too much memory
|
||||
// See https://github.com/groue/GRDB.swift/#memory-management
|
||||
|
||||
let collation = DatabaseCollation("localized_case_insensitive") { (lhs, rhs) in
|
||||
return (lhs as NSString).localizedCaseInsensitiveCompare(rhs)
|
||||
}
|
||||
dbQueue.addCollation(collation)
|
||||
dbQueue.setupMemoryManagement(in: application)
|
||||
|
||||
|
||||
// Use DatabaseMigrator to setup the database
|
||||
//
|
||||
// See https://github.com/groue/GRDB.swift/#migrations
|
||||
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
migrator.registerMigration("createPersons") { db in
|
||||
try db.execute(
|
||||
"CREATE TABLE persons (" +
|
||||
"id INTEGER PRIMARY KEY, " +
|
||||
"firstName TEXT COLLATE localized_case_insensitive, " +
|
||||
"lastName TEXT COLLATE localized_case_insensitive" +
|
||||
")")
|
||||
|
||||
// Create a table
|
||||
// See https://github.com/groue/GRDB.swift#create-tables
|
||||
|
||||
try db.create(table: "persons") { t in
|
||||
// An integer primary key auto-generates unique IDs
|
||||
t.column("id", .integer).primaryKey()
|
||||
|
||||
// Sort person names in a localized case insensitive fashion by default
|
||||
// See https://github.com/groue/GRDB.swift/#unicode
|
||||
t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare)
|
||||
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
|
||||
// Populate the persons table with random data
|
||||
for _ in 0..<8 {
|
||||
try Person(name: Person.randomName(), score: Person.randomScore()).insert(db)
|
||||
}
|
||||
}
|
||||
migrator.registerMigration("addPersons") { db in
|
||||
try Person(firstName: "Arthur", lastName: "Miller").insert(db)
|
||||
try Person(firstName: "Barbra", lastName: "Streisand").insert(db)
|
||||
try Person(firstName: "Cinderella").insert(db)
|
||||
}
|
||||
try! migrator.migrate(dbQueue)
|
||||
}
|
||||
|
||||
// // Migrations for future application versions will be inserted here:
|
||||
// migrator.registerMigration(...) { db in
|
||||
// ...
|
||||
// }
|
||||
|
||||
try migrator.migrate(dbQueue)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import UIKit
|
||||
|
||||
class DemoViewController: UITableViewController {
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(true)
|
||||
navigationController?.isToolbarHidden = true
|
||||
navigationItem.backBarButtonItem = UIBarButtonItem(title: "Demo", style: .plain, target: nil, action: nil)
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
import UIKit
|
||||
|
||||
class DetailViewController: UIViewController {
|
||||
@IBOutlet weak var detailDescriptionLabel: UILabel!
|
||||
|
||||
var person: Person! {
|
||||
didSet {
|
||||
self.configureView()
|
||||
}
|
||||
}
|
||||
|
||||
func configureView() {
|
||||
guard isViewLoaded() else {
|
||||
return
|
||||
}
|
||||
guard person != nil else {
|
||||
return
|
||||
}
|
||||
detailDescriptionLabel.text = person.fullName
|
||||
}
|
||||
|
||||
override func viewWillAppear(animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
configureView()
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
@@ -4,6 +4,8 @@
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>en</string>
|
||||
<key>CFBundleDisplayName</key>
|
||||
<string>GRDB Demo</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
@@ -16,8 +18,6 @@
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>LSRequiresIPhoneOS</key>
|
||||
@@ -30,28 +30,9 @@
|
||||
<array>
|
||||
<string>armv7</string>
|
||||
</array>
|
||||
<key>UIStatusBarTintParameters</key>
|
||||
<dict>
|
||||
<key>UINavigationBar</key>
|
||||
<dict>
|
||||
<key>Style</key>
|
||||
<string>UIBarStyleDefault</string>
|
||||
<key>Translucent</key>
|
||||
<false/>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>UISupportedInterfaceOrientations</key>
|
||||
<array>
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||
</array>
|
||||
<key>UISupportedInterfaceOrientations~ipad</key>
|
||||
<array>
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
<string>UIInterfaceOrientationPortraitUpsideDown</string>
|
||||
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,96 +0,0 @@
|
||||
import UIKit
|
||||
|
||||
class MasterViewController: UITableViewController {
|
||||
var detailViewController: DetailViewController? = nil
|
||||
var persons: [Person] = []
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
self.navigationItem.leftBarButtonItem = self.editButtonItem()
|
||||
if let split = self.splitViewController {
|
||||
let controllers = split.viewControllers
|
||||
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
|
||||
}
|
||||
}
|
||||
|
||||
override func viewWillAppear(animated: Bool) {
|
||||
// Reload persons, and the tableView
|
||||
reloadPersons()
|
||||
tableView.reloadData()
|
||||
|
||||
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
|
||||
super.viewWillAppear(animated)
|
||||
}
|
||||
|
||||
func reloadPersons() {
|
||||
persons = dbQueue.inDatabase { db in
|
||||
Person.order(Col.firstName, Col.lastName).fetchAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Segues
|
||||
|
||||
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
|
||||
if segue.identifier == "showPerson" {
|
||||
let detailViewController = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
|
||||
detailViewController.person = persons[self.tableView.indexPathForSelectedRow!.row]
|
||||
detailViewController.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
|
||||
detailViewController.navigationItem.leftItemsSupplementBackButton = true
|
||||
}
|
||||
else if segue.identifier == "editNewPerson" {
|
||||
let personEditionViewController = (segue.destinationViewController as! UINavigationController).topViewController as! PersonEditionViewController
|
||||
personEditionViewController.person = Person()
|
||||
}
|
||||
}
|
||||
|
||||
// Unwind action: commit person edition
|
||||
@IBAction func commitPersonEdition(segue: UIStoryboardSegue) {
|
||||
let personEditionViewController = segue.sourceViewController as! PersonEditionViewController
|
||||
let person = personEditionViewController.person
|
||||
|
||||
// Ignore person with no name
|
||||
guard (person.firstName ?? "").characters.count > 0 || (person.lastName ?? "").characters.count > 0 else {
|
||||
return
|
||||
}
|
||||
|
||||
// Save person
|
||||
try! dbQueue.inDatabase { db in
|
||||
try person.save(db)
|
||||
}
|
||||
|
||||
// Reload persons, and insert a cell.
|
||||
reloadPersons()
|
||||
let index = persons.indexOf { $0.id == person.id }!
|
||||
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: .Automatic)
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Table View
|
||||
|
||||
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
||||
return persons.count
|
||||
}
|
||||
|
||||
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
|
||||
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
|
||||
|
||||
let person = persons[indexPath.row]
|
||||
cell.textLabel!.text = person.fullName
|
||||
return cell
|
||||
}
|
||||
|
||||
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
|
||||
// Delete the person
|
||||
let person = persons[indexPath.row]
|
||||
try! dbQueue.inTransaction { db in
|
||||
try person.delete(db)
|
||||
return .Commit
|
||||
}
|
||||
persons.removeAtIndex(indexPath.row)
|
||||
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -1,42 +1,49 @@
|
||||
import GRDB
|
||||
|
||||
class Person : Record {
|
||||
var id: Int64!
|
||||
var firstName: String?
|
||||
var lastName: String?
|
||||
var fullName: String {
|
||||
return [firstName, lastName].flatMap { $0 }.filter { !$0.isEmpty }.joinWithSeparator(" ")
|
||||
}
|
||||
class Person: Record {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
var score: Int
|
||||
|
||||
init(firstName: String? = nil, lastName: String? = nil) {
|
||||
self.firstName = firstName
|
||||
self.lastName = lastName
|
||||
init(name: String, score: Int) {
|
||||
self.name = name
|
||||
self.score = score
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: Record overrides
|
||||
|
||||
// MARK: - Record
|
||||
|
||||
override class func databaseTableName() -> String {
|
||||
override class var databaseTableName: String {
|
||||
return "persons"
|
||||
}
|
||||
|
||||
required init(_ row: Row) {
|
||||
id = row.value(named: "id")
|
||||
firstName = row.value(named: "firstName")
|
||||
lastName = row.value(named: "lastName")
|
||||
super.init(row)
|
||||
|
||||
required init(row: Row) {
|
||||
id = row["id"]
|
||||
name = row["name"]
|
||||
score = row["score"]
|
||||
super.init(row: row)
|
||||
}
|
||||
|
||||
override var persistentDictionary: [String: DatabaseValueConvertible?] {
|
||||
return [
|
||||
"id": id,
|
||||
"firstName": firstName,
|
||||
"lastName": lastName]
|
||||
override func encode(to container: inout PersistenceContainer) {
|
||||
container["id"] = id
|
||||
container["name"] = name
|
||||
container["score"] = score
|
||||
}
|
||||
|
||||
override func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
|
||||
override func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
}
|
||||
|
||||
// MARK: Random
|
||||
|
||||
private static let names = ["Arthur", "Anita", "Barbara", "Bernard", "Craig", "Chiara", "David", "Dean", "Éric", "Elena", "Fatima", "Frederik", "Gilbert", "Georgette", "Henriette", "Hassan", "Ignacio", "Irene", "Julie", "Jack", "Karl", "Kristel", "Louis", "Liz", "Masashi", "Mary", "Noam", "Nicole", "Ophelie", "Oleg", "Pascal", "Patricia", "Quentin", "Quinn", "Raoul", "Rachel", "Stephan", "Susie", "Tristan", "Tatiana", "Ursule", "Urbain", "Victor", "Violette", "Wilfried", "Wilhelmina", "Yvon", "Yann", "Zazie", "Zoé"]
|
||||
|
||||
class func randomName() -> String {
|
||||
return names[Int(arc4random_uniform(UInt32(names.count)))]
|
||||
}
|
||||
|
||||
class func randomScore() -> Int {
|
||||
return 10 * Int(arc4random_uniform(101))
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,61 +1,104 @@
|
||||
import UIKit
|
||||
|
||||
class PersonEditionViewController: UITableViewController, UITextFieldDelegate {
|
||||
@IBOutlet weak var firstNameTableViewCell: UITableViewCell!
|
||||
@IBOutlet weak var firstNameTextField: UITextField!
|
||||
@IBOutlet weak var lastNameTableViewCell: UITableViewCell!
|
||||
@IBOutlet weak var lastNameTextField: UITextField!
|
||||
protocol PersonEditionViewControllerDelegate: class {
|
||||
func personEditionControllerDidComplete(_ controller: PersonEditionViewController)
|
||||
}
|
||||
|
||||
class PersonEditionViewController: UITableViewController {
|
||||
weak var delegate: PersonEditionViewControllerDelegate?
|
||||
var person: Person! { didSet { configureView() } }
|
||||
var cancelButtonHidden: Bool = false { didSet { configureView() } }
|
||||
var commitButtonHidden: Bool = false { didSet { configureView() } }
|
||||
|
||||
@IBOutlet fileprivate weak var cancelBarButtonItem: UIBarButtonItem!
|
||||
@IBOutlet fileprivate weak var commitBarButtonItem: UIBarButtonItem!
|
||||
@IBOutlet fileprivate weak var nameCell: UITableViewCell!
|
||||
@IBOutlet fileprivate weak var nameTextField: UITextField!
|
||||
@IBOutlet fileprivate weak var scoreCell: UITableViewCell!
|
||||
@IBOutlet fileprivate weak var scoreTextField: UITextField!
|
||||
|
||||
// The edited person
|
||||
var person: Person!
|
||||
func applyChanges() {
|
||||
if let name = nameTextField.text, !name.isEmpty {
|
||||
person.name = name
|
||||
}
|
||||
person.score = scoreTextField.text.flatMap { Int($0) } ?? 0
|
||||
}
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
|
||||
// Initializes textFields with the person's names
|
||||
firstNameTextField.text = person.firstName
|
||||
lastNameTextField.text = person.lastName
|
||||
configureView()
|
||||
}
|
||||
|
||||
override func viewWillAppear(animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
private func configureView() {
|
||||
guard isViewLoaded else { return }
|
||||
|
||||
// Auto focus firstName
|
||||
firstNameTextField.becomeFirstResponder()
|
||||
nameTextField.text = person.name
|
||||
if person.score == 0 && person.id == nil {
|
||||
scoreTextField.text = ""
|
||||
} else {
|
||||
scoreTextField.text = "\(person.score)"
|
||||
}
|
||||
|
||||
if cancelButtonHidden {
|
||||
navigationItem.leftBarButtonItem = nil
|
||||
} else {
|
||||
navigationItem.leftBarButtonItem = cancelBarButtonItem
|
||||
}
|
||||
|
||||
if cancelButtonHidden {
|
||||
navigationItem.rightBarButtonItem = nil
|
||||
} else {
|
||||
navigationItem.rightBarButtonItem = commitBarButtonItem
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Navigation
|
||||
|
||||
extension PersonEditionViewController {
|
||||
|
||||
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
|
||||
// Force keyboard to dismiss early
|
||||
view.endEditing(true)
|
||||
return true
|
||||
}
|
||||
|
||||
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
|
||||
// Tapping a cell selects its text fields.
|
||||
if indexPath == tableView.indexPathForCell(firstNameTableViewCell) {
|
||||
firstNameTextField.becomeFirstResponder()
|
||||
} else if indexPath == tableView.indexPathForCell(lastNameTableViewCell) {
|
||||
lastNameTextField.becomeFirstResponder()
|
||||
override func willMove(toParentViewController parent: UIViewController?) {
|
||||
super.willMove(toParentViewController: parent)
|
||||
|
||||
if parent == nil {
|
||||
// Self is popping from its navigation controller
|
||||
delegate?.personEditionControllerDidComplete(self)
|
||||
}
|
||||
}
|
||||
|
||||
func textFieldShouldReturn(textField: UITextField) -> Bool {
|
||||
// Tapping Return key focuses next text field.
|
||||
if textField == firstNameTextField {
|
||||
lastNameTextField.becomeFirstResponder()
|
||||
} else {
|
||||
textField.resignFirstResponder()
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Form
|
||||
|
||||
extension PersonEditionViewController: UITextFieldDelegate {
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
nameTextField.becomeFirstResponder()
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
|
||||
tableView.deselectRow(at: indexPath, animated: false)
|
||||
let cell = tableView.cellForRow(at: indexPath)
|
||||
if cell === nameCell {
|
||||
nameTextField.becomeFirstResponder()
|
||||
} else if cell === scoreCell {
|
||||
scoreTextField.becomeFirstResponder()
|
||||
}
|
||||
}
|
||||
|
||||
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
|
||||
if textField == nameTextField {
|
||||
scoreTextField.becomeFirstResponder()
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func textFieldDidEndEditing(textField: UITextField) {
|
||||
// Update person when text field ends editing.
|
||||
if textField == firstNameTextField {
|
||||
person.firstName = textField.text
|
||||
} else if textField == lastNameTextField {
|
||||
person.lastName = textField.text
|
||||
}
|
||||
}
|
||||
|
||||
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
|
||||
// About to cancel or commit: end editing.
|
||||
// This dismisses the keyboard early, and apply pending changes through
|
||||
// textFieldDidEndEditing(_).
|
||||
view.endEditing(true)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
import UIKit
|
||||
import GRDB
|
||||
|
||||
class PersonsViewController: UITableViewController {
|
||||
var personsController: FetchedRecordsController<Person>!
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
|
||||
navigationItem.rightBarButtonItems = [
|
||||
UIBarButtonItem(barButtonSystemItem: .add, target: self, action: .addPerson),
|
||||
editButtonItem
|
||||
]
|
||||
|
||||
personsController = try! FetchedRecordsController(dbQueue, request: personsSortedByScore)
|
||||
personsController.trackChanges(
|
||||
willChange: { [unowned self] _ in
|
||||
self.tableView.beginUpdates()
|
||||
},
|
||||
onChange: { [unowned self] (controller, record, change) in
|
||||
switch change {
|
||||
case .insertion(let indexPath):
|
||||
self.tableView.insertRows(at: [indexPath], with: .fade)
|
||||
|
||||
case .deletion(let indexPath):
|
||||
self.tableView.deleteRows(at: [indexPath], with: .fade)
|
||||
|
||||
case .update(let indexPath, _):
|
||||
if let cell = self.tableView.cellForRow(at: indexPath) {
|
||||
self.configure(cell, at: indexPath)
|
||||
}
|
||||
|
||||
case .move(let indexPath, let newIndexPath, _):
|
||||
// Actually move cells around for more demo effect :-)
|
||||
let cell = self.tableView.cellForRow(at: indexPath)
|
||||
self.tableView.moveRow(at: indexPath, to: newIndexPath)
|
||||
if let cell = cell {
|
||||
self.configure(cell, at: newIndexPath)
|
||||
}
|
||||
|
||||
// A quieter animation:
|
||||
// self.tableView.deleteRows(at: [indexPath], with: .fade)
|
||||
// self.tableView.insertRows(at: [newIndexPath], with: .fade)
|
||||
}
|
||||
},
|
||||
didChange: { [unowned self] _ in
|
||||
self.tableView.endUpdates()
|
||||
})
|
||||
try! personsController.performFetch()
|
||||
|
||||
configureToolbar()
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
navigationController?.isToolbarHidden = false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Navigation
|
||||
|
||||
extension PersonsViewController : PersonEditionViewControllerDelegate {
|
||||
|
||||
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
|
||||
if segue.identifier == "EditPerson" {
|
||||
let person = personsController.record(at: tableView.indexPathForSelectedRow!)
|
||||
let controller = segue.destination as! PersonEditionViewController
|
||||
controller.title = person.name
|
||||
controller.person = person
|
||||
controller.delegate = self // we will save person when back button is tapped
|
||||
controller.cancelButtonHidden = true
|
||||
controller.commitButtonHidden = true
|
||||
}
|
||||
else if segue.identifier == "NewPerson" {
|
||||
setEditing(false, animated: true)
|
||||
let navigationController = segue.destination as! UINavigationController
|
||||
let controller = navigationController.viewControllers.first as! PersonEditionViewController
|
||||
controller.title = "New Person"
|
||||
controller.person = Person(name: "", score: 0)
|
||||
}
|
||||
}
|
||||
|
||||
@IBAction func addPerson(_ sender: AnyObject?) {
|
||||
performSegue(withIdentifier: "NewPerson", sender: sender)
|
||||
}
|
||||
|
||||
@IBAction func cancelPersonEdition(_ segue: UIStoryboardSegue) {
|
||||
// Person creation: cancel button was tapped
|
||||
}
|
||||
|
||||
@IBAction func commitPersonEdition(_ segue: UIStoryboardSegue) {
|
||||
// Person creation: commit button was tapped
|
||||
let controller = segue.source as! PersonEditionViewController
|
||||
controller.applyChanges()
|
||||
let person = controller.person!
|
||||
if !person.name.isEmpty {
|
||||
try! dbQueue.inDatabase { db in
|
||||
try person.save(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func personEditionControllerDidComplete(_ controller: PersonEditionViewController) {
|
||||
// Person edition: back button was tapped
|
||||
controller.applyChanges()
|
||||
let person = controller.person!
|
||||
if !person.name.isEmpty {
|
||||
try! dbQueue.inDatabase { db in
|
||||
try person.save(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - UITableViewDataSource
|
||||
|
||||
extension PersonsViewController {
|
||||
func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
|
||||
let person = personsController.record(at: indexPath)
|
||||
cell.textLabel?.text = person.name
|
||||
cell.detailTextLabel?.text = abs(person.score) > 1 ? "\(person.score) points" : "0 point"
|
||||
}
|
||||
|
||||
override func numberOfSections(in tableView: UITableView) -> Int {
|
||||
return personsController.sections.count
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
||||
return personsController.sections[section].numberOfRecords
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
||||
let cell = tableView.dequeueReusableCell(withIdentifier: "Person", for: indexPath)
|
||||
configure(cell, at: indexPath)
|
||||
return cell
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
|
||||
// Delete the person
|
||||
let person = personsController.record(at: indexPath)
|
||||
try! dbQueue.inDatabase { db in
|
||||
_ = try person.delete(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - FetchedRecordsController Demo
|
||||
|
||||
extension PersonsViewController {
|
||||
|
||||
fileprivate func configureToolbar() {
|
||||
toolbarItems = [
|
||||
UIBarButtonItem(title: "Name ⬆︎", style: .plain, target: self, action: .sortByName),
|
||||
UIBarButtonItem(title: "Score ⬇︎", style: .plain, target: self, action: .sortByScore),
|
||||
UIBarButtonItem(title: "Randomize", style: .plain, target: self, action: .randomizeScores),
|
||||
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
|
||||
UIBarButtonItem(title: "💣", style: .plain, target: self, action: .stressTest)
|
||||
]
|
||||
}
|
||||
|
||||
@IBAction func sortByName() {
|
||||
setEditing(false, animated: true)
|
||||
try! personsController.setRequest(personsSortedByName)
|
||||
}
|
||||
|
||||
@IBAction func sortByScore() {
|
||||
setEditing(false, animated: true)
|
||||
try! personsController.setRequest(personsSortedByScore)
|
||||
}
|
||||
|
||||
@IBAction func randomizeScores() {
|
||||
setEditing(false, animated: true)
|
||||
|
||||
try! dbQueue.inTransaction { db in
|
||||
for person in try Person.fetchAll(db) {
|
||||
person.score = Person.randomScore()
|
||||
try person.update(db)
|
||||
}
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
|
||||
@IBAction func stressTest() {
|
||||
setEditing(false, animated: true)
|
||||
|
||||
for _ in 0..<50 {
|
||||
DispatchQueue.global().async {
|
||||
try! dbQueue.inTransaction { db in
|
||||
if try Person.fetchCount(db) == 0 {
|
||||
// Insert persons
|
||||
for _ in 0..<8 {
|
||||
try Person(name: Person.randomName(), score: Person.randomScore()).insert(db)
|
||||
}
|
||||
} else {
|
||||
// Insert a person
|
||||
if arc4random_uniform(2) == 0 {
|
||||
let person = Person(name: Person.randomName(), score: Person.randomScore())
|
||||
try person.insert(db)
|
||||
}
|
||||
// Delete a person
|
||||
if arc4random_uniform(2) == 0 {
|
||||
if let person = try Person.order(sql: "RANDOM()").fetchOne(db) {
|
||||
try person.delete(db)
|
||||
}
|
||||
}
|
||||
// Update some persons
|
||||
for person in try Person.fetchAll(db) {
|
||||
if arc4random_uniform(2) == 0 {
|
||||
person.score = Person.randomScore()
|
||||
try person.update(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// https://medium.com/swift-programming/swift-selector-syntax-sugar-81c8a8b10df3
|
||||
private extension Selector {
|
||||
static let addPerson = #selector(PersonsViewController.addPerson(_:))
|
||||
static let sortByName = #selector(PersonsViewController.sortByName)
|
||||
static let sortByScore = #selector(PersonsViewController.sortByScore)
|
||||
static let randomizeScores = #selector(PersonsViewController.randomizeScores)
|
||||
static let stressTest = #selector(PersonsViewController.stressTest)
|
||||
}
|
||||
|
||||
private let personsSortedByName = Person.order(Column("name"))
|
||||
private let personsSortedByScore = Person.order(Column("score").desc, Column("name"))
|
||||
@@ -0,0 +1,114 @@
|
||||
import UIKit
|
||||
import GRDB
|
||||
|
||||
class SimplePersonsViewController: UITableViewController {
|
||||
var persons: [Person]!
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
|
||||
navigationItem.rightBarButtonItems = [
|
||||
UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(SimplePersonsViewController.addPerson(_:))),
|
||||
editButtonItem
|
||||
]
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
loadPersons()
|
||||
tableView.reloadData()
|
||||
}
|
||||
|
||||
private func loadPersons() {
|
||||
persons = try! dbQueue.inDatabase { db in
|
||||
try Person.order(Column("score").desc, Column("name")).fetchAll(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Navigation
|
||||
|
||||
extension SimplePersonsViewController : PersonEditionViewControllerDelegate {
|
||||
|
||||
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
|
||||
if segue.identifier == "EditPerson" {
|
||||
let person = persons[tableView.indexPathForSelectedRow!.row]
|
||||
let controller = segue.destination as! PersonEditionViewController
|
||||
controller.title = person.name
|
||||
controller.person = person
|
||||
controller.delegate = self // we will save person when back button is tapped
|
||||
controller.cancelButtonHidden = true
|
||||
controller.commitButtonHidden = true
|
||||
}
|
||||
else if segue.identifier == "NewPerson" {
|
||||
setEditing(false, animated: true)
|
||||
let navigationController = segue.destination as! UINavigationController
|
||||
let controller = navigationController.viewControllers.first as! PersonEditionViewController
|
||||
controller.title = "New Person"
|
||||
controller.person = Person(name: "", score: 0)
|
||||
}
|
||||
}
|
||||
|
||||
@IBAction func addPerson(_ sender: AnyObject?) {
|
||||
performSegue(withIdentifier: "NewPerson", sender: sender)
|
||||
}
|
||||
|
||||
@IBAction func cancelPersonEdition(_ segue: UIStoryboardSegue) {
|
||||
// Person creation: cancel button was tapped
|
||||
}
|
||||
|
||||
@IBAction func commitPersonEdition(_ segue: UIStoryboardSegue) {
|
||||
// Person creation: commit button was tapped
|
||||
let controller = segue.source as! PersonEditionViewController
|
||||
controller.applyChanges()
|
||||
let person = controller.person!
|
||||
if !person.name.isEmpty {
|
||||
try! dbQueue.inDatabase { db in
|
||||
try person.save(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func personEditionControllerDidComplete(_ controller: PersonEditionViewController) {
|
||||
// Person edition: back button was tapped
|
||||
controller.applyChanges()
|
||||
let person = controller.person!
|
||||
if !person.name.isEmpty {
|
||||
try! dbQueue.inDatabase { db in
|
||||
try person.save(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - UITableViewDataSource
|
||||
|
||||
extension SimplePersonsViewController {
|
||||
func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
|
||||
let person = persons[indexPath.row]
|
||||
cell.textLabel?.text = person.name
|
||||
cell.detailTextLabel?.text = abs(person.score) > 1 ? "\(person.score) points" : "0 point"
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
||||
return persons.count
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
||||
let cell = tableView.dequeueReusableCell(withIdentifier: "Person", for: indexPath)
|
||||
configure(cell, at: indexPath)
|
||||
return cell
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
|
||||
// Delete the person
|
||||
let person = persons[indexPath.row]
|
||||
try! dbQueue.inDatabase { db in
|
||||
_ = try person.delete(db)
|
||||
}
|
||||
persons.remove(at: indexPath.row)
|
||||
tableView.deleteRows(at: [indexPath], with: .fade)
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
GRDBDemoiOS
|
||||
===========
|
||||
|
||||
This application runs an universal (iPhone + iPad) application that displays an editable list of persons.
|
||||
|
||||
**To manually integrate GRDB as a Framework in your iOS application:**
|
||||
|
||||
1. Drag the [GRDB project](../../GRDB.xcodeproj) in your own project.
|
||||
|
||||
2. In the **Build Phase** tab of your target, add `GRDBiOS` in the **Target Dependencies** section.
|
||||
|
||||
3. In the **Embedded Binaries** section of the **General** tab of your target, add GRDB.xcodeproj/Products/GRDB.framework (iOS).
|
||||
|
||||
4. Run.
|
||||
|
||||
|
||||
**To see usage of GRDB, check the following files:**
|
||||
|
||||
- [Database.swift](GRDBDemoiOS/Database.swift)
|
||||
|
||||
The setupDatabase() function sets up a global dbQueue that is accessible in the whole application. It is called by the [AppDelegate](GRDBDemoiOS/AppDelegate.swift) when application starts up.
|
||||
|
||||
It uses [migrations](https://github.com/groue/GRDB.swift#migrations) to initialize the database, and [custom string comparison](https://github.com/groue/GRDB.swift#string-comparison) in order to let the database perform the localized sorting of persons by name.
|
||||
|
||||
- [MasterViewController.swift](GRDBDemoiOS/MasterViewController.swift)
|
||||
|
||||
MasterViewController is responsible for displaying the list of persons in a table view, deleting persons, and present a person edition form.
|
||||
|
||||
- [Person.swift](GRDBDemoiOS/Person.swift)
|
||||
|
||||
Person is a simple [Record](https://github.com/groue/GRDB.swift#records) subclass.
|
||||
|
||||
- [DetailViewController.swift](GRDBDemoiOS/DetailViewController.swift) and [PersonEditionViewController.swift](GRDBDemoiOS/PersonEditionViewController.swift)
|
||||
|
||||
Those two view controllers display and edit a Person, in total isolation from the database.
|
||||
@@ -1,578 +0,0 @@
|
||||
// !$*UTF8*$!
|
||||
{
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 46;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
560A37E01C91391800949E71 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37B31C91391800949E71 /* Configuration.swift */; };
|
||||
560A37E11C91391800949E71 /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37B41C91391800949E71 /* Database.swift */; };
|
||||
560A37E21C91391800949E71 /* DatabaseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37B51C91391800949E71 /* DatabaseError.swift */; };
|
||||
560A37E31C91391800949E71 /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37B61C91391800949E71 /* DatabasePool.swift */; };
|
||||
560A37E41C91391800949E71 /* DatabaseQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37B71C91391800949E71 /* DatabaseQueue.swift */; };
|
||||
560A37E51C91391800949E71 /* DatabaseSchemaCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37B81C91391800949E71 /* DatabaseSchemaCache.swift */; };
|
||||
560A37E61C91391800949E71 /* DatabaseValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37B91C91391800949E71 /* DatabaseValue.swift */; };
|
||||
560A37E71C91391800949E71 /* DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37BA1C91391800949E71 /* DatabaseValueConvertible.swift */; };
|
||||
560A37E81C91391800949E71 /* Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37BB1C91391800949E71 /* Row.swift */; };
|
||||
560A37E91C91391800949E71 /* SerializedDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37BC1C91391800949E71 /* SerializedDatabase.swift */; };
|
||||
560A37EA1C91391800949E71 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37BD1C91391800949E71 /* Statement.swift */; };
|
||||
560A37EB1C91391800949E71 /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37BE1C91391800949E71 /* StatementColumnConvertible.swift */; };
|
||||
560A37EC1C91391800949E71 /* CGFloat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37C11C91391800949E71 /* CGFloat.swift */; };
|
||||
560A37ED1C91391800949E71 /* DatabaseCoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37C31C91391800949E71 /* DatabaseCoder.swift */; };
|
||||
560A37EE1C91391800949E71 /* DatabaseDateComponents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37C41C91391800949E71 /* DatabaseDateComponents.swift */; };
|
||||
560A37EF1C91391800949E71 /* DatabaseValue+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37C51C91391800949E71 /* DatabaseValue+Foundation.swift */; };
|
||||
560A37F01C91391800949E71 /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37C61C91391800949E71 /* NSData.swift */; };
|
||||
560A37F11C91391800949E71 /* NSDate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37C71C91391800949E71 /* NSDate.swift */; };
|
||||
560A37F21C91391800949E71 /* NSNull.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37C81C91391800949E71 /* NSNull.swift */; };
|
||||
560A37F31C91391800949E71 /* NSNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37C91C91391800949E71 /* NSNumber.swift */; };
|
||||
560A37F41C91391800949E71 /* NSString.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37CA1C91391800949E71 /* NSString.swift */; };
|
||||
560A37F51C91391800949E71 /* NSURL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37CB1C91391800949E71 /* NSURL.swift */; };
|
||||
560A37F61C91391800949E71 /* Row+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37CC1C91391800949E71 /* Row+Foundation.swift */; };
|
||||
560A37F71C91391800949E71 /* StatementArguments+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37CD1C91391800949E71 /* StatementArguments+Foundation.swift */; };
|
||||
560A37F81C91391800949E71 /* RawRepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37CF1C91391800949E71 /* RawRepresentable.swift */; };
|
||||
560A37F91C91391800949E71 /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37D01C91391800949E71 /* StandardLibrary.swift */; };
|
||||
560A37FA1C91391800949E71 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37D11C91391800949E71 /* Utils.swift */; };
|
||||
560A37FB1C91391800949E71 /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37D31C91391800949E71 /* FetchRequest.swift */; };
|
||||
560A37FC1C91391800949E71 /* SQLCollation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37D41C91391800949E71 /* SQLCollation.swift */; };
|
||||
560A37FD1C91391800949E71 /* SQLFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37D51C91391800949E71 /* SQLFunction.swift */; };
|
||||
560A37FE1C91391800949E71 /* SQLOperator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37D61C91391800949E71 /* SQLOperator.swift */; };
|
||||
560A37FF1C91391800949E71 /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37D71C91391800949E71 /* SQLSelectQuery.swift */; };
|
||||
560A38001C91391800949E71 /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37D91C91391800949E71 /* DatabaseMigrator.swift */; };
|
||||
560A38011C91391800949E71 /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37DA1C91391800949E71 /* Migration.swift */; };
|
||||
560A38021C91391800949E71 /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37DC1C91391800949E71 /* Persistable.swift */; };
|
||||
560A38031C91391800949E71 /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37DD1C91391800949E71 /* Record.swift */; };
|
||||
560A38041C91391800949E71 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37DE1C91391800949E71 /* RowConvertible.swift */; };
|
||||
560A38051C91391800949E71 /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37DF1C91391800949E71 /* TableMapping.swift */; };
|
||||
562FF9951BCE8FA400759400 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562FF9941BCE8FA400759400 /* AppDelegate.swift */; };
|
||||
562FF9971BCE8FA400759400 /* PersonsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562FF9961BCE8FA400759400 /* PersonsViewController.swift */; };
|
||||
562FF99A1BCE8FA400759400 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 562FF9981BCE8FA400759400 /* Main.storyboard */; };
|
||||
562FF99C1BCE8FA400759400 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 562FF99B1BCE8FA400759400 /* Assets.xcassets */; };
|
||||
562FF99F1BCE8FA400759400 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 562FF99D1BCE8FA400759400 /* LaunchScreen.storyboard */; };
|
||||
562FF9EC1BCE903D00759400 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 562FF9EB1BCE903D00759400 /* libsqlite3.tbd */; };
|
||||
562FF9EF1BCE912C00759400 /* PersonEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562FF9EE1BCE912C00759400 /* PersonEditionViewController.swift */; };
|
||||
562FF9F21BCE914E00759400 /* Person.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562FF9F11BCE914E00759400 /* Person.swift */; };
|
||||
566A20F31C58A4B300C5A218 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A20F21C58A4B300C5A218 /* AppDatabase.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
560A37B31C91391800949E71 /* Configuration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Configuration.swift; sourceTree = "<group>"; };
|
||||
560A37B41C91391800949E71 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = "<group>"; };
|
||||
560A37B51C91391800949E71 /* DatabaseError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseError.swift; sourceTree = "<group>"; };
|
||||
560A37B61C91391800949E71 /* DatabasePool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePool.swift; sourceTree = "<group>"; };
|
||||
560A37B71C91391800949E71 /* DatabaseQueue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueue.swift; sourceTree = "<group>"; };
|
||||
560A37B81C91391800949E71 /* DatabaseSchemaCache.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaCache.swift; sourceTree = "<group>"; };
|
||||
560A37B91C91391800949E71 /* DatabaseValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValue.swift; sourceTree = "<group>"; };
|
||||
560A37BA1C91391800949E71 /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = "<group>"; };
|
||||
560A37BB1C91391800949E71 /* Row.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Row.swift; sourceTree = "<group>"; };
|
||||
560A37BC1C91391800949E71 /* SerializedDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SerializedDatabase.swift; sourceTree = "<group>"; };
|
||||
560A37BD1C91391800949E71 /* Statement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Statement.swift; sourceTree = "<group>"; };
|
||||
560A37BE1C91391800949E71 /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = "<group>"; };
|
||||
560A37C11C91391800949E71 /* CGFloat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloat.swift; sourceTree = "<group>"; };
|
||||
560A37C31C91391800949E71 /* DatabaseCoder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCoder.swift; sourceTree = "<group>"; };
|
||||
560A37C41C91391800949E71 /* DatabaseDateComponents.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateComponents.swift; sourceTree = "<group>"; };
|
||||
560A37C51C91391800949E71 /* DatabaseValue+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseValue+Foundation.swift"; sourceTree = "<group>"; };
|
||||
560A37C61C91391800949E71 /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = "<group>"; };
|
||||
560A37C71C91391800949E71 /* NSDate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSDate.swift; sourceTree = "<group>"; };
|
||||
560A37C81C91391800949E71 /* NSNull.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNull.swift; sourceTree = "<group>"; };
|
||||
560A37C91C91391800949E71 /* NSNumber.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSNumber.swift; sourceTree = "<group>"; };
|
||||
560A37CA1C91391800949E71 /* NSString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSString.swift; sourceTree = "<group>"; };
|
||||
560A37CB1C91391800949E71 /* NSURL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSURL.swift; sourceTree = "<group>"; };
|
||||
560A37CC1C91391800949E71 /* Row+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+Foundation.swift"; sourceTree = "<group>"; };
|
||||
560A37CD1C91391800949E71 /* StatementArguments+Foundation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+Foundation.swift"; sourceTree = "<group>"; };
|
||||
560A37CF1C91391800949E71 /* RawRepresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RawRepresentable.swift; sourceTree = "<group>"; };
|
||||
560A37D01C91391800949E71 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = "<group>"; };
|
||||
560A37D11C91391800949E71 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = "<group>"; };
|
||||
560A37D31C91391800949E71 /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = "<group>"; };
|
||||
560A37D41C91391800949E71 /* SQLCollation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollation.swift; sourceTree = "<group>"; };
|
||||
560A37D51C91391800949E71 /* SQLFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunction.swift; sourceTree = "<group>"; };
|
||||
560A37D61C91391800949E71 /* SQLOperator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperator.swift; sourceTree = "<group>"; };
|
||||
560A37D71C91391800949E71 /* SQLSelectQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectQuery.swift; sourceTree = "<group>"; };
|
||||
560A37D91C91391800949E71 /* DatabaseMigrator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseMigrator.swift; sourceTree = "<group>"; };
|
||||
560A37DA1C91391800949E71 /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = "<group>"; };
|
||||
560A37DC1C91391800949E71 /* Persistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistable.swift; sourceTree = "<group>"; };
|
||||
560A37DD1C91391800949E71 /* Record.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Record.swift; sourceTree = "<group>"; };
|
||||
560A37DE1C91391800949E71 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = "<group>"; };
|
||||
560A37DF1C91391800949E71 /* TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableMapping.swift; sourceTree = "<group>"; };
|
||||
562FF9911BCE8FA400759400 /* GRDBDemoiOS7.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBDemoiOS7.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
562FF9941BCE8FA400759400 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
|
||||
562FF9961BCE8FA400759400 /* PersonsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PersonsViewController.swift; sourceTree = "<group>"; };
|
||||
562FF9991BCE8FA400759400 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
|
||||
562FF99B1BCE8FA400759400 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
|
||||
562FF99E1BCE8FA400759400 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
|
||||
562FF9A01BCE8FA400759400 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
562FF9EB1BCE903D00759400 /* libsqlite3.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libsqlite3.tbd; path = usr/lib/libsqlite3.tbd; sourceTree = SDKROOT; };
|
||||
562FF9EE1BCE912C00759400 /* PersonEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonEditionViewController.swift; sourceTree = "<group>"; };
|
||||
562FF9F11BCE914E00759400 /* Person.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Person.swift; sourceTree = "<group>"; };
|
||||
562FF9F41BCE930C00759400 /* GRDBDemoiOS7-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBDemoiOS7-Bridging-Header.h"; sourceTree = "<group>"; };
|
||||
566A20F21C58A4B300C5A218 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
562FF98E1BCE8FA400759400 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
562FF9EC1BCE903D00759400 /* libsqlite3.tbd in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
560A37B21C91391800949E71 /* Core */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
560A37B31C91391800949E71 /* Configuration.swift */,
|
||||
560A37B41C91391800949E71 /* Database.swift */,
|
||||
560A37B51C91391800949E71 /* DatabaseError.swift */,
|
||||
560A37B61C91391800949E71 /* DatabasePool.swift */,
|
||||
560A37B71C91391800949E71 /* DatabaseQueue.swift */,
|
||||
560A37B81C91391800949E71 /* DatabaseSchemaCache.swift */,
|
||||
560A37B91C91391800949E71 /* DatabaseValue.swift */,
|
||||
560A37BA1C91391800949E71 /* DatabaseValueConvertible.swift */,
|
||||
560A37BB1C91391800949E71 /* Row.swift */,
|
||||
560A37BC1C91391800949E71 /* SerializedDatabase.swift */,
|
||||
560A37BD1C91391800949E71 /* Statement.swift */,
|
||||
560A37BE1C91391800949E71 /* StatementColumnConvertible.swift */,
|
||||
560A37BF1C91391800949E71 /* Support */,
|
||||
560A37D11C91391800949E71 /* Utils.swift */,
|
||||
);
|
||||
path = Core;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
560A37BF1C91391800949E71 /* Support */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
560A37C01C91391800949E71 /* CoreGraphics */,
|
||||
560A37C21C91391800949E71 /* Foundation */,
|
||||
560A37CE1C91391800949E71 /* StandardLibrary */,
|
||||
);
|
||||
path = Support;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
560A37C01C91391800949E71 /* CoreGraphics */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
560A37C11C91391800949E71 /* CGFloat.swift */,
|
||||
);
|
||||
path = CoreGraphics;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
560A37C21C91391800949E71 /* Foundation */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
560A37C31C91391800949E71 /* DatabaseCoder.swift */,
|
||||
560A37C41C91391800949E71 /* DatabaseDateComponents.swift */,
|
||||
560A37C51C91391800949E71 /* DatabaseValue+Foundation.swift */,
|
||||
560A37C61C91391800949E71 /* NSData.swift */,
|
||||
560A37C71C91391800949E71 /* NSDate.swift */,
|
||||
560A37C81C91391800949E71 /* NSNull.swift */,
|
||||
560A37C91C91391800949E71 /* NSNumber.swift */,
|
||||
560A37CA1C91391800949E71 /* NSString.swift */,
|
||||
560A37CB1C91391800949E71 /* NSURL.swift */,
|
||||
560A37CC1C91391800949E71 /* Row+Foundation.swift */,
|
||||
560A37CD1C91391800949E71 /* StatementArguments+Foundation.swift */,
|
||||
);
|
||||
path = Foundation;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
560A37CE1C91391800949E71 /* StandardLibrary */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
560A37CF1C91391800949E71 /* RawRepresentable.swift */,
|
||||
560A37D01C91391800949E71 /* StandardLibrary.swift */,
|
||||
);
|
||||
path = StandardLibrary;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
560A37D21C91391800949E71 /* FetchRequest */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
560A37D31C91391800949E71 /* FetchRequest.swift */,
|
||||
560A37D41C91391800949E71 /* SQLCollation.swift */,
|
||||
560A37D51C91391800949E71 /* SQLFunction.swift */,
|
||||
560A37D61C91391800949E71 /* SQLOperator.swift */,
|
||||
560A37D71C91391800949E71 /* SQLSelectQuery.swift */,
|
||||
);
|
||||
path = FetchRequest;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
560A37D81C91391800949E71 /* Migrations */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
560A37D91C91391800949E71 /* DatabaseMigrator.swift */,
|
||||
560A37DA1C91391800949E71 /* Migration.swift */,
|
||||
);
|
||||
path = Migrations;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
560A37DB1C91391800949E71 /* Record */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
560A37DC1C91391800949E71 /* Persistable.swift */,
|
||||
560A37DD1C91391800949E71 /* Record.swift */,
|
||||
560A37DE1C91391800949E71 /* RowConvertible.swift */,
|
||||
560A37DF1C91391800949E71 /* TableMapping.swift */,
|
||||
);
|
||||
path = Record;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
562FF9881BCE8FA400759400 = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
562FF9931BCE8FA400759400 /* GRDBDemoiOS7 */,
|
||||
562FF9921BCE8FA400759400 /* Products */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
562FF9921BCE8FA400759400 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
562FF9911BCE8FA400759400 /* GRDBDemoiOS7.app */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
562FF9931BCE8FA400759400 /* GRDBDemoiOS7 */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
562FF9941BCE8FA400759400 /* AppDelegate.swift */,
|
||||
566A20F21C58A4B300C5A218 /* AppDatabase.swift */,
|
||||
562FF9F01BCE913900759400 /* Controllers */,
|
||||
562FF9F31BCE915B00759400 /* Models */,
|
||||
562FF9A61BCE8FB000759400 /* Resources */,
|
||||
562FF9ED1BCE904D00759400 /* Libraries */,
|
||||
562FF9A71BCE8FB600759400 /* Supporting Files */,
|
||||
);
|
||||
path = GRDBDemoiOS7;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
562FF9A61BCE8FB000759400 /* Resources */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
562FF9981BCE8FA400759400 /* Main.storyboard */,
|
||||
562FF99B1BCE8FA400759400 /* Assets.xcassets */,
|
||||
562FF99D1BCE8FA400759400 /* LaunchScreen.storyboard */,
|
||||
);
|
||||
name = Resources;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
562FF9A71BCE8FB600759400 /* Supporting Files */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
562FF9A01BCE8FA400759400 /* Info.plist */,
|
||||
562FF9F41BCE930C00759400 /* GRDBDemoiOS7-Bridging-Header.h */,
|
||||
);
|
||||
name = "Supporting Files";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
562FF9ED1BCE904D00759400 /* Libraries */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
562FF9EB1BCE903D00759400 /* libsqlite3.tbd */,
|
||||
566A20F41C58A54F00C5A218 /* GRDB */,
|
||||
);
|
||||
name = Libraries;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
562FF9F01BCE913900759400 /* Controllers */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
562FF9EE1BCE912C00759400 /* PersonEditionViewController.swift */,
|
||||
562FF9961BCE8FA400759400 /* PersonsViewController.swift */,
|
||||
);
|
||||
name = Controllers;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
562FF9F31BCE915B00759400 /* Models */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
562FF9F11BCE914E00759400 /* Person.swift */,
|
||||
);
|
||||
name = Models;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
566A20F41C58A54F00C5A218 /* GRDB */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
560A37B21C91391800949E71 /* Core */,
|
||||
560A37D21C91391800949E71 /* FetchRequest */,
|
||||
560A37D81C91391800949E71 /* Migrations */,
|
||||
560A37DB1C91391800949E71 /* Record */,
|
||||
);
|
||||
name = GRDB;
|
||||
path = ../../../GRDB;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
562FF9901BCE8FA400759400 /* GRDBDemoiOS7 */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 562FF9A31BCE8FA400759400 /* Build configuration list for PBXNativeTarget "GRDBDemoiOS7" */;
|
||||
buildPhases = (
|
||||
562FF98D1BCE8FA400759400 /* Sources */,
|
||||
562FF98E1BCE8FA400759400 /* Frameworks */,
|
||||
562FF98F1BCE8FA400759400 /* Resources */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = GRDBDemoiOS7;
|
||||
productName = GRDBDemoiOS7;
|
||||
productReference = 562FF9911BCE8FA400759400 /* GRDBDemoiOS7.app */;
|
||||
productType = "com.apple.product-type.application";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
562FF9891BCE8FA400759400 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastUpgradeCheck = 0700;
|
||||
ORGANIZATIONNAME = "Gwendal Roué";
|
||||
TargetAttributes = {
|
||||
562FF9901BCE8FA400759400 = {
|
||||
CreatedOnToolsVersion = 7.0;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = 562FF98C1BCE8FA400759400 /* Build configuration list for PBXProject "GRDBDemoiOS7" */;
|
||||
compatibilityVersion = "Xcode 3.2";
|
||||
developmentRegion = English;
|
||||
hasScannedForEncodings = 0;
|
||||
knownRegions = (
|
||||
en,
|
||||
Base,
|
||||
);
|
||||
mainGroup = 562FF9881BCE8FA400759400;
|
||||
productRefGroup = 562FF9921BCE8FA400759400 /* Products */;
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
562FF9901BCE8FA400759400 /* GRDBDemoiOS7 */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXResourcesBuildPhase section */
|
||||
562FF98F1BCE8FA400759400 /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
562FF99F1BCE8FA400759400 /* LaunchScreen.storyboard in Resources */,
|
||||
562FF99C1BCE8FA400759400 /* Assets.xcassets in Resources */,
|
||||
562FF99A1BCE8FA400759400 /* Main.storyboard in Resources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
562FF98D1BCE8FA400759400 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
560A37FB1C91391800949E71 /* FetchRequest.swift in Sources */,
|
||||
560A37EC1C91391800949E71 /* CGFloat.swift in Sources */,
|
||||
560A38011C91391800949E71 /* Migration.swift in Sources */,
|
||||
560A37EB1C91391800949E71 /* StatementColumnConvertible.swift in Sources */,
|
||||
560A37EF1C91391800949E71 /* DatabaseValue+Foundation.swift in Sources */,
|
||||
560A37E01C91391800949E71 /* Configuration.swift in Sources */,
|
||||
560A37E91C91391800949E71 /* SerializedDatabase.swift in Sources */,
|
||||
562FF9EF1BCE912C00759400 /* PersonEditionViewController.swift in Sources */,
|
||||
560A38051C91391800949E71 /* TableMapping.swift in Sources */,
|
||||
560A37E71C91391800949E71 /* DatabaseValueConvertible.swift in Sources */,
|
||||
560A37E31C91391800949E71 /* DatabasePool.swift in Sources */,
|
||||
562FF9971BCE8FA400759400 /* PersonsViewController.swift in Sources */,
|
||||
560A37E51C91391800949E71 /* DatabaseSchemaCache.swift in Sources */,
|
||||
560A37E41C91391800949E71 /* DatabaseQueue.swift in Sources */,
|
||||
560A37F11C91391800949E71 /* NSDate.swift in Sources */,
|
||||
562FF9F21BCE914E00759400 /* Person.swift in Sources */,
|
||||
560A37F01C91391800949E71 /* NSData.swift in Sources */,
|
||||
562FF9951BCE8FA400759400 /* AppDelegate.swift in Sources */,
|
||||
560A37FC1C91391800949E71 /* SQLCollation.swift in Sources */,
|
||||
560A37F71C91391800949E71 /* StatementArguments+Foundation.swift in Sources */,
|
||||
560A37EE1C91391800949E71 /* DatabaseDateComponents.swift in Sources */,
|
||||
560A37ED1C91391800949E71 /* DatabaseCoder.swift in Sources */,
|
||||
560A37E61C91391800949E71 /* DatabaseValue.swift in Sources */,
|
||||
560A37F31C91391800949E71 /* NSNumber.swift in Sources */,
|
||||
560A37FF1C91391800949E71 /* SQLSelectQuery.swift in Sources */,
|
||||
560A37F41C91391800949E71 /* NSString.swift in Sources */,
|
||||
560A37E21C91391800949E71 /* DatabaseError.swift in Sources */,
|
||||
560A38041C91391800949E71 /* RowConvertible.swift in Sources */,
|
||||
560A37F91C91391800949E71 /* StandardLibrary.swift in Sources */,
|
||||
560A37FA1C91391800949E71 /* Utils.swift in Sources */,
|
||||
560A37F61C91391800949E71 /* Row+Foundation.swift in Sources */,
|
||||
560A37FD1C91391800949E71 /* SQLFunction.swift in Sources */,
|
||||
560A37FE1C91391800949E71 /* SQLOperator.swift in Sources */,
|
||||
560A37F21C91391800949E71 /* NSNull.swift in Sources */,
|
||||
560A37E11C91391800949E71 /* Database.swift in Sources */,
|
||||
560A37E81C91391800949E71 /* Row.swift in Sources */,
|
||||
560A38021C91391800949E71 /* Persistable.swift in Sources */,
|
||||
560A37F51C91391800949E71 /* NSURL.swift in Sources */,
|
||||
560A37F81C91391800949E71 /* RawRepresentable.swift in Sources */,
|
||||
560A38001C91391800949E71 /* DatabaseMigrator.swift in Sources */,
|
||||
566A20F31C58A4B300C5A218 /* AppDatabase.swift in Sources */,
|
||||
560A37EA1C91391800949E71 /* Statement.swift in Sources */,
|
||||
560A38031C91391800949E71 /* Record.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXVariantGroup section */
|
||||
562FF9981BCE8FA400759400 /* Main.storyboard */ = {
|
||||
isa = PBXVariantGroup;
|
||||
children = (
|
||||
562FF9991BCE8FA400759400 /* Base */,
|
||||
);
|
||||
name = Main.storyboard;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
562FF99D1BCE8FA400759400 /* LaunchScreen.storyboard */ = {
|
||||
isa = PBXVariantGroup;
|
||||
children = (
|
||||
562FF99E1BCE8FA400759400 /* Base */,
|
||||
);
|
||||
name = LaunchScreen.storyboard;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXVariantGroup section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
562FF9A11BCE8FA400759400 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
|
||||
CLANG_CXX_LIBRARY = "libc++";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_EMPTY_BODY = YES;
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu99;
|
||||
GCC_DYNAMIC_NO_PIC = NO;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
GCC_PREPROCESSOR_DEFINITIONS = (
|
||||
"DEBUG=1",
|
||||
"$(inherited)",
|
||||
);
|
||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
||||
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
|
||||
MTL_ENABLE_DEBUG_INFO = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
562FF9A21BCE8FA400759400 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
|
||||
CLANG_CXX_LIBRARY = "libc++";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_EMPTY_BODY = YES;
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
ENABLE_NS_ASSERTIONS = NO;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu99;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
||||
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
SDKROOT = iphoneos;
|
||||
VALIDATE_PRODUCT = YES;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
562FF9A41BCE8FA400759400 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
INFOPLIST_FILE = GRDBDemoiOS7/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 7.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS7;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "GRDBDemoiOS7/GRDBDemoiOS7-Bridging-Header.h";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
562FF9A51BCE8FA400759400 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
INFOPLIST_FILE = GRDBDemoiOS7/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 7.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS7;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "GRDBDemoiOS7/GRDBDemoiOS7-Bridging-Header.h";
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
562FF98C1BCE8FA400759400 /* Build configuration list for PBXProject "GRDBDemoiOS7" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
562FF9A11BCE8FA400759400 /* Debug */,
|
||||
562FF9A21BCE8FA400759400 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
562FF9A31BCE8FA400759400 /* Build configuration list for PBXNativeTarget "GRDBDemoiOS7" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
562FF9A41BCE8FA400759400 /* Debug */,
|
||||
562FF9A51BCE8FA400759400 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
};
|
||||
rootObject = 562FF9891BCE8FA400759400 /* Project object */;
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
|
||||
// The columns for the GRDB Query Interface
|
||||
//
|
||||
// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
|
||||
struct Col {
|
||||
static let id = SQLColumn("id")
|
||||
static let firstName = SQLColumn("firstName")
|
||||
static let lastName = SQLColumn("lastName")
|
||||
}
|
||||
|
||||
|
||||
// The shared database queue, stored in a global.
|
||||
// It is initialized in setupDatabase()
|
||||
|
||||
var dbQueue: DatabaseQueue!
|
||||
|
||||
func setupDatabase() {
|
||||
|
||||
// Connect to the database
|
||||
//
|
||||
// See https://github.com/groue/GRDB.swift/#database-queues
|
||||
|
||||
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as NSString
|
||||
let databasePath = documentsPath.stringByAppendingPathComponent("db.sqlite")
|
||||
dbQueue = try! DatabaseQueue(path: databasePath)
|
||||
|
||||
|
||||
// SQLite does not support Unicode: let's add a custom collation which will
|
||||
// allow us to sort persons by name.
|
||||
//
|
||||
// See https://github.com/groue/GRDB.swift/#string-comparison
|
||||
|
||||
let collation = DatabaseCollation("localized_case_insensitive") { (lhs, rhs) in
|
||||
return (lhs as NSString).localizedCaseInsensitiveCompare(rhs)
|
||||
}
|
||||
|
||||
dbQueue.inDatabase { db in
|
||||
db.addCollation(collation)
|
||||
}
|
||||
|
||||
|
||||
// Use DatabaseMigrator to setup the database
|
||||
//
|
||||
// See https://github.com/groue/GRDB.swift/#migrations
|
||||
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.registerMigration("createPersons") { db in
|
||||
try db.execute(
|
||||
"CREATE TABLE persons (" +
|
||||
"id INTEGER PRIMARY KEY, " +
|
||||
"firstName TEXT COLLATE localized_case_insensitive, " +
|
||||
"lastName TEXT COLLATE localized_case_insensitive" +
|
||||
")")
|
||||
}
|
||||
migrator.registerMigration("addPersons") { db in
|
||||
try Person(firstName: "Arthur", lastName: "Miller").insert(db)
|
||||
try Person(firstName: "Barbra", lastName: "Streisand").insert(db)
|
||||
try Person(firstName: "Cinderella").insert(db)
|
||||
}
|
||||
try! migrator.migrate(dbQueue)
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import UIKit
|
||||
|
||||
@UIApplicationMain
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
|
||||
var window: UIWindow?
|
||||
|
||||
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
|
||||
setupDatabase()
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,190 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="8191" systemVersion="14F27" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="Xbj-yc-Aiu">
|
||||
<dependencies>
|
||||
<deployment identifier="iOS"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="8154"/>
|
||||
</dependencies>
|
||||
<scenes>
|
||||
<!--Persons View Controller-->
|
||||
<scene sceneID="1fE-hv-cjH">
|
||||
<objects>
|
||||
<tableViewController id="ynz-7l-fNg" customClass="PersonsViewController" customModule="GRDBDemoiOS7" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="wb6-9X-0tl">
|
||||
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
|
||||
<prototypes>
|
||||
<tableViewCell contentMode="scaleToFill" selectionStyle="blue" hidesAccessoryWhenEditing="NO" indentationLevel="1" indentationWidth="0.0" reuseIdentifier="Cell" textLabel="0eG-T5-kyh" style="IBUITableViewCellStyleDefault" id="eJm-gh-sbD">
|
||||
<rect key="frame" x="0.0" y="92" width="600" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="eJm-gh-sbD" id="njP-8B-rhM">
|
||||
<rect key="frame" x="0.0" y="0.0" width="600" height="43"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" text="Title" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="0eG-T5-kyh">
|
||||
<rect key="frame" x="15" y="0.0" width="570" height="43"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<fontDescription key="fontDescription" type="boldSystem" pointSize="20"/>
|
||||
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
|
||||
<color key="highlightedColor" red="1" green="1" blue="1" alpha="1" colorSpace="calibratedRGB"/>
|
||||
</label>
|
||||
</subviews>
|
||||
</tableViewCellContentView>
|
||||
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
|
||||
</tableViewCell>
|
||||
</prototypes>
|
||||
<connections>
|
||||
<outlet property="dataSource" destination="ynz-7l-fNg" id="5FA-Zc-cZO"/>
|
||||
<outlet property="delegate" destination="ynz-7l-fNg" id="B8Y-qi-fJZ"/>
|
||||
</connections>
|
||||
</tableView>
|
||||
<toolbarItems/>
|
||||
<navigationItem key="navigationItem" id="gMJ-R9-ZaQ">
|
||||
<barButtonItem key="rightBarButtonItem" systemItem="add" id="XY0-Dc-M7c">
|
||||
<connections>
|
||||
<segue destination="oMH-Sb-bab" kind="presentation" identifier="editNewPerson" id="i19-Bf-uNJ"/>
|
||||
</connections>
|
||||
</barButtonItem>
|
||||
</navigationItem>
|
||||
<simulatedToolbarMetrics key="simulatedBottomBarMetrics"/>
|
||||
</tableViewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="0kz-GI-OO0" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="1195" y="377"/>
|
||||
</scene>
|
||||
<!--Navigation Controller-->
|
||||
<scene sceneID="cvq-JR-nHN">
|
||||
<objects>
|
||||
<navigationController id="Xbj-yc-Aiu" sceneMemberID="viewController">
|
||||
<navigationBar key="navigationBar" contentMode="scaleToFill" id="Hgn-6S-1iz">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
</navigationBar>
|
||||
<connections>
|
||||
<segue destination="ynz-7l-fNg" kind="relationship" relationship="rootViewController" id="C4a-4A-4Md"/>
|
||||
</connections>
|
||||
</navigationController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="OyF-YK-p9J" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="375" y="377"/>
|
||||
</scene>
|
||||
<!--Person Edition View Controller-->
|
||||
<scene sceneID="nA8-Ek-eRe">
|
||||
<objects>
|
||||
<tableViewController id="8yj-TG-7Iv" customClass="PersonEditionViewController" customModule="GRDBDemoiOS7" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="static" style="grouped" separatorStyle="default" rowHeight="44" sectionHeaderHeight="18" sectionFooterHeight="18" id="jhE-wh-IDm">
|
||||
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<color key="backgroundColor" cocoaTouchSystemColor="groupTableViewBackgroundColor"/>
|
||||
<sections>
|
||||
<tableViewSection id="9vV-wM-aZ9">
|
||||
<cells>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="oKc-Vh-GAg">
|
||||
<rect key="frame" x="0.0" y="99" width="600" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="oKc-Vh-GAg" id="EWB-Ks-FwX">
|
||||
<rect key="frame" x="0.0" y="0.0" width="600" height="43"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" textAlignment="right" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="eF9-yN-ByV">
|
||||
<rect key="frame" x="106" y="11" width="479" height="21"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="17"/>
|
||||
<textInputTraits key="textInputTraits" autocapitalizationType="words" autocorrectionType="no" spellCheckingType="no"/>
|
||||
<connections>
|
||||
<outlet property="delegate" destination="8yj-TG-7Iv" id="tG8-8g-5h8"/>
|
||||
</connections>
|
||||
</textField>
|
||||
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="1000" verticalHuggingPriority="251" horizontalCompressionResistancePriority="1000" text="First Name" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="xbk-eb-6vS">
|
||||
<rect key="frame" x="15" y="11" width="83" height="21"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="17"/>
|
||||
<color key="textColor" red="0.1137254902" green="0.47843137250000001" blue="0.98039215690000003" alpha="1" colorSpace="calibratedRGB"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
</subviews>
|
||||
<constraints>
|
||||
<constraint firstAttribute="trailing" secondItem="eF9-yN-ByV" secondAttribute="trailing" constant="15" id="5YN-K6-y1e"/>
|
||||
<constraint firstItem="xbk-eb-6vS" firstAttribute="leading" secondItem="EWB-Ks-FwX" secondAttribute="leading" constant="15" id="6ZF-52-FFn"/>
|
||||
<constraint firstItem="xbk-eb-6vS" firstAttribute="centerY" secondItem="EWB-Ks-FwX" secondAttribute="centerY" id="9zo-vh-Z4q"/>
|
||||
<constraint firstItem="eF9-yN-ByV" firstAttribute="leading" secondItem="xbk-eb-6vS" secondAttribute="trailing" constant="8" symbolic="YES" id="aKR-sh-Dh7"/>
|
||||
<constraint firstItem="eF9-yN-ByV" firstAttribute="centerY" secondItem="EWB-Ks-FwX" secondAttribute="centerY" id="kqk-6N-RLq"/>
|
||||
</constraints>
|
||||
</tableViewCellContentView>
|
||||
</tableViewCell>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="jUE-io-HLU">
|
||||
<rect key="frame" x="0.0" y="143" width="600" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="jUE-io-HLU" id="utc-hw-ReT">
|
||||
<rect key="frame" x="0.0" y="0.0" width="600" height="43"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" textAlignment="right" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="D1U-mQ-lvp">
|
||||
<rect key="frame" x="105" y="11" width="480" height="21"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="17"/>
|
||||
<textInputTraits key="textInputTraits" autocapitalizationType="words" autocorrectionType="no" spellCheckingType="no"/>
|
||||
<connections>
|
||||
<outlet property="delegate" destination="8yj-TG-7Iv" id="2pv-xY-VtW"/>
|
||||
</connections>
|
||||
</textField>
|
||||
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="1000" verticalHuggingPriority="251" horizontalCompressionResistancePriority="1000" text="Last Name" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="oYd-Lu-Kgd">
|
||||
<rect key="frame" x="15" y="11" width="82" height="21"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="17"/>
|
||||
<color key="textColor" red="0.1137254902" green="0.47843137250000001" blue="0.98039215690000003" alpha="1" colorSpace="calibratedRGB"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
</subviews>
|
||||
<constraints>
|
||||
<constraint firstItem="D1U-mQ-lvp" firstAttribute="leading" secondItem="oYd-Lu-Kgd" secondAttribute="trailing" constant="8" symbolic="YES" id="FHD-Pe-EkI"/>
|
||||
<constraint firstItem="oYd-Lu-Kgd" firstAttribute="centerY" secondItem="utc-hw-ReT" secondAttribute="centerY" id="Kdt-DU-1us"/>
|
||||
<constraint firstItem="D1U-mQ-lvp" firstAttribute="centerY" secondItem="utc-hw-ReT" secondAttribute="centerY" id="RVU-rE-8Aq"/>
|
||||
<constraint firstItem="oYd-Lu-Kgd" firstAttribute="leading" secondItem="utc-hw-ReT" secondAttribute="leading" constant="15" id="Wlm-uX-s7l"/>
|
||||
<constraint firstAttribute="trailing" secondItem="D1U-mQ-lvp" secondAttribute="trailing" constant="15" id="fs6-Mj-Cug"/>
|
||||
</constraints>
|
||||
</tableViewCellContentView>
|
||||
</tableViewCell>
|
||||
</cells>
|
||||
</tableViewSection>
|
||||
</sections>
|
||||
<connections>
|
||||
<outlet property="dataSource" destination="8yj-TG-7Iv" id="DrV-HH-zW8"/>
|
||||
<outlet property="delegate" destination="8yj-TG-7Iv" id="5Ta-JL-Sse"/>
|
||||
</connections>
|
||||
</tableView>
|
||||
<toolbarItems/>
|
||||
<navigationItem key="navigationItem" id="0rI-r6-PKi">
|
||||
<barButtonItem key="rightBarButtonItem" style="done" systemItem="done" id="jGa-U1-8mj">
|
||||
<connections>
|
||||
<segue destination="eQQ-Mr-J7f" kind="unwind" identifier="commit" unwindAction="commitPersonEdition:" id="LQt-5H-hX8"/>
|
||||
</connections>
|
||||
</barButtonItem>
|
||||
</navigationItem>
|
||||
<simulatedToolbarMetrics key="simulatedBottomBarMetrics"/>
|
||||
<connections>
|
||||
<outlet property="firstNameTableViewCell" destination="oKc-Vh-GAg" id="GgP-dg-jJI"/>
|
||||
<outlet property="firstNameTextField" destination="eF9-yN-ByV" id="CwB-oL-I3U"/>
|
||||
<outlet property="lastNameTableViewCell" destination="jUE-io-HLU" id="8SU-t1-EJR"/>
|
||||
<outlet property="lastNameTextField" destination="D1U-mQ-lvp" id="4b9-am-ANQ"/>
|
||||
</connections>
|
||||
</tableViewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="sm8-PY-oAW" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
<exit id="eQQ-Mr-J7f" userLabel="Exit" sceneMemberID="exit"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="2843" y="377"/>
|
||||
</scene>
|
||||
<!--Navigation Controller-->
|
||||
<scene sceneID="n5c-pj-sKx">
|
||||
<objects>
|
||||
<navigationController id="oMH-Sb-bab" sceneMemberID="viewController">
|
||||
<navigationBar key="navigationBar" contentMode="scaleToFill" id="d5l-tl-lRt">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
</navigationBar>
|
||||
<connections>
|
||||
<segue destination="8yj-TG-7Iv" kind="relationship" relationship="rootViewController" id="rAN-NO-1Mw"/>
|
||||
</connections>
|
||||
</navigationController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="UxC-4D-edS" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="2023" y="377"/>
|
||||
</scene>
|
||||
</scenes>
|
||||
</document>
|
||||
@@ -1,14 +0,0 @@
|
||||
//
|
||||
// GRDBDemoiOS7-Bridging-Header.h
|
||||
// GRDBDemoiOS7
|
||||
//
|
||||
// Created by Gwendal Roué on 14/10/2015.
|
||||
// Copyright © 2015 Gwendal Roué. All rights reserved.
|
||||
//
|
||||
|
||||
#ifndef GRDBDemoiOS7_Bridging_Header_h
|
||||
#define GRDBDemoiOS7_Bridging_Header_h
|
||||
|
||||
#import "sqlite3.h"
|
||||
|
||||
#endif /* GRDBDemoiOS7_Bridging_Header_h */
|
||||
@@ -1,40 +0,0 @@
|
||||
class Person : Record {
|
||||
var id: Int64!
|
||||
var firstName: String?
|
||||
var lastName: String?
|
||||
var fullName: String {
|
||||
return [firstName, lastName].flatMap { $0 }.filter { !$0.isEmpty }.joinWithSeparator(" ")
|
||||
}
|
||||
|
||||
init(firstName: String? = nil, lastName: String? = nil) {
|
||||
self.firstName = firstName
|
||||
self.lastName = lastName
|
||||
super.init()
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Record
|
||||
|
||||
override class func databaseTableName() -> String {
|
||||
return "persons"
|
||||
}
|
||||
|
||||
required init(_ row: Row) {
|
||||
id = row.value(named: "id")
|
||||
firstName = row.value(named: "firstName")
|
||||
lastName = row.value(named: "lastName")
|
||||
super.init(row)
|
||||
|
||||
}
|
||||
|
||||
override var persistentDictionary: [String: DatabaseValueConvertible?] {
|
||||
return [
|
||||
"id": id,
|
||||
"firstName": firstName,
|
||||
"lastName": lastName]
|
||||
}
|
||||
|
||||
override func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
|
||||
id = rowID
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
import UIKit
|
||||
|
||||
class PersonEditionViewController: UITableViewController, UITextFieldDelegate {
|
||||
@IBOutlet weak var firstNameTableViewCell: UITableViewCell!
|
||||
@IBOutlet weak var firstNameTextField: UITextField!
|
||||
@IBOutlet weak var lastNameTableViewCell: UITableViewCell!
|
||||
@IBOutlet weak var lastNameTextField: UITextField!
|
||||
|
||||
// The edited person
|
||||
var person: Person!
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
|
||||
// Initializes textFields with the person's names
|
||||
firstNameTextField.text = person.firstName
|
||||
lastNameTextField.text = person.lastName
|
||||
}
|
||||
|
||||
override func viewWillAppear(animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
|
||||
// Auto focus firstName
|
||||
firstNameTextField.becomeFirstResponder()
|
||||
}
|
||||
|
||||
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
|
||||
// Tapping a cell selects its text fields.
|
||||
if indexPath == tableView.indexPathForCell(firstNameTableViewCell) {
|
||||
firstNameTextField.becomeFirstResponder()
|
||||
} else if indexPath == tableView.indexPathForCell(lastNameTableViewCell) {
|
||||
lastNameTextField.becomeFirstResponder()
|
||||
}
|
||||
}
|
||||
|
||||
func textFieldShouldReturn(textField: UITextField) -> Bool {
|
||||
// Tapping Return key focuses next text field.
|
||||
if textField == firstNameTextField {
|
||||
lastNameTextField.becomeFirstResponder()
|
||||
} else {
|
||||
textField.resignFirstResponder()
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func textFieldDidEndEditing(textField: UITextField) {
|
||||
// Update person when text field ends editing.
|
||||
if textField == firstNameTextField {
|
||||
person.firstName = textField.text
|
||||
} else if textField == lastNameTextField {
|
||||
person.lastName = textField.text
|
||||
}
|
||||
}
|
||||
|
||||
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
|
||||
// About to cancel or commit: end editing.
|
||||
// This dismisses the keyboard early, and apply pending changes through
|
||||
// textFieldDidEndEditing(_).
|
||||
view.endEditing(true)
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
import UIKit
|
||||
|
||||
class PersonsViewController: UITableViewController {
|
||||
var persons: [Person] = []
|
||||
|
||||
override func viewWillAppear(animated: Bool) {
|
||||
// Reload persons, and the tableView
|
||||
reloadPersons()
|
||||
tableView.reloadData()
|
||||
|
||||
self.navigationItem.leftBarButtonItem = self.editButtonItem()
|
||||
super.viewWillAppear(animated)
|
||||
}
|
||||
|
||||
func reloadPersons() {
|
||||
persons = dbQueue.inDatabase { db in
|
||||
Person.order(Col.firstName, Col.lastName).fetchAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Segues
|
||||
|
||||
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
|
||||
if segue.identifier == "editNewPerson" {
|
||||
let personEditionViewController = (segue.destinationViewController as! UINavigationController).topViewController as! PersonEditionViewController
|
||||
personEditionViewController.person = Person()
|
||||
}
|
||||
}
|
||||
|
||||
// Unwind action: commit person edition
|
||||
@IBAction func commitPersonEdition(segue: UIStoryboardSegue) {
|
||||
let personEditionViewController = segue.sourceViewController as! PersonEditionViewController
|
||||
let person = personEditionViewController.person
|
||||
|
||||
// Ignore person with no name
|
||||
guard (person.firstName ?? "").characters.count > 0 || (person.lastName ?? "").characters.count > 0 else {
|
||||
return
|
||||
}
|
||||
|
||||
// Save person
|
||||
try! dbQueue.inDatabase { db in
|
||||
try person.save(db)
|
||||
}
|
||||
|
||||
// Reload persons, and insert a cell.
|
||||
reloadPersons()
|
||||
let index = persons.indexOf { $0.id == person.id }!
|
||||
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: .Automatic)
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Table View
|
||||
|
||||
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
||||
return persons.count
|
||||
}
|
||||
|
||||
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
|
||||
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
|
||||
|
||||
let person = persons[indexPath.row]
|
||||
cell.textLabel!.text = person.fullName
|
||||
cell.selectionStyle = .None
|
||||
return cell
|
||||
}
|
||||
|
||||
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
|
||||
// Delete the person
|
||||
let person = persons[indexPath.row]
|
||||
try! dbQueue.inTransaction { db in
|
||||
try person.delete(db)
|
||||
return .Commit
|
||||
}
|
||||
persons.removeAtIndex(indexPath.row)
|
||||
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
|
||||
}
|
||||
|
||||
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
|
||||
tableView.deselectRowAtIndexPath(indexPath, animated: true)
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
GRDBDemoiOS7
|
||||
============
|
||||
|
||||
This application runs an application that displays an editable list of persons and targets iOS7.
|
||||
|
||||
**To integrate GRDB in your iOS7 application:**
|
||||
|
||||
1. Drag all Swift files contained in the [GRDB folder](../../GRDB/) in your project.
|
||||
|
||||
2. In the **Build Phase** tab of your target, add `libsqlite3.tbd` in the **Link Binary With Libraries** section.
|
||||
|
||||
3. [Add a Bridging header to your project](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html) in which you add:
|
||||
|
||||
```objc
|
||||
#import "sqlite3.h"
|
||||
```
|
||||
|
||||
4. Run
|
||||
@@ -0,0 +1,132 @@
|
||||
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.20.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).
|
||||
|
||||
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.
|
||||
|
||||
**To install GRDB with a custom SQLite build:**
|
||||
|
||||
1. Clone the GRDB git repository, checkout the latest tagged version, and download SQLite sources:
|
||||
|
||||
```sh
|
||||
cd [GRDB directory]
|
||||
git checkout v2.0
|
||||
git submodule update --init SQLiteCustom/src
|
||||
````
|
||||
|
||||
2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5` and `SQLITE_ENABLE_PREUPDATE_HOOK`.
|
||||
|
||||
3. Create a folder named `GRDBCustomSQLite` somewhere in your project directory.
|
||||
|
||||
4. Create four files in the `GRDBCustomSQLite` folder:
|
||||
|
||||
- `SQLiteLib-USER.xcconfig`: this file sets the extra SQLite compilation flags.
|
||||
|
||||
```xcconfig
|
||||
// As many -D options as there are custom SQLite compilation options
|
||||
// Note: there is no space between -D and the option name.
|
||||
CUSTOM_SQLLIBRARY_CFLAGS = -DSQLITE_ENABLE_FTS5 -DSQLITE_ENABLE_PREUPDATE_HOOK
|
||||
```
|
||||
|
||||
- `GRDBCustomSQLite-USER.xcconfig`: this file lets GRDB know about extra compilation flags, and enables extra GRDB APIs.
|
||||
|
||||
```xcconfig
|
||||
// As many -D options as there are custom SQLite compilation options
|
||||
// Note: there is one space between -D and the option name.
|
||||
CUSTOM_OTHER_SWIFT_FLAGS = -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
```
|
||||
|
||||
- `GRDBCustomSQLite-USER.h`: this file lets your application know about extra compilation flags.
|
||||
|
||||
```c
|
||||
// As many #define as there are custom SQLite compilation options
|
||||
#define SQLITE_ENABLE_FTS5
|
||||
#define SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
```
|
||||
|
||||
- `GRDBCustomSQLite-INSTALL.sh`: this file installs the three other files.
|
||||
|
||||
```sh
|
||||
# License: MIT License
|
||||
# https://github.com/swiftlyfalling/SQLiteLib/blob/master/LICENSE
|
||||
#
|
||||
#######################################################
|
||||
# PROJECT PATHS
|
||||
# !! MODIFY THESE TO MATCH YOUR PROJECT HIERARCHY !!
|
||||
#######################################################
|
||||
|
||||
# The path to the folder containing GRDB.xcodeproj:
|
||||
GRDB_SOURCE_PATH="${PROJECT_DIR}/GRDB"
|
||||
|
||||
# The path to your custom "SQLiteLib-USER.xcconfig":
|
||||
SQLITELIB_XCCONFIG_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/SQLiteLib-USER.xcconfig"
|
||||
|
||||
# The path to your custom "GRDBCustomSQLite-USER.xcconfig":
|
||||
CUSTOMSQLITE_XCCONFIG_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/GRDBCustomSQLite-USER.xcconfig"
|
||||
|
||||
# The path to your custom "GRDBCustomSQLite-USER.h":
|
||||
CUSTOMSQLITE_H_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/GRDBCustomSQLite-USER.h"
|
||||
|
||||
#######################################################
|
||||
#
|
||||
#######################################################
|
||||
|
||||
|
||||
if [ ! -d "$GRDB_SOURCE_PATH" ];
|
||||
then
|
||||
echo "error: Path to GRDB source (GRDB_SOURCE_PATH) missing/incorrect: $GRDB_SOURCE_PATH"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
SyncFileChanges () {
|
||||
SOURCE=$1
|
||||
DESTINATIONPATH=$2
|
||||
DESTINATIONFILENAME=$3
|
||||
DESTINATION="${DESTINATIONPATH}/${DESTINATIONFILENAME}"
|
||||
|
||||
if [ ! -f "$SOURCE" ];
|
||||
then
|
||||
echo "error: Source file missing: $SOURCE"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
rsync -a "$SOURCE" "$DESTINATION"
|
||||
}
|
||||
|
||||
SyncFileChanges $SQLITELIB_XCCONFIG_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom/src" "SQLiteLib-USER.xcconfig"
|
||||
SyncFileChanges $CUSTOMSQLITE_XCCONFIG_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom" "GRDBCustomSQLite-USER.xcconfig"
|
||||
SyncFileChanges $CUSTOMSQLITE_H_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom" "GRDBCustomSQLite-USER.h"
|
||||
|
||||
echo "Finished syncing"
|
||||
```
|
||||
|
||||
Modify the top of `GRDBCustomSQLite-INSTALL.sh` file so that it contains correct paths.
|
||||
|
||||
5. Embed the `GRDB.xcodeproj` project in your own project.
|
||||
|
||||
6. Add the `GRDBCustomSQLiteOSX` or `GRDBCustomSQLiteiOS` target in the **Target Dependencies** section of the **Build Phases** tab of your **application target**.
|
||||
|
||||
7. Add the `GRDBCustomSQLite.framework` from the targetted platform to the **Embedded Binaries** section of the **General** tab of your **application target**.
|
||||
|
||||
8. Add a Run Script phase for your target in the **Pre-actions** section of the **Build** tab of your **application scheme**:
|
||||
|
||||
```sh
|
||||
source "${PROJECT_DIR}/GRDBCustomSQLite/GRDBCustomSQLite-INSTALL.sh"
|
||||
```
|
||||
|
||||
The path should be the path to your `GRDBCustomSQLite-INSTALL.sh` file.
|
||||
|
||||
9. Check the "Shared" checkbox of your application scheme (this lets you commit the pre-action in your Version Control System).
|
||||
|
||||
Now you can use GRDB with your custom SQLite build:
|
||||
|
||||
```swift
|
||||
import GRDBCustomSQLite
|
||||
|
||||
let dbQueue = try DatabaseQueue(...)
|
||||
```
|
||||
@@ -0,0 +1,591 @@
|
||||
GRDB Extension Guide
|
||||
====================
|
||||
|
||||
**Some parts of GRDB are extensible, so that you can make it better fit your needs.**
|
||||
|
||||
This guide is a step-by-step tour of GRDB extensibility, around a few topics:
|
||||
|
||||
- **[Add a value type](#add-a-value-type)**
|
||||
|
||||
You'll learn how to turn UIColor into a value type that you can store, fetch, and use in your records:
|
||||
|
||||
```swift
|
||||
let rows = try Row.fetchCursor(db, "SELECT name, color FROM clothes")
|
||||
while let row = try rows.next() {
|
||||
let name: String = row["name"]
|
||||
let color: UIColor = row["color"] // <-- New! UIColor as value
|
||||
}
|
||||
```
|
||||
|
||||
- **[Add an SQLite function or operator](#add-an-sqlite-function-or-operator)**
|
||||
|
||||
You'll learn how to add support for the [STRFTIME](https://www.sqlite.org/lang_datefunc.html) function, and the [GLOB](https://www.sqlite.org/lang_expr.html#like) operator:
|
||||
|
||||
```swift
|
||||
Books.select(strftime("%Y", Column("publishedDate"))) // <-- New! strftime function
|
||||
Books.filter(Column("body").glob("*Moby-Dick*")) // <-- New! glob method
|
||||
```
|
||||
|
||||
- **[Add a new kind of SQLite expression](#add-a-new-kind-of-sqlite-expression)**
|
||||
|
||||
You'll learn how to add support for [CAST expressions](https://www.sqlite.org/lang_expr.html#castexpr):
|
||||
|
||||
```swift
|
||||
let jsonString = Column("jsonString")
|
||||
let request = Books.select(cast(jsonString, as: .blob)) // <-- New! cast function
|
||||
let rows = try Row.fetchCursor(db, request)
|
||||
while let row = try rows.next() {
|
||||
let data = row.dataNoCopy(atIndex: 0)
|
||||
}
|
||||
```
|
||||
|
||||
- **Extend the query interface requests**
|
||||
|
||||
You may need to extend the [query interface requests](../../../#requests) so that their SELECT queries could embed recursive clauses, table joins, etc.
|
||||
|
||||
Pull requests are welcome. Open issues if you have questions.
|
||||
|
||||
Meanwhile, you can build your own [custom requests](../../../#custom-requests).
|
||||
|
||||
- **[Add a custom FTS5 full-text tokenizer](FTS5Tokenizers.md)**
|
||||
|
||||
Custom tokenizers can leverage extra full-text features such as synonyms or stop words.
|
||||
|
||||
- **Support a new kind of SQL query**
|
||||
|
||||
For example, you may need to generate SQL triggers, or create specific kinds of virtual tables.
|
||||
|
||||
Pull requests are welcome. Open issues if you have questions.
|
||||
|
||||
|
||||
## Add a Value Type
|
||||
|
||||
**All value types adopt the [DatabaseValueConvertible protocol](../../../#custom-value-types).**
|
||||
|
||||
```swift
|
||||
protocol DatabaseValueConvertible {
|
||||
/// Returns a value that can be stored in the database.
|
||||
var databaseValue: DatabaseValue { get }
|
||||
|
||||
/// Returns a value initialized from databaseValue, if possible.
|
||||
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self?
|
||||
}
|
||||
```
|
||||
|
||||
The `databaseValue` property returns [DatabaseValue](../../../#databasevalue), a type that wraps the five values supported by SQLite: NULL, Int64, Double, String and Data. Since DatabaseValue has no public initializer, use `DatabaseValue.null`, or another type that already adopts the protocol: `1.databaseValue`, `"foo".databaseValue`, etc. Conversion to DatabaseValue *must not* fail.
|
||||
|
||||
The `fromDatabaseValue()` factory method returns an instance of your custom type if the databaseValue contains a suitable value. If the databaseValue does not contain a suitable value, such as "foo" for Date, `fromDatabaseValue` *must* return nil (GRDB will interpret this nil result as a conversion error, and react accordingly).
|
||||
|
||||
**What does the DatabaseValueConvertible protocol bring to a type like UIColor?**
|
||||
|
||||
Well, you will be able to use UIColor like all other [value types](../../../#values) (Bool, Int, String, Date, Swift enums, etc.):
|
||||
|
||||
- Use UIColor as [statement arguments](../../../#executing-updates):
|
||||
|
||||
```swift
|
||||
try db.execute(
|
||||
"INSERT INTO clothes (name, color) VALUES (?, ?)",
|
||||
arguments: ["Shirt", UIColor.red])
|
||||
```
|
||||
|
||||
- UIColor can be [extracted from rows](../../../#column-values):
|
||||
|
||||
```swift
|
||||
let rows = try Row.fetchCursor(db, "SELECT * FROM clothes")
|
||||
while let row = try rows.next() {
|
||||
let name: String = row["name"]
|
||||
let color: UIColor = row["color"]
|
||||
}
|
||||
```
|
||||
|
||||
- UIColor can be [directly fetched](../../../#value-queries):
|
||||
|
||||
```swift
|
||||
let colors = try UIColor.fetchAll(db, "SELECT DISTINCT color FROM clothes") // [UIColor]
|
||||
```
|
||||
|
||||
- Use UIColor in [Records](../../../#records):
|
||||
|
||||
```swift
|
||||
class ClothingItem : Record {
|
||||
var name: String
|
||||
var color: UIColor
|
||||
|
||||
required init(row: Row) {
|
||||
name = row["name"]
|
||||
color = row["color"]
|
||||
super.init(row: row)
|
||||
}
|
||||
|
||||
override func encode(to container: inout PersistenceContainer) {
|
||||
container["name"] = name
|
||||
container["color"] = color
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- Use UIColor in the [query interface](../../../#the-query-interface):
|
||||
|
||||
```swift
|
||||
let redClothes = try ClothingItem.filter(colorColumn == UIColor.red).fetchAll(db)
|
||||
```
|
||||
|
||||
**Let's have UIColor adopt DatabaseValueConvertible**
|
||||
|
||||
In order to preserve as most information as possible, we'll archive UIColor as a data blob using the NSCoding protocol. But YMMV.
|
||||
|
||||
```swift
|
||||
extension UIColor : DatabaseValueConvertible {
|
||||
|
||||
/// Encode UIColor as a data blob
|
||||
var databaseValue: DatabaseValue {
|
||||
// Use NSKeyedArchiver to build Data
|
||||
let data = NSKeyedArchiver.archivedData(withRootObject: self)
|
||||
|
||||
// Data is already DatabaseValueConvertible
|
||||
return data.databaseValue
|
||||
}
|
||||
|
||||
/// Returns a UIColor if databaseValue contains suitable data, and
|
||||
/// nil otherwise.
|
||||
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
// Only Data blobs can contain a UIColor
|
||||
guard let data = Data.fromDatabaseValue(databaseValue) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
// We're looking for an archived object
|
||||
guard let color = NSKeyedUnarchiver.unarchiveObject(with: data) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
// The cast function will return nil if the unarchived object doesn't
|
||||
// have the correct type
|
||||
return cast(color) // Converts Any to Self?
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Use the `cast` utility function when you want *non-final classes* to implement DatabaseValueConvertible. It avoids compiler errors that are not easy to deal with. Note that final classes and value types won't need it.
|
||||
|
||||
```swift
|
||||
// Workaround Swift inconvenience around factories methods of non-final classes
|
||||
func cast<T, U>(_ value: T) -> U? {
|
||||
return value as? U
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Add an SQLite Function or Operator
|
||||
|
||||
**When an SQLite [function](https://www.sqlite.org/lang_corefunc.html) or [operator](https://www.sqlite.org/lang_expr.html) is missing from GRDB**, this usually means that there hasn't been a [feature request](http://github.com/groue/GRDB.swift/issues) yet.
|
||||
|
||||
But you don't have to wait: you can extend GRDB and the query interface to add support for the missing syntax element (and eventually submit a pull request later).
|
||||
|
||||
Let's remind our goal: we'll add the [STRFTIME](https://www.sqlite.org/lang_datefunc.html) function, and the [GLOB](https://www.sqlite.org/lang_expr.html#like) operator.
|
||||
|
||||
Their SQL usage is the following:
|
||||
|
||||
```sql
|
||||
-- Publication years of books
|
||||
SELECT STRFTIME('%Y', publishedOn) FROM books;
|
||||
-- Books that talk about Moby Dick
|
||||
SELECT * FROM books WHERE body GLOB '*Moby-Dick*';
|
||||
```
|
||||
|
||||
Translated in the query interface, this gives:
|
||||
|
||||
```swift
|
||||
Books.select(strftime("%Y", Column("publishedDate")))
|
||||
Books.filter(Column("body").glob("*Moby-Dick*"))
|
||||
```
|
||||
|
||||
`strftime` is a top-level Swift function because this is how GRDB usually imports SQLite functions which do not have matching standard Swift counterpart, like AVG, LEGNTH, SUM. It helps the Swift code looking like SQL when it is relevant.
|
||||
|
||||
In the same fashion, we expose the GLOB SQL operator as the `glob` Swift method, just because `value.glob(pattern)` reads like `value GLOB pattern`.
|
||||
|
||||
Whenever you import a SQL feature to Swift, you'll have to decide: should you preserve the SQL look and feel, or adopt a well-established swiftism? It's really up to you.
|
||||
|
||||
|
||||
### STRFTIME
|
||||
|
||||
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
|
||||
The [STRFTIME](https://www.sqlite.org/lang_datefunc.html) SQL function accepts many arguments. We'll simplify it to `strftime(format, date)`, so that we can write:
|
||||
|
||||
```sql
|
||||
// Publication years of books
|
||||
// SELECT STRFTIME('%Y', publishedOn) FROM books
|
||||
Books.select(strftime("%Y", Column("publishedDate")))
|
||||
```
|
||||
|
||||
The signature of the Swift `strftime` function is:
|
||||
|
||||
```swift
|
||||
func strftime(_ format: String, _ date: SQLSpecificExpressible) -> SQLExpression
|
||||
```
|
||||
|
||||
SQLSpecificExpressible and SQLExpression are types of the [query interface](../../../#the-query-interface) that you do not usually see. We have moved down one floor, closer to the SQL guts of GRDB. We'll see more new types and protocols below.
|
||||
|
||||
The return value is SQLExpression. All GRDB functions and operators that build [query interface expressions](../../../#expressions) return values of this type. It represents actual [SQLite expressions](https://www.sqlite.org/lang_expr.html).
|
||||
|
||||
SQLExpression is a protocol, so that you can build your own [custom expressions](#add-a-new-kind-of-sqlite-expression). But GRDB ships with a variety of [built-in expressions](#built-in-expressions) that are ready-made, and here we'll use SQLExpressionFunction that is dedicated to function calls:
|
||||
|
||||
```swift
|
||||
struct SQLExpressionFunction : SQLExpression {
|
||||
/// Creates an SQL function call
|
||||
///
|
||||
/// // ABS(-1)
|
||||
/// SQLExpressionFunction(.abs, arguments: -1)
|
||||
init(_ functionName: SQLFunctionName, arguments: SQLExpressible...)
|
||||
}
|
||||
```
|
||||
|
||||
So here is the code that defines our `strftime` function:
|
||||
|
||||
```swift
|
||||
// Add a SQLFunctionName just like we add NSNotification.Name since
|
||||
// the release of Swift 3.
|
||||
extension SQLFunctionName {
|
||||
/// The `STRFTIME` SQL function
|
||||
static let strftime = SQLFunctionName("STRFTIME")
|
||||
}
|
||||
|
||||
/// Returns an expression that evaluates the `STRFTIME` SQL function.
|
||||
///
|
||||
/// // STRFTIME('%Y', date)
|
||||
/// strftime("%Y", Column("date"))
|
||||
func strftime(_ format: String, _ date: SQLSpecificExpressible) -> SQLExpression {
|
||||
return SQLExpressionFunction(.strftime, arguments: format, date)
|
||||
}
|
||||
```
|
||||
|
||||
The `strftime` function is now complete, ready to be used. We haven't yet described the SQLSpecificExpressible type of the `date` argument:
|
||||
|
||||
SQLSpecificExpressible is the protocol for all types that can be turned into a SQL expression, but types like Int, Date, or UIColor that exist outside of GRDB and the query interface. Having `strftime` accept a SQLSpecificExpressible date prevents it from polluting the global space. It is *specific* to GRDB:
|
||||
|
||||
```swift
|
||||
strftime("%Y", Date()) // Compiler error
|
||||
strftime("%Y", Column("date")) // SQLExpression: STRFTIME('%Y', date)
|
||||
```
|
||||
|
||||
You may want to compare it to another protocol, SQLExpressible, which will be described [below](#add-a-new-kind-of-sqlite-expression), when we add support for CAST SQL expressions.
|
||||
|
||||
> :point_up: **Note**: whenever you extend GRDB with a Swift function, method, or operator, you should generally make sure that its signature contains at least one GRDB-specific type. In the `strftime` function, it is the SQLSpecificExpressible protocol.
|
||||
|
||||
|
||||
### GLOB
|
||||
|
||||
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
|
||||
For the [GLOB](https://www.sqlite.org/lang_expr.html#like) operator, we want to define the glob Swift method:
|
||||
|
||||
```swift
|
||||
// Books that talk about Moby Dick
|
||||
// SELECT * FROM books WHERE body GLOB '*Moby-Dick*'
|
||||
Books.filter(Column("body").glob("*Moby-Dick*"))
|
||||
```
|
||||
|
||||
This time we can't use the SQLExpressionFunction type, because it can't generate the SQL for a binary operator. Instead, we'll use another [built-in expression](#built-in-expressions), SQLExpressionBinary:
|
||||
|
||||
```swift
|
||||
struct SQLExpressionBinary : SQLExpression {
|
||||
/// Creates an expression made of two expressions joined with a binary operator.
|
||||
///
|
||||
/// // length * width
|
||||
/// SQLExpressionBinary(.multiply, Column("length"), Column("width"))
|
||||
init(_ op: SQLBinaryOperator, _ lhs: SQLExpressible, _ rhs: SQLExpressible)
|
||||
}
|
||||
```
|
||||
|
||||
Now we have to find the signature of our Swift method. The GLOB operator accepts any value on both sides. However, what kind of Swift code should we accept?
|
||||
|
||||
```swift
|
||||
// 1) body GLOB '*Moby-Dick*' -- Yes, of course
|
||||
Column("body").glob("*Moby-Dick*")
|
||||
// 2) body GLOB pattern -- Sure, why not?
|
||||
Column("body").glob(Column("pattern"))
|
||||
// 3) 'Some Swift String' GLOB pattern - Not sure, but OK
|
||||
"Some Swift String".glob(Column("pattern"))
|
||||
// 4) 'Some Swift String' GLOB 'Another Swift String' -- NO
|
||||
"Some Swift String".glob("Another Swift String")
|
||||
```
|
||||
|
||||
We don't want the form 4, because this is an unacceptable pollution of the Swift global namespace. A good GRDB extension limits its scope to database-related code.
|
||||
|
||||
We thus have two overloaded definitions of the `glob` method:
|
||||
|
||||
```swift
|
||||
extension SQLSpecificExpressible {
|
||||
func glob(_ pattern: SQLExpressible) -> SQLExpression
|
||||
}
|
||||
extension SQLExpressible {
|
||||
func glob(_ pattern: SQLSpecificExpressible) -> SQLExpression
|
||||
}
|
||||
```
|
||||
|
||||
SQLExpressible is the protocol for all types that can be turned into a SQL expression. This includes all expressions, and all [value types](../../../#values) (including String).
|
||||
|
||||
SQLSpecificExpressible is a sub protocol of SQLExpressible protocol, restricted to all types that can be turned into a SQL expression, but types like Int, Date, or String that exist outside of GRDB and the query interface.
|
||||
|
||||
By extending both, we can define the GLOB operators for any pair that contains at least one type that is specific to GRDB - and leave the global Swift space clean.
|
||||
|
||||
The final implementation follows:
|
||||
|
||||
```swift
|
||||
// Add a SQLBinaryOperator just like we add NSNotification.Name since
|
||||
// the release of Swift 3.
|
||||
extension SQLBinaryOperator {
|
||||
/// The `GLOB` binary operator
|
||||
static let glob = SQLBinaryOperator("GLOB")
|
||||
}
|
||||
|
||||
extension SQLSpecificExpressible {
|
||||
/// Returns an SQL `GLOB` expression.
|
||||
///
|
||||
/// // body GLOB '*Moby-Dick*'
|
||||
/// Column("body").glob("*Moby-Dick*")
|
||||
func glob(_ pattern: SQLExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.glob, self, pattern)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLExpressible {
|
||||
/// Returns an SQL `GLOB` expression.
|
||||
///
|
||||
/// // 'Some Swift String' GLOB pattern
|
||||
/// "Some Swift String".glob(Column("pattern"))
|
||||
func glob(_ pattern: SQLSpecificExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.glob, self, pattern)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Built-in Expressions
|
||||
|
||||
When you extend GRDB with a new function, method, or operator that generates an [SQL expression](https://www.sqlite.org/lang_expr.html), you have to return a value the adopts the SQLExpression protocol.
|
||||
|
||||
We have already seen in our [previous](#strftime) [examples](#glob) two concrete types that generate SQL function calls and binary operators: SQLExpressionFunction and SQLExpressionBinary.
|
||||
|
||||
This section of the documentation lists all built-in expressions. Adding a custom SQLExpression type will be documented [below](#add-a-new-kind-of-sqlite-expression).
|
||||
|
||||
|
||||
#### Column and DatabaseValue
|
||||
|
||||
The [Column](../../../#the-query-interface) type from the query interface, and [DatabaseValue](../../../#databasevalue), the type that wraps the five values supported by SQLite (NULL, Int64, Double, String and Data) are expressions. They are rather trivial, and it is unlikely that you use them in your GRDB extensions.
|
||||
|
||||
|
||||
#### SQLExpressionLiteral
|
||||
|
||||
Use SQLExpressionLiteral when you need to go fast:
|
||||
|
||||
```swift
|
||||
struct SQLExpressionLiteral : SQLExpression {
|
||||
/// Creates an SQL literal expression.
|
||||
///
|
||||
/// SQLExpressionLiteral("1 + 2")
|
||||
/// SQLExpressionLiteral("? + ?", arguments: [1, 2])
|
||||
init(_ sql: String, arguments: StatementArguments? = nil)
|
||||
}
|
||||
```
|
||||
|
||||
For an example of use, see the [Add a new kind of SQLite expression](#add-a-new-kind-of-sqlite-expression) chapter.
|
||||
|
||||
|
||||
#### SQLExpressionUnary
|
||||
|
||||
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
|
||||
SQLExpressionUnary builds an expression by prefixing another expression with an unary operator:
|
||||
|
||||
```swift
|
||||
struct SQLExpressionUnary : SQLExpression {
|
||||
/// Creates an expression made of an unary operator and
|
||||
/// an operand expression.
|
||||
///
|
||||
/// // NOT favorite
|
||||
/// SQLExpressionUnary(.not, Column("favorite"))
|
||||
init(_ op: SQLUnaryOperator, _ value: SQLExpressible)
|
||||
}
|
||||
```
|
||||
|
||||
You add missing SQLite unary operators by extending SQLUnaryOperator:
|
||||
|
||||
```swift
|
||||
extension SQLUnaryOperator {
|
||||
/// The `+` unary operator
|
||||
static let plus = SQLUnaryOperator("+", needsRightSpace: false)
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
#### SQLExpressionBinary
|
||||
|
||||
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
|
||||
SQLExpressionBinary builds an expression by joining two expressions with a binary operator:
|
||||
|
||||
```swift
|
||||
struct SQLExpressionBinary : SQLExpression {
|
||||
/// Creates an expression made of two expressions joined with a binary operator.
|
||||
///
|
||||
/// // length * width
|
||||
/// SQLExpressionBinary(.multiply, Column("length"), Column("width"))
|
||||
init(_ op: SQLBinaryOperator, _ lhs: SQLExpressible, _ rhs: SQLExpressible)
|
||||
}
|
||||
```
|
||||
|
||||
You add missing SQLite binary operators by extending SQLBinaryOperator:
|
||||
|
||||
```swift
|
||||
extension SQLBinaryOperator {
|
||||
/// The `GLOB` binary operator
|
||||
static let glob = SQLBinaryOperator("GLOB")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
#### SQLExpressionFunction
|
||||
|
||||
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
|
||||
SQLExpressionFunction builds an SQL function call:
|
||||
|
||||
```swift
|
||||
struct SQLExpressionFunction : SQLExpression {
|
||||
/// Creates an SQL function call
|
||||
///
|
||||
/// // ABS(-1)
|
||||
/// SQLExpressionFunction(.abs, arguments: -1)
|
||||
init(_ functionName: SQLFunctionName, arguments: SQLExpressible...)
|
||||
}
|
||||
```
|
||||
|
||||
You add missing SQLite function names by extending SQLFunctionName:
|
||||
|
||||
```swift
|
||||
extension SQLFunctionName {
|
||||
/// The `STRFTIME` SQL function
|
||||
static let strftime = SQLFunctionName("STRFTIME")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
#### The IN Operator
|
||||
|
||||
Build a `value IN (...)` expression from any sequence of [values](../../../#values):
|
||||
|
||||
```swift
|
||||
// SQLExpression: id IN (1, 2, 3)
|
||||
[1,2,3].contains(Column("id"))
|
||||
|
||||
// SQLExpression: id NOT IN (1, 2, 3)
|
||||
![1,2,3].contains(Column("id"))
|
||||
```
|
||||
|
||||
|
||||
#### The BETWEEN Operator
|
||||
|
||||
Build a `value BETWEEN min AND max` expression from Swift ranges:
|
||||
|
||||
```swift
|
||||
// SQLExpression: id BETWEEN 1 AND 10
|
||||
1...10.contains(Column("id")
|
||||
```
|
||||
|
||||
|
||||
#### The COUNT Function
|
||||
|
||||
Build a `COUNT(...)` expression from the [count](http://groue.github.io/GRDB.swift/docs/2.0/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/2.0/Functions.html) functions:
|
||||
|
||||
```swift
|
||||
// SQLExpression: COUNT(email)
|
||||
count(Column("email"))
|
||||
|
||||
// SQLExpression: COUNT(DISTINCT email)
|
||||
count(distinct: Column("email"))
|
||||
```
|
||||
|
||||
|
||||
#### The COLLATE Operator
|
||||
|
||||
Build a `expression COLLATE collation` expression with the `collating` method:
|
||||
|
||||
```swift
|
||||
// SQLExpression: name = 'Arthur' COLLATE NOCASE
|
||||
Column("name").collating(.nocase) == "Arthur"
|
||||
```
|
||||
|
||||
|
||||
## Add a New Kind of SQLite Expression
|
||||
|
||||
GRDB does not have built-in support for the full range of the SQLite [expression grammar](https://www.sqlite.org/lang_expr.html).
|
||||
|
||||
For example, [CAST expressions](https://www.sqlite.org/lang_expr.html#castexpr) are not ready-made. They can be useful, though: a CAST expression can efficiently convert json strings to UTF-8 data blobs for you:
|
||||
|
||||
```sql
|
||||
SELECT CAST(jsonString AS BLOB) FROM books
|
||||
```
|
||||
|
||||
We'll add below a Swift `cast` function:
|
||||
|
||||
```swift
|
||||
let request = Books.select(cast(Column("jsonString"), as: .blob))
|
||||
let jsonDatas = try Data.fetchAll(db, request) // [Data]
|
||||
```
|
||||
|
||||
`cast` is a top-level Swift function because this is how GRDB usually imports SQLite features which do not have matching standard Swift counterpart. It helps the Swift code looking like SQL when it is relevant. But YMMV.
|
||||
|
||||
The signature of the `cast` function is:
|
||||
|
||||
```swift
|
||||
func cast(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression
|
||||
```
|
||||
|
||||
Database.ColumnType is a String-based enumeration of all database column types (.integer, .text, .blob, etc.) You have already used if you have [created tables](../../../#create-tables) using the query interface.
|
||||
|
||||
The return type SQLExpression is the type returned by all GRDB functions and operators that build [query interface expressions](../../../#expressions).
|
||||
|
||||
SQLExpression is a protocol. But GRDB ships with a variety of [built-in expressions](#built-in-expressions) that are ready-made, so that you generally don't have to write your custom expression type. Here we need something new. So we'll use the most versatile of all, SQLExpressionLiteral:
|
||||
|
||||
```swift
|
||||
struct SQLExpressionLiteral : SQLExpression {
|
||||
/// Creates an SQL literal expression.
|
||||
///
|
||||
/// SQLExpressionLiteral("1 + 2")
|
||||
/// SQLExpressionLiteral("? + ?", arguments: [1, 2])
|
||||
init(_ sql: String, arguments: StatementArguments? = nil)
|
||||
}
|
||||
```
|
||||
|
||||
Here is the code that defines our `cast` function:
|
||||
|
||||
|
||||
```swift
|
||||
func cast(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression {
|
||||
// Turn the value into a literal expression
|
||||
let literal: SQLExpressionLiteral = value.sqlExpression.literal
|
||||
|
||||
// Build our "CAST(value AS type)" sql snippet
|
||||
let sql = "CAST(\(literal.sql) AS \(type.rawValue))"
|
||||
|
||||
// And return a new literal expression, preserving input arguments
|
||||
return SQLExpressionLiteral(sql, arguments: literal.arguments)
|
||||
}
|
||||
```
|
||||
|
||||
We haven't yet described the SQLExpressible type of the `value` argument:
|
||||
|
||||
SQLExpressible is the protocol for all types that can be turned into a SQL expression. This includes all [value types](../../../#values) (Bool, Int, String, Date, Swift enums, etc.):
|
||||
|
||||
```swift
|
||||
cast("foo", as: .blob) // SQLExpression: CAST('foo' AS BLOB)
|
||||
cast(Column("name"), as: .blob) // SQLExpression: CAST(name AS BLOB)
|
||||
```
|
||||
|
||||
You may want to compare it to another protocol, SQLSpecificExpressible, which has been described [above](#strftime), when we were adding support for the STRFTIME SQL function.
|
||||
|
||||
> :point_up: **Note**: whenever you extend GRDB with a Swift function, method, or operator, you should generally make sure that its signature contains at least one GRDB-specific type. In the `cast` function, it is Database.ColumnType.
|
||||
|
||||
**If SQLExpressionLiteral reveals too limited for your purpose**, you may have to implement a new type that adopts the [SQLExpression](http://groue.github.io/GRDB.swift/docs/2.0/Protocols/SQLExpression.html) protocol.
|
||||
@@ -0,0 +1,389 @@
|
||||
FTS5 Tokenizers
|
||||
===============
|
||||
|
||||
**[FTS5](https://www.sqlite.org/fts5.html) is an extensible full-text search engine.**
|
||||
|
||||
GRDB lets you define your own custom FST5 tokenizers, and extend SQLite built-in tokenizers. Possible use cases are:
|
||||
|
||||
- Have "fi" match the ligature "fi" (U+FB01)
|
||||
- Have "first" match "1st"
|
||||
- Have "Encyclopaedia" match "Encyclopædia"
|
||||
- Have "Mueller" match "Müller", and "Grossmann" match "Großmann"
|
||||
- Have "romaji" match "ローマ字", and "pinyin" match "拼音"
|
||||
- Prevent "the" and other stop words from matching any document
|
||||
|
||||
**Table of Contents**
|
||||
|
||||
- [Tokenizers and Full-Text Search](#tokenizers-and-full-text-search)
|
||||
- [The Tokenizer Protocols](#the-tokenizer-protocols)
|
||||
- [Using a Custom Tokenizer](#using-a-custom-tokenizer)
|
||||
- [FTS5Tokenizer](#fts5tokenizer)
|
||||
- [FTS5CustomTokenizer](#fts5customtokenizer)
|
||||
- [FTS5WrapperTokenizer](#fts5wrappertokenizer)
|
||||
- [Choosing the Wrapped Tokenizer](#choosing-the-wrapped-tokenizer)
|
||||
- [Example: Synonyms](#example-synonyms)
|
||||
- [Example: Latin Script](#example-latin-script)
|
||||
|
||||
|
||||
## Tokenizers and Full-Text Search
|
||||
|
||||
**A Tokenizer splits text into tokens**. For example, a tokenizer can split "SQLite is a database engine" into the five tokens "SQLite", "is", "a", "database", and "engine".
|
||||
|
||||
FTS5 use tokenizers to tokenize both indexed documents and search patterns. **A match between a document and a search pattern happens when both produce *identical* tokens.**
|
||||
|
||||
All SQLite [built-in tokenizers](https://www.sqlite.org/fts5.html#tokenizers) tokenize both "SQLite" and "sqlite" into the common lowercase token "sqlite". This is why they are case-insensitive. Generally speaking, different tokenizers achieve different matching by applying different transformations to the input text.
|
||||
|
||||
- The [ascii](https://www.sqlite.org/fts5.html#ascii_tokenizer) tokenizer turns all ASCII characters to lowercase. "SQLite is a database engine" gives "sqlite", "is", "a", "database", and "engine". The query "SQLITE DATABASE" will match, because its tokens "sqlite" and "database" are found in the document.
|
||||
|
||||
- The [unicode61](https://www.sqlite.org/fts5.html#unicode61_tokenizer) tokenizer remove diacritics from latin characters. Unlike the ascii tokenizer, it will match "Jérôme" with "Jerome", as both produce the same "jerome" token.
|
||||
|
||||
- The [porter](https://www.sqlite.org/fts5.html#porter_tokenizer) tokenizer turns English words into their root: "database engine" gives the "databas" and "engin" tokens. The query "database engines" will match, because it produces the same tokens.
|
||||
|
||||
However, built-in tokenizers don't match "first" with "1st", because they produce the different "first" and "1st" tokens.
|
||||
|
||||
Nor do they match "Grossmann" with "Großmann", because they produce the different "grossmann" and "großmann" tokens.
|
||||
|
||||
Custom tokenizers help dealing with these situations. We'll see how to match "Grossmann" and "Großmann" by tokenizing them into "grossmann" (see [latin script](#example-latin-script)). We'll also see how to have "first" and "1st" emit *synonym tokens*, so that they can match too (see [synonyms](#example-synonyms)).
|
||||
|
||||
|
||||
## The Tokenizer Protocols
|
||||
|
||||
GRDB lets you use and define FTS5 tokenizers through three protocols:
|
||||
|
||||
- [FTS5Tokenizer](#fts5tokenizer): the protocol for all FTS5 tokenizers, including the [built-in tokenizers](https://www.sqlite.org/fts5.html#tokenizers) ascii, unicode61, and porter.
|
||||
|
||||
- [FTS5CustomTokenizer](#fts5customtokenizer): the low-level protocol that lets custom tokenizers use the raw [FTS5 C API](https://www.sqlite.org/fts5.html#custom_tokenizers).
|
||||
|
||||
- [FTS5WrapperTokenizer](#fts5wrappertokenizer): the high-level protocol for custom tokenizers that post-processes the tokens produced by another FTS5Tokenizer.
|
||||
|
||||
|
||||
## Using a Custom Tokenizer
|
||||
|
||||
Once you have a custom tokenizer type that adopts [FTS5CustomTokenizer](#fts5customtokenizer) or [FTS5WrapperTokenizer](#fts5wrappertokenizer), it can fuel the FTS5 engine.
|
||||
|
||||
**Register the custom tokenizer into the database:**
|
||||
|
||||
```swift
|
||||
class MyTokenizer : FTS5CustomTokenizer { ... }
|
||||
|
||||
dbQueue.add(tokenizer: MyTokenizer.self) // or dbPool.add
|
||||
```
|
||||
|
||||
**Create [full-text tables](../../../#create-fts5-virtual-tables) that use the custom tokenizer:**
|
||||
|
||||
```swift
|
||||
try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
t.tokenizer = MyTokenizer.tokenizerDescriptor()
|
||||
t.column("content")
|
||||
}
|
||||
```
|
||||
|
||||
The full-text table can be fed and queried in [a regular way](../../../#full-text-search):
|
||||
|
||||
```swift
|
||||
try db.execute("INSERT INTO documents VALUES (?)", arguments: ["..."])
|
||||
try Document(content: "...").insert(db)
|
||||
|
||||
let pattern = FTS5Pattern(matchingAnyTokenIn:"...")
|
||||
let documents = try Document.matching(pattern).fetchAll(db)
|
||||
```
|
||||
|
||||
|
||||
## FTS5Tokenizer
|
||||
|
||||
**FST5Tokenizer** is the protocol for all FTS5 tokenizers.
|
||||
|
||||
It only requires a tokenization method that matches the low-level `xTokenize` C function documented at https://www.sqlite.org/fts5.html#custom_tokenizers. We'll discuss it more when describing custom tokenizers.
|
||||
|
||||
```swift
|
||||
typealias FTS5TokenCallback = @convention(c) (
|
||||
_ context: UnsafeMutableRawPointer?,
|
||||
_ flags: Int32,
|
||||
_ pToken: UnsafePointer<Int8>?,
|
||||
_ nToken: Int32,
|
||||
_ iStart: Int32,
|
||||
_ iEnd: Int32) -> Int32
|
||||
|
||||
protocol FTS5Tokenizer : class {
|
||||
func tokenize(
|
||||
context: UnsafeMutableRawPointer?,
|
||||
tokenization: FTS5Tokenization,
|
||||
pText: UnsafePointer<Int8>?,
|
||||
nText: Int32,
|
||||
tokenCallback: FTS5TokenCallback?) -> Int32
|
||||
}
|
||||
```
|
||||
|
||||
You can instantiate tokenizers, including [built-in tokenizers](https://www.sqlite.org/fts5.html#tokenizers), with the `Database.makeTokenizer()` method:
|
||||
|
||||
```swift
|
||||
let unicode61 = try db.makeTokenizer(.unicode61()) // FTS5Tokenizer
|
||||
```
|
||||
|
||||
|
||||
## FTS5CustomTokenizer
|
||||
|
||||
**FTS5CustomTokenizer** is the low-level protocol for your custom tokenizers.
|
||||
|
||||
```swift
|
||||
protocol FTS5CustomTokenizer : FTS5Tokenizer {
|
||||
static var name: String { get }
|
||||
init(db: Database, arguments: [String]) throws
|
||||
}
|
||||
```
|
||||
|
||||
Custom tokenizers have a name, like built-in tokenizers have a name. Don't use "ascii", "porter", or "unicode61" since they are already taken!
|
||||
|
||||
```swift
|
||||
final class MyTokenizer : FTS5CustomTokenizer {
|
||||
static let name = "custom"
|
||||
}
|
||||
```
|
||||
|
||||
SQLite instantiates tokenizers when it needs tokens. The arguments parameter of the `init(db:arguments:)` initializer is an array of strings, which your custom tokenizer can use for its own purposes. In the example below, the arguments will be `["arg1", "arg2"]`.
|
||||
|
||||
```swift
|
||||
// CREATE VIRTUAL TABLE documents USING fts5(
|
||||
// tokenize='custom arg1 arg2',
|
||||
// authors, title, body
|
||||
// )
|
||||
try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
t.tokenizer = MyTokenizer.tokenizerDescriptor(arguments: ["arg1", "arg2"])
|
||||
t.column("authors")
|
||||
t.column("title")
|
||||
t.column("body")
|
||||
}
|
||||
```
|
||||
|
||||
FTS5CustomTokenizer inherits from [FTS5Tokenizer](#fts5tokenizer), and performs tokenization with its `tokenize(context:tokenization:pText:nText:tokenCallback:)` method. This low-level method matches the `xTokenize` C function documented at https://www.sqlite.org/fts5.html#custom_tokenizers.
|
||||
|
||||
This method arguments are:
|
||||
|
||||
- `context`: An opaque pointer that is the first argument to the `tokenCallback` function
|
||||
- `tokenization`: The reason why FTS5 is requesting tokenization.
|
||||
- `pText`: The tokenized text bytes. May or may not be nul-terminated.
|
||||
- `nText`: The number of bytes in the tokenized text.
|
||||
- `tokenCallback`: The function to call for each found token. It matches the `xToken` callback at https://www.sqlite.org/fts5.html#custom_tokenizers:
|
||||
- `context`: An opaque pointer
|
||||
- `flags`: Flags that tell FTS5 how to register the token
|
||||
- `pToken`: The token bytes. May or may not be nul-terminated.
|
||||
- `nToken`: The number of bytes in the token
|
||||
- `iStart`: Byte offset of token within input text
|
||||
- `iEnd`: Byte offset of end of token within input text
|
||||
|
||||
Since tokenization is hard, and pointers to byte buffers uneasy to deal with, you may enjoy the [FTS5WrapperTokenizer](#fts5wrappertokenizer) protocol.
|
||||
|
||||
|
||||
## FTS5WrapperTokenizer
|
||||
|
||||
**FTS5WrapperTokenizer** is the high-level protocol for your custom tokenizers. It provides a default implementation for the low-level `tokenize(context:tokenization:pText:nText:tokenCallback:)` method, so that the adopting type does not have to deal with raw byte buffers of the raw [FTS5 C API](https://www.sqlite.org/fts5.html#custom_tokenizers).
|
||||
|
||||
A FTS5WrapperTokenizer lets the hard tokenization job to another tokenizer, the "wrapped tokenizer", and post-processes the tokens produced by this wrapped tokenizer.
|
||||
|
||||
```swift
|
||||
protocol FTS5WrapperTokenizer : FTS5CustomTokenizer {
|
||||
var wrappedTokenizer: FTS5Tokenizer { get }
|
||||
func accept(
|
||||
token: String,
|
||||
flags: FTS5TokenFlags,
|
||||
for tokenization: FTS5Tokenization,
|
||||
tokenCallback: FTS5WrapperTokenCallback) throws
|
||||
}
|
||||
```
|
||||
|
||||
As all custom tokenizers, wrapper tokenizers must have a name:
|
||||
|
||||
```swift
|
||||
final class MyTokenizer : FTS5WrapperTokenizer {
|
||||
static let name = "custom"
|
||||
}
|
||||
```
|
||||
|
||||
The `wrappedTokenizer` property is the mandatory wrapped tokenizer. You instantiate it once, in the initializer:
|
||||
|
||||
```swift
|
||||
final class MyTokenizer : FTS5WrapperTokenizer {
|
||||
let wrappedTokenizer: FTS5Tokenizer
|
||||
|
||||
init(db: Database, arguments: [String]) throws {
|
||||
// Wrap the unicode61 tokenizer
|
||||
wrappedTokenizer = try db.makeTokenizer(.unicode61())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Wrapper tokenizers have to implement the `accept(token:flags:for:tokenCallback:)` method.
|
||||
|
||||
For example, a tokenizer that simply passes tokens through gives:
|
||||
|
||||
```swift
|
||||
final class MyTokenizer : FTS5WrapperTokenizer {
|
||||
func accept(
|
||||
token: String,
|
||||
flags: FTS5TokenFlags,
|
||||
for tokenization: FTS5Tokenization,
|
||||
tokenCallback: FTS5WrapperTokenCallback) throws
|
||||
{
|
||||
// pass through
|
||||
try tokenCallback(token, flags)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The token argument is a token produced by the wrapped tokenizer, ready to be ignored, modified, or multiplied into several [synonyms](#example-synonyms).
|
||||
|
||||
The tokenization parameter tells the reason why tokens are produced, if FTS5 is tokenizing a document, or a search pattern. Some tokenizers may produce different tokens depending on this parameter.
|
||||
|
||||
Finally, the tokenCallback is a function you call to output a custom token.
|
||||
|
||||
There are a two rules to observe when implementing the accept method:
|
||||
|
||||
1. Errors thrown by the tokenCallback function must not be caught (they notify that FTS5 requires the tokenization process to stop immediately).
|
||||
2. The flags parameter should be given unmodified to the tokenCallback function along with the custom token, unless you union it with the `.colocated` flag when the tokenizer produces [synonyms](#example-synonyms).
|
||||
|
||||
|
||||
### Choosing the Wrapped Tokenizer
|
||||
|
||||
The wrapped tokenizer can be hard-coded, or chosen at runtime.
|
||||
|
||||
For example, your custom tokenizer can wrap [unicode61](https://www.sqlite.org/fts5.html#unicode61_tokenizer), unless arguments say otherwise (in a fashion similar to the [porter](https://www.sqlite.org/fts5.html#porter_tokenizer) tokenizer):
|
||||
|
||||
```swift
|
||||
final class MyTokenizer : FTS5WrapperTokenizer {
|
||||
static let name = "custom"
|
||||
let wrappedTokenizer: FTS5Tokenizer
|
||||
|
||||
init(db: Database, arguments: [String]) throws {
|
||||
if arguments.isEmpty {
|
||||
wrappedTokenizer = try db.makeTokenizer(.unicode61())
|
||||
} else {
|
||||
let descriptor = FTS5TokenizerDescriptor(components: arguments)
|
||||
wrappedTokenizer = try db.makeTokenizer(descriptor)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Arguments are provided when the virtual table is created:
|
||||
|
||||
```swift
|
||||
// CREATE VIRTUAL TABLE documents USING fts5(
|
||||
// tokenize='custom',
|
||||
// content
|
||||
// )
|
||||
try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
// Wraps the default unicode61
|
||||
t.tokenizer = MyTokenizer.tokenizerDescriptor()
|
||||
t.column("content")
|
||||
}
|
||||
|
||||
// CREATE VIRTUAL TABLE documents USING fts5(
|
||||
// tokenize='custom ascii'
|
||||
// content
|
||||
// )
|
||||
try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
// Wraps ascii
|
||||
let ascii = FTS5TokenizerDescriptor.ascii()
|
||||
t.tokenizer = MyTokenizer.tokenizerDescriptor(arguments: ascii.components)
|
||||
t.column("content")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Example: Synonyms
|
||||
|
||||
**FTS5 lets tokenizers produce synonyms**, so that, for example, "first" can match "1st".
|
||||
|
||||
The topic of synonyms is documented at https://www.sqlite.org/fts5.html#synonym_support, which describes several methods. You should carefully read this documentation, and pick the method you prefer.
|
||||
|
||||
In the example below, we'll pick method (3), and implement a tokenizer that adds multiple synonyms for a single term to the FTS index. Using this method, when tokenizing document text, the tokenizer provides multiple synonyms for each token. So that when a document such as "I won first place" is tokenized, entries are added to the FTS index for "i", "won", "first", "1st" and "place".
|
||||
|
||||
We'll also take care of the SQLite advice:
|
||||
|
||||
> When using methods (2) or (3), it is important that the tokenizer only provide synonyms when tokenizing document text or query text, not both. Doing so will not cause any errors, but is inefficient.
|
||||
|
||||
```swift
|
||||
final class SynonymsTokenizer : FTS5WrapperTokenizer {
|
||||
static let name = "synonyms"
|
||||
let wrappedTokenizer: FTS5Tokenizer
|
||||
let synonyms: [Set<String>] = [["first", "1st"]]
|
||||
|
||||
init(db: Database, arguments: [String]) throws {
|
||||
wrappedTokenizer = try db.makeTokenizer(.unicode61())
|
||||
}
|
||||
|
||||
func synonyms(for token: String) -> Set<String>? {
|
||||
return synonyms.first { $0.contains(token) }
|
||||
}
|
||||
|
||||
func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
|
||||
if tokenization.contains(.query) {
|
||||
// Don't look for synonyms when tokenizing queries
|
||||
try tokenCallback(token, flags)
|
||||
return
|
||||
}
|
||||
|
||||
guard let synonyms = synonyms(for: token) else {
|
||||
// Token has no synonym
|
||||
try tokenCallback(token, flags)
|
||||
return
|
||||
}
|
||||
|
||||
for (index, synonym) in synonyms.enumerated() {
|
||||
// Notify each synonym, and set the colocated flag for all but the first
|
||||
let synonymFlags = (index == 0) ? flags : flags.union(.colocated)
|
||||
try tokenCallback(synonym, synonymFlags)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
|
||||
## Example: Latin Script
|
||||
|
||||
Languages that use the [latin script](https://en.wikipedia.org/wiki/Latin_script) offer a rich set of typographical, historical, and local features such as diacritics, ligatures, and dotless I: Großmann, fidélité (with the ligature "fi" U+FB01), Diyarbakır.
|
||||
|
||||
Full-text search in such a corpus often needs input tolerance, so that "encyclopaedia" can match "Encyclopædia", "Grossmann", "Großmann", and "Jerome", "Jérôme".
|
||||
|
||||
German has something specific in that both "Mueller" and "Muller" should match "Müller", when "Bauer" should not match "Baur" (only "ü" accepts both "u" and "ue"). A pull request that adds a chapter about German will be welcome.
|
||||
|
||||
A custom FTS5 tokenizer lets you provide fuzzy latin matching: after "Grossmann", "Großmann", and "GROSSMANN" have all been turned into "grossmann", they will all match together.
|
||||
|
||||
We'll wrap the built-in [unicode61](https://www.sqlite.org/fts5.html#unicode61_tokenizer) tokenizer (the one that knows how to split text on spaces and punctuations), and transform its tokens into their bare lowercase ascii form.
|
||||
|
||||
The tokenizer wrapping is provided by the [FTS5WrapperTokenizer](#fts5wrappertokenizer) protocol. The string transformation is provided by the [String.applyingTransform](https://developer.apple.com/reference/swift/string/1643133-applyingtransform) method:
|
||||
|
||||
```swift
|
||||
final class LatinAsciiTokenizer : FTS5WrapperTokenizer {
|
||||
static let name = "latinascii"
|
||||
let wrappedTokenizer: FTS5Tokenizer
|
||||
|
||||
init(db: Database, arguments: [String]) throws {
|
||||
wrappedTokenizer = try db.makeTokenizer(.unicode61())
|
||||
}
|
||||
|
||||
func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
|
||||
if let token = token.applyingTransform(StringTransform("Latin-ASCII; Lower"), reverse: false) {
|
||||
try tokenCallback(token, flags)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> :point_up: **Note**: String.applyingTransform is not available before iOS 9.0 and macOS 10.11. Use the Core Foundation function [CFStringTransform](https://developer.apple.com/reference/corefoundation/1542411-cfstringtransform) instead.
|
||||
|
||||
Remember to register LatinAsciiTokenizer before using it:
|
||||
|
||||
```swift
|
||||
dbQueue.add(tokenizer: LatinAsciiTokenizer.self) // or dbPool.add
|
||||
|
||||
dbQueue.inDatabase { db in
|
||||
try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
t.tokenizer = LatinAsciiTokenizer.tokenizerDescriptor()
|
||||
t.column("authors")
|
||||
t.column("title")
|
||||
t.column("body")
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1 @@
|
||||
The main documentation is available in [README.md](../../../#documentation).
|
||||
@@ -0,0 +1,32 @@
|
||||
Release Process
|
||||
===============
|
||||
|
||||
**This is internal documentation.**
|
||||
|
||||
To release a new GRDB version:
|
||||
|
||||
- Tests
|
||||
- `make test`
|
||||
- Build and run GRDBDemoiOS in Release configuration on a device
|
||||
- Archive GRDBDemoiOS
|
||||
- Check for performance regression with GRDBOSXPerformanceTests
|
||||
- On https://github.com/groue/sqlcipher.git upgrade, update SQLCipher version in README.md
|
||||
- On https://github.com/swiftlyfalling/SQLiteLib upgrade, update SQLite version in README.md and Documentation/CustomSQLiteBuilds.md
|
||||
- Update GRDB version number and release date in:
|
||||
- Makefile
|
||||
- CHANGELOG.md
|
||||
- Documentation/CustomSQLiteBuilds.md
|
||||
- Documentation/ExtendingGRDB.md
|
||||
- GRDB.swift.podspec
|
||||
- GRDBCipher.podspec
|
||||
- README.md
|
||||
- Support/Info.plist
|
||||
- Commit and tag
|
||||
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
|
||||
- Push to the master branch
|
||||
- Push to the Swift3 branch
|
||||
- `pod trunk push --allow-warnings GRDB.swift.podspec`
|
||||
- `pod trunk push --allow-warnings GRDBCipher.podspec`
|
||||
- `make doc`, and update index.html in the `gh-pages` branch
|
||||
- Update http://github.com/groue/GRDBDemo
|
||||
- Update http://github.com/groue/WWDCCompanion
|
||||
+7
-4
@@ -1,16 +1,19 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '0.49.0'
|
||||
s.version = '2.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A versatile SQLite toolkit for Swift, with WAL mode support.'
|
||||
s.summary = 'A Swift application toolkit for SQLite databases.'
|
||||
s.homepage = 'https://github.com/groue/GRDB.swift'
|
||||
s.author = { 'Gwendal Roué' => 'gr@pierlis.com' }
|
||||
s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" }
|
||||
s.source_files = 'GRDB/**/*.{h,m,swift}'
|
||||
s.module_name = 'GRDB'
|
||||
|
||||
s.ios.deployment_target = '8.0'
|
||||
s.osx.deployment_target = '10.9'
|
||||
s.requires_arc = true
|
||||
s.watchos.deployment_target = '2.0'
|
||||
|
||||
s.source_files = 'GRDB/**/*.swift', 'Support/*.h'
|
||||
s.module_map = 'Support/module.modulemap'
|
||||
s.framework = 'Foundation'
|
||||
s.library = 'sqlite3'
|
||||
|
||||
Regular → Executable
+5401
-592
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,109 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "560FC5191CB003810014AA8E"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipherOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "560FC55D1CB00B880014AA8E"
|
||||
BuildableName = "GRDBCipherOSXTests.xctest"
|
||||
BlueprintName = "GRDBCipherOSXTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "567156191CB16729007DC145"
|
||||
BuildableName = "GRDBCipherOSXEncryptedTests.xctest"
|
||||
BlueprintName = "GRDBCipherOSXEncryptedTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "560FC5191CB003810014AA8E"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipherOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "560FC5191CB003810014AA8E"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipherOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "560FC5191CB003810014AA8E"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipherOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -0,0 +1,109 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56AFC9EE1CB1A8BB00F48B96"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipheriOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56AFCA2B1CB1AA9900F48B96"
|
||||
BuildableName = "GRDBCipheriOSTests.xctest"
|
||||
BlueprintName = "GRDBCipheriOSTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56AFCA841CB1ABC800F48B96"
|
||||
BuildableName = "GRDBCipheriOSEncryptedTests.xctest"
|
||||
BlueprintName = "GRDBCipheriOSEncryptedTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56AFC9EE1CB1A8BB00F48B96"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipheriOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56AFC9EE1CB1A8BB00F48B96"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipheriOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56AFC9EE1CB1A8BB00F48B96"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipheriOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F3BA80591CFB2BB2003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLite.framework"
|
||||
BlueprintName = "GRDBCustomSQLiteOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F3BA809A1CFB2F6F003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLiteOSXTests.xctest"
|
||||
BlueprintName = "GRDBCustomSQLiteOSXTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F3BA80591CFB2BB2003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLite.framework"
|
||||
BlueprintName = "GRDBCustomSQLiteOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F3BA80591CFB2BB2003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLite.framework"
|
||||
BlueprintName = "GRDBCustomSQLiteOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F3BA80591CFB2BB2003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLite.framework"
|
||||
BlueprintName = "GRDBCustomSQLiteOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F3BA7FFD1CFB25E4003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLite.framework"
|
||||
BlueprintName = "GRDBCustomSQLiteiOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F3BA80401CFB2AD7003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLiteiOSTests.xctest"
|
||||
BlueprintName = "GRDBCustomSQLiteiOSTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F3BA7FFD1CFB25E4003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLite.framework"
|
||||
BlueprintName = "GRDBCustomSQLiteiOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F3BA7FFD1CFB25E4003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLite.framework"
|
||||
BlueprintName = "GRDBCustomSQLiteiOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F3BA7FFD1CFB25E4003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLite.framework"
|
||||
BlueprintName = "GRDBCustomSQLiteiOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0700"
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -29,7 +29,7 @@
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56E5D7F81B4D422D00430942"
|
||||
BuildableName = "GRDBTests.xctest"
|
||||
BuildableName = "GRDBOSXTests.xctest"
|
||||
BlueprintName = "GRDBOSXTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
@@ -48,19 +48,31 @@
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56E5D7F81B4D422D00430942"
|
||||
BuildableName = "GRDBTests.xctest"
|
||||
BuildableName = "GRDBOSXTests.xctest"
|
||||
BlueprintName = "GRDBOSXTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
<SkippedTests>
|
||||
<Test
|
||||
Identifier = "FMDBPerformanceTests">
|
||||
Identifier = "FetchedRecordsControllerTests/testEmptyFetchedRecordsAfterPerformFetch()">
|
||||
</Test>
|
||||
<Test
|
||||
Identifier = "GRDBPerformanceTests">
|
||||
Identifier = "FetchedRecordsControllerTests/testNoFetchedRecordsBeforeFetch()">
|
||||
</Test>
|
||||
<Test
|
||||
Identifier = "StephenCelisSQLitePerformanceTests">
|
||||
Identifier = "FetchedRecordsControllerTests/testNotEmptyFetchedRecordsAfterPerformFetch()">
|
||||
</Test>
|
||||
<Test
|
||||
Identifier = "FetchedRecordsControllerTests/testNotificationsOnInsertion()">
|
||||
</Test>
|
||||
<Test
|
||||
Identifier = "FetchedRecordsControllerTests/testRecordDeleted()">
|
||||
</Test>
|
||||
<Test
|
||||
Identifier = "FetchedRecordsControllerTests/testRecordInserted()">
|
||||
</Test>
|
||||
<Test
|
||||
Identifier = "FetchedRecordsControllerTests/testRecordUpdated()">
|
||||
</Test>
|
||||
</SkippedTests>
|
||||
</TestableReference>
|
||||
|
||||
+7
-5
@@ -1,24 +1,25 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0710"
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
buildConfiguration = "Release"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56553BDA1C3E906C00522B5C"
|
||||
BuildableName = "GRDBOSXCrashTests.xctest"
|
||||
BlueprintName = "GRDBOSXCrashTests"
|
||||
BlueprintIdentifier = "56439B2D1F4CA1DC0066043F"
|
||||
BuildableName = "GRDBOSXPerformanceComparisonTests.xctest"
|
||||
BlueprintName = "GRDBOSXPerformanceComparisonTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
@@ -30,6 +31,7 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0710"
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -10,6 +10,7 @@
|
||||
buildConfiguration = "Release"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
@@ -30,6 +31,7 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "5654909F1D5A4798005622CB"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBWatchOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "5654909F1D5A4798005622CB"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBWatchOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "5654909F1D5A4798005622CB"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBWatchOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0700"
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -26,14 +26,15 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
codeCoverageEnabled = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56E5D7D21B4D3FEE00430942"
|
||||
BuildableName = "GRDBTests.xctest"
|
||||
BuildableName = "GRDBiOSTests.xctest"
|
||||
BlueprintName = "GRDBiOSTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
|
||||
+5
-8
@@ -4,6 +4,9 @@
|
||||
<Group
|
||||
location = "group:Playgrounds"
|
||||
name = "Playgrounds">
|
||||
<FileRef
|
||||
location = "group:Tour.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:JSONSynchronization.playground">
|
||||
</FileRef>
|
||||
@@ -14,22 +17,16 @@
|
||||
location = "group:TransactionObserver.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:DatabaseTimestamp.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:UserDefaults.playground">
|
||||
location = "group:MyPlayground.playground">
|
||||
</FileRef>
|
||||
</Group>
|
||||
<FileRef
|
||||
location = "group:GRDB.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Tests/GRDBProfiling/GRDBProfiling.xcodeproj">
|
||||
location = "group:Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:DemoApps/GRDBDemoiOS7/GRDBDemoiOS7.xcodeproj">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
@@ -1,54 +1,80 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// Configure a DatabaseQueue
|
||||
/// Configuration for a DatabaseQueue or DatabasePool.
|
||||
public struct Configuration {
|
||||
|
||||
// MARK: - Misc options
|
||||
|
||||
/// If true, foreign key constraints are checked.
|
||||
///
|
||||
/// Default: true
|
||||
public var foreignKeysEnabled: Bool = true
|
||||
|
||||
/// If true, database modifications are disallowed.
|
||||
///
|
||||
/// Default: false
|
||||
public var readonly: Bool = false
|
||||
|
||||
/// A function that is called on every statement executed by the database.
|
||||
///
|
||||
/// Default: nil
|
||||
public var trace: TraceFunction?
|
||||
|
||||
|
||||
// MARK: - Encryption
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
/// The passphrase for encrypted database.
|
||||
///
|
||||
/// Default: nil
|
||||
public var passphrase: String?
|
||||
#endif
|
||||
|
||||
|
||||
// MARK: - Transactions
|
||||
|
||||
/// The default kind of transaction.
|
||||
public var defaultTransactionKind: TransactionKind = .Immediate
|
||||
///
|
||||
/// Default: deferred
|
||||
public var defaultTransactionKind: Database.TransactionKind = .deferred
|
||||
|
||||
|
||||
// MARK: - Concurrency
|
||||
|
||||
public var busyMode: BusyMode = .ImmediateError
|
||||
var threadingMode: ThreadingMode = .Default
|
||||
/// The behavior in case of SQLITE_BUSY error. See https://www.sqlite.org/rescode.html#busy
|
||||
///
|
||||
/// Default: immediateError
|
||||
public var busyMode: Database.BusyMode = .immediateError
|
||||
|
||||
/// The maximum number of concurrent readers (applies to database
|
||||
/// pools only).
|
||||
///
|
||||
/// Default: 5
|
||||
public var maximumReaderCount: Int = 5
|
||||
|
||||
|
||||
// MARK: - Factory Configuration
|
||||
|
||||
/// Returns a factory configuration:
|
||||
///
|
||||
/// - foreignKeysEnabled: true
|
||||
/// - readonly: false
|
||||
/// - trace: nil
|
||||
/// - defaultTransactionKind: .Immediate
|
||||
/// - transactionObserver: nil
|
||||
/// - busyMode: .ImmediateError
|
||||
/// Creates a factory configuration
|
||||
public init() { }
|
||||
|
||||
|
||||
// MARK: - SQLite flags
|
||||
// MARK: - Not Public
|
||||
|
||||
var sqliteOpenFlags: Int32 {
|
||||
return threadingMode.sqliteOpenFlags | (readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE))
|
||||
var threadingMode: Database.ThreadingMode = .`default`
|
||||
var SQLiteConnectionDidOpen: (() -> ())?
|
||||
var SQLiteConnectionWillClose: ((SQLiteConnection) -> ())?
|
||||
var SQLiteConnectionDidClose: (() -> ())?
|
||||
var SQLiteOpenFlags: Int32 {
|
||||
let readWriteFlags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE)
|
||||
return threadingMode.SQLiteOpenFlags | readWriteFlags
|
||||
}
|
||||
}
|
||||
|
||||
/// A tracing function that takes an SQL string.
|
||||
public typealias TraceFunction = (String) -> Void
|
||||
|
||||
/// A tracing function that logs SQL statements with NSLog
|
||||
public func LogSQL(sql: String) {
|
||||
NSLog("SQLite: %@", sql)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
extension Array {
|
||||
/// Creates an array containing the elements of a cursor.
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'bar'")
|
||||
/// let strings = try Array(cursor) // ["foo", "bar"]
|
||||
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
|
||||
self.init()
|
||||
while let element = try cursor.next() {
|
||||
append(element)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Set {
|
||||
/// Creates a set containing the elements of a cursor.
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'foo'")
|
||||
/// let strings = try Set(cursor) // ["foo"]
|
||||
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
|
||||
self.init()
|
||||
while let element = try cursor.next() {
|
||||
insert(element)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A type that supplies the values of some external resource, one at a time.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// The most common way to iterate over the elements of a cursor is to use a
|
||||
/// `while` loop:
|
||||
///
|
||||
/// let cursor = ...
|
||||
/// while let element = try cursor.next() {
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// ## Relationship with standard Sequence and IteratorProtocol
|
||||
///
|
||||
/// Cursors share traits with lazy sequences and iterators from the Swift
|
||||
/// standard library. Differences are:
|
||||
///
|
||||
/// - Cursor types are classes, and have a lifetime.
|
||||
/// - Cursor iteration may throw errors.
|
||||
/// - A cursor can not be repeated.
|
||||
///
|
||||
/// The protocol comes with default implementations for many operations similar
|
||||
/// to those defined by Swift's LazySequenceProtocol:
|
||||
///
|
||||
/// - `func contains(Self.Element)`
|
||||
/// - `func contains(where: (Self.Element) throws -> Bool)`
|
||||
/// - `func enumerated()`
|
||||
/// - `func filter((Self.Element) throws -> Bool)`
|
||||
/// - `func first(where: (Self.Element) throws -> Bool)`
|
||||
/// - `func flatMap<ElementOfResult>((Self.Element) throws -> ElementOfResult?)`
|
||||
/// - `func flatMap<SegmentOfResult>((Self.Element) throws -> SegmentOfResult)`
|
||||
/// - `func forEach((Self.Element) throws -> Void)`
|
||||
/// - `func joined()`
|
||||
/// - `func map<T>((Self.Element) throws -> T)`
|
||||
/// - `func reduce<Result>(Result, (Result, Self.Element) throws -> Result)`
|
||||
public protocol Cursor : class {
|
||||
/// The type of element traversed by the cursor.
|
||||
associatedtype Element
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next element
|
||||
/// exists. Once nil has been returned, all subsequent calls return nil.
|
||||
func next() throws -> Element?
|
||||
}
|
||||
|
||||
/// A type-erased cursor of Element.
|
||||
///
|
||||
/// This cursor forwards its next() method to an arbitrary underlying cursor
|
||||
/// having the same Element type, hiding the specifics of the underlying
|
||||
/// cursor.
|
||||
public class AnyCursor<Element> : Cursor {
|
||||
/// Creates a cursor that wraps a base cursor but whose type depends only on
|
||||
/// the base cursor’s element type
|
||||
public init<C: Cursor>(_ base: C) where C.Element == Element {
|
||||
element = base.next
|
||||
}
|
||||
|
||||
/// Creates a cursor that wraps the given closure in its next() method
|
||||
public init(_ body: @escaping () throws -> Element?) {
|
||||
element = body
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
public func next() throws -> Element? {
|
||||
return try element()
|
||||
}
|
||||
|
||||
private let element: () throws -> Element?
|
||||
}
|
||||
|
||||
extension Cursor {
|
||||
/// Returns a Boolean value indicating whether the cursor contains an
|
||||
/// element that satisfies the given predicate.
|
||||
///
|
||||
/// - parameter predicate: A closure that takes an element of the cursor as
|
||||
/// its argument and returns a Boolean value that indicates whether the
|
||||
/// passed element represents a match.
|
||||
/// - returns: true if the cursor contains an element that satisfies
|
||||
/// predicate; otherwise, false.
|
||||
public func contains(where predicate: (Element) throws -> Bool) throws -> Bool {
|
||||
while let element = try next() {
|
||||
if try predicate(element) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/// Returns a cursor of pairs (n, x), where n represents a consecutive
|
||||
/// integer starting at zero, and x represents an element of the cursor.
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'bar'")
|
||||
/// let c = cursor.enumerated()
|
||||
/// while let (n, x) = c.next() {
|
||||
/// print("\(n): \(x)")
|
||||
/// }
|
||||
/// // Prints: "0: foo"
|
||||
/// // Prints: "1: bar"
|
||||
public func enumerated() -> EnumeratedCursor<Self> {
|
||||
return EnumeratedCursor(self)
|
||||
}
|
||||
|
||||
/// Returns the elements of the cursor that satisfy the given predicate.
|
||||
public func filter(_ isIncluded: @escaping (Element) throws -> Bool) -> FilterCursor<Self> {
|
||||
return FilterCursor(self, isIncluded)
|
||||
}
|
||||
|
||||
/// Returns the first element of the cursor that satisfies the given
|
||||
/// predicate or nil if no such element is found.
|
||||
public func first(where predicate: (Element) throws -> Bool) throws -> Element? {
|
||||
while let element = try next() {
|
||||
if try predicate(element) {
|
||||
return element
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Returns a cursor over the concatenated non-nil results of mapping
|
||||
/// transform over this cursor.
|
||||
public func flatMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult> {
|
||||
return map(transform).filter { $0 != nil }.map { $0! }
|
||||
}
|
||||
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult: Sequence>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, IteratorCursor<SegmentOfResult.Iterator>>> {
|
||||
return flatMap { try IteratorCursor(transform($0)) }
|
||||
}
|
||||
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, SegmentOfResult>> {
|
||||
return map(transform).joined()
|
||||
}
|
||||
|
||||
/// Calls the given closure on each element in the cursor.
|
||||
public func forEach(_ body: (Element) throws -> Void) throws {
|
||||
while let element = try next() {
|
||||
try body(element)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a cursor over the results of the transform function applied to
|
||||
/// this cursor's elements.
|
||||
public func map<T>(_ transform: @escaping (Element) throws -> T) -> MapCursor<Self, T> {
|
||||
return MapCursor(self, transform)
|
||||
}
|
||||
|
||||
/// Returns the result of calling the given combining closure with each
|
||||
/// element of this sequence and an accumulating value.
|
||||
public func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) throws -> Result {
|
||||
var result = initialResult
|
||||
while let element = try next() {
|
||||
result = try nextPartialResult(result, element)
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
extension Cursor where Element: Equatable {
|
||||
/// Returns a Boolean value indicating whether the cursor contains the
|
||||
/// given element.
|
||||
public func contains(_ element: Element) throws -> Bool {
|
||||
while let e = try next() {
|
||||
if e == element {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
extension Cursor where Element: Cursor {
|
||||
/// Returns the elements of this cursor of cursors, concatenated.
|
||||
public func joined() -> FlattenCursor<Self> {
|
||||
return FlattenCursor(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension Cursor where Element: Sequence {
|
||||
/// Returns the elements of this cursor of sequences, concatenated.
|
||||
public func joined() -> FlattenCursor<MapCursor<Self, IteratorCursor<Self.Element.Iterator>>> {
|
||||
return flatMap { $0 }
|
||||
}
|
||||
}
|
||||
|
||||
/// An enumeration of the elements of a cursor.
|
||||
///
|
||||
/// To create an instance of `EnumeratedCursor`, call the `enumerated()` method
|
||||
/// on a cursor:
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'bar'")
|
||||
/// let c = cursor.enumerated()
|
||||
/// while let (n, x) = c.next() {
|
||||
/// print("\(n): \(x)")
|
||||
/// }
|
||||
/// // Prints: "0: foo"
|
||||
/// // Prints: "1: bar"
|
||||
public final class EnumeratedCursor<Base: Cursor> : Cursor {
|
||||
init(_ base: Base) {
|
||||
self.index = 0
|
||||
self.base = base
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
public func next() throws -> (Int, Base.Element)? {
|
||||
guard let element = try base.next() else { return nil }
|
||||
defer { index += 1 }
|
||||
return (index, element)
|
||||
}
|
||||
|
||||
private var index: Int
|
||||
private var base: Base
|
||||
}
|
||||
|
||||
/// A cursor whose elements consist of the elements of some base cursor that
|
||||
/// also satisfy a given predicate.
|
||||
public final class FilterCursor<Base: Cursor> : Cursor {
|
||||
init(_ base: Base, _ isIncluded: @escaping (Base.Element) throws -> Bool) {
|
||||
self.base = base
|
||||
self.isIncluded = isIncluded
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
public func next() throws -> Base.Element? {
|
||||
while let element = try base.next() {
|
||||
if try isIncluded(element) {
|
||||
return element
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private let base: Base
|
||||
private let isIncluded: (Base.Element) throws -> Bool
|
||||
}
|
||||
|
||||
/// A cursor consisting of all the elements contained in each segment contained
|
||||
/// in some Base cursor.
|
||||
///
|
||||
/// See Cursor.joined(), Cursor.flatMap(_:), Sequence.flatMap(_:)
|
||||
public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Cursor {
|
||||
init(_ base: Base) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
public func next() throws -> Base.Element.Element? {
|
||||
while true {
|
||||
if let element = try inner?.next() {
|
||||
return element
|
||||
}
|
||||
guard let inner = try base.next() else {
|
||||
return nil
|
||||
}
|
||||
self.inner = inner
|
||||
}
|
||||
}
|
||||
|
||||
private var inner: Base.Element?
|
||||
private let base: Base
|
||||
}
|
||||
|
||||
/// A Cursor whose elements consist of those in a Base Cursor passed through a
|
||||
/// transform function returning Element.
|
||||
///
|
||||
/// See Cursor.map(_:)
|
||||
public final class MapCursor<Base: Cursor, Element> : Cursor {
|
||||
init(_ base: Base, _ transform: @escaping (Base.Element) throws -> Element) {
|
||||
self.base = base
|
||||
self.transform = transform
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
public func next() throws -> Element? {
|
||||
guard let element = try base.next() else { return nil }
|
||||
return try transform(element)
|
||||
}
|
||||
|
||||
private let base: Base
|
||||
private let transform: (Base.Element) throws -> Element
|
||||
}
|
||||
|
||||
/// A Cursor whose elements are those of a sequence iterator.
|
||||
public final class IteratorCursor<Base: IteratorProtocol> : Cursor {
|
||||
|
||||
/// Creates a cursor from a sequence iterator.
|
||||
public init(_ base: Base) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
/// Creates a cursor from a sequence.
|
||||
public init<S: Sequence>(_ s: S) where S.Iterator == Base {
|
||||
self.base = s.makeIterator()
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
public func next() -> Base.Element? {
|
||||
return base.next()
|
||||
}
|
||||
|
||||
private var base: Base
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<IteratorCursor<Self.Iterator>, SegmentOfResult>> {
|
||||
return IteratorCursor(self).flatMap(transform)
|
||||
}
|
||||
}
|
||||
+2224
-646
File diff suppressed because it is too large.
Load diff
@@ -1,8 +1,195 @@
|
||||
/// DatabaseError wraps an SQLite error.
|
||||
public struct DatabaseError : ErrorType {
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible {
|
||||
public let rawValue: Int32
|
||||
|
||||
/// The SQLite error code (see https://www.sqlite.org/c3ref/c_abort.html).
|
||||
public let code: Int32
|
||||
public init(rawValue: Int32) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
/// A result code limited to the least significant 8 bits of the receiver.
|
||||
/// See https://www.sqlite.org/rescode.html for more information.
|
||||
///
|
||||
/// let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY
|
||||
/// resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true
|
||||
public var primaryResultCode: ResultCode {
|
||||
return ResultCode(rawValue: rawValue & 0xFF)
|
||||
}
|
||||
|
||||
var isPrimary: Bool {
|
||||
return self == primaryResultCode
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
// sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, iOSApplicationExtension 8.2, *) {
|
||||
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
|
||||
} else {
|
||||
return "\(rawValue)"
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
public static func == (_ lhs: ResultCode, _ rhs: ResultCode) -> Bool {
|
||||
return lhs.rawValue == rhs.rawValue
|
||||
}
|
||||
|
||||
/// Returns true if the code on the left matches the code on the right.
|
||||
///
|
||||
/// Primary result codes match themselves and their extended result codes,
|
||||
/// while extended result codes match only themselves:
|
||||
///
|
||||
/// switch error.extendedResultCode {
|
||||
/// case .SQLITE_CONSTRAINT_FOREIGNKEY: // foreign key constraint error
|
||||
/// case .SQLITE_CONSTRAINT: // any other constraint error
|
||||
/// default: // any other database error
|
||||
/// }
|
||||
public static func ~= (pattern: ResultCode, code: ResultCode) -> Bool {
|
||||
if pattern.isPrimary {
|
||||
return pattern == code.primaryResultCode
|
||||
} else {
|
||||
return pattern == code
|
||||
}
|
||||
}
|
||||
|
||||
// Primary Result codes
|
||||
// https://www.sqlite.org/rescode.html#primary_result_code_list
|
||||
|
||||
public static let SQLITE_OK = ResultCode(rawValue: 0) // Successful result
|
||||
public static let SQLITE_ERROR = ResultCode(rawValue: 1) // SQL error or missing database
|
||||
public static let SQLITE_INTERNAL = ResultCode(rawValue: 2) // Internal logic error in SQLite
|
||||
public static let SQLITE_PERM = ResultCode(rawValue: 3) // Access permission denied
|
||||
public static let SQLITE_ABORT = ResultCode(rawValue: 4) // Callback routine requested an abort
|
||||
public static let SQLITE_BUSY = ResultCode(rawValue: 5) // The database file is locked
|
||||
public static let SQLITE_LOCKED = ResultCode(rawValue: 6) // A table in the database is locked
|
||||
public static let SQLITE_NOMEM = ResultCode(rawValue: 7) // A malloc() failed
|
||||
public static let SQLITE_READONLY = ResultCode(rawValue: 8) // Attempt to write a readonly database
|
||||
public static let SQLITE_INTERRUPT = ResultCode(rawValue: 9) // Operation terminated by sqlite3_interrupt()
|
||||
public static let SQLITE_IOERR = ResultCode(rawValue: 10) // Some kind of disk I/O error occurred
|
||||
public static let SQLITE_CORRUPT = ResultCode(rawValue: 11) // The database disk image is malformed
|
||||
public static let SQLITE_NOTFOUND = ResultCode(rawValue: 12) // Unknown opcode in sqlite3_file_control()
|
||||
public static let SQLITE_FULL = ResultCode(rawValue: 13) // Insertion failed because database is full
|
||||
public static let SQLITE_CANTOPEN = ResultCode(rawValue: 14) // Unable to open the database file
|
||||
public static let SQLITE_PROTOCOL = ResultCode(rawValue: 15) // Database lock protocol error
|
||||
public static let SQLITE_EMPTY = ResultCode(rawValue: 16) // Database is empty
|
||||
public static let SQLITE_SCHEMA = ResultCode(rawValue: 17) // The database schema changed
|
||||
public static let SQLITE_TOOBIG = ResultCode(rawValue: 18) // String or BLOB exceeds size limit
|
||||
public static let SQLITE_CONSTRAINT = ResultCode(rawValue: 19) // Abort due to constraint violation
|
||||
public static let SQLITE_MISMATCH = ResultCode(rawValue: 20) // Data type mismatch
|
||||
public static let SQLITE_MISUSE = ResultCode(rawValue: 21) // Library used incorrectly
|
||||
public static let SQLITE_NOLFS = ResultCode(rawValue: 22) // Uses OS features not supported on host
|
||||
public static let SQLITE_AUTH = ResultCode(rawValue: 23) // Authorization denied
|
||||
public static let SQLITE_FORMAT = ResultCode(rawValue: 24) // Auxiliary database format error
|
||||
public static let SQLITE_RANGE = ResultCode(rawValue: 25) // 2nd parameter to sqlite3_bind out of range
|
||||
public static let SQLITE_NOTADB = ResultCode(rawValue: 26) // File opened that is not a database file
|
||||
public static let SQLITE_NOTICE = ResultCode(rawValue: 27) // Notifications from sqlite3_log()
|
||||
public static let SQLITE_WARNING = ResultCode(rawValue: 28) // Warnings from sqlite3_log()
|
||||
public static let SQLITE_ROW = ResultCode(rawValue: 100) // sqlite3_step() has another row ready
|
||||
public static let SQLITE_DONE = ResultCode(rawValue: 101) // sqlite3_step() has finished executing
|
||||
|
||||
// Extended Result Code
|
||||
// https://www.sqlite.org/rescode.html#extended_result_code_list
|
||||
|
||||
public static let SQLITE_IOERR_READ = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (1<<8)))
|
||||
public static let SQLITE_IOERR_SHORT_READ = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (2<<8)))
|
||||
public static let SQLITE_IOERR_WRITE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (3<<8)))
|
||||
public static let SQLITE_IOERR_FSYNC = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (4<<8)))
|
||||
public static let SQLITE_IOERR_DIR_FSYNC = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (5<<8)))
|
||||
public static let SQLITE_IOERR_TRUNCATE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (6<<8)))
|
||||
public static let SQLITE_IOERR_FSTAT = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (7<<8)))
|
||||
public static let SQLITE_IOERR_UNLOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (8<<8)))
|
||||
public static let SQLITE_IOERR_RDLOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (9<<8)))
|
||||
public static let SQLITE_IOERR_DELETE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (10<<8)))
|
||||
public static let SQLITE_IOERR_BLOCKED = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (11<<8)))
|
||||
public static let SQLITE_IOERR_NOMEM = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (12<<8)))
|
||||
public static let SQLITE_IOERR_ACCESS = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (13<<8)))
|
||||
public static let SQLITE_IOERR_CHECKRESERVEDLOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (14<<8)))
|
||||
public static let SQLITE_IOERR_LOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (15<<8)))
|
||||
public static let SQLITE_IOERR_CLOSE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (16<<8)))
|
||||
public static let SQLITE_IOERR_DIR_CLOSE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (17<<8)))
|
||||
public static let SQLITE_IOERR_SHMOPEN = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (18<<8)))
|
||||
public static let SQLITE_IOERR_SHMSIZE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (19<<8)))
|
||||
public static let SQLITE_IOERR_SHMLOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (20<<8)))
|
||||
public static let SQLITE_IOERR_SHMMAP = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (21<<8)))
|
||||
public static let SQLITE_IOERR_SEEK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (22<<8)))
|
||||
public static let SQLITE_IOERR_DELETE_NOENT = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (23<<8)))
|
||||
public static let SQLITE_IOERR_MMAP = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (24<<8)))
|
||||
public static let SQLITE_IOERR_GETTEMPPATH = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (25<<8)))
|
||||
public static let SQLITE_IOERR_CONVPATH = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (26<<8)))
|
||||
public static let SQLITE_IOERR_VNODE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (27<<8)))
|
||||
public static let SQLITE_IOERR_AUTH = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (28<<8)))
|
||||
public static let SQLITE_LOCKED_SHAREDCACHE = ResultCode(rawValue: (SQLITE_LOCKED.rawValue | (1<<8)))
|
||||
public static let SQLITE_BUSY_RECOVERY = ResultCode(rawValue: (SQLITE_BUSY.rawValue | (1<<8)))
|
||||
public static let SQLITE_BUSY_SNAPSHOT = ResultCode(rawValue: (SQLITE_BUSY.rawValue | (2<<8)))
|
||||
public static let SQLITE_CANTOPEN_NOTEMPDIR = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (1<<8)))
|
||||
public static let SQLITE_CANTOPEN_ISDIR = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (2<<8)))
|
||||
public static let SQLITE_CANTOPEN_FULLPATH = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (3<<8)))
|
||||
public static let SQLITE_CANTOPEN_CONVPATH = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (4<<8)))
|
||||
public static let SQLITE_CORRUPT_VTAB = ResultCode(rawValue: (SQLITE_CORRUPT.rawValue | (1<<8)))
|
||||
public static let SQLITE_READONLY_RECOVERY = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (1<<8)))
|
||||
public static let SQLITE_READONLY_CANTLOCK = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (2<<8)))
|
||||
public static let SQLITE_READONLY_ROLLBACK = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (3<<8)))
|
||||
public static let SQLITE_READONLY_DBMOVED = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (4<<8)))
|
||||
public static let SQLITE_ABORT_ROLLBACK = ResultCode(rawValue: (SQLITE_ABORT.rawValue | (2<<8)))
|
||||
public static let SQLITE_CONSTRAINT_CHECK = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (1<<8)))
|
||||
public static let SQLITE_CONSTRAINT_COMMITHOOK = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (2<<8)))
|
||||
public static let SQLITE_CONSTRAINT_FOREIGNKEY = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (3<<8)))
|
||||
public static let SQLITE_CONSTRAINT_FUNCTION = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (4<<8)))
|
||||
public static let SQLITE_CONSTRAINT_NOTNULL = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (5<<8)))
|
||||
public static let SQLITE_CONSTRAINT_PRIMARYKEY = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (6<<8)))
|
||||
public static let SQLITE_CONSTRAINT_TRIGGER = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (7<<8)))
|
||||
public static let SQLITE_CONSTRAINT_UNIQUE = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (8<<8)))
|
||||
public static let SQLITE_CONSTRAINT_VTAB = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (9<<8)))
|
||||
public static let SQLITE_CONSTRAINT_ROWID = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (10<<8)))
|
||||
public static let SQLITE_NOTICE_RECOVER_WAL = ResultCode(rawValue: (SQLITE_NOTICE.rawValue | (1<<8)))
|
||||
public static let SQLITE_NOTICE_RECOVER_ROLLBACK = ResultCode(rawValue: (SQLITE_NOTICE.rawValue | (2<<8)))
|
||||
public static let SQLITE_WARNING_AUTOINDEX = ResultCode(rawValue: (SQLITE_WARNING.rawValue | (1<<8)))
|
||||
public static let SQLITE_AUTH_USER = ResultCode(rawValue: (SQLITE_AUTH.rawValue | (1<<8)))
|
||||
public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8)))
|
||||
|
||||
}
|
||||
|
||||
/// DatabaseError wraps an SQLite error.
|
||||
public struct DatabaseError : Error {
|
||||
|
||||
/// The SQLite error code (see
|
||||
/// https://www.sqlite.org/rescode.html#primary_result_code_list).
|
||||
///
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch let error as DatabaseError where error.resultCode == .SQL_CONSTRAINT {
|
||||
/// // A constraint error
|
||||
/// }
|
||||
///
|
||||
/// This property returns a "primary result code", that is to say the least
|
||||
/// significant 8 bits of any SQLite result code. See
|
||||
/// https://www.sqlite.org/rescode.html for more information.
|
||||
///
|
||||
/// See also `extendedResultCode`.
|
||||
public var resultCode: ResultCode {
|
||||
return extendedResultCode.primaryResultCode
|
||||
}
|
||||
|
||||
/// The SQLite extended error code (see
|
||||
/// https://www.sqlite.org/rescode.html#extended_result_code_list).
|
||||
///
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch let error as DatabaseError where error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY {
|
||||
/// // A foreign key constraint error
|
||||
/// }
|
||||
///
|
||||
/// See also `resultCode`.
|
||||
public let extendedResultCode: ResultCode
|
||||
|
||||
/// The SQLite error message.
|
||||
public let message: String?
|
||||
@@ -10,13 +197,21 @@ public struct DatabaseError : ErrorType {
|
||||
/// The SQL query that yielded the error (if relevant).
|
||||
public let sql: String?
|
||||
|
||||
public init(code: Int32 = SQLITE_ERROR, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
|
||||
self.code = code
|
||||
/// Creates a Database Error
|
||||
public init(resultCode: ResultCode = .SQLITE_ERROR, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
|
||||
self.extendedResultCode = resultCode
|
||||
self.message = message
|
||||
self.sql = sql
|
||||
self.arguments = arguments
|
||||
}
|
||||
|
||||
/// Creates a Database Error with a raw Int32 result code.
|
||||
///
|
||||
/// This initializer is not public because library user is not supposed to
|
||||
/// be exposed to raw result codes.
|
||||
init(resultCode: Int32, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
|
||||
self.init(resultCode: ResultCode(rawValue: resultCode), message: message, sql: sql, arguments: arguments)
|
||||
}
|
||||
|
||||
// MARK: Not public
|
||||
|
||||
@@ -28,11 +223,11 @@ public struct DatabaseError : ErrorType {
|
||||
extension DatabaseError: CustomStringConvertible {
|
||||
/// A textual representation of `self`.
|
||||
public var description: String {
|
||||
var description = "SQLite error \(code)"
|
||||
var description = "SQLite error \(resultCode.rawValue)"
|
||||
if let sql = sql {
|
||||
description += " with statement `\(sql)`"
|
||||
}
|
||||
if let arguments = arguments where !arguments.isEmpty {
|
||||
if let arguments = arguments, !arguments.isEmpty {
|
||||
description += " arguments \(arguments)"
|
||||
}
|
||||
if let message = message {
|
||||
@@ -41,3 +236,21 @@ extension DatabaseError: CustomStringConvertible {
|
||||
return description
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseError : CustomNSError {
|
||||
|
||||
/// NSError bridging: the domain of the error.
|
||||
public static var errorDomain: String {
|
||||
return "GRDB.DatabaseError"
|
||||
}
|
||||
|
||||
/// NSError bridging: the error code within the given domain.
|
||||
public var errorCode: Int {
|
||||
return Int(extendedResultCode.rawValue)
|
||||
}
|
||||
|
||||
/// NSError bridging: the user-info dictionary.
|
||||
public var errorUserInfo: [String : Any] {
|
||||
return [NSLocalizedDescriptionKey: description]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// An SQL function or aggregate.
|
||||
public final class DatabaseFunction {
|
||||
public let name: String
|
||||
let argumentCount: Int32?
|
||||
let pure: Bool
|
||||
private let kind: Kind
|
||||
private var nArg: Int32 { return argumentCount ?? -1 }
|
||||
private var eTextRep: Int32 { return (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
|
||||
|
||||
/// Returns an SQL function.
|
||||
///
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int + 1
|
||||
/// }
|
||||
/// db.add(function: fn)
|
||||
/// try Int.fetchOne(db, "SELECT succ(1)")! // 2
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The function name.
|
||||
/// - argumentCount: The number of arguments of the function. If
|
||||
/// omitted, or nil, the function accepts any number of arguments.
|
||||
/// - pure: Whether the function is "pure", which means that its results
|
||||
/// only depends on its inputs. When a function is pure, SQLite has
|
||||
/// the opportunity to perform additional optimizations. Default value
|
||||
/// is false.
|
||||
/// - function: A function that takes an array of DatabaseValue
|
||||
/// arguments, and returns an optional DatabaseValueConvertible such
|
||||
/// as Int, String, NSDate, etc. The array is guaranteed to have
|
||||
/// exactly *argumentCount* elements, provided *argumentCount* is
|
||||
/// not nil.
|
||||
public init(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?) {
|
||||
self.name = name
|
||||
self.argumentCount = argumentCount
|
||||
self.pure = pure
|
||||
self.kind = .function{ (argc, argv) in
|
||||
let arguments = (0..<Int(argc)).map { index in
|
||||
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
|
||||
}
|
||||
return try function(arguments)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an SQL aggregate function.
|
||||
///
|
||||
/// struct MySum : DatabaseAggregate {
|
||||
/// var sum: Int = 0
|
||||
///
|
||||
/// mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
/// if let int = Int.fromDatabaseValue(dbValues[0]) {
|
||||
/// sum += int
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// func finalize() -> DatabaseValueConvertible? {
|
||||
/// return sum
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// dbQueue.add(function: fn)
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.execute("CREATE TABLE test(i)")
|
||||
/// try db.execute("INSERT INTO test(i) VALUES (1)")
|
||||
/// try db.execute("INSERT INTO test(i) VALUES (2)")
|
||||
/// try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
|
||||
/// }
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The function name.
|
||||
/// - argumentCount: The number of arguments of the aggregate. If
|
||||
/// omitted, or nil, the aggregate accepts any number of arguments.
|
||||
/// - pure: Whether the aggregate is "pure", which means that its
|
||||
/// results only depends on its inputs. When an aggregate is pure,
|
||||
/// SQLite has the opportunity to perform additional optimizations.
|
||||
/// Default value is false.
|
||||
/// - aggregate: A type that implements the DatabaseAggregate protocol.
|
||||
/// For each step of the aggregation, its `step` method is called with
|
||||
/// an array of DatabaseValue arguments. The array is guaranteed to
|
||||
/// have exactly *argumentCount* elements, provided *argumentCount* is
|
||||
/// not nil.
|
||||
public init<Aggregate: DatabaseAggregate>(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, aggregate: Aggregate.Type) {
|
||||
self.name = name
|
||||
self.argumentCount = argumentCount
|
||||
self.pure = pure
|
||||
self.kind = .aggregate { return Aggregate() }
|
||||
}
|
||||
|
||||
/// Calls sqlite3_create_function_v2
|
||||
/// See https://sqlite.org/c3ref/create_function.html
|
||||
func install(in db: Database) {
|
||||
// Retain the function definition
|
||||
let definition = kind.definition
|
||||
let definitionP = Unmanaged.passRetained(definition).toOpaque()
|
||||
|
||||
let code = sqlite3_create_function_v2(
|
||||
db.sqliteConnection,
|
||||
name,
|
||||
nArg,
|
||||
eTextRep,
|
||||
definitionP,
|
||||
kind.xFunc,
|
||||
kind.xStep,
|
||||
kind.xFinal,
|
||||
{ definitionP in
|
||||
// Release the function definition
|
||||
Unmanaged<AnyObject>.fromOpaque(definitionP!).release()
|
||||
})
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage).description)
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls sqlite3_create_function_v2
|
||||
/// See https://sqlite.org/c3ref/create_function.html
|
||||
func uninstall(in db: Database) {
|
||||
let code = sqlite3_create_function_v2(
|
||||
db.sqliteConnection,
|
||||
name,
|
||||
nArg,
|
||||
eTextRep,
|
||||
nil, nil, nil, nil, nil)
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage).description)
|
||||
}
|
||||
}
|
||||
|
||||
/// The way to compute the result of a function.
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
private class FunctionDefinition {
|
||||
let compute: (Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?
|
||||
init(compute: @escaping (Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?) {
|
||||
self.compute = compute
|
||||
}
|
||||
}
|
||||
|
||||
/// The way to start an aggregate.
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
private class AggregateDefinition {
|
||||
let makeAggregate: () -> DatabaseAggregate
|
||||
init(makeAggregate: @escaping () -> DatabaseAggregate) {
|
||||
self.makeAggregate = makeAggregate
|
||||
}
|
||||
}
|
||||
|
||||
/// The current state of an aggregate, storable in SQLite
|
||||
private class AggregateContext {
|
||||
var aggregate: DatabaseAggregate
|
||||
var hasErrored = false
|
||||
init(aggregate: DatabaseAggregate) {
|
||||
self.aggregate = aggregate
|
||||
}
|
||||
}
|
||||
|
||||
/// A function kind: an "SQL function" or an "aggregate".
|
||||
/// See http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
private enum Kind {
|
||||
/// A regular function: SELECT f(1)
|
||||
case function((Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?)
|
||||
|
||||
/// An aggregate: SELECT f(foo) FROM bar GROUP BY baz
|
||||
case aggregate(() -> DatabaseAggregate)
|
||||
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
var definition: AnyObject {
|
||||
switch self {
|
||||
case .function(let compute):
|
||||
return FunctionDefinition(compute: compute)
|
||||
case .aggregate(let makeAggregate):
|
||||
return AggregateDefinition(makeAggregate: makeAggregate)
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds the `xFunc` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
var xFunc: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
|
||||
guard case .function = self else { return nil }
|
||||
return { (sqliteContext, argc, argv) in
|
||||
let definition = Unmanaged<FunctionDefinition>.fromOpaque(sqlite3_user_data(sqliteContext)).takeUnretainedValue()
|
||||
do {
|
||||
try DatabaseFunction.report(
|
||||
result: definition.compute(argc, argv),
|
||||
in: sqliteContext)
|
||||
} catch {
|
||||
DatabaseFunction.report(error: error, in: sqliteContext)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds the `xStep` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
var xStep: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
|
||||
guard case .aggregate = self else { return nil }
|
||||
return { (sqliteContext, argc, argv) in
|
||||
let aggregateContextU = DatabaseFunction.unmanagedAggregateContext(sqliteContext)
|
||||
let aggregateContext = aggregateContextU.takeUnretainedValue()
|
||||
assert(!aggregateContext.hasErrored)
|
||||
do {
|
||||
let arguments = (0..<Int(argc)).map { index in
|
||||
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
|
||||
}
|
||||
try aggregateContext.aggregate.step(arguments)
|
||||
} catch {
|
||||
aggregateContext.hasErrored = true
|
||||
DatabaseFunction.report(error: error, in: sqliteContext)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds the `xFinal` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
var xFinal: (@convention(c) (OpaquePointer?) -> Void)? {
|
||||
guard case .aggregate = self else { return nil }
|
||||
return { (sqliteContext) in
|
||||
let aggregateContextU = DatabaseFunction.unmanagedAggregateContext(sqliteContext)
|
||||
let aggregateContext = aggregateContextU.takeUnretainedValue()
|
||||
aggregateContextU.release()
|
||||
|
||||
guard !aggregateContext.hasErrored else {
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
try DatabaseFunction.report(
|
||||
result: aggregateContext.aggregate.finalize(),
|
||||
in: sqliteContext)
|
||||
} catch {
|
||||
DatabaseFunction.report(error: error, in: sqliteContext)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper function that extracts the current state of an aggregate from an
|
||||
/// sqlite function execution context.
|
||||
///
|
||||
/// The result must be released when the aggregate concludes.
|
||||
///
|
||||
/// See https://sqlite.org/c3ref/context.html
|
||||
/// See https://sqlite.org/c3ref/aggregate_context.html
|
||||
private static func unmanagedAggregateContext(_ sqliteContext: OpaquePointer?) -> Unmanaged<AggregateContext> {
|
||||
// The current aggregate buffer
|
||||
let stride = MemoryLayout<Unmanaged<AggregateContext>>.stride
|
||||
let aggregateContextBufferP = UnsafeMutableRawBufferPointer(start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!, count: stride)
|
||||
|
||||
if aggregateContextBufferP.contains(where: { $0 != 0 }) {
|
||||
// Buffer contains non-null pointer: load aggregate context
|
||||
let aggregateContextP = aggregateContextBufferP.baseAddress!.assumingMemoryBound(to: Unmanaged<AggregateContext>.self)
|
||||
return aggregateContextP.pointee
|
||||
} else {
|
||||
// Buffer contains null pointer: create aggregate context...
|
||||
let aggregate = Unmanaged<AggregateDefinition>.fromOpaque(sqlite3_user_data(sqliteContext))
|
||||
.takeUnretainedValue()
|
||||
.makeAggregate()
|
||||
let aggregateContext = AggregateContext(aggregate: aggregate)
|
||||
|
||||
// retain and store in SQLite's buffer
|
||||
let aggregateContextU = Unmanaged.passRetained(aggregateContext)
|
||||
var aggregateContextP = aggregateContextU.toOpaque()
|
||||
withUnsafeBytes(of: &aggregateContextP) {
|
||||
aggregateContextBufferP.copyBytes(from: $0)
|
||||
}
|
||||
return aggregateContextU
|
||||
}
|
||||
}
|
||||
|
||||
private static func report(result: DatabaseValueConvertible?, in sqliteContext: OpaquePointer?) {
|
||||
switch result?.databaseValue.storage ?? .null {
|
||||
case .null:
|
||||
sqlite3_result_null(sqliteContext)
|
||||
case .int64(let int64):
|
||||
sqlite3_result_int64(sqliteContext, int64)
|
||||
case .double(let double):
|
||||
sqlite3_result_double(sqliteContext, double)
|
||||
case .string(let string):
|
||||
sqlite3_result_text(sqliteContext, string, -1, SQLITE_TRANSIENT)
|
||||
case .blob(let data):
|
||||
data.withUnsafeBytes { bytes in
|
||||
sqlite3_result_blob(sqliteContext, bytes, Int32(data.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static func report(error: Error, in sqliteContext: OpaquePointer?) {
|
||||
if let error = error as? DatabaseError {
|
||||
if let message = error.message {
|
||||
sqlite3_result_error(sqliteContext, message, -1)
|
||||
}
|
||||
sqlite3_result_error_code(sqliteContext, error.extendedResultCode.rawValue)
|
||||
} else {
|
||||
sqlite3_result_error(sqliteContext, "\(error)", -1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseFunction : Hashable {
|
||||
/// The hash value
|
||||
public var hashValue: Int {
|
||||
return name.hashValue ^ nArg.hashValue
|
||||
}
|
||||
|
||||
/// Two functions are equal if they share the same name and arity.
|
||||
public static func == (lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool {
|
||||
return lhs.name == rhs.name && lhs.nArg == rhs.nArg
|
||||
}
|
||||
}
|
||||
|
||||
/// The protocol for custom SQLite aggregates.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct MySum : DatabaseAggregate {
|
||||
/// var sum: Int = 0
|
||||
///
|
||||
/// mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
/// if let int = Int.fromDatabaseValue(dbValues[0]) {
|
||||
/// sum += int
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// func finalize() -> DatabaseValueConvertible? {
|
||||
/// return sum
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// dbQueue.add(function: fn)
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.execute("CREATE TABLE test(i)")
|
||||
/// try db.execute("INSERT INTO test(i) VALUES (1)")
|
||||
/// try db.execute("INSERT INTO test(i) VALUES (2)")
|
||||
/// try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
|
||||
/// }
|
||||
public protocol DatabaseAggregate {
|
||||
/// Creates an aggregate.
|
||||
init()
|
||||
|
||||
/// This method is called at each step of the aggregation.
|
||||
///
|
||||
/// The dbValues argument contains as many values as given to the SQL
|
||||
/// aggregate function.
|
||||
///
|
||||
/// -- One value
|
||||
/// SELECT maxLength(name) FROM players
|
||||
///
|
||||
/// -- Two values
|
||||
/// SELECT maxFullNameLength(firstName, lastName) FROM players
|
||||
///
|
||||
/// This method is never called after the finalize() method has been called.
|
||||
mutating func step(_ dbValues: [DatabaseValue]) throws
|
||||
|
||||
/// Returns the final result
|
||||
func finalize() throws -> DatabaseValueConvertible?
|
||||
}
|
||||
+524
-262
@@ -1,3 +1,13 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
#if os(iOS)
|
||||
import UIKit
|
||||
#endif
|
||||
|
||||
/// A DatabasePool grants concurrent accesses to an SQLite database.
|
||||
public final class DatabasePool {
|
||||
|
||||
@@ -14,117 +24,80 @@ public final class DatabasePool {
|
||||
/// - configuration: A configuration.
|
||||
/// - maximumReaderCount: The maximum number of readers. Default is 5.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public convenience init(path: String, configuration: Configuration = Configuration(), maximumReaderCount: Int = 5) throws {
|
||||
precondition(maximumReaderCount > 1, "maximumReaderCount must be at least 1")
|
||||
public init(path: String, configuration: Configuration = Configuration()) throws {
|
||||
GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1")
|
||||
|
||||
// Shared database schema cache
|
||||
let databaseSchemaCache = SharedDatabaseSchemaCache()
|
||||
// Writer and readers share the same database schema cache
|
||||
let sharedSchemaCache = SharedDatabaseSchemaCache()
|
||||
|
||||
// Writer
|
||||
let writer = try SerializedDatabase(
|
||||
writer = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
schemaCache: databaseSchemaCache)
|
||||
schemaCache: sharedSchemaCache)
|
||||
|
||||
// Activate WAL Mode unless readonly
|
||||
if !configuration.readonly {
|
||||
let mode = writer.inDatabase { db in
|
||||
String.fetchOne(db, "PRAGMA journal_mode=WAL")
|
||||
}
|
||||
guard mode == "wal" else {
|
||||
throw DatabaseError(message: "could not activate WAL Mode at path: \(path)")
|
||||
try writer.sync { db in
|
||||
let journalMode = try String.fetchOne(db, "PRAGMA journal_mode = WAL")
|
||||
guard journalMode == "wal" else {
|
||||
throw DatabaseError(message: "could not activate WAL Mode at path: \(path)")
|
||||
}
|
||||
|
||||
// https://www.sqlite.org/pragma.html#pragma_synchronous
|
||||
// > Many applications choose NORMAL when in WAL mode
|
||||
try db.execute("PRAGMA synchronous = NORMAL")
|
||||
|
||||
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.execute("CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY); DROP TABLE grdb_issue_102;")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.init(path: path, configuration: configuration, maximumReaderCount: maximumReaderCount, databaseSchemaCache: databaseSchemaCache, writer: writer)
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Database access
|
||||
|
||||
/// Synchronously executes a read-only block in the database, and returns
|
||||
/// its result.
|
||||
///
|
||||
/// let persons = dbPool.read { db in
|
||||
/// Person.fetchAll(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// The block is completely isolated. Eventual database updates are *not
|
||||
/// visible* inside the block:
|
||||
///
|
||||
/// dbPool.read { db in
|
||||
/// // Those two values are guaranteed to be equal, even if the `wines`
|
||||
/// // tables is modified between the two requests:
|
||||
/// let count1 = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")
|
||||
/// let count2 = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")
|
||||
/// }
|
||||
///
|
||||
/// dbPool.read { db in
|
||||
/// // Now this value may be different:
|
||||
/// let count = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")
|
||||
/// }
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func read<T>(block: (db: Database) throws -> T) rethrows -> T {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
// See DatabasePoolTests.testReadMethodIsolationOfBlock().
|
||||
return try readerPool.get { reader in
|
||||
try reader.inDatabase { db in
|
||||
var result: T? = nil
|
||||
try db.inTransaction(.Deferred) {
|
||||
result = try block(db: db)
|
||||
return .Commit
|
||||
// Readers
|
||||
readerConfig = configuration
|
||||
readerConfig.readonly = true
|
||||
readerConfig.defaultTransactionKind = .deferred // Make it the default for readers. Other transaction kinds are forbidden by SQLite in read-only connections.
|
||||
readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: { [unowned self] in
|
||||
let reader = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: self.readerConfig,
|
||||
schemaCache: sharedSchemaCache)
|
||||
|
||||
reader.sync { db in
|
||||
for function in self.functions {
|
||||
db.add(function: function)
|
||||
}
|
||||
for collation in self.collations {
|
||||
db.add(collation: collation)
|
||||
}
|
||||
return result!
|
||||
}
|
||||
}
|
||||
|
||||
return reader
|
||||
})
|
||||
}
|
||||
|
||||
/// Synchronously executes an update block in the database, and returns
|
||||
/// its result.
|
||||
///
|
||||
/// dbPool.write { db in
|
||||
/// db.execute(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func write(block: (db: Database) throws -> Void) rethrows {
|
||||
try writer.inDatabase(block)
|
||||
#if os(iOS)
|
||||
deinit {
|
||||
// Undo job done in setupMemoryManagement()
|
||||
//
|
||||
// https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error
|
||||
// Explicit unregistration is required before iOS 9 and OS X 10.11.
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Synchronously executes a block in the database, wrapped inside a
|
||||
/// transaction.
|
||||
///
|
||||
/// If the block throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown.
|
||||
///
|
||||
/// try dbPool.writeInTransaction { db in
|
||||
/// db.execute(...)
|
||||
/// return .Commit
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .Immediate. See https://www.sqlite.org/lang_transaction.html
|
||||
/// for more information.
|
||||
/// - block: A block that executes SQL statements and return either
|
||||
/// .Commit or .Rollback.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func writeInTransaction(kind: TransactionKind? = nil, _ block: (db: Database) throws -> TransactionCompletion) rethrows {
|
||||
try writer.inDatabase { db in
|
||||
try db.inTransaction(kind) {
|
||||
try block(db: db)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// The path to the database.
|
||||
public var path: String {
|
||||
return writer.path
|
||||
}
|
||||
|
||||
|
||||
@@ -137,13 +110,14 @@ public final class DatabasePool {
|
||||
/// more information.
|
||||
///
|
||||
/// - parameter kind: The checkpoint mode (default passive)
|
||||
public func checkpoint(kind: CheckpointMode = .Passive) throws {
|
||||
try writer.inDatabase { db in
|
||||
public func checkpoint(_ kind: Database.CheckpointMode = .passive) throws {
|
||||
try write { db in
|
||||
// TODO: read https://www.sqlite.org/c3ref/wal_checkpoint_v2.html and
|
||||
// check whether we need a busy handler on writer and/or readers.
|
||||
// check whether we need a busy handler on writer and/or readers
|
||||
// when kind is not .Passive.
|
||||
let code = sqlite3_wal_checkpoint_v2(db.sqliteConnection, nil, kind.rawValue, nil, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(code: code, message: db.lastErrorMessage, sql: nil)
|
||||
throw DatabaseError(resultCode: code, message: db.lastErrorMessage, sql: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -154,200 +128,488 @@ public final class DatabasePool {
|
||||
/// Free as much memory as possible.
|
||||
///
|
||||
/// This method blocks the current thread until all database accesses are completed.
|
||||
/// (TODO: test this assertion, and also that all readers connections are closed).
|
||||
///
|
||||
/// See also setupMemoryManagement(application:)
|
||||
public func releaseMemory() {
|
||||
writer.inDatabase { db in
|
||||
db.releaseMemory()
|
||||
}
|
||||
|
||||
// TODO: test that this method blocks the current thread until all database accesses are completed.
|
||||
write { $0.releaseMemory() }
|
||||
readerPool.forEach { reader in
|
||||
reader.inDatabase { db in
|
||||
db.releaseMemory()
|
||||
}
|
||||
reader.sync { $0.releaseMemory() }
|
||||
}
|
||||
|
||||
readerPool.clear()
|
||||
}
|
||||
|
||||
|
||||
#if os(iOS)
|
||||
/// Listens to UIApplicationDidEnterBackgroundNotification and
|
||||
/// UIApplicationDidReceiveMemoryWarningNotification in order to release
|
||||
/// as much memory as possible.
|
||||
///
|
||||
/// - param application: The UIApplication that will start a background
|
||||
/// task to let the database pool release its memory when the application
|
||||
/// enters background.
|
||||
public func setupMemoryManagement(in application: UIApplication) {
|
||||
self.application = application
|
||||
let center = NotificationCenter.default
|
||||
center.addObserver(self, selector: #selector(DatabasePool.applicationDidReceiveMemoryWarning(_:)), name: .UIApplicationDidReceiveMemoryWarning, object: nil)
|
||||
center.addObserver(self, selector: #selector(DatabasePool.applicationDidEnterBackground(_:)), name: .UIApplicationDidEnterBackground, object: nil)
|
||||
}
|
||||
|
||||
private var application: UIApplication!
|
||||
|
||||
@objc private func applicationDidEnterBackground(_ notification: NSNotification) {
|
||||
guard let application = application else {
|
||||
return
|
||||
}
|
||||
|
||||
var task: UIBackgroundTaskIdentifier! = nil
|
||||
task = application.beginBackgroundTask(expirationHandler: nil)
|
||||
|
||||
if task == UIBackgroundTaskInvalid {
|
||||
// Perform releaseMemory() synchronously.
|
||||
releaseMemory()
|
||||
} else {
|
||||
// Perform releaseMemory() asynchronously.
|
||||
DispatchQueue.global().async {
|
||||
self.releaseMemory()
|
||||
application.endBackgroundTask(task)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
|
||||
DispatchQueue.global().async {
|
||||
self.releaseMemory()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// MARK: - Not public
|
||||
|
||||
private let writer: SerializedDatabase
|
||||
private let readerPool: Pool<SerializedDatabase>
|
||||
private var readerConfig: Configuration
|
||||
private var readerPool: Pool<SerializedDatabase>! = nil // var and nil-initialized so that we can use `self` when creating readerPool in DatabasePool.init()
|
||||
|
||||
private var functions = Set<DatabaseFunction>()
|
||||
private var collations = Set<DatabaseCollation>()
|
||||
|
||||
private init(path: String, configuration: Configuration, maximumReaderCount: Int, databaseSchemaCache: DatabaseSchemaCacheType, writer: SerializedDatabase) {
|
||||
self.writer = writer
|
||||
self.readerPool = Pool<SerializedDatabase>(maximumCount: maximumReaderCount)
|
||||
|
||||
var readerConfig = configuration
|
||||
readerConfig.readonly = true
|
||||
readerConfig.defaultTransactionKind = .Deferred // Make it the default. Other transaction kinds are forbidden by SQLite in read-only connections.
|
||||
|
||||
readerPool.makeElement = { [unowned self] in
|
||||
let serializedDatabase = try! SerializedDatabase(
|
||||
path: path,
|
||||
configuration: readerConfig,
|
||||
schemaCache: databaseSchemaCache)
|
||||
|
||||
serializedDatabase.inDatabase { db in
|
||||
for function in self.functions {
|
||||
db.addFunction(function)
|
||||
}
|
||||
for collation in self.collations {
|
||||
db.addCollation(collation)
|
||||
}
|
||||
}
|
||||
|
||||
return serializedDatabase
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The available [checkppint modes](https://www.sqlite.org/c3ref/wal_checkpoint_v2.html).
|
||||
public enum CheckpointMode: Int32 {
|
||||
case Passive = 0 // SQLITE_CHECKPOINT_PASSIVE
|
||||
case Full = 1 // SQLITE_CHECKPOINT_FULL
|
||||
case Restart = 2 // SQLITE_CHECKPOINT_RESTART
|
||||
case Truncate = 3 // SQLITE_CHECKPOINT_TRUNCATE
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - Functions
|
||||
// MARK: - Encryption
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
///
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { databaseValues in
|
||||
/// let dbv = databaseValues.first!
|
||||
/// guard let int = dbv.value() as Int? else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int + 1
|
||||
/// }
|
||||
/// dbPool.addFunction(fn)
|
||||
/// dbPool.read { db in
|
||||
/// Int.fetchOne(db, "SELECT succ(1)") // 2
|
||||
/// }
|
||||
public func addFunction(function: DatabaseFunction) {
|
||||
functions.remove(function)
|
||||
functions.insert(function)
|
||||
#if SQLITE_HAS_CODEC
|
||||
extension DatabasePool {
|
||||
|
||||
writer.inDatabase { db in
|
||||
db.addFunction(function)
|
||||
}
|
||||
|
||||
readerPool.forEach { reader in
|
||||
reader.inDatabase { db in
|
||||
db.addFunction(function)
|
||||
}
|
||||
/// Changes the passphrase of an encrypted database
|
||||
public func change(passphrase: String) throws {
|
||||
try readerPool.clear(andThen: {
|
||||
try write { try $0.change(passphrase: passphrase) }
|
||||
readerConfig.passphrase = passphrase
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove an SQL function.
|
||||
public func removeFunction(function: DatabaseFunction) {
|
||||
functions.remove(function)
|
||||
|
||||
writer.inDatabase { db in
|
||||
db.removeFunction(function)
|
||||
}
|
||||
|
||||
readerPool.forEach { reader in
|
||||
reader.inDatabase { db in
|
||||
db.removeFunction(function)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - Collations
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
/// Add or redefine a collation.
|
||||
///
|
||||
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// dbPool.addCollation(collation)
|
||||
/// dbPool.write { db in
|
||||
/// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD")
|
||||
/// }
|
||||
public func addCollation(collation: DatabaseCollation) {
|
||||
collations.remove(collation)
|
||||
collations.insert(collation)
|
||||
|
||||
writer.inDatabase { db in
|
||||
db.addCollation(collation)
|
||||
}
|
||||
|
||||
readerPool.forEach { reader in
|
||||
reader.inDatabase { db in
|
||||
db.addCollation(collation)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a collation.
|
||||
public func removeCollation(collation: DatabaseCollation) {
|
||||
collations.remove(collation)
|
||||
|
||||
writer.inDatabase { db in
|
||||
db.removeCollation(collation)
|
||||
}
|
||||
|
||||
readerPool.forEach { reader in
|
||||
reader.inDatabase { db in
|
||||
db.removeCollation(collation)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - Transaction Observers
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
/// Add a transaction observer, so that it gets notified of all
|
||||
/// database changes.
|
||||
///
|
||||
/// Database holds weak references to its transaction observers: they are
|
||||
/// not retained, and stop getting notifications after they are deallocated.
|
||||
public func addTransactionObserver(transactionObserver: TransactionObserverType) {
|
||||
writer.inDatabase { db in
|
||||
db.addTransactionObserver(transactionObserver)
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a transaction observer.
|
||||
public func removeTransactionObserver(transactionObserver: TransactionObserverType) {
|
||||
writer.inDatabase { db in
|
||||
db.removeTransactionObserver(transactionObserver)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - DatabaseReader
|
||||
|
||||
extension DatabasePool : DatabaseReader {
|
||||
/// This method is an implementation detail: do not use it directly.
|
||||
public func _readSingleStatement<T>(block: (db: Database) throws -> T) rethrows -> T {
|
||||
|
||||
// MARK: - Read From Database
|
||||
|
||||
/// Synchronously executes a read-only block in a protected dispatch queue,
|
||||
/// and returns its result. The block is wrapped in a deferred transaction.
|
||||
///
|
||||
/// let players = try dbPool.read { db in
|
||||
/// try Player.fetchAll(...)
|
||||
/// }
|
||||
///
|
||||
/// The block is completely isolated. Eventual concurrent database updates
|
||||
/// are *not visible* inside the block:
|
||||
///
|
||||
/// try dbPool.read { db in
|
||||
/// // Those two values are guaranteed to be equal, even if the
|
||||
/// // `wines` table is modified between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// }
|
||||
///
|
||||
/// try dbPool.read { db in
|
||||
/// // Now this value may be different:
|
||||
/// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
/// happen while establishing the read access to the database.
|
||||
public func read<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
return try readerPool.get { reader in
|
||||
try reader.inDatabase { db in
|
||||
try block(db: db)
|
||||
try reader.sync { db in
|
||||
var result: T? = nil
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
// See DatabasePoolTests.testReadMethodIsolationOfBlock().
|
||||
try db.inTransaction(.deferred) {
|
||||
result = try block(db)
|
||||
return .commit
|
||||
}
|
||||
return result!
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a read-only block in a protected dispatch queue,
|
||||
/// and returns its result.
|
||||
///
|
||||
/// The block argument is not isolated: eventual concurrent database updates
|
||||
/// are visible inside the block:
|
||||
///
|
||||
/// try dbPool.unsafeRead { db in
|
||||
/// // Those two values may be different because some other thread
|
||||
/// // may have inserted or deleted a wine between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// }
|
||||
///
|
||||
/// Cursor iteration is safe, though:
|
||||
///
|
||||
/// try dbPool.unsafeRead { db in
|
||||
/// // No concurrent update can mess with this iteration:
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT ...")
|
||||
/// while let row = try rows.next() { ... }
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
/// happen while establishing the read access to the database.
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
return try readerPool.get { reader in
|
||||
try reader.sync(block)
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a read-only block in a protected dispatch queue,
|
||||
/// and returns its result.
|
||||
///
|
||||
/// The block argument is not isolated: eventual concurrent database updates
|
||||
/// are visible inside the block:
|
||||
///
|
||||
/// try dbPool.unsafeReentrantRead { db in
|
||||
/// // Those two values may be different because some other thread
|
||||
/// // may have inserted or deleted a wine between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// }
|
||||
///
|
||||
/// Cursor iteration is safe, though:
|
||||
///
|
||||
/// try dbPool.unsafeReentrantRead { db in
|
||||
/// // No concurrent update can mess with this iteration:
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT ...")
|
||||
/// while let row = try rows.next() { ... }
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
/// happen while establishing the read access to the database.
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
if let reader = currentReader {
|
||||
return try reader.reentrantSync(block)
|
||||
} else {
|
||||
return try readerPool.get { reader in
|
||||
try reader.sync(block)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a reader that can be used from the current dispatch queue,
|
||||
/// if any.
|
||||
private var currentReader: SerializedDatabase? {
|
||||
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 }
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
///
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int + 1
|
||||
/// }
|
||||
/// dbPool.add(function: fn)
|
||||
/// try dbPool.read { db in
|
||||
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
|
||||
/// }
|
||||
public func add(function: DatabaseFunction) {
|
||||
functions.update(with: function)
|
||||
write { $0.add(function: function) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.add(function: function) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove an SQL function.
|
||||
public func remove(function: DatabaseFunction) {
|
||||
functions.remove(function)
|
||||
write { $0.remove(function: function) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.remove(function: function) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// Add or redefine a collation.
|
||||
///
|
||||
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// dbPool.add(collation: collation)
|
||||
/// try dbPool.write { db in
|
||||
/// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD")
|
||||
/// }
|
||||
public func add(collation: DatabaseCollation) {
|
||||
collations.update(with: collation)
|
||||
write { $0.add(collation: collation) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.add(collation: collation) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a collation.
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
collations.remove(collation)
|
||||
write { $0.remove(collation: collation) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.remove(collation: collation) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - DatabaseWriter
|
||||
|
||||
extension DatabasePool : DatabaseWriter {
|
||||
|
||||
// MARK: - Writing in Database
|
||||
|
||||
/// Synchronously executes an update block in a protected dispatch queue,
|
||||
/// and returns its result.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// try dbPool.write { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
///
|
||||
/// To maintain database integrity, and preserve eventual concurrent reads
|
||||
/// from seeing an inconsistent database state, prefer the
|
||||
/// writeInTransaction method.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameters block: A block that executes SQL statements and return
|
||||
/// either .commit or .rollback.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.sync(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, wrapped
|
||||
/// inside a transaction.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// If the block throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If the block returns .rollback, the transaction is
|
||||
/// also rollbacked, but no error is thrown.
|
||||
///
|
||||
/// try dbPool.writeInTransaction { db in
|
||||
/// db.execute(...)
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// Eventual concurrent readers do not see partial changes:
|
||||
///
|
||||
/// dbPool.writeInTransaction { db in
|
||||
/// // Eventually preserve a zero balance
|
||||
/// try db.execute(db, "INSERT INTO credits ...", arguments: [amount])
|
||||
/// try db.execute(db, "INSERT INTO debits ...", arguments: [amount])
|
||||
/// }
|
||||
///
|
||||
/// dbPool.read { db in
|
||||
/// // Here the balance is guaranteed to be zero
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html
|
||||
/// for more information.
|
||||
/// - block: A block that executes SQL statements and return either
|
||||
/// .commit or .rollback.
|
||||
/// - throws: The error thrown by the block, or any error establishing the
|
||||
/// transaction.
|
||||
public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws {
|
||||
try write { db in
|
||||
try db.inTransaction(kind) {
|
||||
try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes an update block in a protected dispatch queue,
|
||||
/// and returns its result.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// try dbPool.unsafeReentrantWrite { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.reentrantSync(block)
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// Asynchronously executes a read-only block in a protected dispatch queue,
|
||||
/// wrapped in a deferred transaction.
|
||||
///
|
||||
/// This method must be called from the writing dispatch queue.
|
||||
///
|
||||
/// The *block* argument is guaranteed to see the database in the last
|
||||
/// committed state at the moment this method is called. Eventual concurrent
|
||||
/// database updates are *not visible* inside the block.
|
||||
///
|
||||
/// try dbPool.write { db in
|
||||
/// try db.execute("DELETE FROM players")
|
||||
/// try dbPool.readFromCurrentState { db in
|
||||
/// // Guaranteed to be zero
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
|
||||
/// }
|
||||
/// try db.execute("INSERT INTO players ...")
|
||||
/// }
|
||||
///
|
||||
/// This method blocks the current thread until the isolation guarantee has
|
||||
/// been established, and before the block argument has run.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
/// happen while establishing the read access to the database.
|
||||
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws {
|
||||
// https://www.sqlite.org/isolation.html
|
||||
//
|
||||
// > In WAL mode, SQLite exhibits "snapshot isolation". When a read
|
||||
// > transaction starts, that reader continues to see an unchanging
|
||||
// > "snapshot" of the database file as it existed at the moment in time
|
||||
// > when the read transaction started. Any write transactions that
|
||||
// > commit while the read transaction is active are still invisible to
|
||||
// > the read transaction, because the reader is seeing a snapshot of
|
||||
// > database file from a prior moment in time.
|
||||
//
|
||||
// That's exactly what we need. But what does "when read transaction
|
||||
// starts" mean?
|
||||
//
|
||||
// http://www.sqlite.org/lang_transaction.html
|
||||
//
|
||||
// > Deferred [transaction] means that no locks are acquired on the
|
||||
// > database until the database is first accessed. [...] Locks are not
|
||||
// > acquired until the first read or write operation. [...] Because the
|
||||
// > acquisition of locks is deferred until they are needed, it is
|
||||
// > possible that another thread or process could create a separate
|
||||
// > transaction and write to the database after the BEGIN on the
|
||||
// > current thread has executed.
|
||||
//
|
||||
// Now that's precise enough: SQLite defers "snapshot isolation" until
|
||||
// the first SELECT:
|
||||
//
|
||||
// Reader Writer
|
||||
// BEGIN DEFERRED TRANSACTION
|
||||
// UPDATE ... (1)
|
||||
// Here the change (1) is visible
|
||||
// SELECT ...
|
||||
// UPDATE ... (2)
|
||||
// Here the change (2) is not visible
|
||||
//
|
||||
// The readFromCurrentState method says that no change should be visible
|
||||
// at all. We thus have to perform a select that establishes the
|
||||
// snapshot isolation before we release the writer queue:
|
||||
//
|
||||
// Reader Writer
|
||||
// BEGIN DEFERRED TRANSACTION
|
||||
// SELECT anything
|
||||
// UPDATE ...
|
||||
// Here the change is not visible by GRDB user
|
||||
|
||||
// This method must be called from the writing dispatch queue:
|
||||
writer.preconditionValidQueue()
|
||||
|
||||
// The semaphore that blocks the writing dispatch queue until snapshot
|
||||
// isolation has been established:
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
|
||||
var readError: Error? = nil
|
||||
try readerPool.get { reader in
|
||||
reader.async { db in
|
||||
do {
|
||||
try db.beginTransaction(.deferred)
|
||||
assert(db.isInsideTransaction)
|
||||
try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").cursor().next()
|
||||
} catch {
|
||||
readError = error
|
||||
semaphore.signal() // Release the writer queue and rethrow error
|
||||
return
|
||||
}
|
||||
semaphore.signal() // We can release the writer queue now that we are isolated for good
|
||||
block(db)
|
||||
_ = try? db.commit() // Ignore commit error
|
||||
}
|
||||
}
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
if let readError = readError {
|
||||
// TODO: write a test for this
|
||||
throw readError
|
||||
}
|
||||
}
|
||||
}
|
||||
+281
-138
@@ -1,16 +1,12 @@
|
||||
import Foundation
|
||||
|
||||
#if os(iOS)
|
||||
import UIKit
|
||||
#endif
|
||||
|
||||
/// A DatabaseQueue serializes access to an SQLite database.
|
||||
public final class DatabaseQueue {
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// The database configuration
|
||||
public var configuration: Configuration {
|
||||
return serializedDatabase.configuration
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Initializers
|
||||
|
||||
/// Opens the SQLite database at path *path*.
|
||||
@@ -23,11 +19,11 @@ public final class DatabaseQueue {
|
||||
/// - path: The path to the database file.
|
||||
/// - configuration: A configuration.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public convenience init(path: String, configuration: Configuration = Configuration()) throws {
|
||||
try self.init(serializedDatabase: SerializedDatabase(
|
||||
public init(path: String, configuration: Configuration = Configuration()) throws {
|
||||
serializedDatabase = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
schemaCache: DatabaseSchemaCache()))
|
||||
schemaCache: SimpleDatabaseSchemaCache())
|
||||
}
|
||||
|
||||
/// Opens an in-memory SQLite database.
|
||||
@@ -37,36 +33,65 @@ public final class DatabaseQueue {
|
||||
/// Database memory is released when the database queue gets deallocated.
|
||||
///
|
||||
/// - parameter configuration: A configuration.
|
||||
public convenience init(configuration: Configuration = Configuration()) {
|
||||
try! self.init(path: ":memory:", configuration: configuration)
|
||||
public init(configuration: Configuration = Configuration()) {
|
||||
// Assume SQLite always succeeds creating an in-memory database
|
||||
serializedDatabase = try! SerializedDatabase(
|
||||
path: ":memory:",
|
||||
configuration: configuration,
|
||||
schemaCache: SimpleDatabaseSchemaCache())
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
deinit {
|
||||
// Undo job done in setupMemoryManagement()
|
||||
//
|
||||
// https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error
|
||||
// Explicit unregistration is required before iOS 9 and OS X 10.11.
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// The database configuration
|
||||
public var configuration: Configuration {
|
||||
return serializedDatabase.configuration
|
||||
}
|
||||
|
||||
/// The path to the database file; it is ":memory:" for in-memory databases.
|
||||
public var path: String {
|
||||
return serializedDatabase.path
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Database access
|
||||
|
||||
/// Synchronously executes a block in the database, and returns its result.
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// let persons = dbQueue.inDatabase { db in
|
||||
/// Person.fetchAll(...)
|
||||
/// let players = try dbQueue.inDatabase { db in
|
||||
/// try Player.fetchAll(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func inDatabase<T>(block: (db: Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.inDatabase(block)
|
||||
public func inDatabase<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.sync(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in the database, wrapped inside a
|
||||
/// transaction.
|
||||
/// Synchronously executes a block in a protected dispatch queue, wrapped
|
||||
/// inside a transaction.
|
||||
///
|
||||
/// If the block throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown.
|
||||
/// error is rethrown. If the block returns .rollback, the transaction is
|
||||
/// also rollbacked, but no error is thrown.
|
||||
///
|
||||
/// try dbQueue.inTransaction { db in
|
||||
/// db.execute(...)
|
||||
/// return .Commit
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
@@ -74,15 +99,15 @@ public final class DatabaseQueue {
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .Immediate. See https://www.sqlite.org/lang_transaction.html
|
||||
/// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html
|
||||
/// for more information.
|
||||
/// - block: A block that executes SQL statements and return either
|
||||
/// .Commit or .Rollback.
|
||||
/// .commit or .rollback.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func inTransaction(kind: TransactionKind? = nil, _ block: (db: Database) throws -> TransactionCompletion) throws {
|
||||
try serializedDatabase.inDatabase { db in
|
||||
public func inTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws {
|
||||
try inDatabase { db in
|
||||
try db.inTransaction(kind) {
|
||||
try block(db: db)
|
||||
try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -93,129 +118,93 @@ public final class DatabaseQueue {
|
||||
/// Free as much memory as possible.
|
||||
///
|
||||
/// This method blocks the current thread until all database accesses are completed.
|
||||
///
|
||||
/// See also setupMemoryManagement(application:)
|
||||
public func releaseMemory() {
|
||||
serializedDatabase.inDatabase { db in
|
||||
db.releaseMemory()
|
||||
inDatabase { $0.releaseMemory() }
|
||||
}
|
||||
|
||||
|
||||
#if os(iOS)
|
||||
/// Listens to UIApplicationDidEnterBackgroundNotification and
|
||||
/// UIApplicationDidReceiveMemoryWarningNotification in order to release
|
||||
/// as much memory as possible.
|
||||
///
|
||||
/// - param application: The UIApplication that will start a background
|
||||
/// task to let the database queue release its memory when the application
|
||||
/// enters background.
|
||||
public func setupMemoryManagement(in application: UIApplication) {
|
||||
self.application = application
|
||||
let center = NotificationCenter.default
|
||||
center.addObserver(self, selector: #selector(DatabaseQueue.applicationDidReceiveMemoryWarning(_:)), name: .UIApplicationDidReceiveMemoryWarning, object: nil)
|
||||
center.addObserver(self, selector: #selector(DatabaseQueue.applicationDidEnterBackground(_:)), name: .UIApplicationDidEnterBackground, object: nil)
|
||||
}
|
||||
|
||||
private var application: UIApplication?
|
||||
|
||||
@objc private func applicationDidEnterBackground(_ notification: NSNotification) {
|
||||
guard let application = application else {
|
||||
return
|
||||
}
|
||||
|
||||
var task: UIBackgroundTaskIdentifier! = nil
|
||||
task = application.beginBackgroundTask(expirationHandler: nil)
|
||||
|
||||
if task == UIBackgroundTaskInvalid {
|
||||
// Perform releaseMemory() synchronously.
|
||||
releaseMemory()
|
||||
} else {
|
||||
// Perform releaseMemory() asynchronously.
|
||||
DispatchQueue.global().async {
|
||||
self.releaseMemory()
|
||||
application.endBackgroundTask(task)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
|
||||
DispatchQueue.global().async {
|
||||
self.releaseMemory()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// MARK: - Not public
|
||||
|
||||
/// The serialized database
|
||||
|
||||
// https://www.sqlite.org/isolation.html
|
||||
//
|
||||
// > Within a single database connection X, a SELECT statement always
|
||||
// > sees all changes to the database that are completed prior to the
|
||||
// > start of the SELECT statement, whether committed or uncommitted.
|
||||
// > And the SELECT statement obviously does not see any changes that
|
||||
// > occur after the SELECT statement completes. But what about changes
|
||||
// > that occur while the SELECT statement is running? What if a SELECT
|
||||
// > statement is started and the sqlite3_step() interface steps through
|
||||
// > roughly half of its output, then some UPDATE statements are run by
|
||||
// > the application that modify the table that the SELECT statement is
|
||||
// > reading, then more calls to sqlite3_step() are made to finish out
|
||||
// > the SELECT statement? Will the later steps of the SELECT statement
|
||||
// > see the changes made by the UPDATE or not? The answer is that this
|
||||
// > behavior is undefined.
|
||||
//
|
||||
// This is why we use a serialized database:
|
||||
private var serializedDatabase: SerializedDatabase
|
||||
|
||||
init(serializedDatabase: SerializedDatabase) {
|
||||
// IMPLEMENTATION NOTE
|
||||
//
|
||||
// https://www.sqlite.org/isolation.html
|
||||
//
|
||||
// > Within a single database connection X, a SELECT statement always
|
||||
// > sees all changes to the database that are completed prior to the
|
||||
// > start of the SELECT statement, whether committed or uncommitted.
|
||||
// > And the SELECT statement obviously does not see any changes that
|
||||
// > occur after the SELECT statement completes. But what about changes
|
||||
// > that occur while the SELECT statement is running? What if a SELECT
|
||||
// > statement is started and the sqlite3_step() interface steps through
|
||||
// > roughly half of its output, then some UPDATE statements are run by
|
||||
// > the application that modify the table that the SELECT statement is
|
||||
// > reading, then more calls to sqlite3_step() are made to finish out
|
||||
// > the SELECT statement? Will the later steps of the SELECT statement
|
||||
// > see the changes made by the UPDATE or not? The answer is that this
|
||||
// > behavior is undefined.
|
||||
//
|
||||
// This is why we use a serialized database:
|
||||
self.serializedDatabase = serializedDatabase
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - Functions
|
||||
// MARK: - Encryption
|
||||
|
||||
extension DatabaseQueue {
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
///
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { databaseValues in
|
||||
/// let dbv = databaseValues.first!
|
||||
/// guard let int = dbv.value() as Int? else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int + 1
|
||||
/// }
|
||||
/// dbQueue.addFunction(fn)
|
||||
/// dbQueue.inDatabase { db in
|
||||
/// Int.fetchOne(db, "SELECT succ(1)") // 2
|
||||
/// }
|
||||
public func addFunction(function: DatabaseFunction) {
|
||||
serializedDatabase.inDatabase { db in
|
||||
db.addFunction(function)
|
||||
#if SQLITE_HAS_CODEC
|
||||
extension DatabaseQueue {
|
||||
|
||||
/// Changes the passphrase of an encrypted database
|
||||
public func change(passphrase: String) throws {
|
||||
try inDatabase { try $0.change(passphrase: passphrase) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove an SQL function.
|
||||
public func removeFunction(function: DatabaseFunction) {
|
||||
serializedDatabase.inDatabase { db in
|
||||
db.removeFunction(function)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - Transaction Observers
|
||||
|
||||
extension DatabaseQueue {
|
||||
|
||||
/// Add a transaction observer, so that it gets notified of all
|
||||
/// database changes.
|
||||
///
|
||||
/// Database holds weak references to its transaction observers: they are
|
||||
/// not retained, and stop getting notifications after they are deallocated.
|
||||
public func addTransactionObserver(transactionObserver: TransactionObserverType) {
|
||||
serializedDatabase.inDatabase { db in
|
||||
db.addTransactionObserver(transactionObserver)
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a transaction observer.
|
||||
public func removeTransactionObserver(transactionObserver: TransactionObserverType) {
|
||||
serializedDatabase.inDatabase { db in
|
||||
db.removeTransactionObserver(transactionObserver)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - Collations
|
||||
|
||||
extension DatabaseQueue {
|
||||
|
||||
/// Add or redefine a collation.
|
||||
///
|
||||
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// dbQueue.addCollation(collation)
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD")
|
||||
/// }
|
||||
public func addCollation(collation: DatabaseCollation) {
|
||||
serializedDatabase.inDatabase { db in
|
||||
db.addCollation(collation)
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a collation.
|
||||
public func removeCollation(collation: DatabaseCollation) {
|
||||
serializedDatabase.inDatabase { db in
|
||||
db.removeCollation(collation)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// =========================================================================
|
||||
@@ -223,9 +212,163 @@ extension DatabaseQueue {
|
||||
|
||||
extension DatabaseQueue : DatabaseReader {
|
||||
|
||||
/// This method is an implementation detail: do not use it directly.
|
||||
public func _readSingleStatement<T>(block: (db: Database) throws -> T) rethrows -> T {
|
||||
// MARK: - DatabaseReader Protocol Adoption
|
||||
|
||||
/// Synchronously executes a read-only block in a protected dispatch queue,
|
||||
/// and returns its result.
|
||||
///
|
||||
/// let players = try dbQueue.read { db in
|
||||
/// try Player.fetchAll(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// Starting iOS 8.2, OSX 10.10, and with custom SQLite builds and
|
||||
/// SQLCipher, attempts to write in the database throw a DatabaseError whose
|
||||
/// resultCode is `SQLITE_READONLY`.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
return try inDatabase { try readOnly($0, block) }
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, *) {
|
||||
return try inDatabase { try readOnly($0, block) }
|
||||
} else {
|
||||
return try inDatabase(block)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Alias for `inDatabase`. See `DatabaseReader.unsafeRead`.
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try inDatabase(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// try dbQueue.unsafeReentrantRead { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try serializedDatabase.reentrantSync(block)
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
///
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int + 1
|
||||
/// }
|
||||
/// dbQueue.add(function: fn)
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
|
||||
/// }
|
||||
public func add(function: DatabaseFunction) {
|
||||
inDatabase { $0.add(function: function) }
|
||||
}
|
||||
|
||||
/// Remove an SQL function.
|
||||
public func remove(function: DatabaseFunction) {
|
||||
inDatabase { $0.remove(function: function) }
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// Add or redefine a collation.
|
||||
///
|
||||
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// dbQueue.add(collation: collation)
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD")
|
||||
/// }
|
||||
public func add(collation: DatabaseCollation) {
|
||||
inDatabase { $0.add(collation: collation) }
|
||||
}
|
||||
|
||||
/// Remove a collation.
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
inDatabase { $0.remove(collation: collation) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - DatabaseWriter
|
||||
|
||||
extension DatabaseQueue : DatabaseWriter {
|
||||
|
||||
// MARK: - DatabaseWriter Protocol Adoption
|
||||
|
||||
/// Alias for `inDatabase`. See `DatabaseWriter.write`.
|
||||
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try inDatabase(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes *block*.
|
||||
///
|
||||
/// Starting iOS 8.2, OSX 10.10, and with custom SQLite builds and
|
||||
/// SQLCipher, attempts to write in the database throw a DatabaseError whose
|
||||
/// resultCode is `SQLITE_READONLY`.
|
||||
///
|
||||
/// This method must be called from the protected database dispatch queue.
|
||||
/// See `DatabaseWriter.readFromCurrentState`.
|
||||
public func readFromCurrentState(_ block: @escaping (Database) -> Void) {
|
||||
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
serializedDatabase.execute { readOnly($0, block) }
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, *) {
|
||||
serializedDatabase.execute { readOnly($0, block) }
|
||||
} else {
|
||||
serializedDatabase.execute(block)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// try dbQueue.unsafeReentrantWrite { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.reentrantSync(block)
|
||||
}
|
||||
}
|
||||
|
||||
// Wraps the block between two `PRAGMA query_only` statements.
|
||||
//
|
||||
// This method is unsafe because the two calls to `PRAGMA query_only` are
|
||||
// not guaranteed to be serialized (some other thread could mess with this).
|
||||
private func readOnly<T>(_ db: Database, _ block: (Database) throws -> T) rethrows -> T {
|
||||
if db.configuration.readonly {
|
||||
return try block(db)
|
||||
} else {
|
||||
try! db.execute("PRAGMA query_only = 1") // Assume can't fail
|
||||
let result = try block(db)
|
||||
try! db.execute("PRAGMA query_only = 0") // Assume can't fail
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// The protocol for all types that can fetch values from a database.
|
||||
///
|
||||
/// It is adopted by DatabaseQueue and DatabasePool.
|
||||
///
|
||||
/// The protocol comes with isolation guarantees that describe the behavior of
|
||||
/// adopting types in a multithreaded application.
|
||||
///
|
||||
/// Types that adopt the protocol can provide in practice stronger guarantees.
|
||||
/// For example, DatabaseQueue provides a stronger isolation level
|
||||
/// than DatabasePool.
|
||||
///
|
||||
/// **Warning**: Isolation guarantees stand as long as there is no external
|
||||
/// connection to the database. Should you have to cope with external
|
||||
/// connections, protect yourself with transactions, and be ready to setup a
|
||||
/// [busy handler](https://www.sqlite.org/c3ref/busy_handler.html).
|
||||
public protocol DatabaseReader : class {
|
||||
|
||||
// MARK: - Read From Database
|
||||
|
||||
/// Synchronously executes a read-only block that takes a database
|
||||
/// connection, and returns its result.
|
||||
///
|
||||
/// Guarantee 1: the block argument is isolated. Eventual concurrent
|
||||
/// database updates are not visible inside the block:
|
||||
///
|
||||
/// try reader.read { db in
|
||||
/// // Those two values are guaranteed to be equal, even if the
|
||||
/// // `wines` table is modified between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// }
|
||||
///
|
||||
/// try reader.read { db in
|
||||
/// // Now this value may be different:
|
||||
/// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// }
|
||||
///
|
||||
/// Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds
|
||||
/// and SQLCipher, attempts to write in the database throw a DatabaseError
|
||||
/// whose resultCode is `SQLITE_READONLY`.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
/// happen while establishing the read access to the database.
|
||||
func read<T>(_ block: (Database) throws -> T) throws -> T
|
||||
|
||||
/// Synchronously executes a read-only block that takes a database
|
||||
/// connection, and returns its result.
|
||||
///
|
||||
/// The two guarantees of the safe `read` method are lifted:
|
||||
///
|
||||
/// The block argument is not isolated: eventual concurrent database updates
|
||||
/// are visible inside the block:
|
||||
///
|
||||
/// try reader.unsafeRead { db in
|
||||
/// // Those two values may be different because some other thread
|
||||
/// // may have inserted or deleted a wine between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// }
|
||||
///
|
||||
/// Cursor iterations are isolated, though:
|
||||
///
|
||||
/// try reader.unsafeRead { db in
|
||||
/// // No concurrent update can mess with this iteration:
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT ...")
|
||||
/// while let row = try rows.next() { ... }
|
||||
/// }
|
||||
///
|
||||
/// The block argument is not prevented from writing (DatabaseQueue, in
|
||||
/// particular, will accept database modifications in `unsafeRead`).
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
/// happen while establishing the read access to the database.
|
||||
func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T
|
||||
|
||||
/// Synchronously executes a block that takes a database connection, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// The two guarantees of the safe `read` method are lifted:
|
||||
///
|
||||
/// The block argument is not isolated: eventual concurrent database updates
|
||||
/// are visible inside the block:
|
||||
///
|
||||
/// try reader.unsafeReentrantRead { db in
|
||||
/// // Those two values may be different because some other thread
|
||||
/// // may have inserted or deleted a wine between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// }
|
||||
///
|
||||
/// Cursor iterations are isolated, though:
|
||||
///
|
||||
/// try reader.unsafeReentrantRead { db in
|
||||
/// // No concurrent update can mess with this iteration:
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT ...")
|
||||
/// while let row = try rows.next() { ... }
|
||||
/// }
|
||||
///
|
||||
/// The block argument is not prevented from writing (DatabaseQueue, in
|
||||
/// particular, will accept database modifications in `unsafeReentrantRead`).
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
/// happen while establishing the read access to the database.
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T
|
||||
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
///
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int + 1
|
||||
/// }
|
||||
/// reader.add(function: fn)
|
||||
/// try reader.read { db in
|
||||
/// try Int.fetchOne(db, "SELECT succ(1)")! // 2
|
||||
/// }
|
||||
func add(function: DatabaseFunction)
|
||||
|
||||
/// Remove an SQL function.
|
||||
func remove(function: DatabaseFunction)
|
||||
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// Add or redefine a collation.
|
||||
///
|
||||
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// reader.add(collation: collation)
|
||||
/// try reader.execute("SELECT * FROM files ORDER BY name COLLATE localized_standard")
|
||||
func add(collation: DatabaseCollation)
|
||||
|
||||
/// Remove a collation.
|
||||
func remove(collation: DatabaseCollation)
|
||||
}
|
||||
|
||||
extension DatabaseReader {
|
||||
|
||||
// MARK: - Backup
|
||||
|
||||
/// Copies the database contents into another database.
|
||||
///
|
||||
/// The `backup` method blocks the current thread until the destination
|
||||
/// database contains the same contents as the source database.
|
||||
///
|
||||
/// When the source is a DatabasePool, concurrent writes can happen during
|
||||
/// the backup. Those writes may, or may not, be reflected in the backup,
|
||||
/// but they won't trigger any error.
|
||||
public func backup(to writer: DatabaseWriter) throws {
|
||||
try backup(to: writer, afterBackupInit: nil, afterBackupStep: nil)
|
||||
}
|
||||
|
||||
func backup(to writer: DatabaseWriter, afterBackupInit: (() -> ())?, afterBackupStep: (() -> ())?) throws {
|
||||
try read { dbFrom in
|
||||
try writer.write { dbDest in
|
||||
guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", dbFrom.sqliteConnection, "main") else {
|
||||
throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage)
|
||||
}
|
||||
guard Int(bitPattern: backup) != Int(SQLITE_ERROR) else {
|
||||
throw DatabaseError(resultCode: .SQLITE_ERROR)
|
||||
}
|
||||
|
||||
afterBackupInit?()
|
||||
|
||||
do {
|
||||
backupLoop: while true {
|
||||
switch sqlite3_backup_step(backup, -1) {
|
||||
case SQLITE_DONE:
|
||||
afterBackupStep?()
|
||||
break backupLoop
|
||||
case SQLITE_OK:
|
||||
afterBackupStep?()
|
||||
case let code:
|
||||
throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
sqlite3_backup_finish(backup)
|
||||
throw error
|
||||
}
|
||||
|
||||
switch sqlite3_backup_finish(backup) {
|
||||
case SQLITE_OK:
|
||||
break
|
||||
case let code:
|
||||
throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage)
|
||||
}
|
||||
|
||||
dbDest.clearSchemaCache()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A type-erased DatabaseReader
|
||||
///
|
||||
/// Instances of AnyDatabaseReader forward their methods to an arbitrary
|
||||
/// underlying database reader.
|
||||
public final class AnyDatabaseReader : DatabaseReader {
|
||||
private let base: DatabaseReader
|
||||
|
||||
/// Creates a database reader that wraps a base database reader.
|
||||
public init(_ base: DatabaseReader) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
public func read<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.read(block)
|
||||
}
|
||||
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeRead(block)
|
||||
}
|
||||
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeReentrantRead(block)
|
||||
}
|
||||
|
||||
public func add(function: DatabaseFunction) {
|
||||
base.add(function: function)
|
||||
}
|
||||
|
||||
public func remove(function: DatabaseFunction) {
|
||||
base.remove(function: function)
|
||||
}
|
||||
|
||||
public func add(collation: DatabaseCollation) {
|
||||
base.add(collation: collation)
|
||||
}
|
||||
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
base.remove(collation: collation)
|
||||
}
|
||||
}
|
||||
@@ -1,74 +1,109 @@
|
||||
/// An thread-unsafe database schema cache
|
||||
class DatabaseSchemaCache: DatabaseSchemaCacheType {
|
||||
private var primaryKeys: [String: PrimaryKey] = [:]
|
||||
private var updateStatements: [String: UpdateStatement] = [:]
|
||||
private var selectStatements: [String: SelectStatement] = [:]
|
||||
/// The protocol for schema cache.
|
||||
///
|
||||
/// This protocol must not contain values that are valid for a single connection
|
||||
/// only, because several connections can share the same schema cache.
|
||||
///
|
||||
/// Statements can't be cached here, for example.
|
||||
protocol DatabaseSchemaCache {
|
||||
mutating func clear()
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo?
|
||||
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String)
|
||||
|
||||
func columns(in table: String) -> [ColumnInfo]?
|
||||
mutating func set(columns: [ColumnInfo], forTable table: String)
|
||||
|
||||
func indexes(on table: String) -> [IndexInfo]?
|
||||
mutating func set(indexes: [IndexInfo], forTable table: String)
|
||||
|
||||
func foreignKeys(on table: String) -> [ForeignKeyInfo]?
|
||||
mutating func set(foreignKeys: [ForeignKeyInfo], forTable table: String)
|
||||
}
|
||||
|
||||
/// A thread-unsafe database schema cache
|
||||
final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
private var primaryKeys: [String: PrimaryKeyInfo] = [:]
|
||||
private var columns: [String: [ColumnInfo]] = [:]
|
||||
private var indexes: [String: [IndexInfo]] = [:]
|
||||
private var foreignKeys: [String: [ForeignKeyInfo]] = [:]
|
||||
|
||||
func clear() {
|
||||
primaryKeys = [:]
|
||||
|
||||
// We do clear updateStatementCache and selectStatementCache despite
|
||||
// the automatic statement recompilation (see https://www.sqlite.org/c3ref/prepare.html)
|
||||
// because the automatic statement recompilation only happens a
|
||||
// limited number of times.
|
||||
updateStatements = [:]
|
||||
selectStatements = [:]
|
||||
columns = [:]
|
||||
indexes = [:]
|
||||
foreignKeys = [:]
|
||||
}
|
||||
|
||||
func primaryKey(tableName tableName: String) -> PrimaryKey? {
|
||||
return primaryKeys[tableName]
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
|
||||
return primaryKeys[table]
|
||||
}
|
||||
|
||||
func setPrimaryKey(primaryKey: PrimaryKey, forTableName tableName: String) {
|
||||
primaryKeys[tableName] = primaryKey
|
||||
func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
|
||||
primaryKeys[table] = primaryKey
|
||||
}
|
||||
|
||||
func updateStatement(sql sql: String) -> UpdateStatement? {
|
||||
return updateStatements[sql]
|
||||
func columns(in table: String) -> [ColumnInfo]? {
|
||||
return columns[table]
|
||||
}
|
||||
|
||||
func setUpdateStatement(statement: UpdateStatement, forSQL sql: String) {
|
||||
updateStatements[sql] = statement
|
||||
func set(columns: [ColumnInfo], forTable table: String) {
|
||||
self.columns[table] = columns
|
||||
}
|
||||
|
||||
func selectStatement(sql sql: String) -> SelectStatement? {
|
||||
return selectStatements[sql]
|
||||
func indexes(on table: String) -> [IndexInfo]? {
|
||||
return indexes[table]
|
||||
}
|
||||
|
||||
func setSelectStatement(statement: SelectStatement, forSQL sql: String) {
|
||||
selectStatements[sql] = statement
|
||||
func set(indexes: [IndexInfo], forTable table: String) {
|
||||
self.indexes[table] = indexes
|
||||
}
|
||||
|
||||
func foreignKeys(on table: String) -> [ForeignKeyInfo]? {
|
||||
return foreignKeys[table]
|
||||
}
|
||||
|
||||
func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
|
||||
self.foreignKeys[table] = foreignKeys
|
||||
}
|
||||
}
|
||||
|
||||
/// A thread-safe database schema cache
|
||||
struct SharedDatabaseSchemaCache: DatabaseSchemaCacheType {
|
||||
private let cache = ReadWriteBox(DatabaseSchemaCache())
|
||||
final class SharedDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
private let cache = ReadWriteBox(SimpleDatabaseSchemaCache())
|
||||
|
||||
mutating func clear() {
|
||||
func clear() {
|
||||
cache.write { $0.clear() }
|
||||
}
|
||||
|
||||
func primaryKey(tableName tableName: String) -> PrimaryKey? {
|
||||
return cache.read { $0.primaryKey(tableName: tableName) }
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
|
||||
return cache.read { $0.primaryKey(table) }
|
||||
}
|
||||
|
||||
mutating func setPrimaryKey(primaryKey: PrimaryKey, forTableName tableName: String) {
|
||||
cache.write { $0.setPrimaryKey(primaryKey, forTableName: tableName) }
|
||||
func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
|
||||
cache.write { $0.set(primaryKey: primaryKey, forTable: table) }
|
||||
}
|
||||
|
||||
func updateStatement(sql sql: String) -> UpdateStatement? {
|
||||
return cache.read { $0.updateStatement(sql: sql) }
|
||||
func columns(in table: String) -> [ColumnInfo]? {
|
||||
return cache.read { $0.columns(in: table) }
|
||||
}
|
||||
|
||||
mutating func setUpdateStatement(statement: UpdateStatement, forSQL sql: String) {
|
||||
cache.write { $0.setUpdateStatement(statement, forSQL: sql) }
|
||||
func set(columns: [ColumnInfo], forTable table: String) {
|
||||
cache.write { $0.set(columns: columns, forTable: table) }
|
||||
}
|
||||
|
||||
func selectStatement(sql sql: String) -> SelectStatement? {
|
||||
return cache.read { $0.selectStatement(sql: sql) }
|
||||
func indexes(on table: String) -> [IndexInfo]? {
|
||||
return cache.read { $0.indexes(on: table) }
|
||||
}
|
||||
|
||||
mutating func setSelectStatement(statement: SelectStatement, forSQL sql: String) {
|
||||
cache.write { $0.setSelectStatement(statement, forSQL: sql) }
|
||||
func set(indexes: [IndexInfo], forTable table: String) {
|
||||
cache.write { $0.set(indexes: indexes, forTable: table) }
|
||||
}
|
||||
|
||||
func foreignKeys(on table: String) -> [ForeignKeyInfo]? {
|
||||
return cache.read { $0.foreignKeys(on: table) }
|
||||
}
|
||||
|
||||
func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
|
||||
cache.write { $0.set(foreignKeys: foreignKeys, forTable: table) }
|
||||
}
|
||||
}
|
||||
+265
-147
@@ -1,4 +1,9 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
// MARK: - DatabaseValue
|
||||
|
||||
@@ -8,28 +13,70 @@ import Foundation
|
||||
public struct DatabaseValue {
|
||||
|
||||
/// An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB).
|
||||
public enum Storage {
|
||||
public enum Storage : Equatable {
|
||||
/// The NULL storage class.
|
||||
case Null
|
||||
case null
|
||||
|
||||
/// The INTEGER storage class, wrapping an Int64.
|
||||
case Int64(Swift.Int64)
|
||||
case int64(Int64)
|
||||
|
||||
/// The REAL storage class, wrapping a Double.
|
||||
case Double(Swift.Double)
|
||||
case double(Double)
|
||||
|
||||
/// The TEXT storage class, wrapping a String.
|
||||
case String(Swift.String)
|
||||
case string(String)
|
||||
|
||||
/// The BLOB storage class, wrapping NSData.
|
||||
case Blob(NSData)
|
||||
/// The BLOB storage class, wrapping Data.
|
||||
case blob(Data)
|
||||
|
||||
/// Returns Int64, Double, String, Data or nil.
|
||||
public var value: DatabaseValueConvertible? {
|
||||
switch self {
|
||||
case .null:
|
||||
return nil
|
||||
case .int64(let int64):
|
||||
return int64
|
||||
case .double(let double):
|
||||
return double
|
||||
case .string(let string):
|
||||
return string
|
||||
case .blob(let data):
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
/// Return true if the storages are identical.
|
||||
///
|
||||
/// Unlike DatabaseValue equality that considers the integer 1 to be
|
||||
/// equal to the 1.0 double (as SQLite does), int64 and double storages
|
||||
/// are never equal.
|
||||
public static func == (_ lhs: Storage, _ rhs: Storage) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case (.null, .null): return true
|
||||
case (.int64(let lhs), .int64(let rhs)): return lhs == rhs
|
||||
case (.double(let lhs), .double(let rhs)): return lhs == rhs
|
||||
case (.string(let lhs), .string(let rhs)): return lhs == rhs
|
||||
case (.blob(let lhs), .blob(let rhs)): return lhs == rhs
|
||||
default: return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The SQLite storage
|
||||
public let storage: Storage
|
||||
|
||||
/// The NULL DatabaseValue.
|
||||
public static let Null = DatabaseValue(storage: .Null)
|
||||
public static let null = DatabaseValue(storage: .null)
|
||||
|
||||
/// Creates a DatabaseValue from Any.
|
||||
///
|
||||
/// The result is nil unless object adopts DatabaseValueConvertible.
|
||||
public init?(value: Any) {
|
||||
guard let convertible = value as? DatabaseValueConvertible else {
|
||||
return nil
|
||||
}
|
||||
self = convertible.databaseValue
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Extracting Value
|
||||
@@ -37,77 +84,17 @@ public struct DatabaseValue {
|
||||
/// Returns true if databaseValue is NULL.
|
||||
public var isNull: Bool {
|
||||
switch storage {
|
||||
case .Null:
|
||||
case .null:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns Int64, Double, String, NSData or nil.
|
||||
public func value() -> DatabaseValueConvertible? {
|
||||
switch storage {
|
||||
case .Null:
|
||||
return nil
|
||||
case .Int64(let int64):
|
||||
return int64
|
||||
case .Double(let double):
|
||||
return double
|
||||
case .String(let string):
|
||||
return string
|
||||
case .Blob(let data):
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the value, converted to the requested type.
|
||||
///
|
||||
/// The result is nil if the SQLite value is NULL, or if the SQLite value
|
||||
/// can not be converted to `Value`.
|
||||
///
|
||||
/// Successful conversions include:
|
||||
///
|
||||
/// - Integer and real SQLite values to Swift Int, Int32, Int64, Double and
|
||||
/// Bool (zero is the only false boolean).
|
||||
/// - Text SQLite values to Swift String.
|
||||
/// - Blob SQLite values to NSData.
|
||||
///
|
||||
/// Types that adopt DatabaseValueConvertible can provide more conversions.
|
||||
///
|
||||
/// - returns: An optional *Value*.
|
||||
public func value<Value: DatabaseValueConvertible>() -> Value? {
|
||||
return Value.fromDatabaseValue(self)
|
||||
}
|
||||
|
||||
/// Returns the value, converted to the requested type.
|
||||
///
|
||||
/// This method crashes if the SQLite value is NULL, or if the SQLite value
|
||||
/// can not be converted to `Value`.
|
||||
///
|
||||
/// Successful conversions include:
|
||||
///
|
||||
/// - Integer and real SQLite values to Swift Int, Int32, Int64, Double and
|
||||
/// Bool (zero is the only false boolean).
|
||||
/// - Text SQLite values to Swift String.
|
||||
/// - Blob SQLite values to NSData.
|
||||
///
|
||||
/// Types that adopt DatabaseValueConvertible can provide more conversions.
|
||||
///
|
||||
/// - returns: A *Value*.
|
||||
public func value<Value: DatabaseValueConvertible>() -> Value {
|
||||
guard let value = Value.fromDatabaseValue(self) as Value? else {
|
||||
fatalError("could not convert \(self) to \(Value.self).")
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Not Public
|
||||
|
||||
init(storage: Storage) {
|
||||
// This initializer is not public because Storage is not a safe type:
|
||||
// one can create a Storage of zero-length NSData, which is invalid
|
||||
// because SQLite can't store zero-length blobs.
|
||||
self.storage = storage
|
||||
}
|
||||
|
||||
@@ -115,22 +102,49 @@ public struct DatabaseValue {
|
||||
init(sqliteValue: SQLiteValue) {
|
||||
switch sqlite3_value_type(sqliteValue) {
|
||||
case SQLITE_NULL:
|
||||
storage = .Null
|
||||
storage = .null
|
||||
case SQLITE_INTEGER:
|
||||
storage = .Int64(sqlite3_value_int64(sqliteValue))
|
||||
storage = .int64(sqlite3_value_int64(sqliteValue))
|
||||
case SQLITE_FLOAT:
|
||||
storage = .Double(sqlite3_value_double(sqliteValue))
|
||||
storage = .double(sqlite3_value_double(sqliteValue))
|
||||
case SQLITE_TEXT:
|
||||
let cString = UnsafePointer<Int8>(sqlite3_value_text(sqliteValue))
|
||||
storage = .String(Swift.String.fromCString(cString)!)
|
||||
storage = .string(String(cString: sqlite3_value_text(sqliteValue)!))
|
||||
case SQLITE_BLOB:
|
||||
let bytes = sqlite3_value_blob(sqliteValue)
|
||||
let length = sqlite3_value_bytes(sqliteValue)
|
||||
storage = .Blob(NSData(bytes: bytes, length: Int(length))) // copy bytes
|
||||
if let bytes = sqlite3_value_blob(sqliteValue) {
|
||||
let count = Int(sqlite3_value_bytes(sqliteValue))
|
||||
storage = .blob(Data(bytes: bytes, count: count)) // copy bytes
|
||||
} else {
|
||||
storage = .blob(Data())
|
||||
}
|
||||
case let type:
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError("Unexpected SQLite value type: \(type)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a DatabaseValue initialized from a raw SQLite statement pointer.
|
||||
init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
switch sqlite3_column_type(sqliteStatement, Int32(index)) {
|
||||
case SQLITE_NULL:
|
||||
storage = .null
|
||||
case SQLITE_INTEGER:
|
||||
storage = .int64(sqlite3_column_int64(sqliteStatement, Int32(index)))
|
||||
case SQLITE_FLOAT:
|
||||
storage = .double(sqlite3_column_double(sqliteStatement, Int32(index)))
|
||||
case SQLITE_TEXT:
|
||||
storage = .string(String(cString: sqlite3_column_text(sqliteStatement, Int32(index))))
|
||||
case SQLITE_BLOB:
|
||||
if let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) {
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
storage = .blob(Data(bytes: bytes, count: count)) // copy bytes
|
||||
} else {
|
||||
storage = .blob(Data())
|
||||
}
|
||||
case let type:
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError("Unexpected SQLite column type: \(type)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -142,55 +156,138 @@ extension DatabaseValue : Hashable {
|
||||
/// The hash value
|
||||
public var hashValue: Int {
|
||||
switch storage {
|
||||
case .Null:
|
||||
case .null:
|
||||
return 0
|
||||
case .Int64(let int64):
|
||||
case .int64(let int64):
|
||||
// 1 == 1.0, hence 1 and 1.0 must have the same hash:
|
||||
return Double(int64).hashValue
|
||||
case .Double(let double):
|
||||
case .double(let double):
|
||||
return double.hashValue
|
||||
case .String(let string):
|
||||
case .string(let string):
|
||||
return string.hashValue
|
||||
case .Blob(let data):
|
||||
case .blob(let data):
|
||||
return data.hashValue
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether two DatabaseValues are equal.
|
||||
///
|
||||
/// 1.databaseValue == "foo".databaseValue // false
|
||||
/// 1.databaseValue == 1.databaseValue // true
|
||||
///
|
||||
/// When comparing integers and doubles, the result is true if and only
|
||||
/// values are equal, and if converting one type to the other does
|
||||
/// not lose information:
|
||||
///
|
||||
/// 1.databaseValue == 1.0.databaseValue // true
|
||||
///
|
||||
/// For a comparison that distinguishes integer and doubles, compare
|
||||
/// storages instead:
|
||||
///
|
||||
/// 1.databaseValue.storage == 1.0.databaseValue.storage // false
|
||||
public static func == (lhs: DatabaseValue, rhs: DatabaseValue) -> Bool {
|
||||
switch (lhs.storage, rhs.storage) {
|
||||
case (.null, .null):
|
||||
return true
|
||||
case (.int64(let lhs), .int64(let rhs)):
|
||||
return lhs == rhs
|
||||
case (.double(let lhs), .double(let rhs)):
|
||||
return lhs == rhs
|
||||
case (.int64(let lhs), .double(let rhs)):
|
||||
return Int64(exactly: rhs) == lhs
|
||||
case (.double(let lhs), .int64(let rhs)):
|
||||
return rhs == Int64(exactly: lhs)
|
||||
case (.string(let lhs), .string(let rhs)):
|
||||
return lhs == rhs
|
||||
case (.blob(let lhs), .blob(let rhs)):
|
||||
return lhs == rhs
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// DatabaseValue adopts Equatable.
|
||||
public func ==(lhs: DatabaseValue, rhs: DatabaseValue) -> Bool {
|
||||
switch (lhs.storage, rhs.storage) {
|
||||
case (.Null, .Null):
|
||||
return true
|
||||
case (.Int64(let lhs), .Int64(let rhs)):
|
||||
return lhs == rhs
|
||||
case (.Double(let lhs), .Double(let rhs)):
|
||||
return lhs == rhs
|
||||
case (.Int64(let lhs), .Double(let rhs)):
|
||||
return int64EqualDouble(lhs, rhs)
|
||||
case (.Double(let lhs), .Int64(let rhs)):
|
||||
return int64EqualDouble(rhs, lhs)
|
||||
case (.String(let lhs), .String(let rhs)):
|
||||
return lhs == rhs
|
||||
case (.Blob(let lhs), .Blob(let rhs)):
|
||||
return lhs == rhs
|
||||
default:
|
||||
return false
|
||||
|
||||
// MARK: - Lossless conversions
|
||||
|
||||
extension DatabaseValue {
|
||||
/// Converts the database value to the type T.
|
||||
///
|
||||
/// let dbValue = "foo".databaseValue
|
||||
/// let string = dbValue.losslessConvert() as String // "foo"
|
||||
///
|
||||
/// Conversion is successful if and only if T.fromDatabaseValue returns a
|
||||
/// non-nil value.
|
||||
///
|
||||
/// This method crashes with a fatal error when conversion fails.
|
||||
///
|
||||
/// let dbValue = "foo".databaseValue
|
||||
/// let int = dbValue.losslessConvert() as Int // fatalError
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: Optional SQL statement that enhances the eventual
|
||||
/// conversion error
|
||||
/// - arguments: Optional statement arguments that enhances the eventual
|
||||
/// conversion error
|
||||
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T where T : DatabaseValueConvertible {
|
||||
if let value = T.fromDatabaseValue(self) {
|
||||
return value
|
||||
}
|
||||
// Failed conversion: this is data loss, a programmer error.
|
||||
var error = "could not convert database value \(self) to \(T.self)"
|
||||
if let sql = sql {
|
||||
error += " with statement `\(sql)`"
|
||||
}
|
||||
if let arguments = arguments, !arguments.isEmpty {
|
||||
error += " arguments \(arguments)"
|
||||
}
|
||||
fatalError(error)
|
||||
}
|
||||
|
||||
/// Converts the database value to the type Optional<T>.
|
||||
///
|
||||
/// let dbValue = "foo".databaseValue
|
||||
/// let string = dbValue.losslessConvert() as String? // "foo"
|
||||
/// let null = DatabaseValue.null.losslessConvert() as String? // nil
|
||||
///
|
||||
/// Conversion is successful if and only if T.fromDatabaseValue returns a
|
||||
/// non-nil value.
|
||||
///
|
||||
/// This method crashes with a fatal error when conversion fails.
|
||||
///
|
||||
/// let dbValue = "foo".databaseValue
|
||||
/// let int = dbValue.losslessConvert() as Int? // fatalError
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: Optional SQL statement that enhances the eventual
|
||||
/// conversion error
|
||||
/// - arguments: Optional statement arguments that enhances the eventual
|
||||
/// conversion error
|
||||
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T? where T : DatabaseValueConvertible {
|
||||
// Use fromDatabaseValue first: this allows DatabaseValue to convert NULL to .null.
|
||||
if let value = T.fromDatabaseValue(self) {
|
||||
return value
|
||||
}
|
||||
if isNull {
|
||||
// Failed conversion from null: ok
|
||||
return nil
|
||||
} else {
|
||||
// Failed conversion from a non-null database value: this is data
|
||||
// loss, a programmer error.
|
||||
var error = "could not convert database value \(self) to \(T.self)"
|
||||
if let sql = sql {
|
||||
error += " with statement `\(sql)`"
|
||||
}
|
||||
if let arguments = arguments, !arguments.isEmpty {
|
||||
error += " arguments \(arguments)"
|
||||
}
|
||||
fatalError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if i and d hold exactly the same value, and if converting one
|
||||
/// type into the other does not lose any information.
|
||||
private func int64EqualDouble(i: Int64, _ d: Double) -> Bool {
|
||||
// See http://stackoverflow.com/questions/33719132/how-to-test-for-lossless-double-integer-conversion/33784296#33784296
|
||||
return (d >= Double(Int64.min))
|
||||
&& (d < Double(Int64.max))
|
||||
&& (round(d) == d)
|
||||
&& (i == Int64(d))
|
||||
}
|
||||
|
||||
|
||||
// MARK: - DatabaseValueConvertible
|
||||
// MARK: - DatabaseValueConvertible & SQLExpressible & SQLExpression
|
||||
|
||||
/// DatabaseValue adopts DatabaseValueConvertible.
|
||||
extension DatabaseValue : DatabaseValueConvertible {
|
||||
@@ -199,44 +296,65 @@ extension DatabaseValue : DatabaseValueConvertible {
|
||||
return self
|
||||
}
|
||||
|
||||
/// Returns *databaseValue*, or nil for NULL input.
|
||||
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> DatabaseValue? {
|
||||
// Follow protocol semantics: DatabaseValueConvertible types turn NULL
|
||||
// into nil:
|
||||
//
|
||||
// DatabaseValue.fetchOne(db, "SELECT NULL") // nil
|
||||
return databaseValue.isNull ? nil : databaseValue
|
||||
/// Returns the database value
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> DatabaseValue? {
|
||||
return dbValue
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - StatementColumnConvertible
|
||||
|
||||
extension DatabaseValue : StatementColumnConvertible {
|
||||
extension DatabaseValue : SQLExpressible {
|
||||
|
||||
/// Returns a DatabaseValue initialized from a raw SQLite statement pointer.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
switch sqlite3_column_type(sqliteStatement, Int32(index)) {
|
||||
case SQLITE_NULL:
|
||||
storage = .Null
|
||||
case SQLITE_INTEGER:
|
||||
storage = .Int64(sqlite3_column_int64(sqliteStatement, Int32(index)))
|
||||
case SQLITE_FLOAT:
|
||||
storage = .Double(sqlite3_column_double(sqliteStatement, Int32(index)))
|
||||
case SQLITE_TEXT:
|
||||
let cString = UnsafePointer<Int8>(sqlite3_column_text(sqliteStatement, Int32(index)))
|
||||
storage = .String(String.fromCString(cString)!)
|
||||
case SQLITE_BLOB:
|
||||
let bytes = sqlite3_column_blob(sqliteStatement, Int32(index))
|
||||
let length = sqlite3_column_bytes(sqliteStatement, Int32(index))
|
||||
storage = .Blob(NSData(bytes: bytes, length: Int(length))) // copy bytes
|
||||
case let type:
|
||||
fatalError("Unexpected SQLite column type: \(type)")
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public var sqlExpression: SQLExpression {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
/// DatabaseValue adopts SQLExpression.
|
||||
extension DatabaseValue : SQLExpression {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
// fast path for NULL
|
||||
if isNull {
|
||||
return "NULL"
|
||||
}
|
||||
|
||||
if arguments != nil {
|
||||
arguments!.values.append(self)
|
||||
return "?"
|
||||
} else {
|
||||
// Correctness above all: use SQLite to quote the value.
|
||||
// Assume that the Quote function always succeeds
|
||||
return DatabaseQueue().inDatabase { try! String.fetchOne($0, "SELECT QUOTE(?)", arguments: [self])! }
|
||||
}
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public var negated: SQLExpression {
|
||||
switch storage {
|
||||
case .null:
|
||||
// SELECT NOT NULL -- NULL
|
||||
return DatabaseValue.null
|
||||
case .int64(let int64):
|
||||
return (int64 == 0).sqlExpression
|
||||
case .double(let double):
|
||||
return (double == 0.0).sqlExpression
|
||||
case .string:
|
||||
// We can't assume all strings are true, and return false:
|
||||
//
|
||||
// SELECT NOT '1' -- 0 (because '1' is turned into the integer 1, which is negated into 0)
|
||||
// SELECT NOT '0' -- 1 (because '0' is turned into the integer 0, which is negated into 1)
|
||||
return SQLExpressionNot(self)
|
||||
case .blob:
|
||||
// We can't assume all blobs are true, and return false:
|
||||
//
|
||||
// SELECT NOT X'31' -- 0 (because X'31' is turned into the string '1', then into integer 1, which is negated into 0)
|
||||
// SELECT NOT X'30' -- 1 (because X'30' is turned into the string '0', then into integer 0, which is negated into 1)
|
||||
return SQLExpressionNot(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
/// DatabaseValue adopts CustomStringConvertible.
|
||||
@@ -244,15 +362,15 @@ extension DatabaseValue : CustomStringConvertible {
|
||||
/// A textual representation of `self`.
|
||||
public var description: String {
|
||||
switch storage {
|
||||
case .Null:
|
||||
case .null:
|
||||
return "NULL"
|
||||
case .Int64(let int64):
|
||||
case .int64(let int64):
|
||||
return String(int64)
|
||||
case .Double(let double):
|
||||
case .double(let double):
|
||||
return String(double)
|
||||
case .String(let string):
|
||||
case .string(let string):
|
||||
return String(reflecting: string)
|
||||
case .Blob(let data):
|
||||
case .blob(let data):
|
||||
return data.description
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,87 +1,176 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
// MARK: - DatabaseValueConvertible
|
||||
|
||||
/// Types that adopt DatabaseValueConvertible can be initialized from
|
||||
/// database values.
|
||||
///
|
||||
/// The protocol comes with built-in methods that allow to fetch sequences,
|
||||
/// The protocol comes with built-in methods that allow to fetch cursors,
|
||||
/// arrays, or single values:
|
||||
///
|
||||
/// String.fetch(db, "SELECT name FROM ...", arguments:...) // DatabaseSequence<String?>
|
||||
/// String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
|
||||
/// String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
|
||||
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
|
||||
/// try String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
|
||||
///
|
||||
/// let statement = db.selectStatement("SELECT name FROM ...")
|
||||
/// String.fetch(statement, arguments:...) // DatabaseSequence<String?>
|
||||
/// String.fetchAll(statement, arguments:...) // [String?]
|
||||
/// String.fetchOne(statement, arguments:...) // String?
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// try String.fetchCursor(statement, arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(statement, arguments:...) // [String]
|
||||
/// try String.fetchOne(statement, arguments:...) // String?
|
||||
///
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
public protocol DatabaseValueConvertible : _SQLExpressionType {
|
||||
public protocol DatabaseValueConvertible : SQLExpressible {
|
||||
/// Returns a value that can be stored in the database.
|
||||
var databaseValue: DatabaseValue { get }
|
||||
|
||||
/// Returns a value initialized from *databaseValue*, if possible.
|
||||
static func fromDatabaseValue(databaseValue: DatabaseValue) -> Self?
|
||||
/// Returns a value initialized from *dbValue*, if possible.
|
||||
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self?
|
||||
}
|
||||
|
||||
// SQLExpressible adoption
|
||||
extension DatabaseValueConvertible {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public var sqlExpression: SQLExpression {
|
||||
return databaseValue
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor of database values extracted from a single column.
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let urls: DatabaseValueCursor<URL> = try URL.fetchCursor(db, "SELECT url FROM links")
|
||||
/// while let url = urls.next() { // URL
|
||||
/// print(url)
|
||||
/// }
|
||||
/// }
|
||||
public final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
|
||||
private let statement: SelectStatement
|
||||
private let sqliteStatement: SQLiteStatement
|
||||
private let columnIndex: Int32
|
||||
private var done = false
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
// We'll read from leftmost column at index 0, unless adapter mangles columns
|
||||
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
public func next() throws -> Value? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: columnIndex)
|
||||
return dbValue.losslessConvert() as Value
|
||||
case let code:
|
||||
statement.database.selectStatementDidFail(statement)
|
||||
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor of optional database values extracted from a single column.
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let urls: NullableDatabaseValueCursor<URL> = try Optional<URL>.fetchCursor(db, "SELECT url FROM links")
|
||||
/// while let url = urls.next() { // URL?
|
||||
/// print(url)
|
||||
/// }
|
||||
/// }
|
||||
public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
|
||||
private let statement: SelectStatement
|
||||
private let sqliteStatement: SQLiteStatement
|
||||
private let columnIndex: Int32
|
||||
private var done = false
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
// We'll read from leftmost column at index 0, unless adapter mangles columns
|
||||
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
public func next() throws -> Value?? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: columnIndex)
|
||||
return dbValue.losslessConvert() as Value?
|
||||
case let code:
|
||||
statement.database.selectStatementDidFail(statement)
|
||||
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// DatabaseValueConvertible comes with built-in methods that allow to fetch
|
||||
/// sequences, arrays, or single values:
|
||||
/// cursors, arrays, or single values:
|
||||
///
|
||||
/// String.fetch(db, "SELECT name FROM ...", arguments:...) // DatabaseSequence<String>
|
||||
/// String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
|
||||
/// String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String
|
||||
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
|
||||
/// try String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
|
||||
///
|
||||
/// let statement = db.selectStatement("SELECT name FROM ...")
|
||||
/// String.fetch(statement, arguments:...) // DatabaseSequence<String>
|
||||
/// String.fetchAll(statement, arguments:...) // [String]
|
||||
/// String.fetchOne(statement, arguments:...) // String
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// try String.fetchCursor(statement, arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(statement, arguments:...) // [String]
|
||||
/// try String.fetchOne(statement, arguments:...) // String
|
||||
///
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
public extension DatabaseValueConvertible {
|
||||
extension DatabaseValueConvertible {
|
||||
|
||||
|
||||
// MARK: - Fetching From SelectStatement
|
||||
// MARK: Fetching From SelectStatement
|
||||
|
||||
/// Returns a sequence of values fetched from a prepared statement.
|
||||
/// Returns a cursor over values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = db.selectStatement("SELECT name FROM ...")
|
||||
/// let names = String.fetch(statement) // DatabaseSequence<String>
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let names = try String.fetchCursor(statement) // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// The returned sequence can be consumed several times, but it may yield
|
||||
/// different results, should database changes have occurred between two
|
||||
/// generations:
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// let names = String.fetch(statement)
|
||||
/// Array(names) // Arthur, Barbara
|
||||
/// db.execute("DELETE ...")
|
||||
/// Array(names) // Arthur
|
||||
///
|
||||
/// If the database is modified while the sequence is iterating, the
|
||||
/// remaining elements are undefined.
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - returns: A sequence.
|
||||
@warn_unused_result
|
||||
public static func fetch(statement: SelectStatement, arguments: StatementArguments? = nil) -> DatabaseSequence<Self> {
|
||||
let sqliteStatement = statement.sqliteStatement
|
||||
return statement.fetchSequence(arguments: arguments) {
|
||||
DatabaseValue(sqliteStatement: sqliteStatement, index: 0).value()
|
||||
}
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> {
|
||||
return try DatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = db.selectStatement("SELECT name FROM ...")
|
||||
/// let names = String.fetchAll(statement) // [String]
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let names = try String.fetchAll(statement) // [String]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array.
|
||||
@warn_unused_result
|
||||
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments? = nil) -> [Self] {
|
||||
return Array(fetch(statement, arguments: arguments))
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
|
||||
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from a prepared statement.
|
||||
@@ -89,65 +178,120 @@ public extension DatabaseValueConvertible {
|
||||
/// The result is nil if the query returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let statement = db.selectStatement("SELECT name FROM ...")
|
||||
/// let name = String.fetchOne(statement) // String?
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let name = try String.fetchOne(statement) // String?
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional value.
|
||||
@warn_unused_result
|
||||
public static func fetchOne(statement: SelectStatement, arguments: StatementArguments? = nil) -> Self? {
|
||||
let sequence = statement.fetchSequence(arguments: arguments) {
|
||||
fromDatabaseValue(DatabaseValue(sqliteStatement: statement.sqliteStatement, index: 0))
|
||||
}
|
||||
if let value = sequence.generate().next() {
|
||||
return value
|
||||
}
|
||||
return nil
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
|
||||
// fetchOne returns nil if there is no row, or if there is a row with a null value
|
||||
let cursor = try NullableDatabaseValueCursor<Self>(statement: statement, arguments: arguments, adapter: adapter)
|
||||
return try cursor.next() ?? nil
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching From Request
|
||||
|
||||
// MARK: - Fetching From SQL
|
||||
|
||||
/// Returns a sequence of values fetched from an SQL query.
|
||||
/// Returns a cursor over values fetched from a fetch request.
|
||||
///
|
||||
/// let names = String.fetch(db, "SELECT name FROM ...") // DatabaseSequence<String>
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try String.fetchCursor(db, request) // Cursor of String
|
||||
/// for let name = try names.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// The returned sequence can be consumed several times, but it may yield
|
||||
/// different results, should database changes have occurred between two
|
||||
/// generations:
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// let names = String.fetch(db, "SELECT name FROM ...")
|
||||
/// Array(names) // Arthur, Barbara
|
||||
/// execute("DELETE ...")
|
||||
/// Array(names) // Arthur
|
||||
///
|
||||
/// If the database is modified while the sequence is iterating, the
|
||||
/// remaining elements are undefined.
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A Database.
|
||||
/// - db: A database connection.
|
||||
/// - request: A fetch request.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseValueCursor<Self> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try String.fetchAll(db, request) // [String]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ request: Request) throws -> [Self] {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchAll(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from a fetch request.
|
||||
///
|
||||
/// The result is nil if the query returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let name = try String.fetchOne(db, request) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: Database, _ request: Request) throws -> Self? {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchOne(statement, adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching From SQL
|
||||
|
||||
/// Returns a cursor over values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try String.fetchCursor(db, "SELECT name FROM ...") // Cursor of String
|
||||
/// while let name = try name.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - returns: A sequence.
|
||||
@warn_unused_result
|
||||
public static func fetch(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> DatabaseSequence<Self> {
|
||||
return fetch(try! db.selectStatement(sql), arguments: arguments)
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> {
|
||||
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from an SQL query.
|
||||
///
|
||||
/// let names = String.fetchAll(db, "SELECT name FROM ...") // [String]
|
||||
/// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - reader: A DatabaseReader.
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array.
|
||||
@warn_unused_result
|
||||
public static func fetchAll(reader: DatabaseReader, _ sql: String, arguments: StatementArguments? = nil) -> [Self] {
|
||||
return reader._readSingleStatement { db in fetchAll(try! db.selectStatement(sql), arguments: arguments) }
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
|
||||
return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from an SQL query.
|
||||
@@ -155,119 +299,156 @@ public extension DatabaseValueConvertible {
|
||||
/// The result is nil if the query returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let name = String.fetchOne(db, "SELECT name FROM ...") // String?
|
||||
/// let name = try String.fetchOne(db, "SELECT name FROM ...") // String?
|
||||
///
|
||||
/// - parameters:
|
||||
/// - reader: A DatabaseReader.
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional value.
|
||||
@warn_unused_result
|
||||
public static func fetchOne(reader: DatabaseReader, _ sql: String, arguments: StatementArguments? = nil) -> Self? {
|
||||
return reader._readSingleStatement { db in fetchOne(try! db.selectStatement(sql), arguments: arguments) }
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
|
||||
return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Swift's Optional comes with built-in methods that allow to fetch sequences
|
||||
/// Swift's Optional comes with built-in methods that allow to fetch cursors
|
||||
/// and arrays of optional DatabaseValueConvertible:
|
||||
///
|
||||
/// Optional<String>.fetch(db, "SELECT name FROM ...", arguments:...) // DatabaseSequence<String?>
|
||||
/// Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
|
||||
/// try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
|
||||
///
|
||||
/// let statement = db.selectStatement("SELECT name FROM ...")
|
||||
/// Optional<String>.fetch(statement, arguments:...) // DatabaseSequence<String?>
|
||||
/// Optional<String>.fetchAll(statement, arguments:...) // [String?]
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// try Optional<String>.fetchCursor(statement, arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(statement, arguments:...) // [String?]
|
||||
///
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
public extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching From SelectStatement
|
||||
|
||||
// MARK: - Fetching From SelectStatement
|
||||
|
||||
/// Returns a sequence of optional values fetched from a prepared statement.
|
||||
/// Returns a cursor over optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = db.selectStatement("SELECT name FROM ...")
|
||||
/// let names = Optional<String>.fetch(statement) // DatabaseSequence<String?>
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchCursor(statement) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// The returned sequence can be consumed several times, but it may yield
|
||||
/// different results, should database changes have occurred between two
|
||||
/// generations:
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// let names = Optional<String>.fetch(statement)
|
||||
/// Array(names) // Arthur, Barbara
|
||||
/// db.execute("DELETE ...")
|
||||
/// Array(names) // Arthur
|
||||
///
|
||||
/// If the database is modified while the sequence is iterating, the
|
||||
/// remaining elements are undefined.
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - returns: A sequence of optional values.
|
||||
@warn_unused_result
|
||||
public static func fetch(statement: SelectStatement, arguments: StatementArguments? = nil) -> DatabaseSequence<Wrapped?> {
|
||||
let sqliteStatement = statement.sqliteStatement
|
||||
return statement.fetchSequence(arguments: arguments) {
|
||||
Wrapped.fromDatabaseValue(DatabaseValue(sqliteStatement: sqliteStatement, index: 0))
|
||||
}
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> {
|
||||
return try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = db.selectStatement("SELECT name FROM ...")
|
||||
/// let names = Optional<String>.fetchAll(statement) // [String?]
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchAll(statement) // [String?]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of optional values.
|
||||
@warn_unused_result
|
||||
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments? = nil) -> [Wrapped?] {
|
||||
return Array(fetch(statement, arguments: arguments))
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
|
||||
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching From Request
|
||||
|
||||
// MARK: - Fetching From SQL
|
||||
|
||||
/// Returns a sequence of optional values fetched from an SQL query.
|
||||
/// Returns a cursor over optional values fetched from a fetch request.
|
||||
///
|
||||
/// let names = Optional<String>.fetch(db, "SELECT name FROM ...") // DatabaseSequence<String?>
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try Optional<String>.fetchCursor(db, request) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// The returned sequence can be consumed several times, but it may yield
|
||||
/// different results, should database changes have occurred between two
|
||||
/// generations:
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// let names = Optional<String>.fetch(db, "SELECT name FROM ...")
|
||||
/// Array(names) // Arthur, Barbara
|
||||
/// db.execute("DELETE ...")
|
||||
/// Array(names) // Arthur
|
||||
///
|
||||
/// If the database is modified while the sequence is iterating, the
|
||||
/// remaining elements are undefined.
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - reader: A DatabaseReader.
|
||||
/// - db: A database connection.
|
||||
/// - requet: A fetch request.
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> NullableDatabaseValueCursor<Wrapped> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try Optional<String>.fetchAll(db, request) // [String?]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ request: Request) throws -> [Wrapped?] {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchAll(statement, adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching From SQL
|
||||
|
||||
/// Returns a cursor over optional values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - returns: A sequence of optional values.
|
||||
@warn_unused_result
|
||||
public static func fetch(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> DatabaseSequence<Wrapped?> {
|
||||
return fetch(try! db.selectStatement(sql), arguments: arguments)
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> {
|
||||
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from an SQL query.
|
||||
///
|
||||
/// let names = String.fetchAll(db, "SELECT name FROM ...") // [String?]
|
||||
/// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String?]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - reader: A DatabaseReader.
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - parameter arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of optional values.
|
||||
@warn_unused_result
|
||||
public static func fetchAll(reader: DatabaseReader, _ sql: String, arguments: StatementArguments? = nil) -> [Wrapped?] {
|
||||
return reader._readSingleStatement { db in fetchAll(try! db.selectStatement(sql), arguments: arguments) }
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
|
||||
return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
/// The protocol for all types that can update a database.
|
||||
///
|
||||
/// It is adopted by DatabaseQueue and DatabasePool.
|
||||
///
|
||||
/// The protocol comes with isolation guarantees that describe the behavior of
|
||||
/// adopting types in a multithreaded application.
|
||||
///
|
||||
/// Types that adopt the protocol can in practice provide stronger guarantees.
|
||||
/// For example, DatabaseQueue provides a stronger isolation level
|
||||
/// than DatabasePool.
|
||||
///
|
||||
/// **Warning**: Isolation guarantees stand as long as there is no external
|
||||
/// connection to the database. Should you have to cope with external
|
||||
/// connections, protect yourself with transactions, and be ready to setup a
|
||||
/// [busy handler](https://www.sqlite.org/c3ref/busy_handler.html).
|
||||
public protocol DatabaseWriter : DatabaseReader {
|
||||
|
||||
// MARK: - Writing in Database
|
||||
|
||||
/// Synchronously executes a block that takes a database connection, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
func write<T>(_ block: (Database) throws -> T) rethrows -> T
|
||||
|
||||
/// Synchronously executes a block that takes a database connection, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// Synchronously or asynchronously executes a read-only block that takes a
|
||||
/// database connection.
|
||||
///
|
||||
/// This method must be called from a writing dispatch queue.
|
||||
///
|
||||
/// The *block* argument is guaranteed to see the database in the state it
|
||||
/// has at the moment this method is called (see below). Eventual concurrent
|
||||
/// database updates are *not visible* inside the block.
|
||||
///
|
||||
/// What is the "current state" of the database?
|
||||
///
|
||||
/// - When this method is called outside of any transaction, the current
|
||||
/// state is the last committed state.
|
||||
///
|
||||
/// try writer.write { db in
|
||||
/// try db.execute("DELETE FROM players")
|
||||
/// try writer.readFromCurrentState { db in
|
||||
/// // Guaranteed to be zero
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
|
||||
/// }
|
||||
/// try db.execute("INSERT INTO players ...")
|
||||
/// }
|
||||
///
|
||||
/// - When this method is called inside an uncommitted transation, the
|
||||
/// current state depends on the caller:
|
||||
///
|
||||
/// DatabasePool.readFromCurrentState runs *block* asynchronously in a
|
||||
/// concurrent reader dispatch queue, and release the writing dispatch
|
||||
/// queue early, before the block has finished. In the example below,
|
||||
/// the insertion runs concurrently with the select, and the select sees
|
||||
/// the database in its last committed state.
|
||||
///
|
||||
/// try dbPool.write { db in
|
||||
/// try db.execute("DELETE FROM players")
|
||||
/// db.inTransaction {
|
||||
/// try db.execute("INSERT INTO players ...")
|
||||
/// try dbPool.readFromCurrentState { db in
|
||||
/// // Zero
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
|
||||
/// }
|
||||
/// return .commit
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// DatabaseQueue.readFromCurrentState simply runs *block* synchronously,
|
||||
/// and returns when the block has completed. In the example below, the
|
||||
/// select sees the uncommitted state of the database, and the insertion
|
||||
/// is run after the select.
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// try db.execute("DELETE FROM players")
|
||||
/// db.inTransaction {
|
||||
/// try db.execute("INSERT INTO players ...")
|
||||
/// try dbQueue.readFromCurrentState { db in
|
||||
/// // One
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
|
||||
/// }
|
||||
/// return .commit
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
func readFromCurrentState(_ block: @escaping (Database) -> Void) throws
|
||||
}
|
||||
|
||||
extension DatabaseWriter {
|
||||
|
||||
// MARK: - Transaction Observers
|
||||
|
||||
/// Add a transaction observer, so that it gets notified of
|
||||
/// database changes.
|
||||
///
|
||||
/// - parameter transactionObserver: A transaction observer.
|
||||
/// - parameter extent: The duration of the observation. The default is
|
||||
/// the observer lifetime (observation lasts until observer
|
||||
/// is deallocated).
|
||||
public func add(transactionObserver: TransactionObserver, extent: Database.TransactionObservationExtent = .observerLifetime) {
|
||||
write { $0.add(transactionObserver: transactionObserver, extent: extent) }
|
||||
}
|
||||
|
||||
/// Remove a transaction observer.
|
||||
public func remove(transactionObserver: TransactionObserver) {
|
||||
write { $0.remove(transactionObserver: transactionObserver) }
|
||||
}
|
||||
}
|
||||
|
||||
/// A type-erased DatabaseWriter
|
||||
///
|
||||
/// Instances of AnyDatabaseWriter forward their methods to an arbitrary
|
||||
/// underlying database writer.
|
||||
public final class AnyDatabaseWriter : DatabaseWriter {
|
||||
private let base: DatabaseWriter
|
||||
|
||||
/// Creates a database writer that wraps a base database writer.
|
||||
public init(_ base: DatabaseWriter) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
public func read<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.read(block)
|
||||
}
|
||||
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeRead(block)
|
||||
}
|
||||
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeReentrantRead(block)
|
||||
}
|
||||
|
||||
public func add(function: DatabaseFunction) {
|
||||
base.add(function: function)
|
||||
}
|
||||
|
||||
public func remove(function: DatabaseFunction) {
|
||||
base.remove(function: function)
|
||||
}
|
||||
|
||||
public func add(collation: DatabaseCollation) {
|
||||
base.add(collation: collation)
|
||||
}
|
||||
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
base.remove(collation: collation)
|
||||
}
|
||||
|
||||
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try base.write(block)
|
||||
}
|
||||
|
||||
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try base.unsafeReentrantWrite(block)
|
||||
}
|
||||
|
||||
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws {
|
||||
try base.readFromCurrentState(block)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,556 @@
|
||||
/// The protocol for all types that define a way to fetch database rows.
|
||||
///
|
||||
/// Requests can feed the fetching methods of any fetchable type (Row,
|
||||
/// value, record):
|
||||
///
|
||||
/// let request: Request = ...
|
||||
/// try Row.fetchCursor(db, request) // RowCursor
|
||||
/// try String.fetchAll(db, request) // [String]
|
||||
/// try Player.fetchOne(db, request) // Player?
|
||||
public protocol Request {
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
|
||||
|
||||
/// The number of rows fetched by the request.
|
||||
///
|
||||
/// Default implementation builds a naive SQL query based on the statement
|
||||
/// returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`.
|
||||
///
|
||||
/// Adopting types can refine this countRequest method and return more
|
||||
/// efficient SQL.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
func fetchCount(_ db: Database) throws -> Int
|
||||
}
|
||||
|
||||
extension Request {
|
||||
/// The number of rows fetched by the request.
|
||||
///
|
||||
/// This default implementation builds a naive SQL query based on the
|
||||
/// statement returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
let (statement, _) = try prepare(db)
|
||||
let sql = "SELECT COUNT(*) FROM (\(statement.sql))"
|
||||
return try Int.fetchOne(db, sql, arguments: statement.arguments)!
|
||||
}
|
||||
}
|
||||
|
||||
extension Request {
|
||||
/// Returns a request bound to type T.
|
||||
///
|
||||
/// The returned request can fetch if the type T is fetchable (Row,
|
||||
/// value, record).
|
||||
///
|
||||
/// // Int?
|
||||
/// let maxScore = Player
|
||||
/// .select(max(scoreColumn))
|
||||
/// .asRequest(of: Int.self) // <--
|
||||
/// .fetchOne(db)
|
||||
///
|
||||
/// - parameter type: The fetched type T
|
||||
/// - returns: A typed request bound to type T.
|
||||
public func asRequest<T>(of type: T.Type) -> AnyTypedRequest<T> {
|
||||
return AnyTypedRequest { try self.prepare($0) }
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns an adapted request.
|
||||
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedRequest<Self> {
|
||||
return AdaptedRequest(self, adapter)
|
||||
}
|
||||
}
|
||||
|
||||
/// An adapted request.
|
||||
public struct AdaptedRequest<Base: Request> : Request {
|
||||
/// Creates an adapted request from a base request and a closure that builds
|
||||
/// a row adapter from a database connection.
|
||||
init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) {
|
||||
self.base = base
|
||||
self.adapter = adapter
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
let (statement, baseAdapter) = try base.prepare(db)
|
||||
if let baseAdapter = baseAdapter {
|
||||
return try (statement, ChainedAdapter(first: baseAdapter, second: adapter(db)))
|
||||
} else {
|
||||
return try (statement, adapter(db))
|
||||
}
|
||||
}
|
||||
|
||||
/// The number of rows fetched by the request.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try base.fetchCount(db)
|
||||
}
|
||||
|
||||
private let base: Base
|
||||
private let adapter: (Database) throws -> RowAdapter
|
||||
}
|
||||
|
||||
/// A type-erased Request.
|
||||
///
|
||||
/// An instance of AnyRequest forwards its operations to an underlying request,
|
||||
/// hiding its specifics.
|
||||
public struct AnyRequest : Request {
|
||||
/// Creates a new request that wraps and forwards operations to `request`.
|
||||
public init(_ request: Request) {
|
||||
self._prepare = { try request.prepare($0) }
|
||||
}
|
||||
|
||||
/// Creates a new request whose `prepare()` method wraps and forwards
|
||||
/// operations the argument closure.
|
||||
public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) {
|
||||
_prepare = prepare
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try _prepare(db)
|
||||
}
|
||||
|
||||
private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?)
|
||||
}
|
||||
|
||||
/// A Request built from raw SQL.
|
||||
public struct SQLRequest : Request {
|
||||
/// Creates a new request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
///
|
||||
/// let request = SQLRequest("SELECT * FROM players")
|
||||
/// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: A SQLRequest
|
||||
public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) {
|
||||
self.init(sql, arguments: arguments, adapter: adapter, fromCache: cached ? .user : nil)
|
||||
}
|
||||
|
||||
/// Creates a new request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
///
|
||||
/// let request = SQLRequest("SELECT * FROM players")
|
||||
/// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - statementCacheName: Optional statement cache name.
|
||||
/// - returns: A SQLRequest
|
||||
init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache statementCacheName: Database.StatementCacheName?) {
|
||||
self.sql = sql
|
||||
self.arguments = arguments
|
||||
self.adapter = adapter
|
||||
self.statementCacheName = statementCacheName
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
let statement: SelectStatement
|
||||
if let statementCacheName = statementCacheName {
|
||||
statement = try db.selectStatement(sql, fromCache: statementCacheName)
|
||||
} else {
|
||||
statement = try db.makeSelectStatement(sql)
|
||||
}
|
||||
if let arguments = arguments {
|
||||
try statement.setArgumentsWithValidation(arguments)
|
||||
}
|
||||
return (statement, adapter)
|
||||
}
|
||||
|
||||
private let sql: String
|
||||
private let arguments: StatementArguments?
|
||||
private let adapter: RowAdapter?
|
||||
private let statementCacheName: Database.StatementCacheName?
|
||||
}
|
||||
|
||||
/// The protocol for requests that know how to decode database rows.
|
||||
///
|
||||
/// Typed requests can fetch if their associated type RowDecoder is able to
|
||||
/// decode rows (Row, value, record)
|
||||
///
|
||||
/// struct Player: RowConvertible { ... }
|
||||
/// let request: ... // Some TypedRequest that fetches Player
|
||||
/// try request.fetchCursor(db) // Cursor of Player
|
||||
/// try request.fetchAll(db) // [Player]
|
||||
/// try request.fetchOne(db) // Player?
|
||||
public protocol TypedRequest : Request {
|
||||
|
||||
/// The type that can convert raw database rows to fetched values
|
||||
associatedtype RowDecoder
|
||||
}
|
||||
|
||||
extension TypedRequest {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns an adapted typed request.
|
||||
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedTypedRequest<Self> {
|
||||
return AdaptedTypedRequest(self, adapter)
|
||||
}
|
||||
}
|
||||
|
||||
/// An adapted typed request.
|
||||
public struct AdaptedTypedRequest<Base: TypedRequest> : TypedRequest {
|
||||
|
||||
/// The type that can convert raw database rows to fetched values
|
||||
public typealias RowDecoder = Base.RowDecoder
|
||||
|
||||
/// Creates an adapted request from a base request and a closure that builds
|
||||
/// a row adapter from a database connection.
|
||||
init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) {
|
||||
adaptedRequest = AdaptedRequest(base, adapter)
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try adaptedRequest.prepare(db)
|
||||
}
|
||||
|
||||
/// The number of rows fetched by the request.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try adaptedRequest.fetchCount(db)
|
||||
}
|
||||
|
||||
private let adaptedRequest: AdaptedRequest<Base>
|
||||
}
|
||||
|
||||
/// A type-erased TypedRequest.
|
||||
///
|
||||
/// An instance of AnyTypedRequest forwards its operations to an underlying
|
||||
/// typed request, hiding its specifics.
|
||||
public struct AnyTypedRequest<T> : TypedRequest {
|
||||
/// The type that can convert raw database rows to fetched values
|
||||
public typealias RowDecoder = T
|
||||
|
||||
/// Creates a new request that wraps and forwards operations to `request`.
|
||||
public init<Request>(_ request: Request) where Request: TypedRequest, Request.RowDecoder == RowDecoder {
|
||||
self._prepare = { try request.prepare($0) }
|
||||
}
|
||||
|
||||
/// Creates a new request whose `prepare()` method wraps and forwards
|
||||
/// operations the argument closure.
|
||||
public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) {
|
||||
_prepare = prepare
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try _prepare(db)
|
||||
}
|
||||
|
||||
private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?)
|
||||
}
|
||||
|
||||
extension TypedRequest where RowDecoder: RowConvertible {
|
||||
|
||||
// MARK: Fetching Record and RowConvertible
|
||||
|
||||
/// A cursor over fetched records.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Player
|
||||
/// let players = try request.fetchCursor(db) // Cursor of Player
|
||||
/// while let player = try players.next() { // Player
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> RecordCursor<RowDecoder> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched records.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Player
|
||||
/// let players = try request.fetchAll(db) // [Player]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
return try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched record.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Player
|
||||
/// let player = try request.fetchOne(db) // Player?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional record.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
return try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
extension TypedRequest where RowDecoder: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching Values
|
||||
|
||||
/// A cursor over fetched values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String
|
||||
/// while let string = try strings.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let strings = try request.fetchAll(db) // [String]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
return try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched value.
|
||||
///
|
||||
/// The result is nil if the request returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let string = try request.fetchOne(db) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
return try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
extension TypedRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching Values
|
||||
|
||||
/// A cursor over fetched values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String
|
||||
/// while let string = try strings.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> ColumnCursor<RowDecoder> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let strings = try request.fetchAll(db) // [String]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
return try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched value.
|
||||
///
|
||||
/// The result is nil if the request returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let string = try request.fetchOne(db) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
return try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching Optional values
|
||||
|
||||
/// A cursor over fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String?
|
||||
/// while let string = try strings.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor<RowDecoder._Wrapped> {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchAll(db) // [String?]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchAll(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching Optional values
|
||||
|
||||
/// A cursor over fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String?
|
||||
/// while let string = try strings.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> NullableColumnCursor<RowDecoder._Wrapped> {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchAll(db) // [String?]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchAll(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
extension TypedRequest where RowDecoder: Row {
|
||||
|
||||
// MARK: Fetching Rows
|
||||
|
||||
/// A cursor over fetched rows.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Row
|
||||
/// let rows = try request.fetchCursor(db) // RowCursor
|
||||
/// while let row = try rows.next() { // Row
|
||||
/// let id: Int64 = row[0]
|
||||
/// let name: String = row[1]
|
||||
/// }
|
||||
///
|
||||
/// Fetched rows are reused during the cursor iteration: don't turn a row
|
||||
/// cursor into an array with `Array(rows)` or `rows.filter { ... }` since
|
||||
/// you would not get the distinct rows you expect. Use `Row.fetchAll(...)`
|
||||
/// instead.
|
||||
///
|
||||
/// For the same reason, make sure you make a copy whenever you extract a
|
||||
/// row for later use: `row.copy()`.
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> RowCursor {
|
||||
return try Row.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched rows.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Row
|
||||
/// let rows = try request.fetchAll(db)
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of fetched rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [Row] {
|
||||
return try Row.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched row.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Row
|
||||
/// let row = try request.fetchOne(db)
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A,n optional rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> Row? {
|
||||
return try Row.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
+713
-406
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,423 @@
|
||||
import Foundation
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// LayoutedColumnMapping is a type that supports the RowAdapter protocol.
|
||||
public struct LayoutedColumnMapping {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// An array of (baseIndex, mappedName) pairs, where baseIndex is the index
|
||||
/// of a column in a base row, and mappedName the mapped name of
|
||||
/// that column.
|
||||
public let layoutColumns: [(Int, String)]
|
||||
|
||||
/// A cache for layoutIndex(ofColumn:)
|
||||
let lowercaseColumnIndexes: [String: Int] // [mappedColumn: layoutColumnIndex]
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Creates a LayoutedColumnMapping from an array of (baseIndex, mappedName)
|
||||
/// pairs. In each pair:
|
||||
///
|
||||
/// - baseIndex is the index of a column in a base row
|
||||
/// - name is the mapped name of the column
|
||||
///
|
||||
/// For example, the following LayoutedColumnMapping defines two columns, "foo"
|
||||
/// and "bar", based on the base columns at indexes 1 and 2:
|
||||
///
|
||||
/// LayoutedColumnMapping(layoutColumns: [(1, "foo"), (2, "bar")])
|
||||
///
|
||||
/// Use it in your custom RowAdapter type:
|
||||
///
|
||||
/// struct FooBarAdapter : RowAdapter {
|
||||
/// func layoutAdapter(layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
/// return LayoutedColumnMapping(layoutColumns: [(1, "foo"), (2, "bar")])
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // <Row foo:"foo" bar: "bar">
|
||||
/// try Row.fetchOne(db, "SELECT NULL, 'foo', 'bar'", adapter: FooBarAdapter())
|
||||
public init<S: Sequence>(layoutColumns: S) where S.Iterator.Element == (Int, String) {
|
||||
self.layoutColumns = Array(layoutColumns)
|
||||
self.lowercaseColumnIndexes = Dictionary(
|
||||
layoutColumns
|
||||
.enumerated()
|
||||
.map { ($0.element.1.lowercased(), $0.offset) },
|
||||
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
|
||||
}
|
||||
|
||||
func baseColumnIndex(atMappingIndex index: Int) -> Int {
|
||||
return layoutColumns[index].0
|
||||
}
|
||||
|
||||
func columnName(atMappingIndex index: Int) -> String {
|
||||
return layoutColumns[index].1
|
||||
}
|
||||
}
|
||||
|
||||
/// LayoutedColumnMapping adopts LayoutedRowAdapter
|
||||
extension LayoutedColumnMapping : LayoutedRowAdapter {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns self.
|
||||
public var mapping: LayoutedColumnMapping {
|
||||
return self
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns the empty dictionary.
|
||||
public var scopes: [String: LayoutedRowAdapter] {
|
||||
return [:]
|
||||
}
|
||||
}
|
||||
|
||||
extension LayoutedColumnMapping : RowLayout {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns the index of the leftmost column named `name`, in a
|
||||
/// case-insensitive way.
|
||||
public func layoutIndex(ofColumn name: String) -> Int? {
|
||||
if let index = lowercaseColumnIndexes[name] {
|
||||
return index
|
||||
}
|
||||
return lowercaseColumnIndexes[name.lowercased()]
|
||||
}
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// LayoutedRowAdapter is a protocol that supports the RowAdapter protocol.
|
||||
///
|
||||
/// GRBD ships with a ready-made type that adopts this protocol:
|
||||
/// LayoutedColumnMapping.
|
||||
public protocol LayoutedRowAdapter {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// A LayoutedColumnMapping that defines how to map a column name to a
|
||||
/// column in a base row.
|
||||
var mapping: LayoutedColumnMapping { get }
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The layouted row adapters for each scope.
|
||||
var scopes: [String: LayoutedRowAdapter] { get }
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// RowLayout is a protocol that supports the RowAdapter protocol. It describes
|
||||
/// a layout of a base row.
|
||||
public protocol RowLayout {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// An array of (baseIndex, name) pairs, where baseIndex is the index
|
||||
/// of a column in a base row, and name the name of that column.
|
||||
var layoutColumns: [(Int, String)] { get }
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns the index of the leftmost column named `name`, in a
|
||||
/// case-insensitive way.
|
||||
func layoutIndex(ofColumn name: String) -> Int?
|
||||
}
|
||||
|
||||
extension SelectStatement : RowLayout {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public var layoutColumns: [(Int, String)] {
|
||||
return Array(columnNames.enumerated())
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func layoutIndex(ofColumn name: String) -> Int? {
|
||||
return index(ofColumn: name)
|
||||
}
|
||||
}
|
||||
|
||||
/// RowAdapter is a protocol that helps two incompatible row interfaces working
|
||||
/// together.
|
||||
///
|
||||
/// GRDB ships with four concrete types that adopt the RowAdapter protocol:
|
||||
///
|
||||
/// - ColumnMapping: renames row columns
|
||||
/// - SuffixRowAdapter: hides the first columns of a row
|
||||
/// - RangeRowAdapter: only exposes a range of columns
|
||||
/// - ScopeAdapter: groups several adapters together to define named scopes
|
||||
///
|
||||
/// To use a row adapter, provide it to any method that fetches:
|
||||
///
|
||||
/// let adapter = SuffixRowAdapter(fromIndex: 2)
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
|
||||
///
|
||||
/// // <Row baz:3>
|
||||
/// try Row.fetchOne(db, sql, adapter: adapter)
|
||||
public protocol RowAdapter {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// You never call this method directly. It is called for you whenever an
|
||||
/// adapter has to be applied.
|
||||
///
|
||||
/// The result is a value that adopts LayoutedRowAdapter, such as
|
||||
/// LayoutedColumnMapping.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // An adapter that turns any row to a row that contains a single
|
||||
/// // column named "foo" whose value is the leftmost value of the
|
||||
/// // base row.
|
||||
/// struct FirstColumnAdapter : RowAdapter {
|
||||
/// func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
/// return LayoutedColumnMapping(layoutColumns: [(0, "foo")])
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // <Row foo:1>
|
||||
/// try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: FirstColumnAdapter())
|
||||
func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter
|
||||
}
|
||||
|
||||
extension RowAdapter {
|
||||
/// Returns an adapter based on self, with added scopes.
|
||||
///
|
||||
/// If self already defines scopes, the added scopes replace
|
||||
/// eventual existing scopes with the same name.
|
||||
///
|
||||
/// - parameter scopes: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
public func addingScopes(_ scopes: [String: RowAdapter]) -> RowAdapter {
|
||||
return ScopeAdapter(mainAdapter: self, scopes: scopes)
|
||||
}
|
||||
}
|
||||
|
||||
extension RowAdapter {
|
||||
func baseColumnIndex(atIndex index: Int, layout: RowLayout) throws -> Int {
|
||||
return try layoutedAdapter(from: layout).mapping.baseColumnIndex(atMappingIndex: index)
|
||||
}
|
||||
}
|
||||
|
||||
/// ColumnMapping is a row adapter that maps column names.
|
||||
///
|
||||
/// let adapter = ColumnMapping(["foo": "bar"])
|
||||
/// let sql = "SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz"
|
||||
///
|
||||
/// // <Row foo:"bar">
|
||||
/// try Row.fetchOne(db, sql, adapter: adapter)
|
||||
public struct ColumnMapping : RowAdapter {
|
||||
/// 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.
|
||||
public init(_ mapping: [String: String]) {
|
||||
self.mapping = mapping
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
let layoutColumns = try mapping
|
||||
.map { (mappedColumn, baseColumn) -> (Int, String) in
|
||||
guard let index = layout.layoutIndex(ofColumn: baseColumn) else {
|
||||
let columnNames = layout.layoutColumns.map { $0.1 }
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Mapping references missing column \(baseColumn). Valid column names are: \(columnNames.joined(separator: ", ")).")
|
||||
}
|
||||
let baseIndex = layout.layoutColumns[index].0
|
||||
return (baseIndex, mappedColumn)
|
||||
}
|
||||
.sorted { $0.0 < $1.0 } // preserve ordering of base columns
|
||||
return LayoutedColumnMapping(layoutColumns: layoutColumns)
|
||||
}
|
||||
}
|
||||
|
||||
/// SuffixRowAdapter is a row adapter that hides the first columns in a row.
|
||||
///
|
||||
/// let adapter = SuffixRowAdapter(fromIndex: 2)
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
|
||||
///
|
||||
/// // <Row baz:3>
|
||||
/// try Row.fetchOne(db, sql, adapter: adapter)
|
||||
public struct SuffixRowAdapter : RowAdapter {
|
||||
/// The suffix index
|
||||
let index: Int
|
||||
|
||||
/// Creates a SuffixRowAdapter that hides all columns before the
|
||||
/// provided index.
|
||||
///
|
||||
/// If index is 0, the layout row is identical to the base row.
|
||||
public init(fromIndex index: Int) {
|
||||
GRDBPrecondition(index >= 0, "Negative column index is out of range")
|
||||
self.index = index
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
return LayoutedColumnMapping(layoutColumns: layout.layoutColumns.suffix(from: index))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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"
|
||||
///
|
||||
/// // <Row bar:2 baz: 3>
|
||||
/// try Row.fetchOne(db, sql, adapter: adapter)
|
||||
public struct RangeRowAdapter : RowAdapter {
|
||||
/// The range
|
||||
let range: CountableRange<Int>
|
||||
|
||||
/// Creates a RangeRowAdapter that only exposes a range of columns.
|
||||
public init(_ range: CountableRange<Int>) {
|
||||
GRDBPrecondition(range.lowerBound >= 0, "Negative column index is out of range")
|
||||
self.range = range
|
||||
}
|
||||
|
||||
/// Creates a RangeRowAdapter that only exposes a range of columns.
|
||||
public init(_ range: CountableClosedRange<Int>) {
|
||||
GRDBPrecondition(range.lowerBound >= 0, "Negative column index is out of range")
|
||||
self.range = range.lowerBound..<(range.upperBound + 1)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
return LayoutedColumnMapping(layoutColumns: layout.layoutColumns[range])
|
||||
}
|
||||
}
|
||||
|
||||
/// ScopeAdapter is a row adapter that lets you define scopes on rows.
|
||||
///
|
||||
/// // Two adapters
|
||||
/// let fooAdapter = ColumnMapping(["value": "foo"])
|
||||
/// let barAdapter = ColumnMapping(["value": "bar"])
|
||||
///
|
||||
/// // Define scopes
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "foo": fooAdapter,
|
||||
/// "bar": barAdapter])
|
||||
///
|
||||
/// // Fetch
|
||||
/// let sql = "SELECT 'foo' AS foo, 'bar' AS bar"
|
||||
/// let row = try Row.fetchOne(db, sql, adapter: adapter)!
|
||||
///
|
||||
/// // Scoped rows:
|
||||
/// if let fooRow = row.scoped(on: "foo") {
|
||||
/// fooRow["value"] // "foo"
|
||||
/// }
|
||||
/// if let barRow = row.scopeed(on: "bar") {
|
||||
/// barRow["value"] // "bar"
|
||||
/// }
|
||||
public struct ScopeAdapter : RowAdapter {
|
||||
|
||||
/// The main adapter
|
||||
let mainAdapter: RowAdapter
|
||||
|
||||
/// The scope adapters
|
||||
let scopes: [String: RowAdapter]
|
||||
|
||||
/// Creates a scoped adapter.
|
||||
///
|
||||
/// - parameter scopes: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
public init(_ scopes: [String: RowAdapter]) {
|
||||
self.mainAdapter = SuffixRowAdapter(fromIndex: 0) // Use SuffixRowAdapter(fromIndex: 0) as the identity adapter
|
||||
self.scopes = scopes
|
||||
}
|
||||
|
||||
init(mainAdapter: RowAdapter, scopes: [String: RowAdapter]) {
|
||||
self.mainAdapter = mainAdapter
|
||||
self.scopes = scopes
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
let layoutedAdapter = try mainAdapter.layoutedAdapter(from: layout)
|
||||
var layoutedScopes = layoutedAdapter.scopes
|
||||
for (name, adapter) in scopes {
|
||||
try layoutedScopes[name] = adapter.layoutedAdapter(from: layout)
|
||||
}
|
||||
return LayoutedScopeAdapter(
|
||||
mapping: layoutedAdapter.mapping,
|
||||
scopes: layoutedScopes)
|
||||
}
|
||||
}
|
||||
|
||||
/// The LayoutedRowAdapter for ScopeAdapter
|
||||
struct LayoutedScopeAdapter : LayoutedRowAdapter {
|
||||
let mapping: LayoutedColumnMapping
|
||||
let scopes: [String: LayoutedRowAdapter]
|
||||
}
|
||||
|
||||
struct ChainedAdapter : RowAdapter {
|
||||
let first: RowAdapter
|
||||
let second: RowAdapter
|
||||
|
||||
func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
return try second.layoutedAdapter(from: first.layoutedAdapter(from: layout).mapping)
|
||||
}
|
||||
}
|
||||
|
||||
extension Row {
|
||||
/// Creates a row from a base row and a statement adapter
|
||||
convenience init(base: Row, adapter: LayoutedRowAdapter) {
|
||||
self.init(impl: AdapterRowImpl(base: base, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns self if adapter is nil
|
||||
func adapted(with adapter: RowAdapter?, layout: RowLayout) throws -> Row {
|
||||
guard let adapter = adapter else {
|
||||
return self
|
||||
}
|
||||
return try Row(base: self, adapter: adapter.layoutedAdapter(from: layout))
|
||||
}
|
||||
}
|
||||
|
||||
struct AdapterRowImpl : RowImpl {
|
||||
let base: Row
|
||||
let adapter: LayoutedRowAdapter
|
||||
let mapping: LayoutedColumnMapping
|
||||
|
||||
init(base: Row, adapter: LayoutedRowAdapter) {
|
||||
self.base = base
|
||||
self.adapter = adapter
|
||||
self.mapping = adapter.mapping
|
||||
}
|
||||
|
||||
var count: Int {
|
||||
return mapping.layoutColumns.count
|
||||
}
|
||||
|
||||
var isFetched: Bool {
|
||||
return base.isFetched
|
||||
}
|
||||
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
|
||||
return base[mapping.baseColumnIndex(atMappingIndex: index)]
|
||||
}
|
||||
|
||||
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
|
||||
return base.dataNoCopy(atIndex: mapping.baseColumnIndex(atMappingIndex: index))
|
||||
}
|
||||
|
||||
func columnName(atUncheckedIndex index: Int) -> String {
|
||||
return mapping.columnName(atMappingIndex: index)
|
||||
}
|
||||
|
||||
func index(ofColumn name: String) -> Int? {
|
||||
return mapping.layoutIndex(ofColumn: name)
|
||||
}
|
||||
|
||||
func scoped(on name: String) -> Row? {
|
||||
guard let adapter = adapter.scopes[name] else {
|
||||
return nil
|
||||
}
|
||||
return Row(base: base, adapter: adapter)
|
||||
}
|
||||
|
||||
var scopeNames: Set<String> {
|
||||
return Set(adapter.scopes.keys)
|
||||
}
|
||||
|
||||
func copy(_ row: Row) -> Row {
|
||||
return Row(base: base.copy(), adapter: adapter)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import Dispatch
|
||||
|
||||
/// SchedulingWatchdog makes sure that databases connections are used on correct
|
||||
/// dispatch queues, and warns the user with a fatal error whenever she misuses
|
||||
/// a database connection.
|
||||
///
|
||||
/// Generally speaking, each connection has its own dispatch queue. But it's not
|
||||
/// enough: users need to use two database connections at the same time:
|
||||
/// https://github.com/groue/GRDB.swift/issues/55. To support this use case, a
|
||||
/// single dispatch queue can be temporarily shared by two or more connections.
|
||||
///
|
||||
/// - SchedulingWatchdog.makeSerializedQueue(allowingDatabase:) creates a
|
||||
/// dispatch queue that allows one database.
|
||||
///
|
||||
/// It does so by registering one instance of SchedulingWatchdog as a specific
|
||||
/// of the dispatch queue, a SchedulingWatchdog that allows that database only.
|
||||
///
|
||||
/// Later on, the queue can be shared by several databases with the method
|
||||
/// allowing(databases:execute:). See SerializedDatabase.sync() for
|
||||
/// an example.
|
||||
///
|
||||
/// - preconditionValidQueue() crashes whenever a database is used in an invalid
|
||||
/// dispatch queue.
|
||||
final class SchedulingWatchdog {
|
||||
private static let specificKey = DispatchSpecificKey<SchedulingWatchdog>()
|
||||
private(set) var allowedDatabases: [Database]
|
||||
|
||||
private init(allowedDatabase database: Database) {
|
||||
allowedDatabases = [database]
|
||||
}
|
||||
|
||||
static func makeSerializedQueue(allowingDatabase database: Database) -> DispatchQueue {
|
||||
let queue = DispatchQueue(label: "GRDB.SerializedDatabase")
|
||||
let watchdog = SchedulingWatchdog(allowedDatabase: database)
|
||||
queue.setSpecific(key: specificKey, value: watchdog)
|
||||
return queue
|
||||
}
|
||||
|
||||
// Temporarily allows `databases` while executing `body`
|
||||
func allowing<T>(databases: [Database], execute body: () throws -> T) rethrows -> T {
|
||||
let backup = allowedDatabases
|
||||
allowedDatabases.append(contentsOf: databases)
|
||||
defer { allowedDatabases = backup }
|
||||
return try body()
|
||||
}
|
||||
|
||||
static func preconditionValidQueue(_ db: Database, _ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
|
||||
GRDBPrecondition(allows(db), message, file: file, line: line)
|
||||
}
|
||||
|
||||
static func allows(_ db: Database) -> Bool {
|
||||
return current?.allows(db) ?? false
|
||||
}
|
||||
|
||||
func allows(_ db: Database) -> Bool {
|
||||
return allowedDatabases.contains { $0 === db }
|
||||
}
|
||||
|
||||
static var current: SchedulingWatchdog? {
|
||||
return DispatchQueue.getSpecific(key: specificKey)
|
||||
}
|
||||
}
|
||||
@@ -2,18 +2,21 @@ import Foundation
|
||||
|
||||
/// A class that serializes accesses to a database.
|
||||
final class SerializedDatabase {
|
||||
/// The database
|
||||
private let database: Database
|
||||
/// The database connection
|
||||
private let db: Database
|
||||
|
||||
/// The database configuration
|
||||
var configuration: Configuration {
|
||||
return database.configuration
|
||||
return db.configuration
|
||||
}
|
||||
|
||||
/// The dispatch queue
|
||||
private let queue: dispatch_queue_t
|
||||
/// The path to the database file
|
||||
var path: String
|
||||
|
||||
convenience init(path: String, configuration: Configuration = Configuration(), schemaCache: DatabaseSchemaCacheType) throws {
|
||||
/// The dispatch queue
|
||||
private let queue: DispatchQueue
|
||||
|
||||
init(path: String, configuration: Configuration = Configuration(), schemaCache: DatabaseSchemaCache) throws {
|
||||
// According to https://www.sqlite.org/threadsafe.html
|
||||
//
|
||||
// > SQLite support three different threading modes:
|
||||
@@ -32,50 +35,135 @@ final class SerializedDatabase {
|
||||
// Since our database connection is only used via our serial dispatch
|
||||
// queue, there is no purpose using the default serialized mode.
|
||||
var config = configuration
|
||||
config.threadingMode = .MultiThread
|
||||
config.threadingMode = .multiThread
|
||||
|
||||
let database = try Database(path: path, configuration: config, schemaCache: schemaCache)
|
||||
self.init(database: database)
|
||||
}
|
||||
|
||||
private init(database: Database) {
|
||||
self.database = database
|
||||
self.queue = dispatch_queue_create("com.github.groue.GRDB", nil)
|
||||
|
||||
// Activate database.preconditionValidQueue()
|
||||
let databaseQueueID = unsafeBitCast(database, UnsafeMutablePointer<Void>.self)
|
||||
dispatch_queue_set_specific(queue, Database.databaseQueueIDKey, databaseQueueID, nil)
|
||||
database.databaseQueueID = databaseQueueID
|
||||
}
|
||||
|
||||
func inDatabase<T>(block: (db: Database) throws -> T) rethrows -> T {
|
||||
// This method is NOT reentrant.
|
||||
//
|
||||
// Avoiding dispatch_sync and calling block() right away if the specific
|
||||
// is currently self.databaseQueueID looks like a promising solution:
|
||||
//
|
||||
// serializedDatabase.inDatabase { db in
|
||||
// serializedDatabase.inDatabase { db in
|
||||
// // Look, ma! I'm reentrant!
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// However it does not survive this code, which deadlocks:
|
||||
//
|
||||
// let queue = dispatch_queue_create("...", nil)
|
||||
// serializedDatabase.inDatabase { db in
|
||||
// dispatch_sync(queue) {
|
||||
// serializedDatabase.inDatabase { db in
|
||||
// // Never run
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// I try not to ship half-baked solutions, so until a complete solution
|
||||
// is found to this problem, I prefer discouraging reentrancy.
|
||||
precondition(database.databaseQueueID != dispatch_get_specific(Database.databaseQueueIDKey), "Database methods are not reentrant.")
|
||||
return try dispatchSync(queue) {
|
||||
try block(db: self.database)
|
||||
db = try Database(path: path, configuration: config, schemaCache: schemaCache)
|
||||
queue = SchedulingWatchdog.makeSerializedQueue(allowingDatabase: db)
|
||||
self.path = path
|
||||
try queue.sync {
|
||||
try db.setup()
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
// Database may be deallocated in its own queue: allow reentrancy
|
||||
reentrantSync { db in
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a block the serialized dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
func sync<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
// Three different cases:
|
||||
//
|
||||
// 1. A database is invoked from some queue like the main queue:
|
||||
//
|
||||
// dbQueue.inDatabase { db in // <-- we're here
|
||||
// }
|
||||
//
|
||||
// 2. A database is invoked in a reentrant way:
|
||||
//
|
||||
// dbQueue.inDatabase { db in
|
||||
// dbQueue.inDatabase { db in // <-- we're here
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// 3. A database in invoked from another database:
|
||||
//
|
||||
// dbQueue1.inDatabase { db1 in
|
||||
// dbQueue2.inDatabase { db2 in // <-- we're here
|
||||
// }
|
||||
// }
|
||||
|
||||
guard let watchdog = SchedulingWatchdog.current else {
|
||||
// Case 1
|
||||
return try queue.sync {
|
||||
try block(db)
|
||||
}
|
||||
}
|
||||
|
||||
// Case 2 is forbidden.
|
||||
GRDBPrecondition(!watchdog.allows(db), "Database methods are not reentrant.")
|
||||
|
||||
// Case 3
|
||||
return try queue.sync {
|
||||
try SchedulingWatchdog.current!.allowing(databases: watchdog.allowedDatabases) {
|
||||
try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a block the serialized dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// This method is reentrant.
|
||||
func reentrantSync<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
// Three different cases:
|
||||
//
|
||||
// 1. A database is invoked from some queue like the main queue:
|
||||
//
|
||||
// dbQueue.inDatabase { db in // <-- we're here
|
||||
// }
|
||||
//
|
||||
// 2. A database is invoked in a reentrant way:
|
||||
//
|
||||
// dbQueue.inDatabase { db in
|
||||
// dbQueue.inDatabase { db in // <-- we're here
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// 3. A database in invoked from another database:
|
||||
//
|
||||
// dbQueue1.inDatabase { db1 in
|
||||
// dbQueue2.inDatabase { db2 in // <-- we're here
|
||||
// }
|
||||
// }
|
||||
|
||||
guard let watchdog = SchedulingWatchdog.current else {
|
||||
// Case 1
|
||||
return try queue.sync {
|
||||
try block(db)
|
||||
}
|
||||
}
|
||||
|
||||
// Case 2
|
||||
if watchdog.allows(db) {
|
||||
return try block(db)
|
||||
}
|
||||
|
||||
// Case 3
|
||||
return try queue.sync {
|
||||
try SchedulingWatchdog.current!.allowing(databases: watchdog.allowedDatabases) {
|
||||
try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Asynchronously executes a block in the serialized dispatch queue.
|
||||
func async(_ block: @escaping (Database) -> Void) {
|
||||
queue.async {
|
||||
block(self.db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if any only if the current dispatch queue is valid.
|
||||
var onValidQueue: Bool {
|
||||
return SchedulingWatchdog.allows(db)
|
||||
}
|
||||
|
||||
/// Executes the block in the current queue.
|
||||
///
|
||||
/// - precondition: the current dispatch queue is valid.
|
||||
func execute<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
preconditionValidQueue()
|
||||
return try block(db)
|
||||
}
|
||||
|
||||
/// Fatal error if current dispatch queue is not valid.
|
||||
func preconditionValidQueue(_ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
|
||||
SchedulingWatchdog.preconditionValidQueue(db, message, file: file, line: line)
|
||||
}
|
||||
}
|
||||
+702
-401
File diff suppressed because it is too large.
Load diff
@@ -1,19 +1,46 @@
|
||||
/// When a type adopts both DatabaseValueConvertible and
|
||||
/// StatementColumnConvertible, it is granted with faster access to the SQLite
|
||||
/// database values.
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// The StatementColumnConvertible protocol grants access to the low-level C
|
||||
/// interface that extracts values from query results:
|
||||
/// https://www.sqlite.org/c3ref/column_blob.html. It can bring performance
|
||||
/// improvements.
|
||||
///
|
||||
/// To use it, have a value type adopt both StatementColumnConvertible and
|
||||
/// DatabaseValueConvertible. GRDB will then automatically apply the
|
||||
/// optimization whenever direct access to SQLite is possible:
|
||||
///
|
||||
/// let rows = Row.fetchCursor(db, "SELECT ...")
|
||||
/// while let row = try rows.next() {
|
||||
/// let int: Int = row[0] // there
|
||||
/// }
|
||||
/// let ints = Int.fetchAll(db, "SELECT ...") // there
|
||||
/// struct Player {
|
||||
/// init(row: Row) {
|
||||
/// name = row["name"] // there
|
||||
/// score = row["score"] // there
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// StatementColumnConvertible is already adopted by all Swift integer types,
|
||||
/// Float, Double, String, and Bool.
|
||||
public protocol StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
/// Initializes a value from a raw SQLite statement pointer.
|
||||
///
|
||||
/// As an example, here is the how Int64 adopts StatementColumnConvertible:
|
||||
/// For example, here is the how Int64 adopts StatementColumnConvertible:
|
||||
///
|
||||
/// extension Int64: StatementColumnConvertible {
|
||||
/// public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
/// init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
/// self = sqlite3_column_int64(sqliteStatement, index)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// When you implement this method, don't check for NULL.
|
||||
/// This initializer is never called for NULL database values: don't perform
|
||||
/// any extra check.
|
||||
///
|
||||
/// See https://www.sqlite.org/c3ref/column_blob.html for more information.
|
||||
///
|
||||
@@ -23,140 +50,410 @@ public protocol StatementColumnConvertible {
|
||||
init(sqliteStatement: SQLiteStatement, index: Int32)
|
||||
}
|
||||
|
||||
/// A cursor of database values extracted from a single column.
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let names: ColumnCursor<String> = try String.fetchCursor(db, "SELECT name FROM players")
|
||||
/// while let name = names.next() { // String
|
||||
/// print(name)
|
||||
/// }
|
||||
/// }
|
||||
public final class ColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
|
||||
private let statement: SelectStatement
|
||||
private let sqliteStatement: SQLiteStatement
|
||||
private let columnIndex: Int32
|
||||
private var done = false
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
// We'll read from leftmost column at index 0, unless adapter mangles columns
|
||||
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
public func next() throws -> Value? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
if sqlite3_column_type(sqliteStatement, columnIndex) == SQLITE_NULL {
|
||||
var error = "could not convert database value NULL to \(Value.self) with statement `\(statement.sql)`"
|
||||
if !statement.arguments.isEmpty {
|
||||
error += " arguments \(statement.arguments)"
|
||||
}
|
||||
fatalError(error)
|
||||
}
|
||||
return Value(sqliteStatement: sqliteStatement, index: columnIndex)
|
||||
case let code:
|
||||
statement.database.selectStatementDidFail(statement)
|
||||
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor of optional database values extracted from a single column.
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let emails: NullableColumnCursor<String> = try Optional<String>.fetchCursor(db, "SELECT email FROM players")
|
||||
/// while let email = emails.next() { // String?
|
||||
/// print(email ?? "<NULL>")
|
||||
/// }
|
||||
/// }
|
||||
public final class NullableColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
|
||||
private let statement: SelectStatement
|
||||
private let sqliteStatement: SQLiteStatement
|
||||
private let columnIndex: Int32
|
||||
private var done = false
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
// We'll read from leftmost column at index 0, unless adapter mangles columns
|
||||
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
public func next() throws -> Value?? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
if sqlite3_column_type(sqliteStatement, columnIndex) == SQLITE_NULL {
|
||||
return .some(nil)
|
||||
}
|
||||
return Value(sqliteStatement: sqliteStatement, index: columnIndex)
|
||||
case let code:
|
||||
statement.database.selectStatementDidFail(statement)
|
||||
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Types that adopt both DatabaseValueConvertible and
|
||||
/// StatementColumnConvertible can be efficiently initialized from
|
||||
/// database values.
|
||||
///
|
||||
/// See DatabaseValueConvertible for more information.
|
||||
public extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
|
||||
// MARK: - Fetching From SelectStatement
|
||||
// MARK: Fetching From SelectStatement
|
||||
|
||||
/// Returns a sequence of values fetched from a prepared statement.
|
||||
/// Returns a cursor over values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = db.selectStatement("SELECT name FROM ...")
|
||||
/// let names = String.fetch(statement) // DatabaseSequence<String>
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let names = try String.fetchCursor(statement) // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// The returned sequence can be consumed several times, but it may yield
|
||||
/// different results, should database changes have occurred between two
|
||||
/// generations:
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// let names = String.fetch(statement)
|
||||
/// Array(names) // Arthur, Barbara
|
||||
/// db.execute("DELETE ...")
|
||||
/// Array(names) // Arthur
|
||||
///
|
||||
/// If the database is modified while the sequence is iterating, the
|
||||
/// remaining elements are undefined.
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - returns: A sequence of values.
|
||||
@warn_unused_result
|
||||
public static func fetch(statement: SelectStatement, arguments: StatementArguments? = nil) -> DatabaseSequence<Self> {
|
||||
let sqliteStatement = statement.sqliteStatement
|
||||
return statement.fetchSequence(arguments: arguments) {
|
||||
guard sqlite3_column_type(sqliteStatement, 0) != SQLITE_NULL else {
|
||||
fatalError("could not convert NULL to \(Self.self).")
|
||||
}
|
||||
return Self.init(sqliteStatement: sqliteStatement, index: 0)
|
||||
}
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> ColumnCursor<Self> {
|
||||
return try ColumnCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = db.selectStatement("SELECT name FROM ...")
|
||||
/// let names = String.fetchAll(statement) // [String]
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let names = try String.fetchAll(statement) // [String]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of values.
|
||||
@warn_unused_result
|
||||
public static func fetchAll(statement: SelectStatement, arguments: StatementArguments? = nil) -> [Self] {
|
||||
return Array(fetch(statement, arguments: arguments))
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
|
||||
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = db.selectStatement("SELECT name FROM ...")
|
||||
/// let name = String.fetchOne(statement) // String?
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let name = try String.fetchOne(statement) // String?
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional value.
|
||||
@warn_unused_result
|
||||
public static func fetchOne(statement: SelectStatement, arguments: StatementArguments? = nil) -> Self? {
|
||||
let sqliteStatement = statement.sqliteStatement
|
||||
let sequence = statement.fetchSequence(arguments: arguments) {
|
||||
(sqlite3_column_type(sqliteStatement, 0) == SQLITE_NULL) ?
|
||||
(nil as Self?) :
|
||||
Self.init(sqliteStatement: sqliteStatement, index: 0)
|
||||
}
|
||||
if let value = sequence.generate().next() {
|
||||
return value
|
||||
}
|
||||
return nil
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
|
||||
// fetchOne returns nil if there is no row, or if there is a row with a null value
|
||||
let cursor = try NullableColumnCursor<Self>(statement: statement, arguments: arguments, adapter: adapter)
|
||||
return try cursor.next() ?? nil
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching From Request
|
||||
|
||||
// MARK: - Fetching From SQL
|
||||
|
||||
/// Returns a sequence of values fetched from an SQL query.
|
||||
/// Returns a cursor over values fetched from a fetch request.
|
||||
///
|
||||
/// let names = String.fetch(db, "SELECT name FROM ...") // DatabaseSequence<String>
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try String.fetchCursor(db, request) // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// The returned sequence can be consumed several times, but it may yield
|
||||
/// different results, should database changes have occurred between two
|
||||
/// generations:
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// let names = String.fetch(db, "SELECT name FROM ...")
|
||||
/// Array(names) // Arthur, Barbara
|
||||
/// execute("DELETE ...")
|
||||
/// Array(names) // Arthur
|
||||
///
|
||||
/// If the database is modified while the sequence is iterating, the
|
||||
/// remaining elements are undefined.
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A Database.
|
||||
/// - db: A database connection.
|
||||
/// - request: A fetch request.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> ColumnCursor<Self> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try String.fetchAll(db, request) // [String]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ request: Request) throws -> [Self] {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchAll(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from a fetch request.
|
||||
///
|
||||
/// The result is nil if the query returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let name = try String.fetchOne(db, request) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: Database, _ request: Request) throws -> Self? {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchOne(statement, adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching From SQL
|
||||
|
||||
/// Returns a cursor over values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try String.fetchCursor(db, "SELECT name FROM ...") // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - returns: A sequence of values.
|
||||
@warn_unused_result
|
||||
public static func fetch(db: Database, _ sql: String, arguments: StatementArguments? = nil) -> DatabaseSequence<Self> {
|
||||
return fetch(try! db.selectStatement(sql), arguments: arguments)
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> ColumnCursor<Self> {
|
||||
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from an SQL query.
|
||||
///
|
||||
/// let names = String.fetchAll(db, "SELECT name FROM ...") // [String]
|
||||
/// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - reader: A DatabaseReader.
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of values.
|
||||
@warn_unused_result
|
||||
public static func fetchAll(reader: DatabaseReader, _ sql: String, arguments: StatementArguments? = nil) -> [Self] {
|
||||
return reader._readSingleStatement { db in fetchAll(try! db.selectStatement(sql), arguments: arguments) }
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
|
||||
return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from an SQL query.
|
||||
///
|
||||
/// let name = String.fetchOne(db, "SELECT name FROM ...") // String?
|
||||
/// let name = try String.fetchOne(db, "SELECT name FROM ...") // String?
|
||||
///
|
||||
/// - parameters:
|
||||
/// - reader: A DatabaseReader.
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional value.
|
||||
@warn_unused_result
|
||||
public static func fetchOne(reader: DatabaseReader, _ sql: String, arguments: StatementArguments? = nil) -> Self? {
|
||||
return reader._readSingleStatement { db in fetchOne(try! db.selectStatement(sql), arguments: arguments) }
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
|
||||
return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Swift's Optional comes with built-in methods that allow to fetch cursors
|
||||
/// and arrays of optional DatabaseValueConvertible:
|
||||
///
|
||||
/// try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// try Optional<String>.fetchCursor(statement, arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(statement, arguments:...) // [String?]
|
||||
///
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching From SelectStatement
|
||||
|
||||
/// Returns a cursor over optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchCursor(statement) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableColumnCursor<Wrapped> {
|
||||
return try NullableColumnCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchAll(statement) // [String?]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
|
||||
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching From Request
|
||||
|
||||
/// Returns a cursor over optional values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try Optional<String>.fetchCursor(db, request) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - requet: A fetch request.
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> NullableColumnCursor<Wrapped> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try Optional<String>.fetchAll(db, request) // [String?]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ request: Request) throws -> [Wrapped?] {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchAll(statement, adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching From SQL
|
||||
|
||||
/// Returns a cursor over optional values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableColumnCursor<Wrapped> {
|
||||
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String?]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - parameter arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
|
||||
return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
@@ -8,9 +8,9 @@ extension CGFloat : DatabaseValueConvertible {
|
||||
return Double(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a CGFloat initialized from *databaseValue*, if possible.
|
||||
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> CGFloat? {
|
||||
guard let double = Double.fromDatabaseValue(databaseValue) else {
|
||||
/// Returns a CGFloat initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> CGFloat? {
|
||||
guard let double = Double.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
}
|
||||
return CGFloat(double)
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// Data is convertible to and from DatabaseValue.
|
||||
extension Data : DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
if let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) {
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
self.init(bytes: bytes, count: count) // copy bytes
|
||||
} else {
|
||||
self.init()
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return DatabaseValue(storage: .blob(self))
|
||||
}
|
||||
|
||||
/// Returns a Data initialized from *dbValue*, if it contains
|
||||
/// a Blob.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Data? {
|
||||
guard case .blob(let data) = dbValue.storage else {
|
||||
return nil
|
||||
}
|
||||
return data
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
/// DatabaseCoder reads and stores objects that conform to NSCoding in
|
||||
/// the database.
|
||||
public struct DatabaseCoder: DatabaseValueConvertible {
|
||||
|
||||
/// The object
|
||||
public let object: AnyObject
|
||||
|
||||
/// Creates a DatabaseCoder from an object that conforms to NSCoding.
|
||||
///
|
||||
/// The result is nil if and only if *object* is nil.
|
||||
public init?(_ object: AnyObject?) {
|
||||
guard let object = object else {
|
||||
return nil
|
||||
}
|
||||
self.object = object
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return NSKeyedArchiver.archivedDataWithRootObject(object).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a DatabaseCoder if *databaseValue* contains an archived object.
|
||||
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> DatabaseCoder? {
|
||||
guard let data = NSData.fromDatabaseValue(databaseValue) else {
|
||||
return nil
|
||||
}
|
||||
return DatabaseCoder(NSKeyedUnarchiver.unarchiveObjectWithData(data))
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import Foundation
|
||||
|
||||
/// DatabaseDateComponents reads and stores NSDateComponents in the database.
|
||||
/// DatabaseDateComponents reads and stores DateComponents in the database.
|
||||
public struct DatabaseDateComponents : DatabaseValueConvertible {
|
||||
|
||||
/// The available formats for reading and storing date components.
|
||||
@@ -46,21 +46,21 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
|
||||
// MARK: - NSDateComponents conversion
|
||||
|
||||
/// The date components
|
||||
public let dateComponents: NSDateComponents
|
||||
public let dateComponents: DateComponents
|
||||
|
||||
/// The database format
|
||||
public let format: Format
|
||||
|
||||
/// Creates a DatabaseDateComponents from an NSDateComponents and a format.
|
||||
/// Creates a DatabaseDateComponents from a DateComponents and a format.
|
||||
///
|
||||
/// The result is nil if and only if *dateComponents* is nil.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - dateComponents: An optional NSDateComponents.
|
||||
/// - dateComponents: An optional DateComponents.
|
||||
/// - format: The format used for storing the date components in
|
||||
/// the database.
|
||||
/// - returns: An optional DatabaseDateComponents.
|
||||
public init?(_ dateComponents: NSDateComponents?, format: Format) {
|
||||
public init?(_ dateComponents: DateComponents?, format: Format) {
|
||||
guard let dateComponents = dateComponents else {
|
||||
return nil
|
||||
}
|
||||
@@ -76,9 +76,9 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
|
||||
let dateString: String?
|
||||
switch format {
|
||||
case .YMD_HM, .YMD_HMS, .YMD_HMSS, .YMD:
|
||||
let year = (dateComponents.year == NSDateComponentUndefined) ? 0 : dateComponents.year
|
||||
let month = (dateComponents.month == NSDateComponentUndefined) ? 1 : dateComponents.month
|
||||
let day = (dateComponents.day == NSDateComponentUndefined) ? 1 : dateComponents.day
|
||||
let year = dateComponents.year ?? 0
|
||||
let month = dateComponents.month ?? 1
|
||||
let day = dateComponents.day ?? 1
|
||||
dateString = NSString(format: "%04d-%02d-%02d", year, month, day) as String
|
||||
default:
|
||||
dateString = nil
|
||||
@@ -87,30 +87,30 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
|
||||
let timeString: String?
|
||||
switch format {
|
||||
case .YMD_HM, .HM:
|
||||
let hour = (dateComponents.hour == NSDateComponentUndefined) ? 0 : dateComponents.hour
|
||||
let minute = (dateComponents.minute == NSDateComponentUndefined) ? 0 : dateComponents.minute
|
||||
let hour = dateComponents.hour ?? 0
|
||||
let minute = dateComponents.minute ?? 0
|
||||
timeString = NSString(format: "%02d:%02d", hour, minute) as String
|
||||
case .YMD_HMS, .HMS:
|
||||
let hour = (dateComponents.hour == NSDateComponentUndefined) ? 0 : dateComponents.hour
|
||||
let minute = (dateComponents.minute == NSDateComponentUndefined) ? 0 : dateComponents.minute
|
||||
let second = (dateComponents.second == NSDateComponentUndefined) ? 0 : dateComponents.second
|
||||
let hour = dateComponents.hour ?? 0
|
||||
let minute = dateComponents.minute ?? 0
|
||||
let second = dateComponents.second ?? 0
|
||||
timeString = NSString(format: "%02d:%02d:%02d", hour, minute, second) as String
|
||||
case .YMD_HMSS, .HMSS:
|
||||
let hour = (dateComponents.hour == NSDateComponentUndefined) ? 0 : dateComponents.hour
|
||||
let minute = (dateComponents.minute == NSDateComponentUndefined) ? 0 : dateComponents.minute
|
||||
let second = (dateComponents.second == NSDateComponentUndefined) ? 0 : dateComponents.second
|
||||
let nanosecond = (dateComponents.nanosecond == NSDateComponentUndefined) ? 0 : dateComponents.nanosecond
|
||||
let hour = dateComponents.hour ?? 0
|
||||
let minute = dateComponents.minute ?? 0
|
||||
let second = dateComponents.second ?? 0
|
||||
let nanosecond = dateComponents.nanosecond ?? 0
|
||||
timeString = NSString(format: "%02d:%02d:%02d.%03d", hour, minute, second, Int(round(Double(nanosecond) / 1_000_000.0))) as String
|
||||
default:
|
||||
timeString = nil
|
||||
}
|
||||
|
||||
return [dateString, timeString].flatMap { $0 }.joinWithSeparator(" ").databaseValue
|
||||
return [dateString, timeString].flatMap { $0 }.joined(separator: " ").databaseValue
|
||||
}
|
||||
|
||||
/// Returns a DatabaseDateComponents if *databaseValue* contains a
|
||||
/// Returns a DatabaseDateComponents if *dbValue* contains a
|
||||
/// valid date.
|
||||
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> DatabaseDateComponents? {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> DatabaseDateComponents? {
|
||||
// https://www.sqlite.org/lang_datefunc.html
|
||||
//
|
||||
// Supported formats are:
|
||||
@@ -127,19 +127,19 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
|
||||
// - HH:MM:SS.SSS
|
||||
|
||||
// We need a String
|
||||
guard let string = String.fromDatabaseValue(databaseValue) else {
|
||||
guard let string = String.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let dateComponents = NSDateComponents()
|
||||
let scanner = NSScanner(string: string)
|
||||
scanner.charactersToBeSkipped = NSCharacterSet()
|
||||
var dateComponents = DateComponents()
|
||||
let scanner = Scanner(string: string)
|
||||
scanner.charactersToBeSkipped = CharacterSet()
|
||||
|
||||
let hasDate: Bool
|
||||
|
||||
// YYYY or HH
|
||||
var initialNumber: Int = 0
|
||||
if !scanner.scanInteger(&initialNumber) {
|
||||
if !scanner.scanInt(&initialNumber) {
|
||||
return nil
|
||||
}
|
||||
switch scanner.scanLocation {
|
||||
@@ -166,44 +166,44 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
|
||||
}
|
||||
|
||||
// -
|
||||
if !scanner.scanString("-", intoString: nil) {
|
||||
if !scanner.scanString("-", into: nil) {
|
||||
return nil
|
||||
}
|
||||
|
||||
// MM
|
||||
var month: Int = 0
|
||||
if scanner.scanInteger(&month) && month >= 1 && month <= 12 {
|
||||
if scanner.scanInt(&month) && month >= 1 && month <= 12 {
|
||||
dateComponents.month = month
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
|
||||
// -
|
||||
if !scanner.scanString("-", intoString: nil) {
|
||||
if !scanner.scanString("-", into: nil) {
|
||||
return nil
|
||||
}
|
||||
|
||||
// DD
|
||||
var day: Int = 0
|
||||
if scanner.scanInteger(&day) && day >= 1 && day <= 31 {
|
||||
if scanner.scanInt(&day) && day >= 1 && day <= 31 {
|
||||
dateComponents.day = day
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
|
||||
// YYYY-MM-DD
|
||||
if scanner.atEnd {
|
||||
if scanner.isAtEnd {
|
||||
return DatabaseDateComponents(dateComponents, format: .YMD)
|
||||
}
|
||||
|
||||
// T/space
|
||||
if !scanner.scanString("T", intoString: nil) && !scanner.scanString(" ", intoString: nil) {
|
||||
if !scanner.scanString("T", into: nil) && !scanner.scanString(" ", into: nil) {
|
||||
return nil
|
||||
}
|
||||
|
||||
// HH
|
||||
var hour: Int = 0
|
||||
if scanner.scanInteger(&hour) && hour >= 0 && hour <= 23 {
|
||||
if scanner.scanInt(&hour) && hour >= 0 && hour <= 23 {
|
||||
dateComponents.hour = hour
|
||||
} else {
|
||||
return nil
|
||||
@@ -214,20 +214,20 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
|
||||
}
|
||||
|
||||
// :
|
||||
if !scanner.scanString(":", intoString: nil) {
|
||||
if !scanner.scanString(":", into: nil) {
|
||||
return nil
|
||||
}
|
||||
|
||||
// MM
|
||||
var minute: Int = 0
|
||||
if scanner.scanInteger(&minute) && minute >= 0 && minute <= 59 {
|
||||
if scanner.scanInt(&minute) && minute >= 0 && minute <= 59 {
|
||||
dateComponents.minute = minute
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
|
||||
// [YYYY-MM-DD] HH:MM
|
||||
if scanner.atEnd {
|
||||
if scanner.isAtEnd {
|
||||
if hasDate {
|
||||
return DatabaseDateComponents(dateComponents, format: .YMD_HM)
|
||||
} else {
|
||||
@@ -236,20 +236,20 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
|
||||
}
|
||||
|
||||
// :
|
||||
if !scanner.scanString(":", intoString: nil) {
|
||||
if !scanner.scanString(":", into: nil) {
|
||||
return nil
|
||||
}
|
||||
|
||||
// SS
|
||||
var second: Int = 0
|
||||
if scanner.scanInteger(&second) && second >= 0 && second <= 59 {
|
||||
if scanner.scanInt(&second) && second >= 0 && second <= 59 {
|
||||
dateComponents.second = second
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
|
||||
// [YYYY-MM-DD] HH:MM:SS
|
||||
if scanner.atEnd {
|
||||
if scanner.isAtEnd {
|
||||
if hasDate {
|
||||
return DatabaseDateComponents(dateComponents, format: .YMD_HMS)
|
||||
} else {
|
||||
@@ -258,15 +258,15 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
|
||||
}
|
||||
|
||||
// .
|
||||
if !scanner.scanString(".", intoString: nil) {
|
||||
if !scanner.scanString(".", into: nil) {
|
||||
return nil
|
||||
}
|
||||
|
||||
// SSS
|
||||
var millisecondDigits: NSString? = nil
|
||||
if scanner.scanCharactersFromSet(NSCharacterSet.decimalDigitCharacterSet(), intoString: &millisecondDigits), var millisecondDigits = millisecondDigits {
|
||||
if scanner.scanCharacters(from: .decimalDigits, into: &millisecondDigits), var millisecondDigits = millisecondDigits {
|
||||
if millisecondDigits.length > 3 {
|
||||
millisecondDigits = millisecondDigits.substringToIndex(3)
|
||||
millisecondDigits = NSString(string: millisecondDigits.substring(to: 3))
|
||||
}
|
||||
dateComponents.nanosecond = millisecondDigits.integerValue * 1_000_000
|
||||
} else {
|
||||
@@ -274,7 +274,7 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
|
||||
}
|
||||
|
||||
// [YYYY-MM-DD] HH:MM:SS.SSS
|
||||
if scanner.atEnd {
|
||||
if scanner.isAtEnd {
|
||||
if hasDate {
|
||||
return DatabaseDateComponents(dateComponents, format: .YMD_HMSS)
|
||||
} else {
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
/// Foundation support for DatabaseValue
|
||||
extension DatabaseValue {
|
||||
|
||||
/// Builds a DatabaseValue from AnyObject.
|
||||
///
|
||||
/// The result is nil unless object adopts DatabaseValueConvertible (NSData,
|
||||
/// NSDate, NSNull, NSNumber, NSString, NSURL).
|
||||
public init?(object: AnyObject) {
|
||||
guard let convertible = object as? DatabaseValueConvertible else {
|
||||
return nil
|
||||
}
|
||||
self.init(storage: convertible.databaseValue.storage)
|
||||
}
|
||||
|
||||
/// Converts a DatabaseValue to AnyObject.
|
||||
///
|
||||
/// - returns: NSNull, NSNumber, NSString, or NSData.
|
||||
public func toAnyObject() -> AnyObject {
|
||||
switch storage {
|
||||
case .Null:
|
||||
return NSNull()
|
||||
case .Int64(let int64):
|
||||
return NSNumber(longLong: int64)
|
||||
case .Double(let double):
|
||||
return NSNumber(double: double)
|
||||
case .String(let string):
|
||||
return string as NSString
|
||||
case .Blob(let data):
|
||||
return data
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import Foundation
|
||||
|
||||
/// DatabaseValueConvertible is free for ReferenceConvertible types whose
|
||||
/// ReferenceType is itself DatabaseValueConvertible.
|
||||
///
|
||||
/// class FooReference { ... }
|
||||
/// struct Foo : ReferenceConvertible {
|
||||
/// typealias ReferenceType = FooReference
|
||||
/// }
|
||||
///
|
||||
/// // If the ReferenceType adopts DatabaseValueConvertible...
|
||||
/// extension FooReference : DatabaseValueConvertible { ... }
|
||||
///
|
||||
/// // ... then the ReferenceConvertible type can freely adopt DatabaseValueConvertible:
|
||||
/// extension Foo : DatabaseValueConvertible { /* empty */ }
|
||||
extension DatabaseValueConvertible where Self: ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return (self as! ReferenceType).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a value initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
return ReferenceType.fromDatabaseValue(dbValue).flatMap { cast($0) }
|
||||
}
|
||||
}
|
||||
|
||||
public extension DatabaseValueConvertible where Self: Decodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible {
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
// Preserve custom database decoding
|
||||
return ReferenceType.fromDatabaseValue(databaseValue).flatMap { cast($0) }
|
||||
}
|
||||
}
|
||||
|
||||
public extension DatabaseValueConvertible where Self: Encodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible {
|
||||
public var databaseValue: DatabaseValue {
|
||||
// Preserve custom database encoding
|
||||
return (self as! ReferenceType).databaseValue
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import Foundation
|
||||
|
||||
/// NSDate is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
extension NSDate : DatabaseValueConvertible {
|
||||
/// Returns a database value that contains the date encoded as
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return (self as Date).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a date initialized from dbValue, if possible.
|
||||
///
|
||||
/// If database value contains a number, that number is interpreted as a
|
||||
/// timeinterval since 00:00:00 UTC on 1 January 1970.
|
||||
///
|
||||
/// If database value contains a string, that string is interpreted as a
|
||||
/// [SQLite date](https://sqlite.org/lang_datefunc.html) in the UTC time
|
||||
/// zone. Nil is returned if the date string does not contain at least the
|
||||
/// year, month and day components. Other components (minutes, etc.)
|
||||
/// are set to zero if missing.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
guard let date = Date.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
}
|
||||
return cast(date)
|
||||
}
|
||||
}
|
||||
|
||||
/// Date is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
extension Date : DatabaseValueConvertible {
|
||||
/// Returns a database value that contains the date encoded as
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return storageDateFormatter.string(from: self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a date initialized from dbValue, if possible.
|
||||
///
|
||||
/// If database value contains a number, that number is interpreted as a
|
||||
/// timeinterval since 00:00:00 UTC on 1 January 1970.
|
||||
///
|
||||
/// If database value contains a string, that string is interpreted as a
|
||||
/// [SQLite date](https://sqlite.org/lang_datefunc.html) in the UTC time
|
||||
/// zone. Nil is returned if the date string does not contain at least the
|
||||
/// year, month and day components. Other components (minutes, etc.)
|
||||
/// are set to zero if missing.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Date? {
|
||||
if let databaseDateComponents = DatabaseDateComponents.fromDatabaseValue(dbValue) {
|
||||
return Date(databaseDateComponents: databaseDateComponents)
|
||||
}
|
||||
if let timestamp = Double.fromDatabaseValue(dbValue) {
|
||||
return Date(timeIntervalSince1970: timestamp)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private init?(databaseDateComponents: DatabaseDateComponents) {
|
||||
guard databaseDateComponents.format.hasYMDComponents else {
|
||||
// Refuse to turn hours without any date information into Date:
|
||||
return nil
|
||||
}
|
||||
guard let date = UTCCalendar.date(from: databaseDateComponents.dateComponents) else {
|
||||
return nil
|
||||
}
|
||||
self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate)
|
||||
}
|
||||
|
||||
/// Creates a date from a [Julian Day](https://en.wikipedia.org/wiki/Julian_day).
|
||||
public init?(julianDay: Double) {
|
||||
// Conversion uses the same algorithm as SQLite: https://www.sqlite.org/src/artifact/8ec787fed4929d8c
|
||||
// TODO: check for overflows one day, and return nil when computation can't complete.
|
||||
let JD = Int64(julianDay * 86400000)
|
||||
let Z = Int(((JD + 43200000)/86400000))
|
||||
var A = Int(((Double(Z) - 1867216.25)/36524.25))
|
||||
A = Z + 1 + A - (A/4)
|
||||
let B = A + 1524
|
||||
let C = Int(((Double(B) - 122.1)/365.25))
|
||||
let D = (36525*(C&32767))/100
|
||||
let E = Int((Double(B-D)/30.6001))
|
||||
let X1 = Int((30.6001*Double(E)))
|
||||
let day = B - D - X1
|
||||
let month = E<14 ? E-1 : E-13
|
||||
let year = month>2 ? C - 4716 : C - 4715
|
||||
var s = Int(((JD + 43200000) % 86400000))
|
||||
var second = Double(s)/1000.0
|
||||
s = Int(second)
|
||||
second -= Double(s)
|
||||
let hour = s/3600
|
||||
s -= hour*3600
|
||||
let minute = s/60
|
||||
second += Double(s - minute*60)
|
||||
|
||||
var dateComponents = DateComponents()
|
||||
dateComponents.year = year
|
||||
dateComponents.month = month
|
||||
dateComponents.day = day
|
||||
dateComponents.hour = hour
|
||||
dateComponents.minute = minute
|
||||
dateComponents.second = Int(second)
|
||||
dateComponents.nanosecond = Int((second - Double(Int(second))) * 1.0e9)
|
||||
|
||||
guard let date = UTCCalendar.date(from: dateComponents) else {
|
||||
return nil
|
||||
}
|
||||
self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate)
|
||||
}
|
||||
}
|
||||
|
||||
/// The DatabaseDate date formatter for stored dates.
|
||||
private let storageDateFormatter: DateFormatter = {
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
|
||||
formatter.locale = Locale(identifier: "en_US_POSIX")
|
||||
formatter.timeZone = TimeZone(secondsFromGMT: 0)
|
||||
return formatter
|
||||
}()
|
||||
|
||||
// The NSCalendar for stored dates.
|
||||
private let UTCCalendar: Calendar = {
|
||||
var calendar = Calendar(identifier: .gregorian)
|
||||
calendar.locale = Locale(identifier: "en_US_POSIX")
|
||||
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
|
||||
return calendar
|
||||
}()
|
||||
@@ -2,23 +2,18 @@ import Foundation
|
||||
|
||||
/// NSData is convertible to and from DatabaseValue.
|
||||
extension NSData : DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
// SQLite cant' store zero-length blobs.
|
||||
guard length > 0 else {
|
||||
return .Null
|
||||
}
|
||||
return DatabaseValue(storage: .Blob(self))
|
||||
return (self as Data).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an NSData initialized from *databaseValue*, if it contains
|
||||
/// Returns an NSData initialized from *dbValue*, if it contains
|
||||
/// a Blob.
|
||||
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Self? {
|
||||
switch databaseValue.storage {
|
||||
case .Blob(let data):
|
||||
return self.init(data: data)
|
||||
default:
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
guard let data = Data.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
}
|
||||
return cast(data)
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
/// NSDate are stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
extension NSDate : DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return storageDateFormatter.stringFromDate(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an NSDate initialized from *databaseValue*, if possible.
|
||||
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Self? {
|
||||
if let databaseDateComponents = DatabaseDateComponents.fromDatabaseValue(databaseValue) {
|
||||
return fromDatabaseDateComponents(databaseDateComponents)
|
||||
}
|
||||
if let julianDayNumber = Double.fromDatabaseValue(databaseValue) {
|
||||
return fromJulienDayNumber(julianDayNumber)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private static func fromJulienDayNumber(julianDayNumber: Double) -> Self? {
|
||||
// Conversion uses the same algorithm as SQLite: https://www.sqlite.org/src/artifact/8ec787fed4929d8c
|
||||
let JD = Int64(julianDayNumber * 86400000)
|
||||
let Z = Int(((JD + 43200000)/86400000))
|
||||
var A = Int(((Double(Z) - 1867216.25)/36524.25))
|
||||
A = Z + 1 + A - (A/4)
|
||||
let B = A + 1524
|
||||
let C = Int(((Double(B) - 122.1)/365.25))
|
||||
let D = (36525*(C&32767))/100
|
||||
let E = Int((Double(B-D)/30.6001))
|
||||
let X1 = Int((30.6001*Double(E)))
|
||||
let day = B - D - X1
|
||||
let month = E<14 ? E-1 : E-13
|
||||
let year = month>2 ? C - 4716 : C - 4715
|
||||
var s = Int(((JD + 43200000) % 86400000))
|
||||
var second = Double(s)/1000.0
|
||||
s = Int(second)
|
||||
second -= Double(s)
|
||||
let hour = s/3600
|
||||
s -= hour*3600
|
||||
let minute = s/60
|
||||
second += Double(s - minute*60)
|
||||
|
||||
let dateComponents = NSDateComponents()
|
||||
dateComponents.year = year
|
||||
dateComponents.month = month
|
||||
dateComponents.day = day
|
||||
dateComponents.hour = hour
|
||||
dateComponents.minute = minute
|
||||
dateComponents.second = Int(second)
|
||||
dateComponents.nanosecond = Int((second - Double(Int(second))) * 1.0e9)
|
||||
|
||||
let date = UTCCalendar.dateFromComponents(dateComponents)!
|
||||
return self.init(timeInterval: 0, sinceDate: date)
|
||||
}
|
||||
|
||||
private static func fromDatabaseDateComponents(databaseDateComponents: DatabaseDateComponents) -> Self? {
|
||||
guard databaseDateComponents.format.hasYMDComponents else {
|
||||
// Refuse to turn hours without any date information into NSDate:
|
||||
return nil
|
||||
}
|
||||
let date = UTCCalendar.dateFromComponents(databaseDateComponents.dateComponents)!
|
||||
return self.init(timeInterval: 0, sinceDate: date)
|
||||
}
|
||||
}
|
||||
|
||||
/// The DatabaseDate date formatter for stored dates.
|
||||
private let storageDateFormatter: NSDateFormatter = {
|
||||
let formatter = NSDateFormatter()
|
||||
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
|
||||
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
|
||||
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
|
||||
return formatter
|
||||
}()
|
||||
|
||||
// The NSCalendar for stored dates.
|
||||
private let UTCCalendar: NSCalendar = {
|
||||
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
|
||||
calendar.locale = NSLocale(localeIdentifier: "en_US_POSIX")
|
||||
calendar.timeZone = NSTimeZone(forSecondsFromGMT: 0)
|
||||
return calendar
|
||||
}()
|
||||
@@ -1,15 +1,15 @@
|
||||
import Foundation
|
||||
|
||||
/// NSNull adopts DatabaseValueConvertible
|
||||
extension NSNull: DatabaseValueConvertible {
|
||||
extension NSNull : DatabaseValueConvertible {
|
||||
|
||||
/// Returns DatabaseValue.Null.
|
||||
/// Returns DatabaseValue.null.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return .Null
|
||||
return .null
|
||||
}
|
||||
|
||||
/// Returns nil.
|
||||
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Self? {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -1,31 +1,46 @@
|
||||
import Foundation
|
||||
|
||||
private let integerRoundingBehavior = NSDecimalNumberHandler(roundingMode: .plain, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
|
||||
|
||||
/// NSNumber adopts DatabaseValueConvertible
|
||||
extension NSNumber: DatabaseValueConvertible {
|
||||
extension NSNumber : DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
switch String.fromCString(objCType)! {
|
||||
// Don't lose precision: store integers that fits in Int64 as Int64
|
||||
if let decimal = self as? NSDecimalNumber,
|
||||
decimal == decimal.rounding(accordingToBehavior: integerRoundingBehavior), // integer
|
||||
decimal.compare(NSDecimalNumber(value: Int64.max)) != .orderedDescending, // decimal <= Int64.max
|
||||
decimal.compare(NSDecimalNumber(value: Int64.min)) != .orderedAscending // decimal >= Int64.min
|
||||
{
|
||||
return int64Value.databaseValue
|
||||
}
|
||||
|
||||
switch String(cString: objCType) {
|
||||
case "c":
|
||||
return Int64(charValue).databaseValue
|
||||
return Int64(int8Value).databaseValue
|
||||
case "C":
|
||||
return Int64(unsignedCharValue).databaseValue
|
||||
return Int64(uint8Value).databaseValue
|
||||
case "s":
|
||||
return Int64(shortValue).databaseValue
|
||||
return Int64(int16Value).databaseValue
|
||||
case "S":
|
||||
return Int64(unsignedShortValue).databaseValue
|
||||
return Int64(uint16Value).databaseValue
|
||||
case "i":
|
||||
return Int64(intValue).databaseValue
|
||||
return Int64(int32Value).databaseValue
|
||||
case "I":
|
||||
return Int64(unsignedIntValue).databaseValue
|
||||
return Int64(uint32Value).databaseValue
|
||||
case "l":
|
||||
return Int64(longValue).databaseValue
|
||||
return Int64(intValue).databaseValue
|
||||
case "L":
|
||||
return Int64(unsignedLongValue).databaseValue
|
||||
let uint = uintValue
|
||||
GRDBPrecondition(UInt64(uint) <= UInt64(Int64.max), "could not convert \(uint) to an Int64 that can be stored in the database")
|
||||
return Int64(uint).databaseValue
|
||||
case "q":
|
||||
return Int64(longLongValue).databaseValue
|
||||
return Int64(int64Value).databaseValue
|
||||
case "Q":
|
||||
return Int64(unsignedLongLongValue).databaseValue
|
||||
let uint64 = uint64Value
|
||||
GRDBPrecondition(uint64 <= UInt64(Int64.max), "could not convert \(uint64) to an Int64 that can be stored in the database")
|
||||
return Int64(uint64).databaseValue
|
||||
case "f":
|
||||
return Double(floatValue).databaseValue
|
||||
case "d":
|
||||
@@ -33,17 +48,18 @@ extension NSNumber: DatabaseValueConvertible {
|
||||
case "B":
|
||||
return boolValue.databaseValue
|
||||
case let objCType:
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError("DatabaseValueConvertible: Unsupported NSNumber type: \(objCType)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an NSNumber initialized from *databaseValue*, if possible.
|
||||
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Self? {
|
||||
switch databaseValue.storage {
|
||||
case .Int64(let int64):
|
||||
return self.init(longLong: int64)
|
||||
case .Double(let double):
|
||||
return self.init(double: double)
|
||||
/// Returns an NSNumber initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64):
|
||||
return self.init(value: int64)
|
||||
case .double(let double):
|
||||
return self.init(value: double)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import Foundation
|
||||
|
||||
/// NSString adopts DatabaseValueConvertible
|
||||
extension NSString: DatabaseValueConvertible {
|
||||
extension NSString : DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return (self as String).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an NSString initialized from *databaseValue*, if possible.
|
||||
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Self? {
|
||||
guard let string = String.fromDatabaseValue(databaseValue) else {
|
||||
/// Returns an NSString initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
guard let string = String.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
}
|
||||
return self.init(string: string)
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
/// NSURL adopts DatabaseValueConvertible.
|
||||
extension NSURL : DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// (the URL's absoluteString).
|
||||
public var databaseValue: DatabaseValue {
|
||||
return absoluteString.databaseValue
|
||||
}
|
||||
|
||||
/// Returns an NSURL initialized from *databaseValue*, if possible.
|
||||
public static func fromDatabaseValue(databaseValue: DatabaseValue) -> Self? {
|
||||
guard let string = String.fromDatabaseValue(databaseValue) else {
|
||||
return nil
|
||||
}
|
||||
return self.init(string: string)
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
/// Foundation support for Row
|
||||
extension Row {
|
||||
|
||||
/// Builds a row from an NSDictionary.
|
||||
///
|
||||
/// The result is nil unless all dictionary keys are strings, and values
|
||||
/// adopt DatabaseValueConvertible (NSData, NSDate, NSNull, NSNumber,
|
||||
/// NSString, NSURL).
|
||||
public convenience init?(_ dictionary: NSDictionary) {
|
||||
var initDictionary = [String: DatabaseValueConvertible?]()
|
||||
for (key, value) in dictionary {
|
||||
guard let columnName = key as? String else {
|
||||
return nil
|
||||
}
|
||||
guard let databaseValue = DatabaseValue(object: value) else {
|
||||
return nil
|
||||
}
|
||||
initDictionary[columnName] = databaseValue
|
||||
}
|
||||
self.init(initDictionary)
|
||||
}
|
||||
|
||||
/// Converts a row to an NSDictionary.
|
||||
///
|
||||
/// When the row contains duplicated column names, the dictionary contains
|
||||
/// the value of the leftmost column.
|
||||
///
|
||||
/// - returns: An NSDictionary.
|
||||
public func toNSDictionary() -> NSDictionary {
|
||||
let dictionary = NSMutableDictionary(capacity: count)
|
||||
// Reverse so that the result dictionary contains values for the leftmost columns.
|
||||
for (columnName, databaseValue) in reverse() {
|
||||
dictionary[columnName] = databaseValue.toAnyObject()
|
||||
}
|
||||
return dictionary
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
extension StatementArguments {
|
||||
|
||||
// MARK: Positional Arguments
|
||||
|
||||
/// Initializes arguments from an NSArray.
|
||||
///
|
||||
/// The result is nil unless all objects adopt DatabaseValueConvertible
|
||||
/// (NSData, NSDate, NSNull, NSNumber, NSString, NSURL).
|
||||
///
|
||||
/// let values: NSArray = ["foo", "bar", "baz"]
|
||||
/// db.execute("INSERT ... (?,?,?)", arguments: StatementArguments(values)!)
|
||||
///
|
||||
/// - parameter array: An NSArray
|
||||
/// - returns: A StatementArguments.
|
||||
public init?(_ array: NSArray) {
|
||||
// IMPLEMENTATION NOTE
|
||||
//
|
||||
// This initializer is required for the following code to compile:
|
||||
//
|
||||
// let statement = try db.updateStatement("INSERT INTO persons (name, age) VALUES (?, ?)")
|
||||
// let persons = [ // NSArray of NSArray, actually
|
||||
// ["Arthur", 41],
|
||||
// ["Barbara", 38],
|
||||
// ]
|
||||
// for person in persons {
|
||||
// try statement.execute(StatementArguments(person)) // Avoid an error here
|
||||
// }
|
||||
var values = [DatabaseValueConvertible?]()
|
||||
for object in array {
|
||||
guard let databaseValue = DatabaseValue(object: object) else {
|
||||
return nil
|
||||
}
|
||||
values.append(databaseValue)
|
||||
}
|
||||
self.init(values)
|
||||
}
|
||||
|
||||
|
||||
// MARK: Named Arguments
|
||||
|
||||
/// Initializes arguments from an NSDictionary.
|
||||
///
|
||||
/// The result is nil unless all dictionary keys are strings, and values
|
||||
/// adopt DatabaseValueConvertible (NSData, NSDate, NSNull, NSNumber,
|
||||
/// NSString, NSURL).
|
||||
///
|
||||
/// let values: NSDictionary = ["firstName": "Arthur", "lastName": "Miller"]
|
||||
/// db.execute("INSERT ... (?,?,?)", arguments: StatementArguments(values)!)
|
||||
///
|
||||
/// - parameter dictionary: An NSDictionary
|
||||
/// - returns: A StatementArguments.
|
||||
public init?(_ dictionary: NSDictionary) {
|
||||
// IMPLEMENTATION NOTE
|
||||
//
|
||||
// This initializer is required for the following code to compile:
|
||||
//
|
||||
// let statement = try db.updateStatement("INSERT INTO persons (name, age) VALUES (:name, :age)")
|
||||
// let persons = [ // NSArray of NSDictionary, actually
|
||||
// ["name": "Arthur", "age": 41],
|
||||
// ["name": "Barbara", "age": 38],
|
||||
// ]
|
||||
// for person in persons {
|
||||
// try statement.execute(StatementArguments(person)) // Avoid an error here
|
||||
// }
|
||||
var initDictionary = [String: DatabaseValueConvertible?]()
|
||||
for (key, value) in dictionary {
|
||||
guard let columnName = key as? String else {
|
||||
return nil
|
||||
}
|
||||
guard let databaseValue = DatabaseValue(object: value) else {
|
||||
return nil
|
||||
}
|
||||
initDictionary[columnName] = databaseValue
|
||||
}
|
||||
self.init(initDictionary)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import Foundation
|
||||
|
||||
/// NSURL stores its absoluteString in the database.
|
||||
extension NSURL : DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// (the URL's absoluteString).
|
||||
public var databaseValue: DatabaseValue {
|
||||
return absoluteString?.databaseValue ?? .null
|
||||
}
|
||||
|
||||
/// Returns an NSURL initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
guard let string = String.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
}
|
||||
return cast(URL(string: string))
|
||||
}
|
||||
}
|
||||
|
||||
/// URL stores its absoluteString in the database.
|
||||
extension URL : DatabaseValueConvertible { }
|
||||
@@ -0,0 +1,25 @@
|
||||
import Foundation
|
||||
|
||||
/// NSUUID adopts DatabaseValueConvertible
|
||||
extension NSUUID : DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
var uuidBytes = ContiguousArray(repeating: UInt8(0), count: 16)
|
||||
return uuidBytes.withUnsafeMutableBufferPointer { buffer in
|
||||
getBytes(buffer.baseAddress!)
|
||||
return NSData(bytes: buffer.baseAddress, length: 16).databaseValue
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an NSUUID initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
guard let data = NSData.fromDatabaseValue(dbValue), data.length == 16 else {
|
||||
return nil
|
||||
}
|
||||
return self.init(uuidBytes: data.bytes.assumingMemoryBound(to: UInt8.self))
|
||||
}
|
||||
}
|
||||
|
||||
/// UUID adopts DatabaseValueConvertible
|
||||
extension UUID : DatabaseValueConvertible { }
|
||||
@@ -0,0 +1,91 @@
|
||||
private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer {
|
||||
let dbValue: DatabaseValue
|
||||
let codingPath: [CodingKey]
|
||||
|
||||
/// Decodes a null value.
|
||||
///
|
||||
/// - returns: Whether the encountered value was null.
|
||||
func decodeNil() -> Bool {
|
||||
return dbValue.isNull
|
||||
}
|
||||
|
||||
/// Decodes a single value of the given type.
|
||||
///
|
||||
/// - parameter type: The type to decode as.
|
||||
/// - returns: A value of the requested type.
|
||||
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type.
|
||||
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
|
||||
func decode(_ type: Bool.Type) throws -> Bool { return dbValue.losslessConvert() }
|
||||
func decode(_ type: Int.Type) throws -> Int { return dbValue.losslessConvert() }
|
||||
func decode(_ type: Int8.Type) throws -> Int8 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: Int16.Type) throws -> Int16 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: Int32.Type) throws -> Int32 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: Int64.Type) throws -> Int64 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: UInt.Type) throws -> UInt { return dbValue.losslessConvert() }
|
||||
func decode(_ type: UInt8.Type) throws -> UInt8 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: UInt16.Type) throws -> UInt16 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: UInt32.Type) throws -> UInt32 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: UInt64.Type) throws -> UInt64 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: Float.Type) throws -> Float { return dbValue.losslessConvert() }
|
||||
func decode(_ type: Double.Type) throws -> Double { return dbValue.losslessConvert() }
|
||||
func decode(_ type: String.Type) throws -> String { return dbValue.losslessConvert() }
|
||||
|
||||
/// Decodes a single value of the given type.
|
||||
///
|
||||
/// - parameter type: The type to decode as.
|
||||
/// - returns: A value of the requested type.
|
||||
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value 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 {
|
||||
// Prefer DatabaseValueConvertible decoding over Decodable.
|
||||
// This allows custom database decoding, such as decoding Date from
|
||||
// String, for example.
|
||||
return type.fromDatabaseValue(dbValue) as! T
|
||||
} else {
|
||||
return try T(from: DatabaseValueDecoder(dbValue: dbValue, codingPath: codingPath))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct DatabaseValueDecoder: Decoder {
|
||||
let dbValue: DatabaseValue
|
||||
|
||||
init(dbValue: DatabaseValue, codingPath: [CodingKey]) {
|
||||
self.dbValue = dbValue
|
||||
self.codingPath = codingPath
|
||||
}
|
||||
|
||||
// Decoder
|
||||
let codingPath: [CodingKey]
|
||||
var userInfo: [CodingUserInfoKey : Any] { return [:] }
|
||||
|
||||
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
|
||||
throw DecodingError.typeMismatch(
|
||||
type,
|
||||
DecodingError.Context(codingPath: codingPath, debugDescription: "keyed decoding is not supported"))
|
||||
}
|
||||
|
||||
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
|
||||
throw DecodingError.typeMismatch(
|
||||
UnkeyedDecodingContainer.self,
|
||||
DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported"))
|
||||
}
|
||||
|
||||
func singleValueContainer() throws -> SingleValueDecodingContainer {
|
||||
return DatabaseValueDecodingContainer(dbValue: dbValue, codingPath: codingPath)
|
||||
}
|
||||
}
|
||||
|
||||
public extension DatabaseValueConvertible where Self: Decodable {
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
return try? self.init(from: DatabaseValueDecoder(dbValue: databaseValue, codingPath: []))
|
||||
}
|
||||
}
|
||||
|
||||
public extension DatabaseValueConvertible where Self: Decodable & RawRepresentable, Self.RawValue: DatabaseValueConvertible {
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
// Preserve custom database decoding
|
||||
return RawValue.fromDatabaseValue(databaseValue).flatMap { self.init(rawValue: $0) }
|
||||
}
|
||||
}
|
||||
Loaded 100 of 466 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user