mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-06 05:28:44 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
baeba0dea3 | ||
|
|
3dc31ad638 | ||
|
|
4201e2a611 | ||
|
|
d9f6fa7de6 | ||
|
|
d0146762bc | ||
|
|
7e8f2e2fbc | ||
|
|
497f4b65ef | ||
|
|
03c44778ba | ||
|
|
0cc744ae16 | ||
|
|
fae3862547 | ||
|
|
70a222f3c9 | ||
|
|
5676adca99 | ||
|
|
3a77ca68c4 | ||
|
|
248437d1d6 | ||
|
|
afcde4609e | ||
|
|
2e98974373 | ||
|
|
086a33fd62 | ||
|
|
33359dd435 | ||
|
|
574d71b50c | ||
|
|
c806b706d4 | ||
|
|
c3b8c0f7e9 | ||
|
|
a1cd622892 | ||
|
|
dea3ee0b84 | ||
|
|
5c64348ea8 | ||
|
|
262ac2c476 | ||
|
|
dbfbe30749 | ||
|
|
70437bd4cb | ||
|
|
2d30b5ea1c | ||
|
|
5414111bed | ||
|
|
9168bac16e | ||
|
|
8760d36f6c | ||
|
|
141b870bc0 | ||
|
|
5e4406e78c | ||
|
|
c5426bfcf7 | ||
|
|
76561a567f | ||
|
|
8288f0c751 | ||
|
|
7dc008db8b | ||
|
|
86bb4a27a4 | ||
|
|
f2d9f50930 | ||
|
|
b9af7e6a25 | ||
|
|
00825748ff | ||
|
|
fe0edde4a9 | ||
|
|
edfea91920 | ||
|
|
319e6bcdc8 | ||
|
|
274f73e040 | ||
|
|
fab37838b2 | ||
|
|
a5a3610bf6 | ||
|
|
07e600163c | ||
|
|
14a5dc5489 | ||
|
|
46c2b94425 | ||
|
|
9a1dc7f292 | ||
|
|
c68fc37959 | ||
|
|
aa1f555e05 | ||
|
|
699e64c610 | ||
|
|
e8c1392314 | ||
|
|
c1ae47d188 | ||
|
|
13a9f1113a | ||
|
|
c4ad86863f | ||
|
|
8300a618f8 | ||
|
|
52f0038262 | ||
|
|
31710ce91c | ||
|
|
a9c75652e1 | ||
|
|
3e13e5be57 | ||
|
|
c27979a210 | ||
|
|
37d7c84bc3 | ||
|
|
62f5c8fc2f | ||
|
|
289c449dff | ||
|
|
e7b7b603d2 | ||
|
|
e7e342600b | ||
|
|
db6e3b8371 | ||
|
|
79ed15c38c | ||
|
|
6f175dcafb | ||
|
|
ca70a10bd4 | ||
|
|
ae3319e9f9 | ||
|
|
5112cb24f5 | ||
|
|
c6bbccc02e | ||
|
|
93ec4d2515 | ||
|
|
955dc6094b | ||
|
|
bd694cbc53 | ||
|
|
c115a035ec | ||
|
|
288144f347 | ||
|
|
3bdfdaa40a | ||
|
|
22949813af | ||
|
|
5c98b01484 | ||
|
|
ea5e1cd0db | ||
|
|
b5d9955442 | ||
|
|
feb5cb35b4 | ||
|
|
654c7083eb | ||
|
|
a0457928b3 | ||
|
|
4df535a3a9 | ||
|
|
0b251ec4e0 | ||
|
|
7704a9ac41 | ||
|
|
59031893ff | ||
|
|
fcfa044320 | ||
|
|
f95658e7ce | ||
|
|
2c16fcaa99 | ||
|
|
4e638016e1 | ||
|
|
5d811c0e68 | ||
|
|
9f1f51637a | ||
|
|
7c16ffcdf8 | ||
|
|
7ca582719b | ||
|
|
e4b83baa53 | ||
|
|
ac6b2933a8 | ||
|
|
92758fa51d | ||
|
|
acd06a4f5a | ||
|
|
eec6b17398 | ||
|
|
15fbf02647 | ||
|
|
c296be5057 | ||
|
|
129e178ee0 | ||
|
|
1e5caa62a8 | ||
|
|
420ed0764b | ||
|
|
ce6bbb2885 | ||
|
|
87d6c5dd29 | ||
|
|
dccd456497 | ||
|
|
520bdd64e6 | ||
|
|
72608fd016 | ||
|
|
69b51ffbd5 | ||
|
|
c9044ea07b | ||
|
|
362c40326f | ||
|
|
28d0793688 | ||
|
|
abdc2000c4 | ||
|
|
3d845b1e9f | ||
|
|
bae8c97df4 | ||
|
|
452c1d4b92 | ||
|
|
9990e6e2a6 | ||
|
|
8d0dc3eb78 | ||
|
|
0a2a3c75c1 | ||
|
|
830e6acb4f | ||
|
|
1da85dff58 | ||
|
|
dd40e3be5b | ||
|
|
224d6488a9 | ||
|
|
cac31d3294 | ||
|
|
951d5fa58d | ||
|
|
7a4f0778df | ||
|
|
5aff4d29fc | ||
|
|
402b7001ee | ||
|
|
f7d0979fb1 | ||
|
|
2289ed9d95 | ||
|
|
dfcb44016f | ||
|
|
37a434a615 | ||
|
|
0ddcf1e401 | ||
|
|
0aa673f24e | ||
|
|
b3a24daa2f | ||
|
|
8c6954cd75 | ||
|
|
283f08de07 | ||
|
|
d96543ddeb | ||
|
|
4b320f3cb5 | ||
|
|
69a6d3e3f3 | ||
|
|
93d4587732 | ||
|
|
7481b9788a | ||
|
|
acf3e0b397 | ||
|
|
88ae0fa059 | ||
|
|
a1e63d9028 | ||
|
|
2a1ad8d31c | ||
|
|
ba7cd2160f | ||
|
|
8e50383371 | ||
|
|
ffc5352840 | ||
|
|
53e849cbec | ||
|
|
b71d57d7ec | ||
|
|
4fe2b2542f | ||
|
|
8c7895d8ab | ||
|
|
ad15f4dc59 | ||
|
|
c4ef161a83 | ||
|
|
bb48025947 | ||
|
|
389a7f28c4 | ||
|
|
714cc1c734 | ||
|
|
8d0da7f870 | ||
|
|
e42e74103d | ||
|
|
4bcdb91895 | ||
|
|
938977bbca | ||
|
|
581c1c46e2 | ||
|
|
768b2ab620 | ||
|
|
4eff5ab357 | ||
|
|
888892b92f | ||
|
|
ba4f146c9c | ||
|
|
8359dd2ae2 | ||
|
|
0be80db8f9 | ||
|
|
72de142519 | ||
|
|
0a7468f56d | ||
|
|
33b5c6c616 | ||
|
|
4003d7600d | ||
|
|
a7122ba8bb | ||
|
|
dc8c85d3db | ||
|
|
fc1b4a6f35 | ||
|
|
af42623654 | ||
|
|
ab1a672336 | ||
|
|
4501d7dcde | ||
|
|
5d463d6bff | ||
|
|
9c8a9fbe32 | ||
|
|
1a89b2eae5 | ||
|
|
fd65e72bbb | ||
|
|
33e8d0875d | ||
|
|
19e75576a8 | ||
|
|
980860b2e9 | ||
|
|
eee3e36238 | ||
|
|
eaadd37e87 | ||
|
|
a1e508b1df | ||
|
|
2c8f9dffdd | ||
|
|
92fd3bf8ae | ||
|
|
c940675bf3 | ||
|
|
2a147d5029 | ||
|
|
0d236ae32c | ||
|
|
cf4654108e | ||
|
|
7e9eed9374 | ||
|
|
383581938a | ||
|
|
df50da9024 | ||
|
|
d3a65303a1 | ||
|
|
9a2bf923d2 | ||
|
|
9b27c0c651 | ||
|
|
2af85e7347 | ||
|
|
071f0f4443 | ||
|
|
903e8c96aa | ||
|
|
79a5fb9c15 | ||
|
|
46ef4b27bb | ||
|
|
1838797d38 | ||
|
|
c7d500b8ba | ||
|
|
95a09cb644 | ||
|
|
c6ab92e60a | ||
|
|
c0d5f3019b | ||
|
|
b09d5c3833 | ||
|
|
3eff1b48b1 | ||
|
|
a12fffc4e7 | ||
|
|
94715130fc | ||
|
|
313188ca0e | ||
|
|
5a68b008c6 | ||
|
|
6fe9098c76 | ||
|
|
631a914acd | ||
|
|
d1f24c9722 | ||
|
|
7b76c9319a | ||
|
|
63083c5d1e | ||
|
|
c51a3cd624 | ||
|
|
1fadb7485a | ||
|
|
58e05d13d1 | ||
|
|
d8c9692d4d | ||
|
|
f83ffd3a25 | ||
|
|
d12ff2a92b | ||
|
|
8709d6f9a9 | ||
|
|
e2806c55ff | ||
|
|
08d6c843d6 | ||
|
|
0da3726a89 | ||
|
|
36676bcad3 | ||
|
|
1509e1e9a8 | ||
|
|
4c71dd9ebe | ||
|
|
ef8d0d6334 | ||
|
|
7477b7a173 | ||
|
|
246f36821b | ||
|
|
d567ee60bf | ||
|
|
3a157d2808 | ||
|
|
7d0c2f9ef8 | ||
|
|
f356f8734a | ||
|
|
5b7f4a7ff5 | ||
|
|
e10efca17a | ||
|
|
578b9a5275 | ||
|
|
63304b3d12 | ||
|
|
39f6ca0035 | ||
|
|
5e3c62c963 | ||
|
|
6966600223 | ||
|
|
e028cbb6d5 | ||
|
|
8b3c3f48a8 | ||
|
|
2d84e72097 | ||
|
|
d91fe7b633 | ||
|
|
090df10831 | ||
|
|
f21037bb69 | ||
|
|
f3041bcc9a | ||
|
|
67b1225dfa | ||
|
|
23f2e0371e | ||
|
|
a3d8df222f | ||
|
|
632ef3707c | ||
|
|
79dc099e6d | ||
|
|
75035fb40c | ||
|
|
b4887b661c | ||
|
|
e8835af363 | ||
|
|
1fabe08332 | ||
|
|
c2e3638e8d | ||
|
|
71abced420 | ||
|
|
ac00046b07 | ||
|
|
38b5204713 | ||
|
|
4b173dece5 | ||
|
|
8ce2c09b52 | ||
|
|
8125574f8f | ||
|
|
8974360cac | ||
|
|
6e48cc1524 | ||
|
|
a1ea75ca34 | ||
|
|
81d2f21093 | ||
|
|
fd73a31abc | ||
|
|
1583ac0c08 | ||
|
|
cafbecd8af | ||
|
|
78c36612b7 | ||
|
|
a95385c740 | ||
|
|
a58ebf7c48 | ||
|
|
13623575ff | ||
|
|
87c5f913b8 | ||
|
|
41172d7967 | ||
|
|
820bc87cfe | ||
|
|
2901acfb41 | ||
|
|
681460a415 | ||
|
|
19b067405f | ||
|
|
3b494b5737 | ||
|
|
5f11a19296 | ||
|
|
3ff7675eb7 | ||
|
|
3d06841eba | ||
|
|
188c026c6b | ||
|
|
caf051f19d | ||
|
|
c4a3d934a9 | ||
|
|
b19424aa23 | ||
|
|
bc229fa6fd | ||
|
|
9beb5b553b | ||
|
|
667e6a8e06 | ||
|
|
8f9b667c29 | ||
|
|
a8e0c76a30 | ||
|
|
49609ff08e | ||
|
|
efe201e032 | ||
|
|
28c903f7ea | ||
|
|
a5b45031d2 | ||
|
|
42e178b41d | ||
|
|
c3fe2c13f4 | ||
|
|
af8a6872d9 | ||
|
|
f40a5e68ea | ||
|
|
c4ad98426c | ||
|
|
a0e3d4ad69 | ||
|
|
d64bfe1cec | ||
|
|
8a213af2ab | ||
|
|
f02659e5d7 | ||
|
|
bdf943c3d9 | ||
|
|
9f1d5bc631 | ||
|
|
f2b46679a6 | ||
|
|
c5f38af247 | ||
|
|
2bfef4f02d | ||
|
|
07ae50cbb0 | ||
|
|
7f10bf4005 | ||
|
|
9130fe7b38 | ||
|
|
340dcd1748 | ||
|
|
8919bb5810 | ||
|
|
bea98db813 | ||
|
|
05a0130c1e | ||
|
|
e486437865 | ||
|
|
1043516fb7 | ||
|
|
c9b8b81ffb | ||
|
|
99b143a55c | ||
|
|
8401f42f3e | ||
|
|
f69949edea | ||
|
|
62e33f294e | ||
|
|
2a8e48ba63 | ||
|
|
6372bf663f | ||
|
|
ac7cc09bfe | ||
|
|
c9f0d473cf | ||
|
|
8a7ffdbb67 | ||
|
|
d30baaf16c | ||
|
|
1981adeb22 | ||
|
|
8427b8b668 | ||
|
|
6db590a31b | ||
|
|
22faa03a48 | ||
|
|
d3cd0ae85a | ||
|
|
b624955bf3 | ||
|
|
1b20cd14d1 | ||
|
|
baf2f780c9 | ||
|
|
9d1997b6cd | ||
|
|
313baa0064 | ||
|
|
006eee9f51 | ||
|
|
2720caf945 | ||
|
|
62faa57bf0 | ||
|
|
abbdb995e6 | ||
|
|
fd2ae60a65 | ||
|
|
2c4cf2d06b | ||
|
|
0f5ec15d47 | ||
|
|
1c3dfb346f | ||
|
|
b76013d60b | ||
|
|
e3ed95571c | ||
|
|
c749893858 | ||
|
|
9135be3da6 | ||
|
|
9930fd3938 | ||
|
|
c62c3df00d | ||
|
|
0419d67533 | ||
|
|
32d69c5be0 | ||
|
|
c2fb23c69c | ||
|
|
47611e14f7 | ||
|
|
b90f876b5b | ||
|
|
9037d51bc7 | ||
|
|
fb8c68f5e0 | ||
|
|
4995b5bb8c | ||
|
|
c87ebfd4eb |
No files matched your search
+115
-51
@@ -1,3 +1,6 @@
|
||||
# The OS X Build Environment
|
||||
# https://docs.travis-ci.com/user/reference/osx/#Xcode-version
|
||||
|
||||
language: objective-c
|
||||
xcode_project: GRDB.xcodeproj
|
||||
|
||||
@@ -12,140 +15,201 @@ jobs:
|
||||
###########################################
|
||||
## Test GRDB
|
||||
|
||||
# Test GRDBOSX (Xcode 9)
|
||||
# Test GRDBOSX (Xcode 9.2)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=GRDBOSX (Xcode 9, macOS 10.12)
|
||||
- TID=GRDBOSX (Xcode 9.2, macOS)
|
||||
script: make test_framework_GRDBOSX
|
||||
|
||||
# Test GRDBWatchOS (Xcode 9)
|
||||
# Test GRDBWatchOS (Xcode 9.2)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=GRDBWatchOS (Xcode 9, watchOS)
|
||||
- TID=GRDBWatchOS (Xcode 9.2, watchOS)
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
# Test GRDBiOS (Xcode 9, iOS <MAXIMUM VERSION>)
|
||||
# Test GRDBiOS (Xcode 9.2, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=GRDBiOS (Xcode 9, iOS <MAX>)
|
||||
- TID=GRDBiOS (Xcode 9.2, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget
|
||||
|
||||
# Test GRDBiOS (Xcode 9, iOS <MINIMUM VERSION>))
|
||||
# Test GRDBiOS (Xcode 9.2, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=GRDBiOS (Xcode 9, iOS <MIN>)
|
||||
- TID=GRDBiOS (Xcode 9.2, iOS <MIN>)
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
# Test GRDB [SPM] (Xcode 9, macOS 10.12)
|
||||
# Test GRDB [SPM] (Xcode 9.2, macOS)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=GRDB [SPM] (Xcode 9.2, macOS)
|
||||
script: make test_SPM
|
||||
|
||||
# Test GRDBOSX (Xcode 9.0)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDB [SPM] (Xcode 9, macOS 10.12)
|
||||
script: make test_SPM
|
||||
- TID=GRDBOSX (Xcode 9.0, macOS)
|
||||
script: make test_framework_GRDBOSX
|
||||
|
||||
# Test GRDBiOS (Xcode 9.0, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBiOS (Xcode 9.0, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget
|
||||
|
||||
###########################################
|
||||
## Test GRDB (Custom SQLite)
|
||||
|
||||
# Test GRDBCustomSQLiteOSX (Xcode 9)
|
||||
# Test GRDBCustomSQLiteOSX (Xcode 9.2)
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteOSX (Xcode 9, macOS 10.12)
|
||||
- TID=GRDBCustomSQLiteOSX (Xcode 9.2, macOS)
|
||||
script: make test_framework_GRDBCustomSQLiteOSX
|
||||
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 9, iOS <MAXIMUM VERSION>)
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 9.2, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 9, iOS <MAX>)
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 9.2, iOS <MAX>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget
|
||||
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 9, iOS <MINIMUM VERSION>))
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 9.2, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 9.2, iOS <MIN>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
|
||||
|
||||
# Test GRDBCustomSQLiteOSX (Xcode 9.0)
|
||||
- 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
|
||||
- TID=GRDBCustomSQLiteOSX (Xcode 9.0, macOS)
|
||||
script: make test_framework_GRDBCustomSQLiteOSX
|
||||
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 9.0, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 9.0, iOS <MAX>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget
|
||||
|
||||
###########################################
|
||||
## Test GRDB (SQLCipher)
|
||||
|
||||
# Test GRDBCipherOSX (Xcode 9)
|
||||
# Test GRDBCipherOSX (Xcode 9.2)
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=GRDBCipherOSX (Xcode 9, macOS 10.12)
|
||||
- TID=GRDBCipherOSX (Xcode 9.2, macOS)
|
||||
script: make test_framework_GRDBCipherOSX
|
||||
|
||||
# Test GRDBCipheriOS (Xcode 9, iOS <MAXIMUM VERSION>)
|
||||
# Test GRDBCipheriOS (Xcode 9.2, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=GRDBCipheriOS (Xcode 9, iOS <MAX>)
|
||||
- TID=GRDBCipheriOS (Xcode 9.2, iOS <MAX>)
|
||||
script: make test_framework_GRDBCipheriOS_maxTarget
|
||||
|
||||
# Test GRDBCipheriOS (Xcode 9, iOS <MINIMUM VERSION>))
|
||||
# Test GRDBCipheriOS (Xcode 9.2, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=GRDBCipheriOS (Xcode 9.2, iOS <MIN>)
|
||||
script: make test_framework_GRDBCipheriOS_minTarget
|
||||
|
||||
# Test GRDBCipherOSX (Xcode 9.0)
|
||||
- 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
|
||||
- TID=GRDBCipherOSX (Xcode 9.0, macOS)
|
||||
script: make test_framework_GRDBCipherOSX
|
||||
|
||||
# Test GRDBCipheriOS (Xcode 9.0, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBCipheriOS (Xcode 9.0, iOS <MAX>)
|
||||
script: make test_framework_GRDBCipheriOS_maxTarget
|
||||
|
||||
|
||||
###########################################
|
||||
## Test Installation Methods
|
||||
|
||||
# Manual Install
|
||||
# Manual Install (Xcode 9.2)
|
||||
- stage: Test Installation
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=Manual Install
|
||||
- TID=Manual Install (Xcode 9.2)
|
||||
script: make test_install_manual
|
||||
|
||||
# Manual Install (GRDBCipher)
|
||||
# Manual Install (GRDBCipher, Xcode 9.2)
|
||||
- stage: Test Installation
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=Manual Install (GRDBCipher)
|
||||
- TID=Manual Install (GRDBCipher, Xcode 9.2)
|
||||
script: make test_install_GRDBCipher
|
||||
|
||||
# Cocoapods Lint
|
||||
# Cocoapods Lint (Xcode 9.2)
|
||||
- stage: Test Installation
|
||||
osx_image: xcode9.2
|
||||
install:
|
||||
- gem install cocoapods # Since Travis is not always on latest version
|
||||
env:
|
||||
- TID=Cocoapods (Xcode 9.2)
|
||||
script: make test_CocoaPodsLint
|
||||
|
||||
# Cocoapods Lint (Xcode 9.0)
|
||||
- stage: Test Installation
|
||||
osx_image: xcode9
|
||||
install:
|
||||
- gem install cocoapods # Since Travis is not always on latest version
|
||||
env:
|
||||
- TID=Cocoapods
|
||||
- TID=Cocoapods (Xcode 9.0)
|
||||
script: make test_CocoaPodsLint
|
||||
|
||||
# SPM Install
|
||||
# SPM Install (Xcode 9.2)
|
||||
- stage: Test Installation
|
||||
osx_image: xcode9
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=SPM
|
||||
- TID=SPM (Xcode 9.2)
|
||||
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
|
||||
## Commented out until `make test_CarthageBuild` performs *reliably*.
|
||||
## See https://github.com/groue/GRDB.swift/pull/262
|
||||
# - stage: Test Installation
|
||||
# osx_image: xcode9.2
|
||||
# before_install:
|
||||
# - brew update
|
||||
# - brew outdated carthage || brew upgrade carthage
|
||||
# env:
|
||||
# - TID=Carthages
|
||||
# script: make test_CarthageBuild
|
||||
+455
-2
@@ -1,6 +1,459 @@
|
||||
Release Notes
|
||||
=============
|
||||
|
||||
## 2.9.0
|
||||
|
||||
Released February 25, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v2.8.0...v2.9.0)
|
||||
|
||||
### New
|
||||
|
||||
- **Changes tracking overhaul**: changes tracking, a feature previously restricted to the `Record` class and its subclasses, is now available for all records. And it has a better looking API ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#changes-tracking)).
|
||||
- **Database snapshots**: Database pools can now take database snapshots. A snapshot sees an unchanging database content, as it existed at the moment the snapshot was created ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#database-snapshots)).
|
||||
- **Improved support for joined queries**: more than a set on new APIs, we provide a set of guidelines that will help you deal with your wildest joined queries. Check the new [Joined Queries Support](https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support) documentation chapter.
|
||||
- `Database.columns(in:)` returns information about the columns of a table.
|
||||
- `Request.adapted(_:)` is no longer experimental.
|
||||
- `Configuration.allowsUnsafeTransactions` lets you leave transactions opened between two database accesses (see below).
|
||||
- Support for explicit transaction management, via the new `Database.beginTransaction`, `commit`, and `rollback` methods.
|
||||
|
||||
|
||||
### Fixed
|
||||
|
||||
- It is now a programmer error to leave a transaction opened at the end of a database access block:
|
||||
|
||||
```swift
|
||||
// Fatal error: A transaction has been left opened at the end of a database access
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.beginTransaction()
|
||||
}
|
||||
```
|
||||
|
||||
One can still opt-in for the unsafe behavior by setting the new `allowsUnsafeTransactions` configuration flag:
|
||||
|
||||
```swift
|
||||
var config = Configuration()
|
||||
config.allowsUnsafeTransactions = true
|
||||
let dbQueue = DatabaseQueue(configuration: config)
|
||||
|
||||
// OK
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.beginTransaction()
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Deprecated
|
||||
|
||||
- `Database.columnCount(in:)` is deprecated. Use `db.columns(in:).count` instead.
|
||||
- `RecordBox`, introduced in [2.7.0](#270), was ill-advised. It has been deprecated. Use [changes tracking](https://github.com/groue/GRDB.swift/blob/master/README.md#changes-tracking) methods on the Persistable protocol instead.
|
||||
- `Record.hasPersistentChangedValues` has been deprecated, renamed `hasDatabaseChanges`.
|
||||
- `Record.persistentChangedValues` has been deprecated, renamed `databaseChanges`.
|
||||
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
- The [Changes Tracking](https://github.com/groue/GRDB.swift/blob/master/README.md#changes-tracking) chapter has been updated for the new universal support for record changes.
|
||||
- A new [Database Snapshots](https://github.com/groue/GRDB.swift/blob/master/README.md#database-snapshots) chapter has been added.
|
||||
- The [Concurrency](https://github.com/groue/GRDB.swift/blob/master/README.md#concurrency) chapter has been updated for database snapshots.
|
||||
- A new [Differences between Database Queues and Pools](https://github.com/groue/GRDB.swift/blob/master/README.md#differences-between-database-queues-and-pools) chapter has been added, that attempts at visually show how much database pools are different from database queues.
|
||||
- A new [Joined Queries Support](https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support) chapter has been added.
|
||||
- The [Row Adapters](https://github.com/groue/GRDB.swift/blob/master/README.md#row-adapters) chapter has been made consistent with the new chapter on joined queries.
|
||||
- The [Codable Records](https://github.com/groue/GRDB.swift/blob/master/README.md#codable-records) chapter has been made consistent with the new chapter on joined queries.
|
||||
- The [Database Schema Introspection](https://github.com/groue/GRDB.swift/blob/master/README.md#database-schema-introspection) has been updated for `Database.columns(in:)`
|
||||
|
||||
|
||||
### API diff
|
||||
|
||||
```diff
|
||||
+struct ColumnInfo {
|
||||
+ let name: String
|
||||
+ let type: String
|
||||
+ let isNotNull: Bool
|
||||
+ let defaultValueSQL: String?
|
||||
+ let primaryKeyIndex: Int
|
||||
+}
|
||||
|
||||
struct Configuration {
|
||||
+ var allowsUnsafeTransactions: Bool
|
||||
}
|
||||
|
||||
class Database {
|
||||
+ @available(*, deprecated, message: "Use db.columns(in: tableName).count instead")
|
||||
func columnCount(in tableName: String) throws -> Int
|
||||
+ func columns(in tableName: String) throws -> [ColumnInfo]
|
||||
+ func beginTransaction(_ kind: TransactionKind? = nil) throws
|
||||
+ func rollback() throws
|
||||
+ func commit() throws
|
||||
}
|
||||
|
||||
class DatabasePool {
|
||||
+ func makeSnapshot() throws -> DatabaseSnapshot
|
||||
}
|
||||
|
||||
+class DatabaseSnapshot: DatabaseReader { }
|
||||
|
||||
extension MutablePersistable {
|
||||
+ @discardableResult
|
||||
+ func updateChanges(_ db: Database, from record: MutablePersistable) throws -> Bool
|
||||
+ func databaseEqual(_ record: Self) -> Bool
|
||||
+ func databaseChanges(from record: MutablePersistable) -> [String: DatabaseValue]
|
||||
}
|
||||
class Record {
|
||||
- final func updateChanges(_ db: Database) throws
|
||||
+ @discardableResult
|
||||
+ final func updateChanges(_ db: Database) throws -> Bool
|
||||
}
|
||||
|
||||
+@available(*, deprecated, message: "Prefer changes methods defined on the MutablePersistable protocol: databaseEqual(_:), databaseChanges(from:), updateChanges(from:)")
|
||||
class RecordBox: Record { }
|
||||
|
||||
class Row {
|
||||
+ var unscoped: Row
|
||||
+ var containsNonNullValue: Bool
|
||||
+ func hasNull(atIndex index: Int) -> Bool
|
||||
+ subscript<Record: RowConvertible>(_ scope: String) -> Record
|
||||
+ subscript<Record: RowConvertible>(_ scope: String) -> Record?
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
+ static func selectionSQL(alias: String? = nil) -> String
|
||||
+ static func numberOfSelectedColumns(_ db: Database) throws -> Int
|
||||
}
|
||||
|
||||
+struct EmptyRowAdapter: RowAdapter { }
|
||||
|
||||
struct ScopeAdapter {
|
||||
+ init(base: RowAdapter, scopes: [String: RowAdapter])
|
||||
}
|
||||
|
||||
+func splittingRowAdapters(columnCounts: [Int]) -> [RowAdapter]
|
||||
```
|
||||
|
||||
|
||||
## 2.8.0
|
||||
|
||||
Released January 29, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v2.7.0...v2.8.0)
|
||||
|
||||
**New**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.22.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- The FTS5 full-text search engine has been enhanced with [initial token queries](https://sqlite.org/fts5.html#carrotq), and FTS5Pattern has gained a new initializer: `FTS5Pattern(matchingPrefixPhrase:)`
|
||||
- The `Cursor` protocol is extended with more methods inspired by the standard Sequence protocol: `drop(while:)`, `dropFirst()`, `dropFirst(_:)`, `dropLast()`, `dropLast(_:)`, `joined(separator:)`, `prefix(_:)`, `max()`, `max(by:)`, `min()`, `min(by:)`, `prefix(while:)`, `reduce(into:_:)`, `suffix(_:)`,
|
||||
|
||||
|
||||
## 2.7.0
|
||||
|
||||
Released January 21, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v2.6.1...v2.7.0)
|
||||
|
||||
**New**
|
||||
|
||||
- The new RecordBox class brings changes tracking to any record type ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#recordbox-class)):
|
||||
|
||||
```swift
|
||||
// A regular record struct
|
||||
struct Player: RowConvertible, MutablePersistable { ... }
|
||||
|
||||
try dbQueue.inDatabase { db in
|
||||
// Fetch a boxed player
|
||||
if let boxedPlayer = try RecordBox<Player>.fetchOne(db, key: 1) {
|
||||
// boxedPlayer.value is Player
|
||||
boxedPlayer.value.score = 300
|
||||
|
||||
if boxedPlayer.hasPersistentChangedValues {
|
||||
print("player has been modified")
|
||||
}
|
||||
|
||||
// Does nothing if player has not been modified:
|
||||
try boxedPlayer.updateChanges(db)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 2.6.1
|
||||
|
||||
Released January 19, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v2.6.0...v2.6.1)
|
||||
|
||||
**Fixed**
|
||||
|
||||
- Fixed a crash that could happen when a transaction observer uses the `stopObservingDatabaseChangesUntilNextTransaction()` method.
|
||||
|
||||
|
||||
## 2.6.0
|
||||
|
||||
Released January 18, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v2.5.0...v2.6.0)
|
||||
|
||||
### New
|
||||
|
||||
- Database observation has been enhanced:
|
||||
|
||||
- `TransactionObserver.stopObservingDatabaseChangesUntilNextTransaction()` allows transaction observers to stop observing the database for the remaining extent of a transaction.
|
||||
- GRDB no longer prevents the [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt) when no transaction observers are interested in deleted rows.
|
||||
- FetchedRecordsController now avoids checking for changes in untracked rowIds.
|
||||
- `DatabaseRegion` is a new public type that helps transaction observers recognize impactful database changes. This type is not documented in the main documentation. For more information, see [DatabaseRegion reference](http://groue.github.io/GRDB.swift/docs/2.6/Structs/DatabaseRegion.html), and look at [FetchedRecordsController implementation](https://github.com/groue/GRDB.swift/blob/master/GRDB/Record/FetchedRecordsController.swift).
|
||||
- `TransactionObserver` protocol provides default implementations for rarely used callbacks.
|
||||
|
||||
- `Row` adopts RandomAccessCollection
|
||||
|
||||
### API diff
|
||||
|
||||
```diff
|
||||
extension TransactionObserver {
|
||||
+ func stopObservingDatabaseChangesUntilNextTransaction()
|
||||
+
|
||||
+ // Default implementation
|
||||
+ func databaseWillCommit() throws
|
||||
+
|
||||
+ #if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
+ // Default implementation
|
||||
+ func databaseWillChange(with event: DatabasePreUpdateEvent)
|
||||
+ #endif
|
||||
}
|
||||
|
||||
+struct DatabaseRegion: Equatable {
|
||||
+ var isEmpty: Bool
|
||||
+
|
||||
+ init()
|
||||
+
|
||||
+ func union(_ other: DatabaseRegion) -> DatabaseRegion
|
||||
+ mutating func formUnion(_ other: DatabaseRegion)
|
||||
+
|
||||
+ func isModified(byEventsOfKind eventKind: DatabaseEventKind) -> Bool
|
||||
+ func isModified(by event: DatabaseEvent) -> Bool
|
||||
+}
|
||||
|
||||
class SelectStatement {
|
||||
+ var fetchedRegion: DatabaseRegion
|
||||
+
|
||||
+ @available(*, deprecated, renamed:"DatabaseRegion")
|
||||
+ typealias SelectionInfo = DatabaseRegion
|
||||
+
|
||||
+ @available(*, deprecated, renamed:"fetchedRegion")
|
||||
+ var selectionInfo: DatabaseRegion
|
||||
}
|
||||
|
||||
enum DatabaseEventKind {
|
||||
- func impacts(_ selectionInfo: SelectStatement.SelectionInfo) -> Bool
|
||||
+ @available(*, deprecated, message: "Use DatabaseRegion.isModified(byEventsOfKind:) instead")
|
||||
+ func impacts(_ region: DatabaseRegion) -> Bool
|
||||
}
|
||||
|
||||
protocol Request {
|
||||
+ // Default implementation
|
||||
+ func fetchedRegion(_ db: Database) throws -> DatabaseRegion
|
||||
}
|
||||
|
||||
+extension Row: RandomAccessCollection {
|
||||
+}
|
||||
+extension RowIndex: Strideable {
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 2.5.0
|
||||
|
||||
Released January 11, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v2.4.2...v2.5.0)
|
||||
|
||||
### Fixed
|
||||
|
||||
- [Transaction observers](https://github.com/groue/GRDB.swift/blob/master/README.md#transactionobserver-protocol) used to be notified of some database changes they were not interested into, in case of complex statements with side effects (foreign key cascades or sql triggers). This has been fixed.
|
||||
|
||||
|
||||
### New
|
||||
|
||||
- The query interface has learned to build requests from any key (primary keys and unique keys) ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#fetching-by-key)):
|
||||
|
||||
```swift
|
||||
// SELECT * FROM players WHERE id = 1
|
||||
let request = Player.filter(key: 1)
|
||||
let player = try request.fetchOne(db) // Player?
|
||||
|
||||
// SELECT * FROM countries WHERE isoCode IN ('FR', 'US')
|
||||
let request = Country.filter(keys: ["FR", "US"])
|
||||
let countries = try request.fetchAll(db) // [Country]
|
||||
|
||||
// SELECT * FROM players WHERE email = 'arthur@example.com'
|
||||
let request = Player.filter(key: ["email": "arthur@example.com"])
|
||||
let player = try request.fetchOne(db) // Player?
|
||||
```
|
||||
|
||||
This feature has been introduced in order to ease the use of [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB):
|
||||
|
||||
```swift
|
||||
// New
|
||||
Player.filter(key: 1).rx
|
||||
.fetchOne(in: dbQueue)
|
||||
.subscribe(onNext: { player: Player? in
|
||||
print("Player 1 has changed")
|
||||
})
|
||||
```
|
||||
|
||||
|
||||
### API diff
|
||||
|
||||
```diff
|
||||
extension TableMapping {
|
||||
+ static func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> QueryInterfaceRequest<Self>
|
||||
+ static func filter<Sequence: Swift.Sequence>(keys: Sequence) -> QueryInterfaceRequest<Self> where Sequence.Element: DatabaseValueConvertible
|
||||
+ static func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest<Self>
|
||||
+ static func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest<Self>
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest where T: TableMapping {
|
||||
+ func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> QueryInterfaceRequest<T>
|
||||
+ func filter<Sequence: Swift.Sequence>(keys: Sequence) -> QueryInterfaceRequest<T> where Sequence.Element: DatabaseValueConvertible
|
||||
+ func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest<T>
|
||||
+ func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest<T>
|
||||
}
|
||||
|
||||
extension RowConvertible where Self: TableMapping {
|
||||
- static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Self?
|
||||
+ static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]?) throws -> Self?
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 2.4.2
|
||||
|
||||
Released January 6, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v2.4.1...v2.4.2)
|
||||
|
||||
**Fixed**
|
||||
|
||||
- When using a database pool, the schema introspection methods could return wrong values whenever the database schema was concurrently read and modified. This has been fixed.
|
||||
- `DatabasePool.readFromCurrentState` no longer accepts to spawn a reader when a transaction is currently opened on the writer connection.
|
||||
|
||||
|
||||
## 2.4.1
|
||||
|
||||
Released December 16, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.4.0...v2.4.1)
|
||||
|
||||
**Fixed**
|
||||
|
||||
- [#284](https://github.com/groue/GRDB.swift/pull/284): fixes a misuse of the sqlite3_config() function when configuring the global SQLite [Error Log](https://github.com/groue/GRDB.swift/blob/master/README.md#error-log)
|
||||
|
||||
|
||||
## 2.4.0
|
||||
|
||||
Released December 3, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.3.1...v2.4.0)
|
||||
|
||||
**New**
|
||||
|
||||
- [#280](https://github.com/groue/GRDB.swift/pull/280): It is now possible to add an untyped column to an existing table.
|
||||
|
||||
```swift
|
||||
try db.alter(table: "players") { t in
|
||||
t.add(column: "score")
|
||||
}
|
||||
```
|
||||
|
||||
- [#281](https://github.com/groue/GRDB.swift/pull/280): The `Database.dropFTS4SynchronizationTriggers` & `Database.dropFTS5SynchronizationTriggers` method help cleaning up synchronized full-text table ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#deleting-synchronized-full-text-tables))
|
||||
|
||||
**Breaking Change**
|
||||
|
||||
- [#282](https://github.com/groue/GRDB.swift/issues/282): This version comes with a breaking change that affects users who manually embed the GRDBCipher and GRDBCustom frameworks in their projects. This change does not affect users of the GRDB framework, or users of GRDBCipher through CocoaPods. Now, instead of embedding the GRDB.xcodeproj project, you have to embed the GRDBCipher.xcodeproj or GRDBCustom.xcodeproj. Please have a look at the updated [Encryption](https://github.com/groue/GRDB.swift/blob/master/README.md#encryption) and [Custom SQLite Builds](https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md) documentation chapters.
|
||||
|
||||
|
||||
## 2.3.1
|
||||
|
||||
Released November 8, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.3.0...v2.3.1)
|
||||
|
||||
**Fixed**
|
||||
|
||||
- GRDB 2.2.0 has introduced a fix in the way [transaction observers](https://github.com/groue/GRDB.swift/blob/master/README.md#transactionobserver-protocol) are notified of empty deferred transactions (`BEGIN; COMMIT;`). That fix was incomplete, and inconsistent.
|
||||
|
||||
Now all transactions are notified, without any exception, including:
|
||||
|
||||
```swift
|
||||
try db.execute("BEGIN; COMMIT;")
|
||||
try db.execute("SAVEPOINT foo; RELEASE SAVEPOINT foo;")
|
||||
```
|
||||
|
||||
[Rationale](https://github.com/groue/GRDB.swift/commit/820bc87cfeee701743da852f3634e2c695e911ee#diff-3e791e9db648cd302590c9b86c70757fR376)
|
||||
|
||||
|
||||
## 2.3.0
|
||||
|
||||
Released November 5, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.2.0...v2.3.0)
|
||||
|
||||
**New**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.21.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
|
||||
|
||||
## 2.2.0
|
||||
|
||||
Released October 31, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.1.0...v2.2.0)
|
||||
|
||||
**New**
|
||||
|
||||
- `Database.viewExists(_:)` returns whether a view exists in the database.
|
||||
- `Database.triggerExists(_:)` returns whether a trigger exists in the database.
|
||||
|
||||
**Fixed**
|
||||
|
||||
- `DROP VIEW` statements would not drop views ([#267](https://github.com/groue/GRDB.swift/issues/267))
|
||||
- GRDB used to incorrectly send incomplete transaction notifications to [transaction observers](https://github.com/groue/GRDB.swift/blob/master/README.md#transactionobserver-protocol) in the case of empty deferred transactions. This is no longer the case. Since empty deferred transactions have SQLite consider that no transaction started at all, they are no longer notified to transaction observers:
|
||||
|
||||
```sql
|
||||
-- Nothing happens, and thus no notification is sent
|
||||
BEGIN TRANSACTION
|
||||
COMMIT
|
||||
```
|
||||
|
||||
Those empty deferred transactions still count for the [afterNextTransactionCommit](https://github.com/groue/GRDB.swift/blob/master/README.md#after-commit-hook) database method, and the `.nextTransaction` [observation extent](https://github.com/groue/GRDB.swift/blob/master/README.md#observation-extent).
|
||||
|
||||
|
||||
## 2.1.0
|
||||
|
||||
Released October 24, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.0.3...v2.1.0)
|
||||
|
||||
### New
|
||||
|
||||
- GRDBCipher can now build from command line ([groue/sqlcipher/pull/1](https://github.com/groue/sqlcipher/pull/1) by [Darren Clark](https://github.com/darrenclark))
|
||||
- Upgrade custom SQLite builds to [v3.20.1](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- The new method `Request.asSQLRequest` allows to inspect the sql and arguments of any request:
|
||||
|
||||
```swift
|
||||
let request = Player.all()
|
||||
let sql = try request.asSQLRequest(db).sql
|
||||
print(sql) // Prints "SELECT * FROM players"
|
||||
```
|
||||
|
||||
- StatementArguments adopts Equatable
|
||||
|
||||
|
||||
### Fixed
|
||||
|
||||
- `DROP TABLE` statements would not drop temporary tables.
|
||||
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
- New FAQ: [How do I create a database in my application?](https://github.com/groue/GRDB.swift/blob/master/README.md#how-do-i-create-a-database-in-my-application)
|
||||
- New FAQ: [How do I print a request as SQL?](https://github.com/groue/GRDB.swift/blob/master/README.md#how-do-i-print-a-request-as-sql)
|
||||
- The [Codable Record](https://github.com/groue/GRDB.swift/blob/master/README.md#codable-records) chapter has been enhanced with more information and sample code.
|
||||
|
||||
|
||||
### API diff
|
||||
|
||||
```diff
|
||||
extension Request {
|
||||
+ func asSQLRequest(_ db: Database, cached: Bool = false) throws -> SQLRequest
|
||||
}
|
||||
struct SQLRequest {
|
||||
+ let sql: String
|
||||
+ let arguments: StatementArguments?
|
||||
+ let adapter: RowAdapter?
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 2.0.3
|
||||
|
||||
Released October 9, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.0.2...v2.0.3)
|
||||
|
||||
**Fixed**: Record types that conform to Encodable now encode their null columns.
|
||||
|
||||
|
||||
## 2.0.2
|
||||
|
||||
Released October 5, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.0.1...v2.0.2)
|
||||
@@ -114,7 +567,7 @@ New features have been added in order to plug a few holes and support the [RxGRD
|
||||
- Query interface requests learned how to limit the number of deleted rows:
|
||||
|
||||
```swift
|
||||
// Delete the worse ten players:
|
||||
// Delete the last ten players:
|
||||
// DELETE FROM players ORDER BY score LIMIT 10
|
||||
let request = Player.order(scoreColumn).limit(10)
|
||||
try request.deleteAll(db)
|
||||
@@ -186,7 +639,7 @@ New features have been added in order to plug a few holes and support the [RxGRD
|
||||
- The deprecated `TableMapping.primaryKeyRowComparator` method has been removed.
|
||||
|
||||
|
||||
### Documentation diff
|
||||
### Documentation Diff
|
||||
|
||||
- [WatchOS installation procedure](https://github.com/groue/GRDB.swift#installation) has been updated with new instructions.
|
||||
- The [introduction to multithreading with database pools](https://github.com/groue/GRDB.swift#database-pools) has been enhanced.
|
||||
|
||||
@@ -14,9 +14,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
}
|
||||
|
||||
private func setupDatabase(_ application: UIApplication) throws {
|
||||
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString
|
||||
let databasePath = documentsPath.appendingPathComponent("db.sqlite")
|
||||
dbQueue = try AppDatabase.openDatabase(atPath: databasePath)
|
||||
let databaseURL = try FileManager.default
|
||||
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
.appendingPathComponent("db.sqlite")
|
||||
dbQueue = try AppDatabase.openDatabase(atPath: databaseURL.path)
|
||||
|
||||
// Be a nice iOS citizen, and don't consume too much memory
|
||||
// See https://github.com/groue/GRDB.swift/#memory-management
|
||||
|
||||
@@ -3,7 +3,7 @@ Custom SQLite Builds
|
||||
|
||||
By default, GRDB uses the version of SQLite that ships with the target operating system.
|
||||
|
||||
**You can build GRDB with a custom build of [SQLite 3.20.0](https://www.sqlite.org/changes.html).**
|
||||
**You can build GRDB with a custom build of [SQLite 3.22.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).
|
||||
|
||||
@@ -15,7 +15,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
|
||||
```sh
|
||||
cd [GRDB directory]
|
||||
git checkout v2.0.2
|
||||
git checkout v2.9.0
|
||||
git submodule update --init SQLiteCustom/src
|
||||
````
|
||||
|
||||
@@ -60,7 +60,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
# !! MODIFY THESE TO MATCH YOUR PROJECT HIERARCHY !!
|
||||
#######################################################
|
||||
|
||||
# The path to the folder containing GRDB.xcodeproj:
|
||||
# The path to the folder containing GRDBCustom.xcodeproj:
|
||||
GRDB_SOURCE_PATH="${PROJECT_DIR}/GRDB"
|
||||
|
||||
# The path to your custom "SQLiteLib-USER.xcconfig":
|
||||
@@ -107,7 +107,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
|
||||
Modify the top of `GRDBCustomSQLite-INSTALL.sh` file so that it contains correct paths.
|
||||
|
||||
5. Embed the `GRDB.xcodeproj` project in your own project.
|
||||
5. Embed the `GRDBCustom.xcodeproj` project in your own project.
|
||||
|
||||
6. Add the `GRDBCustomSQLiteOSX` or `GRDBCustomSQLiteiOS` target in the **Target Dependencies** section of the **Build Phases** tab of your **application target**.
|
||||
|
||||
|
||||
@@ -1,591 +0,0 @@
|
||||
GRDB Extension Guide
|
||||
====================
|
||||
|
||||
**Some parts of GRDB are extensible, so that you can make it better fit your needs.**
|
||||
|
||||
This guide is a step-by-step tour of GRDB extensibility, around a few topics:
|
||||
|
||||
- **[Add a value type](#add-a-value-type)**
|
||||
|
||||
You'll learn how to turn UIColor into a value type that you can store, fetch, and use in your records:
|
||||
|
||||
```swift
|
||||
let rows = try Row.fetchCursor(db, "SELECT name, color FROM clothes")
|
||||
while let row = try rows.next() {
|
||||
let name: String = row["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.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 47 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 39 KiB |
@@ -16,7 +16,6 @@ To release a new GRDB version:
|
||||
- Makefile
|
||||
- CHANGELOG.md
|
||||
- Documentation/CustomSQLiteBuilds.md
|
||||
- Documentation/ExtendingGRDB.md
|
||||
- GRDB.swift.podspec
|
||||
- GRDBCipher.podspec
|
||||
- README.md
|
||||
@@ -24,9 +23,12 @@ To release a new GRDB version:
|
||||
- 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
|
||||
- Push to the Swift4 branch
|
||||
- `pod trunk push --allow-warnings GRDB.swift.podspec`
|
||||
- `pod trunk push --allow-warnings GRDBCipher.podspec`
|
||||
- `make doc`, and update index.html in the `gh-pages` branch
|
||||
- Update http://github.com/groue/GRDBDemo
|
||||
- Update http://github.com/groue/WWDCCompanion
|
||||
- Update [performance comparison](https://github.com/groue/GRDB.swift/wiki/Performance):
|
||||
|
||||
`make test_performance | Tests/parsePerformanceTests.rb | Tests/generatePerformanceReport.rb`
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '2.0.2'
|
||||
s.version = '2.9.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A Swift application toolkit for SQLite databases.'
|
||||
|
||||
+140
-3635
File diff suppressed because it is too large.
Load diff
+21
@@ -23,9 +23,30 @@
|
||||
location = "group:MyPlayground.playground">
|
||||
</FileRef>
|
||||
</Group>
|
||||
<FileRef
|
||||
location = "group:CHANGELOG.md">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:README.md">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:TODO.md">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Documentation/ReleaseProcess.md">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Makefile">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:GRDB.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:GRDBCustom.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:GRDBCipher.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj">
|
||||
</FileRef>
|
||||
|
||||
@@ -43,6 +43,38 @@ public struct Configuration {
|
||||
/// Default: deferred
|
||||
public var defaultTransactionKind: Database.TransactionKind = .deferred
|
||||
|
||||
/// If false, it is a programmer error to leave a transaction opened at the
|
||||
/// end of a database access block.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
///
|
||||
/// // fatal error: A transaction has been left opened at the end of a database access
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.beginTransaction()
|
||||
/// }
|
||||
///
|
||||
/// If true, one can leave opened transaction at the end of database access
|
||||
/// blocks:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.allowsUnsafeTransactions = true
|
||||
/// let dbQueue = DatabaseQueue(configuration: config)
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.beginTransaction()
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.commit()
|
||||
/// }
|
||||
///
|
||||
/// This configuration flag has no effect on DatabasePool readers: those
|
||||
/// never allow leaving a transaction opened at the end of a read access.
|
||||
///
|
||||
/// Default: false
|
||||
public var allowsUnsafeTransactions: Bool = false
|
||||
|
||||
// MARK: - Concurrency
|
||||
|
||||
|
||||
+486
-70
@@ -1,3 +1,16 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// Parts of this file are derived from the Swift.org open source project:
|
||||
//
|
||||
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// MARK: - Array, Sequence, Set extensions
|
||||
|
||||
extension Array {
|
||||
/// Creates an array containing the elements of a cursor.
|
||||
///
|
||||
@@ -11,6 +24,15 @@ extension Array {
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<IteratorCursor<Iterator>, SegmentOfResult>> {
|
||||
return IteratorCursor(self).flatMap(transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension Set {
|
||||
/// Creates a set containing the elements of a cursor.
|
||||
///
|
||||
@@ -24,6 +46,8 @@ extension Set {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Cursor
|
||||
|
||||
/// A type that supplies the values of some external resource, one at a time.
|
||||
///
|
||||
/// ## Overview
|
||||
@@ -46,19 +70,11 @@ extension Set {
|
||||
/// - 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)`
|
||||
/// to those defined by Swift's Sequence protocol: `contains`, `dropFirst`,
|
||||
/// `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`,
|
||||
/// `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`,
|
||||
/// `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`,
|
||||
/// `suffix`.
|
||||
public protocol Cursor : class {
|
||||
/// The type of element traversed by the cursor.
|
||||
associatedtype Element
|
||||
@@ -68,32 +84,6 @@ public protocol Cursor : class {
|
||||
func next() throws -> Element?
|
||||
}
|
||||
|
||||
/// A type-erased cursor of Element.
|
||||
///
|
||||
/// This cursor forwards its next() method to an arbitrary underlying cursor
|
||||
/// having the same Element type, hiding the specifics of the underlying
|
||||
/// cursor.
|
||||
public class AnyCursor<Element> : Cursor {
|
||||
/// Creates a cursor that wraps a base cursor but whose type depends only on
|
||||
/// the base cursor’s element type
|
||||
public init<C: Cursor>(_ base: C) where C.Element == Element {
|
||||
element = base.next
|
||||
}
|
||||
|
||||
/// Creates a cursor that wraps the given closure in its next() method
|
||||
public init(_ body: @escaping () throws -> Element?) {
|
||||
element = body
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
public func next() throws -> Element? {
|
||||
return try element()
|
||||
}
|
||||
|
||||
private let element: () throws -> Element?
|
||||
}
|
||||
|
||||
extension Cursor {
|
||||
/// Returns a Boolean value indicating whether the cursor contains an
|
||||
/// element that satisfies the given predicate.
|
||||
@@ -148,6 +138,102 @@ extension Cursor {
|
||||
return map(transform).filter { $0 != nil }.map { $0! }
|
||||
}
|
||||
|
||||
/// Returns a cursor that skips any initial elements that satisfy
|
||||
/// `predicate`.
|
||||
///
|
||||
/// - Parameter predicate: A closure that takes an element of the cursir as
|
||||
/// its argument and returns `true` if the element should be skipped or
|
||||
/// `false` otherwise. Once `predicate` returns `false` it will not be
|
||||
/// called again.
|
||||
public func drop(while predicate: @escaping (Element) throws -> Bool) -> DropWhileCursor<Self> {
|
||||
return DropWhileCursor(self, predicate: predicate)
|
||||
}
|
||||
|
||||
/// Returns a cursor containing all but the given number of initial
|
||||
/// elements.
|
||||
///
|
||||
/// If the number of elements to drop exceeds the number of elements in
|
||||
/// the cursor, the result is an empty cursor.
|
||||
///
|
||||
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropFirst(2))
|
||||
/// // Prints "[3, 4, 5]"
|
||||
/// try print(numbers.dropFirst(10))
|
||||
/// // Prints "[]"
|
||||
///
|
||||
/// - Parameter n: The number of elements to drop from the beginning of
|
||||
/// the cursor. `n` must be greater than or equal to zero.
|
||||
/// - Returns: A cursor starting after the specified number of
|
||||
/// elements.
|
||||
public func dropFirst(_ n: Int) -> DropFirstCursor<Self> {
|
||||
return DropFirstCursor(self, limit: n)
|
||||
}
|
||||
|
||||
/// Returns a cursor containing all but the first element of the cursor.
|
||||
///
|
||||
/// The following example drops the first element from a cursor of integers.
|
||||
///
|
||||
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropFirst())
|
||||
/// // Prints "[2, 3, 4, 5]"
|
||||
///
|
||||
/// If the cursor has no elements, the result is an empty cursor.
|
||||
///
|
||||
/// - Returns: A cursor starting after the first element of the cursor.
|
||||
public func dropFirst() -> DropFirstCursor<Self> {
|
||||
return dropFirst(1)
|
||||
}
|
||||
|
||||
/// Returns an array containing all but the given number of final
|
||||
/// elements.
|
||||
///
|
||||
/// The cursor must be finite. If the number of elements to drop exceeds
|
||||
/// the number of elements in the cursor, the result is an empty array.
|
||||
///
|
||||
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropLast(2))
|
||||
/// // Prints "[1, 2, 3]"
|
||||
/// try print(numbers.dropLast(10))
|
||||
/// // Prints "[]"
|
||||
///
|
||||
/// - Parameter n: The number of elements to drop off the end of the
|
||||
/// cursor. `n` must be greater than or equal to zero.
|
||||
/// - Returns: An array leaving off the specified number of elements.
|
||||
public func dropLast(_ n: Int) throws -> [Element] {
|
||||
GRDBPrecondition(n >= 0, "Can't drop a negative number of elements from a cursor")
|
||||
if n == 0 { return try Array(self) }
|
||||
|
||||
var result: [Element] = []
|
||||
var ringBuffer: [Element] = []
|
||||
var i = ringBuffer.startIndex
|
||||
|
||||
while let element = try next() {
|
||||
if ringBuffer.count < n {
|
||||
ringBuffer.append(element)
|
||||
} else {
|
||||
result.append(ringBuffer[i])
|
||||
ringBuffer[i] = element
|
||||
i = ringBuffer.index(after: i) % n
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/// Returns an array containing all but the last element of the cursor.
|
||||
///
|
||||
/// The following example drops the last element from a cursor of integers.
|
||||
///
|
||||
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropLast())
|
||||
/// // Prints "[1, 2, 3, 4]"
|
||||
///
|
||||
/// If the cursor has no elements, the result is an empty cursor.
|
||||
///
|
||||
/// - Returns: An array leaving off the last element of the cursor.
|
||||
public func dropLast() throws -> [Element] {
|
||||
return try dropLast(1)
|
||||
}
|
||||
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult: Sequence>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, IteratorCursor<SegmentOfResult.Iterator>>> {
|
||||
@@ -173,17 +259,152 @@ extension Cursor {
|
||||
return MapCursor(self, transform)
|
||||
}
|
||||
|
||||
/// Returns the result of calling the given combining closure with each
|
||||
/// element of this sequence and an accumulating value.
|
||||
public func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) throws -> Result {
|
||||
var result = initialResult
|
||||
while let element = try next() {
|
||||
result = try nextPartialResult(result, element)
|
||||
/// Returns the maximum element in the cursor, using the given predicate as
|
||||
/// the comparison between elements.
|
||||
///
|
||||
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
|
||||
/// if its first argument should be ordered before its second
|
||||
/// argument; otherwise, `false`.
|
||||
/// - Returns: The cursor's maximum element, according to
|
||||
/// `areInIncreasingOrder`. If the cursor has no elements, returns `nil`.
|
||||
public func max(by areInIncreasingOrder: (Element, Element) throws -> Bool) throws -> Element? {
|
||||
guard var result = try next() else {
|
||||
return nil
|
||||
}
|
||||
while let e = try next() {
|
||||
if try areInIncreasingOrder(result, e) {
|
||||
result = e
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/// Returns the minimum element in the cursor, using the given predicate as
|
||||
/// the comparison between elements.
|
||||
///
|
||||
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
|
||||
/// if its first argument should be ordered before its second
|
||||
/// argument; otherwise, `false`.
|
||||
/// - Returns: The cursor's minimum element, according to
|
||||
/// `areInIncreasingOrder`. If the cursor has no elements, returns `nil`.
|
||||
public func min(by areInIncreasingOrder: (Element, Element) throws -> Bool) throws -> Element? {
|
||||
guard var result = try next() else {
|
||||
return nil
|
||||
}
|
||||
while let e = try next() {
|
||||
if try areInIncreasingOrder(e, result) {
|
||||
result = e
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/// Returns a cursor, up to the specified maximum length, containing the
|
||||
/// initial elements of the cursor.
|
||||
///
|
||||
/// If the maximum length exceeds the number of elements in the cursor,
|
||||
/// the result contains all the elements in the cursor.
|
||||
///
|
||||
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.prefix(2))
|
||||
/// // Prints "[1, 2]"
|
||||
/// try print(numbers.prefix(10))
|
||||
/// // Prints "[1, 2, 3, 4, 5]"
|
||||
///
|
||||
/// - Parameter maxLength: The maximum number of elements to return. The
|
||||
/// value of `maxLength` must be greater than or equal to zero.
|
||||
/// - Returns: A cursor starting at the beginning of this cursor
|
||||
/// with at most `maxLength` elements.
|
||||
public func prefix(_ maxLength: Int) -> PrefixCursor<Self> {
|
||||
return PrefixCursor(self, maxLength: maxLength)
|
||||
}
|
||||
|
||||
/// Returns a cursor of the initial consecutive elements that satisfy
|
||||
/// `predicate`.
|
||||
///
|
||||
/// - Parameter predicate: A closure that takes an element of the cursor as
|
||||
/// its argument and returns `true` if the element should be included or
|
||||
/// `false` otherwise. Once `predicate` returns `false` it will not be
|
||||
/// called again.
|
||||
public func prefix(while predicate: @escaping (Element) throws -> Bool) -> PrefixWhileCursor<Self> {
|
||||
return PrefixWhileCursor(self, predicate: predicate)
|
||||
}
|
||||
|
||||
/// Returns the result of calling the given combining closure with each
|
||||
/// element of this cursor and an accumulating value.
|
||||
public func reduce<Result>(
|
||||
_ initialResult: Result,
|
||||
_ nextPartialResult: (Result, Element) throws -> Result)
|
||||
throws -> Result
|
||||
{
|
||||
var accumulator = initialResult
|
||||
while let element = try next() {
|
||||
accumulator = try nextPartialResult(accumulator, element)
|
||||
}
|
||||
return accumulator
|
||||
}
|
||||
|
||||
/// Returns the result of calling the given combining closure with each
|
||||
/// element of this cursor and an accumulating value.
|
||||
public func reduce<Result>(
|
||||
into initialResult: Result,
|
||||
_ updateAccumulatingResult: (inout Result, Element) throws -> Void)
|
||||
throws -> Result
|
||||
{
|
||||
var accumulator = initialResult
|
||||
while let element = try next() {
|
||||
try updateAccumulatingResult(&accumulator, element)
|
||||
}
|
||||
return accumulator
|
||||
}
|
||||
|
||||
/// Returns an array, up to the given maximum length, containing the
|
||||
/// final elements of the cursor.
|
||||
///
|
||||
/// The cursor must be finite. If the maximum length exceeds the number of
|
||||
/// elements in the cursor, the result contains all the elements in the
|
||||
/// cursor.
|
||||
///
|
||||
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.suffix(2))
|
||||
/// // Prints "[4, 5]"
|
||||
/// try print(numbers.suffix(10))
|
||||
/// // Prints "[1, 2, 3, 4, 5]"
|
||||
///
|
||||
/// - Parameter maxLength: The maximum number of elements to return. The
|
||||
/// value of `maxLength` must be greater than or equal to zero.
|
||||
public func suffix(_ maxLength: Int) throws -> [Element] {
|
||||
GRDBPrecondition(maxLength >= 0, "Can't take a suffix of negative length from a cursor")
|
||||
if maxLength == 0 {
|
||||
return []
|
||||
}
|
||||
|
||||
var ringBuffer: [Element] = []
|
||||
ringBuffer.reserveCapacity(maxLength)
|
||||
|
||||
var i = ringBuffer.startIndex
|
||||
|
||||
while let element = try next() {
|
||||
if ringBuffer.count < maxLength {
|
||||
ringBuffer.append(element)
|
||||
} else {
|
||||
ringBuffer[i] = element
|
||||
i += 1
|
||||
i %= maxLength
|
||||
}
|
||||
}
|
||||
|
||||
if i != ringBuffer.startIndex {
|
||||
let s0 = ringBuffer[i..<ringBuffer.endIndex]
|
||||
let s1 = ringBuffer[0..<i]
|
||||
return Array([s0, s1].joined())
|
||||
}
|
||||
return ringBuffer
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Equatable elements
|
||||
|
||||
extension Cursor where Element: Equatable {
|
||||
/// Returns a Boolean value indicating whether the cursor contains the
|
||||
/// given element.
|
||||
@@ -197,6 +418,36 @@ extension Cursor where Element: Equatable {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Comparable elements
|
||||
|
||||
extension Cursor where Element: Comparable {
|
||||
/// Returns the maximum element in the cursor.
|
||||
///
|
||||
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
|
||||
/// if its first argument should be ordered before its second
|
||||
/// argument; otherwise, `false`.
|
||||
/// - Returns: The cursor's maximum element, according to
|
||||
/// `areInIncreasingOrder`. If the cursor has no elements, returns
|
||||
/// `nil`.
|
||||
public func max() throws -> Element? {
|
||||
return try max(by: <)
|
||||
}
|
||||
|
||||
/// Returns the minimum element in the cursor.
|
||||
///
|
||||
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
|
||||
/// if its first argument should be ordered before its second
|
||||
/// argument; otherwise, `false`.
|
||||
/// - Returns: The cursor's minimum element, according to
|
||||
/// `areInIncreasingOrder`. If the cursor has no elements, returns
|
||||
/// `nil`.
|
||||
public func min() throws -> Element? {
|
||||
return try min(by: <)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Cursor elements
|
||||
|
||||
extension Cursor where Element: Cursor {
|
||||
/// Returns the elements of this cursor of cursors, concatenated.
|
||||
public func joined() -> FlattenCursor<Self> {
|
||||
@@ -204,13 +455,122 @@ extension Cursor where Element: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Sequence elements
|
||||
|
||||
extension Cursor where Element: Sequence {
|
||||
/// Returns the elements of this cursor of sequences, concatenated.
|
||||
public func joined() -> FlattenCursor<MapCursor<Self, IteratorCursor<Self.Element.Iterator>>> {
|
||||
public func joined() -> FlattenCursor<MapCursor<Self, IteratorCursor<Element.Iterator>>> {
|
||||
return flatMap { $0 }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: String elements
|
||||
|
||||
extension Cursor where Element: StringProtocol {
|
||||
/// Returns the elements of this cursor of sequences, concatenated.
|
||||
public func joined(separator: String = "") throws -> String {
|
||||
if separator.isEmpty {
|
||||
var result = ""
|
||||
while let x = try next() {
|
||||
result.append(String(x))
|
||||
}
|
||||
return result
|
||||
} else {
|
||||
var result = ""
|
||||
if let first = try next() {
|
||||
result.append(String(first))
|
||||
while let next = try next() {
|
||||
result.append(separator)
|
||||
result.append(String(next))
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Specialized Cursors
|
||||
|
||||
/// A type-erased cursor of Element.
|
||||
///
|
||||
/// This cursor forwards its next() method to an arbitrary underlying cursor
|
||||
/// having the same Element type, hiding the specifics of the underlying
|
||||
/// cursor.
|
||||
public class AnyCursor<Element> : Cursor {
|
||||
private let element: () throws -> Element?
|
||||
|
||||
/// Creates a cursor that wraps a base cursor but whose type depends only on
|
||||
/// the base cursor’s element type
|
||||
public init<C: Cursor>(_ base: C) where C.Element == Element {
|
||||
element = base.next
|
||||
}
|
||||
|
||||
/// Creates a cursor that wraps the given closure in its next() method
|
||||
public init(_ body: @escaping () throws -> Element?) {
|
||||
element = body
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
/// :nodoc:
|
||||
public func next() throws -> Element? {
|
||||
return try element()
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public final class DropFirstCursor<Base: Cursor> : Cursor {
|
||||
private let base: Base
|
||||
private let limit: Int
|
||||
private var dropped: Int = 0
|
||||
|
||||
init(_ base: Base, limit: Int) {
|
||||
GRDBPrecondition(limit >= 0, "Can't drop a negative number of elements from a cursor")
|
||||
self.base = base
|
||||
self.limit = limit
|
||||
}
|
||||
|
||||
public func next() throws -> Base.Element? {
|
||||
while dropped < limit {
|
||||
if try base.next() == nil {
|
||||
dropped = limit
|
||||
return nil
|
||||
}
|
||||
dropped += 1
|
||||
}
|
||||
return try base.next()
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor whose elements consist of the elements that follow the initial
|
||||
/// consecutive elements of some base cursor that satisfy a given predicate.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class DropWhileCursor<Base: Cursor> : Cursor {
|
||||
private let base: Base
|
||||
private let predicate: (Base.Element) throws -> Bool
|
||||
private var predicateHasFailed = false
|
||||
|
||||
init(_ base: Base, predicate: @escaping (Base.Element) throws -> Bool) {
|
||||
self.base = base
|
||||
self.predicate = predicate
|
||||
}
|
||||
|
||||
public func next() throws -> Base.Element? {
|
||||
if predicateHasFailed {
|
||||
return try base.next()
|
||||
}
|
||||
|
||||
while let nextElement = try base.next() {
|
||||
if try !predicate(nextElement) {
|
||||
predicateHasFailed = true
|
||||
return nextElement
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// An enumeration of the elements of a cursor.
|
||||
///
|
||||
/// To create an instance of `EnumeratedCursor`, call the `enumerated()` method
|
||||
@@ -223,27 +583,35 @@ extension Cursor where Element: Sequence {
|
||||
/// }
|
||||
/// // Prints: "0: foo"
|
||||
/// // Prints: "1: bar"
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class EnumeratedCursor<Base: Cursor> : Cursor {
|
||||
private let base: Base
|
||||
private var index: Int
|
||||
|
||||
init(_ base: Base) {
|
||||
self.index = 0
|
||||
self.base = base
|
||||
self.index = 0
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
/// :nodoc:
|
||||
public func next() throws -> (Int, Base.Element)? {
|
||||
guard let element = try base.next() else { return nil }
|
||||
defer { index += 1 }
|
||||
return (index, element)
|
||||
}
|
||||
|
||||
private var index: Int
|
||||
private var base: Base
|
||||
}
|
||||
|
||||
/// A cursor whose elements consist of the elements of some base cursor that
|
||||
/// also satisfy a given predicate.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class FilterCursor<Base: Cursor> : Cursor {
|
||||
private let base: Base
|
||||
private let isIncluded: (Base.Element) throws -> Bool
|
||||
|
||||
init(_ base: Base, _ isIncluded: @escaping (Base.Element) throws -> Bool) {
|
||||
self.base = base
|
||||
self.isIncluded = isIncluded
|
||||
@@ -251,6 +619,7 @@ public final class FilterCursor<Base: Cursor> : Cursor {
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
/// :nodoc:
|
||||
public func next() throws -> Base.Element? {
|
||||
while let element = try base.next() {
|
||||
if try isIncluded(element) {
|
||||
@@ -259,22 +628,25 @@ public final class FilterCursor<Base: Cursor> : Cursor {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private let base: Base
|
||||
private let isIncluded: (Base.Element) throws -> Bool
|
||||
}
|
||||
|
||||
/// A cursor consisting of all the elements contained in each segment contained
|
||||
/// in some Base cursor.
|
||||
///
|
||||
/// See Cursor.joined(), Cursor.flatMap(_:), Sequence.flatMap(_:)
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Cursor {
|
||||
private let base: Base
|
||||
private var inner: Base.Element?
|
||||
|
||||
init(_ base: Base) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
/// :nodoc:
|
||||
public func next() throws -> Base.Element.Element? {
|
||||
while true {
|
||||
if let element = try inner?.next() {
|
||||
@@ -286,16 +658,18 @@ public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Curs
|
||||
self.inner = inner
|
||||
}
|
||||
}
|
||||
|
||||
private var inner: Base.Element?
|
||||
private let base: Base
|
||||
}
|
||||
|
||||
/// A Cursor whose elements consist of those in a Base Cursor passed through a
|
||||
/// transform function returning Element.
|
||||
///
|
||||
/// See Cursor.map(_:)
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class MapCursor<Base: Cursor, Element> : Cursor {
|
||||
private let base: Base
|
||||
private let transform: (Base.Element) throws -> Element
|
||||
|
||||
init(_ base: Base, _ transform: @escaping (Base.Element) throws -> Element) {
|
||||
self.base = base
|
||||
self.transform = transform
|
||||
@@ -303,18 +677,70 @@ public final class MapCursor<Base: Cursor, Element> : Cursor {
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
/// :nodoc:
|
||||
public func next() throws -> Element? {
|
||||
guard let element = try base.next() else { return nil }
|
||||
return try transform(element)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// A cursor that only consumes up to `n` elements from an underlying
|
||||
/// `Base` cursor.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class PrefixCursor<Base: Cursor> : Cursor {
|
||||
private let base: Base
|
||||
private let transform: (Base.Element) throws -> Element
|
||||
private let maxLength: Int
|
||||
private var taken = 0
|
||||
|
||||
init(_ base: Base, maxLength: Int) {
|
||||
self.base = base
|
||||
self.maxLength = maxLength
|
||||
}
|
||||
|
||||
public func next() throws -> Base.Element? {
|
||||
if taken >= maxLength { return nil }
|
||||
taken += 1
|
||||
|
||||
if let next = try base.next() {
|
||||
return next
|
||||
}
|
||||
|
||||
taken = maxLength
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor whose elements consist of the initial consecutive elements of
|
||||
/// some base cursor that satisfy a given predicate.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class PrefixWhileCursor<Base: Cursor> : Cursor {
|
||||
private let base: Base
|
||||
private let predicate: (Base.Element) throws -> Bool
|
||||
private var predicateHasFailed = false
|
||||
|
||||
init(_ base: Base, predicate: @escaping (Base.Element) throws -> Bool) {
|
||||
self.base = base
|
||||
self.predicate = predicate
|
||||
}
|
||||
|
||||
public func next() throws -> Base.Element? {
|
||||
if !predicateHasFailed, let nextElement = try base.next() {
|
||||
if try predicate(nextElement) {
|
||||
return nextElement
|
||||
} else {
|
||||
predicateHasFailed = true
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// A Cursor whose elements are those of a sequence iterator.
|
||||
public final class IteratorCursor<Base: IteratorProtocol> : Cursor {
|
||||
|
||||
private var base: Base
|
||||
|
||||
/// Creates a cursor from a sequence iterator.
|
||||
public init(_ base: Base) {
|
||||
self.base = base
|
||||
@@ -327,18 +753,8 @@ public final class IteratorCursor<Base: IteratorProtocol> : Cursor {
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
/// :nodoc:
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,530 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Database Schema
|
||||
|
||||
/// Clears the database schema cache.
|
||||
///
|
||||
/// You may need to clear the cache manually if the database schema is
|
||||
/// modified by another connection.
|
||||
public func clearSchemaCache() {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
schemaCache.clear()
|
||||
|
||||
// We also clear updateStatementCache and selectStatementCache despite
|
||||
// the automatic statement recompilation (see https://www.sqlite.org/c3ref/prepare.html)
|
||||
// because the automatic statement recompilation only happens a
|
||||
// limited number of times.
|
||||
internalStatementCache.clear()
|
||||
publicStatementCache.clear()
|
||||
}
|
||||
|
||||
/// Returns whether a table exists.
|
||||
public func tableExists(_ tableName: String) throws -> Bool {
|
||||
// SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html)
|
||||
return try Row.fetchOne(self, "SELECT 1 FROM (SELECT sql, type, name FROM sqlite_master UNION SELECT sql, type, name FROM sqlite_temp_master) WHERE type = 'table' AND LOWER(name) = ?", arguments: [tableName.lowercased()]) != nil
|
||||
}
|
||||
|
||||
/// Returns whether a view exists.
|
||||
public func viewExists(_ viewName: String) throws -> Bool {
|
||||
// SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html)
|
||||
return try Row.fetchOne(self, "SELECT 1 FROM (SELECT sql, type, name FROM sqlite_master UNION SELECT sql, type, name FROM sqlite_temp_master) WHERE type = 'view' AND LOWER(name) = ?", arguments: [viewName.lowercased()]) != nil
|
||||
}
|
||||
|
||||
/// Returns whether a trigger exists.
|
||||
public func triggerExists(_ triggerName: String) throws -> Bool {
|
||||
// SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html)
|
||||
return try Row.fetchOne(self, "SELECT 1 FROM (SELECT sql, type, name FROM sqlite_master UNION SELECT sql, type, name FROM sqlite_temp_master) WHERE type = 'trigger' AND LOWER(name) = ?", arguments: [triggerName.lowercased()]) != nil
|
||||
}
|
||||
|
||||
/// The primary key for table named `tableName`.
|
||||
///
|
||||
/// All tables have a primary key, even when it is not explicit. When a
|
||||
/// table has no explicit primary key, the result is the hidden
|
||||
/// "rowid" column.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
public func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
|
||||
if let primaryKey = schemaCache.primaryKey(tableName) {
|
||||
return primaryKey
|
||||
}
|
||||
|
||||
// https://www.sqlite.org/pragma.html
|
||||
//
|
||||
// > PRAGMA database.table_info(table-name);
|
||||
// >
|
||||
// > This pragma returns one row for each column in the named table.
|
||||
// > Columns in the result set include the column name, data type,
|
||||
// > whether or not the column can be NULL, and the default value for
|
||||
// > the column. The "pk" column in the result set is zero for columns
|
||||
// > that are not part of the primary key, and is the index of the
|
||||
// > column in the primary key for columns that are part of the primary
|
||||
// > key.
|
||||
//
|
||||
// CREATE TABLE players (
|
||||
// id INTEGER PRIMARY KEY,
|
||||
// name TEXT,
|
||||
// score INTEGER)
|
||||
//
|
||||
// PRAGMA table_info("players")
|
||||
//
|
||||
// cid | name | type | notnull | dflt_value | pk |
|
||||
// 0 | id | INTEGER | 0 | NULL | 1 |
|
||||
// 1 | name | TEXT | 0 | NULL | 0 |
|
||||
// 2 | score | INTEGER | 0 | NULL | 0 |
|
||||
|
||||
let columns = try self.columns(in: tableName)
|
||||
|
||||
let primaryKey: PrimaryKeyInfo
|
||||
let pkColumns = columns
|
||||
.filter { $0.primaryKeyIndex > 0 }
|
||||
.sorted { $0.primaryKeyIndex < $1.primaryKeyIndex }
|
||||
|
||||
switch pkColumns.count {
|
||||
case 0:
|
||||
// No explicit primary key => primary key is hidden rowID column
|
||||
primaryKey = .hiddenRowID
|
||||
case 1:
|
||||
// Single column
|
||||
let pkColumn = pkColumns.first!
|
||||
|
||||
// https://www.sqlite.org/lang_createtable.html:
|
||||
//
|
||||
// > With one exception noted below, if a rowid table has a primary
|
||||
// > key that consists of a single column and the declared type of
|
||||
// > that column is "INTEGER" in any mixture of upper and lower
|
||||
// > case, then the column becomes an alias for the rowid. Such a
|
||||
// > column is usually referred to as an "integer primary key".
|
||||
// > A PRIMARY KEY column only becomes an integer primary key if the
|
||||
// > declared type name is exactly "INTEGER". Other integer type
|
||||
// > names like "INT" or "BIGINT" or "SHORT INTEGER" or "UNSIGNED
|
||||
// > INTEGER" causes the primary key column to behave as an ordinary
|
||||
// > table column with integer affinity and a unique index, not as
|
||||
// > an alias for the rowid.
|
||||
// >
|
||||
// > The exception mentioned above is that if the declaration of a
|
||||
// > column with declared type "INTEGER" includes an "PRIMARY KEY
|
||||
// > DESC" clause, it does not become an alias for the rowid [...]
|
||||
//
|
||||
// FIXME: We ignore the exception, and consider all INTEGER primary
|
||||
// keys as aliases for the rowid:
|
||||
if pkColumn.type.uppercased() == "INTEGER" {
|
||||
primaryKey = .rowID(pkColumn.name)
|
||||
} else {
|
||||
primaryKey = .regular([pkColumn.name])
|
||||
}
|
||||
default:
|
||||
// Multi-columns primary key
|
||||
primaryKey = .regular(pkColumns.map { $0.name })
|
||||
}
|
||||
|
||||
schemaCache.set(primaryKey: primaryKey, forTable: tableName)
|
||||
return primaryKey
|
||||
}
|
||||
|
||||
/// The number of columns in the table named `tableName`.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
@available(*, deprecated, message: "Use db.columns(in: tableName).count instead")
|
||||
public func columnCount(in tableName: String) throws -> Int {
|
||||
return try columns(in: tableName).count
|
||||
}
|
||||
|
||||
/// The indexes on table named `tableName`; returns the empty array if the
|
||||
/// table does not exist.
|
||||
///
|
||||
/// Note: SQLite does not define any index for INTEGER PRIMARY KEY columns:
|
||||
/// this method does not return any index that represents this primary key.
|
||||
///
|
||||
/// If you want to know if a set of columns uniquely identify a row, prefer
|
||||
/// table(_:hasUniqueKey:) instead.
|
||||
public func indexes(on tableName: String) throws -> [IndexInfo] {
|
||||
if let indexes = schemaCache.indexes(on: tableName) {
|
||||
return indexes
|
||||
}
|
||||
|
||||
let indexes = try Row.fetchAll(self, "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))").map { row -> IndexInfo in
|
||||
let indexName: String = row[1]
|
||||
let unique: Bool = row[2]
|
||||
let columns = try Row.fetchAll(self, "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))")
|
||||
.map { ($0[0] as Int, $0[2] as String) }
|
||||
.sorted { $0.0 < $1.0 }
|
||||
.map { $0.1 }
|
||||
return IndexInfo(name: indexName, columns: columns, unique: unique)
|
||||
}
|
||||
|
||||
schemaCache.set(indexes: indexes, forTable: tableName)
|
||||
return indexes
|
||||
}
|
||||
|
||||
/// True if a sequence of columns uniquely identifies a row, that is to say
|
||||
/// if the columns are the primary key, or if there is a unique index on them.
|
||||
public func table<T: Sequence>(_ tableName: String, hasUniqueKey columns: T) throws -> Bool where T.Iterator.Element == String {
|
||||
return try columnsForUniqueKey(Array(columns), in: tableName) != nil
|
||||
}
|
||||
|
||||
/// The foreign keys defined on table named `tableName`.
|
||||
public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo] {
|
||||
if let foreignKeys = schemaCache.foreignKeys(on: tableName) {
|
||||
return foreignKeys
|
||||
}
|
||||
|
||||
var rawForeignKeys: [(destinationTable: String, mapping: [(origin: String, destination: String?, seq: Int)])] = []
|
||||
var previousId: Int? = nil
|
||||
for row in try Row.fetchAll(self, "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") {
|
||||
// row = <Row id:0 seq:0 table:"parents" from:"parentId" to:"id" on_update:"..." on_delete:"..." match:"...">
|
||||
let id: Int = row[0]
|
||||
let seq: Int = row[1]
|
||||
let table: String = row[2]
|
||||
let origin: String = row[3]
|
||||
let destination: String? = row[4]
|
||||
|
||||
if previousId == id {
|
||||
rawForeignKeys[rawForeignKeys.count - 1].mapping.append((origin: origin, destination: destination, seq: seq))
|
||||
} else {
|
||||
rawForeignKeys.append((destinationTable: table, mapping: [(origin: origin, destination: destination, seq: seq)]))
|
||||
previousId = id
|
||||
}
|
||||
}
|
||||
|
||||
let foreignKeys = try rawForeignKeys.map { (destinationTable, columnMapping) -> ForeignKeyInfo in
|
||||
let orderedMapping = columnMapping
|
||||
.sorted { $0.seq < $1.seq }
|
||||
.map { (origin: $0.origin, destination: $0 .destination) }
|
||||
|
||||
let completeMapping: [(origin: String, destination: String)]
|
||||
if orderedMapping.contains(where: { (_, destination) in destination == nil }) {
|
||||
let pk = try primaryKey(destinationTable)
|
||||
completeMapping = zip(pk.columns, orderedMapping).map { (pkColumn, arrow) in
|
||||
(origin: arrow.origin, destination: pkColumn)
|
||||
}
|
||||
} else {
|
||||
completeMapping = orderedMapping.map { (origin, destination) in
|
||||
(origin: origin, destination: destination!)
|
||||
}
|
||||
}
|
||||
return ForeignKeyInfo(destinationTable: destinationTable, mapping: completeMapping)
|
||||
}
|
||||
|
||||
schemaCache.set(foreignKeys: foreignKeys, forTable: tableName)
|
||||
return foreignKeys
|
||||
}
|
||||
|
||||
/// Returns the actual name of the database table
|
||||
func canonicalName(table: String) throws -> String {
|
||||
if let canonicalName = schemaCache.canonicalName(table: table) {
|
||||
return canonicalName
|
||||
}
|
||||
|
||||
guard let canonicalName = try String.fetchOne(self, """
|
||||
SELECT name FROM (
|
||||
SELECT name, type FROM sqlite_master
|
||||
UNION
|
||||
SELECT name, type FROM sqlite_temp_master)
|
||||
WHERE type = 'table' AND LOWER(name) = ?
|
||||
""", arguments: [table.lowercased()])
|
||||
else {
|
||||
throw DatabaseError(message: "no such table: \(table)")
|
||||
}
|
||||
|
||||
schemaCache.set(canonicalName: canonicalName, forTable: table)
|
||||
return canonicalName
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
/// The columns in the table named `tableName`
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
public func columns(in tableName: String) throws -> [ColumnInfo] {
|
||||
if let columns = schemaCache.columns(in: tableName) {
|
||||
return columns
|
||||
}
|
||||
|
||||
// https://www.sqlite.org/pragma.html
|
||||
//
|
||||
// > PRAGMA database.table_info(table-name);
|
||||
// >
|
||||
// > This pragma returns one row for each column in the named table.
|
||||
// > Columns in the result set include the column name, data type,
|
||||
// > whether or not the column can be NULL, and the default value for
|
||||
// > the column. The "pk" column in the result set is zero for columns
|
||||
// > that are not part of the primary key, and is the index of the
|
||||
// > column in the primary key for columns that are part of the primary
|
||||
// > key.
|
||||
//
|
||||
// CREATE TABLE players (
|
||||
// id INTEGER PRIMARY KEY,
|
||||
// firstName TEXT,
|
||||
// lastName TEXT)
|
||||
//
|
||||
// PRAGMA table_info("players")
|
||||
//
|
||||
// cid | name | type | notnull | dflt_value | pk |
|
||||
// 0 | id | INTEGER | 0 | NULL | 1 |
|
||||
// 1 | name | TEXT | 0 | NULL | 0 |
|
||||
// 2 | score | INTEGER | 0 | NULL | 0 |
|
||||
|
||||
if sqlite3_libversion_number() < 3008005 {
|
||||
// Work around a bug in SQLite where PRAGMA table_info would
|
||||
// return a result even after the table was deleted.
|
||||
if try !tableExists(tableName) {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
}
|
||||
}
|
||||
let columns = try ColumnInfo
|
||||
.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
|
||||
.sorted(by: { $0.cid < $1.cid })
|
||||
guard columns.count > 0 else {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
}
|
||||
|
||||
schemaCache.set(columns: columns, forTable: tableName)
|
||||
return columns
|
||||
}
|
||||
|
||||
/// If there exists a unique key on columns, return the columns
|
||||
/// ordered as the matching index (or primay key). Case of returned columns
|
||||
/// is not guaranteed.
|
||||
func columnsForUniqueKey<T: Sequence>(_ columns: T, in tableName: String) throws -> [String]? where T.Iterator.Element == String {
|
||||
let primaryKey = try self.primaryKey(tableName) // first, so that we fail early and consistently should the table not exist
|
||||
let lowercasedColumns = Set(columns.map { $0.lowercased() })
|
||||
if Set(primaryKey.columns.map { $0.lowercased() }) == lowercasedColumns {
|
||||
return primaryKey.columns
|
||||
}
|
||||
if let index = try indexes(on: tableName).first(where: { index in index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns }) {
|
||||
// There is an explicit unique index on the columns
|
||||
return index.columns
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// A column of a database table.
|
||||
///
|
||||
/// This type closely matches the information returned by the
|
||||
/// `table_info` pragma.
|
||||
///
|
||||
/// > CREATE TABLE players (
|
||||
/// id INTEGER PRIMARY KEY,
|
||||
/// firstName TEXT,
|
||||
/// lastName TEXT)
|
||||
/// > PRAGMA table_info("players")
|
||||
/// cid name type notnull dflt_value pk
|
||||
/// ---- ----- ------- -------- ---------- ---
|
||||
/// 0 id INTEGER 0 NULL 1
|
||||
/// 1 name TEXT 0 NULL 0
|
||||
/// 2 score INTEGER 0 NULL 0
|
||||
///
|
||||
/// See `Database.columns(in:)` and https://www.sqlite.org/pragma.html#pragma_table_info
|
||||
public struct ColumnInfo : RowConvertible {
|
||||
let cid: Int
|
||||
|
||||
/// The column name
|
||||
public let name: String
|
||||
|
||||
/// The column data type
|
||||
public let type: String
|
||||
|
||||
/// True if and only if the column is constrained to be not null.
|
||||
public let isNotNull: Bool
|
||||
|
||||
/// The SQL snippet that defines the default value, if any.
|
||||
///
|
||||
/// When nil, the column has no default value.
|
||||
///
|
||||
/// When not nil, it contains an SQL string that defines an expression. That
|
||||
/// expression may be a literal, as `1`, or `'foo'`. It may also contain a
|
||||
/// non-constant expression such as `CURRENT_TIMESTAMP`.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try db.execute("""
|
||||
/// CREATE TABLE players(
|
||||
/// id INTEGER PRIMARY KEY,
|
||||
/// name TEXT DEFAULT 'Anonymous',
|
||||
/// score INT DEFAULT 0,
|
||||
/// creationDate DATE DEFAULT CURRENT_TIMESTAMP
|
||||
/// )
|
||||
/// """)
|
||||
/// let columnInfos = try db.columns(in: "players")
|
||||
/// columnInfos[0].defaultValueSQL // nil
|
||||
/// columnInfos[1].defaultValueSQL // "'Anoynymous'"
|
||||
/// columnInfos[2].defaultValueSQL // "0"
|
||||
/// columnInfos[3].defaultValueSQL // "CURRENT_TIMESTAMP"
|
||||
public let defaultValueSQL: String?
|
||||
|
||||
/// Zero for columns that are not part of the primary key.
|
||||
///
|
||||
/// Before SQLite 3.7.16, it is 1 for columns that are part of the
|
||||
/// primary key.
|
||||
///
|
||||
/// Starting from SQLite 3.7.16, it is the one-based index of the column in
|
||||
/// the primary key for columns that are part of the primary key.
|
||||
///
|
||||
/// References:
|
||||
/// - https://sqlite.org/releaselog/3_7_16.html
|
||||
/// - http://mailinglists.sqlite.org/cgi-bin/mailman/private/sqlite-users/2013-April/046034.html
|
||||
public let primaryKeyIndex: Int
|
||||
|
||||
/// :nodoc:
|
||||
public init(row: Row) {
|
||||
cid = row["cid"]
|
||||
name = row["name"]
|
||||
type = row["type"]
|
||||
isNotNull = row["notnull"]
|
||||
defaultValueSQL = row["dflt_value"]
|
||||
primaryKeyIndex = row["pk"]
|
||||
}
|
||||
}
|
||||
|
||||
/// An index on a database table.
|
||||
///
|
||||
/// See `Database.indexes(on:)`
|
||||
public struct IndexInfo {
|
||||
/// The name of the index
|
||||
public let name: String
|
||||
|
||||
/// The indexed columns
|
||||
public let columns: [String]
|
||||
|
||||
/// True if the index is unique
|
||||
public let isUnique: Bool
|
||||
|
||||
init(name: String, columns: [String], unique: Bool) {
|
||||
self.name = name
|
||||
self.columns = columns
|
||||
self.isUnique = unique
|
||||
}
|
||||
}
|
||||
|
||||
/// Primary keys are returned from the Database.primaryKey(_:) method.
|
||||
///
|
||||
/// When the table's primary key is the rowid:
|
||||
///
|
||||
/// // CREATE TABLE items (name TEXT)
|
||||
/// let pk = try db.primaryKey("items")
|
||||
/// pk.columns // ["rowid"]
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // true
|
||||
///
|
||||
/// // CREATE TABLE citizens (
|
||||
/// // id INTEGER PRIMARY KEY,
|
||||
/// // name TEXT
|
||||
/// // )
|
||||
/// let pk = try db.primaryKey("citizens")!
|
||||
/// pk.columns // ["id"]
|
||||
/// pk.rowIDColumn // "id"
|
||||
/// pk.isRowID // true
|
||||
///
|
||||
/// When the table's primary key is not the rowid:
|
||||
///
|
||||
/// // CREATE TABLE countries (
|
||||
/// // isoCode TEXT NOT NULL PRIMARY KEY
|
||||
/// // name TEXT
|
||||
/// // )
|
||||
/// let pk = db.primaryKey("countries")!
|
||||
/// pk.columns // ["isoCode"]
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // false
|
||||
///
|
||||
/// // CREATE TABLE citizenships (
|
||||
/// // citizenID INTEGER NOT NULL REFERENCES citizens(id)
|
||||
/// // countryIsoCode TEXT NOT NULL REFERENCES countries(isoCode)
|
||||
/// // PRIMARY KEY (citizenID, countryIsoCode)
|
||||
/// // )
|
||||
/// let pk = db.primaryKey("citizenships")!
|
||||
/// pk.columns // ["citizenID", "countryIsoCode"]
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // false
|
||||
public struct PrimaryKeyInfo {
|
||||
private enum Impl {
|
||||
/// The hidden rowID.
|
||||
case hiddenRowID
|
||||
|
||||
/// An INTEGER PRIMARY KEY column that aliases the Row ID.
|
||||
/// Associated string is the column name.
|
||||
case rowID(String)
|
||||
|
||||
/// Any primary key, but INTEGER PRIMARY KEY.
|
||||
/// Associated strings are column names.
|
||||
case regular([String])
|
||||
}
|
||||
|
||||
private let impl: Impl
|
||||
|
||||
static func rowID(_ column: String) -> PrimaryKeyInfo {
|
||||
return PrimaryKeyInfo(impl: .rowID(column))
|
||||
}
|
||||
|
||||
static func regular(_ columns: [String]) -> PrimaryKeyInfo {
|
||||
assert(!columns.isEmpty)
|
||||
return PrimaryKeyInfo(impl: .regular(columns))
|
||||
}
|
||||
|
||||
static let hiddenRowID = PrimaryKeyInfo(impl: .hiddenRowID)
|
||||
|
||||
/// The columns in the primary key; this array is never empty.
|
||||
public var columns: [String] {
|
||||
switch impl {
|
||||
case .hiddenRowID:
|
||||
return [Column.rowID.name]
|
||||
case .rowID(let column):
|
||||
return [column]
|
||||
case .regular(let columns):
|
||||
return columns
|
||||
}
|
||||
}
|
||||
|
||||
/// When not nil, the name of the column that contains the INTEGER PRIMARY KEY.
|
||||
public var rowIDColumn: String? {
|
||||
switch impl {
|
||||
case .hiddenRowID:
|
||||
return nil
|
||||
case .rowID(let column):
|
||||
return column
|
||||
case .regular:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// When true, the primary key is the rowid:
|
||||
public var isRowID: Bool {
|
||||
switch impl {
|
||||
case .hiddenRowID:
|
||||
return true
|
||||
case .rowID:
|
||||
return true
|
||||
case .regular:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// You get foreign keys from table names, with the
|
||||
/// `foreignKeys(on:)` method.
|
||||
public struct ForeignKeyInfo {
|
||||
/// The name of the destination table
|
||||
public let destinationTable: String
|
||||
|
||||
/// The column to column mapping
|
||||
public let mapping: [(origin: String, destination: String)]
|
||||
|
||||
/// The origin columns
|
||||
public var originColumns: [String] {
|
||||
return mapping.map { $0.origin }
|
||||
}
|
||||
|
||||
/// The destination columns
|
||||
public var destinationColumns: [String] {
|
||||
return mapping.map { $0.destination }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
import Foundation
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Statements
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?")
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: A SelectStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func makeSelectStatement(_ sql: String) throws -> SelectStatement {
|
||||
return try makeSelectStatement(sql, prepFlags: 0)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?", prepFlags: 0)
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
/// - returns: A SelectStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
func makeSelectStatement(_ sql: String, prepFlags: Int32) throws -> SelectStatement {
|
||||
return try SelectStatement.prepare(sql: sql, prepFlags: prepFlags, in: self)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?")
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
///
|
||||
/// The returned statement may have already been used: it may or may not
|
||||
/// contain values for its eventual arguments.
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func cachedSelectStatement(_ sql: String) throws -> SelectStatement {
|
||||
return try publicStatementCache.selectStatement(sql)
|
||||
}
|
||||
|
||||
/// Returns a cached statement that does not conflict with user's cached statements.
|
||||
func internalCachedSelectStatement(_ sql: String) throws -> SelectStatement {
|
||||
return try internalStatementCache.selectStatement(sql)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeUpdateStatement("INSERT INTO players (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func makeUpdateStatement(_ sql: String) throws -> UpdateStatement {
|
||||
return try makeUpdateStatement(sql, prepFlags: 0)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeUpdateStatement("INSERT INTO players (name) VALUES (?)", prepFlags: 0)
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
func makeUpdateStatement(_ sql: String, prepFlags: Int32) throws -> UpdateStatement {
|
||||
return try UpdateStatement.prepare(sql: sql, prepFlags: prepFlags, in: self)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedUpdateStatement("INSERT INTO players (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// The returned statement may have already been used: it may or may not
|
||||
/// contain values for its eventual arguments.
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func cachedUpdateStatement(_ sql: String) throws -> UpdateStatement {
|
||||
return try publicStatementCache.updateStatement(sql)
|
||||
}
|
||||
|
||||
/// Returns a cached statement that does not conflict with user's cached statements.
|
||||
func internalCachedUpdateStatement(_ sql: String) throws -> UpdateStatement {
|
||||
return try internalStatementCache.updateStatement(sql)
|
||||
}
|
||||
|
||||
/// Executes one or several SQL statements, separated by semi-colons.
|
||||
///
|
||||
/// try db.execute(
|
||||
/// "INSERT INTO players (name) VALUES (:name)",
|
||||
/// arguments: ["name": "Arthur"])
|
||||
///
|
||||
/// try db.execute("""
|
||||
/// INSERT INTO players (name) VALUES (?);
|
||||
/// INSERT INTO players (name) VALUES (?);
|
||||
/// INSERT INTO players (name) VALUES (?);
|
||||
/// """, arguments; ['Arthur', 'Barbara', 'Craig'])
|
||||
///
|
||||
/// This method may throw a DatabaseError.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func execute(_ sql: String, arguments: StatementArguments? = nil) throws {
|
||||
// This method is like sqlite3_exec (https://www.sqlite.org/c3ref/exec.html)
|
||||
// It adds support for arguments, and the tricky part is to consume
|
||||
// arguments as statements are executed.
|
||||
//
|
||||
// Here we build two functions:
|
||||
// - consumeArguments returns arguments for a statement
|
||||
// - validateRemainingArguments validates the remaining arguments, after
|
||||
// all statements have been executed, in the same way
|
||||
// as Statement.validate(arguments:)
|
||||
|
||||
var arguments = arguments ?? StatementArguments()
|
||||
let initialValuesCount = arguments.values.count
|
||||
let consumeArguments = { (statement: UpdateStatement) throws -> StatementArguments in
|
||||
let bindings = try arguments.consume(statement, allowingRemainingValues: true)
|
||||
return StatementArguments(bindings)
|
||||
}
|
||||
let validateRemainingArguments = {
|
||||
if !arguments.values.isEmpty {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)")
|
||||
}
|
||||
}
|
||||
|
||||
// Iterate SQL statements
|
||||
let sqlCodeUnits = sql.utf8CString
|
||||
try sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
|
||||
let sqlStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
|
||||
let sqlEnd = sqlStart + sqlCodeUnits.count
|
||||
var statementStart = sqlStart
|
||||
while statementStart < sqlEnd - 1 {
|
||||
var statementEnd: UnsafePointer<Int8>? = nil
|
||||
do {
|
||||
let statement: UpdateStatement
|
||||
// Compile
|
||||
do {
|
||||
let statementCompilationAuthorizer = StatementCompilationAuthorizer()
|
||||
authorizer = statementCompilationAuthorizer
|
||||
defer { authorizer = nil }
|
||||
|
||||
statement = try UpdateStatement(
|
||||
database: self,
|
||||
statementStart: statementStart,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: 0,
|
||||
authorizer: statementCompilationAuthorizer)
|
||||
}
|
||||
|
||||
// Execute
|
||||
let arguments = try consumeArguments(statement)
|
||||
statement.unsafeSetArguments(arguments)
|
||||
try statement.execute()
|
||||
|
||||
// Next
|
||||
statementStart = statementEnd!
|
||||
} catch is EmptyStatementError {
|
||||
// End
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Force arguments validity: it is a programmer error to provide
|
||||
// arguments that do not match the statement.
|
||||
try! validateRemainingArguments() // throws if there are remaining arguments.
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
func updateStatementWillExecute(_ statement: UpdateStatement) {
|
||||
observationBroker.updateStatementWillExecute(statement)
|
||||
}
|
||||
|
||||
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
|
||||
if statement.invalidatesDatabaseSchemaCache {
|
||||
clearSchemaCache()
|
||||
}
|
||||
|
||||
try observationBroker.updateStatementDidExecute(statement)
|
||||
}
|
||||
|
||||
func updateStatementDidFail(_ statement: UpdateStatement) throws {
|
||||
// Failed statements can not be reused, because sqlite3_reset won't
|
||||
// be able to restore the statement to its initial state:
|
||||
// https://www.sqlite.org/c3ref/reset.html
|
||||
//
|
||||
// So make sure we clear this statement from the cache.
|
||||
internalStatementCache.remove(statement)
|
||||
publicStatementCache.remove(statement)
|
||||
|
||||
try observationBroker.updateStatementDidFail(statement)
|
||||
}
|
||||
|
||||
func selectStatementDidFail(_ statement: SelectStatement) {
|
||||
// Failed statements can not be reused, because sqlite3_reset won't
|
||||
// be able to restore the statement to its initial state:
|
||||
// https://www.sqlite.org/c3ref/reset.html
|
||||
//
|
||||
// So make sure we clear this statement from the cache.
|
||||
internalStatementCache.remove(statement)
|
||||
publicStatementCache.remove(statement)
|
||||
}
|
||||
}
|
||||
+376
-2189
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,53 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// A Collation is a string comparison function used by SQLite.
|
||||
public final class DatabaseCollation {
|
||||
public let name: String
|
||||
let function: (Int32, UnsafeRawPointer?, Int32, UnsafeRawPointer?) -> ComparisonResult
|
||||
|
||||
/// Creates a collation.
|
||||
///
|
||||
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// db.add(collation: collation)
|
||||
/// try db.execute("CREATE TABLE files (name TEXT COLLATE localized_standard")
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The function name.
|
||||
/// - function: A function that compares two strings.
|
||||
public init(_ name: String, function: @escaping (String, String) -> ComparisonResult) {
|
||||
self.name = name
|
||||
self.function = { (length1, buffer1, length2, buffer2) in
|
||||
// Buffers are not C strings: they do not end with \0.
|
||||
let string1 = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped), length: Int(length1), encoding: .utf8, freeWhenDone: false)!
|
||||
let string2 = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped), length: Int(length2), encoding: .utf8, freeWhenDone: false)!
|
||||
return function(string1, string2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseCollation : Hashable {
|
||||
/// :nodoc:
|
||||
public var hashValue: Int {
|
||||
// Collation equality is based on the sqlite3_strnicmp SQLite function.
|
||||
// (see https://www.sqlite.org/c3ref/create_collation.html). Computing
|
||||
// a hash value that honors the Swift Hashable contract (value equality
|
||||
// implies hash equality) is thus non trivial. But it's not that
|
||||
// important, since this hashValue is only used when one adds
|
||||
// or removes a collation from a database connection.
|
||||
return 0
|
||||
}
|
||||
|
||||
/// Two collations are equal if they share the same name (case insensitive)
|
||||
/// :nodoc:
|
||||
public static func == (lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool {
|
||||
// See https://www.sqlite.org/c3ref/create_collation.html
|
||||
return sqlite3_stricmp(lhs.name, lhs.name) == 0
|
||||
}
|
||||
}
|
||||
@@ -25,24 +25,6 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
|
||||
return self == primaryResultCode
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
// sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, iOSApplicationExtension 8.2, *) {
|
||||
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
|
||||
} else {
|
||||
return "\(rawValue)"
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
public static func == (_ lhs: ResultCode, _ rhs: ResultCode) -> Bool {
|
||||
return lhs.rawValue == rhs.rawValue
|
||||
}
|
||||
|
||||
/// Returns true if the code on the left matches the code on the right.
|
||||
///
|
||||
/// Primary result codes match themselves and their extended result codes,
|
||||
@@ -155,11 +137,36 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
|
||||
public static let SQLITE_WARNING_AUTOINDEX = ResultCode(rawValue: (SQLITE_WARNING.rawValue | (1<<8)))
|
||||
public static let SQLITE_AUTH_USER = ResultCode(rawValue: (SQLITE_AUTH.rawValue | (1<<8)))
|
||||
public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8)))
|
||||
}
|
||||
|
||||
// Equatable
|
||||
extension ResultCode {
|
||||
/// :nodoc:
|
||||
public static func == (_ lhs: ResultCode, _ rhs: ResultCode) -> Bool {
|
||||
return lhs.rawValue == rhs.rawValue
|
||||
}
|
||||
}
|
||||
|
||||
// CustomStringConvertible
|
||||
extension ResultCode {
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
// sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, iOSApplicationExtension 8.2, *) {
|
||||
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
|
||||
} else {
|
||||
return "\(rawValue)"
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
/// DatabaseError wraps an SQLite error.
|
||||
public struct DatabaseError : Error {
|
||||
public struct DatabaseError : Error, CustomStringConvertible, CustomNSError {
|
||||
|
||||
/// The SQLite error code (see
|
||||
/// https://www.sqlite.org/rescode.html#primary_result_code_list).
|
||||
@@ -220,8 +227,9 @@ public struct DatabaseError : Error {
|
||||
let arguments: StatementArguments?
|
||||
}
|
||||
|
||||
extension DatabaseError: CustomStringConvertible {
|
||||
/// A textual representation of `self`.
|
||||
// CustomStringConvertible
|
||||
extension DatabaseError {
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
var description = "SQLite error \(resultCode.rawValue)"
|
||||
if let sql = sql {
|
||||
@@ -237,19 +245,23 @@ extension DatabaseError: CustomStringConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseError : CustomNSError {
|
||||
// CustomNSError
|
||||
extension DatabaseError {
|
||||
|
||||
/// NSError bridging: the domain of the error.
|
||||
/// :nodoc:
|
||||
public static var errorDomain: String {
|
||||
return "GRDB.DatabaseError"
|
||||
}
|
||||
|
||||
/// NSError bridging: the error code within the given domain.
|
||||
/// :nodoc:
|
||||
public var errorCode: Int {
|
||||
return Int(extendedResultCode.rawValue)
|
||||
}
|
||||
|
||||
/// NSError bridging: the user-info dictionary.
|
||||
/// :nodoc:
|
||||
public var errorUserInfo: [String : Any] {
|
||||
return [NSLocalizedDescriptionKey: description]
|
||||
}
|
||||
|
||||
@@ -311,11 +311,13 @@ public final class DatabaseFunction {
|
||||
|
||||
extension DatabaseFunction : Hashable {
|
||||
/// The hash value
|
||||
/// :nodoc:
|
||||
public var hashValue: Int {
|
||||
return name.hashValue ^ nArg.hashValue
|
||||
}
|
||||
|
||||
/// Two functions are equal if they share the same name and arity.
|
||||
/// :nodoc:
|
||||
public static func == (lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool {
|
||||
return lhs.name == rhs.name && lhs.nArg == rhs.nArg
|
||||
}
|
||||
|
||||
+107
-64
@@ -10,8 +10,25 @@ import Foundation
|
||||
|
||||
/// A DatabasePool grants concurrent accesses to an SQLite database.
|
||||
public final class DatabasePool {
|
||||
private let writer: SerializedDatabase
|
||||
private var readerConfig: Configuration
|
||||
private var readerPool: Pool<SerializedDatabase>!
|
||||
|
||||
// MARK: - Initializers
|
||||
private var functions = Set<DatabaseFunction>()
|
||||
private var collations = Set<DatabaseCollation>()
|
||||
|
||||
#if os(iOS)
|
||||
private weak var application: UIApplication?
|
||||
#endif
|
||||
|
||||
// MARK: - Database Information
|
||||
|
||||
/// The path to the database.
|
||||
public var path: String {
|
||||
return writer.path
|
||||
}
|
||||
|
||||
// MARK: - Initializer
|
||||
|
||||
/// Opens the SQLite database at path *path*.
|
||||
///
|
||||
@@ -22,19 +39,15 @@ public final class DatabasePool {
|
||||
/// - parameters:
|
||||
/// - path: The path to the database file.
|
||||
/// - configuration: A configuration.
|
||||
/// - maximumReaderCount: The maximum number of readers. Default is 5.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public init(path: String, configuration: Configuration = Configuration()) throws {
|
||||
GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1")
|
||||
|
||||
// Writer and readers share the same database schema cache
|
||||
let sharedSchemaCache = SharedDatabaseSchemaCache()
|
||||
|
||||
// Writer
|
||||
writer = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
schemaCache: sharedSchemaCache)
|
||||
schemaCache: SimpleDatabaseSchemaCache())
|
||||
|
||||
// Activate WAL Mode unless readonly
|
||||
if !configuration.readonly {
|
||||
@@ -63,21 +76,13 @@ public final class DatabasePool {
|
||||
readerConfig = configuration
|
||||
readerConfig.readonly = true
|
||||
readerConfig.defaultTransactionKind = .deferred // Make it the default for readers. Other transaction kinds are forbidden by SQLite in read-only connections.
|
||||
readerConfig.allowsUnsafeTransactions = false // Because there's no guarantee that one can get the same reader in order to close its opened transaction.
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
schemaCache: SimpleDatabaseSchemaCache())
|
||||
reader.sync { self.setupDatabase($0) }
|
||||
return reader
|
||||
})
|
||||
}
|
||||
@@ -92,17 +97,20 @@ public final class DatabasePool {
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// The path to the database.
|
||||
public var path: String {
|
||||
return writer.path
|
||||
private func setupDatabase(_ db: Database) {
|
||||
for function in self.functions {
|
||||
db.add(function: function)
|
||||
}
|
||||
for collation in self.collations {
|
||||
db.add(collation: collation)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - WAL Management
|
||||
|
||||
}
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
// MARK: - WAL Checkpoints
|
||||
|
||||
/// Runs a WAL checkpoint
|
||||
///
|
||||
/// See https://www.sqlite.org/wal.html and
|
||||
@@ -121,10 +129,12 @@ public final class DatabasePool {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
// MARK: - Memory management
|
||||
|
||||
|
||||
/// Free as much memory as possible.
|
||||
///
|
||||
/// This method blocks the current thread until all database accesses are completed.
|
||||
@@ -155,8 +165,6 @@ public final class DatabasePool {
|
||||
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
|
||||
@@ -183,24 +191,12 @@ public final class DatabasePool {
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// MARK: - Not public
|
||||
|
||||
private let writer: 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>()
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - Encryption
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
extension DatabasePool {
|
||||
|
||||
// MARK: - Encryption
|
||||
|
||||
/// Changes the passphrase of an encrypted database
|
||||
public func change(passphrase: String) throws {
|
||||
@@ -212,14 +208,10 @@ public final class DatabasePool {
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - DatabaseReader
|
||||
|
||||
extension DatabasePool : DatabaseReader {
|
||||
|
||||
// MARK: - Read From Database
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// Synchronously executes a read-only block in a protected dispatch queue,
|
||||
/// and returns its result. The block is wrapped in a deferred transaction.
|
||||
///
|
||||
@@ -255,6 +247,8 @@ extension DatabasePool : DatabaseReader {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
// See DatabasePoolTests.testReadMethodIsolationOfBlock().
|
||||
try db.inTransaction(.deferred) {
|
||||
// Reset the schema cache before running user code in snapshot isolation
|
||||
db.schemaCache = SimpleDatabaseSchemaCache()
|
||||
result = try block(db)
|
||||
return .commit
|
||||
}
|
||||
@@ -292,7 +286,11 @@ extension DatabasePool : DatabaseReader {
|
||||
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)
|
||||
try reader.sync { db in
|
||||
// No schema cache when snapshot isolation is not established
|
||||
db.schemaCache = EmptyDatabaseSchemaCache()
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -328,7 +326,11 @@ extension DatabasePool : DatabaseReader {
|
||||
return try reader.reentrantSync(block)
|
||||
} else {
|
||||
return try readerPool.get { reader in
|
||||
try reader.sync(block)
|
||||
try reader.sync { db in
|
||||
// No schema cache when snapshot isolation is not established
|
||||
db.schemaCache = EmptyDatabaseSchemaCache()
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -355,7 +357,6 @@ extension DatabasePool : DatabaseReader {
|
||||
return readers.first { $0.onValidQueue }
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
@@ -387,7 +388,6 @@ extension DatabasePool : DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// Add or redefine a collation.
|
||||
@@ -417,10 +417,6 @@ extension DatabasePool : DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - DatabaseWriter
|
||||
|
||||
extension DatabasePool : DatabaseWriter {
|
||||
|
||||
// MARK: - Writing in Database
|
||||
@@ -510,13 +506,13 @@ extension DatabasePool : DatabaseWriter {
|
||||
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.
|
||||
/// This method must be called from the writing dispatch queue, outside of a
|
||||
/// transaction. You'll get a fatal error otherwise.
|
||||
///
|
||||
/// The *block* argument is guaranteed to see the database in the last
|
||||
/// committed state at the moment this method is called. Eventual concurrent
|
||||
@@ -582,8 +578,11 @@ extension DatabasePool : DatabaseWriter {
|
||||
// UPDATE ...
|
||||
// Here the change is not visible by GRDB user
|
||||
|
||||
// This method must be called from the writing dispatch queue:
|
||||
writer.preconditionValidQueue()
|
||||
// Check that we're on the writer queue...
|
||||
writer.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction.")
|
||||
}
|
||||
|
||||
// The semaphore that blocks the writing dispatch queue until snapshot
|
||||
// isolation has been established:
|
||||
@@ -602,7 +601,11 @@ extension DatabasePool : DatabaseWriter {
|
||||
return
|
||||
}
|
||||
semaphore.signal() // We can release the writer queue now that we are isolated for good
|
||||
|
||||
// Reset the schema cache before running user code in snapshot isolation
|
||||
db.schemaCache = SimpleDatabaseSchemaCache()
|
||||
block(db)
|
||||
|
||||
_ = try? db.commit() // Ignore commit error
|
||||
}
|
||||
}
|
||||
@@ -613,3 +616,43 @@ extension DatabasePool : DatabaseWriter {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
// MARK: - Snapshots
|
||||
|
||||
/// Creates a database snapshot.
|
||||
//:
|
||||
/// The snapshot sees an unchanging database content, as it existed at the
|
||||
/// moment it was created.
|
||||
///
|
||||
/// When you want to control the latest committed changes seen by a
|
||||
/// snapshot, create it from the pool's writer protected dispatch queue:
|
||||
///
|
||||
/// let snapshot1 = try dbPool.write { db -> DatabaseSnapshot in
|
||||
/// try Player.deleteAll()
|
||||
/// return dbPool.makeSnapshot()
|
||||
/// }
|
||||
/// // <- Other threads may modify the database here
|
||||
/// let snapshot2 = try dbPool.makeSnapshot()
|
||||
///
|
||||
/// try snapshot1.read { db in
|
||||
/// // Guaranteed to be zero
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// try snapshot2.read { db in
|
||||
/// // Could be anything
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// You can create as many snapshots as you need, regardless of the maximum
|
||||
/// number of reader connections in the pool.
|
||||
///
|
||||
/// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html
|
||||
public func makeSnapshot() throws -> DatabaseSnapshot {
|
||||
let snapshot = try DatabaseSnapshot(path: path, configuration: writer.configuration)
|
||||
snapshot.read { setupDatabase($0) }
|
||||
return snapshot
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,22 @@ import UIKit
|
||||
|
||||
/// A DatabaseQueue serializes access to an SQLite database.
|
||||
public final class DatabaseQueue {
|
||||
private var serializedDatabase: SerializedDatabase
|
||||
#if os(iOS)
|
||||
private weak var application: UIApplication?
|
||||
#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: - Initializers
|
||||
|
||||
@@ -50,23 +66,12 @@ public final class DatabaseQueue {
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// The database configuration
|
||||
public var configuration: Configuration {
|
||||
return serializedDatabase.configuration
|
||||
}
|
||||
|
||||
/// The path to the database file; it is ":memory:" for in-memory databases.
|
||||
public var path: String {
|
||||
return serializedDatabase.path
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Database access
|
||||
|
||||
}
|
||||
|
||||
extension DatabaseQueue {
|
||||
|
||||
// MARK: - Database Access
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
@@ -111,10 +116,12 @@ public final class DatabaseQueue {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
extension DatabaseQueue {
|
||||
|
||||
// MARK: - Memory management
|
||||
|
||||
|
||||
/// Free as much memory as possible.
|
||||
///
|
||||
/// This method blocks the current thread until all database accesses are completed.
|
||||
@@ -124,7 +131,6 @@ public final class DatabaseQueue {
|
||||
inDatabase { $0.releaseMemory() }
|
||||
}
|
||||
|
||||
|
||||
#if os(iOS)
|
||||
/// Listens to UIApplicationDidEnterBackgroundNotification and
|
||||
/// UIApplicationDidReceiveMemoryWarningNotification in order to release
|
||||
@@ -140,8 +146,6 @@ public final class DatabaseQueue {
|
||||
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
|
||||
@@ -168,37 +172,13 @@ public final class DatabaseQueue {
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// MARK: - Not public
|
||||
|
||||
// https://www.sqlite.org/isolation.html
|
||||
//
|
||||
// > Within a single database connection X, a SELECT statement always
|
||||
// > sees all changes to the database that are completed prior to the
|
||||
// > start of the SELECT statement, whether committed or uncommitted.
|
||||
// > And the SELECT statement obviously does not see any changes that
|
||||
// > occur after the SELECT statement completes. But what about changes
|
||||
// > that occur while the SELECT statement is running? What if a SELECT
|
||||
// > statement is started and the sqlite3_step() interface steps through
|
||||
// > roughly half of its output, then some UPDATE statements are run by
|
||||
// > the application that modify the table that the SELECT statement is
|
||||
// > reading, then more calls to sqlite3_step() are made to finish out
|
||||
// > the SELECT statement? Will the later steps of the SELECT statement
|
||||
// > see the changes made by the UPDATE or not? The answer is that this
|
||||
// > behavior is undefined.
|
||||
//
|
||||
// This is why we use a serialized database:
|
||||
private var serializedDatabase: SerializedDatabase
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - Encryption
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
extension DatabaseQueue {
|
||||
|
||||
|
||||
// MARK: - Encryption
|
||||
|
||||
/// Changes the passphrase of an encrypted database
|
||||
public func change(passphrase: String) throws {
|
||||
try inDatabase { try $0.change(passphrase: passphrase) }
|
||||
@@ -206,13 +186,9 @@ public final class DatabaseQueue {
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - DatabaseReader
|
||||
|
||||
extension DatabaseQueue : DatabaseReader {
|
||||
|
||||
// MARK: - DatabaseReader Protocol Adoption
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// Synchronously executes a read-only block in a protected dispatch queue,
|
||||
/// and returns its result.
|
||||
@@ -244,6 +220,8 @@ extension DatabaseQueue : DatabaseReader {
|
||||
}
|
||||
|
||||
/// Alias for `inDatabase`. See `DatabaseReader.unsafeRead`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try inDatabase(block)
|
||||
}
|
||||
@@ -257,11 +235,12 @@ extension DatabaseQueue : DatabaseReader {
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try serializedDatabase.reentrantSync(block)
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
@@ -285,7 +264,6 @@ extension DatabaseQueue : DatabaseReader {
|
||||
inDatabase { $0.remove(function: function) }
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// Add or redefine a collation.
|
||||
@@ -307,15 +285,11 @@ extension DatabaseQueue : DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - DatabaseWriter
|
||||
|
||||
extension DatabaseQueue : DatabaseWriter {
|
||||
|
||||
// MARK: - DatabaseWriter Protocol Adoption
|
||||
|
||||
|
||||
/// Alias for `inDatabase`. See `DatabaseWriter.write`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try inDatabase(block)
|
||||
}
|
||||
@@ -326,22 +300,34 @@ extension DatabaseQueue : DatabaseWriter {
|
||||
/// 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.
|
||||
/// This method must be called from the protected database dispatch queue,
|
||||
/// outside of a transaction. You'll get a fatal error otherwise.
|
||||
///
|
||||
/// See `DatabaseWriter.readFromCurrentState`.
|
||||
///
|
||||
/// :nodoc:
|
||||
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
|
||||
// Check that we're on the correct queue...
|
||||
serializedDatabase.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction.")
|
||||
|
||||
// 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
|
||||
readOnly(db, block)
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, *) {
|
||||
readOnly(db, block)
|
||||
} else {
|
||||
block(db)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Unsafe Database Access
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
@@ -356,19 +342,13 @@ extension DatabaseQueue : DatabaseWriter {
|
||||
}
|
||||
}
|
||||
|
||||
// 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 {
|
||||
guard !db.configuration.readonly else {
|
||||
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
|
||||
}
|
||||
|
||||
// Assume those pragmas never fail
|
||||
try! db.execute("PRAGMA query_only = 1")
|
||||
defer { try! db.execute("PRAGMA query_only = 0") }
|
||||
return try block(db)
|
||||
}
|
||||
|
||||
|
||||
@@ -221,30 +221,43 @@ public final class AnyDatabaseReader : DatabaseReader {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// :nodoc:
|
||||
public func read<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.read(block)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeRead(block)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeReentrantRead(block)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// :nodoc:
|
||||
public func add(function: DatabaseFunction) {
|
||||
base.add(function: function)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func remove(function: DatabaseFunction) {
|
||||
base.remove(function: function)
|
||||
}
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// :nodoc:
|
||||
public func add(collation: DatabaseCollation) {
|
||||
base.add(collation: collation)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
base.remove(collation: collation)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
/// DatabaseRegion defines a region in the database. DatabaseRegion is dedicated
|
||||
/// to help transaction observers recognize impactful database changes in their
|
||||
/// `observes(eventsOfKind:)` and `databaseDidChange(with:)` methods.
|
||||
///
|
||||
/// A database region is the union of any number of "table regions", which can
|
||||
/// cover a full table, or the combination of columns and rows (identified by
|
||||
/// their rowids):
|
||||
///
|
||||
/// |Table1 | |Table2 | |Table3 | |Table4 | |Table5 |
|
||||
/// |-------| |-------| |-------| |-------| |-------|
|
||||
/// |x|x|x|x| |x| | | | |x|x|x|x| |x|x| |x| | | | | |
|
||||
/// |x|x|x|x| |x| | | | | | | | | | | | | | | |x| | |
|
||||
/// |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | |
|
||||
/// |x|x|x|x| |x| | | | | | | | | | | | | | | | | | |
|
||||
///
|
||||
/// You don't create a database region directly. Instead, you use one of
|
||||
/// those methods:
|
||||
///
|
||||
/// - `SelectStatement.fetchedRegion`:
|
||||
///
|
||||
/// let statement = db.makeSelectStatement("SELECT name, score FROM players")
|
||||
/// print(statement.fetchedRegion)
|
||||
/// // prints "players(name,score)"
|
||||
///
|
||||
/// - `Request.fetchedRegion(_:)`
|
||||
///
|
||||
/// let request = Player.filter(key: 1)
|
||||
/// try print(request.fetchedRegion(db))
|
||||
/// // prints "players(*)[1]"
|
||||
///
|
||||
/// Database regions returned by requests can be more precise than regions
|
||||
/// returned by select statements. Especially, regions returned by statements
|
||||
/// don't know about rowids:
|
||||
///
|
||||
/// // A plain statement
|
||||
/// let statement = db.makeSelectStatement("SELECT * FROM players WHERE id = 1")
|
||||
/// statement.fetchedRegion // "players(*)"
|
||||
///
|
||||
/// // A query interface request that executes the same statement:
|
||||
/// let request = Player.filter(key: 1)
|
||||
/// try request.fetchedRegion(db) // "players(*)[1]"
|
||||
public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
private let tableRegions: [String: TableRegion]?
|
||||
private init(tableRegions: [String: TableRegion]?) {
|
||||
self.tableRegions = tableRegions
|
||||
}
|
||||
|
||||
/// Returns whether the region is empty.
|
||||
public var isEmpty: Bool {
|
||||
guard let tableRegions = tableRegions else { return false }
|
||||
return tableRegions.isEmpty
|
||||
}
|
||||
|
||||
/// The full database: (All columns in all tables) × (all rows)
|
||||
static let fullDatabase = DatabaseRegion(tableRegions: nil)
|
||||
|
||||
/// The empty database region
|
||||
public init() {
|
||||
self.init(tableRegions: [:])
|
||||
}
|
||||
|
||||
/// A full table: (all columns in the table) × (all rows)
|
||||
init(table: String) {
|
||||
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: nil)])
|
||||
}
|
||||
|
||||
/// Full columns in a table: (some columns in a table) × (all rows)
|
||||
init(table: String, columns: Set<String>) {
|
||||
self.init(tableRegions: [table: TableRegion(columns: columns, rowIds: nil)])
|
||||
}
|
||||
|
||||
/// Full rows in a table: (all columns in a table) × (some rows)
|
||||
init(table: String, rowIds: Set<Int64>) {
|
||||
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: rowIds)])
|
||||
}
|
||||
|
||||
/// Returns the intersection of this region and the given one.
|
||||
///
|
||||
/// This method is not public because there is no known public use case for
|
||||
/// this intersection. It is currently only used as support for
|
||||
/// the isModified(byEventsOfKind:) method.
|
||||
func intersection(_ other: DatabaseRegion) -> DatabaseRegion {
|
||||
guard let tableRegions = tableRegions else { return other }
|
||||
guard let otherTableRegions = other.tableRegions else { return self }
|
||||
|
||||
var tableRegionsIntersection: [String: TableRegion] = [:]
|
||||
for (table, tableRegion) in tableRegions {
|
||||
guard let otherTableRegion = otherTableRegions
|
||||
.first(where: { (otherTable, _) in otherTable == table })?
|
||||
.value else { continue }
|
||||
let tableRegionIntersection = tableRegion.intersection(otherTableRegion)
|
||||
guard !tableRegionIntersection.isEmpty else { continue }
|
||||
tableRegionsIntersection[table] = tableRegionIntersection
|
||||
}
|
||||
|
||||
return DatabaseRegion(tableRegions: tableRegionsIntersection)
|
||||
}
|
||||
|
||||
/// Only keeps those rowIds in the given table
|
||||
func tableIntersection(_ table: String, rowIds: Set<Int64>) -> DatabaseRegion {
|
||||
guard var tableRegions = tableRegions else {
|
||||
return DatabaseRegion(table: table, rowIds: rowIds)
|
||||
}
|
||||
|
||||
guard let tableRegion = tableRegions[table] else {
|
||||
return self
|
||||
}
|
||||
|
||||
let intersection = tableRegion.intersection(TableRegion(columns: nil, rowIds: rowIds))
|
||||
if intersection.isEmpty {
|
||||
tableRegions.removeValue(forKey: table)
|
||||
} else {
|
||||
tableRegions[table] = intersection
|
||||
}
|
||||
return DatabaseRegion(tableRegions: tableRegions)
|
||||
}
|
||||
|
||||
/// Returns the union of this region and the given one.
|
||||
public func union(_ other: DatabaseRegion) -> DatabaseRegion {
|
||||
guard let tableRegions = tableRegions else { return .fullDatabase }
|
||||
guard let otherTableRegions = other.tableRegions else { return .fullDatabase }
|
||||
|
||||
var tableRegionsUnion: [String: TableRegion] = [:]
|
||||
let tableNames = Set(tableRegions.map { $0.key }).union(Set(otherTableRegions.map { $0.key }))
|
||||
for table in tableNames {
|
||||
let tableRegion = tableRegions[table]
|
||||
let otherTableRegion = otherTableRegions[table]
|
||||
let tableRegionUnion: TableRegion
|
||||
switch (tableRegion, otherTableRegion) {
|
||||
case (nil, nil):
|
||||
preconditionFailure()
|
||||
case (nil, let tableRegion?), (let tableRegion?, nil):
|
||||
tableRegionUnion = tableRegion
|
||||
case (let tableRegion?, let otherTableRegion?):
|
||||
tableRegionUnion = tableRegion.union(otherTableRegion)
|
||||
}
|
||||
tableRegionsUnion[table] = tableRegionUnion
|
||||
}
|
||||
|
||||
return DatabaseRegion(tableRegions: tableRegionsUnion)
|
||||
}
|
||||
|
||||
/// Inserts the given region into this region
|
||||
public mutating func formUnion(_ other: DatabaseRegion) {
|
||||
self = union(other)
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseRegion {
|
||||
|
||||
// MARK: - Database Events
|
||||
|
||||
/// Returns whether the content in the region would be impacted if the
|
||||
/// database were modified by an event of this kind.
|
||||
public func isModified(byEventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
return !intersection(eventKind.modifiedRegion).isEmpty
|
||||
}
|
||||
|
||||
/// Returns whether the content in the region is impacted by this event.
|
||||
///
|
||||
/// - precondition: event has been filtered by the same region
|
||||
/// in the TransactionObserver.observes(eventsOfKind:) method, by calling
|
||||
/// region.isModified(byEventsOfKind:)
|
||||
public func isModified(by event: DatabaseEvent) -> Bool {
|
||||
guard let tableRegions = tableRegions else {
|
||||
return true
|
||||
}
|
||||
|
||||
switch tableRegions.count {
|
||||
case 1:
|
||||
// The precondition applies here:
|
||||
//
|
||||
// The region contains a single table. Due to the
|
||||
// filtering of events performed in observes(eventsOfKind:), the
|
||||
// event argument is guaranteed to be about the fetched table.
|
||||
// We thus only have to check for rowIds.
|
||||
assert(event.tableName == tableRegions[tableRegions.startIndex].key) // sanity check
|
||||
guard let rowIds = tableRegions[tableRegions.startIndex].value.rowIds else {
|
||||
return true
|
||||
}
|
||||
return rowIds.contains(event.rowID)
|
||||
default:
|
||||
guard let tableRegion = tableRegions[event.tableName] else {
|
||||
// Shouldn't happen if the precondition is met.
|
||||
fatalError("precondition failure: event was not filtered out in observes(eventsOfKind:) by region.isModified(byEventsOfKind:)")
|
||||
}
|
||||
guard let rowIds = tableRegion.rowIds else {
|
||||
return true
|
||||
}
|
||||
return rowIds.contains(event.rowID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Equatable
|
||||
extension DatabaseRegion {
|
||||
/// :nodoc:
|
||||
public static func == (lhs: DatabaseRegion, rhs: DatabaseRegion) -> Bool {
|
||||
switch (lhs.tableRegions, rhs.tableRegions) {
|
||||
case (nil, nil):
|
||||
return true
|
||||
case (let ltableRegions?, let rtableRegions?):
|
||||
let ltableNames = Set(ltableRegions.map { $0.key })
|
||||
let rtableNames = Set(rtableRegions.map { $0.key })
|
||||
guard ltableNames == rtableNames else {
|
||||
return false
|
||||
}
|
||||
for tableName in ltableNames {
|
||||
if ltableRegions[tableName]! != rtableRegions[tableName]! {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// CustomStringConvertible
|
||||
extension DatabaseRegion {
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
guard let tableRegions = tableRegions else {
|
||||
return "full database"
|
||||
}
|
||||
if tableRegions.isEmpty {
|
||||
return "empty"
|
||||
}
|
||||
return tableRegions
|
||||
.sorted(by: { (l, r) in l.key < r.key })
|
||||
.map { (table, tableRegion) in
|
||||
var desc = table
|
||||
if let columns = tableRegion.columns {
|
||||
desc += "(" + columns.sorted().joined(separator: ",") + ")"
|
||||
} else {
|
||||
desc += "(*)"
|
||||
}
|
||||
if let rowIds = tableRegion.rowIds {
|
||||
desc += "[" + rowIds.sorted().map { "\($0)" }.joined(separator: ",") + "]"
|
||||
}
|
||||
return desc
|
||||
}
|
||||
.joined(separator: ",")
|
||||
}
|
||||
}
|
||||
|
||||
private struct TableRegion: Equatable {
|
||||
var columns: Set<String>? // nil means "all columns"
|
||||
var rowIds: Set<Int64>? // nil means "all rowids"
|
||||
|
||||
var isEmpty: Bool {
|
||||
if let columns = columns, columns.isEmpty { return true }
|
||||
if let rowIds = rowIds, rowIds.isEmpty { return true }
|
||||
return false
|
||||
}
|
||||
|
||||
static func == (lhs: TableRegion, rhs: TableRegion) -> Bool {
|
||||
if lhs.columns != rhs.columns { return false }
|
||||
if lhs.rowIds != rhs.rowIds { return false }
|
||||
return true
|
||||
}
|
||||
|
||||
func intersection(_ other: TableRegion) -> TableRegion {
|
||||
let columnsIntersection: Set<String>?
|
||||
switch (self.columns, other.columns) {
|
||||
case (nil, let columns), (let columns, nil):
|
||||
columnsIntersection = columns
|
||||
case (let columns?, let other?):
|
||||
columnsIntersection = columns.intersection(other)
|
||||
}
|
||||
|
||||
let rowIdsIntersection: Set<Int64>?
|
||||
switch (self.rowIds, other.rowIds) {
|
||||
case (nil, let rowIds), (let rowIds, nil):
|
||||
rowIdsIntersection = rowIds
|
||||
case (let rowIds?, let other?):
|
||||
rowIdsIntersection = rowIds.intersection(other)
|
||||
}
|
||||
|
||||
return TableRegion(columns: columnsIntersection, rowIds: rowIdsIntersection)
|
||||
}
|
||||
|
||||
func union(_ other: TableRegion) -> TableRegion {
|
||||
let columnsUnion: Set<String>?
|
||||
switch (self.columns, other.columns) {
|
||||
case (nil, _), (_, nil):
|
||||
columnsUnion = nil
|
||||
case (let columns?, let other?):
|
||||
columnsUnion = columns.union(other)
|
||||
}
|
||||
|
||||
let rowIdsUnion: Set<Int64>?
|
||||
switch (self.rowIds, other.rowIds) {
|
||||
case (nil, _), (_, nil):
|
||||
rowIdsUnion = nil
|
||||
case (let rowIds?, let other?):
|
||||
rowIdsUnion = rowIds.union(other)
|
||||
}
|
||||
|
||||
return TableRegion(columns: columnsUnion, rowIds: rowIdsUnion)
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,10 @@
|
||||
/// The protocol for schema cache.
|
||||
///
|
||||
/// This protocol must not contain values that are valid for a single connection
|
||||
/// only, because several connections can share the same schema cache.
|
||||
///
|
||||
/// Statements can't be cached here, for example.
|
||||
/// The protocol for database schema cache.
|
||||
protocol DatabaseSchemaCache {
|
||||
mutating func clear()
|
||||
|
||||
func canonicalName(table: String) -> String?
|
||||
mutating func set(canonicalName: String, forTable table: String)
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo?
|
||||
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String)
|
||||
|
||||
@@ -21,24 +19,34 @@ protocol DatabaseSchemaCache {
|
||||
}
|
||||
|
||||
/// A thread-unsafe database schema cache
|
||||
final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
struct SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
private var canonicalNames: [String: String] = [:]
|
||||
private var primaryKeys: [String: PrimaryKeyInfo] = [:]
|
||||
private var columns: [String: [ColumnInfo]] = [:]
|
||||
private var indexes: [String: [IndexInfo]] = [:]
|
||||
private var foreignKeys: [String: [ForeignKeyInfo]] = [:]
|
||||
|
||||
func clear() {
|
||||
mutating func clear() {
|
||||
canonicalNames = [:]
|
||||
primaryKeys = [:]
|
||||
columns = [:]
|
||||
indexes = [:]
|
||||
foreignKeys = [:]
|
||||
}
|
||||
|
||||
func canonicalName(table: String) -> String? {
|
||||
return canonicalNames[table]
|
||||
}
|
||||
|
||||
mutating func set(canonicalName: String, forTable table: String) {
|
||||
canonicalNames[table] = table
|
||||
}
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
|
||||
return primaryKeys[table]
|
||||
}
|
||||
|
||||
func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
|
||||
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
|
||||
primaryKeys[table] = primaryKey
|
||||
}
|
||||
|
||||
@@ -46,7 +54,7 @@ final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
return columns[table]
|
||||
}
|
||||
|
||||
func set(columns: [ColumnInfo], forTable table: String) {
|
||||
mutating func set(columns: [ColumnInfo], forTable table: String) {
|
||||
self.columns[table] = columns
|
||||
}
|
||||
|
||||
@@ -54,7 +62,7 @@ final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
return indexes[table]
|
||||
}
|
||||
|
||||
func set(indexes: [IndexInfo], forTable table: String) {
|
||||
mutating func set(indexes: [IndexInfo], forTable table: String) {
|
||||
self.indexes[table] = indexes
|
||||
}
|
||||
|
||||
@@ -62,48 +70,27 @@ final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
return foreignKeys[table]
|
||||
}
|
||||
|
||||
func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
|
||||
mutating func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
|
||||
self.foreignKeys[table] = foreignKeys
|
||||
}
|
||||
}
|
||||
|
||||
/// A thread-safe database schema cache
|
||||
final class SharedDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
private let cache = ReadWriteBox(SimpleDatabaseSchemaCache())
|
||||
/// An always empty database schema cache
|
||||
struct EmptyDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
func clear() { }
|
||||
|
||||
func clear() {
|
||||
cache.write { $0.clear() }
|
||||
}
|
||||
func canonicalName(table: String) -> String? { return nil }
|
||||
func set(canonicalName: String, forTable table: String) { }
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
|
||||
return cache.read { $0.primaryKey(table) }
|
||||
}
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo? { return nil }
|
||||
func set(primaryKey: PrimaryKeyInfo, forTable table: String) { }
|
||||
|
||||
func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
|
||||
cache.write { $0.set(primaryKey: primaryKey, forTable: table) }
|
||||
}
|
||||
func columns(in table: String) -> [ColumnInfo]? { return nil }
|
||||
func set(columns: [ColumnInfo], forTable table: String) { }
|
||||
|
||||
func columns(in table: String) -> [ColumnInfo]? {
|
||||
return cache.read { $0.columns(in: table) }
|
||||
}
|
||||
func indexes(on table: String) -> [IndexInfo]? { return nil }
|
||||
func set(indexes: [IndexInfo], forTable table: String) { }
|
||||
|
||||
func set(columns: [ColumnInfo], forTable table: String) {
|
||||
cache.write { $0.set(columns: columns, forTable: table) }
|
||||
}
|
||||
|
||||
func indexes(on table: String) -> [IndexInfo]? {
|
||||
return cache.read { $0.indexes(on: table) }
|
||||
}
|
||||
|
||||
func set(indexes: [IndexInfo], forTable table: String) {
|
||||
cache.write { $0.set(indexes: indexes, forTable: table) }
|
||||
}
|
||||
|
||||
func foreignKeys(on table: String) -> [ForeignKeyInfo]? {
|
||||
return cache.read { $0.foreignKeys(on: table) }
|
||||
}
|
||||
|
||||
func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
|
||||
cache.write { $0.set(foreignKeys: foreignKeys, forTable: table) }
|
||||
}
|
||||
func foreignKeys(on table: String) -> [ForeignKeyInfo]? { return nil }
|
||||
func set(foreignKeys: [ForeignKeyInfo], forTable table: String) { }
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
/// A DatabaseSnapshot sees an unchanging database content, as it existed at the
|
||||
/// moment it was created.
|
||||
///
|
||||
/// See DatabasePool.makeSnapshot()
|
||||
///
|
||||
/// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html
|
||||
public class DatabaseSnapshot : DatabaseReader {
|
||||
private var serializedDatabase: SerializedDatabase
|
||||
|
||||
/// The database configuration
|
||||
var configuration: Configuration {
|
||||
return serializedDatabase.configuration
|
||||
}
|
||||
|
||||
init(path: String, configuration: Configuration = Configuration()) throws {
|
||||
var configuration = configuration
|
||||
configuration.readonly = true
|
||||
configuration.allowsUnsafeTransactions = true // Snaphost keeps a long-lived transaction
|
||||
|
||||
serializedDatabase = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
schemaCache: SimpleDatabaseSchemaCache())
|
||||
|
||||
try serializedDatabase.sync { db in
|
||||
// Assert WAL mode
|
||||
let journalMode = try String.fetchOne(db, "PRAGMA journal_mode")
|
||||
guard journalMode == "wal" else {
|
||||
throw DatabaseError(message: "WAL mode is not activated at path: \(path)")
|
||||
}
|
||||
|
||||
// Establish snapshot isolation (see deinit)
|
||||
try db.beginTransaction(.deferred)
|
||||
|
||||
// Take snapshot
|
||||
// See DatabasePool.readFromCurrentState for a complete discussion
|
||||
try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").cursor().next()
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
// Leave snapshot isolation
|
||||
serializedDatabase.sync { db in
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// DatabaseReader
|
||||
extension DatabaseSnapshot {
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// Synchronously executes a read-only block that takes a database
|
||||
/// connection, and returns its result.
|
||||
///
|
||||
/// let players = try snapshot.read { db in
|
||||
/// try Player.fetchAll(...)
|
||||
/// }
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.sync(block)
|
||||
}
|
||||
|
||||
/// Alias for `read`. See `DatabaseReader.unsafeRead`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.sync(block)
|
||||
}
|
||||
|
||||
/// Alias for `read`. See `DatabaseReader.unsafeReentrantRead`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try serializedDatabase.sync(block)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
///
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int + 1
|
||||
/// }
|
||||
/// snapshot.add(function: fn)
|
||||
/// try snapshot.read { db in
|
||||
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
|
||||
/// }
|
||||
public func add(function: DatabaseFunction) {
|
||||
serializedDatabase.sync { $0.add(function: function) }
|
||||
}
|
||||
|
||||
/// Remove an SQL function.
|
||||
public func remove(function: DatabaseFunction) {
|
||||
serializedDatabase.sync { $0.remove(function: function) }
|
||||
}
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// Add or redefine a collation.
|
||||
///
|
||||
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// snapshot.add(collation: collation)
|
||||
/// let files = try snapshot.read { db in
|
||||
/// try File.fetchAll(db, "SELECT * FROM files ORDER BY name COLLATE localized_standard")
|
||||
/// }
|
||||
public func add(collation: DatabaseCollation) {
|
||||
serializedDatabase.sync { $0.add(collation: collation) }
|
||||
}
|
||||
|
||||
/// Remove a collation.
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
serializedDatabase.sync { $0.remove(collation: collation) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,12 @@ import Foundation
|
||||
/// DatabaseValue is the intermediate type between SQLite and your values.
|
||||
///
|
||||
/// See https://www.sqlite.org/datatype3.html
|
||||
public struct DatabaseValue {
|
||||
public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLExpressible, SQLExpression {
|
||||
/// The SQLite storage
|
||||
public let storage: Storage
|
||||
|
||||
/// The NULL DatabaseValue.
|
||||
public static let null = DatabaseValue(storage: .null)
|
||||
|
||||
/// An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB).
|
||||
public enum Storage : Equatable {
|
||||
@@ -62,12 +67,6 @@ public struct DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
/// The SQLite storage
|
||||
public let storage: Storage
|
||||
|
||||
/// The NULL DatabaseValue.
|
||||
public static let null = DatabaseValue(storage: .null)
|
||||
|
||||
/// Creates a DatabaseValue from Any.
|
||||
///
|
||||
/// The result is nil unless object adopts DatabaseValueConvertible.
|
||||
@@ -78,7 +77,6 @@ public struct DatabaseValue {
|
||||
self = convertible.databaseValue
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Extracting Value
|
||||
|
||||
/// Returns true if databaseValue is NULL.
|
||||
@@ -91,7 +89,6 @@ public struct DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Not Public
|
||||
|
||||
init(storage: Storage) {
|
||||
@@ -147,13 +144,13 @@ public struct DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Hashable & Equatable
|
||||
|
||||
/// DatabaseValue adopts Hashable.
|
||||
extension DatabaseValue : Hashable {
|
||||
// Hashable
|
||||
extension DatabaseValue {
|
||||
|
||||
/// The hash value
|
||||
/// :nodoc:
|
||||
public var hashValue: Int {
|
||||
switch storage {
|
||||
case .null:
|
||||
@@ -207,6 +204,16 @@ extension DatabaseValue : Hashable {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLSelectable
|
||||
|
||||
extension DatabaseValue {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func qualified(by qualifier: SQLTableQualifier) -> DatabaseValue {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Lossless conversions
|
||||
|
||||
@@ -286,11 +293,8 @@ extension DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - DatabaseValueConvertible & SQLExpressible & SQLExpression
|
||||
|
||||
/// DatabaseValue adopts DatabaseValueConvertible.
|
||||
extension DatabaseValue : DatabaseValueConvertible {
|
||||
// DatabaseValueConvertible
|
||||
extension DatabaseValue {
|
||||
/// Returns self
|
||||
public var databaseValue: DatabaseValue {
|
||||
return self
|
||||
@@ -302,17 +306,19 @@ extension DatabaseValue : DatabaseValueConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValue : SQLExpressible {
|
||||
|
||||
// SQLExpressible
|
||||
extension DatabaseValue {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public var sqlExpression: SQLExpression {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
/// DatabaseValue adopts SQLExpression.
|
||||
extension DatabaseValue : SQLExpression {
|
||||
// SQLExpression
|
||||
extension DatabaseValue {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
// fast path for NULL
|
||||
if isNull {
|
||||
@@ -330,6 +336,7 @@ extension DatabaseValue : SQLExpression {
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public var negated: SQLExpression {
|
||||
switch storage {
|
||||
case .null:
|
||||
@@ -355,11 +362,9 @@ extension DatabaseValue : SQLExpression {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
/// DatabaseValue adopts CustomStringConvertible.
|
||||
extension DatabaseValue : CustomStringConvertible {
|
||||
/// A textual representation of `self`.
|
||||
// CustomStringConvertible
|
||||
extension DatabaseValue {
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
switch storage {
|
||||
case .null:
|
||||
|
||||
@@ -30,10 +30,9 @@ public protocol DatabaseValueConvertible : SQLExpressible {
|
||||
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self?
|
||||
}
|
||||
|
||||
// SQLExpressible adoption
|
||||
extension DatabaseValueConvertible {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public var sqlExpression: SQLExpression {
|
||||
return databaseValue
|
||||
}
|
||||
@@ -62,6 +61,7 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func next() throws -> Value? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
@@ -101,6 +101,7 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func next() throws -> Value?? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
@@ -132,7 +133,6 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
extension DatabaseValueConvertible {
|
||||
|
||||
|
||||
// MARK: Fetching From SelectStatement
|
||||
|
||||
/// Returns a cursor over values fetched from a prepared statement.
|
||||
|
||||
@@ -41,65 +41,23 @@ public protocol DatabaseWriter : DatabaseReader {
|
||||
/// Synchronously or asynchronously executes a read-only block that takes a
|
||||
/// database connection.
|
||||
///
|
||||
/// This method must be called from a writing dispatch queue.
|
||||
/// This method must be called from a writing dispatch queue, outside of any
|
||||
/// transaction. You'll get a fatal error otherwise.
|
||||
///
|
||||
/// The *block* argument is guaranteed to see the database in the state it
|
||||
/// has at the moment this method is called (see below). Eventual concurrent
|
||||
/// The *block* argument is guaranteed to see the database in the last
|
||||
/// committed state at the moment this method is called. Eventual concurrent
|
||||
/// database updates are *not visible* inside the block.
|
||||
///
|
||||
/// What is the "current state" of the database?
|
||||
/// For example:
|
||||
///
|
||||
/// - 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 ...")
|
||||
/// 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")!
|
||||
/// }
|
||||
///
|
||||
/// - 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.
|
||||
/// try db.execute("INSERT INTO players ...")
|
||||
/// }
|
||||
func readFromCurrentState(_ block: @escaping (Database) -> Void) throws
|
||||
}
|
||||
|
||||
@@ -136,43 +94,61 @@ public final class AnyDatabaseWriter : DatabaseWriter {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// :nodoc:
|
||||
public func read<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.read(block)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeRead(block)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeReentrantRead(block)
|
||||
}
|
||||
|
||||
public func add(function: DatabaseFunction) {
|
||||
base.add(function: function)
|
||||
/// :nodoc:
|
||||
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws {
|
||||
try base.readFromCurrentState(block)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
// MARK: - Writing in Database
|
||||
|
||||
/// :nodoc:
|
||||
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try base.write(block)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
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)
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// :nodoc:
|
||||
public func add(function: DatabaseFunction) {
|
||||
base.add(function: function)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func remove(function: DatabaseFunction) {
|
||||
base.remove(function: function)
|
||||
}
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// :nodoc:
|
||||
public func add(collation: DatabaseCollation) {
|
||||
base.add(collation: collation)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
base.remove(collation: collation)
|
||||
}
|
||||
}
|
||||
+117
-51
@@ -22,6 +22,13 @@ public protocol Request {
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
func fetchCount(_ db: Database) throws -> Int
|
||||
|
||||
/// The database region that the request looks into.
|
||||
///
|
||||
/// This method has a default implementation.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
func fetchedRegion(_ db: Database) throws -> DatabaseRegion
|
||||
}
|
||||
|
||||
extension Request {
|
||||
@@ -36,6 +43,26 @@ extension Request {
|
||||
let sql = "SELECT COUNT(*) FROM (\(statement.sql))"
|
||||
return try Int.fetchOne(db, sql, arguments: statement.arguments)!
|
||||
}
|
||||
|
||||
/// Returns an equivalent SQLRequest.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: An SQLRequest
|
||||
public func asSQLRequest(_ db: Database, cached: Bool = false) throws -> SQLRequest {
|
||||
let (statement, adapter) = try prepare(db)
|
||||
return SQLRequest(statement.sql, arguments: statement.arguments, adapter: adapter, cached: cached)
|
||||
}
|
||||
|
||||
/// The database region that the request looks into.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
let (statement, _) = try prepare(db)
|
||||
return statement.fetchedRegion
|
||||
}
|
||||
}
|
||||
|
||||
extension Request {
|
||||
@@ -53,11 +80,9 @@ extension Request {
|
||||
/// - 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) }
|
||||
return AnyTypedRequest(self)
|
||||
}
|
||||
|
||||
/// [**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)
|
||||
@@ -66,6 +91,9 @@ extension Request {
|
||||
|
||||
/// An adapted request.
|
||||
public struct AdaptedRequest<Base: Request> : Request {
|
||||
private let base: Base
|
||||
private let adapter: (Database) throws -> RowAdapter
|
||||
|
||||
/// Creates an adapted request from a base request and a closure that builds
|
||||
/// a row adapter from a database connection.
|
||||
init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) {
|
||||
@@ -73,10 +101,7 @@ public struct AdaptedRequest<Base: Request> : Request {
|
||||
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.
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
let (statement, baseAdapter) = try base.prepare(db)
|
||||
if let baseAdapter = baseAdapter {
|
||||
@@ -86,15 +111,15 @@ public struct AdaptedRequest<Base: Request> : Request {
|
||||
}
|
||||
}
|
||||
|
||||
/// The number of rows fetched by the request.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try base.fetchCount(db)
|
||||
}
|
||||
|
||||
private let base: Base
|
||||
private let adapter: (Database) throws -> RowAdapter
|
||||
/// :nodoc:
|
||||
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try base.fetchedRegion(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// A type-erased Request.
|
||||
@@ -102,30 +127,48 @@ public struct AdaptedRequest<Base: Request> : Request {
|
||||
/// An instance of AnyRequest forwards its operations to an underlying request,
|
||||
/// hiding its specifics.
|
||||
public struct AnyRequest : Request {
|
||||
private let base: Request
|
||||
|
||||
/// Creates a new request that wraps and forwards operations to `request`.
|
||||
public init(_ request: Request) {
|
||||
self._prepare = { try request.prepare($0) }
|
||||
base = request
|
||||
}
|
||||
|
||||
/// Creates a new request whose `prepare()` method wraps and forwards
|
||||
/// operations the argument closure.
|
||||
public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) {
|
||||
_prepare = prepare
|
||||
struct PrepareRequest: Request {
|
||||
let base: (Database) throws -> (SelectStatement, RowAdapter?)
|
||||
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try base(db)
|
||||
}
|
||||
}
|
||||
base = PrepareRequest(base: prepare)
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try _prepare(db)
|
||||
return try base.prepare(db)
|
||||
}
|
||||
|
||||
private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?)
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try base.fetchCount(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try base.fetchedRegion(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// A Request built from raw SQL.
|
||||
public struct SQLRequest : Request {
|
||||
public let sql: String
|
||||
public let arguments: StatementArguments?
|
||||
public let adapter: RowAdapter?
|
||||
private let cache: Cache?
|
||||
|
||||
/// Creates a new request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
///
|
||||
@@ -140,7 +183,7 @@ public struct SQLRequest : Request {
|
||||
/// 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)
|
||||
self.init(sql, arguments: arguments, adapter: adapter, fromCache: cached ? .public : nil)
|
||||
}
|
||||
|
||||
/// Creates a new request from an SQL string, optional arguments, and
|
||||
@@ -155,23 +198,28 @@ public struct SQLRequest : Request {
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - statementCacheName: Optional statement cache name.
|
||||
/// - returns: A SQLRequest
|
||||
init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache statementCacheName: Database.StatementCacheName?) {
|
||||
init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache cache: Cache?) {
|
||||
self.sql = sql
|
||||
self.arguments = arguments
|
||||
self.adapter = adapter
|
||||
self.statementCacheName = statementCacheName
|
||||
self.cache = cache
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
///
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
let statement: SelectStatement
|
||||
if let statementCacheName = statementCacheName {
|
||||
statement = try db.selectStatement(sql, fromCache: statementCacheName)
|
||||
} else {
|
||||
switch cache {
|
||||
case .none:
|
||||
statement = try db.makeSelectStatement(sql)
|
||||
case .public?:
|
||||
statement = try db.cachedSelectStatement(sql)
|
||||
case .internal?:
|
||||
statement = try db.internalCachedSelectStatement(sql)
|
||||
}
|
||||
if let arguments = arguments {
|
||||
try statement.setArgumentsWithValidation(arguments)
|
||||
@@ -179,10 +227,17 @@ public struct SQLRequest : Request {
|
||||
return (statement, adapter)
|
||||
}
|
||||
|
||||
private let sql: String
|
||||
private let arguments: StatementArguments?
|
||||
private let adapter: RowAdapter?
|
||||
private let statementCacheName: Database.StatementCacheName?
|
||||
/// There are two statement caches: one for statements generated by the
|
||||
/// user, and one for the statements generated by GRDB. Those are separated
|
||||
/// so that GRDB has no opportunity to inadvertently modify the arguments of
|
||||
/// user's cached statements.
|
||||
enum Cache {
|
||||
/// The public cache, for library user
|
||||
case `public`
|
||||
|
||||
/// The internal cache, for grdb
|
||||
case `internal`
|
||||
}
|
||||
}
|
||||
|
||||
/// The protocol for requests that know how to decode database rows.
|
||||
@@ -212,32 +267,31 @@ extension TypedRequest {
|
||||
|
||||
/// 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
|
||||
|
||||
private let base: AdaptedRequest<Base>
|
||||
|
||||
/// 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)
|
||||
self.base = 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.
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try adaptedRequest.prepare(db)
|
||||
return try base.prepare(db)
|
||||
}
|
||||
|
||||
/// The number of rows fetched by the request.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try adaptedRequest.fetchCount(db)
|
||||
return try base.fetchCount(db)
|
||||
}
|
||||
|
||||
private let adaptedRequest: AdaptedRequest<Base>
|
||||
/// :nodoc:
|
||||
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try base.fetchedRegion(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// A type-erased TypedRequest.
|
||||
@@ -247,27 +301,39 @@ public struct AdaptedTypedRequest<Base: TypedRequest> : TypedRequest {
|
||||
public struct AnyTypedRequest<T> : TypedRequest {
|
||||
/// The type that can convert raw database rows to fetched values
|
||||
public typealias RowDecoder = T
|
||||
private let base: Request
|
||||
|
||||
/// Support for Request.asRequest(of:)
|
||||
/// Not public because not type-safe.
|
||||
fileprivate init(_ request: Request) {
|
||||
base = request
|
||||
}
|
||||
|
||||
/// 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) }
|
||||
base = request
|
||||
}
|
||||
|
||||
/// Creates a new request whose `prepare()` method wraps and forwards
|
||||
/// operations the argument closure.
|
||||
public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) {
|
||||
_prepare = prepare
|
||||
base = AnyRequest(prepare)
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try _prepare(db)
|
||||
return try base.prepare(db)
|
||||
}
|
||||
|
||||
private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?)
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try base.fetchCount(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try base.fetchedRegion(db)
|
||||
}
|
||||
}
|
||||
|
||||
extension TypedRequest where RowDecoder: RowConvertible {
|
||||
|
||||
+180
-75
@@ -6,7 +6,22 @@ import Foundation
|
||||
#endif
|
||||
|
||||
/// A database row.
|
||||
public final class Row {
|
||||
public final class Row : Equatable, Hashable, RandomAccessCollection, ExpressibleByDictionaryLiteral, CustomStringConvertible {
|
||||
let impl: RowImpl
|
||||
|
||||
/// Unless we are producing a row array, we use a single row when iterating
|
||||
/// a statement:
|
||||
///
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT ...")
|
||||
/// let players = try Player.fetchAll(db, "SELECT ...")
|
||||
///
|
||||
/// This row keeps an unmanaged reference to the statement, and a handle to
|
||||
/// the sqlite statement, so that we avoid many retain/release invocations.
|
||||
///
|
||||
/// The statementRef is released in deinit.
|
||||
let statementRef: Unmanaged<SelectStatement>?
|
||||
let sqliteStatement: SQLiteStatement?
|
||||
|
||||
/// The number of columns in the row.
|
||||
public let count: Int
|
||||
|
||||
@@ -51,26 +66,11 @@ public final class Row {
|
||||
|
||||
// MARK: - Not Public
|
||||
|
||||
let impl: RowImpl
|
||||
|
||||
/// Returns true if and only if the row was fetched from a database.
|
||||
var isFetched: Bool {
|
||||
return impl.isFetched
|
||||
}
|
||||
|
||||
/// Unless we are producing a row array, we use a single row when iterating
|
||||
/// a statement:
|
||||
///
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT ...")
|
||||
/// let players = try Player.fetchAll(db, "SELECT ...")
|
||||
///
|
||||
/// This row keeps an unmanaged reference to the statement, and a handle to
|
||||
/// the sqlite statement, so that we avoid many retain/release invocations.
|
||||
///
|
||||
/// The statementRef is released in deinit.
|
||||
let statementRef: Unmanaged<SelectStatement>?
|
||||
let sqliteStatement: SQLiteStatement?
|
||||
|
||||
deinit {
|
||||
statementRef?.release()
|
||||
}
|
||||
@@ -131,6 +131,42 @@ extension Row {
|
||||
|
||||
// MARK: - Extracting Values
|
||||
|
||||
/// Returns true if and only if one column contains a non-null value, or if
|
||||
/// the row was fetched with a row adapter that defines a scoped row that
|
||||
/// contains a non-null value.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, "SELECT 'foo', 1")!
|
||||
/// row.containsNonNullValue // true
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, "SELECT NULL, NULL")!
|
||||
/// row.containsNonNullValue // false
|
||||
public var containsNonNullValue: Bool {
|
||||
for i in (0..<count) {
|
||||
if !hasNull(atIndex: i) { return true }
|
||||
}
|
||||
|
||||
for name in scopeNames where scoped(on: name)!.containsNonNullValue {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
/// Returns true if the row contains null at given index.
|
||||
///
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
/// righmost column.
|
||||
///
|
||||
/// This method is equivalent to `row[index] == nil`, but may be preferred
|
||||
/// in performance-critical code because it can avoid decoding database
|
||||
/// values.
|
||||
public func hasNull(atIndex index: Int) -> Bool {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
|
||||
return impl.hasNull(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns Int64, Double, String, Data or nil, depending on the value
|
||||
/// stored at the given index.
|
||||
///
|
||||
@@ -151,7 +187,7 @@ extension Row {
|
||||
/// fail, a fatal error is raised.
|
||||
public subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value? {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
return impl.value(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
@@ -169,9 +205,9 @@ extension Row {
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value? {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
|
||||
if let sqliteStatement = sqliteStatement { // fast path
|
||||
return Row.statementColumnConvertible(atUncheckedIndex: Int32(index), in: sqliteStatement)
|
||||
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
}
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
return impl.fastValue(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
@@ -183,7 +219,7 @@ extension Row {
|
||||
/// SQLite value can not be converted to `Value`.
|
||||
public subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
return impl.value(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
@@ -200,9 +236,9 @@ extension Row {
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
|
||||
if let sqliteStatement = sqliteStatement { // fast path
|
||||
return Row.statementColumnConvertible(atUncheckedIndex: Int32(index), in: sqliteStatement)
|
||||
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
}
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
return impl.fastValue(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns Int64, Double, String, Data or nil, depending on the value
|
||||
@@ -238,7 +274,7 @@ extension Row {
|
||||
guard let index = impl.index(ofColumn: columnName) else {
|
||||
return nil
|
||||
}
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
return impl.value(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -258,9 +294,9 @@ extension Row {
|
||||
return nil
|
||||
}
|
||||
if let sqliteStatement = sqliteStatement { // fast path
|
||||
return Row.statementColumnConvertible(atUncheckedIndex: Int32(index), in: sqliteStatement)
|
||||
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
}
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
return impl.fastValue(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -277,7 +313,7 @@ extension Row {
|
||||
// Programmer error
|
||||
fatalError("no such column: \(columnName)")
|
||||
}
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
return impl.value(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -295,13 +331,13 @@ extension Row {
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value {
|
||||
guard let index = impl.index(ofColumn: columnName) else {
|
||||
// Programmer error
|
||||
// Programmer error
|
||||
fatalError("no such column: \(columnName)")
|
||||
}
|
||||
if let sqliteStatement = sqliteStatement { // fast path
|
||||
return Row.statementColumnConvertible(atUncheckedIndex: Int32(index), in: sqliteStatement)
|
||||
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
}
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
return impl.fastValue(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns Int64, Double, String, NSData or nil, depending on the value
|
||||
@@ -437,22 +473,36 @@ extension Row {
|
||||
|
||||
extension Row {
|
||||
|
||||
// MARK: - Helpers
|
||||
@inline(__always)
|
||||
private static func statementColumnConvertible<Value: StatementColumnConvertible>(atUncheckedIndex index: Int32, in sqliteStatement: SQLiteStatement) -> Value? {
|
||||
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else {
|
||||
// MARK: - Extracting Records
|
||||
|
||||
/// Returns the record encoded in the given scope.
|
||||
///
|
||||
/// A fatal error is raised in the row was not fetched with a row adapter
|
||||
/// that defines this scope.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support
|
||||
/// for more information.
|
||||
public subscript<Record: RowConvertible>(_ scope: String) -> Record {
|
||||
guard let scopedRow = scoped(on: scope) else {
|
||||
// Programmer error
|
||||
fatalError("no such scope: \(scope)")
|
||||
}
|
||||
return Record(row: scopedRow)
|
||||
}
|
||||
|
||||
/// Returns the record encoded in the given scope, if and only if the scope
|
||||
/// has been defined by a row adapter, and the scoped row contains a
|
||||
/// non-null value. Otherwise, return nil.
|
||||
///
|
||||
/// This subscript is designed to handle left joined records.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support
|
||||
/// for more information.
|
||||
public subscript<Record: RowConvertible>(_ scope: String) -> Record? {
|
||||
guard let scopedRow = scoped(on: scope), scopedRow.containsNonNullValue else {
|
||||
return nil
|
||||
}
|
||||
return Value.init(sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
private static func statementColumnConvertible<Value: StatementColumnConvertible>(atUncheckedIndex index: Int32, in sqliteStatement: SQLiteStatement) -> Value {
|
||||
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else {
|
||||
// Programmer error
|
||||
fatalError("could not convert database value NULL to \(Value.self)")
|
||||
}
|
||||
return Value.init(sqliteStatement: sqliteStatement, index: index)
|
||||
return Record(row: scopedRow)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -460,8 +510,12 @@ extension Row {
|
||||
|
||||
// MARK: - Scopes
|
||||
|
||||
/// Returns a scoped row, if the row was fetched along with a row adapter
|
||||
/// that defines this scope.
|
||||
var scopeNames: Set<String> {
|
||||
return impl.scopeNames
|
||||
}
|
||||
|
||||
/// Returns a scoped row, if the row was fetched with a row adapter that
|
||||
/// defines this scope.
|
||||
///
|
||||
/// // Two adapters
|
||||
/// let fooAdapter = ColumnMapping(["value": "foo"])
|
||||
@@ -486,6 +540,12 @@ extension Row {
|
||||
public func scoped(on name: String) -> Row? {
|
||||
return impl.scoped(on: name)
|
||||
}
|
||||
|
||||
/// Returns a copy of the row, without any scoped row (if the row was fetched
|
||||
/// with a row adapter that defines scopes).
|
||||
public var unscoped: Row {
|
||||
return Row(impl: ArrayRowImpl(columns: map { ($0, $1) }))
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor of database rows. For example:
|
||||
@@ -506,6 +566,7 @@ public final class RowCursor : Cursor {
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func next() throws -> Row? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
@@ -725,7 +786,8 @@ extension Row {
|
||||
}
|
||||
}
|
||||
|
||||
extension Row : ExpressibleByDictionaryLiteral {
|
||||
// ExpressibleByDictionaryLiteral
|
||||
extension Row {
|
||||
|
||||
/// Creates a row initialized with elements. Column order is preserved, and
|
||||
/// duplicated columns names are allowed.
|
||||
@@ -738,17 +800,20 @@ extension Row : ExpressibleByDictionaryLiteral {
|
||||
}
|
||||
}
|
||||
|
||||
extension Row : Collection {
|
||||
// RandomAccessCollection
|
||||
extension Row {
|
||||
|
||||
// MARK: - Row as a Collection of (ColumnName, DatabaseValue) Pairs
|
||||
|
||||
/// The index of the first (ColumnName, DatabaseValue) pair.
|
||||
/// :nodoc:
|
||||
public var startIndex: RowIndex {
|
||||
return Index(0)
|
||||
}
|
||||
|
||||
/// The "past-the-end" index, successor of the index of the last
|
||||
/// (ColumnName, DatabaseValue) pair.
|
||||
/// :nodoc:
|
||||
public var endIndex: RowIndex {
|
||||
return Index(count)
|
||||
}
|
||||
@@ -761,25 +826,14 @@ extension Row : Collection {
|
||||
impl.columnName(atUncheckedIndex: index),
|
||||
impl.databaseValue(atUncheckedIndex: index))
|
||||
}
|
||||
|
||||
/// Returns the position immediately after `i`.
|
||||
///
|
||||
/// - Precondition: `(startIndex..<endIndex).contains(i)`
|
||||
public func index(after i: RowIndex) -> RowIndex {
|
||||
return RowIndex(i.index + 1)
|
||||
}
|
||||
|
||||
/// Replaces `i` with its successor.
|
||||
public func formIndex(after i: inout RowIndex) {
|
||||
i = RowIndex(i.index + 1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Row adopts Equatable.
|
||||
extension Row : Equatable {
|
||||
// Equatable
|
||||
extension Row {
|
||||
|
||||
/// Returns true if and only if both rows have the same columns and values,
|
||||
/// in the same order. Columns are compared in a case-sensitive way.
|
||||
/// :nodoc:
|
||||
public static func == (lhs: Row, rhs: Row) -> Bool {
|
||||
if lhs === rhs {
|
||||
return true
|
||||
@@ -789,10 +843,7 @@ extension Row : Equatable {
|
||||
return false
|
||||
}
|
||||
|
||||
var liter = lhs.makeIterator()
|
||||
var riter = rhs.makeIterator()
|
||||
|
||||
while let (lcol, lval) = liter.next(), let (rcol, rval) = riter.next() {
|
||||
for ((lcol, lval), (rcol, rval)) in zip(lhs, rhs) {
|
||||
guard lcol == rcol else {
|
||||
return false
|
||||
}
|
||||
@@ -819,18 +870,19 @@ extension Row : Equatable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Row adopts Hashable.
|
||||
extension Row : Hashable {
|
||||
// Hashable
|
||||
extension Row {
|
||||
/// The hash value
|
||||
/// :nodoc:
|
||||
public var hashValue: Int {
|
||||
return columnNames.reduce(0) { (acc, column) in acc ^ column.hashValue } ^
|
||||
databaseValues.reduce(0) { (acc, dbValue) in acc ^ dbValue.hashValue }
|
||||
}
|
||||
}
|
||||
|
||||
/// Row adopts CustomStringConvertible.
|
||||
extension Row: CustomStringConvertible {
|
||||
/// A textual representation of `self`.
|
||||
// CustomStringConvertible
|
||||
extension Row {
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
return "<Row"
|
||||
+ map { (column, dbValue) in
|
||||
@@ -843,22 +895,38 @@ extension Row: CustomStringConvertible {
|
||||
|
||||
// MARK: - RowIndex
|
||||
|
||||
/// Indexes to (columnName, dbValue) pairs in a database row.
|
||||
public struct RowIndex : Comparable {
|
||||
/// Indexes to (ColumnName, DatabaseValue) pairs in a database row.
|
||||
public struct RowIndex : Comparable, Strideable {
|
||||
let index: Int
|
||||
init(_ index: Int) { self.index = index }
|
||||
|
||||
/// Equality operator
|
||||
}
|
||||
|
||||
// Comparable
|
||||
extension RowIndex {
|
||||
/// :nodoc:
|
||||
public static func == (lhs: RowIndex, rhs: RowIndex) -> Bool {
|
||||
return lhs.index == rhs.index
|
||||
}
|
||||
|
||||
// Comparison operator
|
||||
/// :nodoc:
|
||||
public static func < (lhs: RowIndex, rhs: RowIndex) -> Bool {
|
||||
return lhs.index < rhs.index
|
||||
}
|
||||
}
|
||||
|
||||
// Strideable: support for Row: RandomAccessCollection
|
||||
extension RowIndex {
|
||||
/// :nodoc:
|
||||
public func distance(to other: RowIndex) -> Int {
|
||||
return other.index - index
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func advanced(by n: Int) -> RowIndex {
|
||||
return RowIndex(index + n)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - RowImpl
|
||||
|
||||
@@ -867,6 +935,9 @@ protocol RowImpl {
|
||||
var count: Int { get }
|
||||
var isFetched: Bool { get }
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue
|
||||
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value
|
||||
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value?
|
||||
func hasNull(atUncheckedIndex index:Int) -> Bool
|
||||
func dataNoCopy(atUncheckedIndex index:Int) -> Data?
|
||||
func columnName(atUncheckedIndex index: Int) -> String
|
||||
|
||||
@@ -881,6 +952,27 @@ protocol RowImpl {
|
||||
func copy(_ row: Row) -> Row
|
||||
}
|
||||
|
||||
extension RowImpl {
|
||||
func hasNull(atUncheckedIndex index:Int) -> Bool {
|
||||
return databaseValue(atUncheckedIndex: index).isNull
|
||||
}
|
||||
|
||||
func value<Value: DatabaseValueConvertible>(atUncheckedIndex index: Int) -> Value {
|
||||
return databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
|
||||
func value<Value: DatabaseValueConvertible>(atUncheckedIndex index: Int) -> Value? {
|
||||
return databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
|
||||
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value {
|
||||
return databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
|
||||
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value? {
|
||||
return databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
}
|
||||
|
||||
/// See Row.init(dictionary:)
|
||||
private struct ArrayRowImpl : RowImpl {
|
||||
@@ -1009,6 +1101,11 @@ private struct StatementRowImpl : RowImpl {
|
||||
return true
|
||||
}
|
||||
|
||||
func hasNull(atUncheckedIndex index:Int) -> Bool {
|
||||
// Avoid extracting values, because this modifies the statement.
|
||||
return sqlite3_column_type(sqliteStatement, Int32(index)) == SQLITE_NULL
|
||||
}
|
||||
|
||||
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
|
||||
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
|
||||
return nil
|
||||
@@ -1024,6 +1121,14 @@ private struct StatementRowImpl : RowImpl {
|
||||
return DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
}
|
||||
|
||||
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value {
|
||||
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
}
|
||||
|
||||
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value? {
|
||||
return Value.losslessConvert(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
}
|
||||
|
||||
func columnName(atUncheckedIndex index: Int) -> String {
|
||||
return statementRef.takeUnretainedValue().columnNames[index]
|
||||
}
|
||||
|
||||
+129
-12
@@ -1,8 +1,50 @@
|
||||
import Foundation
|
||||
|
||||
/// Returns an array of row adapters that split a row according to the input
|
||||
/// number of columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let sql = "SELECT 1, 2,3,4, 5,6, 7,8"
|
||||
/// // <.><. . .><. .><. .>
|
||||
/// let adapters = splittingRowAdapters([1, 3, 2])
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "a": adapters[0],
|
||||
/// "b": adapters[1],
|
||||
/// "c": adapters[2],
|
||||
/// "d": adapters[3]])
|
||||
/// let row = try Row.fetchOne(db, sql, adapter: adapter)
|
||||
/// row.scoped(on: "a") // [1]
|
||||
/// row.scoped(on: "b") // [2, 3, 4]
|
||||
/// row.scoped(on: "c") // [5, 6]
|
||||
/// row.scoped(on: "d") // [7, 8]
|
||||
public func splittingRowAdapters(columnCounts: [Int]) -> [RowAdapter] {
|
||||
guard !columnCounts.isEmpty else {
|
||||
// Identity adapter
|
||||
return [SuffixRowAdapter(fromIndex: 0)]
|
||||
}
|
||||
|
||||
// [1, 3, 2] -> [0, 1, 4, 6]
|
||||
let columnIndexes = columnCounts.reduce(into: [0]) { (acc, count) in
|
||||
acc.append(acc.last! + count)
|
||||
}
|
||||
|
||||
// [0, 1, 4, 6] -> [(0..<1), (1..<4), (4..<6)]
|
||||
let rangeAdapters = zip(columnIndexes, columnIndexes.suffix(from: 1))
|
||||
.map { RangeRowAdapter($0..<$1) }
|
||||
|
||||
// (6...)
|
||||
let suffixAdapter = SuffixRowAdapter(fromIndex: columnIndexes.last!)
|
||||
|
||||
// [(0..<1), (1..<4), (4..<6), (6...)]
|
||||
return rangeAdapters + [suffixAdapter]
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// LayoutedColumnMapping is a type that supports the RowAdapter protocol.
|
||||
///
|
||||
/// :nodoc:
|
||||
public struct LayoutedColumnMapping {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -56,6 +98,8 @@ public struct LayoutedColumnMapping {
|
||||
}
|
||||
|
||||
/// LayoutedColumnMapping adopts LayoutedRowAdapter
|
||||
///
|
||||
/// :nodoc:
|
||||
extension LayoutedColumnMapping : LayoutedRowAdapter {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -72,6 +116,7 @@ extension LayoutedColumnMapping : LayoutedRowAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
extension LayoutedColumnMapping : RowLayout {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -91,6 +136,8 @@ extension LayoutedColumnMapping : RowLayout {
|
||||
///
|
||||
/// GRBD ships with a ready-made type that adopts this protocol:
|
||||
/// LayoutedColumnMapping.
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol LayoutedRowAdapter {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -108,6 +155,8 @@ public protocol LayoutedRowAdapter {
|
||||
///
|
||||
/// RowLayout is a protocol that supports the RowAdapter protocol. It describes
|
||||
/// a layout of a base row.
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol RowLayout {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -124,11 +173,15 @@ public protocol RowLayout {
|
||||
|
||||
extension SelectStatement : RowLayout {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public var layoutColumns: [(Int, String)] {
|
||||
return Array(columnNames.enumerated())
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func layoutIndex(ofColumn name: String) -> Int? {
|
||||
return index(ofColumn: name)
|
||||
}
|
||||
@@ -186,7 +239,7 @@ extension RowAdapter {
|
||||
/// - parameter scopes: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
public func addingScopes(_ scopes: [String: RowAdapter]) -> RowAdapter {
|
||||
return ScopeAdapter(mainAdapter: self, scopes: scopes)
|
||||
return ScopeAdapter(base: self, scopes: scopes)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,6 +249,19 @@ extension RowAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/// EmptyRowAdapter is a row adapter that hides all columns.
|
||||
public struct EmptyRowAdapter: RowAdapter {
|
||||
/// Creates an EmptyRowAdapter
|
||||
public init() { }
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
return LayoutedColumnMapping(layoutColumns: [])
|
||||
}
|
||||
}
|
||||
|
||||
/// ColumnMapping is a row adapter that maps column names.
|
||||
///
|
||||
/// let adapter = ColumnMapping(["foo": "bar"])
|
||||
@@ -214,6 +280,8 @@ public struct ColumnMapping : RowAdapter {
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
let layoutColumns = try mapping
|
||||
.map { (mappedColumn, baseColumn) -> (Int, String) in
|
||||
@@ -250,6 +318,8 @@ public struct SuffixRowAdapter : RowAdapter {
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
return LayoutedColumnMapping(layoutColumns: layout.layoutColumns.suffix(from: index))
|
||||
}
|
||||
@@ -279,6 +349,8 @@ public struct RangeRowAdapter : RowAdapter {
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
return LayoutedColumnMapping(layoutColumns: layout.layoutColumns[range])
|
||||
}
|
||||
@@ -308,29 +380,57 @@ public struct RangeRowAdapter : RowAdapter {
|
||||
/// }
|
||||
public struct ScopeAdapter : RowAdapter {
|
||||
|
||||
/// The main adapter
|
||||
let mainAdapter: RowAdapter
|
||||
/// The base adapter
|
||||
let base: RowAdapter
|
||||
|
||||
/// The scope adapters
|
||||
let scopes: [String: RowAdapter]
|
||||
|
||||
/// Creates a scoped adapter.
|
||||
/// Creates an adapter that preserves row contents and add scoped rows.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let adapter = ScopeAdapter(["suffix": SuffixRowAdapter(fromIndex: 1)])
|
||||
/// let row = try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: adapter)!
|
||||
/// row // [1, 2, 3]
|
||||
/// row.scoped(on: "suffix") // [2, 3]
|
||||
///
|
||||
/// - parameter scopes: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
public init(_ scopes: [String: RowAdapter]) {
|
||||
self.mainAdapter = SuffixRowAdapter(fromIndex: 0) // Use SuffixRowAdapter(fromIndex: 0) as the identity adapter
|
||||
self.scopes = scopes
|
||||
// Use SuffixRowAdapter(fromIndex: 0) as the identity adapter
|
||||
self.init(base: SuffixRowAdapter(fromIndex: 0), scopes: scopes)
|
||||
}
|
||||
|
||||
init(mainAdapter: RowAdapter, scopes: [String: RowAdapter]) {
|
||||
self.mainAdapter = mainAdapter
|
||||
/// Creates an adapter based on the base adapter, and add scoped rows.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let baseAdapter = RangeRowAdapter(0..<1)
|
||||
/// let adapter = ScopeAdapter(base: baseAdapter, scopes: ["suffix": SuffixRowAdapter(fromIndex: 1)])
|
||||
/// let row = try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: adapter)!
|
||||
/// row // [1]
|
||||
/// row.scoped(on: "initial") // [2, 3]
|
||||
///
|
||||
/// If the base adapter already defines scopes, the given scopes replace
|
||||
/// eventual existing scopes with the same name.
|
||||
///
|
||||
/// This initializer is equivalent to `baseAdapter.addingScopes(scopes)`.
|
||||
///
|
||||
/// - parameter base: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
/// - parameter scopes: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
public init(base: RowAdapter, scopes: [String: RowAdapter]) {
|
||||
self.base = base
|
||||
self.scopes = scopes
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
let layoutedAdapter = try mainAdapter.layoutedAdapter(from: layout)
|
||||
let layoutedAdapter = try base.layoutedAdapter(from: layout)
|
||||
var layoutedScopes = layoutedAdapter.scopes
|
||||
for (name, adapter) in scopes {
|
||||
try layoutedScopes[name] = adapter.layoutedAdapter(from: layout)
|
||||
@@ -390,12 +490,29 @@ struct AdapterRowImpl : RowImpl {
|
||||
return base.isFetched
|
||||
}
|
||||
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
|
||||
return base[mapping.baseColumnIndex(atMappingIndex: index)]
|
||||
func hasNull(atUncheckedIndex index: Int) -> Bool {
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return base.impl.hasNull(atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return base.impl.databaseValue(atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value {
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return base.impl.fastValue(atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value? {
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return base.impl.fastValue(atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
|
||||
return base.dataNoCopy(atIndex: mapping.baseColumnIndex(atMappingIndex: index))
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return base.impl.dataNoCopy(atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func columnName(atUncheckedIndex index: Int) -> String {
|
||||
|
||||
@@ -16,14 +16,15 @@ import Dispatch
|
||||
/// of the dispatch queue, a SchedulingWatchdog that allows that database only.
|
||||
///
|
||||
/// Later on, the queue can be shared by several databases with the method
|
||||
/// allowing(databases:execute:). See SerializedDatabase.sync() for
|
||||
/// an example.
|
||||
/// inheritingAllowedDatabases(from:execute:). See SerializedDatabase.sync()
|
||||
/// for an example.
|
||||
///
|
||||
/// - preconditionValidQueue() crashes whenever a database is used in an invalid
|
||||
/// dispatch queue.
|
||||
final class SchedulingWatchdog {
|
||||
private static let specificKey = DispatchSpecificKey<SchedulingWatchdog>()
|
||||
private(set) var allowedDatabases: [Database]
|
||||
var databaseObservationBroker: DatabaseObservationBroker?
|
||||
|
||||
private init(allowedDatabase database: Database) {
|
||||
allowedDatabases = [database]
|
||||
@@ -36,27 +37,22 @@ final class SchedulingWatchdog {
|
||||
return queue
|
||||
}
|
||||
|
||||
// Temporarily allows `databases` while executing `body`
|
||||
func allowing<T>(databases: [Database], execute body: () throws -> T) rethrows -> T {
|
||||
func inheritingAllowedDatabases<T>(from other: SchedulingWatchdog, execute body: () throws -> T) rethrows -> T {
|
||||
let backup = allowedDatabases
|
||||
allowedDatabases.append(contentsOf: databases)
|
||||
allowedDatabases.append(contentsOf: other.allowedDatabases)
|
||||
defer { allowedDatabases = backup }
|
||||
return try body()
|
||||
}
|
||||
|
||||
static func preconditionValidQueue(_ db: Database, _ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
|
||||
GRDBPrecondition(allows(db), message, file: file, line: line)
|
||||
}
|
||||
|
||||
static func allows(_ db: Database) -> Bool {
|
||||
return current?.allows(db) ?? false
|
||||
}
|
||||
|
||||
func allows(_ db: Database) -> Bool {
|
||||
return allowedDatabases.contains { $0 === db }
|
||||
GRDBPrecondition(current?.allows(db) ?? false, message, file: file, line: line)
|
||||
}
|
||||
|
||||
static var current: SchedulingWatchdog? {
|
||||
return DispatchQueue.getSpecific(key: specificKey)
|
||||
}
|
||||
|
||||
func allows(_ db: Database) -> Bool {
|
||||
return allowedDatabases.contains { $0 === db }
|
||||
}
|
||||
}
|
||||
@@ -81,7 +81,8 @@ final class SerializedDatabase {
|
||||
guard let watchdog = SchedulingWatchdog.current else {
|
||||
// Case 1
|
||||
return try queue.sync {
|
||||
try block(db)
|
||||
defer { preconditionNoTransactionLeft(db) }
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,8 +91,9 @@ final class SerializedDatabase {
|
||||
|
||||
// Case 3
|
||||
return try queue.sync {
|
||||
try SchedulingWatchdog.current!.allowing(databases: watchdog.allowedDatabases) {
|
||||
try block(db)
|
||||
try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) {
|
||||
defer { preconditionNoTransactionLeft(db) }
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -125,19 +127,22 @@ final class SerializedDatabase {
|
||||
guard let watchdog = SchedulingWatchdog.current else {
|
||||
// Case 1
|
||||
return try queue.sync {
|
||||
try block(db)
|
||||
defer { preconditionNoTransactionLeft(db) }
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
|
||||
// Case 2
|
||||
if watchdog.allows(db) {
|
||||
defer { preconditionNoTransactionLeft(db) }
|
||||
return try block(db)
|
||||
}
|
||||
|
||||
// Case 3
|
||||
return try queue.sync {
|
||||
try SchedulingWatchdog.current!.allowing(databases: watchdog.allowedDatabases) {
|
||||
try block(db)
|
||||
try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) {
|
||||
defer { preconditionNoTransactionLeft(db) }
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -146,12 +151,13 @@ final class SerializedDatabase {
|
||||
func async(_ block: @escaping (Database) -> Void) {
|
||||
queue.async {
|
||||
block(self.db)
|
||||
self.preconditionNoTransactionLeft(self.db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if any only if the current dispatch queue is valid.
|
||||
var onValidQueue: Bool {
|
||||
return SchedulingWatchdog.allows(db)
|
||||
return SchedulingWatchdog.current?.allows(db) ?? false
|
||||
}
|
||||
|
||||
/// Executes the block in the current queue.
|
||||
@@ -166,4 +172,9 @@ final class SerializedDatabase {
|
||||
func preconditionValidQueue(_ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
|
||||
SchedulingWatchdog.preconditionValidQueue(db, message, file: file, line: line)
|
||||
}
|
||||
|
||||
/// Fatal error if a transaction has been left opened.
|
||||
func preconditionNoTransactionLeft(_ db: Database, _ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access", file: StaticString = #file, line: UInt = #line) {
|
||||
GRDBPrecondition(configuration.allowsUnsafeTransactions || !db.isInsideTransaction, message, file: file, line: line)
|
||||
}
|
||||
}
|
||||
+165
-133
@@ -8,6 +8,9 @@ import Foundation
|
||||
/// A raw SQLite statement, suitable for the SQLite C API.
|
||||
public typealias SQLiteStatement = OpaquePointer
|
||||
|
||||
/// Statements are separated by semicolons and white spaces
|
||||
let statementSeparatorCharacterSet = CharacterSet(charactersIn: ";").union(.whitespacesAndNewlines)
|
||||
|
||||
/// An error emitted when one tries to compile an empty statement.
|
||||
struct EmptyStatementError : Error {
|
||||
}
|
||||
@@ -25,10 +28,9 @@ public class Statement {
|
||||
public var sql: String {
|
||||
// trim white space and semicolumn for homogeneous output
|
||||
return String(cString: sqlite3_sql(sqliteStatement))
|
||||
.trimmingCharacters(in: CharacterSet(charactersIn: ";").union(.whitespacesAndNewlines))
|
||||
.trimmingCharacters(in: statementSeparatorCharacterSet)
|
||||
}
|
||||
|
||||
/// The database
|
||||
unowned let database: Database
|
||||
|
||||
/// Creates a prepared statement.
|
||||
@@ -42,7 +44,12 @@ public class Statement {
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
/// - throws: DatabaseError in case of compilation error, and
|
||||
/// EmptyStatementError if the compiled string is blank or empty.
|
||||
init(database: Database, statementStart: UnsafePointer<Int8>, statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>, prepFlags: Int32) throws {
|
||||
init(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
prepFlags: Int32) throws
|
||||
{
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
|
||||
var sqliteStatement: SQLiteStatement? = nil
|
||||
@@ -58,9 +65,6 @@ public class Statement {
|
||||
}
|
||||
|
||||
guard let statement = sqliteStatement else {
|
||||
// Sanity check: verify that the string contains only whitespace
|
||||
assert(String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: statementStart), count: statementEnd.pointee! - statementStart, deallocator: .none), encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
||||
|
||||
// I wish we could simply return nil, and make this initializer failable.
|
||||
//
|
||||
// Unfortunately, there is a Swift bug with failable+throwing initializers:
|
||||
@@ -105,7 +109,7 @@ public class Statement {
|
||||
guard let cString = sqlite3_bind_parameter_name(self.sqliteStatement, Int32($0 + 1)) else {
|
||||
return nil
|
||||
}
|
||||
return String(String(cString: cString).characters.dropFirst()) // Drop initial ":", "@", "$"
|
||||
return String(String(cString: cString).dropFirst()) // Drop initial ":", "@", "$"
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -135,7 +139,7 @@ public class Statement {
|
||||
clearBindings()
|
||||
|
||||
var valuesIterator = arguments.values.makeIterator()
|
||||
for (index, argumentName) in sqliteArgumentNames.enumerated() {
|
||||
for (index, argumentName) in zip(Int32(1)..., sqliteArgumentNames) {
|
||||
if let argumentName = argumentName, let value = arguments.namedValues[argumentName] {
|
||||
bind(value, at: index)
|
||||
} else if let value = valuesIterator.next() {
|
||||
@@ -156,26 +160,26 @@ public class Statement {
|
||||
// Apply
|
||||
reset()
|
||||
clearBindings()
|
||||
for (index, dbValue) in bindings.enumerated() {
|
||||
for (index, dbValue) in zip(Int32(1)..., bindings) {
|
||||
bind(dbValue, at: index)
|
||||
}
|
||||
}
|
||||
|
||||
// 0-based index
|
||||
private func bind(_ dbValue: DatabaseValue, at index: Int) {
|
||||
// 1-based index
|
||||
private func bind(_ dbValue: DatabaseValue, at index: Int32) {
|
||||
let code: Int32
|
||||
switch dbValue.storage {
|
||||
case .null:
|
||||
code = sqlite3_bind_null(sqliteStatement, Int32(index + 1))
|
||||
code = sqlite3_bind_null(sqliteStatement, index)
|
||||
case .int64(let int64):
|
||||
code = sqlite3_bind_int64(sqliteStatement, Int32(index + 1), int64)
|
||||
code = sqlite3_bind_int64(sqliteStatement, index, int64)
|
||||
case .double(let double):
|
||||
code = sqlite3_bind_double(sqliteStatement, Int32(index + 1), double)
|
||||
code = sqlite3_bind_double(sqliteStatement, index, double)
|
||||
case .string(let string):
|
||||
code = sqlite3_bind_text(sqliteStatement, Int32(index + 1), string, -1, SQLITE_TRANSIENT)
|
||||
code = sqlite3_bind_text(sqliteStatement, index, string, -1, SQLITE_TRANSIENT)
|
||||
case .blob(let data):
|
||||
code = data.withUnsafeBytes { bytes in
|
||||
sqlite3_bind_blob(sqliteStatement, Int32(index + 1), bytes, Int32(data.count), SQLITE_TRANSIENT)
|
||||
sqlite3_bind_blob(sqliteStatement, index, bytes, Int32(data.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,15 +210,75 @@ public class Statement {
|
||||
try! validate(arguments: self.arguments)
|
||||
}
|
||||
}
|
||||
|
||||
/// Utility function for cursors
|
||||
func cursorReset(arguments: StatementArguments? = nil) {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
prepare(withArguments: arguments)
|
||||
reset()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - AuthorizedStatement
|
||||
|
||||
/// A common protocol for UpdateStatement and SelectStatement
|
||||
protocol AuthorizedStatement {
|
||||
// This initializer should be a required initializer of Statement.
|
||||
//
|
||||
// But Swift requires this required initializer to be public:
|
||||
// https://bugs.swift.org/browse/SR-2347
|
||||
//
|
||||
// We work around SR-2347 with this internal protocol.
|
||||
init(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
prepFlags: Int32,
|
||||
authorizer: StatementCompilationAuthorizer) throws
|
||||
}
|
||||
|
||||
extension AuthorizedStatement {
|
||||
// Static function instead of an initializer because initializer doesn't
|
||||
// compile due to the "capturing of an uninitialized self" in
|
||||
// `sqlCodeUnits.withUnsafeBufferPointer`.
|
||||
static func prepare(sql: String, prepFlags: Int32, in database: Database) throws -> Self {
|
||||
let authorizer = StatementCompilationAuthorizer()
|
||||
database.authorizer = authorizer
|
||||
defer { database.authorizer = nil }
|
||||
|
||||
let sqlCodeUnits = sql.utf8CString
|
||||
return try sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
|
||||
let statementStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
|
||||
var statementEnd: UnsafePointer<Int8>? = nil
|
||||
let statement: Self
|
||||
do {
|
||||
statement = try self.init(
|
||||
database: database,
|
||||
statementStart: statementStart,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: prepFlags,
|
||||
authorizer: authorizer)
|
||||
} catch is EmptyStatementError {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_ERROR,
|
||||
message: "empty statement",
|
||||
sql: sql,
|
||||
arguments: nil)
|
||||
}
|
||||
|
||||
let remainingData = Data(
|
||||
bytesNoCopy: UnsafeMutableRawPointer(mutating: statementEnd!),
|
||||
count: statementStart + sqlCodeUnits.count - statementEnd! - 1,
|
||||
deallocator: .none)
|
||||
|
||||
let remainingSQL = String(data: remainingData, encoding: .utf8)!
|
||||
.trimmingCharacters(in: statementSeparatorCharacterSet)
|
||||
|
||||
guard remainingSQL.isEmpty else {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: "Multiple statements found. To execute multiple statements, use Database.execute() instead.",
|
||||
sql: sql,
|
||||
arguments: nil)
|
||||
}
|
||||
|
||||
return statement
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SelectStatement
|
||||
|
||||
@@ -228,8 +292,16 @@ public class Statement {
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
/// }
|
||||
public final class SelectStatement : Statement {
|
||||
/// Information about the table and columns read by a SelectStatement
|
||||
public private(set) var selectionInfo: SelectionInfo
|
||||
/// :nodoc:
|
||||
@available(*, deprecated, renamed:"DatabaseRegion")
|
||||
public typealias SelectionInfo = DatabaseRegion
|
||||
|
||||
/// :nodoc:
|
||||
@available(*, deprecated, renamed:"fetchedRegion")
|
||||
public var selectionInfo: DatabaseRegion { return fetchedRegion }
|
||||
|
||||
/// The database region that the statement looks into.
|
||||
public private(set) var fetchedRegion: DatabaseRegion
|
||||
|
||||
/// Creates a prepared statement.
|
||||
///
|
||||
@@ -243,29 +315,38 @@ public final class SelectStatement : Statement {
|
||||
/// - authorizer: A StatementCompilationAuthorizer
|
||||
/// - throws: DatabaseError in case of compilation error, and
|
||||
/// EmptyStatementError if the compiled string is blank or empty.
|
||||
init(database: Database, statementStart: UnsafePointer<Int8>, statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>, prepFlags: Int32, authorizer: StatementCompilationAuthorizer) throws {
|
||||
self.selectionInfo = SelectionInfo()
|
||||
init(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
prepFlags: Int32,
|
||||
authorizer: StatementCompilationAuthorizer) throws
|
||||
{
|
||||
self.fetchedRegion = DatabaseRegion()
|
||||
try super.init(
|
||||
database: database,
|
||||
statementStart: statementStart,
|
||||
statementEnd: statementEnd,
|
||||
prepFlags: prepFlags)
|
||||
Database.preconditionValidSelectStatement(sql: sql, authorizer: authorizer)
|
||||
self.selectionInfo = authorizer.selectionInfo
|
||||
|
||||
GRDBPrecondition(authorizer.invalidatesDatabaseSchemaCache == false, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
|
||||
GRDBPrecondition(authorizer.transactionEffect == nil, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
|
||||
|
||||
self.fetchedRegion = authorizer.region
|
||||
}
|
||||
|
||||
/// The number of columns in the resulting rows.
|
||||
public lazy var columnCount: Int = {
|
||||
Int(sqlite3_column_count(self.sqliteStatement))
|
||||
}()
|
||||
public var columnCount: Int {
|
||||
return Int(sqlite3_column_count(self.sqliteStatement))
|
||||
}
|
||||
|
||||
/// The column names, ordered from left to right.
|
||||
public lazy var columnNames: [String] = {
|
||||
let sqliteStatement = self.sqliteStatement
|
||||
return (0..<self.columnCount).map { (index: Int) -> String in String(cString: sqlite3_column_name(sqliteStatement, Int32(index))) }
|
||||
return (0..<Int32(self.columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
|
||||
}()
|
||||
|
||||
/// Cache for indexOfColumn(). Keys are lowercase.
|
||||
/// Cache for index(ofColumn:). Keys are lowercase.
|
||||
private lazy var columnIndexes: [String: Int] = {
|
||||
return Dictionary(
|
||||
self.columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
|
||||
@@ -284,69 +365,18 @@ public final class SelectStatement : Statement {
|
||||
func cursor(arguments: StatementArguments? = nil) -> StatementCursor {
|
||||
return StatementCursor(statement: self, arguments: arguments)
|
||||
}
|
||||
|
||||
/// Information about the table and columns read by a SelectStatement
|
||||
public struct SelectionInfo : CustomStringConvertible {
|
||||
mutating func insert(allColumnsOfTable table: String) {
|
||||
tables.insert(table)
|
||||
}
|
||||
|
||||
mutating func insert(column: String, ofTable table: String) {
|
||||
columns[table, default: []].insert(column)
|
||||
}
|
||||
|
||||
/// Returns true if isUnknown is true
|
||||
func contains(anyColumnFrom table: String) -> Bool {
|
||||
if isUnknown { return true }
|
||||
return tables.contains(table) || columns.index(forKey: table) != nil
|
||||
}
|
||||
|
||||
/// Returns true if isUnknown is true
|
||||
func contains(anyColumnIn columns: Set<String>, from table: String) -> Bool {
|
||||
if isUnknown { return true }
|
||||
return tables.contains(table) || !(self.columns[table]?.isDisjoint(with: columns) ?? true)
|
||||
}
|
||||
|
||||
init() {
|
||||
self.init(isUnknown: false)
|
||||
}
|
||||
|
||||
static func unknown() -> SelectionInfo {
|
||||
return self.init(isUnknown: true)
|
||||
}
|
||||
|
||||
/// If true, selection is unknown
|
||||
private let isUnknown: Bool
|
||||
|
||||
// `SELECT a, b FROM t1` -> ["t1": ["a", "b"]]
|
||||
private var columns: [String: Set<String>] = [:]
|
||||
|
||||
// `SELECT COUNT(*) FROM t1` -> ["t1"]
|
||||
private var tables: Set<String> = []
|
||||
|
||||
private init(isUnknown: Bool) {
|
||||
self.isUnknown = isUnknown
|
||||
}
|
||||
|
||||
/// A textual representation of `self`.
|
||||
public var description: String {
|
||||
if isUnknown {
|
||||
return "unknown"
|
||||
}
|
||||
return tables.union(columns.keys)
|
||||
.sorted()
|
||||
.map { table -> String in
|
||||
if let columns = columns[table] {
|
||||
return "\(table)(\(columns.sorted().joined(separator: ",")))"
|
||||
} else {
|
||||
return "\(table)(*)"
|
||||
}
|
||||
}
|
||||
.joined(separator: ",")
|
||||
}
|
||||
|
||||
/// Utility function for cursors
|
||||
func cursorReset(arguments: StatementArguments? = nil) {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
prepare(withArguments: arguments)
|
||||
reset()
|
||||
}
|
||||
}
|
||||
|
||||
// Hide AuthorizedStatement from Jazzy
|
||||
extension SelectStatement: AuthorizedStatement { }
|
||||
|
||||
/// A cursor that iterates a database statement without producing any value.
|
||||
/// For example:
|
||||
///
|
||||
@@ -366,6 +396,7 @@ public final class StatementCursor: Cursor {
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func next() throws -> Void? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
@@ -395,32 +426,20 @@ public final class StatementCursor: Cursor {
|
||||
/// return .commit
|
||||
/// }
|
||||
public final class UpdateStatement : Statement {
|
||||
enum TransactionStatementInfo {
|
||||
enum SavepointAction : String {
|
||||
case begin = "BEGIN"
|
||||
case release = "RELEASE"
|
||||
case rollback = "ROLLBACK"
|
||||
}
|
||||
|
||||
enum TransactionAction : String {
|
||||
case begin = "BEGIN"
|
||||
case commit = "COMMIT"
|
||||
case rollback = "ROLLBACK"
|
||||
}
|
||||
|
||||
case transaction(action: TransactionAction)
|
||||
case savepoint(name: String, action: SavepointAction)
|
||||
enum TransactionEffect {
|
||||
case beginTransaction
|
||||
case commitTransaction
|
||||
case rollbackTransaction
|
||||
case beginSavepoint(String)
|
||||
case releaseSavepoint(String)
|
||||
case rollbackSavepoint(String)
|
||||
}
|
||||
|
||||
/// If true, the database schema cache gets invalidated after this statement
|
||||
/// is executed.
|
||||
private(set) var invalidatesDatabaseSchemaCache: Bool
|
||||
|
||||
/// If true, the statement needs support from TruncateOptimizationBlocker
|
||||
/// when executed
|
||||
private(set) var needsTruncateOptimizationPreventionDuringExecution: Bool
|
||||
|
||||
private(set) var transactionStatementInfo: TransactionStatementInfo?
|
||||
private(set) var transactionEffect: TransactionEffect?
|
||||
private(set) var databaseEventKinds: [DatabaseEventKind]
|
||||
|
||||
/// Creates a prepared statement.
|
||||
@@ -435,9 +454,14 @@ public final class UpdateStatement : Statement {
|
||||
/// - authorizer: A StatementCompilationAuthorizer
|
||||
/// - throws: DatabaseError in case of compilation error, and
|
||||
/// EmptyStatementError if the compiled string is blank or empty.
|
||||
init(database: Database, statementStart: UnsafePointer<Int8>, statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>, prepFlags: Int32, authorizer: StatementCompilationAuthorizer) throws {
|
||||
init(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
prepFlags: Int32,
|
||||
authorizer: StatementCompilationAuthorizer) throws
|
||||
{
|
||||
self.invalidatesDatabaseSchemaCache = false
|
||||
self.needsTruncateOptimizationPreventionDuringExecution = false
|
||||
self.databaseEventKinds = []
|
||||
try super.init(
|
||||
database: database,
|
||||
@@ -445,8 +469,7 @@ public final class UpdateStatement : Statement {
|
||||
statementEnd: statementEnd,
|
||||
prepFlags: prepFlags)
|
||||
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
|
||||
self.needsTruncateOptimizationPreventionDuringExecution = authorizer.needsTruncateOptimizationPreventionDuringExecution
|
||||
self.transactionStatementInfo = authorizer.transactionStatementInfo
|
||||
self.transactionEffect = authorizer.transactionEffect
|
||||
self.databaseEventKinds = authorizer.databaseEventKinds
|
||||
}
|
||||
|
||||
@@ -460,10 +483,6 @@ public final class UpdateStatement : Statement {
|
||||
reset()
|
||||
database.updateStatementWillExecute(self)
|
||||
|
||||
if needsTruncateOptimizationPreventionDuringExecution {
|
||||
database.authorizer = TruncateOptimizationBlocker()
|
||||
}
|
||||
|
||||
while true {
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_ROW:
|
||||
@@ -486,12 +505,10 @@ public final class UpdateStatement : Statement {
|
||||
continue
|
||||
|
||||
case SQLITE_DONE:
|
||||
database.authorizer = nil
|
||||
database.updateStatementDidExecute(self)
|
||||
try database.updateStatementDidExecute(self)
|
||||
return
|
||||
|
||||
case let code:
|
||||
database.authorizer = nil
|
||||
try database.updateStatementDidFail(self)
|
||||
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql, arguments: self.arguments) // Error uses self.arguments, not the optional arguments parameter.
|
||||
}
|
||||
@@ -499,6 +516,9 @@ public final class UpdateStatement : Statement {
|
||||
}
|
||||
}
|
||||
|
||||
// Hide AuthorizedStatement from Jazzy
|
||||
extension UpdateStatement: AuthorizedStatement { }
|
||||
|
||||
|
||||
// MARK: - StatementArguments
|
||||
|
||||
@@ -573,7 +593,9 @@ public final class UpdateStatement : Statement {
|
||||
/// let row = try Row.fetchOne(db, sql, arguments: [1, 2, "bar"] + ["foo": "foo"])!
|
||||
/// print(row)
|
||||
/// // Prints <Row two:2 foo:"foo" one:1 foo2:"foo" bar:"bar">
|
||||
public struct StatementArguments {
|
||||
public struct StatementArguments: CustomStringConvertible, Equatable, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral {
|
||||
var values: [DatabaseValue] = []
|
||||
var namedValues: [String: DatabaseValue] = [:]
|
||||
|
||||
public var isEmpty: Bool {
|
||||
return values.isEmpty && namedValues.isEmpty
|
||||
@@ -831,9 +853,6 @@ public struct StatementArguments {
|
||||
|
||||
// MARK: Not Public
|
||||
|
||||
var values: [DatabaseValue] = []
|
||||
var namedValues: [String: DatabaseValue] = [:]
|
||||
|
||||
mutating func consume(_ statement: Statement, allowingRemainingValues: Bool) throws -> [DatabaseValue] {
|
||||
let initialValuesCount = values.count
|
||||
let bindings = try statement.sqliteArgumentNames.map { argumentName -> DatabaseValue in
|
||||
@@ -860,7 +879,8 @@ public struct StatementArguments {
|
||||
}
|
||||
}
|
||||
|
||||
extension StatementArguments : ExpressibleByArrayLiteral {
|
||||
// ExpressibleByArrayLiteral
|
||||
extension StatementArguments {
|
||||
/// Returns a StatementArguments from an array literal:
|
||||
///
|
||||
/// db.selectRows("SELECT ...", arguments: ["Arthur", 41])
|
||||
@@ -869,7 +889,8 @@ extension StatementArguments : ExpressibleByArrayLiteral {
|
||||
}
|
||||
}
|
||||
|
||||
extension StatementArguments : ExpressibleByDictionaryLiteral {
|
||||
// ExpressibleByDictionaryLiteral
|
||||
extension StatementArguments {
|
||||
/// Returns a StatementArguments from a dictionary literal:
|
||||
///
|
||||
/// db.selectRows("SELECT ...", arguments: ["name": "Arthur", "score": 41])
|
||||
@@ -878,8 +899,9 @@ extension StatementArguments : ExpressibleByDictionaryLiteral {
|
||||
}
|
||||
}
|
||||
|
||||
extension StatementArguments : CustomStringConvertible {
|
||||
/// A textual representation of `self`.
|
||||
// CustomStringConvertible
|
||||
extension StatementArguments {
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
let valuesDescriptions = values.map { $0.description }
|
||||
let namedValuesDescriptions = namedValues.map { (key, value) -> String in
|
||||
@@ -889,6 +911,16 @@ extension StatementArguments : CustomStringConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
// Equatable
|
||||
extension StatementArguments {
|
||||
/// :nodoc:
|
||||
public static func == (lhs: StatementArguments, rhs: StatementArguments) -> Bool {
|
||||
if lhs.values != rhs.values { return false }
|
||||
if lhs.namedValues != rhs.namedValues { return false }
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/// A thread-unsafe statement cache
|
||||
struct StatementCache {
|
||||
unowned let db: Database
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// A protocol around sqlite3_set_authorizer
|
||||
protocol StatementAuthorizer : class {
|
||||
func authorize(
|
||||
_ actionCode: Int32,
|
||||
_ cString1: UnsafePointer<Int8>?,
|
||||
_ cString2: UnsafePointer<Int8>?,
|
||||
_ cString3: UnsafePointer<Int8>?,
|
||||
_ cString4: UnsafePointer<Int8>?)
|
||||
-> Int32
|
||||
}
|
||||
|
||||
/// A class that gathers information about one statement during its compilation.
|
||||
final class StatementCompilationAuthorizer : StatementAuthorizer {
|
||||
/// What this statements reads
|
||||
var region = DatabaseRegion()
|
||||
|
||||
/// What this statements writes
|
||||
var databaseEventKinds: [DatabaseEventKind] = []
|
||||
|
||||
/// True if a statement alter the schema in a way that required schema cache
|
||||
/// invalidation. For example, adding a column to a table invalidates the
|
||||
/// schema cache, but not creating a table.
|
||||
var invalidatesDatabaseSchemaCache = false
|
||||
|
||||
/// Not nil if a statement is a BEGIN/COMMIT/ROLLBACK/RELEASE transaction or
|
||||
/// savepoint statement.
|
||||
var transactionEffect: UpdateStatement.TransactionEffect?
|
||||
|
||||
private var isDropStatement = false
|
||||
|
||||
func authorize(
|
||||
_ actionCode: Int32,
|
||||
_ cString1: UnsafePointer<Int8>?,
|
||||
_ cString2: UnsafePointer<Int8>?,
|
||||
_ cString3: UnsafePointer<Int8>?,
|
||||
_ cString4: UnsafePointer<Int8>?)
|
||||
-> Int32
|
||||
{
|
||||
// print("StatementCompilationAuthorizer: \(actionCode) \([cString1, cString2, cString3, cString4].flatMap { $0.map({ String(cString: $0) }) })")
|
||||
|
||||
switch actionCode {
|
||||
case SQLITE_DROP_TABLE, SQLITE_DROP_VTABLE, SQLITE_DROP_TEMP_TABLE,
|
||||
SQLITE_DROP_INDEX, SQLITE_DROP_TEMP_INDEX:
|
||||
isDropStatement = true
|
||||
invalidatesDatabaseSchemaCache = true
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_DROP_VIEW, SQLITE_DROP_TEMP_VIEW,
|
||||
SQLITE_DROP_TRIGGER, SQLITE_CREATE_TEMP_TRIGGER:
|
||||
isDropStatement = true
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_DETACH, SQLITE_ALTER_TABLE,
|
||||
SQLITE_CREATE_INDEX, SQLITE_CREATE_TEMP_INDEX:
|
||||
invalidatesDatabaseSchemaCache = true
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_READ:
|
||||
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
|
||||
guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
|
||||
if columnName.isEmpty {
|
||||
// SELECT COUNT(*) FROM table
|
||||
region.formUnion(DatabaseRegion(table: tableName))
|
||||
} else {
|
||||
// SELECT column FROM table
|
||||
region.formUnion(DatabaseRegion(table: tableName, columns: [columnName]))
|
||||
}
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_INSERT:
|
||||
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
|
||||
databaseEventKinds.append(.insert(tableName: tableName))
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_DELETE:
|
||||
if isDropStatement { return SQLITE_OK }
|
||||
guard let cString1 = cString1 else { return SQLITE_OK }
|
||||
|
||||
// Deletions from sqlite_master and sqlite_temp_master are not like
|
||||
// other deletions: the update hook does not notify them, and they
|
||||
// are prevented when the truncate optimization is disabled.
|
||||
// Let's authorize such deletions by returning SQLITE_OK:
|
||||
guard strcmp(cString1, "sqlite_master") != 0 else { return SQLITE_OK }
|
||||
guard strcmp(cString1, "sqlite_temp_master") != 0 else { return SQLITE_OK }
|
||||
|
||||
// Now we prevent the truncate optimization so that transaction
|
||||
// observers are notified of individual row deletions.
|
||||
databaseEventKinds.append(.delete(tableName: String(cString: cString1)))
|
||||
return SQLITE_IGNORE
|
||||
|
||||
case SQLITE_UPDATE:
|
||||
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
|
||||
guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
|
||||
insertUpdateEventKind(tableName: tableName, columnName: columnName)
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_TRANSACTION:
|
||||
guard let cString1 = cString1 else { return SQLITE_OK }
|
||||
if strcmp(cString1, "BEGIN") == 0 {
|
||||
transactionEffect = .beginTransaction
|
||||
} else if strcmp(cString1, "COMMIT") == 0 {
|
||||
transactionEffect = .commitTransaction
|
||||
} else if strcmp(cString1, "ROLLBACK") == 0 {
|
||||
transactionEffect = .rollbackTransaction
|
||||
}
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_SAVEPOINT:
|
||||
guard let cString1 = cString1 else { return SQLITE_OK }
|
||||
guard let name = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
|
||||
if strcmp(cString1, "BEGIN") == 0 {
|
||||
transactionEffect = .beginSavepoint(name)
|
||||
} else if strcmp(cString1, "RELEASE") == 0 {
|
||||
transactionEffect = .releaseSavepoint(name)
|
||||
} else if strcmp(cString1, "ROLLBACK") == 0 {
|
||||
transactionEffect = .rollbackSavepoint(name)
|
||||
}
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_FUNCTION:
|
||||
// Starting SQLite 3.19.0, `SELECT COUNT(*) FROM table` triggers
|
||||
// an authorization callback for SQLITE_READ with an empty
|
||||
// column: http://www.sqlite.org/changes.html#version_3_19_0
|
||||
//
|
||||
// Before SQLite 3.19.0, `SELECT COUNT(*) FROM table` does not
|
||||
// trigger any authorization callback that tells about the
|
||||
// counted table: any use of the COUNT function makes the
|
||||
// region undetermined (the full database).
|
||||
guard sqlite3_libversion_number() < 3019000 else { return SQLITE_OK }
|
||||
guard let cString2 = cString2 else { return SQLITE_OK }
|
||||
if sqlite3_stricmp(cString2, "COUNT") == 0 {
|
||||
region = .fullDatabase
|
||||
}
|
||||
return SQLITE_OK
|
||||
|
||||
default:
|
||||
return SQLITE_OK
|
||||
}
|
||||
}
|
||||
|
||||
func insertUpdateEventKind(tableName: String, columnName: String) {
|
||||
for (index, eventKind) in databaseEventKinds.enumerated() {
|
||||
if case .update(let t, let columnNames) = eventKind, t == tableName {
|
||||
var columnNames = columnNames
|
||||
columnNames.insert(columnName)
|
||||
databaseEventKinds[index] = .update(tableName: tableName, columnNames: columnNames)
|
||||
return
|
||||
}
|
||||
}
|
||||
databaseEventKinds.append(.update(tableName: tableName, columnNames: [columnName]))
|
||||
}
|
||||
}
|
||||
|
||||
/// This authorizer prevents the [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
|
||||
/// which makes transaction observers unable to observe individual deletions
|
||||
/// when user runs `DELETE FROM t` statements.
|
||||
//
|
||||
/// Warning: to perform well, this authorizer must be used during statement
|
||||
/// execution, not during statement compilation.
|
||||
final class TruncateOptimizationBlocker : StatementAuthorizer {
|
||||
func authorize(
|
||||
_ actionCode: Int32,
|
||||
_ cString1: UnsafePointer<Int8>?,
|
||||
_ cString2: UnsafePointer<Int8>?,
|
||||
_ cString3: UnsafePointer<Int8>?,
|
||||
_ cString4: UnsafePointer<Int8>?)
|
||||
-> Int32
|
||||
{
|
||||
// print("TruncateOptimizationBlocker: \(actionCode) \([cString1, cString2, cString3, cString4].flatMap { $0.map({ String(cString: $0) }) })")
|
||||
return (actionCode == SQLITE_DELETE) ? SQLITE_IGNORE : SQLITE_OK
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +50,27 @@ public protocol StatementColumnConvertible {
|
||||
init(sqliteStatement: SQLiteStatement, index: Int32)
|
||||
}
|
||||
|
||||
extension StatementColumnConvertible {
|
||||
|
||||
@inline(__always)
|
||||
static func losslessConvert(sqliteStatement: SQLiteStatement, index: Int32) -> Self? {
|
||||
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else {
|
||||
return nil
|
||||
}
|
||||
return self.init(sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
static func losslessConvert(sqliteStatement: SQLiteStatement, index: Int32) -> Self {
|
||||
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else {
|
||||
// Programmer error
|
||||
fatalError("could not convert database value NULL to \(Self.self)")
|
||||
}
|
||||
return self.init(sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// A cursor of database values extracted from a single column.
|
||||
/// For example:
|
||||
///
|
||||
@@ -73,6 +94,7 @@ public final class ColumnCursor<Value: DatabaseValueConvertible & StatementColum
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func next() throws -> Value? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
@@ -118,6 +140,7 @@ public final class NullableColumnCursor<Value: DatabaseValueConvertible & Statem
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func next() throws -> Value?? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+17
-4
@@ -111,16 +111,16 @@ public struct FTS4 : VirtualTableModule {
|
||||
let oldRowID = "old.\(rowIDColumn.quotedDatabaseIdentifier)"
|
||||
|
||||
try db.execute("""
|
||||
CREATE TRIGGER \("__\(contentTable)_bu".quotedDatabaseIdentifier) BEFORE UPDATE ON \(content) BEGIN
|
||||
CREATE TRIGGER \("__\(tableName)_bu".quotedDatabaseIdentifier) BEFORE UPDATE ON \(content) BEGIN
|
||||
DELETE FROM \(ftsTable) WHERE docid=\(oldRowID);
|
||||
END;
|
||||
CREATE TRIGGER \("__\(contentTable)_bd".quotedDatabaseIdentifier) BEFORE DELETE ON \(content) BEGIN
|
||||
CREATE TRIGGER \("__\(tableName)_bd".quotedDatabaseIdentifier) BEFORE DELETE ON \(content) BEGIN
|
||||
DELETE FROM \(ftsTable) WHERE docid=\(oldRowID);
|
||||
END;
|
||||
CREATE TRIGGER \("__\(contentTable)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
|
||||
CREATE TRIGGER \("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
|
||||
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns));
|
||||
END;
|
||||
CREATE TRIGGER \("__\(contentTable)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
|
||||
CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
|
||||
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns));
|
||||
END;
|
||||
""")
|
||||
@@ -269,6 +269,7 @@ public final class FTS4ColumnDefinition {
|
||||
/// See https://www.sqlite.org/fts3.html#the_notindexed_option
|
||||
///
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
/// :nodoc:
|
||||
@discardableResult
|
||||
public func notIndexed() -> Self {
|
||||
// notindexed FTS4 option was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
|
||||
@@ -313,3 +314,15 @@ public final class FTS4ColumnDefinition {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
/// Deletes the synchronization triggers for a synchronized FTS4 table
|
||||
public func dropFTS4SynchronizationTriggers(forTable tableName: String) throws {
|
||||
try execute("""
|
||||
DROP TRIGGER IF EXISTS \("__\(tableName)_bu".quotedDatabaseIdentifier);
|
||||
DROP TRIGGER IF EXISTS \("__\(tableName)_bd".quotedDatabaseIdentifier);
|
||||
DROP TRIGGER IF EXISTS \("__\(tableName)_au".quotedDatabaseIdentifier);
|
||||
DROP TRIGGER IF EXISTS \("__\(tableName)_ai".quotedDatabaseIdentifier);
|
||||
""")
|
||||
}
|
||||
}
|
||||
+14
-3
@@ -111,13 +111,13 @@
|
||||
.joined(separator: ", ")
|
||||
|
||||
try db.execute("""
|
||||
CREATE TRIGGER \("__\(contentTable)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
|
||||
CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
|
||||
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
|
||||
END;
|
||||
CREATE TRIGGER \("__\(contentTable)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN
|
||||
CREATE TRIGGER \("__\(tableName)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN
|
||||
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
|
||||
END;
|
||||
CREATE TRIGGER \("__\(contentTable)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
|
||||
CREATE TRIGGER \("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
|
||||
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
|
||||
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
|
||||
END;
|
||||
@@ -319,4 +319,15 @@
|
||||
/// The FTS5 rank column
|
||||
public static let rank = Column("rank")
|
||||
}
|
||||
|
||||
extension Database {
|
||||
/// Deletes the synchronization triggers for a synchronized FTS5 table
|
||||
public func dropFTS5SynchronizationTriggers(forTable tableName: String) throws {
|
||||
try execute("""
|
||||
DROP TRIGGER IF EXISTS \("__\(tableName)_ai".quotedDatabaseIdentifier);
|
||||
DROP TRIGGER IF EXISTS \("__\(tableName)_ad".quotedDatabaseIdentifier);
|
||||
DROP TRIGGER IF EXISTS \("__\(tableName)_au".quotedDatabaseIdentifier);
|
||||
""")
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -38,7 +38,7 @@
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Custom FTS5 Tokenizers
|
||||
// MARK: - FTS5
|
||||
|
||||
private class FTS5TokenizerConstructor {
|
||||
let db: Database
|
||||
|
||||
@@ -44,6 +44,19 @@
|
||||
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
|
||||
}
|
||||
|
||||
/// Creates a pattern that matches a contiguous string prefix; returns
|
||||
/// nil if no pattern could be built.
|
||||
///
|
||||
/// FTS5Pattern(matchingPrefixPhrase: "") // nil
|
||||
/// FTS5Pattern(matchingPrefixPhrase: "foo bar") // ^"foo bar"
|
||||
///
|
||||
/// - parameter string: The string to turn into an FTS5 pattern
|
||||
public init?(matchingPrefixPhrase string: String) {
|
||||
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil }
|
||||
guard !tokens.isEmpty else { return nil }
|
||||
try? self.init(rawPattern: "^\"" + tokens.joined(separator: " ") + "\"")
|
||||
}
|
||||
|
||||
init(rawPattern: String, allowedColumns: [String] = []) throws {
|
||||
// Correctness above all: use SQLite to validate the pattern.
|
||||
//
|
||||
@@ -77,6 +90,8 @@
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - FTS5
|
||||
|
||||
/// Creates a pattern from a raw pattern string; throws DatabaseError on
|
||||
/// invalid syntax.
|
||||
///
|
||||
|
||||
@@ -106,8 +106,9 @@
|
||||
}
|
||||
|
||||
extension Database {
|
||||
/// MARK: - FTS5 Tokenizers
|
||||
|
||||
// MARK: - FTS5
|
||||
|
||||
/// Private type that makes a pre-registered FTS5 tokenizer available
|
||||
/// through the FTS5Tokenizer protocol.
|
||||
private final class FTS5RegisteredTokenizer : FTS5Tokenizer {
|
||||
|
||||
@@ -85,6 +85,8 @@ public struct DatabaseMigrator {
|
||||
/// - identifier: The migration identifier.
|
||||
/// - block: The migration block that performs SQL statements.
|
||||
/// - precondition: No migration with the same same as already been registered.
|
||||
///
|
||||
/// :nodoc:
|
||||
public mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void) {
|
||||
registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate))
|
||||
}
|
||||
|
||||
@@ -1,23 +1,40 @@
|
||||
/// A column in the database
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift#the-query-interface
|
||||
public struct Column {
|
||||
public struct Column : SQLExpression {
|
||||
/// The hidden rowID column
|
||||
public static let rowID = Column("rowid")
|
||||
|
||||
/// The name of the column
|
||||
public let name: String
|
||||
|
||||
private var qualifier: SQLTableQualifier?
|
||||
|
||||
/// Creates a column given its name.
|
||||
public init(_ name: String) {
|
||||
self.name = name
|
||||
}
|
||||
}
|
||||
|
||||
extension Column : SQLExpression {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
if let qualifierName = qualifier?.name {
|
||||
return qualifierName.quotedDatabaseIdentifier + "." + name.quotedDatabaseIdentifier
|
||||
}
|
||||
return name.quotedDatabaseIdentifier
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func qualified(by qualifier: SQLTableQualifier) -> Column {
|
||||
if self.qualifier != nil {
|
||||
// Never requalify
|
||||
return self
|
||||
}
|
||||
var column = self
|
||||
column.qualifier = qualifier
|
||||
return column
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,8 @@ extension QueryInterfaceRequest : TypedRequest {
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try query.prepare(db)
|
||||
}
|
||||
@@ -23,9 +25,18 @@ extension QueryInterfaceRequest : TypedRequest {
|
||||
/// The number of rows fetched by the request.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try query.fetchCount(db)
|
||||
}
|
||||
|
||||
/// The database region that the request looks into.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try query.fetchedRegion(db)
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
@@ -104,13 +115,13 @@ extension QueryInterfaceRequest {
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(Column("email") == "arthur@example.com")
|
||||
public func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest<T> {
|
||||
var query = self.query
|
||||
if let whereExpression = query.whereExpression {
|
||||
query.whereExpression = whereExpression && predicate.sqlExpression
|
||||
} else {
|
||||
query.whereExpression = predicate.sqlExpression
|
||||
}
|
||||
return QueryInterfaceRequest(query: query)
|
||||
return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in
|
||||
if let expression = expression {
|
||||
return expression && predicate.sqlExpression
|
||||
} else {
|
||||
return predicate.sqlExpression
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// A new QueryInterfaceRequest with the provided *predicate* added to the
|
||||
@@ -235,6 +246,125 @@ extension QueryInterfaceRequest {
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest where T: TableMapping {
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM players WHERE id = 1
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(key: 1)
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> QueryInterfaceRequest<T> {
|
||||
guard let key = key else {
|
||||
return T.none()
|
||||
}
|
||||
|
||||
return filter(keys: [key])
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM players WHERE id IN (1, 2, 3)
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(keys: [1, 2, 3])
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public func filter<Sequence: Swift.Sequence>(keys: Sequence) -> QueryInterfaceRequest<T> where Sequence.Element: DatabaseValueConvertible {
|
||||
let keys = Array(keys)
|
||||
let makePredicate: (Column) -> SQLExpression
|
||||
switch keys.count {
|
||||
case 0:
|
||||
return T.none()
|
||||
case 1:
|
||||
makePredicate = { $0 == keys[0] }
|
||||
default:
|
||||
makePredicate = { keys.contains($0) }
|
||||
}
|
||||
|
||||
return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in
|
||||
let primaryKey = try db.primaryKey(T.databaseTableName)
|
||||
GRDBPrecondition(primaryKey.columns.count == 1, "Requesting by key requires a single-column primary key in the table \(T.databaseTableName)")
|
||||
let keysPredicate = makePredicate(Column(primaryKey.columns[0]))
|
||||
if let expression = expression {
|
||||
return expression && keysPredicate
|
||||
} else {
|
||||
return keysPredicate
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM passports WHERE personId = 1 AND countryCode = 'FR'
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(key: ["personId": 1, "countryCode": "FR"])
|
||||
///
|
||||
/// When executed, this request raises a fatal error if there is no unique
|
||||
/// index on the key columns.
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest<T> {
|
||||
guard let key = key else {
|
||||
return T.none()
|
||||
}
|
||||
|
||||
return filter(keys: [key])
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM passports WHERE (personId = 1 AND countryCode = 'FR') OR ...
|
||||
/// let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...])
|
||||
///
|
||||
/// When executed, this request raises a fatal error if there is no unique
|
||||
/// index on the key columns.
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest<T> {
|
||||
guard !keys.isEmpty else {
|
||||
return T.none()
|
||||
}
|
||||
|
||||
return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in
|
||||
let keyPredicates: [SQLExpression] = try keys.map { key in
|
||||
// Prevent filter(db, keys: [[:]])
|
||||
GRDBPrecondition(!key.isEmpty, "Invalid empty key dictionary")
|
||||
|
||||
// Prevent filter(keys: [["foo": 1, "bar": 2]]) where
|
||||
// ("foo", "bar") is not a unique key (primary key or columns of a
|
||||
// unique index)
|
||||
guard let orderedColumns = try db.columnsForUniqueKey(key.keys, in: T.databaseTableName) else {
|
||||
fatalError("table \(T.databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))")
|
||||
}
|
||||
|
||||
let lowercaseOrderedColumns = orderedColumns.map { $0.lowercased() }
|
||||
let columnPredicates: [SQLExpression] = key
|
||||
// Sort key columns in the same order as the unique index
|
||||
.sorted { (kv1, kv2) in lowercaseOrderedColumns.index(of: kv1.0.lowercased())! < lowercaseOrderedColumns.index(of: kv2.0.lowercased())! }
|
||||
.map { (column, value) in Column(column) == value }
|
||||
return SQLBinaryOperator.and.join(columnPredicates)! // not nil because columnPredicates is not empty
|
||||
}
|
||||
|
||||
let keysPredicate = SQLBinaryOperator.or.join(keyPredicates)! // not nil because keyPredicates is not empty
|
||||
|
||||
if let expression = expression {
|
||||
return expression && keysPredicate
|
||||
} else {
|
||||
return keysPredicate
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest where RowDecoder: MutablePersistable {
|
||||
|
||||
// MARK: Deleting
|
||||
@@ -308,6 +438,60 @@ extension TableMapping {
|
||||
return all().filter(predicate)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM players WHERE id = 1
|
||||
/// let request = Player.filter(key: 1)
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public static func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> QueryInterfaceRequest<Self> {
|
||||
return all().filter(key: key)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM players WHERE id IN (1, 2, 3)
|
||||
/// let request = Player.filter(keys: [1, 2, 3])
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public static func filter<Sequence: Swift.Sequence>(keys: Sequence) -> QueryInterfaceRequest<Self> where Sequence.Element: DatabaseValueConvertible {
|
||||
return all().filter(keys: keys)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM passports WHERE personId = 1 AND countryCode = 'FR'
|
||||
/// let request = Passport.filter(key: ["personId": 1, "countryCode": "FR"])
|
||||
///
|
||||
/// When executed, this request raises a fatal error if there is no unique
|
||||
/// index on the key columns.
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public static func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest<Self> {
|
||||
return all().filter(key: key)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM passports WHERE (personId = 1 AND countryCode = 'FR') OR ...
|
||||
/// let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...])
|
||||
///
|
||||
/// When executed, this request raises a fatal error if there is no unique
|
||||
/// index on the key columns.
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public static func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest<Self> {
|
||||
return all().filter(keys: keys)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM players WHERE email = 'arthur@example.com'
|
||||
|
||||
@@ -1,10 +1,28 @@
|
||||
// MARK: - QueryInterfaceSelectQueryDefinition
|
||||
|
||||
struct DatabasePromise<T> {
|
||||
let resolve: (Database) throws -> T
|
||||
|
||||
init(value: T) {
|
||||
self.resolve = { _ in value }
|
||||
}
|
||||
|
||||
init(_ resolve: @escaping (Database) throws -> T) {
|
||||
self.resolve = resolve
|
||||
}
|
||||
|
||||
func map(_ transform: @escaping (Database, T) throws -> T) -> DatabasePromise {
|
||||
return DatabasePromise { db in
|
||||
try transform(db, self.resolve(db))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct QueryInterfaceSelectQueryDefinition {
|
||||
var selection: [SQLSelectable]
|
||||
var isDistinct: Bool
|
||||
var source: SQLSource?
|
||||
var whereExpression: SQLExpression?
|
||||
var wherePromise: DatabasePromise<SQLExpression?>
|
||||
var groupByExpressions: [SQLExpression]
|
||||
var orderings: [SQLOrderingTerm]
|
||||
var isReversed: Bool
|
||||
@@ -25,7 +43,7 @@ struct QueryInterfaceSelectQueryDefinition {
|
||||
self.selection = selection
|
||||
self.isDistinct = isDistinct
|
||||
self.source = source
|
||||
self.whereExpression = whereExpression
|
||||
self.wherePromise = DatabasePromise(value: whereExpression)
|
||||
self.groupByExpressions = groupByExpressions
|
||||
self.orderings = orderings
|
||||
self.isReversed = isReversed
|
||||
@@ -33,7 +51,13 @@ struct QueryInterfaceSelectQueryDefinition {
|
||||
self.limit = limit
|
||||
}
|
||||
|
||||
func sql(_ arguments: inout StatementArguments?) -> String {
|
||||
func mapWhereExpression(_ transform: @escaping (Database, SQLExpression?) throws -> SQLExpression?) -> QueryInterfaceSelectQueryDefinition {
|
||||
var query = self
|
||||
query.wherePromise = query.wherePromise.map(transform)
|
||||
return query
|
||||
}
|
||||
|
||||
func sql(_ db: Database, _ arguments: inout StatementArguments?) throws -> String {
|
||||
var sql = "SELECT"
|
||||
|
||||
if isDistinct {
|
||||
@@ -44,10 +68,10 @@ struct QueryInterfaceSelectQueryDefinition {
|
||||
sql += " " + selection.map { $0.resultColumnSQL(&arguments) }.joined(separator: ", ")
|
||||
|
||||
if let source = source {
|
||||
sql += " FROM " + source.sourceSQL(&arguments)
|
||||
sql += try " FROM " + source.sourceSQL(db, &arguments)
|
||||
}
|
||||
|
||||
if let whereExpression = whereExpression {
|
||||
if let whereExpression = try wherePromise.resolve(db) {
|
||||
sql += " WHERE " + whereExpression.expressionSQL(&arguments)
|
||||
}
|
||||
|
||||
@@ -86,10 +110,10 @@ struct QueryInterfaceSelectQueryDefinition {
|
||||
var arguments: StatementArguments? = StatementArguments()
|
||||
|
||||
if let source = source {
|
||||
sql += " FROM " + source.sourceSQL(&arguments)
|
||||
sql += try " FROM " + source.sourceSQL(db, &arguments)
|
||||
}
|
||||
|
||||
if let whereExpression = whereExpression {
|
||||
if let whereExpression = try wherePromise.resolve(db) {
|
||||
sql += " WHERE " + whereExpression.expressionSQL(&arguments)
|
||||
}
|
||||
|
||||
@@ -147,7 +171,7 @@ struct QueryInterfaceSelectQueryDefinition {
|
||||
extension QueryInterfaceSelectQueryDefinition : Request {
|
||||
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
var arguments: StatementArguments? = StatementArguments()
|
||||
let sql = self.sql(&arguments)
|
||||
let sql = try self.sql(db, &arguments)
|
||||
let statement = try db.makeSelectStatement(sql)
|
||||
try statement.setArgumentsWithValidation(arguments!)
|
||||
return (statement, nil)
|
||||
@@ -157,6 +181,42 @@ extension QueryInterfaceSelectQueryDefinition : Request {
|
||||
return try Int.fetchOne(db, countQuery)!
|
||||
}
|
||||
|
||||
/// The database region that the request looks into.
|
||||
func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
let (statement, _) = try prepare(db)
|
||||
let region = statement.fetchedRegion
|
||||
|
||||
// Can we intersect the region with rowIds?
|
||||
//
|
||||
// Give up unless request feeds from a single database table
|
||||
guard let source = source else {
|
||||
return region
|
||||
}
|
||||
guard case .table(name: let tableName, alias: _) = source else {
|
||||
return region
|
||||
}
|
||||
|
||||
// Give up unless primary key is rowId
|
||||
let primaryKeyInfo = try db.primaryKey(tableName)
|
||||
guard primaryKeyInfo.isRowID else {
|
||||
return region
|
||||
}
|
||||
|
||||
// Give up unless there is a where clause
|
||||
guard let whereExpression = try wherePromise.resolve(db) else {
|
||||
return region
|
||||
}
|
||||
|
||||
// The whereExpression knows better
|
||||
guard let rowIds = whereExpression.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else {
|
||||
return region
|
||||
}
|
||||
|
||||
// Database regions are case-insensitive: use the canonical table name
|
||||
let canonicalTableName = try db.canonicalName(table: tableName)
|
||||
return region.tableIntersection(canonicalTableName, rowIds: rowIds)
|
||||
}
|
||||
|
||||
private var countQuery: QueryInterfaceSelectQueryDefinition {
|
||||
guard groupByExpressions.isEmpty && limit == nil else {
|
||||
// SELECT ... GROUP BY ...
|
||||
@@ -206,7 +266,7 @@ indirect enum SQLSource {
|
||||
case table(name: String, alias: String?)
|
||||
case query(query: QueryInterfaceSelectQueryDefinition, alias: String?)
|
||||
|
||||
func sourceSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
func sourceSQL(_ db: Database, _ arguments: inout StatementArguments?) throws -> String {
|
||||
switch self {
|
||||
case .table(let table, let alias):
|
||||
if let alias = alias {
|
||||
@@ -216,9 +276,9 @@ indirect enum SQLSource {
|
||||
}
|
||||
case .query(let query, let alias):
|
||||
if let alias = alias {
|
||||
return "(" + query.sql(&arguments) + ") AS " + alias.quotedDatabaseIdentifier
|
||||
return try "(" + query.sql(db, &arguments) + ") AS " + alias.quotedDatabaseIdentifier
|
||||
} else {
|
||||
return "(" + query.sql(&arguments) + ")"
|
||||
return try "(" + query.sql(db, &arguments) + ")"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,11 +51,15 @@ public struct SQLCollatedExpression {
|
||||
extension SQLCollatedExpression : SQLOrderingTerm {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public var reversed: SQLOrderingTerm {
|
||||
return desc
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return sqlExpression.orderingTermSQL(&arguments)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// SQLCollection is the protocol for types that can be checked for inclusion.
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol SQLCollection {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
/// like Column.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol SQLExpressible {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -27,6 +29,8 @@ public protocol SQLExpressible {
|
||||
/// and it adopts SQLSpecificExpressible.
|
||||
///
|
||||
/// On the other side, Int adopts SQLExpressible (via DatabaseValueConvertible).
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol SQLSpecificExpressible : SQLExpressible {
|
||||
// SQLExpressible can be adopted by Swift standard types, and user
|
||||
// types, through the DatabaseValueConvertible protocol which inherits
|
||||
@@ -53,11 +57,15 @@ public protocol SQLSpecificExpressible : SQLExpressible {
|
||||
extension SQLExpressible where Self: SQLOrderingTerm {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public var reversed: SQLOrderingTerm {
|
||||
return SQLOrdering.desc(sqlExpression)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return sqlExpression.expressionSQL(&arguments)
|
||||
}
|
||||
@@ -68,17 +76,30 @@ extension SQLExpressible where Self: SQLOrderingTerm {
|
||||
extension SQLExpressible where Self: SQLSelectable {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func resultColumnSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return sqlExpression.expressionSQL(&arguments)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func countedSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return sqlExpression.expressionSQL(&arguments)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func count(distinct: Bool) -> SQLCount? {
|
||||
return sqlExpression.count(distinct: distinct)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func columnCount(_ db: Database) throws -> Int {
|
||||
return 1
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@ extension SQLExpression {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Converts an expression to an SQLExpressionLiteral
|
||||
///
|
||||
/// :nodoc:
|
||||
public var literal: SQLExpressionLiteral {
|
||||
var arguments: StatementArguments? = []
|
||||
let sql = expressionSQL(&arguments)
|
||||
@@ -57,6 +59,8 @@ public struct SQLExpressionLiteral : SQLExpression {
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
if let literalArguments = self.arguments {
|
||||
guard arguments != nil else {
|
||||
@@ -68,6 +72,13 @@ public struct SQLExpressionLiteral : SQLExpression {
|
||||
}
|
||||
return sql
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionLiteral {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionUnary
|
||||
@@ -75,6 +86,8 @@ public struct SQLExpressionLiteral : SQLExpression {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// SQLUnaryOperator is a SQLite unary operator.
|
||||
///
|
||||
/// :nodoc:
|
||||
public struct SQLUnaryOperator : Hashable {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -97,11 +110,15 @@ public struct SQLUnaryOperator : Hashable {
|
||||
}
|
||||
|
||||
/// The hash value
|
||||
///
|
||||
/// :nodoc:
|
||||
public var hashValue: Int {
|
||||
return sql.hashValue
|
||||
}
|
||||
|
||||
/// Equality operator
|
||||
///
|
||||
/// :nodoc:
|
||||
public static func == (lhs: SQLUnaryOperator, rhs: SQLUnaryOperator) -> Bool {
|
||||
return lhs.sql == rhs.sql
|
||||
}
|
||||
@@ -113,6 +130,8 @@ public struct SQLUnaryOperator : Hashable {
|
||||
/// an operand expression.
|
||||
///
|
||||
/// SQLExpressionUnary(.not, Column("favorite"))
|
||||
///
|
||||
/// :nodoc:
|
||||
public struct SQLExpressionUnary : SQLExpression {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -137,9 +156,18 @@ public struct SQLExpressionUnary : SQLExpression {
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return op.sql + (op.needsRightSpace ? " " : "") + expression.expressionSQL(&arguments)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionUnary {
|
||||
return SQLExpressionUnary(op, expression.qualified(by: qualifier))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionBinary
|
||||
@@ -147,6 +175,8 @@ public struct SQLExpressionUnary : SQLExpression {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// SQLBinaryOperator is a SQLite binary operator.
|
||||
///
|
||||
/// :nodoc:
|
||||
public struct SQLBinaryOperator : Hashable {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -223,6 +253,8 @@ public struct SQLBinaryOperator : Hashable {
|
||||
/// binary operator.
|
||||
///
|
||||
/// SQLExpressionBinary(.multiply, Column("length"), Column("width"))
|
||||
///
|
||||
/// :nodoc:
|
||||
public struct SQLExpressionBinary : SQLExpression {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -265,6 +297,63 @@ public struct SQLExpressionBinary : SQLExpression {
|
||||
return SQLExpressionNot(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
|
||||
switch op {
|
||||
case .equal, .is:
|
||||
// Look for `id == 1` or `id IS 1`?
|
||||
switch (lhs, rhs) {
|
||||
case (let column as Column, let dbValue as DatabaseValue),
|
||||
(let dbValue as DatabaseValue, let column as Column):
|
||||
// Look for `id == 1`, `rowid == 1`, `1 == id`, `1 == rowid`
|
||||
|
||||
var rowIdNames = [Column.rowID.name.lowercased()]
|
||||
if let rowIdName = rowIdName {
|
||||
rowIdNames.append(rowIdName.lowercased())
|
||||
}
|
||||
|
||||
guard rowIdNames.contains(column.name.lowercased()) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
if let rowId = Int64.fromDatabaseValue(dbValue) {
|
||||
return [rowId]
|
||||
} else {
|
||||
return []
|
||||
}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
|
||||
case .and:
|
||||
let lids = lhs.matchedRowIds(rowIdName: rowIdName)
|
||||
let rids = rhs.matchedRowIds(rowIdName: rowIdName)
|
||||
switch (lids, rids) {
|
||||
case (nil, nil): return nil
|
||||
case let (ids?, nil), let (nil, ids?): return ids
|
||||
case let (lids?, rids?): return lids.intersection(rids)
|
||||
}
|
||||
|
||||
case .or:
|
||||
let lids = lhs.matchedRowIds(rowIdName: rowIdName)
|
||||
let rids = rhs.matchedRowIds(rowIdName: rowIdName)
|
||||
switch (lids, rids) {
|
||||
case let (lids?, rids?): return lids.union(rids)
|
||||
default: return nil
|
||||
}
|
||||
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionBinary {
|
||||
return SQLExpressionBinary(op, lhs.qualified(by: qualifier), rhs.qualified(by: qualifier))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionContains
|
||||
@@ -296,6 +385,38 @@ struct SQLExpressionContains : SQLExpression {
|
||||
var negated: SQLExpression {
|
||||
return SQLExpressionContains(expression, collection, negated: !isNegated)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
|
||||
// Look for `id IN (1, 2, 3)`
|
||||
guard let column = expression as? Column,
|
||||
let array = collection as? SQLExpressionsArray else
|
||||
{
|
||||
return nil
|
||||
}
|
||||
|
||||
var rowIdNames = [Column.rowID.name.lowercased()]
|
||||
if let rowIdName = rowIdName {
|
||||
rowIdNames.append(rowIdName.lowercased())
|
||||
}
|
||||
|
||||
guard rowIdNames.contains(column.name.lowercased()) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
var rowIDs: Set<Int64> = []
|
||||
for expression in array.expressions {
|
||||
guard let dbValue = expression as? DatabaseValue else { return nil }
|
||||
if let rowId = Int64.fromDatabaseValue(dbValue) {
|
||||
rowIDs.insert(rowId)
|
||||
}
|
||||
}
|
||||
return rowIDs
|
||||
}
|
||||
|
||||
func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionContains {
|
||||
return SQLExpressionContains(expression.qualified(by: qualifier), collection, negated: isNegated)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionBetween
|
||||
@@ -331,6 +452,14 @@ struct SQLExpressionBetween : SQLExpression {
|
||||
var negated: SQLExpression {
|
||||
return SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated)
|
||||
}
|
||||
|
||||
func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionBetween {
|
||||
return SQLExpressionBetween(
|
||||
expression.qualified(by: qualifier),
|
||||
lowerBound.qualified(by: qualifier),
|
||||
upperBound.qualified(by: qualifier),
|
||||
negated: isNegated)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionFunction
|
||||
@@ -342,6 +471,8 @@ public struct SQLFunctionName : Hashable {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The SQL function name
|
||||
///
|
||||
/// :nodoc:
|
||||
public let sql: String
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
@@ -349,16 +480,22 @@ public struct SQLFunctionName : Hashable {
|
||||
/// Creates a function name
|
||||
///
|
||||
/// SQLFunctionName("ABS")
|
||||
///
|
||||
/// :nodoc:
|
||||
public init(_ sql: String) {
|
||||
self.sql = sql
|
||||
}
|
||||
|
||||
/// The hash value
|
||||
///
|
||||
/// :nodoc:
|
||||
public var hashValue: Int {
|
||||
return sql.hashValue
|
||||
}
|
||||
|
||||
/// Equality operator
|
||||
///
|
||||
/// :nodoc:
|
||||
public static func == (lhs: SQLFunctionName, rhs: SQLFunctionName) -> Bool {
|
||||
return lhs.sql == rhs.sql
|
||||
}
|
||||
@@ -370,6 +507,8 @@ public struct SQLFunctionName : Hashable {
|
||||
///
|
||||
/// // ABS(-1)
|
||||
/// SQLExpressionFunction(.abs, [-1.databaseValue])
|
||||
///
|
||||
/// :nodoc:
|
||||
public struct SQLExpressionFunction : SQLExpression {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -406,6 +545,13 @@ public struct SQLExpressionFunction : SQLExpression {
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return functionName.sql + "(" + (self.arguments.map { $0.expressionSQL(&arguments) } as [String]).joined(separator: ", ") + ")"
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionFunction {
|
||||
return SQLExpressionFunction(functionName, arguments: arguments.map { $0.qualified(by: qualifier) })
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionCount
|
||||
@@ -425,6 +571,10 @@ struct SQLExpressionCount : SQLExpression {
|
||||
func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return "COUNT(" + counted.countedSQL(&arguments) + ")"
|
||||
}
|
||||
|
||||
func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionCount {
|
||||
return SQLExpressionCount(counted.qualified(by: qualifier))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionCountDistinct
|
||||
@@ -443,6 +593,10 @@ struct SQLExpressionCountDistinct : SQLExpression {
|
||||
func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return "COUNT(DISTINCT " + counted.expressionSQL(&arguments) + ")"
|
||||
}
|
||||
|
||||
func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionCountDistinct {
|
||||
return SQLExpressionCountDistinct(counted.qualified(by: qualifier))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionCollate
|
||||
@@ -462,11 +616,14 @@ struct SQLExpressionCollate : SQLExpression {
|
||||
|
||||
func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
let sql = expression.expressionSQL(&arguments)
|
||||
let chars = sql.characters
|
||||
if chars.last! == ")" {
|
||||
return String(chars.prefix(upTo: chars.index(chars.endIndex, offsetBy: -1))) + " COLLATE " + collationName.rawValue + ")"
|
||||
if sql.last! == ")" {
|
||||
return String(sql.prefix(upTo: sql.index(sql.endIndex, offsetBy: -1))) + " COLLATE " + collationName.rawValue + ")"
|
||||
} else {
|
||||
return sql + " COLLATE " + collationName.rawValue
|
||||
}
|
||||
}
|
||||
|
||||
func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionCollate {
|
||||
return SQLExpressionCollate(expression.qualified(by: qualifier), collationName: collationName)
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,8 @@
|
||||
/// - SQLExpressionExists
|
||||
/// - SQLExpressionFunction
|
||||
/// - SQLExpressionCollate
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderingTerm {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
@@ -53,6 +55,11 @@ public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderi
|
||||
/// let expression = [1,2,3].contains(Column("id")) // id IN (1,2,3)
|
||||
/// expression.negated // id NOT IN (1,2,3)
|
||||
var negated: SQLExpression { get }
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns the rowIds matched by the expression.
|
||||
func matchedRowIds(rowIdName: String?) -> Set<Int64>? // TODO: this method should take SQLTableQualifier in account
|
||||
}
|
||||
|
||||
extension SQLExpression {
|
||||
@@ -64,9 +71,19 @@ extension SQLExpression {
|
||||
/// let column = Column("favorite")
|
||||
/// column.negated // NOT favorite
|
||||
///
|
||||
/// :nodoc:
|
||||
public var negated: SQLExpression {
|
||||
return SQLExpressionNot(self)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The default implementation returns nil
|
||||
///
|
||||
/// :nodoc:
|
||||
public func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// SQLExpression: SQLExpressible
|
||||
@@ -74,6 +91,8 @@ extension SQLExpression {
|
||||
extension SQLExpression {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public var sqlExpression: SQLExpression {
|
||||
return self
|
||||
}
|
||||
@@ -84,6 +103,8 @@ extension SQLExpression {
|
||||
extension SQLExpression {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func count(distinct: Bool) -> SQLCount? {
|
||||
if distinct {
|
||||
// SELECT DISTINCT expr FROM tableName ...
|
||||
@@ -115,4 +136,8 @@ struct SQLExpressionNot : SQLExpression {
|
||||
var negated: SQLExpression {
|
||||
return expression
|
||||
}
|
||||
|
||||
func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionNot {
|
||||
return SQLExpressionNot(expression.qualified(by: qualifier))
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@
|
||||
///
|
||||
/// The protocol for all types that can be used as an SQL ordering term, as
|
||||
/// described at https://www.sqlite.org/syntax/ordering-term.html
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol SQLOrderingTerm {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
|
||||
@@ -15,33 +15,75 @@
|
||||
/// // SELECT *, rowid FROM players
|
||||
/// let request = Player.all()
|
||||
public struct AllColumns {
|
||||
private var qualifier: SQLTableQualifier?
|
||||
|
||||
///
|
||||
public init() { }
|
||||
}
|
||||
|
||||
extension AllColumns : SQLSelectable {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func resultColumnSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
if let qualifierName = qualifier?.name {
|
||||
return qualifierName.quotedDatabaseIdentifier + ".*"
|
||||
}
|
||||
return "*"
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func countedSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
guard qualifier == nil else {
|
||||
// SELECT COUNT(t.*) is invalid SQL
|
||||
fatalError("Not implemented, or invalid query")
|
||||
}
|
||||
return "*"
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func count(distinct: Bool) -> SQLCount? {
|
||||
// SELECT DISTINCT * FROM tableName ...
|
||||
guard !distinct else {
|
||||
return nil
|
||||
}
|
||||
|
||||
guard qualifier == nil else {
|
||||
return nil
|
||||
}
|
||||
|
||||
// SELECT * FROM tableName ...
|
||||
// ->
|
||||
// SELECT COUNT(*) FROM tableName ...
|
||||
return .all
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func qualified(by qualifier: SQLTableQualifier) -> AllColumns {
|
||||
if self.qualifier != nil {
|
||||
// Never requalify
|
||||
return self
|
||||
}
|
||||
var allColumns = AllColumns()
|
||||
allColumns.qualifier = qualifier
|
||||
return allColumns
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func columnCount(_ db: Database) throws -> Int {
|
||||
guard let qualifier = qualifier else {
|
||||
fatalError("Can't compute number of columns without a qualifier")
|
||||
}
|
||||
return try db.columns(in: qualifier.tableName).count
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -67,4 +109,12 @@ struct SQLAliasedExpression : SQLSelectable {
|
||||
func count(distinct: Bool) -> SQLCount? {
|
||||
return expression.count(distinct: distinct)
|
||||
}
|
||||
|
||||
func qualified(by qualifier: SQLTableQualifier) -> SQLAliasedExpression {
|
||||
return SQLAliasedExpression(expression.qualified(by: qualifier), alias: alias)
|
||||
}
|
||||
|
||||
func columnCount(_ db: Database) throws -> Int {
|
||||
return 1
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@
|
||||
///
|
||||
/// SQLSelectable is the protocol for types that can be selected, as
|
||||
/// described at https://www.sqlite.org/syntax/result-column.html
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol SQLSelectable {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
func resultColumnSQL(_ arguments: inout StatementArguments?) -> String
|
||||
@@ -13,11 +15,36 @@ public protocol SQLSelectable {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
func count(distinct: Bool) -> SQLCount?
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
func columnCount(_ db: Database) throws -> Int
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
func qualified(by qualifier: SQLTableQualifier) -> Self
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public class SQLTableQualifier {
|
||||
var tableName: String
|
||||
private var alias: String?
|
||||
|
||||
init(tableName: String, alias: String?) {
|
||||
self.tableName = tableName
|
||||
self.alias = alias
|
||||
}
|
||||
|
||||
var name: String? {
|
||||
return alias
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Counting
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public enum SQLCount {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
|
||||
@@ -587,7 +587,7 @@ extension SQLBinaryOperator {
|
||||
|
||||
extension SQLUnaryOperator {
|
||||
/// The `-` unary operator
|
||||
public static let minus = SQLUnaryOperator("-", needsRightSpace: false)
|
||||
static let minus = SQLUnaryOperator("-", needsRightSpace: false)
|
||||
}
|
||||
|
||||
/// An SQL arithmetic multiplication.
|
||||
|
||||
@@ -19,7 +19,9 @@ extension Database {
|
||||
/// - parameters:
|
||||
/// - name: The table name.
|
||||
/// - temporary: If true, creates a temporary table.
|
||||
/// - ifNotExists: If false, no error is thrown if table already exists.
|
||||
/// - ifNotExists: If false (the default), an error is thrown if the
|
||||
/// table already exists. Otherwise, the table is created unless it
|
||||
/// already exists.
|
||||
/// - withoutRowID: If true, uses WITHOUT ROWID optimization.
|
||||
/// - body: A closure that defines table columns and constraints.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
@@ -46,7 +48,9 @@ extension Database {
|
||||
/// - parameters:
|
||||
/// - name: The table name.
|
||||
/// - temporary: If true, creates a temporary table.
|
||||
/// - ifNotExists: If false, no error is thrown if table already exists.
|
||||
/// - ifNotExists: If false (the default), an error is thrown if the
|
||||
/// table already exists. Otherwise, the table is created unless it
|
||||
/// already exists.
|
||||
/// - withoutRowID: If true, uses WITHOUT ROWID optimization.
|
||||
/// - body: A closure that defines table columns and constraints.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
@@ -75,7 +79,9 @@ extension Database {
|
||||
/// - parameters:
|
||||
/// - name: The table name.
|
||||
/// - temporary: If true, creates a temporary table.
|
||||
/// - ifNotExists: If false, no error is thrown if table already exists.
|
||||
/// - ifNotExists: If false (the default), an error is thrown if the
|
||||
/// table already exists. Otherwise, the table is created unless it
|
||||
/// already exists.
|
||||
/// - body: A closure that defines table columns and constraints.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, body: (TableDefinition) -> Void) throws {
|
||||
@@ -495,7 +501,7 @@ public final class TableAlteration {
|
||||
/// - returns: An ColumnDefinition that allows you to refine the
|
||||
/// column definition.
|
||||
@discardableResult
|
||||
public func add(column name: String, _ type: Database.ColumnType) -> ColumnDefinition {
|
||||
public func add(column name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition {
|
||||
let column = ColumnDefinition(name: name, type: type)
|
||||
addedColumns.append(column)
|
||||
return column
|
||||
|
||||
@@ -39,7 +39,7 @@ public protocol VirtualTableModule {
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Database Schema: Virtual Table
|
||||
// MARK: - Database Schema
|
||||
|
||||
/// Creates a virtual database table.
|
||||
///
|
||||
@@ -49,7 +49,9 @@ extension Database {
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The table name.
|
||||
/// - ifNotExists: If false, no error is thrown if table already exists.
|
||||
/// - ifNotExists: If false (the default), an error is thrown if the
|
||||
/// table already exists. Otherwise, the table is created unless it
|
||||
/// already exists.
|
||||
/// - module: The name of an SQLite virtual table module.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func create(virtualTable name: String, ifNotExists: Bool = false, using module: String) throws {
|
||||
@@ -88,7 +90,9 @@ extension Database {
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The table name.
|
||||
/// - ifNotExists: If false, no error is thrown if table already exists.
|
||||
/// - ifNotExists: If false (the default), an error is thrown if the
|
||||
/// table already exists. Otherwise, the table is created unless it
|
||||
/// already exists.
|
||||
/// - module: a VirtualTableModule
|
||||
/// - body: An optional closure that defines the virtual table.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
|
||||
@@ -104,8 +104,8 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
{
|
||||
self.itemsAreIdenticalFactory = itemsAreIdenticalFactory
|
||||
self.request = request
|
||||
(self.selectionInfo, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
|
||||
try FetchedRecordsController.fetchSelectionInfoAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory)
|
||||
(self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
|
||||
try FetchedRecordsController.fetchRegionAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory)
|
||||
}
|
||||
self.databaseWriter = databaseWriter
|
||||
self.queue = queue
|
||||
@@ -133,7 +133,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
let initialItems = try Item<Record>.fetchAll(db, request)
|
||||
fetchedItems = initialItems
|
||||
if let fetchAndNotifyChanges = fetchAndNotifyChanges {
|
||||
let observer = FetchedRecordsObserver(selectionInfo: self.selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges)
|
||||
let observer = FetchedRecordsObserver(region: self.region, fetchAndNotifyChanges: fetchAndNotifyChanges)
|
||||
self.observer = observer
|
||||
observer.items = initialItems
|
||||
db.add(transactionObserver: observer)
|
||||
@@ -162,8 +162,8 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
/// main queue unless stated otherwise in the controller's initializer).
|
||||
public func setRequest<Request>(_ request: Request) throws where Request: TypedRequest, Request.RowDecoder == Record {
|
||||
self.request = request
|
||||
(self.selectionInfo, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
|
||||
try FetchedRecordsController.fetchSelectionInfoAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory)
|
||||
(self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
|
||||
try FetchedRecordsController.fetchRegionAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory)
|
||||
}
|
||||
|
||||
// No observer: don't look for changes
|
||||
@@ -179,7 +179,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
// and notify eventual changes
|
||||
let initialItems = fetchedItems
|
||||
databaseWriter.write { db in
|
||||
let observer = FetchedRecordsObserver(selectionInfo: selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges)
|
||||
let observer = FetchedRecordsObserver(region: region, fetchAndNotifyChanges: fetchAndNotifyChanges)
|
||||
self.observer = observer
|
||||
observer.items = initialItems
|
||||
db.add(transactionObserver: observer)
|
||||
@@ -299,7 +299,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
onChange: onChange,
|
||||
didChange: didChange,
|
||||
didProcessTransaction: didProcessTransaction)
|
||||
let observer = FetchedRecordsObserver(selectionInfo: selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges)
|
||||
let observer = FetchedRecordsObserver(region: region, fetchAndNotifyChanges: fetchAndNotifyChanges)
|
||||
self.observer = observer
|
||||
if let initialItems = initialItems {
|
||||
observer.items = initialItems
|
||||
@@ -378,8 +378,8 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
/// The request
|
||||
fileprivate var request: Request
|
||||
|
||||
/// The observed selection info
|
||||
private var selectionInfo : SelectStatement.SelectionInfo
|
||||
/// The observed database region
|
||||
private var region : DatabaseRegion
|
||||
|
||||
/// The eventual current database observer
|
||||
private var observer: FetchedRecordsObserver<Record>?
|
||||
@@ -387,16 +387,15 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
/// The eventual error handler
|
||||
fileprivate var errorHandler: ((FetchedRecordsController<Record>, Error) -> ())?
|
||||
|
||||
private static func fetchSelectionInfoAndComparator(
|
||||
private static func fetchRegionAndComparator(
|
||||
_ db: Database,
|
||||
request: Request,
|
||||
itemsAreIdenticalFactory: ItemComparatorFactory<Record>) throws
|
||||
-> (SelectStatement.SelectionInfo, ItemComparator<Record>)
|
||||
-> (DatabaseRegion, ItemComparator<Record>)
|
||||
{
|
||||
let (statement, _) = try request.prepare(db)
|
||||
let selectionInfo = statement.selectionInfo
|
||||
let region = try request.fetchedRegion(db)
|
||||
let itemsAreIdentical = try itemsAreIdenticalFactory(db)
|
||||
return (selectionInfo, itemsAreIdentical)
|
||||
return (region, itemsAreIdentical)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -522,15 +521,15 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
|
||||
var needsComputeChanges: Bool
|
||||
var items: [Item<Record>]! // ought to be not nil when observer has started tracking transactions
|
||||
let queue: DispatchQueue // protects items
|
||||
let selectionInfo: SelectStatement.SelectionInfo
|
||||
let region: DatabaseRegion
|
||||
var fetchAndNotifyChanges: (FetchedRecordsObserver<Record>) -> ()
|
||||
|
||||
init(selectionInfo: SelectStatement.SelectionInfo, fetchAndNotifyChanges: @escaping (FetchedRecordsObserver<Record>) -> ()) {
|
||||
init(region: DatabaseRegion, fetchAndNotifyChanges: @escaping (FetchedRecordsObserver<Record>) -> ()) {
|
||||
self.isValid = true
|
||||
self.items = nil
|
||||
self.needsComputeChanges = false
|
||||
self.queue = DispatchQueue(label: "GRDB.FetchedRecordsObserver")
|
||||
self.selectionInfo = selectionInfo
|
||||
self.region = region
|
||||
self.fetchAndNotifyChanges = fetchAndNotifyChanges
|
||||
}
|
||||
|
||||
@@ -539,22 +538,17 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
|
||||
}
|
||||
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
return eventKind.impacts(selectionInfo)
|
||||
return region.isModified(byEventsOfKind: eventKind)
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
/// Part of the TransactionObserverType protocol
|
||||
func databaseWillChange(with event: DatabasePreUpdateEvent) { }
|
||||
#endif
|
||||
|
||||
/// Part of the TransactionObserverType protocol
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
needsComputeChanges = true
|
||||
if region.isModified(by: event) {
|
||||
needsComputeChanges = true
|
||||
stopObservingDatabaseChangesUntilNextTransaction()
|
||||
}
|
||||
}
|
||||
|
||||
/// Part of the TransactionObserverType protocol
|
||||
func databaseWillCommit() throws { }
|
||||
|
||||
/// Part of the TransactionObserverType protocol
|
||||
func databaseDidRollback(_ db: Database) {
|
||||
needsComputeChanges = false
|
||||
@@ -1004,8 +998,6 @@ public enum FetchedRecordChange {
|
||||
}
|
||||
|
||||
extension FetchedRecordChange: CustomStringConvertible {
|
||||
|
||||
/// A textual representation of `self`.
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .insertion(let indexPath):
|
||||
|
||||
@@ -28,7 +28,6 @@ private struct PersistableKeyedEncodingContainer<Key: CodingKey> : KeyedEncoding
|
||||
mutating func encode(_ value: Float, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: Double, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: String, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encodeNil(forKey key: Key) throws { encode(nil, key.stringValue) }
|
||||
|
||||
/// Encodes the given value for the given key.
|
||||
///
|
||||
@@ -45,6 +44,24 @@ private struct PersistableKeyedEncodingContainer<Key: CodingKey> : KeyedEncoding
|
||||
}
|
||||
}
|
||||
|
||||
// Provide explicit encoding of optionals, because default implementation does not encode nil values.
|
||||
mutating func encodeNil(forKey key: Key) throws { encode(nil, key.stringValue) }
|
||||
mutating func encodeIfPresent(_ value: Bool?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: Int?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: Int8?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: Int16?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: Int32?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: Int64?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: UInt?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: UInt8?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: UInt16?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: UInt32?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: UInt64?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: Float?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: Double?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: String?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent<T>(_ value: T?, forKey key: Key) throws where T : Encodable { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
|
||||
/// Stores a keyed encoding container for the given key and returns it.
|
||||
///
|
||||
/// - parameter keyType: The key type to use for the container.
|
||||
@@ -189,6 +206,8 @@ extension MutablePersistable where Self: Encodable {
|
||||
try! self.encode(to: encoder)
|
||||
}
|
||||
}
|
||||
encode { (value, key) in container[key] = value }
|
||||
encode { (value, key) in
|
||||
container[key] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,15 +13,16 @@ extension Database.ConflictResolution {
|
||||
// MARK: - PersistenceError
|
||||
|
||||
/// An error thrown by a type that adopts Persistable.
|
||||
public enum PersistenceError: Error {
|
||||
public enum PersistenceError: Error, CustomStringConvertible {
|
||||
|
||||
/// Thrown by MutablePersistable.update() when no matching row could be
|
||||
/// found in the database.
|
||||
case recordNotFound(MutablePersistable)
|
||||
}
|
||||
|
||||
extension PersistenceError : CustomStringConvertible {
|
||||
/// A textual representation of `self`.
|
||||
// CustomStringConvertible
|
||||
extension PersistenceError {
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .recordNotFound(let persistable):
|
||||
@@ -97,6 +98,8 @@ public struct PersistenceContainer {
|
||||
|
||||
/// Accesses the value associated with the given column, in a
|
||||
/// case-insensitive fashion.
|
||||
///
|
||||
/// :nodoc:
|
||||
subscript(caseInsensitive column: String) -> DatabaseValueConvertible? {
|
||||
get {
|
||||
if let value = storage[column] {
|
||||
@@ -386,6 +389,30 @@ extension MutablePersistable {
|
||||
try update(db, columns: Set(columns.map { $0.name }))
|
||||
}
|
||||
|
||||
/// If the record has differences from the other record, executes an UPDATE
|
||||
/// statement so that those changes and only those changes are saved in
|
||||
/// the database.
|
||||
///
|
||||
/// This method is guaranteed to have saved the eventual changes in the
|
||||
/// database if it returns without error.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter columns: The columns to update.
|
||||
/// - returns: Whether the record had changes.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// PersistenceError.recordNotFound is thrown if the primary key does not
|
||||
/// match any row in the database and record could not be updated.
|
||||
@discardableResult
|
||||
public func updateChanges(_ db: Database, from record: MutablePersistable) throws -> Bool {
|
||||
let changedColumns = Set(databaseChanges(from: record).keys)
|
||||
if changedColumns.isEmpty {
|
||||
return false
|
||||
} else {
|
||||
try update(db, columns: changedColumns)
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes an INSERT or an UPDATE statement so that `self` is saved in
|
||||
/// the database.
|
||||
///
|
||||
@@ -410,6 +437,43 @@ extension MutablePersistable {
|
||||
return try performExists(db)
|
||||
}
|
||||
|
||||
// MARK: - Changes Tracking
|
||||
|
||||
/// Returns a boolean indicating whether this record and the other record
|
||||
/// have the same database representation.
|
||||
public func databaseEqual(_ record: Self) -> Bool {
|
||||
return databaseChangesIterator(from: record).next() == nil
|
||||
}
|
||||
|
||||
/// A dictionary of values changed from the other record.
|
||||
///
|
||||
/// Its keys are column names. Its values come from the other record.
|
||||
///
|
||||
/// Note that this method is not symmetrical, not only in terms of values,
|
||||
/// but also in terms of columns. When the two records don't define the
|
||||
/// same set of columns in their `encode(to:)` method, only the columns
|
||||
/// defined by the receiver record are considered.
|
||||
public func databaseChanges(from record: MutablePersistable) -> [String: DatabaseValue] {
|
||||
return Dictionary(uniqueKeysWithValues: databaseChangesIterator(from: record))
|
||||
}
|
||||
|
||||
fileprivate func databaseChangesIterator(from record: MutablePersistable) -> AnyIterator<(String, DatabaseValue)> {
|
||||
let oldContainer = PersistenceContainer(record)
|
||||
var newValueIterator = PersistenceContainer(self).makeIterator()
|
||||
return AnyIterator {
|
||||
// Loop until we find a change, or exhaust columns:
|
||||
while let (column, newValue) = newValueIterator.next() {
|
||||
let oldValue = oldContainer[caseInsensitive: column]
|
||||
let oldDbValue = oldValue?.databaseValue ?? .null
|
||||
let newDbValue = newValue?.databaseValue ?? .null
|
||||
if newDbValue != oldDbValue {
|
||||
return (column, oldDbValue)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CRUD Internals
|
||||
|
||||
/// Return true if record has a non-null primary key
|
||||
@@ -573,7 +637,7 @@ extension MutablePersistable {
|
||||
// Avoid hitting the database
|
||||
return 0
|
||||
}
|
||||
return try filter(db, keys: keys).deleteAll(db)
|
||||
return try filter(keys: keys).deleteAll(db)
|
||||
}
|
||||
|
||||
/// Delete a record, identified by its primary key; returns whether a
|
||||
@@ -624,7 +688,7 @@ extension MutablePersistable {
|
||||
// Avoid hitting the database
|
||||
return 0
|
||||
}
|
||||
return try filter(db, keys: keys).deleteAll(db)
|
||||
return try filter(keys: keys).deleteAll(db)
|
||||
}
|
||||
|
||||
/// Delete a record, identified by a unique key (the primary key or any key
|
||||
@@ -824,7 +888,7 @@ final class DAO {
|
||||
onConflict: onConflict,
|
||||
tableName: databaseTableName,
|
||||
insertedColumns: persistenceContainer.columns)
|
||||
let statement = try db.updateStatement(query.sql, fromCache: .grdb)
|
||||
let statement = try db.internalCachedUpdateStatement(query.sql)
|
||||
statement.unsafeSetArguments(StatementArguments(persistenceContainer.values))
|
||||
return statement
|
||||
}
|
||||
@@ -870,7 +934,7 @@ final class DAO {
|
||||
tableName: databaseTableName,
|
||||
updatedColumns: updatedColumns,
|
||||
conditionColumns: primaryKeyColumns)
|
||||
let statement = try db.updateStatement(query.sql, fromCache: .grdb)
|
||||
let statement = try db.internalCachedUpdateStatement(query.sql)
|
||||
statement.unsafeSetArguments(StatementArguments(updatedValues + primaryKeyValues))
|
||||
return statement
|
||||
}
|
||||
@@ -887,7 +951,7 @@ final class DAO {
|
||||
let query = DeleteQuery(
|
||||
tableName: databaseTableName,
|
||||
conditionColumns: primaryKeyColumns)
|
||||
let statement = try db.updateStatement(query.sql, fromCache: .grdb)
|
||||
let statement = try db.internalCachedUpdateStatement(query.sql)
|
||||
statement.unsafeSetArguments(StatementArguments(primaryKeyValues))
|
||||
return statement
|
||||
}
|
||||
@@ -904,7 +968,7 @@ final class DAO {
|
||||
let query = ExistsQuery(
|
||||
tableName: databaseTableName,
|
||||
conditionColumns: primaryKeyColumns)
|
||||
let statement = try db.selectStatement(query.sql, fromCache: .grdb)
|
||||
let statement = try db.internalCachedSelectStatement(query.sql)
|
||||
statement.unsafeSetArguments(StatementArguments(primaryKeyValues))
|
||||
return statement
|
||||
}
|
||||
|
||||
+48
-41
@@ -13,7 +13,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
/// Creates a Record from a row.
|
||||
required public init(row: Row) {
|
||||
if row.isFetched {
|
||||
// Take care of the hasPersistentChangedValues flag.
|
||||
// Take care of the hasDatabaseChanges flag.
|
||||
//
|
||||
// Row may be a reused row which will turn invalid as soon as the
|
||||
// SQLite statement is iterated. We need to store an
|
||||
@@ -146,7 +146,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
/// `encode(to:)` method.
|
||||
///
|
||||
/// The eventual primary key is copied, as well as the
|
||||
/// `hasPersistentChangedValues` flag.
|
||||
/// `hasDatabaseChanges` flag.
|
||||
///
|
||||
/// - returns: A copy of self.
|
||||
open func copy() -> Self {
|
||||
@@ -181,11 +181,18 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
/// you may set it to true or false when you know better. Setting it to
|
||||
/// false does not prevent it from turning true on subsequent modifications
|
||||
/// of the record.
|
||||
public var hasPersistentChangedValues: Bool {
|
||||
get { return makePersistentChangedValuesIterator().next() != nil }
|
||||
public var hasDatabaseChanges: Bool {
|
||||
get { return databaseChangesIterator().next() != nil }
|
||||
set { referenceRow = newValue ? nil : Row(self) }
|
||||
}
|
||||
|
||||
/// Deprecated alias for `hasDatabaseChanges`.
|
||||
@available(*, deprecated, renamed: "hasDatabaseChanges")
|
||||
public var hasPersistentChangedValues: Bool {
|
||||
get { return hasDatabaseChanges }
|
||||
set { hasDatabaseChanges = newValue }
|
||||
}
|
||||
|
||||
/// A dictionary of changes that have not been saved.
|
||||
///
|
||||
/// Its keys are column names, and values the old values that have been
|
||||
@@ -194,30 +201,31 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
/// Unless the record has actually been fetched or saved, the old values
|
||||
/// are nil.
|
||||
///
|
||||
/// See `hasPersistentChangedValues` for more information.
|
||||
public var persistentChangedValues: [String: DatabaseValue?] {
|
||||
var persistentChangedValues: [String: DatabaseValue?] = [:]
|
||||
|
||||
for (key, value) in makePersistentChangedValuesIterator() {
|
||||
persistentChangedValues[key] = value
|
||||
}
|
||||
return persistentChangedValues
|
||||
/// See `hasDatabaseChanges` for more information.
|
||||
public var databaseChanges: [String: DatabaseValue?] {
|
||||
return Dictionary(uniqueKeysWithValues: databaseChangesIterator())
|
||||
}
|
||||
|
||||
// A change iterator that is used by both hasPersistentChangedValues and
|
||||
/// Deprecated alias for `databaseChanges`.
|
||||
@available(*, deprecated, renamed: "databaseChanges")
|
||||
public var persistentChangedValues: [String: DatabaseValue?] {
|
||||
return databaseChanges
|
||||
}
|
||||
|
||||
// A change iterator that is used by both hasDatabaseChanges and
|
||||
// persistentChangedValues properties.
|
||||
private func makePersistentChangedValuesIterator() -> AnyIterator<(column: String, old: DatabaseValue?)> {
|
||||
private func databaseChangesIterator() -> AnyIterator<(String, DatabaseValue?)> {
|
||||
let oldRow = referenceRow
|
||||
var newValueIterator = PersistenceContainer(self).makeIterator()
|
||||
return AnyIterator {
|
||||
// Loop until we find a change, or exhaust columns:
|
||||
while let (column, newValue) = newValueIterator.next() {
|
||||
let new = newValue?.databaseValue ?? .null
|
||||
guard let oldRow = oldRow, let old: DatabaseValue = oldRow[column] else {
|
||||
return (column: column, old: nil)
|
||||
let newDbValue = newValue?.databaseValue ?? .null
|
||||
guard let oldRow = oldRow, let oldDbValue: DatabaseValue = oldRow[column] else {
|
||||
return (column, nil)
|
||||
}
|
||||
if new != old {
|
||||
return (column: column, old: old)
|
||||
if newDbValue != oldDbValue {
|
||||
return (column, oldDbValue)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -225,7 +233,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
}
|
||||
|
||||
|
||||
/// Reference row for the *hasPersistentChangedValues* property.
|
||||
/// Reference row for the *hasDatabaseChanges* property.
|
||||
var referenceRow: Row?
|
||||
|
||||
|
||||
@@ -233,8 +241,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
|
||||
/// Executes an INSERT statement.
|
||||
///
|
||||
/// On success, this method sets the *hasPersistentChangedValues* flag
|
||||
/// to false.
|
||||
/// On success, this method sets the *hasDatabaseChanges* flag to false.
|
||||
///
|
||||
/// This method is guaranteed to have inserted a row in the database if it
|
||||
/// returns without error.
|
||||
@@ -257,20 +264,19 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
didInsert(with: rowID, for: rowIDColumn)
|
||||
|
||||
// Update persistenceContainer with inserted id, so that we can
|
||||
// set hasPersistentChangedValues to false:
|
||||
// set hasDatabaseChanges to false:
|
||||
if let rowIDColumn = rowIDColumn {
|
||||
persistenceContainer[caseInsensitive: rowIDColumn] = rowID
|
||||
}
|
||||
}
|
||||
|
||||
// Set hasPersistentChangedValues to false
|
||||
// Set hasDatabaseChanges to false
|
||||
referenceRow = Row(persistenceContainer)
|
||||
}
|
||||
|
||||
/// Executes an UPDATE statement.
|
||||
///
|
||||
/// On success, this method sets the *hasPersistentChangedValues* flag
|
||||
/// to false.
|
||||
/// On success, this method sets the *hasDatabaseChanges* flag to false.
|
||||
///
|
||||
/// This method is guaranteed to have updated a row in the database if it
|
||||
/// returns without error.
|
||||
@@ -284,7 +290,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
// The simplest code would be:
|
||||
//
|
||||
// try performUpdate(db, columns: columns)
|
||||
// hasPersistentChangedValues = false
|
||||
// hasDatabaseChanges = false
|
||||
//
|
||||
// But this would trigger two calls to `encode(to:)`.
|
||||
let dao = try DAO(db, self)
|
||||
@@ -297,30 +303,33 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
throw PersistenceError.recordNotFound(self)
|
||||
}
|
||||
|
||||
// Set hasPersistentChangedValues to false
|
||||
// Set hasDatabaseChanges to false
|
||||
referenceRow = Row(dao.persistenceContainer)
|
||||
}
|
||||
|
||||
/// If the record has been changed, executes an UPDATE statement so that
|
||||
/// those changes and only those changes are saved in the database.
|
||||
///
|
||||
/// On success, this method sets the *hasPersistentChangedValues* flag
|
||||
/// to false.
|
||||
/// On success, this method sets the *hasDatabaseChanges* flag to false.
|
||||
///
|
||||
/// This method is guaranteed to have saved the eventual changes in the
|
||||
/// database if it returns without error.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter columns: The columns to update.
|
||||
/// - returns: Whether the record had changes.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// PersistenceError.recordNotFound is thrown if the primary key does not
|
||||
/// match any row in the database and record could not be updated.
|
||||
final public func updateChanges(_ db: Database) throws {
|
||||
let changedColumns = Set(persistentChangedValues.keys)
|
||||
guard !changedColumns.isEmpty else {
|
||||
return
|
||||
@discardableResult
|
||||
final public func updateChanges(_ db: Database) throws -> Bool {
|
||||
let changedColumns = Set(databaseChanges.keys)
|
||||
if changedColumns.isEmpty {
|
||||
return false
|
||||
} else {
|
||||
try update(db, columns: changedColumns)
|
||||
return true
|
||||
}
|
||||
try update(db, columns: changedColumns)
|
||||
}
|
||||
|
||||
/// Executes an INSERT or an UPDATE statement so that `self` is saved in
|
||||
@@ -331,8 +340,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
///
|
||||
/// Otherwise, performs an insert.
|
||||
///
|
||||
/// On success, this method sets the *hasPersistentChangedValues* flag
|
||||
/// to false.
|
||||
/// On success, this method sets the *hasDatabaseChanges* flag to false.
|
||||
///
|
||||
/// This method is guaranteed to have inserted or updated a row in the
|
||||
/// database if it returns without error.
|
||||
@@ -346,8 +354,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
|
||||
/// Executes a DELETE statement.
|
||||
///
|
||||
/// On success, this method sets the *hasPersistentChangedValues* flag
|
||||
/// to true.
|
||||
/// On success, this method sets the *hasDatabaseChanges* flag to true.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: Whether a database row was deleted.
|
||||
@@ -357,8 +364,8 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
defer {
|
||||
// Future calls to update() will throw NotFound. Make the user
|
||||
// a favor and make sure this error is thrown even if she checks the
|
||||
// hasPersistentChangedValues flag:
|
||||
hasPersistentChangedValues = true
|
||||
// hasDatabaseChanges flag:
|
||||
hasDatabaseChanges = true
|
||||
}
|
||||
return try performDelete(db)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
/// RecordBox is a subclass of Record that aims at giving any record type the
|
||||
/// changes tracking provided by the Record class.
|
||||
///
|
||||
/// // A Regular record struct
|
||||
/// struct Player: RowConvertible, MutablePersistable, Codable {
|
||||
/// static let databaseTableName = "players"
|
||||
/// var id: Int64?
|
||||
/// var name: String
|
||||
/// var score: Int
|
||||
/// mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
/// id = rowID
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// // Fetch a player record
|
||||
/// let playerRecord = try RecordBox<Player>.fetchOne(db, key: 1)!
|
||||
///
|
||||
/// // Profit from changes tracking
|
||||
/// playerRecord.value.score = 300
|
||||
/// playerRecord.hasPersistentChangedValues // true
|
||||
/// playerRecord.persistentChangedValues["score"] // 100 (the old value)
|
||||
/// }
|
||||
@available(*, deprecated, message: "Prefer changes methods defined on the MutablePersistable protocol: databaseEqual(_:), databaseChanges(from:), updateChanges(from:)")
|
||||
public final class RecordBox<T: RowConvertible & MutablePersistable>: Record {
|
||||
/// The boxed record
|
||||
public var value: T
|
||||
|
||||
/// Creates a RecordBox that wraps the given record
|
||||
public init(value: T) {
|
||||
self.value = value
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - RowConvertible
|
||||
|
||||
/// Initializes a record from `row`.
|
||||
public required init(row: Row) {
|
||||
self.value = T(row: row)
|
||||
super.init(row: row)
|
||||
}
|
||||
|
||||
// MARK: - TableMapping
|
||||
|
||||
/// :nodoc:
|
||||
override public class var databaseTableName: String {
|
||||
return T.databaseTableName
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
override public class var databaseSelection: [SQLSelectable] {
|
||||
return T.databaseSelection
|
||||
}
|
||||
|
||||
// MARK: - MutablePersistable
|
||||
|
||||
/// :nodoc:
|
||||
override public class var persistenceConflictPolicy: PersistenceConflictPolicy {
|
||||
return T.persistenceConflictPolicy
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
override public func encode(to container: inout PersistenceContainer) {
|
||||
value.encode(to: &container)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
override public func didInsert(with rowID: Int64, for column: String?) {
|
||||
value.didInsert(with: rowID, for: column)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
override public func insert(_ db: Database) throws {
|
||||
try value.insert(db)
|
||||
hasPersistentChangedValues = false
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
override public func update(_ db: Database, columns: Set<String>) throws {
|
||||
try value.update(db, columns: columns)
|
||||
hasPersistentChangedValues = false
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
@discardableResult
|
||||
override public func delete(_ db: Database) throws -> Bool {
|
||||
defer {
|
||||
// Future calls to update() will throw NotFound. Make the user
|
||||
// a favor and make sure this error is thrown even if she checks the
|
||||
// hasPersistentChangedValues flag:
|
||||
hasPersistentChangedValues = true
|
||||
}
|
||||
return try value.delete(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func exists(_ db: Database) throws -> Bool {
|
||||
return try value.exists(db)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,20 @@
|
||||
private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainerProtocol {
|
||||
let row: Row
|
||||
let decoder: RowDecoder
|
||||
|
||||
init(row: Row) {
|
||||
self.row = row
|
||||
init(decoder: RowDecoder) {
|
||||
self.decoder = decoder
|
||||
}
|
||||
|
||||
/// The path of coding keys taken to get to this point in decoding.
|
||||
/// A `nil` value indicates an unkeyed container.
|
||||
var codingPath: [CodingKey] { return [] }
|
||||
var codingPath: [CodingKey] { return decoder.codingPath }
|
||||
|
||||
/// All the keys the `Decoder` has for this container.
|
||||
///
|
||||
/// Different keyed containers from the same `Decoder` may return different keys here; it is possible to encode with multiple key types which are not convertible to one another. This should report all keys present which are convertible to the requested type.
|
||||
var allKeys: [Key] {
|
||||
return row.columnNames.flatMap { Key(stringValue: $0) }
|
||||
let row = decoder.row
|
||||
let columnNames = Set(row.columnNames)
|
||||
let scopeNames = row.scopeNames
|
||||
return columnNames.union(scopeNames).flatMap { Key(stringValue: $0) }
|
||||
}
|
||||
|
||||
/// Returns whether the `Decoder` contains a value associated with the given key.
|
||||
@@ -23,7 +24,8 @@ private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainer
|
||||
/// - parameter key: The key to search for.
|
||||
/// - returns: Whether the `Decoder` has an entry for the given key.
|
||||
func contains(_ key: Key) -> Bool {
|
||||
return row.hasColumn(key.stringValue)
|
||||
let row = decoder.row
|
||||
return row.hasColumn(key.stringValue) || (row.scoped(on: key.stringValue) != nil)
|
||||
}
|
||||
|
||||
/// Decodes a null value for the given key.
|
||||
@@ -32,7 +34,8 @@ private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainer
|
||||
/// - returns: Whether the encountered value was null.
|
||||
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
|
||||
func decodeNil(forKey key: Key) throws -> Bool {
|
||||
return row[key.stringValue] == nil
|
||||
let row = decoder.row
|
||||
return row[key.stringValue] == nil && (row.scoped(on: key.stringValue) == nil)
|
||||
}
|
||||
|
||||
/// Decodes a value of the given type for the given key.
|
||||
@@ -43,20 +46,50 @@ private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainer
|
||||
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type.
|
||||
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
|
||||
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
|
||||
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return row[key.stringValue] }
|
||||
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return row[key.stringValue] }
|
||||
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return row[key.stringValue] }
|
||||
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { return row[key.stringValue] }
|
||||
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { return row[key.stringValue] }
|
||||
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { return row[key.stringValue] }
|
||||
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { return row[key.stringValue] }
|
||||
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { return row[key.stringValue] }
|
||||
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { return row[key.stringValue] }
|
||||
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { return row[key.stringValue] }
|
||||
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { return row[key.stringValue] }
|
||||
func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return row[key.stringValue] }
|
||||
func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return row[key.stringValue] }
|
||||
func decode(_ type: String.Type, forKey key: Key) throws -> String { return row[key.stringValue] }
|
||||
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return decoder.row[key.stringValue] }
|
||||
func decode(_ type: String.Type, forKey key: Key) throws -> String { return decoder.row[key.stringValue] }
|
||||
|
||||
/// Decodes a value of the given type for the given key, if present.
|
||||
///
|
||||
/// This method returns nil if the container does not have a value
|
||||
/// associated with key, or if the value is null. The difference between
|
||||
/// these states can be distinguished with a contains(_:) call.
|
||||
func decodeIfPresent<T>(_ type: T.Type, forKey key: Key) throws -> T? where T : Decodable {
|
||||
let row = decoder.row
|
||||
|
||||
// Try column
|
||||
if row.hasColumn(key.stringValue) {
|
||||
let dbValue: DatabaseValue = row[key.stringValue]
|
||||
if let type = T.self as? DatabaseValueConvertible.Type {
|
||||
// Prefer DatabaseValueConvertible decoding over Decodable.
|
||||
// This allows decoding Date from String, or DatabaseValue from NULL.
|
||||
return type.fromDatabaseValue(dbValue) as! T?
|
||||
} else if dbValue.isNull {
|
||||
return nil
|
||||
} else {
|
||||
return try T(from: RowDecoder(row: row, codingPath: codingPath + [key]))
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback on scope
|
||||
if let scopedRow = row.scoped(on: key.stringValue), scopedRow.containsNonNullValue {
|
||||
return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key]))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Decodes a value of the given type for the given key.
|
||||
///
|
||||
@@ -67,14 +100,27 @@ private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainer
|
||||
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
|
||||
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
|
||||
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable {
|
||||
let dbValue: DatabaseValue = row[key.stringValue]
|
||||
if let type = T.self as? DatabaseValueConvertible.Type {
|
||||
// Prefer DatabaseValueConvertible decoding over Decodable.
|
||||
// This allows decoding Date from String, or DatabaseValue from NULL.
|
||||
return type.fromDatabaseValue(dbValue) as! T
|
||||
} else {
|
||||
return try T(from: RowDecoder(row: row, codingPath: codingPath + [key]))
|
||||
let row = decoder.row
|
||||
|
||||
// Try column
|
||||
if row.hasColumn(key.stringValue) {
|
||||
let dbValue: DatabaseValue = row[key.stringValue]
|
||||
if let type = T.self as? DatabaseValueConvertible.Type {
|
||||
// Prefer DatabaseValueConvertible decoding over Decodable.
|
||||
// This allows decoding Date from String, or DatabaseValue from NULL.
|
||||
return type.fromDatabaseValue(dbValue) as! T
|
||||
} else {
|
||||
return try T(from: RowDecoder(row: row, codingPath: codingPath + [key]))
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback on scope
|
||||
if let scopedRow = row.scoped(on: key.stringValue) {
|
||||
return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key]))
|
||||
}
|
||||
|
||||
let path = (codingPath.map { $0.stringValue } + [key.stringValue]).joined(separator: ".")
|
||||
fatalError("No such column or scope: \(path)")
|
||||
}
|
||||
|
||||
/// Returns the data stored for the given key as represented in a container keyed by the given key type.
|
||||
@@ -84,7 +130,7 @@ private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainer
|
||||
/// - returns: A keyed decoding container view into `self`.
|
||||
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is not a keyed container.
|
||||
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey {
|
||||
fatalError("Not implemented")
|
||||
fatalError("not implemented")
|
||||
}
|
||||
|
||||
/// Returns the data stored for the given key as represented in an unkeyed container.
|
||||
@@ -93,7 +139,9 @@ private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainer
|
||||
/// - returns: An unkeyed decoding container view into `self`.
|
||||
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is not an unkeyed container.
|
||||
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
|
||||
fatalError("Not implemented")
|
||||
throw DecodingError.typeMismatch(
|
||||
UnkeyedDecodingContainer.self,
|
||||
DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported"))
|
||||
}
|
||||
|
||||
/// Returns a `Decoder` instance for decoding `super` from the container associated with the default `super` key.
|
||||
@@ -104,7 +152,7 @@ private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainer
|
||||
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the default `super` key.
|
||||
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the default `super` key.
|
||||
public func superDecoder() throws -> Decoder {
|
||||
fatalError("Not implemented")
|
||||
return decoder
|
||||
}
|
||||
|
||||
/// Returns a `Decoder` instance for decoding `super` from the container associated with the given key.
|
||||
@@ -114,16 +162,15 @@ private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainer
|
||||
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
|
||||
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
|
||||
public func superDecoder(forKey key: Key) throws -> Decoder {
|
||||
fatalError("Not implemented")
|
||||
return decoder
|
||||
}
|
||||
}
|
||||
|
||||
private struct RowSingleValueDecodingContainer: SingleValueDecodingContainer {
|
||||
let row: Row
|
||||
var codingPath: [CodingKey]
|
||||
let column: CodingKey
|
||||
|
||||
var codingPath: [CodingKey] { return [] }
|
||||
|
||||
/// Decodes a null value.
|
||||
///
|
||||
/// - returns: Whether the encountered value was null.
|
||||
@@ -182,14 +229,7 @@ private struct RowDecoder: Decoder {
|
||||
var userInfo: [CodingUserInfoKey : Any] { return [:] }
|
||||
|
||||
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
|
||||
// Asked for a keyed type: top level required
|
||||
guard codingPath.isEmpty else {
|
||||
throw DecodingError.typeMismatch(
|
||||
RowDecoder.self,
|
||||
DecodingError.Context(codingPath: codingPath, debugDescription: "nested decoding is not supported"))
|
||||
}
|
||||
|
||||
return KeyedDecodingContainer(RowKeyedDecodingContainer<Key>(row: row))
|
||||
return KeyedDecodingContainer(RowKeyedDecodingContainer<Key>(decoder: self))
|
||||
}
|
||||
|
||||
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
|
||||
@@ -205,7 +245,7 @@ private struct RowDecoder: Decoder {
|
||||
RowDecoder.self,
|
||||
DecodingError.Context(codingPath: codingPath, debugDescription: "single value decoding requires a coding key"))
|
||||
}
|
||||
return RowSingleValueDecodingContainer(row: row, column: codingKey)
|
||||
return RowSingleValueDecodingContainer(row: row, codingPath: codingPath, column: codingKey)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// - returns: A cursor over fetched records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> RecordCursor<Self> where Sequence.Element: DatabaseValueConvertible {
|
||||
return try filter(db, keys: keys).fetchCursor(db)
|
||||
return try filter(keys: keys).fetchCursor(db)
|
||||
}
|
||||
|
||||
/// Returns an array of records, given their primary keys.
|
||||
@@ -98,7 +98,7 @@ extension RowConvertible where Self: TableMapping {
|
||||
// Avoid hitting the database
|
||||
return []
|
||||
}
|
||||
return try filter(db, keys: keys).fetchAll(db)
|
||||
return try filter(keys: keys).fetchAll(db)
|
||||
}
|
||||
|
||||
/// Returns a single record given its primary key.
|
||||
@@ -115,7 +115,7 @@ extension RowConvertible where Self: TableMapping {
|
||||
// Avoid hitting the database
|
||||
return nil
|
||||
}
|
||||
return try filter(db, keys: [key]).fetchOne(db)
|
||||
return try filter(key: key).fetchOne(db)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,7 +139,7 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// - returns: A cursor over fetched records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> RecordCursor<Self> {
|
||||
return try filter(db, keys: keys).fetchCursor(db)
|
||||
return try filter(keys: keys).fetchCursor(db)
|
||||
}
|
||||
|
||||
/// Returns an array of records identified by the provided unique keys
|
||||
@@ -155,12 +155,11 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// - returns: An array of records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> [Self] {
|
||||
let keys = Array(keys)
|
||||
if keys.isEmpty {
|
||||
// Avoid hitting the database
|
||||
return []
|
||||
}
|
||||
return try filter(db, keys: keys).fetchAll(db)
|
||||
return try filter(keys: keys).fetchAll(db)
|
||||
}
|
||||
|
||||
/// Returns a single record identified by a unique key (the primary key or
|
||||
@@ -173,7 +172,11 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// - key: A dictionary of values.
|
||||
/// - returns: An optional record.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Self? {
|
||||
return try filter(db, keys: [key]).fetchOne(db)
|
||||
public static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]?) throws -> Self? {
|
||||
guard let key = key else {
|
||||
// Avoid hitting the database
|
||||
return nil
|
||||
}
|
||||
return try filter(key: key).fetchOne(db)
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@
|
||||
/// RowConvertible is adopted by Record.
|
||||
public protocol RowConvertible {
|
||||
|
||||
/// Initializes a record from `row`.
|
||||
/// Creates a record from `row`.
|
||||
///
|
||||
/// For performance reasons, the row argument may be reused during the
|
||||
/// iteration of a fetch query. If you want to keep the row for later use,
|
||||
@@ -51,6 +51,7 @@ public final class RecordCursor<Record: RowConvertible> : Cursor {
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func next() throws -> Record? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
|
||||
@@ -58,7 +58,7 @@ extension TableMapping {
|
||||
|
||||
extension TableMapping {
|
||||
|
||||
// MARK: Counting All
|
||||
// MARK: - Counting All
|
||||
|
||||
/// The number of records.
|
||||
///
|
||||
@@ -70,63 +70,53 @@ extension TableMapping {
|
||||
|
||||
extension TableMapping {
|
||||
|
||||
// MARK: Key Requests
|
||||
// MARK: - SQL Generation
|
||||
|
||||
static func filter<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> QueryInterfaceRequest<Self> where Sequence.Element: DatabaseValueConvertible {
|
||||
let primaryKey = try db.primaryKey(databaseTableName)
|
||||
let columns = primaryKey.columns.map { Column($0) }
|
||||
GRDBPrecondition(columns.count == 1, "table \(databaseTableName) has multiple columns in its primary key")
|
||||
let column = columns[0]
|
||||
|
||||
let keys = Array(keys)
|
||||
switch keys.count {
|
||||
case 0:
|
||||
return none()
|
||||
case 1:
|
||||
return filter(column == keys[0])
|
||||
default:
|
||||
return filter(keys.contains(column))
|
||||
}
|
||||
/// The selection as an SQL String.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct Player: TableMapping {
|
||||
/// static let databaseTableName = "players"
|
||||
/// }
|
||||
///
|
||||
/// // SELECT "players".* FROM players
|
||||
/// let sql = "SELECT \(Player.selectionSQL()) FROM players"
|
||||
///
|
||||
/// // SELECT "p".* FROM players AS p
|
||||
/// let sql = "SELECT \(Player.selectionSQL(alias: "p")) FROM players AS p"
|
||||
public static func selectionSQL(alias: String? = nil) -> String {
|
||||
let qualifier = SQLTableQualifier(tableName: databaseTableName, alias: alias ?? databaseTableName)
|
||||
let selection = databaseSelection.map { $0.qualified(by: qualifier) }
|
||||
var arguments: StatementArguments? = nil
|
||||
return selection
|
||||
.map { $0.resultColumnSQL(&arguments) }
|
||||
.joined(separator: ", ")
|
||||
}
|
||||
|
||||
// Raises a fatal error if there is no unique index on the columns (unless
|
||||
// fatalErrorOnMissingUniqueIndex is false, for testability).
|
||||
//
|
||||
// TODO: think about
|
||||
// - allowing non unique keys in Type.fetchOne(db, key: ...) ???
|
||||
// - allowing non unique keys in Type.fetchAll/Cursor(db, keys: ...)
|
||||
// - forbidding nil values: Player.deleteOne(db, key: ["email": nil]) may delete several rows (case of a nullable unique key)
|
||||
static func filter(_ db: Database, keys: [[String: DatabaseValueConvertible?]], fatalErrorOnMissingUniqueIndex: Bool = true) throws -> QueryInterfaceRequest<Self> {
|
||||
// SELECT * FROM table WHERE ((a=? AND b=?) OR (c=? AND d=?) OR ...)
|
||||
let keyPredicates: [SQLExpression] = try keys.map { key in
|
||||
// Prevent filter(db, keys: [[:]])
|
||||
GRDBPrecondition(!key.isEmpty, "Invalid empty key dictionary")
|
||||
|
||||
// Prevent filter(db, keys: [["foo": 1, "bar": 2]]) where
|
||||
// ("foo", "bar") is not a unique key (primary key or columns of a
|
||||
// unique index)
|
||||
guard let orderedColumns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else {
|
||||
let message = "table \(databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))"
|
||||
if fatalErrorOnMissingUniqueIndex {
|
||||
fatalError(message)
|
||||
} else {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: message)
|
||||
}
|
||||
}
|
||||
|
||||
let lowercaseOrderedColumns = orderedColumns.map { $0.lowercased() }
|
||||
let columnPredicates: [SQLExpression] = key
|
||||
// Sort key columns in the same order as the unique index
|
||||
.sorted { (kv1, kv2) in lowercaseOrderedColumns.index(of: kv1.0.lowercased())! < lowercaseOrderedColumns.index(of: kv2.0.lowercased())! }
|
||||
.map { (column, value) in Column(column) == value }
|
||||
return SQLBinaryOperator.and.join(columnPredicates)! // not nil because columnPredicates is not empty
|
||||
}
|
||||
|
||||
guard let predicate = SQLBinaryOperator.or.join(keyPredicates) else {
|
||||
// No key
|
||||
return none()
|
||||
}
|
||||
|
||||
return filter(predicate)
|
||||
/// Returns the number of selected columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct Player: TableMapping {
|
||||
/// static let databaseTableName = "players"
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("id", .integer).primaryKey()
|
||||
/// t.column("name", .text)
|
||||
/// t.column("score", .integer)
|
||||
/// }
|
||||
///
|
||||
/// // 3
|
||||
/// try Player.numberOfSelectedColumns(db)
|
||||
/// }
|
||||
public static func numberOfSelectedColumns(_ db: Database) throws -> Int {
|
||||
let qualifier = SQLTableQualifier(tableName: databaseTableName, alias: nil)
|
||||
return try databaseSelection
|
||||
.map { try $0.qualified(by: qualifier).columnCount(db) }
|
||||
.reduce(0, +)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,16 +23,24 @@ public func databaseQuestionMarks(count: Int) -> String {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// This protocol is an implementation detail of GRDB. Don't use it.
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol _OptionalProtocol {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
associatedtype _Wrapped
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// This conformance is an implementation detail of GRDB. Don't rely on it.
|
||||
///
|
||||
/// :nodoc:
|
||||
extension Optional : _OptionalProtocol {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public typealias _Wrapped = Wrapped
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDBCipher'
|
||||
s.version = '2.0.2'
|
||||
s.version = '2.9.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A Swift application toolkit for SQLite databases.'
|
||||
|
||||
Executable
+3199
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
<FileRef
|
||||
location = "self:GRDBCipher.xcodeproj">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded</key>
|
||||
<false/>
|
||||
</dict>
|
||||
</plist>
|
||||
+37
-7
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0900"
|
||||
LastUpgradeVersion = "0910"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -17,7 +17,35 @@
|
||||
BlueprintIdentifier = "560FC5191CB003810014AA8E"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipherOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
ReferencedContainer = "container:GRDBCipher.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "560FC55D1CB00B880014AA8E"
|
||||
BuildableName = "GRDBCipherOSXTests.xctest"
|
||||
BlueprintName = "GRDBCipherOSXTests"
|
||||
ReferencedContainer = "container:GRDBCipher.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "567156191CB16729007DC145"
|
||||
BuildableName = "GRDBCipherOSXEncryptedTests.xctest"
|
||||
BlueprintName = "GRDBCipherOSXEncryptedTests"
|
||||
ReferencedContainer = "container:GRDBCipher.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
@@ -26,6 +54,7 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
@@ -35,7 +64,7 @@
|
||||
BlueprintIdentifier = "560FC55D1CB00B880014AA8E"
|
||||
BuildableName = "GRDBCipherOSXTests.xctest"
|
||||
BlueprintName = "GRDBCipherOSXTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
ReferencedContainer = "container:GRDBCipher.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
<TestableReference
|
||||
@@ -45,7 +74,7 @@
|
||||
BlueprintIdentifier = "567156191CB16729007DC145"
|
||||
BuildableName = "GRDBCipherOSXEncryptedTests.xctest"
|
||||
BlueprintName = "GRDBCipherOSXEncryptedTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
ReferencedContainer = "container:GRDBCipher.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
@@ -55,7 +84,7 @@
|
||||
BlueprintIdentifier = "560FC5191CB003810014AA8E"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipherOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
ReferencedContainer = "container:GRDBCipher.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
@@ -65,6 +94,7 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
@@ -77,7 +107,7 @@
|
||||
BlueprintIdentifier = "560FC5191CB003810014AA8E"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipherOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
ReferencedContainer = "container:GRDBCipher.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
@@ -95,7 +125,7 @@
|
||||
BlueprintIdentifier = "560FC5191CB003810014AA8E"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipherOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
ReferencedContainer = "container:GRDBCipher.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
+36
-15
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0900"
|
||||
LastUpgradeVersion = "0910"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -17,7 +17,35 @@
|
||||
BlueprintIdentifier = "56AFC9EE1CB1A8BB00F48B96"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipheriOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
ReferencedContainer = "container:GRDBCipher.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56AFCA841CB1ABC800F48B96"
|
||||
BuildableName = "GRDBCipheriOSEncryptedTests.xctest"
|
||||
BlueprintName = "GRDBCipheriOSEncryptedTests"
|
||||
ReferencedContainer = "container:GRDBCipher.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56AFCA2B1CB1AA9900F48B96"
|
||||
BuildableName = "GRDBCipheriOSTests.xctest"
|
||||
BlueprintName = "GRDBCipheriOSTests"
|
||||
ReferencedContainer = "container:GRDBCipher.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
@@ -26,6 +54,7 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
@@ -35,7 +64,7 @@
|
||||
BlueprintIdentifier = "56AFCA2B1CB1AA9900F48B96"
|
||||
BuildableName = "GRDBCipheriOSTests.xctest"
|
||||
BlueprintName = "GRDBCipheriOSTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
ReferencedContainer = "container:GRDBCipher.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
<TestableReference
|
||||
@@ -45,7 +74,7 @@
|
||||
BlueprintIdentifier = "56AFCA841CB1ABC800F48B96"
|
||||
BuildableName = "GRDBCipheriOSEncryptedTests.xctest"
|
||||
BlueprintName = "GRDBCipheriOSEncryptedTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
ReferencedContainer = "container:GRDBCipher.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
@@ -55,7 +84,7 @@
|
||||
BlueprintIdentifier = "56AFC9EE1CB1A8BB00F48B96"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipheriOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
ReferencedContainer = "container:GRDBCipher.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
@@ -65,6 +94,7 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
@@ -77,7 +107,7 @@
|
||||
BlueprintIdentifier = "56AFC9EE1CB1A8BB00F48B96"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipheriOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
ReferencedContainer = "container:GRDBCipher.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
@@ -89,15 +119,6 @@
|
||||
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">
|
||||
Executable
+2518
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
<FileRef
|
||||
location = "self:GRDBCustom.xcodeproj">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded</key>
|
||||
<false/>
|
||||
</dict>
|
||||
</plist>
|
||||
+19
-21
@@ -17,7 +17,21 @@
|
||||
BlueprintIdentifier = "F3BA80591CFB2BB2003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLite.framework"
|
||||
BlueprintName = "GRDBCustomSQLiteOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
ReferencedContainer = "container:GRDBCustom.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F3BA809A1CFB2F6F003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLiteOSXTests.xctest"
|
||||
BlueprintName = "GRDBCustomSQLiteOSXTests"
|
||||
ReferencedContainer = "container:GRDBCustom.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
@@ -26,6 +40,7 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
@@ -35,7 +50,7 @@
|
||||
BlueprintIdentifier = "F3BA809A1CFB2F6F003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLiteOSXTests.xctest"
|
||||
BlueprintName = "GRDBCustomSQLiteOSXTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
ReferencedContainer = "container:GRDBCustom.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
@@ -45,7 +60,7 @@
|
||||
BlueprintIdentifier = "F3BA80591CFB2BB2003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLite.framework"
|
||||
BlueprintName = "GRDBCustomSQLiteOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
ReferencedContainer = "container:GRDBCustom.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
@@ -55,21 +70,13 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F3BA80591CFB2BB2003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLite.framework"
|
||||
BlueprintName = "GRDBCustomSQLiteOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
@@ -79,15 +86,6 @@
|
||||
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">
|
||||
+21
-6
@@ -17,7 +17,21 @@
|
||||
BlueprintIdentifier = "F3BA7FFD1CFB25E4003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLite.framework"
|
||||
BlueprintName = "GRDBCustomSQLiteiOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
ReferencedContainer = "container:GRDBCustom.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F3BA80401CFB2AD7003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLiteiOSTests.xctest"
|
||||
BlueprintName = "GRDBCustomSQLiteiOSTests"
|
||||
ReferencedContainer = "container:GRDBCustom.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
@@ -27,7 +41,8 @@
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
codeCoverageEnabled = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
@@ -36,7 +51,7 @@
|
||||
BlueprintIdentifier = "F3BA80401CFB2AD7003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLiteiOSTests.xctest"
|
||||
BlueprintName = "GRDBCustomSQLiteiOSTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
ReferencedContainer = "container:GRDBCustom.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
@@ -46,7 +61,7 @@
|
||||
BlueprintIdentifier = "F3BA7FFD1CFB25E4003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLite.framework"
|
||||
BlueprintName = "GRDBCustomSQLiteiOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
ReferencedContainer = "container:GRDBCustom.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
@@ -69,7 +84,7 @@
|
||||
BlueprintIdentifier = "F3BA7FFD1CFB25E4003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLite.framework"
|
||||
BlueprintName = "GRDBCustomSQLiteiOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
ReferencedContainer = "container:GRDBCustom.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
@@ -87,7 +102,7 @@
|
||||
BlueprintIdentifier = "F3BA7FFD1CFB25E4003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLite.framework"
|
||||
BlueprintName = "GRDBCustomSQLiteiOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
ReferencedContainer = "container:GRDBCustom.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
@@ -0,0 +1,29 @@
|
||||
> ℹ We use Github issues for bug reports, feature requests, general support, and questions about the library.
|
||||
>
|
||||
> Please fill out this template when filing an issue, and remove this header before submitting.
|
||||
|
||||
## What did you do?
|
||||
|
||||
> Please replace this with what you did.
|
||||
|
||||
## What did you expect to happen?
|
||||
|
||||
> Please replace this with what you expected to happen.
|
||||
|
||||
## What happened instead?
|
||||
|
||||
> Please replace this with of what happened instead.
|
||||
|
||||
## Environment
|
||||
|
||||
**GRDB flavor(s):** (GRDB, GRDBCipher, GRDBCustom?)
|
||||
**GRDB version:**
|
||||
**Installation method:** (CocoaPods, SPM, manual?)
|
||||
**Xcode version:**
|
||||
**Swift version:**
|
||||
**Platform(s) running GRDB:** (iOS, macOS, watchOS?)
|
||||
**macOS version running Xcode:**
|
||||
|
||||
## Demo Project
|
||||
|
||||
> Please link to or upload a project we can download that reproduces the issue.
|
||||
@@ -1,4 +1,4 @@
|
||||
Copyright (C) 2017 Gwendal Roué
|
||||
Copyright (C) 2018 Gwendal Roué
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ default: test
|
||||
# Requirements
|
||||
# ============
|
||||
#
|
||||
# Xcode 8.3.3, with iOS8.1 Simulator installed
|
||||
# Xcode >= 9.0, with iOS8.1 Simulator installed
|
||||
# CocoaPods ~> 1.2.0 - https://cocoapods.org
|
||||
# Carthage ~> 0.20.1 - https://github.com/carthage/carthage
|
||||
# Jazzy ~> 0.7.4 - https://github.com/realm/jazzy
|
||||
@@ -29,6 +29,7 @@ XCODEBUILD := set -o pipefail && $(shell command -v xcodebuild)
|
||||
XCODEVERSION_FULL := $(word 2, $(shell xcodebuild -version))
|
||||
XCODEVERSION_MAJOR := $(shell xcodebuild -version 2>&1 | grep Xcode | cut -d' ' -f2 | cut -d'.' -f1)
|
||||
XCODEVERSION_MINOR := $(shell xcodebuild -version 2>&1 | grep Xcode | cut -d' ' -f2 | cut -d'.' -f2)
|
||||
XCODEVERSION_PATCH := $(shell xcodebuild -version 2>&1 | grep Xcode | cut -d' ' -f2 | cut -d'.' -f3)
|
||||
|
||||
# The Xcode Version, containing only the "MAJOR.MINOR" (ex. "8.3" for Xcode 8.3, 8.3.1, etc.)
|
||||
XCODEVERSION := $(XCODEVERSION_MAJOR).$(XCODEVERSION_MINOR)
|
||||
@@ -46,9 +47,18 @@ TEST_ACTIONS = clean build build-for-testing test-without-building
|
||||
# xcodebuild destination to run tests on iOS 8.1 (requires a pre-installed simulator)
|
||||
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 4s,OS=8.1"
|
||||
|
||||
ifeq ($(XCODEVERSION),9.0)
|
||||
# xcodebuild destination to run tests on latest iOS (Xcode 9.0)
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.0"
|
||||
ifeq ($(XCODEVERSION),9.2)
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.2"
|
||||
else ifeq ($(XCODEVERSION),9.1)
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.1"
|
||||
else ifeq ($(XCODEVERSION),9.0)
|
||||
ifeq ($(XCODEVERSION_PATCH),1)
|
||||
# Xcode 9.0.1: @groue's personal computer
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.0.1"
|
||||
else
|
||||
# Xcode 9.0: Travis https://docs.travis-ci.com/user/reference/osx/#Xcode-9.0
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.0"
|
||||
endif
|
||||
else
|
||||
# Xcode < 9.0 is not supported
|
||||
endif
|
||||
@@ -127,7 +137,7 @@ test_framework_GRDBiOS_minTarget:
|
||||
|
||||
test_framework_GRDBCustomSQLiteOSX: SQLiteCustom
|
||||
$(XCODEBUILD) \
|
||||
-project GRDB.xcodeproj \
|
||||
-project GRDBCustom.xcodeproj \
|
||||
-scheme GRDBCustomSQLiteOSX \
|
||||
$(TEST_ACTIONS) \
|
||||
$(XCPRETTY)
|
||||
@@ -136,7 +146,7 @@ test_framework_GRDBCustomSQLiteiOS: test_framework_GRDBCustomSQLiteiOS_maxTarget
|
||||
|
||||
test_framework_GRDBCustomSQLiteiOS_maxTarget: SQLiteCustom
|
||||
$(XCODEBUILD) \
|
||||
-project GRDB.xcodeproj \
|
||||
-project GRDBCustom.xcodeproj \
|
||||
-scheme GRDBCustomSQLiteiOS \
|
||||
-destination $(MAX_IOS_DESTINATION) \
|
||||
$(TEST_ACTIONS) \
|
||||
@@ -144,7 +154,7 @@ test_framework_GRDBCustomSQLiteiOS_maxTarget: SQLiteCustom
|
||||
|
||||
test_framework_GRDBCustomSQLiteiOS_minTarget: SQLiteCustom
|
||||
$(XCODEBUILD) \
|
||||
-project GRDB.xcodeproj \
|
||||
-project GRDBCustom.xcodeproj \
|
||||
-scheme GRDBCustomSQLiteiOS \
|
||||
-destination $(MIN_IOS_DESTINATION) \
|
||||
$(TEST_ACTIONS) \
|
||||
@@ -152,7 +162,7 @@ test_framework_GRDBCustomSQLiteiOS_minTarget: SQLiteCustom
|
||||
|
||||
test_framework_GRDBCipherOSX: SQLCipher
|
||||
$(XCODEBUILD) \
|
||||
-project GRDB.xcodeproj \
|
||||
-project GRDBCipher.xcodeproj \
|
||||
-scheme GRDBCipherOSX \
|
||||
$(TEST_ACTIONS) \
|
||||
$(XCPRETTY)
|
||||
@@ -161,7 +171,7 @@ test_framework_GRDBCipheriOS: test_framework_GRDBCipheriOS_maxTarget test_framew
|
||||
|
||||
test_framework_GRDBCipheriOS_maxTarget: SQLCipher
|
||||
$(XCODEBUILD) \
|
||||
-project GRDB.xcodeproj \
|
||||
-project GRDBCipher.xcodeproj \
|
||||
-scheme GRDBCipheriOS \
|
||||
-destination $(MAX_IOS_DESTINATION) \
|
||||
$(TEST_ACTIONS) \
|
||||
@@ -169,13 +179,14 @@ test_framework_GRDBCipheriOS_maxTarget: SQLCipher
|
||||
|
||||
test_framework_GRDBCipheriOS_minTarget: SQLCipher
|
||||
$(XCODEBUILD) \
|
||||
-project GRDB.xcodeproj \
|
||||
-project GRDBCipher.xcodeproj \
|
||||
-scheme GRDBCipheriOS \
|
||||
-destination $(MIN_IOS_DESTINATION) \
|
||||
$(TEST_ACTIONS) \
|
||||
$(XCPRETTY)
|
||||
|
||||
test_SPM:
|
||||
# Add sanitizers when available: https://twitter.com/simjp/status/929140877540278272
|
||||
$(SWIFT) package clean
|
||||
$(SWIFT) build
|
||||
$(SWIFT) build -c release
|
||||
@@ -222,6 +233,13 @@ test_CarthageBuild: SQLiteCustom SQLCipher
|
||||
ifdef CARTHAGE
|
||||
rm -rf Carthage
|
||||
$(CARTHAGE) build --no-skip-current
|
||||
$(XCODEBUILD) \
|
||||
-project Tests/Carthage/GRDBiOS/iOS.xcodeproj \
|
||||
-scheme iOS \
|
||||
-configuration Release \
|
||||
-destination $(MAX_IOS_DESTINATION) \
|
||||
clean build \
|
||||
$(XCPRETTY)
|
||||
else
|
||||
@echo Carthage must be installed for test_CarthageBuild
|
||||
@exit 1
|
||||
@@ -233,10 +251,10 @@ test_performance: Realm FMDB SQLite.swift
|
||||
-scheme GRDBOSXPerformanceComparisonTests \
|
||||
build-for-testing test-without-building
|
||||
|
||||
Realm: Tests/Performance/Realm/build/osx/swift-4.0/RealmSwift.framework
|
||||
Realm: Tests/Performance/Realm/build/osx/swift-4.0.3/RealmSwift.framework
|
||||
|
||||
# Makes sure the Tests/Performance/Realm submodule has been downloaded, and Realm framework has been built.
|
||||
Tests/Performance/Realm/build/osx/swift-4.0/RealmSwift.framework:
|
||||
Tests/Performance/Realm/build/osx/swift-4.0.3/RealmSwift.framework:
|
||||
$(GIT) submodule update --init --recursive Tests/Performance/Realm
|
||||
cd Tests/Performance/Realm && sh build.sh osx-swift
|
||||
|
||||
@@ -285,10 +303,10 @@ ifdef JAZZY
|
||||
--author 'Gwendal Roué' \
|
||||
--author_url https://github.com/groue \
|
||||
--github_url https://github.com/groue/GRDB.swift \
|
||||
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v2.0 \
|
||||
--module-version 2.0 \
|
||||
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v2.9.0 \
|
||||
--module-version 2.9 \
|
||||
--module GRDB \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/2.0/ \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/2.9/ \
|
||||
--output Documentation/Reference \
|
||||
--podspec GRDB.swift.podspec
|
||||
else
|
||||
|
||||
+1
-1
Submodule SQLCipher/src updated: d0f6d20911...be3ac49760.
+1
-1
Submodule SQLiteCustom/src updated: d0b7a5cebc...ced2815553.
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>2.0.2</string>
|
||||
<string>2.9.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
- [ ] We share the database cache between database pool writers and readers. But what if a writer modifies the database schema within a transaction, and a concurrent reader reads the cache? Bad things, isn't it? Write failing tests first, and fix the bug.
|
||||
- [ ] Attach databases. Interesting question: what happens when one attaches a non-WAL db to a databasePool?
|
||||
- [ ] SQLCipher: sqlite3_rekey is discouraged (https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320)
|
||||
- [ ] What is the behavior inTransaction and inSavepoint behaviors in case of commit error? Code looks like we do not rollback, leaving the app in a weird state (out of Swift transaction block with a SQLite transaction that may still be opened).
|
||||
- [ ] Query builder
|
||||
- [ ] SELECT readers.*, books.* FROM ... JOIN ...
|
||||
- [ ] date functions
|
||||
@@ -12,15 +10,32 @@
|
||||
- [ ] REGEXP https://www.sqlite.org/lang_expr.html
|
||||
- [ ] CASE x WHEN w1 THEN r1 WHEN w2 THEN r2 ELSE r3 END https://www.sqlite.org/lang_expr.html
|
||||
- [ ] Write regression tests for #156 and #157
|
||||
- [ ] Allow concurrent reads from a snapshot
|
||||
- [ ] Decode NSDecimalNumber from text database values
|
||||
|
||||
GRDB 2.0
|
||||
GRDB 3.0
|
||||
|
||||
- [ ] Document Record.updateChanges(_:)
|
||||
- [ ] WIP on diff algorithms in RxGRDB needs access to MutablePersistable.databaseDictionary. The problem is that one should not need a writing protocol just to read. So consider introducing a new DatabaseEncodable protocol above MutablePersistable. It does not grant any writing methods. But it has encode(to:) and databaseDictionary.
|
||||
- [ ] Refactor SQL generation and rowId extraction from expression on the visitor pattern. Provide more documentation for literal expressions which become the only way to extend GRDB.
|
||||
- [ ] Hide useless scheduling methods behind protocols : https://forums.swift.org/t/discouraging-protocol-methods-on-concrete-values/8737/4?u=gwendal.roue
|
||||
- [ ] Make DatabasePool.write safe. See https://github.com/groue/GRDB.swift/commit/5e3c7d9c430df606a1cccfd4983be6b50e778a5c#commitcomment-26988970
|
||||
- [ ] Do one of those two:
|
||||
1. Make save() impossible to customize: remove it from Persistable protocol, and remove performSave() from tne public API.
|
||||
2. Open Record.save(), and have RecordBox.save() forward this method to its underlying type.
|
||||
- [ ] Not sure: Make the MutablePersistable.update(_:columns:) method mutating (as support for an updatedDate column)
|
||||
- [ ] Not sure: type safety
|
||||
- [ ] Introduce some record protocol with an associated primary key type. Restrict filter(key:) methods to this type. Allow distinguishing FooId from BarId types.
|
||||
- [ ] Replace Column with TypedColumn. How to avoid code duplication (repeated types)? Keypaths?
|
||||
- [ ] Rename Request to FetchRequest, because Request is a bad name: https://github.com/swift-server/http/pull/7#issuecomment-308448528
|
||||
- [ ] Rename RowConvertible, TableMapping, MutablePersistable and Persistable so that their names contain Record: FetchableRecord, TableRecord, MutablePersistableRecord, PersistableRecord?
|
||||
- [ ] Not sure: Consider introducing RowDecodable and RowEncodable on top of FetchableRecord and MutablePersistableRecord. This would allow keeping fetching and persistence methods private in some files.
|
||||
- [ ] Drop IteratorCursor, use AnyCursor instead
|
||||
- [ ] Drop TypedRequest, have FetchRequest defaults to Row requests.
|
||||
- [ ] Rename columnCount -> numberOfColumns
|
||||
- [ ] Try to remove double Persistable/MutablePersistable protocols: Would non-mutating Record methods help?
|
||||
|
||||
Not sure
|
||||
|
||||
- [ ] Support for resource values (see https://developer.apple.com/library/ios/qa/qa1719/_index.html)
|
||||
- [ ] encode/decode nested records/arrays/dictionaries as JSON?
|
||||
- [ ] Think about supporting Cursor's underestimatedCount, which could speed up Array(cursor) and fetchAll()
|
||||
- [ ] Support for OR ROLLBACK, and mismatch between the Swift depth and the SQLite depth of nested transactions/savepoint:
|
||||
|
||||
@@ -62,14 +77,6 @@ Not sure
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] Support for NSColor/UIColor. Beware UIColor components can go beyond [0, 1.0] in iOS10.
|
||||
- [ ] Store dates as timestamp (https://twitter.com/gloparco/status/780948021613912064, https://github.com/groue/GRDB.swift/issues/97)
|
||||
|
||||
|
||||
Require changes in the Swift language:
|
||||
|
||||
- [ ] Specific and optimized Optional<StatementColumnConvertible>.fetch... methods when http://openradar.appspot.com/22852669 is fixed.
|
||||
|
||||
|
||||
Requires recompilation of SQLite:
|
||||
|
||||
@@ -97,3 +104,4 @@ Reading list:
|
||||
- React oddity: http://stackoverflow.com/questions/41721769/realm-update-object-without-updating-lists
|
||||
- File protection: https://github.com/ccgus/fmdb/issues/262
|
||||
- File protection: https://lists.apple.com/archives/cocoa-dev/2012/Aug/msg00527.html
|
||||
- [iOS apps are terminated every time they enter the background if they share an encrypted database with an app extension](https://github.com/sqlcipher/sqlcipher/issues/255)
|
||||
+6
-6
@@ -14,7 +14,7 @@
|
||||
567374481B4D46600089DE44 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567374461B4D46600089DE44 /* LaunchScreen.storyboard */; };
|
||||
568E2B991CACE4ED00426E7B /* SimplePersonsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568E2B981CACE4ED00426E7B /* SimplePersonsViewController.swift */; };
|
||||
56AEC9D91CAA985700452D96 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D21CAA985700452D96 /* AppDelegate.swift */; };
|
||||
56AEC9DA1CAA985700452D96 /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D31CAA985700452D96 /* Database.swift */; };
|
||||
56AEC9DA1CAA985700452D96 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D31CAA985700452D96 /* AppDatabase.swift */; };
|
||||
56AEC9DB1CAA985700452D96 /* DemoViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D41CAA985700452D96 /* DemoViewController.swift */; };
|
||||
56AEC9DD1CAA985700452D96 /* Person.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D61CAA985700452D96 /* Person.swift */; };
|
||||
56AEC9DE1CAA985700452D96 /* PersonEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D71CAA985700452D96 /* PersonEditionViewController.swift */; };
|
||||
@@ -44,7 +44,7 @@
|
||||
567374491B4D46600089DE44 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
568E2B981CACE4ED00426E7B /* SimplePersonsViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SimplePersonsViewController.swift; sourceTree = "<group>"; };
|
||||
56AEC9D21CAA985700452D96 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
|
||||
56AEC9D31CAA985700452D96 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = "<group>"; };
|
||||
56AEC9D31CAA985700452D96 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
|
||||
56AEC9D41CAA985700452D96 /* DemoViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DemoViewController.swift; sourceTree = "<group>"; };
|
||||
56AEC9D61CAA985700452D96 /* Person.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Person.swift; sourceTree = "<group>"; };
|
||||
56AEC9D71CAA985700452D96 /* PersonEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonEditionViewController.swift; sourceTree = "<group>"; };
|
||||
@@ -85,7 +85,7 @@
|
||||
children = (
|
||||
56AEC9D21CAA985700452D96 /* AppDelegate.swift */,
|
||||
567374441B4D46600089DE44 /* Assets.xcassets */,
|
||||
56AEC9D31CAA985700452D96 /* Database.swift */,
|
||||
56AEC9D31CAA985700452D96 /* AppDatabase.swift */,
|
||||
56AEC9D41CAA985700452D96 /* DemoViewController.swift */,
|
||||
567374491B4D46600089DE44 /* Info.plist */,
|
||||
567374461B4D46600089DE44 /* LaunchScreen.storyboard */,
|
||||
@@ -193,7 +193,7 @@
|
||||
56AEC9DD1CAA985700452D96 /* Person.swift in Sources */,
|
||||
56AEC9DF1CAA985700452D96 /* PersonsViewController.swift in Sources */,
|
||||
56AEC9DB1CAA985700452D96 /* DemoViewController.swift in Sources */,
|
||||
56AEC9DA1CAA985700452D96 /* Database.swift in Sources */,
|
||||
56AEC9DA1CAA985700452D96 /* AppDatabase.swift in Sources */,
|
||||
568E2B991CACE4ED00426E7B /* SimplePersonsViewController.swift in Sources */,
|
||||
56AEC9DE1CAA985700452D96 /* PersonEditionViewController.swift in Sources */,
|
||||
56AEC9D91CAA985700452D96 /* AppDelegate.swift in Sources */,
|
||||
@@ -263,7 +263,7 @@
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 3.0;
|
||||
SWIFT_VERSION = 4.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -300,7 +300,7 @@
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_VERSION = 3.0;
|
||||
SWIFT_VERSION = 4.0;
|
||||
VALIDATE_PRODUCT = YES;
|
||||
};
|
||||
name = Release;
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
<?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 = "567374371B4D46600089DE44"
|
||||
BuildableName = "iOS.app"
|
||||
BlueprintName = "iOS"
|
||||
ReferencedContainer = "container:iOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "567374371B4D46600089DE44"
|
||||
BuildableName = "iOS.app"
|
||||
BlueprintName = "iOS"
|
||||
ReferencedContainer = "container:iOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "567374371B4D46600089DE44"
|
||||
BuildableName = "iOS.app"
|
||||
BlueprintName = "iOS"
|
||||
ReferencedContainer = "container:iOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "567374371B4D46600089DE44"
|
||||
BuildableName = "iOS.app"
|
||||
BlueprintName = "iOS"
|
||||
ReferencedContainer = "container:iOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -7,147 +7,70 @@
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
56288F841FD4256C0091310B /* GRDBCipher.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56288F7D1FD424A40091310B /* GRDBCipher.framework */; };
|
||||
56288F851FD4256C0091310B /* GRDBCipher.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56288F7D1FD424A40091310B /* GRDBCipher.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
|
||||
56B0372B1E8E31D0003B6DA4 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0372A1E8E31D0003B6DA4 /* AppDelegate.swift */; };
|
||||
56B0372D1E8E31D0003B6DA4 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0372C1E8E31D0003B6DA4 /* ViewController.swift */; };
|
||||
56B037301E8E31D0003B6DA4 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B0372E1E8E31D0003B6DA4 /* Main.storyboard */; };
|
||||
56B037321E8E31D0003B6DA4 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 56B037311E8E31D0003B6DA4 /* Assets.xcassets */; };
|
||||
56B037351E8E31D0003B6DA4 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B037331E8E31D0003B6DA4 /* LaunchScreen.storyboard */; };
|
||||
56B0373D1E8E3219003B6DA4 /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0373C1E8E3219003B6DA4 /* Database.swift */; };
|
||||
56B037791E8E328C003B6DA4 /* GRDBCipher.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0376C1E8E3250003B6DA4 /* GRDBCipher.framework */; };
|
||||
56B0377A1E8E328C003B6DA4 /* GRDBCipher.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0376C1E8E3250003B6DA4 /* GRDBCipher.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
|
||||
56B0377F1E8E32B9003B6DA4 /* Person.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0377E1E8E32B9003B6DA4 /* Person.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
56B037551E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
56288F761FD424A40091310B /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = DC3773F319C8CBB3004FCF85;
|
||||
remoteInfo = GRDBOSX;
|
||||
};
|
||||
56B037571E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56E5D7F91B4D422D00430942;
|
||||
remoteInfo = GRDBOSXTests;
|
||||
};
|
||||
56B037591E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 560C981A1C0E22D300BF8471;
|
||||
remoteInfo = GRDBOSXPerformanceTests;
|
||||
};
|
||||
56B0375B1E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56553C181C3E906C00522B5C;
|
||||
remoteInfo = GRDBOSXCrashTests;
|
||||
};
|
||||
56B0375D1E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDBCipher.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 560FC54D1CB003810014AA8E;
|
||||
remoteInfo = GRDBCipherOSX;
|
||||
};
|
||||
56B0375F1E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
56288F781FD424A40091310B /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDBCipher.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 560FC5B01CB00B880014AA8E;
|
||||
remoteInfo = GRDBCipherOSXTests;
|
||||
};
|
||||
56B037611E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
56288F7A1FD424A40091310B /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDBCipher.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 5671566C1CB16729007DC145;
|
||||
remoteInfo = GRDBCipherOSXEncryptedTests;
|
||||
};
|
||||
56B037631E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
56288F7C1FD424A40091310B /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = F3BA805A1CFB2BB2003DC1BA;
|
||||
remoteInfo = GRDBCustomSQLiteOSX;
|
||||
};
|
||||
56B037651E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = F3BA809B1CFB2F6F003DC1BA;
|
||||
remoteInfo = GRDBCustomSQLiteOSXTests;
|
||||
};
|
||||
56B037671E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56E5D7CA1B4D3FED00430942;
|
||||
remoteInfo = GRDBiOS;
|
||||
};
|
||||
56B037691E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56E5D7D31B4D3FEE00430942;
|
||||
remoteInfo = GRDBiOSTests;
|
||||
};
|
||||
56B0376B1E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDBCipher.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56AFCA231CB1A8BB00F48B96;
|
||||
remoteInfo = GRDBCipheriOS;
|
||||
};
|
||||
56B0376D1E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
56288F7E1FD424A40091310B /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDBCipher.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56AFCA7F1CB1AA9900F48B96;
|
||||
remoteInfo = GRDBCipheriOSTests;
|
||||
};
|
||||
56B0376F1E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
56288F801FD424A40091310B /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDBCipher.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56AFCAD71CB1ABC800F48B96;
|
||||
remoteInfo = GRDBCipheriOSEncryptedTests;
|
||||
};
|
||||
56B037711E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
56288F821FD424AD0091310B /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = F3BA7FFE1CFB25E4003DC1BA;
|
||||
remoteInfo = GRDBCustomSQLiteiOS;
|
||||
};
|
||||
56B037731E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = F3BA80411CFB2AD7003DC1BA;
|
||||
remoteInfo = GRDBCustomSQLiteiOSTests;
|
||||
};
|
||||
56B037751E8E3250003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 565490A01D5A4798005622CB;
|
||||
remoteInfo = GRDBWatchOS;
|
||||
};
|
||||
56B037771E8E3263003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDBCipher.xcodeproj */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 56AFC9EE1CB1A8BB00F48B96;
|
||||
remoteInfo = GRDBCipheriOS;
|
||||
};
|
||||
56B0377B1E8E328C003B6DA4 /* PBXContainerItemProxy */ = {
|
||||
56288F861FD4256C0091310B /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
|
||||
containerPortal = 56B0373E1E8E3250003B6DA4 /* GRDBCipher.xcodeproj */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 56AFC9EE1CB1A8BB00F48B96;
|
||||
remoteInfo = GRDBCipheriOS;
|
||||
@@ -161,7 +84,7 @@
|
||||
dstPath = "";
|
||||
dstSubfolderSpec = 10;
|
||||
files = (
|
||||
56B0377A1E8E328C003B6DA4 /* GRDBCipher.framework in Embed Frameworks */,
|
||||
56288F851FD4256C0091310B /* GRDBCipher.framework in Embed Frameworks */,
|
||||
);
|
||||
name = "Embed Frameworks";
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
@@ -177,7 +100,7 @@
|
||||
56B037341E8E31D0003B6DA4 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
|
||||
56B037361E8E31D0003B6DA4 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
56B0373C1E8E3219003B6DA4 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = "<group>"; };
|
||||
56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = "<group>"; };
|
||||
56B0373E1E8E3250003B6DA4 /* GRDBCipher.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDBCipher.xcodeproj; path = ../../../GRDBCipher.xcodeproj; sourceTree = "<group>"; };
|
||||
56B0377E1E8E32B9003B6DA4 /* Person.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Person.swift; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
@@ -186,17 +109,30 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
56B037791E8E328C003B6DA4 /* GRDBCipher.framework in Frameworks */,
|
||||
56288F841FD4256C0091310B /* GRDBCipher.framework in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
56288F6E1FD424A40091310B /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56288F771FD424A40091310B /* GRDBCipher.framework */,
|
||||
56288F791FD424A40091310B /* GRDBCipherOSXTests.xctest */,
|
||||
56288F7B1FD424A40091310B /* GRDBCipherOSXEncryptedTests.xctest */,
|
||||
56288F7D1FD424A40091310B /* GRDBCipher.framework */,
|
||||
56288F7F1FD424A40091310B /* GRDBCipheriOSTests.xctest */,
|
||||
56288F811FD424A40091310B /* GRDBCipheriOSEncryptedTests.xctest */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56B0371E1E8E31D0003B6DA4 = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */,
|
||||
56B0373E1E8E3250003B6DA4 /* GRDBCipher.xcodeproj */,
|
||||
56B037291E8E31D0003B6DA4 /* GRDBiOS */,
|
||||
56B037281E8E31D0003B6DA4 /* Products */,
|
||||
);
|
||||
@@ -225,30 +161,6 @@
|
||||
path = GRDBiOS;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56B0373F1E8E3250003B6DA4 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56B037561E8E3250003B6DA4 /* GRDB.framework */,
|
||||
56B037581E8E3250003B6DA4 /* GRDBOSXTests.xctest */,
|
||||
56B0375A1E8E3250003B6DA4 /* GRDBOSXPerformanceTests.xctest */,
|
||||
56B0375C1E8E3250003B6DA4 /* GRDBOSXCrashTests.xctest */,
|
||||
56B0375E1E8E3250003B6DA4 /* GRDBCipher.framework */,
|
||||
56B037601E8E3250003B6DA4 /* GRDBCipherOSXTests.xctest */,
|
||||
56B037621E8E3250003B6DA4 /* GRDBCipherOSXEncryptedTests.xctest */,
|
||||
56B037641E8E3250003B6DA4 /* GRDBCustomSQLite.framework */,
|
||||
56B037661E8E3250003B6DA4 /* GRDBCustomSQLiteOSXTests.xctest */,
|
||||
56B037681E8E3250003B6DA4 /* GRDB.framework */,
|
||||
56B0376A1E8E3250003B6DA4 /* GRDBiOSTests.xctest */,
|
||||
56B0376C1E8E3250003B6DA4 /* GRDBCipher.framework */,
|
||||
56B0376E1E8E3250003B6DA4 /* GRDBCipheriOSTests.xctest */,
|
||||
56B037701E8E3250003B6DA4 /* GRDBCipheriOSEncryptedTests.xctest */,
|
||||
56B037721E8E3250003B6DA4 /* GRDBCustomSQLite.framework */,
|
||||
56B037741E8E3250003B6DA4 /* GRDBCustomSQLiteiOSTests.xctest */,
|
||||
56B037761E8E3250003B6DA4 /* GRDB.framework */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
@@ -264,8 +176,8 @@
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
56B037781E8E3263003B6DA4 /* PBXTargetDependency */,
|
||||
56B0377C1E8E328C003B6DA4 /* PBXTargetDependency */,
|
||||
56288F831FD424AD0091310B /* PBXTargetDependency */,
|
||||
56288F871FD4256C0091310B /* PBXTargetDependency */,
|
||||
);
|
||||
name = GRDBiOS;
|
||||
productName = GRDBiOS;
|
||||
@@ -279,7 +191,7 @@
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastSwiftUpdateCheck = 0830;
|
||||
LastUpgradeCheck = 0830;
|
||||
LastUpgradeCheck = 0910;
|
||||
ORGANIZATIONNAME = "Gwendal Roué";
|
||||
TargetAttributes = {
|
||||
56B037261E8E31D0003B6DA4 = {
|
||||
@@ -302,8 +214,8 @@
|
||||
projectDirPath = "";
|
||||
projectReferences = (
|
||||
{
|
||||
ProductGroup = 56B0373F1E8E3250003B6DA4 /* Products */;
|
||||
ProjectRef = 56B0373E1E8E3250003B6DA4 /* GRDB.xcodeproj */;
|
||||
ProductGroup = 56288F6E1FD424A40091310B /* Products */;
|
||||
ProjectRef = 56B0373E1E8E3250003B6DA4 /* GRDBCipher.xcodeproj */;
|
||||
},
|
||||
);
|
||||
projectRoot = "";
|
||||
@@ -314,123 +226,46 @@
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXReferenceProxy section */
|
||||
56B037561E8E3250003B6DA4 /* GRDB.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDB.framework;
|
||||
remoteRef = 56B037551E8E3250003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B037581E8E3250003B6DA4 /* GRDBOSXTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBOSXTests.xctest;
|
||||
remoteRef = 56B037571E8E3250003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B0375A1E8E3250003B6DA4 /* GRDBOSXPerformanceTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBOSXPerformanceTests.xctest;
|
||||
remoteRef = 56B037591E8E3250003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B0375C1E8E3250003B6DA4 /* GRDBOSXCrashTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBOSXCrashTests.xctest;
|
||||
remoteRef = 56B0375B1E8E3250003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B0375E1E8E3250003B6DA4 /* GRDBCipher.framework */ = {
|
||||
56288F771FD424A40091310B /* GRDBCipher.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDBCipher.framework;
|
||||
remoteRef = 56B0375D1E8E3250003B6DA4 /* PBXContainerItemProxy */;
|
||||
remoteRef = 56288F761FD424A40091310B /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B037601E8E3250003B6DA4 /* GRDBCipherOSXTests.xctest */ = {
|
||||
56288F791FD424A40091310B /* GRDBCipherOSXTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBCipherOSXTests.xctest;
|
||||
remoteRef = 56B0375F1E8E3250003B6DA4 /* PBXContainerItemProxy */;
|
||||
remoteRef = 56288F781FD424A40091310B /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B037621E8E3250003B6DA4 /* GRDBCipherOSXEncryptedTests.xctest */ = {
|
||||
56288F7B1FD424A40091310B /* GRDBCipherOSXEncryptedTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBCipherOSXEncryptedTests.xctest;
|
||||
remoteRef = 56B037611E8E3250003B6DA4 /* PBXContainerItemProxy */;
|
||||
remoteRef = 56288F7A1FD424A40091310B /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B037641E8E3250003B6DA4 /* GRDBCustomSQLite.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDBCustomSQLite.framework;
|
||||
remoteRef = 56B037631E8E3250003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B037661E8E3250003B6DA4 /* GRDBCustomSQLiteOSXTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBCustomSQLiteOSXTests.xctest;
|
||||
remoteRef = 56B037651E8E3250003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B037681E8E3250003B6DA4 /* GRDB.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDB.framework;
|
||||
remoteRef = 56B037671E8E3250003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B0376A1E8E3250003B6DA4 /* GRDBiOSTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBiOSTests.xctest;
|
||||
remoteRef = 56B037691E8E3250003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B0376C1E8E3250003B6DA4 /* GRDBCipher.framework */ = {
|
||||
56288F7D1FD424A40091310B /* GRDBCipher.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDBCipher.framework;
|
||||
remoteRef = 56B0376B1E8E3250003B6DA4 /* PBXContainerItemProxy */;
|
||||
remoteRef = 56288F7C1FD424A40091310B /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B0376E1E8E3250003B6DA4 /* GRDBCipheriOSTests.xctest */ = {
|
||||
56288F7F1FD424A40091310B /* GRDBCipheriOSTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBCipheriOSTests.xctest;
|
||||
remoteRef = 56B0376D1E8E3250003B6DA4 /* PBXContainerItemProxy */;
|
||||
remoteRef = 56288F7E1FD424A40091310B /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B037701E8E3250003B6DA4 /* GRDBCipheriOSEncryptedTests.xctest */ = {
|
||||
56288F811FD424A40091310B /* GRDBCipheriOSEncryptedTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBCipheriOSEncryptedTests.xctest;
|
||||
remoteRef = 56B0376F1E8E3250003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B037721E8E3250003B6DA4 /* GRDBCustomSQLite.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDBCustomSQLite.framework;
|
||||
remoteRef = 56B037711E8E3250003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B037741E8E3250003B6DA4 /* GRDBCustomSQLiteiOSTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBCustomSQLiteiOSTests.xctest;
|
||||
remoteRef = 56B037731E8E3250003B6DA4 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B037761E8E3250003B6DA4 /* GRDB.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDB.framework;
|
||||
remoteRef = 56B037751E8E3250003B6DA4 /* PBXContainerItemProxy */;
|
||||
remoteRef = 56288F801FD424A40091310B /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
/* End PBXReferenceProxy section */
|
||||
@@ -463,15 +298,15 @@
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXTargetDependency section */
|
||||
56B037781E8E3263003B6DA4 /* PBXTargetDependency */ = {
|
||||
56288F831FD424AD0091310B /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = GRDBCipheriOS;
|
||||
targetProxy = 56B037771E8E3263003B6DA4 /* PBXContainerItemProxy */;
|
||||
targetProxy = 56288F821FD424AD0091310B /* PBXContainerItemProxy */;
|
||||
};
|
||||
56B0377C1E8E328C003B6DA4 /* PBXTargetDependency */ = {
|
||||
56288F871FD4256C0091310B /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = GRDBCipheriOS;
|
||||
targetProxy = 56B0377B1E8E328C003B6DA4 /* PBXContainerItemProxy */;
|
||||
targetProxy = 56288F861FD4256C0091310B /* PBXContainerItemProxy */;
|
||||
};
|
||||
/* End PBXTargetDependency section */
|
||||
|
||||
@@ -505,7 +340,9 @@
|
||||
CLANG_CXX_LIBRARY = "libc++";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
||||
@@ -513,7 +350,11 @@
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
@@ -536,7 +377,7 @@
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 10.3;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 11.1;
|
||||
MTL_ENABLE_DEBUG_INFO = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
@@ -555,7 +396,9 @@
|
||||
CLANG_CXX_LIBRARY = "libc++";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
||||
@@ -563,7 +406,11 @@
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
@@ -580,7 +427,7 @@
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 10.3;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 11.1;
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
|
||||
@@ -598,7 +445,7 @@
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBiOS;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 3.0;
|
||||
SWIFT_VERSION = 4.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -612,7 +459,7 @@
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBiOS;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 3.0;
|
||||
SWIFT_VERSION = 4.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
@@ -635,6 +482,7 @@
|
||||
56B0373B1E8E31D0003B6DA4 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0830"
|
||||
LastUpgradeVersion = "0910"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -26,6 +26,7 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
@@ -45,6 +46,7 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import XCTest
|
||||
#if GRDBCIPHER
|
||||
@testable import GRDBCipher
|
||||
#elseif GRDBCUSTOMSQLITE
|
||||
@testable import GRDBCustomSQLite
|
||||
#else
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#else
|
||||
import SQLite3
|
||||
#endif
|
||||
@testable import GRDB
|
||||
#endif
|
||||
|
||||
class ColumnInfoTests: GRDBTestCase {
|
||||
|
||||
func testColumnInfo() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("""
|
||||
CREATE TABLE t (
|
||||
a INT,
|
||||
b TEXT,
|
||||
c VARCHAR(10),
|
||||
d int DEFAULT NULL,
|
||||
e Text NOT NULL DEFAULT 'foo',
|
||||
"fooéı👨👨🏿🇫🇷🇨🇮" INT DEFAULT 0,
|
||||
g INT DEFAULT 1e6,
|
||||
h REAL DEFAULT 1.0,
|
||||
i DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
j DATE DEFAULT (DATETIME('now', 'localtime')),
|
||||
"" fooéı👨👨🏿🇫🇷🇨🇮,
|
||||
PRIMARY KEY(c, a)
|
||||
)
|
||||
""")
|
||||
let columns = try db.columns(in: "t")
|
||||
XCTAssertEqual(columns.count, 11)
|
||||
|
||||
XCTAssertEqual(columns[0].name, "a")
|
||||
XCTAssertEqual(columns[0].isNotNull, false)
|
||||
XCTAssertEqual(columns[0].type, "INT")
|
||||
// D. Richard Hipp wrote in SQLite mailing list on Tue Apr 30 22:43:47 EDT 2013 (http://mailinglists.sqlite.org/cgi-bin/mailman/private/sqlite-users/2013-April/046034.html):
|
||||
//
|
||||
// > Re: Incorrect documentation for PRAGMA table_info (pk column)
|
||||
// >
|
||||
// > For SQLite 3.7.15 and earlier, the "pk" columns meaning was undocumented
|
||||
// > and hence undefined. As it happened it was always 1. Beginning with
|
||||
// > SQLite 3.7.16 we defined the meaning of the "pk" column to be the 1-based
|
||||
// > index of the column in the primary key.
|
||||
//
|
||||
// https://sqlite.org/releaselog/3_7_16.html
|
||||
//
|
||||
// > Enhance the PRAGMA table_info command so that the "pk" column
|
||||
// > is an increasing integer to show the order of columns in the
|
||||
// > primary key.
|
||||
if sqlite3_libversion_number() < 3007016 {
|
||||
XCTAssertEqual(columns[0].primaryKeyIndex, 1)
|
||||
} else {
|
||||
XCTAssertEqual(columns[0].primaryKeyIndex, 2)
|
||||
}
|
||||
XCTAssertNil(columns[0].defaultValueSQL)
|
||||
|
||||
XCTAssertEqual(columns[1].name, "b")
|
||||
XCTAssertEqual(columns[1].isNotNull, false)
|
||||
XCTAssertEqual(columns[1].type, "TEXT")
|
||||
XCTAssertEqual(columns[1].primaryKeyIndex, 0)
|
||||
XCTAssertNil(columns[1].defaultValueSQL)
|
||||
|
||||
XCTAssertEqual(columns[2].name, "c")
|
||||
XCTAssertEqual(columns[2].isNotNull, false)
|
||||
XCTAssertEqual(columns[2].type, "VARCHAR(10)")
|
||||
XCTAssertEqual(columns[2].primaryKeyIndex, 1)
|
||||
XCTAssertNil(columns[2].defaultValueSQL)
|
||||
|
||||
XCTAssertEqual(columns[3].name, "d")
|
||||
XCTAssertEqual(columns[3].isNotNull, false)
|
||||
XCTAssertEqual(columns[3].type, "int")
|
||||
XCTAssertEqual(columns[3].primaryKeyIndex, 0)
|
||||
XCTAssertEqual(columns[3].defaultValueSQL, "NULL")
|
||||
|
||||
XCTAssertEqual(columns[4].name, "e")
|
||||
XCTAssertEqual(columns[4].isNotNull, true)
|
||||
XCTAssertEqual(columns[4].type, "Text")
|
||||
XCTAssertEqual(columns[4].primaryKeyIndex, 0)
|
||||
XCTAssertEqual(columns[4].defaultValueSQL, "'foo'")
|
||||
|
||||
XCTAssertEqual(columns[5].name, "fooéı👨👨🏿🇫🇷🇨🇮")
|
||||
XCTAssertEqual(columns[5].isNotNull, false)
|
||||
XCTAssertEqual(columns[5].type, "INT")
|
||||
XCTAssertEqual(columns[5].primaryKeyIndex, 0)
|
||||
XCTAssertEqual(columns[5].defaultValueSQL, "0")
|
||||
|
||||
XCTAssertEqual(columns[6].name, "g")
|
||||
XCTAssertEqual(columns[6].isNotNull, false)
|
||||
XCTAssertEqual(columns[6].type, "INT")
|
||||
XCTAssertEqual(columns[6].primaryKeyIndex, 0)
|
||||
XCTAssertEqual(columns[6].defaultValueSQL, "1e6")
|
||||
|
||||
XCTAssertEqual(columns[7].name, "h")
|
||||
XCTAssertEqual(columns[7].isNotNull, false)
|
||||
XCTAssertEqual(columns[7].type, "REAL")
|
||||
XCTAssertEqual(columns[7].primaryKeyIndex, 0)
|
||||
XCTAssertEqual(columns[7].defaultValueSQL, "1.0")
|
||||
|
||||
XCTAssertEqual(columns[8].name, "i")
|
||||
XCTAssertEqual(columns[8].isNotNull, false)
|
||||
XCTAssertEqual(columns[8].type, "DATETIME")
|
||||
XCTAssertEqual(columns[8].primaryKeyIndex, 0)
|
||||
XCTAssertEqual(columns[8].defaultValueSQL, "CURRENT_TIMESTAMP")
|
||||
|
||||
XCTAssertEqual(columns[9].name, "j")
|
||||
XCTAssertEqual(columns[9].isNotNull, false)
|
||||
XCTAssertEqual(columns[9].type, "DATE")
|
||||
XCTAssertEqual(columns[9].primaryKeyIndex, 0)
|
||||
XCTAssertEqual(columns[9].defaultValueSQL, "DATETIME('now', 'localtime')")
|
||||
|
||||
XCTAssertEqual(columns[10].name, "")
|
||||
XCTAssertEqual(columns[10].isNotNull, false)
|
||||
XCTAssertEqual(columns[10].type, "fooéı👨👨🏿🇫🇷🇨🇮")
|
||||
XCTAssertEqual(columns[10].primaryKeyIndex, 0)
|
||||
XCTAssertNil(columns[10].defaultValueSQL)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -192,12 +192,8 @@ private class UserTypedRequest2<T> : TypedRequest {
|
||||
private class UserTransactionObserver : TransactionObserver {
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { return false }
|
||||
func databaseDidChange(with event: DatabaseEvent) { }
|
||||
func databaseWillCommit() throws { }
|
||||
func databaseDidCommit(_ db: Database) { }
|
||||
func databaseDidRollback(_ db: Database) { }
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
func databaseWillChange(with event: DatabasePreUpdateEvent) { }
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - VirtualTableModule
|
||||
|
||||
@@ -28,6 +28,13 @@ class CursorTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testDropLast() {
|
||||
XCTAssertTrue(try IteratorCursor([1, 2, 3, 4, 5]).dropLast(0) == [1, 2, 3, 4, 5])
|
||||
XCTAssertTrue(try IteratorCursor([1, 2, 3, 4, 5]).dropLast(2) == [1, 2, 3])
|
||||
XCTAssertTrue(try IteratorCursor([1, 2, 3, 4, 5]).dropLast(10) == [])
|
||||
XCTAssertTrue(try IteratorCursor([1, 2, 3, 4, 5]).dropLast() == [1, 2, 3, 4])
|
||||
}
|
||||
|
||||
func testContainsIsLazy() {
|
||||
func makeCursor() -> AnyCursor<Int> {
|
||||
var i = 0
|
||||
@@ -103,9 +110,70 @@ class CursorTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testJoinedWithSeparator() throws {
|
||||
do {
|
||||
let x = try IteratorCursor([String]()).joined()
|
||||
XCTAssertEqual(x, "")
|
||||
}
|
||||
do {
|
||||
let x = try IteratorCursor([String]()).joined(separator: "><")
|
||||
XCTAssertEqual(x, "")
|
||||
}
|
||||
do {
|
||||
let x = try IteratorCursor(["foo"]).joined()
|
||||
XCTAssertEqual(x, "foo")
|
||||
}
|
||||
do {
|
||||
let x = try IteratorCursor(["foo"]).joined(separator: "><")
|
||||
XCTAssertEqual(x, "foo")
|
||||
}
|
||||
do {
|
||||
let x = try IteratorCursor(["foo", "bar", "baz"]).joined()
|
||||
XCTAssertEqual(x, "foobarbaz")
|
||||
}
|
||||
do {
|
||||
let x = try IteratorCursor(["foo", "bar", "baz"]).joined(separator: "><")
|
||||
XCTAssertEqual(x, "foo><bar><baz")
|
||||
}
|
||||
}
|
||||
|
||||
func testMax() {
|
||||
XCTAssertEqual(try IteratorCursor([1, 2, 3]).max(), 3)
|
||||
XCTAssertEqual(try IteratorCursor([1, 2, 3]).max(by: >), 1)
|
||||
}
|
||||
|
||||
func testMin() {
|
||||
XCTAssertEqual(try IteratorCursor([1, 2, 3]).min(), 1)
|
||||
XCTAssertEqual(try IteratorCursor([1, 2, 3]).min(by: >), 3)
|
||||
}
|
||||
|
||||
func testReduce() throws {
|
||||
let cursor = IteratorCursor([1, 2])
|
||||
let squareSum = try cursor.reduce(0) { (acc, int) in acc + int * int }
|
||||
XCTAssertEqual(squareSum, 5)
|
||||
}
|
||||
|
||||
func testReduceInto() throws {
|
||||
let cursor = IteratorCursor([1, 2])
|
||||
let squareSum = try cursor.reduce(into: 0) { (acc, int) in acc += int * int }
|
||||
XCTAssertEqual(squareSum, 5)
|
||||
}
|
||||
|
||||
func testSuffix() throws {
|
||||
do {
|
||||
let cursor = IteratorCursor([1, 2, 3, 4, 5])
|
||||
let suffix = try cursor.suffix(0)
|
||||
XCTAssertTrue(suffix == [])
|
||||
}
|
||||
do {
|
||||
let cursor = IteratorCursor([1, 2, 3, 4, 5])
|
||||
let suffix = try cursor.suffix(2)
|
||||
XCTAssertTrue(suffix == [4, 5])
|
||||
}
|
||||
do {
|
||||
let cursor = IteratorCursor([1, 2, 3, 4, 5])
|
||||
let suffix = try cursor.suffix(10)
|
||||
XCTAssertTrue(suffix == [1, 2, 3, 4, 5])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,41 @@ import XCTest
|
||||
|
||||
class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
|
||||
|
||||
func testDatabaseAfterNextTransactionCommit() throws {
|
||||
func testTransactionCompletions() throws {
|
||||
// implicit transaction
|
||||
try assertTransaction(start: "", end: "CREATE TABLE t(a)", isNotifiedAs: .commit)
|
||||
|
||||
// explicit commit
|
||||
try assertTransaction(start: "BEGIN DEFERRED TRANSACTION", end: "COMMIT", isNotifiedAs: .commit)
|
||||
try assertTransaction(start: "BEGIN DEFERRED TRANSACTION; CREATE TABLE t(a)", end: "COMMIT", isNotifiedAs: .commit)
|
||||
try assertTransaction(start: "BEGIN IMMEDIATE TRANSACTION", end: "COMMIT", isNotifiedAs: .commit)
|
||||
try assertTransaction(start: "BEGIN IMMEDIATE TRANSACTION; CREATE TABLE t(a)", end: "COMMIT", isNotifiedAs: .commit)
|
||||
try assertTransaction(start: "BEGIN EXCLUSIVE TRANSACTION", end: "COMMIT", isNotifiedAs: .commit)
|
||||
try assertTransaction(start: "BEGIN EXCLUSIVE TRANSACTION; CREATE TABLE t(a)", end: "COMMIT", isNotifiedAs: .commit)
|
||||
try assertTransaction(start: "SAVEPOINT test", end: "COMMIT", isNotifiedAs: .commit)
|
||||
try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a)", end: "COMMIT", isNotifiedAs: .commit)
|
||||
try assertTransaction(start: "SAVEPOINT test; ROLLBACK TRANSACTION TO SAVEPOINT test", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit)
|
||||
try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a); ROLLBACK TRANSACTION TO SAVEPOINT test", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit)
|
||||
try assertTransaction(start: "SAVEPOINT test", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit)
|
||||
try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a)", end: "RELEASE SAVEPOINT test", isNotifiedAs: .commit)
|
||||
|
||||
// explicit rollback
|
||||
try assertTransaction(start: "BEGIN DEFERRED TRANSACTION", end: "ROLLBACK", isNotifiedAs: .rollback)
|
||||
try assertTransaction(start: "BEGIN DEFERRED TRANSACTION; CREATE TABLE t(a)", end: "ROLLBACK", isNotifiedAs: .rollback)
|
||||
try assertTransaction(start: "BEGIN IMMEDIATE TRANSACTION", end: "ROLLBACK", isNotifiedAs: .rollback)
|
||||
try assertTransaction(start: "BEGIN IMMEDIATE TRANSACTION; CREATE TABLE t(a)", end: "ROLLBACK", isNotifiedAs: .rollback)
|
||||
try assertTransaction(start: "BEGIN EXCLUSIVE TRANSACTION", end: "ROLLBACK", isNotifiedAs: .rollback)
|
||||
try assertTransaction(start: "BEGIN EXCLUSIVE TRANSACTION; CREATE TABLE t(a)", end: "ROLLBACK", isNotifiedAs: .rollback)
|
||||
try assertTransaction(start: "SAVEPOINT test", end: "ROLLBACK", isNotifiedAs: .rollback)
|
||||
try assertTransaction(start: "SAVEPOINT test; CREATE TABLE t(a)", end: "ROLLBACK", isNotifiedAs: .rollback)
|
||||
}
|
||||
|
||||
func assertTransaction(start startSQL: String, end endSQL: String, isNotifiedAs expectedCompletion: Database.TransactionCompletion) throws {
|
||||
try assertTransaction_registerBefore(start: startSQL, end: endSQL, isNotifiedAs: expectedCompletion)
|
||||
try assertTransaction_registerBetween(start: startSQL, end: endSQL, isNotifiedAs: expectedCompletion)
|
||||
}
|
||||
|
||||
func assertTransaction_registerBefore(start startSQL: String, end endSQL: String, isNotifiedAs expectedCompletion: Database.TransactionCompletion) throws {
|
||||
class Witness { }
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
@@ -26,23 +60,39 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
XCTAssertNotNil(deallocationWitness)
|
||||
XCTAssertEqual(transactionCount, 0)
|
||||
|
||||
try db.inTransaction { .commit }
|
||||
XCTAssertEqual(transactionCount, 1)
|
||||
try db.execute(startSQL)
|
||||
try db.execute(endSQL)
|
||||
switch expectedCompletion {
|
||||
case .commit:
|
||||
XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)")
|
||||
case .rollback:
|
||||
XCTAssertEqual(transactionCount, 0, "\(startSQL); \(endSQL)")
|
||||
}
|
||||
XCTAssertNil(deallocationWitness)
|
||||
|
||||
try db.inTransaction { .commit }
|
||||
XCTAssertEqual(transactionCount, 1)
|
||||
try db.inTransaction {
|
||||
try db.execute("DROP TABLE IF EXISTS t; CREATE TABLE t(a); ")
|
||||
return .commit
|
||||
}
|
||||
switch expectedCompletion {
|
||||
case .commit:
|
||||
XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)")
|
||||
case .rollback:
|
||||
XCTAssertEqual(transactionCount, 0, "\(startSQL); \(endSQL)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabaseAfterNextTransactionCommitWithRollback() throws {
|
||||
func assertTransaction_registerBetween(start startSQL: String, end endSQL: String, isNotifiedAs expectedCompletion: Database.TransactionCompletion) throws {
|
||||
class Witness { }
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
var transactionCount = 0
|
||||
try db.execute(startSQL)
|
||||
|
||||
weak var deallocationWitness: Witness? = nil
|
||||
do {
|
||||
let witness = Witness()
|
||||
@@ -54,14 +104,27 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
XCTAssertNotNil(deallocationWitness)
|
||||
XCTAssertEqual(transactionCount, 0)
|
||||
|
||||
try db.inTransaction { .rollback }
|
||||
XCTAssertEqual(transactionCount, 0)
|
||||
try db.execute(endSQL)
|
||||
switch expectedCompletion {
|
||||
case .commit:
|
||||
XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)")
|
||||
case .rollback:
|
||||
XCTAssertEqual(transactionCount, 0, "\(startSQL); \(endSQL)")
|
||||
}
|
||||
XCTAssertNil(deallocationWitness)
|
||||
|
||||
try db.inTransaction { .commit }
|
||||
XCTAssertEqual(transactionCount, 0)
|
||||
try db.inTransaction {
|
||||
try db.execute("DROP TABLE IF EXISTS t; CREATE TABLE t(a); ")
|
||||
return .commit
|
||||
}
|
||||
switch expectedCompletion {
|
||||
case .commit:
|
||||
XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)")
|
||||
case .rollback:
|
||||
XCTAssertEqual(transactionCount, 0, "\(startSQL); \(endSQL)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,23 +10,11 @@ import XCTest
|
||||
class DatabaseLogErrorTests: GRDBTestCase {
|
||||
|
||||
func testErrorLog() throws {
|
||||
// Remember current log function
|
||||
let currentLogError = Database.logError
|
||||
|
||||
var lastResultCode: ResultCode? = nil
|
||||
var lastMessage: String? = nil
|
||||
Database.logError = { (resultCode, message) in
|
||||
lastResultCode = resultCode
|
||||
lastMessage = message
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
dbQueue.inDatabase { db in
|
||||
_ = try? db.execute("That's not SQL.")
|
||||
}
|
||||
XCTAssertEqual(lastResultCode!, ResultCode.SQLITE_ERROR)
|
||||
XCTAssertEqual(lastMessage!, "near \"That\": syntax error")
|
||||
|
||||
// Restore current log function
|
||||
Database.logError = currentLogError
|
||||
}
|
||||
}
|
||||
@@ -865,6 +865,38 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testLongRunningReadTransaction() throws {
|
||||
// A test for a "user-defined" DatabaseSnapshot based on DatabaseQueue
|
||||
let dbName = "test.sqlite"
|
||||
let dbPool = try makeDatabasePool(filename: dbName)
|
||||
dbConfiguration.allowsUnsafeTransactions = true
|
||||
dbConfiguration.readonly = true
|
||||
let dbQueue = try makeDatabaseQueue(filename: dbName)
|
||||
|
||||
try dbPool.write { db in
|
||||
try db.create(table: "t") { $0.column("id", .integer).primaryKey() }
|
||||
try db.execute("INSERT INTO t DEFAULT VALUES")
|
||||
}
|
||||
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.beginTransaction(.deferred)
|
||||
}
|
||||
|
||||
try dbQueue.inDatabase { db in
|
||||
try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 1)
|
||||
}
|
||||
|
||||
try dbPool.write { db in
|
||||
try db.execute("INSERT INTO t DEFAULT VALUES")
|
||||
}
|
||||
|
||||
try dbQueue.inDatabase { db in
|
||||
try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 1)
|
||||
try db.rollback()
|
||||
try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 2)
|
||||
}
|
||||
}
|
||||
|
||||
func testIssue80() throws {
|
||||
// See https://github.com/groue/GRDB.swift/issues/80
|
||||
|
||||
@@ -33,28 +33,9 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
|
||||
|
||||
try dbPool.read { db in
|
||||
// Warm cache in a reader
|
||||
let primaryKey = try db.primaryKey("items")
|
||||
XCTAssertEqual(primaryKey.rowIDColumn, "id")
|
||||
|
||||
let columns = try db.columns(in: "items")
|
||||
XCTAssertEqual(columns.count, 4)
|
||||
XCTAssertEqual(columns[0].name, "id")
|
||||
XCTAssertEqual(columns[1].name, "email")
|
||||
XCTAssertEqual(columns[2].name, "foo")
|
||||
XCTAssertEqual(columns[3].name, "bar")
|
||||
|
||||
let indexes = try db.indexes(on: "items")
|
||||
XCTAssertEqual(indexes.count, 2)
|
||||
for index in indexes {
|
||||
switch index.name {
|
||||
case "foobar":
|
||||
XCTAssertEqual(index.columns, ["foo", "bar"])
|
||||
XCTAssertFalse(index.isUnique)
|
||||
default:
|
||||
XCTAssertEqual(index.columns, ["email"])
|
||||
XCTAssertTrue(index.isUnique)
|
||||
}
|
||||
}
|
||||
_ = try db.primaryKey("items")
|
||||
_ = try db.columns(in: "items")
|
||||
_ = try db.indexes(on: "items")
|
||||
|
||||
// Assert that reader cache is warmed
|
||||
XCTAssertTrue(db.schemaCache.primaryKey("items") != nil)
|
||||
@@ -62,7 +43,12 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
|
||||
XCTAssertTrue(db.schemaCache.indexes(on: "items") != nil)
|
||||
}
|
||||
|
||||
dbPool.write { db in
|
||||
try dbPool.write { db in
|
||||
// Warm cache in the writer
|
||||
_ = try db.primaryKey("items")
|
||||
_ = try db.columns(in: "items")
|
||||
_ = try db.indexes(on: "items")
|
||||
|
||||
// Assert that writer cache is warmed
|
||||
XCTAssertTrue(db.schemaCache.primaryKey("items") != nil)
|
||||
XCTAssertTrue(db.schemaCache.columns(in: "items") != nil)
|
||||
@@ -137,4 +123,95 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
|
||||
blocks[index]()
|
||||
}
|
||||
}
|
||||
|
||||
func testCacheSnapshotIsolation() throws {
|
||||
// This test checks that the schema cache follows snapshot isolation.
|
||||
// and that writer and readers do not naively share the same cache.
|
||||
dbConfiguration.trace = { print($0) }
|
||||
let dbPool = try makeDatabasePool()
|
||||
|
||||
// writer reader
|
||||
// CREATE TABLE foo
|
||||
// table exists: true
|
||||
// >
|
||||
let s1 = DispatchSemaphore(value: 0)
|
||||
// table exists: true
|
||||
// <
|
||||
let s2 = DispatchSemaphore(value: 0)
|
||||
// DROP TABLE foo
|
||||
// table exists: false
|
||||
// >
|
||||
let s3 = DispatchSemaphore(value: 0)
|
||||
// table exists: true
|
||||
// <
|
||||
let s4 = DispatchSemaphore(value: 0)
|
||||
// table exists: false
|
||||
|
||||
let block1 = { () in
|
||||
try! dbPool.write { db in
|
||||
try db.execute("CREATE TABLE foo(id INTEGER PRIMARY KEY)")
|
||||
// warm cache
|
||||
_ = try db.primaryKey("foo")
|
||||
// cache contains the primary key
|
||||
XCTAssertNotNil(db.schemaCache.primaryKey("foo"))
|
||||
s1.signal()
|
||||
_ = s2.wait(timeout: .distantFuture)
|
||||
try db.execute("DROP TABLE foo")
|
||||
// cache does not contain the primary key
|
||||
XCTAssertNil(db.schemaCache.primaryKey("foo"))
|
||||
s3.signal()
|
||||
_ = s4.wait(timeout: .distantFuture)
|
||||
// cache does not contain the primary key
|
||||
XCTAssertNil(db.schemaCache.primaryKey("foo"))
|
||||
}
|
||||
}
|
||||
let block2 = { () in
|
||||
_ = s1.wait(timeout: .distantFuture)
|
||||
try! dbPool.read { db in
|
||||
// activate snapshot isolation so that foo table is visible during the whole read. Any read is enough.
|
||||
try db.makeSelectStatement("SELECT * FROM sqlite_master").cursor().next()
|
||||
// warm cache
|
||||
_ = try db.primaryKey("foo")
|
||||
// cache contains the primary key
|
||||
XCTAssertNotNil(db.schemaCache.primaryKey("foo"))
|
||||
s2.signal()
|
||||
_ = s3.wait(timeout: .distantFuture)
|
||||
// cache contains the primary key
|
||||
XCTAssertNotNil(db.schemaCache.primaryKey("foo"))
|
||||
// warm cache if needed
|
||||
_ = try db.primaryKey("foo")
|
||||
s4.signal()
|
||||
}
|
||||
}
|
||||
let blocks = [block1, block2]
|
||||
DispatchQueue.concurrentPerform(iterations: blocks.count) { index in
|
||||
blocks[index]()
|
||||
}
|
||||
}
|
||||
|
||||
func testUnsafeReaderHasNoDatabaseCache() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
|
||||
try dbPool.write { db in
|
||||
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY, email TEXT UNIQUE, foo INT, bar DOUBLE)")
|
||||
try db.execute("CREATE INDEX foobar ON items(foo, bar)")
|
||||
}
|
||||
|
||||
try dbPool.unsafeRead { db in
|
||||
// Assert that a cache is empty
|
||||
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
|
||||
XCTAssertTrue(db.schemaCache.columns(in: "items") == nil)
|
||||
XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil)
|
||||
|
||||
// Warm cache in a reader
|
||||
_ = try db.primaryKey("items")
|
||||
_ = try db.columns(in: "items")
|
||||
_ = try db.indexes(on: "items")
|
||||
|
||||
// Assert that a reader cache is still empty
|
||||
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
|
||||
XCTAssertTrue(db.schemaCache.columns(in: "items") == nil)
|
||||
XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,7 @@ class ConcurrencyTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
func testDeferredTransactionConcurrency() throws {
|
||||
let dbQueue1 = try makeDatabaseQueue()
|
||||
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
#if GRDBCIPHER_USE_ENCRYPTION
|
||||
// Work around SQLCipher bug when two connections are open to the
|
||||
// same empty database: make sure the database is not empty before
|
||||
@@ -48,7 +48,7 @@ class ConcurrencyTests: GRDBTestCase {
|
||||
try db.execute("CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
|
||||
}
|
||||
#endif
|
||||
let dbQueue2 = try makeDatabaseQueue()
|
||||
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
|
||||
// Queue 1 Queue 2
|
||||
// BEGIN DEFERRED TRANSACTION
|
||||
@@ -118,8 +118,8 @@ class ConcurrencyTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
func testExclusiveTransactionConcurrency() throws {
|
||||
let dbQueue1 = try makeDatabaseQueue()
|
||||
let dbQueue2 = try makeDatabaseQueue()
|
||||
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
|
||||
// Queue 1 Queue 2
|
||||
// BEGIN EXCLUSIVE TRANSACTION
|
||||
@@ -174,8 +174,8 @@ class ConcurrencyTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
func testImmediateTransactionConcurrency() throws {
|
||||
let dbQueue1 = try makeDatabaseQueue()
|
||||
let dbQueue2 = try makeDatabaseQueue()
|
||||
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
|
||||
// Queue 1 Queue 2
|
||||
// BEGIN IMMEDIATE TRANSACTION
|
||||
@@ -230,7 +230,7 @@ class ConcurrencyTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
func testBusyCallback() throws {
|
||||
let dbQueue1 = try makeDatabaseQueue()
|
||||
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
#if GRDBCIPHER_USE_ENCRYPTION
|
||||
// Work around SQLCipher bug when two connections are open to the
|
||||
// same empty database: make sure the database is not empty before
|
||||
@@ -239,7 +239,7 @@ class ConcurrencyTests: GRDBTestCase {
|
||||
try db.execute("CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
|
||||
}
|
||||
#endif
|
||||
let dbQueue2 = try makeDatabaseQueue()
|
||||
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
|
||||
// Queue 1 Queue 2
|
||||
// BEGIN EXCLUSIVE TRANSACTION
|
||||
@@ -293,7 +293,7 @@ class ConcurrencyTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
func testReaderDuringDefaultTransaction() throws {
|
||||
let dbQueue1 = try makeDatabaseQueue()
|
||||
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
#if GRDBCIPHER_USE_ENCRYPTION
|
||||
// Work around SQLCipher bug when two connections are open to the
|
||||
// same empty database: make sure the database is not empty before
|
||||
@@ -302,7 +302,7 @@ class ConcurrencyTests: GRDBTestCase {
|
||||
try db.execute("CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
|
||||
}
|
||||
#endif
|
||||
let dbQueue2 = try makeDatabaseQueue()
|
||||
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
|
||||
// Here we test that a reader can read while a writer is writing.
|
||||
|
||||
@@ -359,7 +359,7 @@ class ConcurrencyTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
func testReaderInDeferredTransactionDuringDefaultTransaction() throws {
|
||||
let dbQueue1 = try makeDatabaseQueue()
|
||||
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
#if GRDBCIPHER_USE_ENCRYPTION
|
||||
// Work around SQLCipher bug when two connections are open to the
|
||||
// same empty database: make sure the database is not empty before
|
||||
@@ -368,7 +368,7 @@ class ConcurrencyTests: GRDBTestCase {
|
||||
try db.execute("CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
|
||||
}
|
||||
#endif
|
||||
let dbQueue2 = try makeDatabaseQueue()
|
||||
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
|
||||
// The `SELECT * FROM stuffs` statement of Queue 2 prevents Queue 1
|
||||
// from committing with SQLITE_BUSY.
|
||||
|
||||
@@ -12,12 +12,12 @@ class DatabaseQueueReadOnlyTests : GRDBTestCase {
|
||||
func testReadOnlyDatabaseCanNotBeModified() throws {
|
||||
// Create database
|
||||
do {
|
||||
_ = try makeDatabaseQueue()
|
||||
_ = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
}
|
||||
|
||||
// Open it again, readonly
|
||||
dbConfiguration.readonly = true
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
let statement = try dbQueue.inDatabase { db in
|
||||
try db.makeUpdateStatement("CREATE TABLE items (id INTEGER PRIMARY KEY)")
|
||||
}
|
||||
|
||||
@@ -90,4 +90,17 @@ class DatabaseQueueTests: GRDBTestCase {
|
||||
XCTAssertEqual(error.description.lowercased(), "sqlite error 1 with statement `create table files_fail (name text collate test_collation_foo)`: no such collation sequence: test_collation_foo")
|
||||
}
|
||||
}
|
||||
|
||||
func testAllowsUnsafeTransactions() throws {
|
||||
dbConfiguration.allowsUnsafeTransactions = true
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.beginTransaction()
|
||||
}
|
||||
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.commit()
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 153 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user