mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-06 05:28:44 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ebeb7bc969 | ||
|
|
6ccac5f69c | ||
|
|
cc41b8b259 | ||
|
|
db1a3456b7 | ||
|
|
1b9305c073 | ||
|
|
a33814ef40 | ||
|
|
581bc9f27c | ||
|
|
40cff0053f | ||
|
|
cc33b12b0d | ||
|
|
2add1c68ea | ||
|
|
380b6676a6 | ||
|
|
f133a36477 | ||
|
|
5f2d6f8e2f | ||
|
|
a72c207ec5 | ||
|
|
ae3c28dee1 | ||
|
|
bd919e5209 | ||
|
|
d1697756e9 | ||
|
|
83c3745165 | ||
|
|
56a4a964b7 | ||
|
|
c9a02faf08 | ||
|
|
e59388738e | ||
|
|
c8368d98eb | ||
|
|
d12dad2e34 | ||
|
|
1ee8c73562 | ||
|
|
ad8de84257 | ||
|
|
48398b4913 | ||
|
|
d719fe4612 | ||
|
|
034a30b444 | ||
|
|
9609e2ac4c | ||
|
|
66c2b72a28 | ||
|
|
da48b0880e | ||
|
|
4134b1549a | ||
|
|
7265b2535b | ||
|
|
bb638377ac | ||
|
|
466113fc4a | ||
|
|
31aea350cb | ||
|
|
56869577d4 | ||
|
|
ed3c597a92 | ||
|
|
cbb607b6b0 | ||
|
|
7f64abe820 | ||
|
|
b43dc1ba37 | ||
|
|
59962e5e88 | ||
|
|
8eabcecb69 | ||
|
|
a3ad726111 | ||
|
|
a46b4edb0a | ||
|
|
7059fe3815 | ||
|
|
780f1afe91 | ||
|
|
2459b4e56f | ||
|
|
f750cee594 | ||
|
|
1c3824f4b9 | ||
|
|
5ba1fa856d | ||
|
|
f40a685ac9 | ||
|
|
bf3b6577d5 | ||
|
|
7b0659332b | ||
|
|
19812cb015 | ||
|
|
b283c80776 | ||
|
|
49838c67ee | ||
|
|
4a40bddd82 | ||
|
|
208b7860aa | ||
|
|
05e7c9470b | ||
|
|
2f79d5f805 | ||
|
|
1f120a04f9 | ||
|
|
90a46f6556 | ||
|
|
4dff14a02a | ||
|
|
d9a9acb616 | ||
|
|
8ea215931e | ||
|
|
6caed6aacc | ||
|
|
0c192fcb57 | ||
|
|
3e819a5051 | ||
|
|
b31983cc3a | ||
|
|
e24cb1783c | ||
|
|
a913aba018 | ||
|
|
35d34ab524 | ||
|
|
604cf6b522 | ||
|
|
e987695732 | ||
|
|
09f37a86ad | ||
|
|
ff32f99610 | ||
|
|
4cd099ef30 | ||
|
|
54d3b0eabc | ||
|
|
b3d731b040 | ||
|
|
6629ec48a3 | ||
|
|
19c273771d | ||
|
|
e7b6919bc1 | ||
|
|
60e6c7d250 | ||
|
|
4feeb0e608 | ||
|
|
b3243efdf5 | ||
|
|
60a23bb280 | ||
|
|
973f38727d | ||
|
|
deaac5808d | ||
|
|
22dc01610e | ||
|
|
fe702d8fea | ||
|
|
10e669423f | ||
|
|
fbf146657e | ||
|
|
8667fab206 | ||
|
|
e974cd4b33 | ||
|
|
43c96803be | ||
|
|
70b42a5633 | ||
|
|
9f989f7706 | ||
|
|
4d976ef803 | ||
|
|
02257fd78f | ||
|
|
929c8f49a6 | ||
|
|
a6ec38c805 | ||
|
|
e5ec8ea3b2 | ||
|
|
36ac5a2802 | ||
|
|
b5beff5030 | ||
|
|
d1d1a5da77 | ||
|
|
713d58612e | ||
|
|
bd0990deb4 | ||
|
|
35e8d9c12b | ||
|
|
1fb7f9ff5b | ||
|
|
7eecb059e6 | ||
|
|
ba8375adb1 | ||
|
|
2ef547c461 | ||
|
|
a34784ca73 | ||
|
|
5594d46c2d | ||
|
|
dc7a1e3f41 | ||
|
|
68732487f9 | ||
|
|
5ea1d4376d | ||
|
|
9cb8b205c5 | ||
|
|
a35c453423 | ||
|
|
e7f91d7c25 | ||
|
|
4886f43463 | ||
|
|
929c8ac2b5 | ||
|
|
1438934aa6 | ||
|
|
ec65335fcd | ||
|
|
39d31dbd11 | ||
|
|
6c5be7a169 | ||
|
|
b45894fd51 | ||
|
|
a660b4e5c4 | ||
|
|
e11c88cf05 | ||
|
|
40f930f08a | ||
|
|
0c55e7819d | ||
|
|
3c17ee941f | ||
|
|
5a67ca0411 | ||
|
|
63d04a6707 | ||
|
|
676a116cda | ||
|
|
55435fd324 | ||
|
|
612f8059b8 | ||
|
|
ffd16f7639 | ||
|
|
528860161e | ||
|
|
1fe6094da5 | ||
|
|
399c51b1ee | ||
|
|
55e4abd534 | ||
|
|
e9d02f441b | ||
|
|
f858bcbe5b | ||
|
|
cd107711a9 | ||
|
|
ce4c20b112 | ||
|
|
0b8ba1ccfa | ||
|
|
c72c97fd53 | ||
|
|
1e12068e64 | ||
|
|
1799fe1ff9 | ||
|
|
ae5175c5b4 | ||
|
|
86d5b0b23d | ||
|
|
341044356f | ||
|
|
5eb7a62062 | ||
|
|
74f96c0766 | ||
|
|
49b62cb27a | ||
|
|
798588c54b | ||
|
|
f1a9cdaa8e | ||
|
|
c66c0a11b6 | ||
|
|
b1cdd1360b | ||
|
|
7c8b48e08a | ||
|
|
64df5c6b41 | ||
|
|
a5c1361dc9 | ||
|
|
798b1a7d2e | ||
|
|
e484e4c6de | ||
|
|
31299a529a | ||
|
|
53ac681d49 | ||
|
|
828ef48441 | ||
|
|
63e8742fb1 | ||
|
|
192a958fdc | ||
|
|
f606e633da | ||
|
|
e2d2b031a5 | ||
|
|
c203a972ff | ||
|
|
44df1aa0bd | ||
|
|
d010587f44 | ||
|
|
840525c11a | ||
|
|
a0881d851c | ||
|
|
ac00e05a72 | ||
|
|
4938568ea7 | ||
|
|
cb4c07a5fb | ||
|
|
4edd76341e | ||
|
|
bb8aee8965 | ||
|
|
5d97d2d680 | ||
|
|
3eb2646cad | ||
|
|
96c3dadb7b | ||
|
|
4d9a238c27 | ||
|
|
a475cfa340 | ||
|
|
e54cec9123 | ||
|
|
3edad29501 | ||
|
|
392a004bd1 | ||
|
|
7f8ec17511 | ||
|
|
d9e6fd3b89 | ||
|
|
6cf59838a6 | ||
|
|
3efa60ce8a | ||
|
|
7a90cd2562 | ||
|
|
4cdbe4f0f4 | ||
|
|
595408b351 | ||
|
|
4ee1fd9f65 | ||
|
|
f16f4d557a | ||
|
|
27314d1af3 | ||
|
|
4f14fb0ccd | ||
|
|
9b2a8f847f | ||
|
|
dae4ae1c6b | ||
|
|
c8023adff1 | ||
|
|
c34ac0f17b | ||
|
|
2222a1bfe2 | ||
|
|
3134809c22 | ||
|
|
203e8c41ce | ||
|
|
5804c044d5 | ||
|
|
80c378df21 | ||
|
|
0f3bc5922d | ||
|
|
1810edfa6e | ||
|
|
362b8d3243 | ||
|
|
b06f76512d | ||
|
|
6c2b421b57 | ||
|
|
63b3b4225a | ||
|
|
5b7ad40163 | ||
|
|
1751fb38e5 | ||
|
|
184a2bcf18 | ||
|
|
57fce9d20f | ||
|
|
d354157c0e | ||
|
|
de78e065cb | ||
|
|
17a49b5d8c | ||
|
|
6c6bbf6294 | ||
|
|
72f04367d9 | ||
|
|
7395305f87 | ||
|
|
1c62a665c7 | ||
|
|
518919aeee | ||
|
|
da798b3748 | ||
|
|
441e936d88 | ||
|
|
23def44101 | ||
|
|
35fafdb476 | ||
|
|
0e20e6a0bb | ||
|
|
04654a5c85 | ||
|
|
e17c4e5271 | ||
|
|
4d79b35c47 | ||
|
|
26aeb7dcbd | ||
|
|
7bc3582525 | ||
|
|
1ad00e1102 | ||
|
|
311ad6b940 | ||
|
|
c65f3289a3 | ||
|
|
cfeaf2f376 | ||
|
|
8434e856f4 | ||
|
|
35a700027c | ||
|
|
2196158f58 | ||
|
|
56d5ca180a | ||
|
|
60326b8f65 | ||
|
|
363943583d | ||
|
|
4348889865 | ||
|
|
50e50e82e1 | ||
|
|
fd30f16364 | ||
|
|
21879db549 | ||
|
|
313b9d64f6 | ||
|
|
87be97a38d | ||
|
|
4f5054d792 | ||
|
|
51545c4db0 | ||
|
|
98fb48eb1d | ||
|
|
fa2817ab52 | ||
|
|
2a35601ff4 | ||
|
|
ed70058a1f | ||
|
|
79a1b65547 | ||
|
|
cccddd8455 | ||
|
|
9a4d9f7f1f | ||
|
|
c532f40b7d | ||
|
|
d7e68c340c | ||
|
|
42a985112a | ||
|
|
16a653ed9d | ||
|
|
91f18323be | ||
|
|
09bbb50e1f | ||
|
|
a4eebfeeb2 | ||
|
|
62d19c9d11 | ||
|
|
07142b3052 | ||
|
|
a304bc0eed | ||
|
|
857b7e53d9 | ||
|
|
2987bb129c | ||
|
|
8da9ad696b | ||
|
|
8720d6937a | ||
|
|
9262834ffb | ||
|
|
a41b1a5a2d | ||
|
|
1e362fdd53 | ||
|
|
8dfe166944 | ||
|
|
8d0feea2c2 | ||
|
|
47d9f5920f | ||
|
|
25eca4146c | ||
|
|
61938601fd | ||
|
|
61d114f297 | ||
|
|
eddebfbba5 | ||
|
|
323d828eb7 | ||
|
|
bb763f7315 | ||
|
|
b1d93112da | ||
|
|
56bd3513a3 | ||
|
|
ddcf26058b | ||
|
|
ba4ee3f1fc | ||
|
|
dedfd5cd33 | ||
|
|
b5296f4206 | ||
|
|
e2e2c58d9f | ||
|
|
7a90b9ce23 | ||
|
|
ae0928e686 | ||
|
|
b815ad7a8c | ||
|
|
06cca9033a | ||
|
|
5302364139 | ||
|
|
78b7fc6169 | ||
|
|
b159c30cf1 | ||
|
|
5c7712bf6c | ||
|
|
e64b766599 | ||
|
|
89a852286c | ||
|
|
1e312cfbb1 | ||
|
|
8d4522227c | ||
|
|
eee39a7c0b | ||
|
|
bd58c18bb0 | ||
|
|
685b3a4f21 | ||
|
|
4e82a482d1 | ||
|
|
1214e28563 | ||
|
|
9170ed6e3a | ||
|
|
f2bb8bb8af | ||
|
|
24d74698ef | ||
|
|
ba615c15cb | ||
|
|
88f206e7f5 | ||
|
|
511740ccd7 | ||
|
|
7a2fab1126 | ||
|
|
fd435f0941 | ||
|
|
ffd5a8b321 | ||
|
|
5454e43bc4 | ||
|
|
a94fd2d127 | ||
|
|
14c53c5e3e | ||
|
|
b25648eea1 | ||
|
|
10d0d162b5 | ||
|
|
e5b2be4346 | ||
|
|
4cea442b59 | ||
|
|
532f682fc7 | ||
|
|
c2cd689c32 | ||
|
|
c3e986eb56 | ||
|
|
d91f4c244f | ||
|
|
22b768963f | ||
|
|
57354cd1ef | ||
|
|
c74cc40d5c | ||
|
|
b867a74b6b | ||
|
|
7a10486492 | ||
|
|
f36b833654 | ||
|
|
ef9206088e | ||
|
|
e141b26411 | ||
|
|
1f4da13060 | ||
|
|
4ec85e2f25 | ||
|
|
842831d729 | ||
|
|
39a0b5672b | ||
|
|
2729892676 | ||
|
|
50318354a6 | ||
|
|
77593c8031 | ||
|
|
3bfb9adb99 | ||
|
|
deebf289de | ||
|
|
d4e777900c | ||
|
|
1b44683cfe | ||
|
|
0ff53f0bd7 | ||
|
|
a5cbf08a76 | ||
|
|
023fa8afc9 | ||
|
|
a721748de1 | ||
|
|
ad112285e6 | ||
|
|
fe05ac9753 | ||
|
|
b873162a6f | ||
|
|
846604cce5 | ||
|
|
b1ea970f62 | ||
|
|
5bcfb7f488 | ||
|
|
1908f1b4f6 | ||
|
|
b0bf8e81aa | ||
|
|
4866ba0c84 | ||
|
|
8dadf42504 | ||
|
|
fc18b15106 | ||
|
|
9b4e55be28 | ||
|
|
8a4686984a | ||
|
|
42ebffc4fc | ||
|
|
2d2c596f75 | ||
|
|
fa464b489d | ||
|
|
b531504912 | ||
|
|
e4a346995b | ||
|
|
f0d1f2387d | ||
|
|
7eb592df79 | ||
|
|
a704c0ad35 | ||
|
|
acf4077878 | ||
|
|
ba50771007 | ||
|
|
898db8b7d4 | ||
|
|
d452a00592 | ||
|
|
4ab8fb359b | ||
|
|
29e6082663 | ||
|
|
7c6197b1fc | ||
|
|
1e0e40912b | ||
|
|
ff84638df8 | ||
|
|
90dee9c171 | ||
|
|
53873c7864 | ||
|
|
f60a9708b2 | ||
|
|
84497bfba7 | ||
|
|
4dfd672c04 | ||
|
|
d8b64aa2f4 | ||
|
|
4968100420 | ||
|
|
b52687f356 | ||
|
|
71d4565aa5 | ||
|
|
42ff295092 | ||
|
|
f0758e2a6c | ||
|
|
33e93ea156 | ||
|
|
9f212184fd | ||
|
|
1c16d4bd3f | ||
|
|
0008ffc735 | ||
|
|
e5dce929bb | ||
|
|
40bcf96c2b | ||
|
|
519d4470e3 | ||
|
|
cdf18b5480 | ||
|
|
dbe4965438 | ||
|
|
899b9b07dd | ||
|
|
54d8a03e87 | ||
|
|
052ad87da0 | ||
|
|
2a515b1d8d | ||
|
|
dad48df039 | ||
|
|
ee798df57d | ||
|
|
eed21b8f8f | ||
|
|
29938f5703 | ||
|
|
52bcf97d73 | ||
|
|
9934184f5f | ||
|
|
fdf33cbf81 | ||
|
|
34458bc86e | ||
|
|
9b061b3aa7 | ||
|
|
2fa6acef1c | ||
|
|
3afb1f145a | ||
|
|
b03b75d125 | ||
|
|
b9756f0bdc | ||
|
|
c3234cb79f | ||
|
|
828ab97837 | ||
|
|
ac66510f32 | ||
|
|
599397b6f7 | ||
|
|
e230f5d358 | ||
|
|
91486f1b70 | ||
|
|
95e6de8654 | ||
|
|
784baaec46 | ||
|
|
6adaca568f | ||
|
|
bcdcceb809 | ||
|
|
de3d075ff2 | ||
|
|
c5f3aa21b3 | ||
|
|
9831b0e3d4 | ||
|
|
24a8df801f | ||
|
|
e0cfd404a1 | ||
|
|
0e62c3455b | ||
|
|
9cd5a7926a | ||
|
|
8e4995c8d9 | ||
|
|
ca5fc1e8fc | ||
|
|
14dca4667a | ||
|
|
ebff14adac | ||
|
|
51f02ed46e | ||
|
|
03740d0918 | ||
|
|
c83a16e22e | ||
|
|
e1bf662884 | ||
|
|
d866bc9044 | ||
|
|
fd0e4c20ee | ||
|
|
55ca0a80b6 | ||
|
|
eeaf3dc2cf | ||
|
|
467b948349 | ||
|
|
f368af3d02 | ||
|
|
0f34ee7d16 | ||
|
|
2fe89fc41b | ||
|
|
968942f128 | ||
|
|
b5fae096a9 | ||
|
|
5cad9a1071 | ||
|
|
f4a350c3d0 | ||
|
|
89885ed4d9 |
No files matched your search
@@ -0,0 +1,4 @@
|
||||
source 'https://rubygems.org'
|
||||
|
||||
gem 'xcpretty'
|
||||
gem 'xcpretty-travis-formatter'
|
||||
+12
@@ -99,3 +99,15 @@ xcuserdata
|
||||
# GRDBCustomSQLite USER configuration files
|
||||
SQLiteCustom/GRDBCustomSQLite-USER.h
|
||||
SQLiteCustom/GRDBCustomSQLite-USER.xcconfig
|
||||
|
||||
# CocoaPods test
|
||||
Podfile.lock
|
||||
Pods
|
||||
|
||||
# SPM
|
||||
.build
|
||||
Package.pins
|
||||
Tests/SPM/Packages
|
||||
|
||||
# Ruby
|
||||
.ruby-version
|
||||
+1
-1
@@ -1 +1 @@
|
||||
3.0
|
||||
3.1
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
language: objective-c
|
||||
xcode_project: GRDB.xcodeproj
|
||||
|
||||
# Disable the default Travis-CI submodule logic
|
||||
# The various make commands ensure that the appropriate submodules are retrieved
|
||||
git:
|
||||
submodules: false
|
||||
|
||||
jobs:
|
||||
include:
|
||||
|
||||
###########################################
|
||||
## Test GRDB
|
||||
|
||||
# Test GRDBOSX (Xcode 8.3)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
env:
|
||||
- TID=GRDBOSX (Xcode 8.3, macOS 10.12)
|
||||
script: make test_framework_GRDBOSX
|
||||
|
||||
# Test GRDBWatchOS (Xcode 8.3)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
env:
|
||||
- TID=GRDBWatchOS (Xcode 8.3, watchOS)
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
# Test GRDBiOS (Xcode 8.3, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
env:
|
||||
- TID=GRDBiOS (Xcode 8.3, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget
|
||||
|
||||
# Test GRDBiOS (Xcode 8.3, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
env:
|
||||
- TID=GRDBiOS (Xcode 8.3, iOS <MIN>)
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
# Test GRDB [SPM] (Xcode 8.3, macOS 10.12)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
env:
|
||||
- TID=GRDB [SPM] (Xcode 8.3, macOS 10.12)
|
||||
script: make test_SPM
|
||||
|
||||
###########################################
|
||||
## Test GRDB (Custom SQLite)
|
||||
|
||||
# Test GRDBCustomSQLiteOSX (Xcode 8.3)
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteOSX (Xcode 8.3, macOS 10.12)
|
||||
script: make test_framework_GRDBCustomSQLiteOSX
|
||||
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 8.3, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 8.3, iOS <MAX>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget
|
||||
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 8.3, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 8.3, iOS <MIN>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
|
||||
|
||||
###########################################
|
||||
## Test GRDB (SQLCipher)
|
||||
|
||||
# Test GRDBCipherOSX (Xcode 8.3)
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
env:
|
||||
- TID=GRDBCipherOSX (Xcode 8.3, macOS 10.12)
|
||||
script: make test_framework_GRDBCipherOSX
|
||||
|
||||
# Test GRDBCipheriOS (Xcode 8.3, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
env:
|
||||
- TID=GRDBCipheriOS (Xcode 8.3, iOS <MAX>)
|
||||
script: make test_framework_GRDBCipheriOS_maxTarget
|
||||
|
||||
# Test GRDBCipheriOS (Xcode 8.3, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
env:
|
||||
- TID=GRDBCipheriOS (Xcode 8.3, iOS <MIN>)
|
||||
script: make test_framework_GRDBCipheriOS_minTarget
|
||||
|
||||
###########################################
|
||||
## Test Installation Methods
|
||||
|
||||
# Manual Install
|
||||
- stage: Test Installation
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
env:
|
||||
- TID=Manual Install
|
||||
script: make test_install_manual
|
||||
|
||||
# Manual Install (GRDBCipher)
|
||||
- stage: Test Installation
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
env:
|
||||
- TID=Manual Install (GRDBCipher)
|
||||
script: make test_install_GRDBCipher
|
||||
|
||||
# Cocoapods Lint
|
||||
- stage: Test Installation
|
||||
osx_image: xcode8.3
|
||||
install:
|
||||
- gem install cocoapods # Since Travis is not always on latest version
|
||||
env:
|
||||
- TID=Cocoapods
|
||||
script: make test_CocoaPodsLint
|
||||
|
||||
# SPM Install
|
||||
- stage: Test Installation
|
||||
osx_image: xcode8.3
|
||||
env:
|
||||
- TID=SPM
|
||||
script: make test_install_SPM
|
||||
|
||||
## The following doesn’t work, as `make test_CarthageBuild` does not yet work.
|
||||
## Carthage Build
|
||||
#- stage: Carthage
|
||||
# osx_image: xcode8.3
|
||||
# before_install:
|
||||
# - brew update
|
||||
# - brew outdated carthage || brew upgrade carthage
|
||||
# script: make test_CarthageBuild
|
||||
+552
-9
@@ -1,6 +1,549 @@
|
||||
Release Notes
|
||||
=============
|
||||
|
||||
## 1.2
|
||||
|
||||
Released July 13, 2017
|
||||
|
||||
**New**
|
||||
|
||||
- Record types that do not provide values for all table columns in their `encode(to:)` method are now supported.
|
||||
|
||||
- The table creation API has been enhanced:
|
||||
|
||||
- SQLite supports untyped columns:
|
||||
|
||||
```swift
|
||||
try dbQueue.inDatabase { db in
|
||||
// CREATE TABLE t(a, b)
|
||||
try db.create(table: "t") { t in
|
||||
t.column("a")
|
||||
t.column("b")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Untyped columns behave like decimal, boolean, date columns, and generally all columns with [NUMERIC type affinity](https://sqlite.org/datatype3.html#type_affinity).
|
||||
|
||||
This feature addresses [#169](https://github.com/groue/GRDB.swift/issues/169).
|
||||
|
||||
- The `indexed()` methods lets you create a non-unique index on a table column:
|
||||
|
||||
```swift
|
||||
try dbQueue.inDatabase { db in
|
||||
// CREATE TABLE rounds(score INTEGER)
|
||||
// CREATE INDEX rounds_on_score ON rounds(score)
|
||||
try db.create(table: "rounds") { t in
|
||||
t.column("score", .integer).indexed()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- It is now possible to define references to tables without any explicit primary key. The generated SQL then uses the `rowid` hidden primary key column:
|
||||
|
||||
```swift
|
||||
try dbQueue.inDatabase { db in
|
||||
// CREATE TABLE nodes(
|
||||
// name TEXT,
|
||||
// parentId INTEGER REFERENCES nodes(rowid)
|
||||
// )
|
||||
try db.create(table: "nodes") { t in
|
||||
t.column("name", .text)
|
||||
t.column("parentId", .integer).references("nodes")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `DatabaseQueue`, `DatabasePool` and their common protocol `DatabaseReader` can now perform "unsafe reentrant reads" ([documentation](https://github.com/groue/GRDB.swift#unsafe-concurrency-apis)):
|
||||
|
||||
```swift
|
||||
try dbPool.read { db in
|
||||
// This is allowed
|
||||
try dbPool.unsafeReentrantRead { db in
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
**Fixed**
|
||||
|
||||
- `DatabasePool.read`, and `DatabasePool.unsafeRead` now raise a fatal error when used in a reentrant way:
|
||||
|
||||
```swift
|
||||
try dbPool.read { db in
|
||||
// fatal error: "Database methods are not reentrant."
|
||||
try dbPool.read { db in
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
While this change may appear as a breaking change, it is really a fix: reentrant reads deadlock as soon as the maximum number of readers has been reached.
|
||||
|
||||
|
||||
**API diff**
|
||||
|
||||
```diff
|
||||
final class ColumnDefinition {
|
||||
+ @discardableResult func indexed() -> Self
|
||||
}
|
||||
|
||||
final class TableDefinition {
|
||||
- func column(_ name: String, _ type: Database.ColumnType) -> ColumnDefinition
|
||||
+ func column(_ name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition
|
||||
}
|
||||
|
||||
protocol DatabaseReader {
|
||||
+ func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 1.1
|
||||
|
||||
Released July 1, 2017
|
||||
|
||||
**New**
|
||||
|
||||
- `DatabaseAggregate` is the protocol for custom aggregate functions (fixes [#236](https://github.com/groue/GRDB.swift/issues/236), [documentation](https://github.com/groue/GRDB.swift#custom-aggregates)):
|
||||
|
||||
```swift
|
||||
struct MySum : DatabaseAggregate {
|
||||
var sum: Int = 0
|
||||
|
||||
mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
if let int = Int.fromDatabaseValue(dbValues[0]) {
|
||||
sum += int
|
||||
}
|
||||
}
|
||||
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
return sum
|
||||
}
|
||||
}
|
||||
|
||||
let dbQueue = DatabaseQueue()
|
||||
let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE TABLE test(i)")
|
||||
try db.execute("INSERT INTO test(i) VALUES (1)")
|
||||
try db.execute("INSERT INTO test(i) VALUES (2)")
|
||||
try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
|
||||
}
|
||||
```
|
||||
|
||||
**Fixed**
|
||||
|
||||
- `QueryInterfaceRequest.order(_:)` clears the eventual reversed flag, and better reflects the documentation of this method: "Any previous ordering is replaced."
|
||||
|
||||
**Deprecated**
|
||||
|
||||
- `TableMapping.primaryKeyRowComparator` is deprecated, without any replacement.
|
||||
|
||||
**API diff**
|
||||
|
||||
```diff
|
||||
final class DatabaseFunction {
|
||||
+ init<Aggregate: DatabaseAggregate>(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, aggregate: Aggregate.Type)
|
||||
}
|
||||
|
||||
+protocol DatabaseAggregate {
|
||||
+ init()
|
||||
+ mutating func step(_ dbValues: [DatabaseValue]) throws
|
||||
+ func finalize() throws -> DatabaseValueConvertible?
|
||||
+}
|
||||
|
||||
extension TableMapping {
|
||||
+ @available(*, deprecated)
|
||||
static func primaryKeyRowComparator(_ db: Database) throws -> (Row, Row) -> Bool
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 1.0 :tada:
|
||||
|
||||
Released June 20, 2017
|
||||
|
||||
**GRDB 1.0 comes with enhancements, and API stability.**
|
||||
|
||||
It comes with breaking changes, but the good news is that they are the last (until GRDB 2.0) :sweat_smile:!
|
||||
|
||||
- **Requirements have changed: Xcode 8.3+ / Swift 3.1**
|
||||
|
||||
As a matter of fact, GRDB 1.0 still supports Xcode 8.1 and Swift 3.0. But future versions are free to use Swift 3.1 features, and will require Xcode 8.3+.
|
||||
|
||||
The targetted operating systems are unchanged: iOS 8.0+ / OSX 10.9+ / watchOS 2.0+
|
||||
|
||||
- **[Record types](https://github.com/groue/GRDB.swift#records) have their `persistentDictionary` property replaced with the `encode(to:)` method:**
|
||||
|
||||
```swift
|
||||
struct Player : Persistable {
|
||||
let name: String
|
||||
let score: Int
|
||||
|
||||
// Old
|
||||
// var persistentDictionary: [String: DatabaseValueConvertible?] {
|
||||
// return [
|
||||
// "name": name,
|
||||
// "score": score,
|
||||
// ]
|
||||
// }
|
||||
|
||||
// New
|
||||
func encode(to container: inout PersistenceContainer) {
|
||||
container["name"] = name
|
||||
container["score"] = score
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This is good for applications that declare lists of columns:
|
||||
|
||||
```swift
|
||||
struct Player : RowConvertible, Persistable {
|
||||
let name: String
|
||||
let score: Int
|
||||
|
||||
static let databaseTableName = "players"
|
||||
|
||||
// Declare Player columns
|
||||
enum Columns {
|
||||
static let name = Column("name")
|
||||
static let score = Column("score")
|
||||
}
|
||||
|
||||
// Use columns in `init(row:)`
|
||||
init(row: Row) {
|
||||
name = row.value(Columns.name)
|
||||
score = row.value(Columns.score)
|
||||
}
|
||||
|
||||
// Use columns in the new `encode(to:)` method:
|
||||
func encode(to container: inout PersistenceContainer) {
|
||||
container[Columns.name] = name
|
||||
container[Columns.score] = score
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- **[Database Observation](https://github.com/groue/GRDB.swift#database-changes-observation) has been enhanced:**
|
||||
|
||||
`Database.afterNextTransactionCommit(_:)` is the simplest way to handle successful [transactions](https://github.com/groue/GRDB.swift#transactions-and-savepoints), and synchronize the database with other resources such as files, or system sensors ([documentation](https://github.com/groue/GRDB.swift#after-commit-hook)).
|
||||
|
||||
```swift
|
||||
// Make sure the database is inside a transaction
|
||||
db.inSavepoint {
|
||||
// Perform some database job
|
||||
try ...
|
||||
|
||||
// Register extra job that is only executed after database changes
|
||||
// have been committed and written to disk.
|
||||
db.afterNextTransactionCommit { ... }
|
||||
}
|
||||
```
|
||||
|
||||
On the low-level side, applications can now specify the extent of database observation ([documentation](https://github.com/groue/GRDB.swift#observation-extent)).
|
||||
|
||||
- **DatabaseMigrator is easier to test**, with its `DatabaseMigrator.migrate(_:upTo:)` method which partially migrates your databases ([documentation](https://github.com/groue/GRDB.swift#migrations)).
|
||||
|
||||
- On the side of database schema introspection, the new `Database.foreignKeys(on:)` method lists the foreign keys defined on a table.
|
||||
|
||||
**Full list of changes**
|
||||
|
||||
```diff
|
||||
class Database {
|
||||
- func add(transactionObserver: TransactionObserver)
|
||||
+ func add(transactionObserver: TransactionObserver, extent: TransactionObservationExtent = .observerLifetime)
|
||||
+ func afterNextTransactionCommit(_ closure: @escaping (Database) -> ())
|
||||
+ func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo]
|
||||
}
|
||||
|
||||
-struct DatabaseCoder: DatabaseValueConvertible
|
||||
|
||||
struct DatabaseMigrator {
|
||||
+ func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws
|
||||
}
|
||||
|
||||
protocol DatabaseWriter : DatabaseReader {
|
||||
- func add(transactionObserver: TransactionObserver)
|
||||
+ func add(transactionObserver: TransactionObserver, extent: TransactionObservationExtent = .observerLifetime)
|
||||
}
|
||||
|
||||
protocol MutablePersistable : TableMapping {
|
||||
- var persistentDictionary: [String: DatabaseValueConvertible?] { get }
|
||||
+ func encode(to container: inout PersistenceContainer)
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
- func contains(_ value: SQLExpressible) -> SQLExpression
|
||||
- func exists() -> SQLExpression
|
||||
}
|
||||
|
||||
extension Request {
|
||||
- func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AnyRequest
|
||||
+ func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedRequest<Self>
|
||||
}
|
||||
|
||||
protocol TypedRequest : Request {
|
||||
- associatedtype Fetched
|
||||
+ associatedtype RowDecoder
|
||||
}
|
||||
|
||||
extension TypedRequest {
|
||||
- func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AnyTypedRequest<Fetched>
|
||||
+ func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedTypedRequest<Self>
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 0.110.0
|
||||
|
||||
Released May 28, 2017
|
||||
|
||||
**New**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.19.2](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Upgrade SQLCipher to v3.4.1 ([announcement](https://discuss.zetetic.net/t/sqlcipher-3-4-1-release/1962), [changelog](https://github.com/sqlcipher/sqlcipher/blob/master/CHANGELOG.md))
|
||||
- A [large test suite](https://travis-ci.org/groue/GRDB.swift) that runs on Travis-CI, thanks to [@swiftlyfalling](https://github.com/swiftlyfalling) in [PR #213](https://github.com/groue/GRDB.swift/pull/213)
|
||||
|
||||
**Fixed**
|
||||
|
||||
- Remove deprecation warning about `sqlite3_trace`() for [custom SQLite builds](https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md) (addresses [#100](https://github.com/groue/GRDB.swift/issues/100))
|
||||
|
||||
|
||||
## 0.109.0
|
||||
|
||||
Released May 22, 2017
|
||||
|
||||
**Fixed**
|
||||
|
||||
- Failed value conversions now consistently crash with a fatal error.
|
||||
|
||||
**New**
|
||||
|
||||
- `DatabaseValue.losslessConvert()` performs a lossless conversion to a value type.
|
||||
|
||||
**Breaking Changes**
|
||||
|
||||
- `DatabaseEventKind.impacts(_ selectionInfo:SelectStatement.SelectionInfo)` now returns an non-optional boolean.
|
||||
- `DatabaseWriter.availableDatabaseConnection` has been replaced by `DatabaseWriter.unsafeReentrantWrite()`.
|
||||
- `Request.bound(to:)` has been renamed `Request.asRequest(of:)`.
|
||||
|
||||
|
||||
## 0.108.0
|
||||
|
||||
Released May 17, 2017
|
||||
|
||||
**New**
|
||||
|
||||
- Use CocoaPods to install GRDB with [SQLCipher](https://github.com/groue/GRDB.swift#encryption):
|
||||
|
||||
```ruby
|
||||
pod 'GRDBCipher'
|
||||
```
|
||||
|
||||
|
||||
**Breaking Changes**
|
||||
|
||||
- `RowConvertible.awakeFromFetch()` has been removed.
|
||||
|
||||
|
||||
## 0.107.0
|
||||
|
||||
Released May 5, 2017
|
||||
|
||||
**New**
|
||||
|
||||
- `SQLRequest` learned how to reuse cached prepared statements: `SQLRequest("SELECT ...", cached: true)`
|
||||
|
||||
- `Database.logError` lets you register a global error logging function:
|
||||
|
||||
```swift
|
||||
Database.logError = { resultCode, message in
|
||||
NSLog("%@", "SQLite error \(resultCode): \(message)")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 0.106.1
|
||||
|
||||
Released April 12, 2017
|
||||
|
||||
No change, but a better support for Swift Package Manager at the git repository level.
|
||||
|
||||
|
||||
## 0.106.0
|
||||
|
||||
Released April 11, 2017
|
||||
|
||||
**New**
|
||||
|
||||
- Swift Package Manager, thanks to [Andrey Fidrya](https://github.com/zmeyc) in [PR #202](https://github.com/groue/GRDB.swift/pull/202).
|
||||
|
||||
|
||||
## 0.105.0
|
||||
|
||||
Released April 6, 2017
|
||||
|
||||
**Fixed**
|
||||
|
||||
- [FetchedRecordsController](https://github.com/groue/GRDB.swift#fetchedrecordscontroller) used to be able to miss changes performed on requests that use the `COUNT` SQL function. This is fixed.
|
||||
|
||||
|
||||
**New**
|
||||
|
||||
- `DatabaseWriter.availableDatabaseConnection` allows reentrant uses of GRDB, and improves support for [reactive](http://reactivex.io) programming.
|
||||
|
||||
|
||||
**Breaking Changes**
|
||||
|
||||
- `DatabaseEventKind.impacts(_ selectionInfo:SelectStatement.SelectionInfo)` now returns an optional boolean which, when nil, tells that GRDB doesn't know if a statement has any impact on the selection of a request. In practice, this happens as soon as a request uses the `COUNT` SQL function.
|
||||
|
||||
|
||||
## 0.104.0
|
||||
|
||||
Released April 3, 2017
|
||||
|
||||
**New**
|
||||
|
||||
- Support for Xcode 8.3 and Swift 3.1 (Xcode 8.1 and Swift 3 are still supported).
|
||||
- Upgrade custom SQLite builds to [v3.18.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Support for [reactive](http://reactivex.io) extensions:
|
||||
- `SelectStatement.SelectionInfo` is an opaque value that knows which database tables and columns are read by a [select statement](https://github.com/groue/GRDB.swift#prepared-statements).
|
||||
- `DatabaseEventKind.impacts(_ selectionInfo:SelectStatement.SelectionInfo)` tells whether a database change has any impact on the results of a select statement. See [Database Changes Observation](https://github.com/groue/GRDB.swift#database-changes-observation)
|
||||
- `TableMapping.primaryKeyRowComparator(_ db: Database)` returns a function that compares two database rows and return true if and only if they have the same non-null primary key.
|
||||
|
||||
**Breaking Changes**
|
||||
|
||||
- SQLite C API is now available right from the GRBD module: you don't need any longer to import `SQLiteiPhoneOS` module et al (see documentation for [Raw SQLite Pointers](https://github.com/groue/GRDB.swift#raw-sqlite-pointers)).
|
||||
- The [manual installation procedure for WatchOS extensions](https://github.com/groue/GRDB.swift#installation) has changed.
|
||||
- [Carthage](https://github.com/Carthage/Carthage) is no longer supported. At the present time it is unable to support the various frameworks built by GRDB (system SQLite, SQLCipher, custom SQLite builds, etc.)
|
||||
|
||||
|
||||
## 0.103.0
|
||||
|
||||
Released March 26, 2017
|
||||
|
||||
**Fixed**
|
||||
|
||||
- `DatabaseError` conversion to `NSError` preserves extended result codes.
|
||||
- `DatabaseQueue.read` and `DatabaseQueue.readFromCurrentState` throw an error upon database modifications.
|
||||
- Added missing availability checks for SQLite features that are not available on all versions of iOS, macOS, watchOS.
|
||||
- Removed useless availability checks for SQLite features that are available with [SQLCipher](https://github.com/groue/GRDB.swift#encryption) and [custom SQLite builds](https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md).
|
||||
- Prevent [wrong linking of SQLCipher](https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688)
|
||||
|
||||
**Breaking Changes**
|
||||
|
||||
- `DatabaseQueue.writeInTransaction`, alias for `DatabaseQueue.inTransaction`, has been removed.
|
||||
- `DatabaseValue.value()` has been removed, in favor of `DatabaseValue.storage`.
|
||||
|
||||
|
||||
## 0.102.0
|
||||
|
||||
Released March 2, 2017
|
||||
|
||||
**New: Error Handling** (fixes [#171](https://github.com/groue/GRDB.swift/issues/171))
|
||||
|
||||
- GRDB activates SQLite's [extended result codes](https://www.sqlite.org/rescode.html) for more detailed error reporting.
|
||||
- The new `ResultCode` type defines constants for all SQLite [result codes and extended result codes](https://www.sqlite.org/rescode.html).
|
||||
- The SQLite error code of `DatabaseError` can be queried with `resultCode`, or `extendedResultCode`, depending on the level of details you need ([documentation](https://github.com/groue/GRDB.swift#databaseerror)):
|
||||
|
||||
```swift
|
||||
do {
|
||||
...
|
||||
} catch let error as DatabaseError where error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY {
|
||||
// handle foreign key constraint error
|
||||
} catch let error as DatabaseError where error.resultCode == .SQLITE_CONSTRAINT {
|
||||
// handle any other constraint error
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
**New: Request**
|
||||
|
||||
- The Request protocol for [custom requests](https://github.com/groue/GRDB.swift#custom-requests) learned how to count:
|
||||
|
||||
```swift
|
||||
let request: Request = ...
|
||||
let count = try request.fetchCount(db) // Int
|
||||
```
|
||||
|
||||
Default implementation performs a naive counting based on the request SQL: `SELECT COUNT(*) FROM (...)`. Adopting types can refine the counting SQL by providing their own `fetchCount` implementation.
|
||||
|
||||
Thanks [David Hart](https://github.com/hartbit) for this [suggestion](https://github.com/groue/GRDB.swift/issues/176#issuecomment-282783884).
|
||||
|
||||
|
||||
**Breaking Changes**
|
||||
|
||||
- `DatabaseError.code` has been removed, replaced with `DatabaseError.resultCode` and `DatabaseError.extendedResultCode` ([documentation](https://github.com/groue/GRDB.swift#databaseerror)).
|
||||
- `DatabaseMigrator.registerMigrationWithDisabledForeignKeyChecks` has been renamed `DatabaseMigrator.registerMigrationWithDeferredForeignKeyCheck` ([documentation](https://github.com/groue/GRDB.swift#advanced-database-schema-changes))
|
||||
|
||||
|
||||
## 0.101.1
|
||||
|
||||
Released January 20, 2017
|
||||
|
||||
**New**
|
||||
|
||||
- `DatabaseEventKind.tableName` makes it easier to track any change that may happen to a database table ([documentation](https://github.com/groue/GRDB.swift#filtering-database-events))
|
||||
- `FetchedRecordsController.allowBackgroundChangesTracking(in:)`: call this [FetchedRecordsController](https://github.com/groue/GRDB.swift#fetchedrecordscontroller) method when changes performed while the application is in the background should be processed before the application enters the suspended state.
|
||||
|
||||
|
||||
**Breaking Changes**
|
||||
|
||||
- `Configuration.fileAttributes` has been removed (see [Data Protection](https://github.com/groue/GRDB.swift#data-protection))
|
||||
|
||||
|
||||
## 0.100.0
|
||||
|
||||
Released January 10, 2017
|
||||
|
||||
**New**
|
||||
|
||||
- `Row` adopts the Hashable protocol
|
||||
- [FetchedRecordsController](https://github.com/groue/GRDB.swift#fetchedrecordscontroller) now outputs request changes on all platforms, for both table and collection views. Merged [#160](https://github.com/groue/GRDB.swift/pull/160) by [@kdubb](https://github.com/kdubb).
|
||||
- Upgrade custom SQLite builds to [v3.16.2](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
|
||||
**Breaking Changes**
|
||||
|
||||
- It is now a programmer error to invoke `FetchedRecordsController.fetchedRecords` before `performFetch()`:
|
||||
|
||||
```diff
|
||||
final class FetchedRecordsController<Record: RowConvertible> {
|
||||
- var fetchedRecords: [Record]?
|
||||
+ var fetchedRecords: [Record]
|
||||
}
|
||||
```
|
||||
|
||||
- The fetched record type of a FetchedRecordsController is now infered from the request that feeds the controller:
|
||||
|
||||
```diff
|
||||
final class FetchedRecordsController<Record: RowConvertible> {
|
||||
- convenience init(...:request: Request) throws
|
||||
+ convenience init<Request>(...:request: Request) throws where Request: TypedRequest, Request.Fetched == Record
|
||||
}
|
||||
```
|
||||
|
||||
- FetchedRecordsController now automatically compares records by primary key when the record type adopts the TableMapping protocol, such as all Record subclasses. This feature used to require an explicit `compareRecordsByPrimaryKey` initialization parameter:
|
||||
|
||||
```diff
|
||||
extension FetchedRecordsController where Record: TableMapping {
|
||||
- convenience init(...:compareRecordsByPrimaryKey: Bool) throws
|
||||
}
|
||||
```
|
||||
|
||||
- Change tracking APIs have been modified:
|
||||
|
||||
```diff
|
||||
final class FetchedRecordsController<Record: RowConvertible> {
|
||||
- func trackChanges(recordsWillChange:tableViewEvent:recordsDidChange:)
|
||||
+ func trackChanges(willChange:onChange:didChange:)
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 0.99.2
|
||||
|
||||
Released December 22, 2016
|
||||
@@ -566,8 +1109,8 @@ Released September 16, 2016
|
||||
- `Row.databaseValue(atIndex:)` and `Row.databaseValue(named:)` have been removed. Use `value(atIndex:)` and `value(named:)` instead:
|
||||
|
||||
```diff
|
||||
-let dbv = row.databaseValue(atIndex: 0)
|
||||
+let dbv: DatabaseValue = row.value(atIndex: 0)
|
||||
-let dbValue = row.databaseValue(atIndex: 0)
|
||||
+let dbValue: DatabaseValue = row.value(atIndex: 0)
|
||||
```
|
||||
|
||||
|
||||
@@ -672,8 +1215,8 @@ Released September 11, 2016
|
||||
+ init?(value: Any)
|
||||
}
|
||||
protocol DatabaseValueConvertible {
|
||||
- static func fromDatabaseValue(databaseValue: DatabaseValue) -> DatabaseValue?
|
||||
+ static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> DatabaseValue?
|
||||
- static func fromDatabaseValue(dbValue: DatabaseValue) -> DatabaseValue?
|
||||
+ static func fromDatabaseValue(_ dbValue: DatabaseValue) -> DatabaseValue?
|
||||
}
|
||||
+extension Data : DatabaseValueConvertible
|
||||
+extension Date : DatabaseValueConvertible
|
||||
@@ -922,8 +1465,8 @@ Released September 16, 2016
|
||||
- `Row.databaseValue(atIndex:)` and `Row.databaseValue(named:)` have been removed. Use `value(atIndex:)` and `value(named:)` instead:
|
||||
|
||||
```diff
|
||||
-let dbv = row.databaseValue(atIndex: 0)
|
||||
+let dbv: DatabaseValue = row.value(atIndex: 0)
|
||||
-let dbValue = row.databaseValue(atIndex: 0)
|
||||
+let dbValue: DatabaseValue = row.value(atIndex: 0)
|
||||
```
|
||||
|
||||
|
||||
@@ -1411,8 +1954,8 @@ Released May 18, 2016
|
||||
- `DatabaseValue.failableValue()` has been removed. Instead, use DatabaseConvertible.fromDatabaseValue():
|
||||
|
||||
```diff
|
||||
-let date = dbv.failableValue() as NSDate?
|
||||
+let date = NSDate.fromDatabaseValue(dbv)
|
||||
-let date = dbValue.failableValue() as NSDate?
|
||||
+let date = NSDate.fromDatabaseValue(dbValue)
|
||||
```
|
||||
|
||||
- `Row.databaseValue(named:)` now returns an optional DatabaseValue. It is nil when the column does not exist in the row.
|
||||
@@ -2523,7 +3066,7 @@ Released September 6, 2015
|
||||
**Breaking changes**
|
||||
|
||||
- `DatabaseDate` has been removed (replaced by built-in NSDate support).
|
||||
- `DatabaseValueConvertible`: `init?(databaseValue:)` has been replaced by `static func fromDatabaseValue(_:) -> Self?`
|
||||
- `DatabaseValueConvertible`: `init?(dbValue:)` has been replaced by `static func fromDatabaseValue(_:) -> Self?`
|
||||
- `Blob.init(_:)` has been replaced with `Blob.init(data:)` and `Blob.init(dataNoCopy:)`.
|
||||
- `RowModel.edited` has been renamed `RowModel.databaseEdited`.
|
||||
- `RowModel.databaseTable` has been replaced with `RowModel.databaseTableName()` which returns a String.
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"screenWidth" : "{130,145}",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"screenWidth" : "{146,165}",
|
||||
"scale" : "2x"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"version" : 1,
|
||||
"author" : "xcode"
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"assets" : [
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"filename" : "Circular.imageset",
|
||||
"role" : "circular"
|
||||
},
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"filename" : "Extra Large.imageset",
|
||||
"role" : "extra-large"
|
||||
},
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"filename" : "Modular.imageset",
|
||||
"role" : "modular"
|
||||
},
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"filename" : "Utilitarian.imageset",
|
||||
"role" : "utilitarian"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"version" : 1,
|
||||
"author" : "xcode"
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"screenWidth" : "{130,145}",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"screenWidth" : "{146,165}",
|
||||
"scale" : "2x"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"version" : 1,
|
||||
"author" : "xcode"
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"screenWidth" : "{130,145}",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"screenWidth" : "{146,165}",
|
||||
"scale" : "2x"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"version" : 1,
|
||||
"author" : "xcode"
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"screenWidth" : "{130,145}",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "watch",
|
||||
"screenWidth" : "{146,165}",
|
||||
"scale" : "2x"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"version" : 1,
|
||||
"author" : "xcode"
|
||||
}
|
||||
}
|
||||
-1
@@ -1 +0,0 @@
|
||||
Did you know that git does not support storing empty directories?
|
||||
@@ -1,39 +0,0 @@
|
||||
import GRDB
|
||||
import WatchKit
|
||||
|
||||
// The shared database queue
|
||||
var dbQueue: DatabaseQueue!
|
||||
|
||||
func setupDatabase() {
|
||||
|
||||
// Connect to the database
|
||||
// See https://github.com/groue/GRDB.swift/#database-connections
|
||||
|
||||
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString
|
||||
let databasePath = documentsPath.appendingPathComponent("db.sqlite")
|
||||
dbQueue = try! DatabaseQueue(path: databasePath)
|
||||
|
||||
|
||||
// Use DatabaseMigrator to setup the database
|
||||
// See https://github.com/groue/GRDB.swift/#migrations
|
||||
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
migrator.registerMigration("createPersons") { db in
|
||||
// Compare person names in a localized case insensitive fashion
|
||||
// See https://github.com/groue/GRDB.swift/#unicode
|
||||
try db.create(table: "persons") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare)
|
||||
}
|
||||
}
|
||||
|
||||
migrator.registerMigration("addPersons") { db in
|
||||
// Populate the persons table with random data
|
||||
for _ in 0..<8 {
|
||||
try Person(name: Person.randomName()).insert(db)
|
||||
}
|
||||
}
|
||||
|
||||
try! migrator.migrate(dbQueue)
|
||||
}
|
||||
@@ -1,8 +1,50 @@
|
||||
//
|
||||
// ExtensionDelegate.swift
|
||||
// GRDBDemoWatchOS Extension
|
||||
//
|
||||
// Created by Gwendal Roué on 03/04/2017.
|
||||
// Copyright © 2017 Gwendal Roué. All rights reserved.
|
||||
//
|
||||
|
||||
import WatchKit
|
||||
|
||||
class ExtensionDelegate: NSObject, WKExtensionDelegate {
|
||||
|
||||
func applicationDidFinishLaunching() {
|
||||
setupDatabase()
|
||||
// Perform any final initialization of your application.
|
||||
}
|
||||
|
||||
func applicationDidBecomeActive() {
|
||||
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
|
||||
}
|
||||
|
||||
func applicationWillResignActive() {
|
||||
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
|
||||
// Use this method to pause ongoing tasks, disable timers, etc.
|
||||
}
|
||||
|
||||
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
|
||||
// Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one.
|
||||
for task in backgroundTasks {
|
||||
// Use a switch statement to check the task type
|
||||
switch task {
|
||||
case let backgroundTask as WKApplicationRefreshBackgroundTask:
|
||||
// Be sure to complete the background task once you’re done.
|
||||
backgroundTask.setTaskCompleted()
|
||||
case let snapshotTask as WKSnapshotRefreshBackgroundTask:
|
||||
// Snapshot tasks have a unique completion call, make sure to set your expiration date
|
||||
snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil)
|
||||
case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask:
|
||||
// Be sure to complete the connectivity task once you’re done.
|
||||
connectivityTask.setTaskCompleted()
|
||||
case let urlSessionTask as WKURLSessionRefreshBackgroundTask:
|
||||
// Be sure to complete the URL session task once you’re done.
|
||||
urlSessionTask.setTaskCompleted()
|
||||
default:
|
||||
// make sure to complete unhandled task types
|
||||
task.setTaskCompleted()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -18,8 +18,6 @@
|
||||
<string>XPC!</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>NSExtension</key>
|
||||
@@ -27,7 +25,7 @@
|
||||
<key>NSExtensionAttributes</key>
|
||||
<dict>
|
||||
<key>WKAppBundleIdentifier</key>
|
||||
<string>GRDB.GRDBDemoiOS.watchkitapp</string>
|
||||
<string>com.github.groue.GRDBDemoiOS.watchkitapp</string>
|
||||
</dict>
|
||||
<key>NSExtensionPointIdentifier</key>
|
||||
<string>com.apple.watchkit</string>
|
||||
|
||||
@@ -1,25 +1,23 @@
|
||||
//
|
||||
// InterfaceController.swift
|
||||
// GRDBDemoWatchOS Extension
|
||||
//
|
||||
// Created by Gwendal Roué on 03/04/2017.
|
||||
// Copyright © 2017 Gwendal Roué. All rights reserved.
|
||||
//
|
||||
|
||||
import WatchKit
|
||||
import Foundation
|
||||
import GRDB
|
||||
|
||||
class InterfaceController: WKInterfaceController {
|
||||
|
||||
@IBOutlet var table: WKInterfaceTable!
|
||||
|
||||
@IBOutlet var versionLabel: WKInterfaceLabel!
|
||||
|
||||
override func awake(withContext context: Any?) {
|
||||
super.awake(withContext: context)
|
||||
|
||||
let persons = try! dbQueue.inDatabase { db in
|
||||
try Person.order(Column("name")).fetchAll(db)
|
||||
}
|
||||
|
||||
table.setNumberOfRows(persons.count, withRowType: "Person")
|
||||
for (i, person) in persons.enumerated() {
|
||||
let row = table.rowController(at: i) as! PersonRowController
|
||||
row.nameLabel.setText(person.name)
|
||||
}
|
||||
let sqliteVersion = String(cString: sqlite3_libversion(), encoding: .utf8)
|
||||
versionLabel.setText(sqliteVersion)
|
||||
}
|
||||
}
|
||||
|
||||
class PersonRowController: NSObject {
|
||||
@IBOutlet var nameLabel: WKInterfaceLabel!
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
import GRDB
|
||||
|
||||
class Person: Record {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
|
||||
init(name: String) {
|
||||
self.name = name
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: Record overrides
|
||||
|
||||
override class var databaseTableName: String {
|
||||
return "persons"
|
||||
}
|
||||
|
||||
required init(row: Row) {
|
||||
id = row.value(named: "id")
|
||||
name = row.value(named: "name")
|
||||
super.init(row: row)
|
||||
}
|
||||
|
||||
override var persistentDictionary: [String : DatabaseValueConvertible?] {
|
||||
return [
|
||||
"id": id,
|
||||
"name": name]
|
||||
}
|
||||
|
||||
override func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
}
|
||||
|
||||
// MARK: Random
|
||||
|
||||
private static let names = ["Arthur", "Anita", "Barbara", "Bernard", "Craig", "Chiara", "David", "Dean", "Éric", "Elena", "Fatima", "Frederik", "Gilbert", "Georgette", "Henriette", "Hassan", "Ignacio", "Irene", "Julie", "Jack", "Karl", "Kristel", "Louis", "Liz", "Masashi", "Mary", "Noam", "Nicole", "Ophelie", "Oleg", "Pascal", "Patricia", "Quentin", "Quinn", "Raoul", "Rachel", "Stephan", "Susie", "Tristan", "Tatiana", "Ursule", "Urbain", "Victor", "Violette", "Wilfried", "Wilhelmina", "Yvon", "Yann", "Zazie", "Zoé"]
|
||||
|
||||
class func randomName() -> String {
|
||||
return names[Int(arc4random_uniform(UInt32(names.count)))]
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<document type="com.apple.InterfaceBuilder.WatchKit.Storyboard" version="3.0" toolsVersion="10117" systemVersion="15G31" targetRuntime="watchKit" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="AgC-eL-Hgc">
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<document type="com.apple.InterfaceBuilder.WatchKit.Storyboard" version="3.0" toolsVersion="12118" systemVersion="16E195" targetRuntime="watchKit" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="AgC-eL-Hgc">
|
||||
<device id="watch38" orientation="portrait">
|
||||
<adaptation id="fullscreen"/>
|
||||
</device>
|
||||
<dependencies>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBWatchKitPlugin" version="10032"/>
|
||||
<deployment identifier="watchOS"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12086"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBWatchKitPlugin" version="12029"/>
|
||||
</dependencies>
|
||||
<scenes>
|
||||
<!--Interface Controller-->
|
||||
@@ -10,23 +14,15 @@
|
||||
<objects>
|
||||
<controller id="AgC-eL-Hgc" customClass="InterfaceController" customModule="GRDBDemoWatchOS" customModuleProvider="target">
|
||||
<items>
|
||||
<table alignment="left" id="as6-ga-ksx">
|
||||
<group width="1" alignment="left" verticalAlignment="center" layout="vertical" id="tkk-aG-QQF">
|
||||
<items>
|
||||
<tableRow identifier="Person" selectable="NO" id="0Rj-aC-A4i" customClass="PersonRowController" customModule="GRDBDemoWatchOS_Extension">
|
||||
<group key="rootItem" width="1" alignment="left" id="Ohb-zN-5mC">
|
||||
<items>
|
||||
<label alignment="left" verticalAlignment="center" text="Label" id="jSM-Ni-30q"/>
|
||||
</items>
|
||||
</group>
|
||||
<connections>
|
||||
<outlet property="nameLabel" destination="jSM-Ni-30q" id="qRo-7r-tXk"/>
|
||||
</connections>
|
||||
</tableRow>
|
||||
<label alignment="center" text="SQLite version" id="dGA-xX-x8V"/>
|
||||
<label alignment="center" text="Label" id="whi-N6-h8U"/>
|
||||
</items>
|
||||
</table>
|
||||
</group>
|
||||
</items>
|
||||
<connections>
|
||||
<outlet property="table" destination="as6-ga-ksx" id="Zqf-oi-mIm"/>
|
||||
<outlet property="versionLabel" destination="whi-N6-h8U" id="5xN-Gj-yNt"/>
|
||||
</connections>
|
||||
</controller>
|
||||
</objects>
|
||||
|
||||
@@ -18,8 +18,6 @@
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>UISupportedInterfaceOrientations</key>
|
||||
@@ -28,7 +26,7 @@
|
||||
<string>UIInterfaceOrientationPortraitUpsideDown</string>
|
||||
</array>
|
||||
<key>WKCompanionAppBundleIdentifier</key>
|
||||
<string>GRDB.GRDBDemoiOS</string>
|
||||
<string>com.github.groue.GRDBDemoiOS</string>
|
||||
<key>WKWatchKitApp</key>
|
||||
<true/>
|
||||
</dict>
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+141
@@ -0,0 +1,141 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0730"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
BuildableName = "GRDBDemoWatchOS.app"
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56B036021E8D9EBE003B6DA4"
|
||||
BuildableName = "GRDBDemoiOS.app"
|
||||
BlueprintName = "GRDBDemoiOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FCA1E926430002582E0"
|
||||
BuildableName = "GRDBDemoWatchOS Extension.appex"
|
||||
BlueprintName = "GRDBDemoWatchOS Extension"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
BuildableName = "GRDBDemoWatchOS.app"
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<RemoteRunnable
|
||||
runnableDebuggingMode = "2"
|
||||
BundleIdentifier = "com.apple.carousel"
|
||||
RemotePath = "/GRDBDemoiOS">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
BuildableName = "GRDBDemoWatchOS.app"
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</RemoteRunnable>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
BuildableName = "GRDBDemoWatchOS.app"
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<RemoteRunnable
|
||||
runnableDebuggingMode = "2"
|
||||
BundleIdentifier = "com.apple.carousel"
|
||||
RemotePath = "/GRDBDemoiOS">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
BuildableName = "GRDBDemoWatchOS.app"
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</RemoteRunnable>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
BuildableName = "GRDBDemoWatchOS.app"
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0830"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56B036021E8D9EBE003B6DA4"
|
||||
BuildableName = "GRDBDemoiOS.app"
|
||||
BlueprintName = "GRDBDemoiOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56B036021E8D9EBE003B6DA4"
|
||||
BuildableName = "GRDBDemoiOS.app"
|
||||
BlueprintName = "GRDBDemoiOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Release"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56B036021E8D9EBE003B6DA4"
|
||||
BuildableName = "GRDBDemoiOS.app"
|
||||
BlueprintName = "GRDBDemoiOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56B036021E8D9EBE003B6DA4"
|
||||
BuildableName = "GRDBDemoiOS.app"
|
||||
BlueprintName = "GRDBDemoiOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -1,5 +1,15 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"idiom" : "iphone",
|
||||
"size" : "20x20",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "iphone",
|
||||
"size" : "20x20",
|
||||
"scale" : "3x"
|
||||
},
|
||||
{
|
||||
"idiom" : "iphone",
|
||||
"size" : "29x29",
|
||||
@@ -32,6 +42,16 @@
|
||||
"filename" : "Icon-60@3x.png",
|
||||
"scale" : "3x"
|
||||
},
|
||||
{
|
||||
"idiom" : "ipad",
|
||||
"size" : "20x20",
|
||||
"scale" : "1x"
|
||||
},
|
||||
{
|
||||
"idiom" : "ipad",
|
||||
"size" : "20x20",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "ipad",
|
||||
"size" : "29x29",
|
||||
|
||||
@@ -40,14 +40,17 @@ func setupDatabase(_ application: UIApplication) throws {
|
||||
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
}
|
||||
|
||||
migrator.registerMigration("addPersons") { db in
|
||||
|
||||
// Populate the persons table with random data
|
||||
for _ in 0..<8 {
|
||||
try Person(name: Person.randomName(), score: Person.randomScore()).insert(db)
|
||||
}
|
||||
}
|
||||
|
||||
// // Migrations for future application versions will be inserted here:
|
||||
// migrator.registerMigration(...) { db in
|
||||
// ...
|
||||
// }
|
||||
|
||||
try migrator.migrate(dbQueue)
|
||||
}
|
||||
@@ -18,8 +18,6 @@
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>LSRequiresIPhoneOS</key>
|
||||
|
||||
@@ -24,11 +24,10 @@ class Person: Record {
|
||||
super.init(row: row)
|
||||
}
|
||||
|
||||
override var persistentDictionary: [String : DatabaseValueConvertible?] {
|
||||
return [
|
||||
"id": id,
|
||||
"name": name,
|
||||
"score": score]
|
||||
override func encode(to container: inout PersistenceContainer) {
|
||||
container["id"] = id
|
||||
container["name"] = name
|
||||
container["score"] = score
|
||||
}
|
||||
|
||||
override func didInsert(with rowID: Int64, for column: String?) {
|
||||
|
||||
@@ -12,14 +12,13 @@ class PersonsViewController: UITableViewController {
|
||||
editButtonItem
|
||||
]
|
||||
|
||||
let request = personsSortedByScore
|
||||
personsController = try! FetchedRecordsController(dbQueue, request: request, compareRecordsByPrimaryKey: true)
|
||||
personsController = try! FetchedRecordsController(dbQueue, request: personsSortedByScore)
|
||||
personsController.trackChanges(
|
||||
recordsWillChange: { [unowned self] _ in
|
||||
willChange: { [unowned self] _ in
|
||||
self.tableView.beginUpdates()
|
||||
},
|
||||
tableViewEvent: { [unowned self] (controller, record, event) in
|
||||
switch event {
|
||||
onChange: { [unowned self] (controller, record, change) in
|
||||
switch change {
|
||||
case .insertion(let indexPath):
|
||||
self.tableView.insertRows(at: [indexPath], with: .fade)
|
||||
|
||||
@@ -44,7 +43,7 @@ class PersonsViewController: UITableViewController {
|
||||
// self.tableView.insertRows(at: [newIndexPath], with: .fade)
|
||||
}
|
||||
},
|
||||
recordsDidChange: { [unowned self] _ in
|
||||
didChange: { [unowned self] _ in
|
||||
self.tableView.endUpdates()
|
||||
})
|
||||
try! personsController.performFetch()
|
||||
|
||||
@@ -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.15.2](https://www.sqlite.org/changes.html).**
|
||||
**You can build GRDB with a custom build of [SQLite 3.19.2](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.swift directory]
|
||||
git checkout v0.99.2
|
||||
git checkout v1.2
|
||||
git submodule update --init SQLiteCustom/src
|
||||
````
|
||||
|
||||
|
||||
@@ -117,8 +117,9 @@ Well, you will be able to use UIColor like all other [value types](../../../#val
|
||||
super.init(row: row)
|
||||
}
|
||||
|
||||
override var persistentDictionary: [String: DatabaseValueConvertible?] {
|
||||
return ["name": name, "color": color]
|
||||
override func encode(to container: inout PersistenceContainer) {
|
||||
container["name"] = name
|
||||
container["color"] = color
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -208,6 +209,8 @@ Whenever you import a SQL feature to Swift, you'll have to decide: should you pr
|
||||
|
||||
### 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
|
||||
@@ -273,6 +276,8 @@ You may want to compare it to another protocol, SQLExpressible, which will be de
|
||||
|
||||
### 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
|
||||
@@ -390,6 +395,8 @@ For an example of use, see the [Add a new kind of SQLite expression](#add-a-new-
|
||||
|
||||
#### 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
|
||||
@@ -415,6 +422,8 @@ extension SQLUnaryOperator {
|
||||
|
||||
#### 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
|
||||
@@ -439,6 +448,8 @@ extension SQLBinaryOperator {
|
||||
|
||||
#### SQLExpressionFunction
|
||||
|
||||
[**:fire: EXPERIMENTAL**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
|
||||
SQLExpressionFunction builds an SQL function call:
|
||||
|
||||
```swift
|
||||
@@ -473,15 +484,6 @@ Build a `value IN (...)` expression from any sequence of [values](../../../#valu
|
||||
![1,2,3].contains(Column("id"))
|
||||
```
|
||||
|
||||
The most general way to generate an `IN` operator is from any value that adopts the [SQLCollection](http://cocoadocs.org/docsets/GRDB.swift/0.99.2/Protocols/SQLCollection.html) protocol, like the [query interface requests](../../../#requests):
|
||||
|
||||
```swift
|
||||
let request = Person.select(Column("id"))
|
||||
|
||||
// SQLExpression: in IN (SELECT id FROM persons)
|
||||
request.contains(Column("id"))
|
||||
```
|
||||
|
||||
|
||||
#### The BETWEEN Operator
|
||||
|
||||
@@ -493,21 +495,9 @@ Build a `value BETWEEN min AND max` expression from Swift ranges:
|
||||
```
|
||||
|
||||
|
||||
#### The EXISTS Operator
|
||||
|
||||
Build a `EXISTS(...)` expression from any value that adopts the [SQLSelectQuery](http://cocoadocs.org/docsets/GRDB.swift/0.99.2/Protocols/SQLSelectQuery.html) protocol, like the [query interface requests](../../../#requests):
|
||||
|
||||
```swift
|
||||
let request = Person.all()
|
||||
|
||||
// SQLExpression: EXISTS(SELECT * FROM persons)
|
||||
request.exists()
|
||||
```
|
||||
|
||||
|
||||
#### The COUNT Function
|
||||
|
||||
Build a `COUNT(...)` expression from the [count](http://cocoadocs.org/docsets/GRDB.swift/0.99.2/Functions.html) and [count(distinct:)](http://cocoadocs.org/docsets/GRDB.swift/0.99.2/Functions.html) functions:
|
||||
Build a `COUNT(...)` expression from the [count](http://groue.github.io/GRDB.swift/docs/1.2/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/1.2/Functions.html) functions:
|
||||
|
||||
```swift
|
||||
// SQLExpression: COUNT(email)
|
||||
@@ -598,4 +588,4 @@ You may want to compare it to another protocol, SQLSpecificExpressible, which ha
|
||||
|
||||
> :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://cocoadocs.org/docsets/GRDB.swift/0.99.2/Protocols/SQLExpression.html) protocol.
|
||||
**If SQLExpressionLiteral reveals too limited for your purpose**, you may have to implement a new type that adopts the [SQLExpression](http://groue.github.io/GRDB.swift/docs/1.2/Protocols/SQLExpression.html) protocol.
|
||||
@@ -6,29 +6,28 @@ Release Process
|
||||
To release a new GRDB version:
|
||||
|
||||
- Tests
|
||||
- Run GRDBOX tests
|
||||
- Run GRDBCipherOSX tests
|
||||
- Run GRDBCustomSQLiteOSX tests
|
||||
- Run GRDBiOS tests
|
||||
- Run GRDBCipheriOS tests
|
||||
- Run GRDBCustomSQLiteiOS tests
|
||||
- Build and run GRDBDemoiOS
|
||||
- Build and run GRDBDemoWatchOS
|
||||
- `make test`
|
||||
- Build and run GRDBDemoiOS in Release configuration on a device
|
||||
- Archive GRDBDemoiOS
|
||||
- Check for performance regression with GRDBOSXPerformanceTests
|
||||
- `rm -rf Carthage; carthage build --no-skip-current`
|
||||
- `pod lib lint --allow-warnings`
|
||||
- On SDK upgrade, update Support/sqlite3.h
|
||||
- On https://github.com/groue/sqlcipher.git upgrade, update SQLCipher version in README.md
|
||||
- On https://github.com/swiftlyfalling/SQLiteLib upgrade, update SQLite version in README.md and Documentation/CustomSQLiteBuilds.md
|
||||
- Update GRDB version number and release date in:
|
||||
- Makefile
|
||||
- CHANGELOG.md
|
||||
- Documentation/CustomSQLiteBuilds.md
|
||||
- Documentation/ExtendingGRDB.md
|
||||
- GRDB.swift.podspec
|
||||
- GRDBCipher.podspec
|
||||
- README.md
|
||||
- Support/Info.plist
|
||||
- Commit and tag
|
||||
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
|
||||
- Push to the master branch
|
||||
- Push to the Swift3 branch
|
||||
- `pod trunk push --allow-warnings`
|
||||
- `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
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '0.99.2'
|
||||
s.version = '1.2'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A Swift application toolkit for SQLite databases.'
|
||||
@@ -13,7 +13,7 @@ Pod::Spec.new do |s|
|
||||
s.osx.deployment_target = '10.9'
|
||||
s.watchos.deployment_target = '2.0'
|
||||
|
||||
s.source_files = 'GRDB/**/*.{h,swift}'
|
||||
s.source_files = 'GRDB/**/*.swift', 'Support/*.{c,h}'
|
||||
s.module_map = 'Support/module.modulemap'
|
||||
s.framework = 'Foundation'
|
||||
s.library = 'sqlite3'
|
||||
|
||||
+1669
-1207
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,109 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0830"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "560FC5191CB003810014AA8E"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipherOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "560FC55D1CB00B880014AA8E"
|
||||
BuildableName = "GRDBCipherOSXTests.xctest"
|
||||
BlueprintName = "GRDBCipherOSXTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "567156191CB16729007DC145"
|
||||
BuildableName = "GRDBCipherOSXEncryptedTests.xctest"
|
||||
BlueprintName = "GRDBCipherOSXEncryptedTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "560FC5191CB003810014AA8E"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipherOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "560FC5191CB003810014AA8E"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipherOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "560FC5191CB003810014AA8E"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipherOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -0,0 +1,109 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0830"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56AFC9EE1CB1A8BB00F48B96"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipheriOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56AFCA2B1CB1AA9900F48B96"
|
||||
BuildableName = "GRDBCipheriOSTests.xctest"
|
||||
BlueprintName = "GRDBCipheriOSTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56AFCA841CB1ABC800F48B96"
|
||||
BuildableName = "GRDBCipheriOSEncryptedTests.xctest"
|
||||
BlueprintName = "GRDBCipheriOSEncryptedTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56AFC9EE1CB1A8BB00F48B96"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipheriOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56AFC9EE1CB1A8BB00F48B96"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipheriOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56AFC9EE1CB1A8BB00F48B96"
|
||||
BuildableName = "GRDBCipher.framework"
|
||||
BlueprintName = "GRDBCipheriOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0830"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F3BA80591CFB2BB2003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLite.framework"
|
||||
BlueprintName = "GRDBCustomSQLiteOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F3BA809A1CFB2F6F003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLiteOSXTests.xctest"
|
||||
BlueprintName = "GRDBCustomSQLiteOSXTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F3BA80591CFB2BB2003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLite.framework"
|
||||
BlueprintName = "GRDBCustomSQLiteOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F3BA80591CFB2BB2003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLite.framework"
|
||||
BlueprintName = "GRDBCustomSQLiteOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F3BA80591CFB2BB2003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLite.framework"
|
||||
BlueprintName = "GRDBCustomSQLiteOSX"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -0,0 +1,99 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0830"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F3BA7FFD1CFB25E4003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLite.framework"
|
||||
BlueprintName = "GRDBCustomSQLiteiOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F3BA80401CFB2AD7003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLiteiOSTests.xctest"
|
||||
BlueprintName = "GRDBCustomSQLiteiOSTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F3BA7FFD1CFB25E4003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLite.framework"
|
||||
BlueprintName = "GRDBCustomSQLiteiOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F3BA7FFD1CFB25E4003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLite.framework"
|
||||
BlueprintName = "GRDBCustomSQLiteiOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "F3BA7FFD1CFB25E4003DC1BA"
|
||||
BuildableName = "GRDBCustomSQLite.framework"
|
||||
BlueprintName = "GRDBCustomSQLiteiOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -29,7 +29,7 @@
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56E5D7F81B4D422D00430942"
|
||||
BuildableName = "GRDBTests.xctest"
|
||||
BuildableName = "GRDBOSXTests.xctest"
|
||||
BlueprintName = "GRDBOSXTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
@@ -48,7 +48,7 @@
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56E5D7F81B4D422D00430942"
|
||||
BuildableName = "GRDBTests.xctest"
|
||||
BuildableName = "GRDBOSXTests.xctest"
|
||||
BlueprintName = "GRDBOSXTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0730"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Release"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "560C97CF1C0E22D300BF8471"
|
||||
BuildableName = "GRDBOSXPerformanceTests.xctest"
|
||||
BlueprintName = "GRDBOSXPerformanceTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -26,14 +26,15 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
codeCoverageEnabled = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56E5D7D21B4D3FEE00430942"
|
||||
BuildableName = "GRDBTests.xctest"
|
||||
BuildableName = "GRDBiOSTests.xctest"
|
||||
BlueprintName = "GRDBiOSTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@
|
||||
location = "group:GRDB.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Tests/GRDBProfiling/GRDBProfiling.xcodeproj">
|
||||
location = "group:Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj">
|
||||
|
||||
@@ -1,21 +1,7 @@
|
||||
import Foundation
|
||||
|
||||
#if !USING_BUILTIN_SQLITE
|
||||
#if os(OSX)
|
||||
import SQLiteMacOSX
|
||||
#elseif os(iOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteiPhoneSimulator
|
||||
#else
|
||||
import SQLiteiPhoneOS
|
||||
#endif
|
||||
#elseif os(watchOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteWatchSimulator
|
||||
#else
|
||||
import SQLiteWatchOS
|
||||
#endif
|
||||
#endif
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#endif
|
||||
|
||||
/// Configuration for a DatabaseQueue or DatabasePool.
|
||||
@@ -49,29 +35,12 @@ public struct Configuration {
|
||||
#endif
|
||||
|
||||
|
||||
// MARK: - File Attributes
|
||||
|
||||
/// The file attributes that should be applied to the database files (see
|
||||
/// `NSFileMnager.setAttributes(_,ofItemAtPath:)`).
|
||||
///
|
||||
/// SQLite will create [temporary files](https://www.sqlite.org/tempfiles.html)
|
||||
/// when it needs them.
|
||||
///
|
||||
/// In WAL mode (see DatabasePool), SQLite will also eventually create
|
||||
/// `-shm` and `-wal` files.
|
||||
///
|
||||
/// GRDB will apply file attributes to all those files.
|
||||
///
|
||||
/// Default: nil
|
||||
public var fileAttributes: [FileAttributeKey: Any]? = nil
|
||||
|
||||
|
||||
// MARK: - Transactions
|
||||
|
||||
/// The default kind of transaction.
|
||||
///
|
||||
/// Default: Immediate
|
||||
public var defaultTransactionKind: Database.TransactionKind = .immediate
|
||||
/// Default: deferred
|
||||
public var defaultTransactionKind: Database.TransactionKind = .deferred
|
||||
|
||||
|
||||
// MARK: - Concurrency
|
||||
@@ -101,7 +70,8 @@ public struct Configuration {
|
||||
var SQLiteConnectionWillClose: ((SQLiteConnection) -> ())?
|
||||
var SQLiteConnectionDidClose: (() -> ())?
|
||||
var SQLiteOpenFlags: Int32 {
|
||||
return threadingMode.SQLiteOpenFlags | (readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE))
|
||||
let readWriteFlags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE)
|
||||
return threadingMode.SQLiteOpenFlags | readWriteFlags
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+10
-11
@@ -3,8 +3,7 @@ extension Array {
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'bar'")
|
||||
/// let strings = try Array(cursor) // ["foo", "bar"]
|
||||
public init<C : Cursor>(_ cursor: C) throws where C.Element == Element {
|
||||
// TODO: cursors should have an underestimatedCount
|
||||
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
|
||||
self.init()
|
||||
while let element = try cursor.next() {
|
||||
append(element)
|
||||
@@ -64,7 +63,7 @@ public protocol Cursor : class {
|
||||
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 {
|
||||
public init<C: Cursor>(_ base: C) where C.Element == Element {
|
||||
element = base.next
|
||||
}
|
||||
|
||||
@@ -138,13 +137,13 @@ extension Cursor {
|
||||
|
||||
/// 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>>> {
|
||||
public func flatMap<SegmentOfResult: Sequence>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, IteratorCursor<SegmentOfResult.Iterator>>> {
|
||||
return flatMap { try IteratorCursor(transform($0)) }
|
||||
}
|
||||
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult : Cursor>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, SegmentOfResult>> {
|
||||
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, SegmentOfResult>> {
|
||||
return map(transform).joined()
|
||||
}
|
||||
|
||||
@@ -211,7 +210,7 @@ extension Cursor where Element: Sequence {
|
||||
/// }
|
||||
/// // Prints: "0: foo"
|
||||
/// // Prints: "1: bar"
|
||||
public final class EnumeratedCursor<Base : Cursor> : Cursor {
|
||||
public final class EnumeratedCursor<Base: Cursor> : Cursor {
|
||||
init(_ base: Base) {
|
||||
self.index = 0
|
||||
self.base = base
|
||||
@@ -231,7 +230,7 @@ public final class EnumeratedCursor<Base : Cursor> : Cursor {
|
||||
|
||||
/// A cursor whose elements consist of the elements of some base cursor that
|
||||
/// also satisfy a given predicate.
|
||||
public final class FilterCursor<Base : Cursor> : Cursor {
|
||||
public final class FilterCursor<Base: Cursor> : Cursor {
|
||||
init(_ base: Base, _ isIncluded: @escaping (Base.Element) throws -> Bool) {
|
||||
self.base = base
|
||||
self.isIncluded = isIncluded
|
||||
@@ -283,7 +282,7 @@ public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Curs
|
||||
/// transform function returning Element.
|
||||
///
|
||||
/// See Cursor.map(_:)
|
||||
public final class MapCursor<Base : Cursor, Element> : Cursor {
|
||||
public final class MapCursor<Base: Cursor, Element> : Cursor {
|
||||
init(_ base: Base, _ transform: @escaping (Base.Element) throws -> Element) {
|
||||
self.base = base
|
||||
self.transform = transform
|
||||
@@ -301,7 +300,7 @@ public final class MapCursor<Base : Cursor, Element> : Cursor {
|
||||
}
|
||||
|
||||
/// A Cursor whose elements are those of a sequence iterator.
|
||||
public final class IteratorCursor<Base : IteratorProtocol> : Cursor {
|
||||
public final class IteratorCursor<Base: IteratorProtocol> : Cursor {
|
||||
|
||||
/// Creates a cursor from a sequence iterator.
|
||||
public init(_ base: Base) {
|
||||
@@ -309,7 +308,7 @@ public final class IteratorCursor<Base : IteratorProtocol> : Cursor {
|
||||
}
|
||||
|
||||
/// Creates a cursor from a sequence.
|
||||
public init<S : Sequence>(_ s: S) where S.Iterator == Base {
|
||||
public init<S: Sequence>(_ s: S) where S.Iterator == Base {
|
||||
self.base = s.makeIterator()
|
||||
}
|
||||
|
||||
@@ -326,7 +325,7 @@ 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>> {
|
||||
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<IteratorCursor<Self.Iterator>, SegmentOfResult>> {
|
||||
return IteratorCursor(self).flatMap(transform)
|
||||
}
|
||||
}
|
||||
+549
-288
File diff suppressed because it is too large.
Load diff
+196
-22
@@ -1,28 +1,194 @@
|
||||
import Foundation
|
||||
|
||||
#if !USING_BUILTIN_SQLITE
|
||||
#if os(OSX)
|
||||
import SQLiteMacOSX
|
||||
#elseif os(iOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteiPhoneSimulator
|
||||
#else
|
||||
import SQLiteiPhoneOS
|
||||
#endif
|
||||
#elseif os(watchOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteWatchSimulator
|
||||
#else
|
||||
import SQLiteWatchOS
|
||||
#endif
|
||||
#endif
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#endif
|
||||
|
||||
public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible {
|
||||
public let rawValue: Int32
|
||||
|
||||
public init(rawValue: Int32) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
/// A result code limited to the least significant 8 bits of the receiver.
|
||||
/// See https://www.sqlite.org/rescode.html for more information.
|
||||
///
|
||||
/// let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY
|
||||
/// resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true
|
||||
public var primaryResultCode: ResultCode {
|
||||
return ResultCode(rawValue: rawValue & 0xFF)
|
||||
}
|
||||
|
||||
var isPrimary: Bool {
|
||||
return self == primaryResultCode
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
// sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, iOSApplicationExtension 8.2, *) {
|
||||
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
|
||||
} else {
|
||||
return "\(rawValue)"
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
public static func == (_ lhs: ResultCode, _ rhs: ResultCode) -> Bool {
|
||||
return lhs.rawValue == rhs.rawValue
|
||||
}
|
||||
|
||||
/// Returns true if the code on the left matches the code on the right.
|
||||
///
|
||||
/// Primary result codes match themselves and their extended result codes,
|
||||
/// while extended result codes match only themselves:
|
||||
///
|
||||
/// switch error.extendedResultCode {
|
||||
/// case .SQLITE_CONSTRAINT_FOREIGNKEY: // foreign key constraint error
|
||||
/// case .SQLITE_CONSTRAINT: // any other constraint error
|
||||
/// default: // any other database error
|
||||
/// }
|
||||
public static func ~= (pattern: ResultCode, code: ResultCode) -> Bool {
|
||||
if pattern.isPrimary {
|
||||
return pattern == code.primaryResultCode
|
||||
} else {
|
||||
return pattern == code
|
||||
}
|
||||
}
|
||||
|
||||
// Primary Result codes
|
||||
// https://www.sqlite.org/rescode.html#primary_result_code_list
|
||||
|
||||
public static let SQLITE_OK = ResultCode(rawValue: 0) // Successful result
|
||||
public static let SQLITE_ERROR = ResultCode(rawValue: 1) // SQL error or missing database
|
||||
public static let SQLITE_INTERNAL = ResultCode(rawValue: 2) // Internal logic error in SQLite
|
||||
public static let SQLITE_PERM = ResultCode(rawValue: 3) // Access permission denied
|
||||
public static let SQLITE_ABORT = ResultCode(rawValue: 4) // Callback routine requested an abort
|
||||
public static let SQLITE_BUSY = ResultCode(rawValue: 5) // The database file is locked
|
||||
public static let SQLITE_LOCKED = ResultCode(rawValue: 6) // A table in the database is locked
|
||||
public static let SQLITE_NOMEM = ResultCode(rawValue: 7) // A malloc() failed
|
||||
public static let SQLITE_READONLY = ResultCode(rawValue: 8) // Attempt to write a readonly database
|
||||
public static let SQLITE_INTERRUPT = ResultCode(rawValue: 9) // Operation terminated by sqlite3_interrupt()
|
||||
public static let SQLITE_IOERR = ResultCode(rawValue: 10) // Some kind of disk I/O error occurred
|
||||
public static let SQLITE_CORRUPT = ResultCode(rawValue: 11) // The database disk image is malformed
|
||||
public static let SQLITE_NOTFOUND = ResultCode(rawValue: 12) // Unknown opcode in sqlite3_file_control()
|
||||
public static let SQLITE_FULL = ResultCode(rawValue: 13) // Insertion failed because database is full
|
||||
public static let SQLITE_CANTOPEN = ResultCode(rawValue: 14) // Unable to open the database file
|
||||
public static let SQLITE_PROTOCOL = ResultCode(rawValue: 15) // Database lock protocol error
|
||||
public static let SQLITE_EMPTY = ResultCode(rawValue: 16) // Database is empty
|
||||
public static let SQLITE_SCHEMA = ResultCode(rawValue: 17) // The database schema changed
|
||||
public static let SQLITE_TOOBIG = ResultCode(rawValue: 18) // String or BLOB exceeds size limit
|
||||
public static let SQLITE_CONSTRAINT = ResultCode(rawValue: 19) // Abort due to constraint violation
|
||||
public static let SQLITE_MISMATCH = ResultCode(rawValue: 20) // Data type mismatch
|
||||
public static let SQLITE_MISUSE = ResultCode(rawValue: 21) // Library used incorrectly
|
||||
public static let SQLITE_NOLFS = ResultCode(rawValue: 22) // Uses OS features not supported on host
|
||||
public static let SQLITE_AUTH = ResultCode(rawValue: 23) // Authorization denied
|
||||
public static let SQLITE_FORMAT = ResultCode(rawValue: 24) // Auxiliary database format error
|
||||
public static let SQLITE_RANGE = ResultCode(rawValue: 25) // 2nd parameter to sqlite3_bind out of range
|
||||
public static let SQLITE_NOTADB = ResultCode(rawValue: 26) // File opened that is not a database file
|
||||
public static let SQLITE_NOTICE = ResultCode(rawValue: 27) // Notifications from sqlite3_log()
|
||||
public static let SQLITE_WARNING = ResultCode(rawValue: 28) // Warnings from sqlite3_log()
|
||||
public static let SQLITE_ROW = ResultCode(rawValue: 100) // sqlite3_step() has another row ready
|
||||
public static let SQLITE_DONE = ResultCode(rawValue: 101) // sqlite3_step() has finished executing
|
||||
|
||||
// Extended Result Code
|
||||
// https://www.sqlite.org/rescode.html#extended_result_code_list
|
||||
|
||||
public static let SQLITE_IOERR_READ = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (1<<8)))
|
||||
public static let SQLITE_IOERR_SHORT_READ = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (2<<8)))
|
||||
public static let SQLITE_IOERR_WRITE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (3<<8)))
|
||||
public static let SQLITE_IOERR_FSYNC = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (4<<8)))
|
||||
public static let SQLITE_IOERR_DIR_FSYNC = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (5<<8)))
|
||||
public static let SQLITE_IOERR_TRUNCATE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (6<<8)))
|
||||
public static let SQLITE_IOERR_FSTAT = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (7<<8)))
|
||||
public static let SQLITE_IOERR_UNLOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (8<<8)))
|
||||
public static let SQLITE_IOERR_RDLOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (9<<8)))
|
||||
public static let SQLITE_IOERR_DELETE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (10<<8)))
|
||||
public static let SQLITE_IOERR_BLOCKED = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (11<<8)))
|
||||
public static let SQLITE_IOERR_NOMEM = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (12<<8)))
|
||||
public static let SQLITE_IOERR_ACCESS = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (13<<8)))
|
||||
public static let SQLITE_IOERR_CHECKRESERVEDLOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (14<<8)))
|
||||
public static let SQLITE_IOERR_LOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (15<<8)))
|
||||
public static let SQLITE_IOERR_CLOSE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (16<<8)))
|
||||
public static let SQLITE_IOERR_DIR_CLOSE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (17<<8)))
|
||||
public static let SQLITE_IOERR_SHMOPEN = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (18<<8)))
|
||||
public static let SQLITE_IOERR_SHMSIZE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (19<<8)))
|
||||
public static let SQLITE_IOERR_SHMLOCK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (20<<8)))
|
||||
public static let SQLITE_IOERR_SHMMAP = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (21<<8)))
|
||||
public static let SQLITE_IOERR_SEEK = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (22<<8)))
|
||||
public static let SQLITE_IOERR_DELETE_NOENT = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (23<<8)))
|
||||
public static let SQLITE_IOERR_MMAP = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (24<<8)))
|
||||
public static let SQLITE_IOERR_GETTEMPPATH = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (25<<8)))
|
||||
public static let SQLITE_IOERR_CONVPATH = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (26<<8)))
|
||||
public static let SQLITE_IOERR_VNODE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (27<<8)))
|
||||
public static let SQLITE_IOERR_AUTH = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (28<<8)))
|
||||
public static let SQLITE_LOCKED_SHAREDCACHE = ResultCode(rawValue: (SQLITE_LOCKED.rawValue | (1<<8)))
|
||||
public static let SQLITE_BUSY_RECOVERY = ResultCode(rawValue: (SQLITE_BUSY.rawValue | (1<<8)))
|
||||
public static let SQLITE_BUSY_SNAPSHOT = ResultCode(rawValue: (SQLITE_BUSY.rawValue | (2<<8)))
|
||||
public static let SQLITE_CANTOPEN_NOTEMPDIR = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (1<<8)))
|
||||
public static let SQLITE_CANTOPEN_ISDIR = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (2<<8)))
|
||||
public static let SQLITE_CANTOPEN_FULLPATH = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (3<<8)))
|
||||
public static let SQLITE_CANTOPEN_CONVPATH = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (4<<8)))
|
||||
public static let SQLITE_CORRUPT_VTAB = ResultCode(rawValue: (SQLITE_CORRUPT.rawValue | (1<<8)))
|
||||
public static let SQLITE_READONLY_RECOVERY = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (1<<8)))
|
||||
public static let SQLITE_READONLY_CANTLOCK = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (2<<8)))
|
||||
public static let SQLITE_READONLY_ROLLBACK = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (3<<8)))
|
||||
public static let SQLITE_READONLY_DBMOVED = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (4<<8)))
|
||||
public static let SQLITE_ABORT_ROLLBACK = ResultCode(rawValue: (SQLITE_ABORT.rawValue | (2<<8)))
|
||||
public static let SQLITE_CONSTRAINT_CHECK = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (1<<8)))
|
||||
public static let SQLITE_CONSTRAINT_COMMITHOOK = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (2<<8)))
|
||||
public static let SQLITE_CONSTRAINT_FOREIGNKEY = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (3<<8)))
|
||||
public static let SQLITE_CONSTRAINT_FUNCTION = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (4<<8)))
|
||||
public static let SQLITE_CONSTRAINT_NOTNULL = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (5<<8)))
|
||||
public static let SQLITE_CONSTRAINT_PRIMARYKEY = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (6<<8)))
|
||||
public static let SQLITE_CONSTRAINT_TRIGGER = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (7<<8)))
|
||||
public static let SQLITE_CONSTRAINT_UNIQUE = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (8<<8)))
|
||||
public static let SQLITE_CONSTRAINT_VTAB = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (9<<8)))
|
||||
public static let SQLITE_CONSTRAINT_ROWID = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (10<<8)))
|
||||
public static let SQLITE_NOTICE_RECOVER_WAL = ResultCode(rawValue: (SQLITE_NOTICE.rawValue | (1<<8)))
|
||||
public static let SQLITE_NOTICE_RECOVER_ROLLBACK = ResultCode(rawValue: (SQLITE_NOTICE.rawValue | (2<<8)))
|
||||
public static let SQLITE_WARNING_AUTOINDEX = ResultCode(rawValue: (SQLITE_WARNING.rawValue | (1<<8)))
|
||||
public static let SQLITE_AUTH_USER = ResultCode(rawValue: (SQLITE_AUTH.rawValue | (1<<8)))
|
||||
public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8)))
|
||||
|
||||
}
|
||||
|
||||
/// DatabaseError wraps an SQLite error.
|
||||
public struct DatabaseError : Error {
|
||||
|
||||
/// The SQLite error code (see https://www.sqlite.org/c3ref/c_abort.html).
|
||||
public let code: Int32
|
||||
/// The SQLite error code (see
|
||||
/// https://www.sqlite.org/rescode.html#primary_result_code_list).
|
||||
///
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch let error as DatabaseError where error.resultCode == .SQL_CONSTRAINT {
|
||||
/// // A constraint error
|
||||
/// }
|
||||
///
|
||||
/// This property returns a "primary result code", that is to say the least
|
||||
/// significant 8 bits of any SQLite result code. See
|
||||
/// https://www.sqlite.org/rescode.html for more information.
|
||||
///
|
||||
/// See also `extendedResultCode`.
|
||||
public var resultCode: ResultCode {
|
||||
return extendedResultCode.primaryResultCode
|
||||
}
|
||||
|
||||
/// The SQLite extended error code (see
|
||||
/// https://www.sqlite.org/rescode.html#extended_result_code_list).
|
||||
///
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch let error as DatabaseError where error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY {
|
||||
/// // A foreign key constraint error
|
||||
/// }
|
||||
///
|
||||
/// See also `resultCode`.
|
||||
public let extendedResultCode: ResultCode
|
||||
|
||||
/// The SQLite error message.
|
||||
public let message: String?
|
||||
@@ -30,13 +196,21 @@ public struct DatabaseError : Error {
|
||||
/// The SQL query that yielded the error (if relevant).
|
||||
public let sql: String?
|
||||
|
||||
public init(code: Int32 = SQLITE_ERROR, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
|
||||
self.code = code
|
||||
/// Creates a Database Error
|
||||
public init(resultCode: ResultCode = .SQLITE_ERROR, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
|
||||
self.extendedResultCode = resultCode
|
||||
self.message = message
|
||||
self.sql = sql
|
||||
self.arguments = arguments
|
||||
}
|
||||
|
||||
/// Creates a Database Error with a raw Int32 result code.
|
||||
///
|
||||
/// This initializer is not public because library user is not supposed to
|
||||
/// be exposed to raw result codes.
|
||||
init(resultCode: Int32, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
|
||||
self.init(resultCode: ResultCode(rawValue: resultCode), message: message, sql: sql, arguments: arguments)
|
||||
}
|
||||
|
||||
// MARK: Not public
|
||||
|
||||
@@ -48,7 +222,7 @@ public struct DatabaseError : Error {
|
||||
extension DatabaseError: CustomStringConvertible {
|
||||
/// A textual representation of `self`.
|
||||
public var description: String {
|
||||
var description = "SQLite error \(code)"
|
||||
var description = "SQLite error \(extendedResultCode.rawValue)"
|
||||
if let sql = sql {
|
||||
description += " with statement `\(sql)`"
|
||||
}
|
||||
@@ -71,7 +245,7 @@ extension DatabaseError : CustomNSError {
|
||||
|
||||
/// NSError bridging: the error code within the given domain.
|
||||
public var errorCode: Int {
|
||||
return Int(code)
|
||||
return Int(extendedResultCode.rawValue)
|
||||
}
|
||||
|
||||
/// NSError bridging: the user-info dictionary.
|
||||
|
||||
@@ -0,0 +1,369 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#endif
|
||||
|
||||
/// An SQL function or aggregate.
|
||||
public final class DatabaseFunction {
|
||||
public let name: String
|
||||
let argumentCount: Int32?
|
||||
let pure: Bool
|
||||
private let kind: Kind
|
||||
fileprivate var nArg: Int32 { return argumentCount ?? -1 }
|
||||
fileprivate var eTextRep: Int32 { return (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
|
||||
|
||||
/// Returns an SQL function.
|
||||
///
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int + 1
|
||||
/// }
|
||||
/// db.add(function: fn)
|
||||
/// try Int.fetchOne(db, "SELECT succ(1)")! // 2
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The function name.
|
||||
/// - argumentCount: The number of arguments of the function. If
|
||||
/// omitted, or nil, the function accepts any number of arguments.
|
||||
/// - pure: Whether the function is "pure", which means that its results
|
||||
/// only depends on its inputs. When a function is pure, SQLite has
|
||||
/// the opportunity to perform additional optimizations. Default value
|
||||
/// is false.
|
||||
/// - function: A function that takes an array of DatabaseValue
|
||||
/// arguments, and returns an optional DatabaseValueConvertible such
|
||||
/// as Int, String, NSDate, etc. The array is guaranteed to have
|
||||
/// exactly *argumentCount* elements, provided *argumentCount* is
|
||||
/// not nil.
|
||||
public init(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?) {
|
||||
self.name = name
|
||||
self.argumentCount = argumentCount
|
||||
self.pure = pure
|
||||
self.kind = .function{ (argc, argv) in
|
||||
let arguments = (0..<Int(argc)).map { index in
|
||||
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
|
||||
}
|
||||
return try function(arguments)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an SQL aggregate function.
|
||||
///
|
||||
/// struct MySum : DatabaseAggregate {
|
||||
/// var sum: Int = 0
|
||||
///
|
||||
/// mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
/// if let int = Int.fromDatabaseValue(dbValues[0]) {
|
||||
/// sum += int
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// func finalize() -> DatabaseValueConvertible? {
|
||||
/// return sum
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// dbQueue.add(function: fn)
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.execute("CREATE TABLE test(i)")
|
||||
/// try db.execute("INSERT INTO test(i) VALUES (1)")
|
||||
/// try db.execute("INSERT INTO test(i) VALUES (2)")
|
||||
/// try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
|
||||
/// }
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The function name.
|
||||
/// - argumentCount: The number of arguments of the aggregate. If
|
||||
/// omitted, or nil, the aggregate accepts any number of arguments.
|
||||
/// - pure: Whether the aggregate is "pure", which means that its
|
||||
/// results only depends on its inputs. When an aggregate is pure,
|
||||
/// SQLite has the opportunity to perform additional optimizations.
|
||||
/// Default value is false.
|
||||
/// - aggregate: A type that implements the DatabaseAggregate protocol.
|
||||
/// For each step of the aggregation, its `step` method is called with
|
||||
/// an array of DatabaseValue arguments. The array is guaranteed to
|
||||
/// have exactly *argumentCount* elements, provided *argumentCount* is
|
||||
/// not nil.
|
||||
public init<Aggregate: DatabaseAggregate>(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, aggregate: Aggregate.Type) {
|
||||
self.name = name
|
||||
self.argumentCount = argumentCount
|
||||
self.pure = pure
|
||||
self.kind = .aggregate { return Aggregate() }
|
||||
}
|
||||
|
||||
/// Calls sqlite3_create_function_v2
|
||||
/// See https://sqlite.org/c3ref/create_function.html
|
||||
func install(in db: Database) {
|
||||
// Retain the function definition
|
||||
let definition = kind.definition
|
||||
let definitionP = Unmanaged.passRetained(definition).toOpaque()
|
||||
|
||||
let code = sqlite3_create_function_v2(
|
||||
db.sqliteConnection,
|
||||
name,
|
||||
nArg,
|
||||
eTextRep,
|
||||
definitionP,
|
||||
kind.xFunc,
|
||||
kind.xStep,
|
||||
kind.xFinal,
|
||||
{ definitionP in
|
||||
// Release the function definition
|
||||
Unmanaged<AnyObject>.fromOpaque(definitionP!).release()
|
||||
})
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage).description)
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls sqlite3_create_function_v2
|
||||
/// See https://sqlite.org/c3ref/create_function.html
|
||||
func uninstall(in db: Database) {
|
||||
let code = sqlite3_create_function_v2(
|
||||
db.sqliteConnection,
|
||||
name,
|
||||
nArg,
|
||||
eTextRep,
|
||||
nil, nil, nil, nil, nil)
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage).description)
|
||||
}
|
||||
}
|
||||
|
||||
/// The way to compute the result of a function.
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
private class FunctionDefinition {
|
||||
let compute: (Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?
|
||||
init(compute: @escaping (Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?) {
|
||||
self.compute = compute
|
||||
}
|
||||
}
|
||||
|
||||
/// The way to start an aggregate.
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
private class AggregateDefinition {
|
||||
let makeAggregate: () -> DatabaseAggregate
|
||||
init(makeAggregate: @escaping () -> DatabaseAggregate) {
|
||||
self.makeAggregate = makeAggregate
|
||||
}
|
||||
}
|
||||
|
||||
/// The current state of an aggregate, storable in SQLite
|
||||
private class AggregateContext {
|
||||
var aggregate: DatabaseAggregate
|
||||
var hasErrored = false
|
||||
init(aggregate: DatabaseAggregate) {
|
||||
self.aggregate = aggregate
|
||||
}
|
||||
}
|
||||
|
||||
/// A function kind: an "SQL function" or an "aggregate".
|
||||
/// See http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
private enum Kind {
|
||||
/// A regular function: SELECT f(1)
|
||||
case function((Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?)
|
||||
|
||||
/// An aggregate: SELECT f(foo) FROM bar GROUP BY baz
|
||||
case aggregate(() -> DatabaseAggregate)
|
||||
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
var definition: AnyObject {
|
||||
switch self {
|
||||
case .function(let compute):
|
||||
return FunctionDefinition(compute: compute)
|
||||
case .aggregate(let makeAggregate):
|
||||
return AggregateDefinition(makeAggregate: makeAggregate)
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds the `xFunc` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
var xFunc: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
|
||||
guard case .function = self else { return nil }
|
||||
return { (sqliteContext, argc, argv) in
|
||||
let definition = Unmanaged<FunctionDefinition>.fromOpaque(sqlite3_user_data(sqliteContext)).takeUnretainedValue()
|
||||
do {
|
||||
try DatabaseFunction.report(
|
||||
result: definition.compute(argc, argv),
|
||||
in: sqliteContext)
|
||||
} catch {
|
||||
DatabaseFunction.report(error: error, in: sqliteContext)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds the `xStep` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
var xStep: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
|
||||
guard case .aggregate = self else { return nil }
|
||||
return { (sqliteContext, argc, argv) in
|
||||
let aggregateContextU = DatabaseFunction.unmanagedAggregateContext(sqliteContext)
|
||||
let aggregateContext = aggregateContextU.takeUnretainedValue()
|
||||
assert(!aggregateContext.hasErrored)
|
||||
do {
|
||||
let arguments = (0..<Int(argc)).map { index in
|
||||
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
|
||||
}
|
||||
try aggregateContext.aggregate.step(arguments)
|
||||
} catch {
|
||||
aggregateContext.hasErrored = true
|
||||
DatabaseFunction.report(error: error, in: sqliteContext)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds the `xFinal` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
var xFinal: (@convention(c) (OpaquePointer?) -> Void)? {
|
||||
guard case .aggregate = self else { return nil }
|
||||
return { (sqliteContext) in
|
||||
let aggregateContextU = DatabaseFunction.unmanagedAggregateContext(sqliteContext)
|
||||
let aggregateContext = aggregateContextU.takeUnretainedValue()
|
||||
aggregateContextU.release()
|
||||
|
||||
guard !aggregateContext.hasErrored else {
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
try DatabaseFunction.report(
|
||||
result: aggregateContext.aggregate.finalize(),
|
||||
in: sqliteContext)
|
||||
} catch {
|
||||
DatabaseFunction.report(error: error, in: sqliteContext)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper function that extracts the current state of an aggregate from an
|
||||
/// sqlite function execution context.
|
||||
///
|
||||
/// The result must be released when the aggregate concludes.
|
||||
///
|
||||
/// See https://sqlite.org/c3ref/context.html
|
||||
/// See https://sqlite.org/c3ref/aggregate_context.html
|
||||
private static func unmanagedAggregateContext(_ sqliteContext: OpaquePointer?) -> Unmanaged<AggregateContext> {
|
||||
// The current aggregate buffer
|
||||
let stride = MemoryLayout<Unmanaged<AggregateContext>>.stride
|
||||
let aggregateContextBufferP = UnsafeMutableRawBufferPointer(start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!, count: stride)
|
||||
|
||||
if aggregateContextBufferP.contains(where: { $0 != 0 }) {
|
||||
// Buffer contains non-null pointer: load aggregate context
|
||||
let aggregateContextP = aggregateContextBufferP.baseAddress!.assumingMemoryBound(to: Unmanaged<AggregateContext>.self)
|
||||
return aggregateContextP.pointee
|
||||
} else {
|
||||
// Buffer contains null pointer: create aggregate context...
|
||||
let aggregate = Unmanaged<AggregateDefinition>.fromOpaque(sqlite3_user_data(sqliteContext))
|
||||
.takeUnretainedValue()
|
||||
.makeAggregate()
|
||||
let aggregateContext = AggregateContext(aggregate: aggregate)
|
||||
|
||||
// retain and store in SQLite's buffer
|
||||
let aggregateContextU = Unmanaged.passRetained(aggregateContext)
|
||||
var aggregateContextP = aggregateContextU.toOpaque()
|
||||
withUnsafeBytes(of: &aggregateContextP) {
|
||||
aggregateContextBufferP.copyBytes(from: $0)
|
||||
}
|
||||
return aggregateContextU
|
||||
}
|
||||
}
|
||||
|
||||
private static func report(result: DatabaseValueConvertible?, in sqliteContext: OpaquePointer?) {
|
||||
switch result?.databaseValue.storage ?? .null {
|
||||
case .null:
|
||||
sqlite3_result_null(sqliteContext)
|
||||
case .int64(let int64):
|
||||
sqlite3_result_int64(sqliteContext, int64)
|
||||
case .double(let double):
|
||||
sqlite3_result_double(sqliteContext, double)
|
||||
case .string(let string):
|
||||
sqlite3_result_text(sqliteContext, string, -1, SQLITE_TRANSIENT)
|
||||
case .blob(let data):
|
||||
data.withUnsafeBytes { bytes in
|
||||
sqlite3_result_blob(sqliteContext, bytes, Int32(data.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static func report(error: Error, in sqliteContext: OpaquePointer?) {
|
||||
if let error = error as? DatabaseError {
|
||||
if let message = error.message {
|
||||
sqlite3_result_error(sqliteContext, message, -1)
|
||||
}
|
||||
sqlite3_result_error_code(sqliteContext, error.extendedResultCode.rawValue)
|
||||
} else {
|
||||
sqlite3_result_error(sqliteContext, "\(error)", -1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseFunction : Hashable {
|
||||
/// The hash value
|
||||
public var hashValue: Int {
|
||||
return name.hashValue ^ nArg.hashValue
|
||||
}
|
||||
|
||||
/// Two functions are equal if they share the same name and arity.
|
||||
public static func == (lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool {
|
||||
return lhs.name == rhs.name && lhs.nArg == rhs.nArg
|
||||
}
|
||||
}
|
||||
|
||||
/// The protocol for custom SQLite aggregates.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct MySum : DatabaseAggregate {
|
||||
/// var sum: Int = 0
|
||||
///
|
||||
/// mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
/// if let int = Int.fromDatabaseValue(dbValues[0]) {
|
||||
/// sum += int
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// func finalize() -> DatabaseValueConvertible? {
|
||||
/// return sum
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// dbQueue.add(function: fn)
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.execute("CREATE TABLE test(i)")
|
||||
/// try db.execute("INSERT INTO test(i) VALUES (1)")
|
||||
/// try db.execute("INSERT INTO test(i) VALUES (2)")
|
||||
/// try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
|
||||
/// }
|
||||
public protocol DatabaseAggregate {
|
||||
/// Creates an aggregate.
|
||||
init()
|
||||
|
||||
/// This method is called at each step of the aggregation.
|
||||
///
|
||||
/// The dbValues argument contains as many values as given to the SQL
|
||||
/// aggregate function.
|
||||
///
|
||||
/// -- One value
|
||||
/// SELECT maxLength(name) FROM persons
|
||||
///
|
||||
/// -- Two values
|
||||
/// SELECT maxFullNameLength(firstName, lastName) FROM persons
|
||||
///
|
||||
/// This method is never called after the finalize() method has been called.
|
||||
mutating func step(_ dbValues: [DatabaseValue]) throws
|
||||
|
||||
/// Returns the final result
|
||||
func finalize() throws -> DatabaseValueConvertible?
|
||||
}
|
||||
+113
-59
@@ -1,27 +1,13 @@
|
||||
import Foundation
|
||||
|
||||
#if !USING_BUILTIN_SQLITE
|
||||
#if os(OSX)
|
||||
import SQLiteMacOSX
|
||||
#elseif os(iOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteiPhoneSimulator
|
||||
#else
|
||||
import SQLiteiPhoneOS
|
||||
#endif
|
||||
#elseif os(watchOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteWatchSimulator
|
||||
#else
|
||||
import SQLiteWatchOS
|
||||
#endif
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if os(iOS)
|
||||
import UIKit
|
||||
#endif
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#endif
|
||||
|
||||
/// A DatabasePool grants concurrent accesses to an SQLite database.
|
||||
public final class DatabasePool {
|
||||
|
||||
@@ -41,9 +27,6 @@ public final class DatabasePool {
|
||||
public init(path: String, configuration: Configuration = Configuration()) throws {
|
||||
GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1")
|
||||
|
||||
// Database Store
|
||||
store = try DatabaseStore(path: path, attributes: configuration.fileAttributes)
|
||||
|
||||
// Writer and readers share the same database schema cache
|
||||
let sharedSchemaCache = SharedDatabaseSchemaCache()
|
||||
|
||||
@@ -79,10 +62,8 @@ public final class DatabasePool {
|
||||
// Readers
|
||||
readerConfig = configuration
|
||||
readerConfig.readonly = true
|
||||
readerConfig.defaultTransactionKind = .deferred // Make it the default. Other transaction kinds are forbidden by SQLite in read-only connections.
|
||||
|
||||
readerPool = Pool<SerializedDatabase>(maximumCount: configuration.maximumReaderCount)
|
||||
readerPool.makeElement = { [unowned self] in
|
||||
readerConfig.defaultTransactionKind = .deferred // Make it the default for readers. Other transaction kinds are forbidden by SQLite in read-only connections.
|
||||
readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: { [unowned self] in
|
||||
let reader = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: self.readerConfig,
|
||||
@@ -98,7 +79,7 @@ public final class DatabasePool {
|
||||
}
|
||||
|
||||
return reader
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
@@ -116,7 +97,7 @@ public final class DatabasePool {
|
||||
|
||||
/// The path to the database.
|
||||
public var path: String {
|
||||
return store.path
|
||||
return writer.path
|
||||
}
|
||||
|
||||
|
||||
@@ -130,13 +111,13 @@ public final class DatabasePool {
|
||||
///
|
||||
/// - parameter kind: The checkpoint mode (default passive)
|
||||
public func checkpoint(_ kind: Database.CheckpointMode = .passive) throws {
|
||||
try writer.sync { db in
|
||||
try write { db in
|
||||
// TODO: read https://www.sqlite.org/c3ref/wal_checkpoint_v2.html and
|
||||
// check whether we need a busy handler on writer and/or readers
|
||||
// when kind is not .Passive.
|
||||
let code = sqlite3_wal_checkpoint_v2(db.sqliteConnection, nil, kind.rawValue, nil, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(code: code, message: db.lastErrorMessage, sql: nil)
|
||||
throw DatabaseError(resultCode: code, message: db.lastErrorMessage, sql: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -151,16 +132,10 @@ public final class DatabasePool {
|
||||
/// See also setupMemoryManagement(application:)
|
||||
public func releaseMemory() {
|
||||
// TODO: test that this method blocks the current thread until all database accesses are completed.
|
||||
writer.sync { db in
|
||||
db.releaseMemory()
|
||||
}
|
||||
|
||||
write { $0.releaseMemory() }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { db in
|
||||
db.releaseMemory()
|
||||
}
|
||||
reader.sync { $0.releaseMemory() }
|
||||
}
|
||||
|
||||
readerPool.clear()
|
||||
}
|
||||
|
||||
@@ -212,10 +187,9 @@ public final class DatabasePool {
|
||||
|
||||
// MARK: - Not public
|
||||
|
||||
let store: DatabaseStore // Not private for tests that require syncing with the store
|
||||
fileprivate let writer: SerializedDatabase
|
||||
fileprivate var readerConfig: Configuration
|
||||
fileprivate let readerPool: Pool<SerializedDatabase>
|
||||
fileprivate var readerPool: Pool<SerializedDatabase>! = nil // var and nil-initialized so that we can use `self` when creating readerPool in DatabasePool.init()
|
||||
|
||||
fileprivate var functions = Set<DatabaseFunction>()
|
||||
fileprivate var collations = Set<DatabaseCollation>()
|
||||
@@ -231,9 +205,7 @@ public final class DatabasePool {
|
||||
/// Changes the passphrase of an encrypted database
|
||||
public func change(passphrase: String) throws {
|
||||
try readerPool.clear(andThen: {
|
||||
try writer.sync { db in
|
||||
try db.change(passphrase: passphrase)
|
||||
}
|
||||
try write { try $0.change(passphrase: passphrase) }
|
||||
readerConfig.passphrase = passphrase
|
||||
})
|
||||
}
|
||||
@@ -276,11 +248,12 @@ extension DatabasePool : DatabaseReader {
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
/// happen while establishing the read access to the database.
|
||||
public func read<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
// See DatabasePoolTests.testReadMethodIsolationOfBlock().
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
return try readerPool.get { reader in
|
||||
try reader.sync { db in
|
||||
var result: T? = nil
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
// See DatabasePoolTests.testReadMethodIsolationOfBlock().
|
||||
try db.inTransaction(.deferred) {
|
||||
result = try block(db)
|
||||
return .commit
|
||||
@@ -317,21 +290,78 @@ extension DatabasePool : DatabaseReader {
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
/// happen while establishing the read access to the database.
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
return try readerPool.get { reader in
|
||||
try reader.sync { db in
|
||||
try block(db)
|
||||
try reader.sync(block)
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a read-only block in a protected dispatch queue,
|
||||
/// and returns its result.
|
||||
///
|
||||
/// The block argument is not isolated: eventual concurrent database updates
|
||||
/// are visible inside the block:
|
||||
///
|
||||
/// try dbPool.unsafeReentrantRead { db in
|
||||
/// // Those two values may be different because some other thread
|
||||
/// // may have inserted or deleted a wine between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// }
|
||||
///
|
||||
/// Cursor iteration is safe, though:
|
||||
///
|
||||
/// try dbPool.unsafeReentrantRead { db in
|
||||
/// // No concurrent update can mess with this iteration:
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT ...")
|
||||
/// while let row = try rows.next() { ... }
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
/// happen while establishing the read access to the database.
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
if let reader = currentReader {
|
||||
return try reader.reentrantSync(block)
|
||||
} else {
|
||||
return try readerPool.get { reader in
|
||||
try reader.sync(block)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a reader that can be used from the current dispatch queue,
|
||||
/// if any.
|
||||
private var currentReader: SerializedDatabase? {
|
||||
var readers: [SerializedDatabase] = []
|
||||
readerPool.forEach { reader in
|
||||
// We can't check for reader.onValidQueue here because
|
||||
// Pool.forEach() runs its closure argument in some arbitrary
|
||||
// dispatch queue. We thus extract the reader so that we can query
|
||||
// it below.
|
||||
readers.append(reader)
|
||||
}
|
||||
|
||||
// Now the readers array contains some readers. The pool readers may
|
||||
// already be different, because some other thread may have started
|
||||
// a new read, for example.
|
||||
//
|
||||
// This doesn't matter: the reader we are looking for is already on
|
||||
// its own dispatch queue. If it exists, is still in use, thus still
|
||||
// in the pool, and thus still relevant for our check:
|
||||
return readers.first { $0.onValidQueue }
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
///
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { databaseValues in
|
||||
/// let dbv = databaseValues.first!
|
||||
/// guard let int = dbv.value() as Int? else {
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int + 1
|
||||
@@ -342,15 +372,19 @@ extension DatabasePool : DatabaseReader {
|
||||
/// }
|
||||
public func add(function: DatabaseFunction) {
|
||||
functions.update(with: function)
|
||||
writer.sync { db in db.add(function: function) }
|
||||
readerPool.forEach { $0.sync { db in db.add(function: function) } }
|
||||
write { $0.add(function: function) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.add(function: function) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove an SQL function.
|
||||
public func remove(function: DatabaseFunction) {
|
||||
functions.remove(function)
|
||||
writer.sync { db in db.remove(function: function) }
|
||||
readerPool.forEach { $0.sync { db in db.remove(function: function) } }
|
||||
write { $0.remove(function: function) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.remove(function: function) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -367,15 +401,19 @@ extension DatabasePool : DatabaseReader {
|
||||
/// }
|
||||
public func add(collation: DatabaseCollation) {
|
||||
collations.update(with: collation)
|
||||
writer.sync { db in db.add(collation: collation) }
|
||||
readerPool.forEach { $0.sync { db in db.add(collation: collation) } }
|
||||
write { $0.add(collation: collation) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.add(collation: collation) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a collation.
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
collations.remove(collation)
|
||||
writer.sync { db in db.remove(collation: collation) }
|
||||
readerPool.forEach { $0.sync { db in db.remove(collation: collation) } }
|
||||
write { $0.remove(collation: collation) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.remove(collation: collation) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -449,13 +487,29 @@ extension DatabasePool : DatabaseWriter {
|
||||
/// - throws: The error thrown by the block, or any error establishing the
|
||||
/// transaction.
|
||||
public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws {
|
||||
try writer.sync { db in
|
||||
try write { db in
|
||||
try db.inTransaction(kind) {
|
||||
try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes an update block in a protected dispatch queue,
|
||||
/// and returns its result.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// try dbPool.unsafeReentrantWrite { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.reentrantSync(block)
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
@@ -525,7 +579,7 @@ extension DatabasePool : DatabaseWriter {
|
||||
do {
|
||||
try db.beginTransaction(.deferred)
|
||||
assert(db.isInsideTransaction)
|
||||
try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").fetchCursor().next() // doesn't work with cached statement
|
||||
try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").cursor().next() // doesn't work with cached statement
|
||||
} catch {
|
||||
readError = error
|
||||
semaphore.signal() // Release the writer queue and rethrow error
|
||||
|
||||
+100
-49
@@ -20,7 +20,6 @@ public final class DatabaseQueue {
|
||||
/// - configuration: A configuration.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public init(path: String, configuration: Configuration = Configuration()) throws {
|
||||
store = try DatabaseStore(path: path, attributes: configuration.fileAttributes)
|
||||
serializedDatabase = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
@@ -35,7 +34,6 @@ public final class DatabaseQueue {
|
||||
///
|
||||
/// - parameter configuration: A configuration.
|
||||
public init(configuration: Configuration = Configuration()) {
|
||||
store = nil
|
||||
// Assume SQLite always succeeds creating an in-memory database
|
||||
serializedDatabase = try! SerializedDatabase(
|
||||
path: ":memory:",
|
||||
@@ -61,9 +59,9 @@ public final class DatabaseQueue {
|
||||
return serializedDatabase.configuration
|
||||
}
|
||||
|
||||
/// The path to the database file; nil for in-memory databases.
|
||||
public var path: String! {
|
||||
return store?.path
|
||||
/// The path to the database file; it is ":memory:" for in-memory databases.
|
||||
public var path: String {
|
||||
return serializedDatabase.path
|
||||
}
|
||||
|
||||
|
||||
@@ -107,7 +105,7 @@ public final class DatabaseQueue {
|
||||
/// .commit or .rollback.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func inTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws {
|
||||
try serializedDatabase.sync { db in
|
||||
try inDatabase { db in
|
||||
try db.inTransaction(kind) {
|
||||
try block(db)
|
||||
}
|
||||
@@ -123,9 +121,7 @@ public final class DatabaseQueue {
|
||||
///
|
||||
/// See also setupMemoryManagement(application:)
|
||||
public func releaseMemory() {
|
||||
serializedDatabase.sync { db in
|
||||
db.releaseMemory()
|
||||
}
|
||||
inDatabase { $0.releaseMemory() }
|
||||
}
|
||||
|
||||
|
||||
@@ -175,8 +171,6 @@ public final class DatabaseQueue {
|
||||
|
||||
|
||||
// MARK: - Not public
|
||||
|
||||
private let store: DatabaseStore?
|
||||
|
||||
// https://www.sqlite.org/isolation.html
|
||||
//
|
||||
@@ -207,9 +201,7 @@ public final class DatabaseQueue {
|
||||
|
||||
/// Changes the passphrase of an encrypted database
|
||||
public func change(passphrase: String) throws {
|
||||
try serializedDatabase.sync { db in
|
||||
try db.change(passphrase: passphrase)
|
||||
}
|
||||
try inDatabase { try $0.change(passphrase: passphrase) }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -222,18 +214,51 @@ extension DatabaseQueue : DatabaseReader {
|
||||
|
||||
// MARK: - DatabaseReader Protocol Adoption
|
||||
|
||||
/// Alias for inDatabase
|
||||
/// Synchronously executes a read-only block in a protected dispatch queue,
|
||||
/// and returns its result.
|
||||
///
|
||||
/// This method is part of the DatabaseReader protocol adoption.
|
||||
/// let persons = try dbQueue.read { db in
|
||||
/// try Person.fetchAll(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// Starting iOS 8.2, OSX 10.10, and with custom SQLite builds and
|
||||
/// SQLCipher, attempts to write in the database throw a DatabaseError whose
|
||||
/// resultCode is `SQLITE_READONLY`.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.sync(block)
|
||||
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
return try inDatabase { try readOnly($0, block) }
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, *) {
|
||||
return try inDatabase { try readOnly($0, block) }
|
||||
} else {
|
||||
return try inDatabase(block)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Alias for inDatabase
|
||||
///
|
||||
/// This method is part of the DatabaseReader protocol adoption.
|
||||
/// Alias for `inDatabase`. See `DatabaseReader.unsafeRead`.
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.sync(block)
|
||||
return try inDatabase(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// try dbQueue.unsafeReentrantRead { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try serializedDatabase.reentrantSync(block)
|
||||
}
|
||||
|
||||
|
||||
@@ -241,9 +266,8 @@ extension DatabaseQueue : DatabaseReader {
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
///
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { databaseValues in
|
||||
/// let dbv = databaseValues.first!
|
||||
/// guard let int = dbv.value() as Int? else {
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int + 1
|
||||
@@ -253,16 +277,12 @@ extension DatabaseQueue : DatabaseReader {
|
||||
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
|
||||
/// }
|
||||
public func add(function: DatabaseFunction) {
|
||||
serializedDatabase.sync { db in
|
||||
db.add(function: function)
|
||||
}
|
||||
inDatabase { $0.add(function: function) }
|
||||
}
|
||||
|
||||
/// Remove an SQL function.
|
||||
public func remove(function: DatabaseFunction) {
|
||||
serializedDatabase.sync { db in
|
||||
db.remove(function: function)
|
||||
}
|
||||
inDatabase { $0.remove(function: function) }
|
||||
}
|
||||
|
||||
|
||||
@@ -278,16 +298,12 @@ extension DatabaseQueue : DatabaseReader {
|
||||
/// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD")
|
||||
/// }
|
||||
public func add(collation: DatabaseCollation) {
|
||||
serializedDatabase.sync { db in
|
||||
db.add(collation: collation)
|
||||
}
|
||||
inDatabase { $0.add(collation: collation) }
|
||||
}
|
||||
|
||||
/// Remove a collation.
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
serializedDatabase.sync { db in
|
||||
db.remove(collation: collation)
|
||||
}
|
||||
inDatabase { $0.remove(collation: collation) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -299,25 +315,60 @@ extension DatabaseQueue : DatabaseWriter {
|
||||
|
||||
// MARK: - DatabaseWriter Protocol Adoption
|
||||
|
||||
/// Alias for inDatabase
|
||||
///
|
||||
/// This method is part of the DatabaseWriter protocol adoption.
|
||||
/// Alias for `inDatabase`. See `DatabaseWriter.write`.
|
||||
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try inDatabase(block)
|
||||
}
|
||||
|
||||
/// Alias for inTransaction
|
||||
///
|
||||
/// This method is part of the DatabaseWriter protocol adoption.
|
||||
public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws {
|
||||
try inTransaction(kind, block)
|
||||
}
|
||||
|
||||
/// Synchronously executes *block*.
|
||||
///
|
||||
/// This method is part of the DatabaseWriter protocol adoption, and must
|
||||
/// be called from the protected database dispatch queue.
|
||||
/// Starting iOS 8.2, OSX 10.10, and with custom SQLite builds and
|
||||
/// SQLCipher, attempts to write in the database throw a DatabaseError whose
|
||||
/// resultCode is `SQLITE_READONLY`.
|
||||
///
|
||||
/// This method must be called from the protected database dispatch queue.
|
||||
/// See `DatabaseWriter.readFromCurrentState`.
|
||||
public func readFromCurrentState(_ block: @escaping (Database) -> Void) {
|
||||
serializedDatabase.execute(block)
|
||||
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
serializedDatabase.execute { readOnly($0, block) }
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, *) {
|
||||
serializedDatabase.execute { readOnly($0, block) }
|
||||
} else {
|
||||
serializedDatabase.execute(block)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// try dbQueue.unsafeReentrantWrite { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.reentrantSync(block)
|
||||
}
|
||||
}
|
||||
|
||||
// Wraps the block between two `PRAGMA query_only` statements.
|
||||
//
|
||||
// This method is unsafe because the two calls to `PRAGMA query_only` are
|
||||
// not guaranteed to be serialized (some other thread could mess with this).
|
||||
private func readOnly<T>(_ db: Database, _ block: (Database) throws -> T) rethrows -> T {
|
||||
if db.configuration.readonly {
|
||||
return try block(db)
|
||||
} else {
|
||||
try! db.execute("PRAGMA query_only = 1") // Assume can't fail
|
||||
let result = try block(db)
|
||||
try! db.execute("PRAGMA query_only = 0") // Assume can't fail
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,19 +1,5 @@
|
||||
#if !USING_BUILTIN_SQLITE
|
||||
#if os(OSX)
|
||||
import SQLiteMacOSX
|
||||
#elseif os(iOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteiPhoneSimulator
|
||||
#else
|
||||
import SQLiteiPhoneOS
|
||||
#endif
|
||||
#elseif os(watchOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteWatchSimulator
|
||||
#else
|
||||
import SQLiteWatchOS
|
||||
#endif
|
||||
#endif
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#endif
|
||||
|
||||
/// The protocol for all types that can fetch values from a database.
|
||||
@@ -38,8 +24,8 @@ public protocol DatabaseReader : class {
|
||||
/// Synchronously executes a read-only block that takes a database
|
||||
/// connection, and returns its result.
|
||||
///
|
||||
/// The block argument is isolated. Eventual concurrent database updates are
|
||||
/// not visible inside the block:
|
||||
/// Guarantee 1: the block argument is isolated. Eventual concurrent
|
||||
/// database updates are not visible inside the block:
|
||||
///
|
||||
/// try reader.read { db in
|
||||
/// // Those two values are guaranteed to be equal, even if the
|
||||
@@ -53,6 +39,10 @@ public protocol DatabaseReader : class {
|
||||
/// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// }
|
||||
///
|
||||
/// Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds
|
||||
/// and SQLCipher, attempts to write in the database throw a DatabaseError
|
||||
/// whose resultCode is `SQLITE_READONLY`.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
/// happen while establishing the read access to the database.
|
||||
@@ -61,6 +51,8 @@ public protocol DatabaseReader : class {
|
||||
/// Synchronously executes a read-only block that takes a database
|
||||
/// connection, and returns its result.
|
||||
///
|
||||
/// The two guarantees of the safe `read` method are lifted:
|
||||
///
|
||||
/// The block argument is not isolated: eventual concurrent database updates
|
||||
/// are visible inside the block:
|
||||
///
|
||||
@@ -71,7 +63,7 @@ public protocol DatabaseReader : class {
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// }
|
||||
///
|
||||
/// Cursor iteration is safe, though:
|
||||
/// Cursor iterations are isolated, though:
|
||||
///
|
||||
/// try reader.unsafeRead { db in
|
||||
/// // No concurrent update can mess with this iteration:
|
||||
@@ -79,19 +71,55 @@ public protocol DatabaseReader : class {
|
||||
/// while let row = try rows.next() { ... }
|
||||
/// }
|
||||
///
|
||||
/// The block argument is not prevented from writing (DatabaseQueue, in
|
||||
/// particular, will accept database modifications in `unsafeRead`).
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
/// happen while establishing the read access to the database.
|
||||
func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T
|
||||
|
||||
/// Synchronously executes a block that takes a database connection, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// The two guarantees of the safe `read` method are lifted:
|
||||
///
|
||||
/// The block argument is not isolated: eventual concurrent database updates
|
||||
/// are visible inside the block:
|
||||
///
|
||||
/// try reader.unsafeReentrantRead { db in
|
||||
/// // Those two values may be different because some other thread
|
||||
/// // may have inserted or deleted a wine between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// }
|
||||
///
|
||||
/// Cursor iterations are isolated, though:
|
||||
///
|
||||
/// try reader.unsafeReentrantRead { db in
|
||||
/// // No concurrent update can mess with this iteration:
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT ...")
|
||||
/// while let row = try rows.next() { ... }
|
||||
/// }
|
||||
///
|
||||
/// The block argument is not prevented from writing (DatabaseQueue, in
|
||||
/// particular, will accept database modifications in `unsafeReentrantRead`).
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
/// happen while establishing the read access to the database.
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T
|
||||
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
///
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { databaseValues in
|
||||
/// let dbv = databaseValues.first!
|
||||
/// guard let int = dbv.value() as Int? else {
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int + 1
|
||||
@@ -141,10 +169,10 @@ extension DatabaseReader {
|
||||
try read { dbFrom in
|
||||
try writer.write { dbDest in
|
||||
guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", dbFrom.sqliteConnection, "main") else {
|
||||
throw DatabaseError(code: dbDest.lastErrorCode, message: dbDest.lastErrorMessage)
|
||||
throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage)
|
||||
}
|
||||
guard Int(bitPattern: backup) != Int(SQLITE_ERROR) else {
|
||||
throw DatabaseError(code: SQLITE_ERROR)
|
||||
throw DatabaseError(resultCode: .SQLITE_ERROR)
|
||||
}
|
||||
|
||||
afterBackupInit?()
|
||||
@@ -158,7 +186,7 @@ extension DatabaseReader {
|
||||
case SQLITE_OK:
|
||||
afterBackupStep?()
|
||||
case let code:
|
||||
throw DatabaseError(code: code, message: dbDest.lastErrorMessage)
|
||||
throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
@@ -170,7 +198,7 @@ extension DatabaseReader {
|
||||
case SQLITE_OK:
|
||||
break
|
||||
case let code:
|
||||
throw DatabaseError(code: code, message: dbDest.lastErrorMessage)
|
||||
throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage)
|
||||
}
|
||||
|
||||
dbDest.clearSchemaCache()
|
||||
|
||||
@@ -7,14 +7,17 @@
|
||||
protocol DatabaseSchemaCache {
|
||||
mutating func clear()
|
||||
|
||||
func primaryKey(_ tableName: String) -> PrimaryKeyInfo??
|
||||
mutating func set(primaryKey: PrimaryKeyInfo?, for tableName: String)
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo??
|
||||
mutating func set(primaryKey: PrimaryKeyInfo?, forTable table: String)
|
||||
|
||||
func columns(in tableName: String) -> [ColumnInfo]?
|
||||
mutating func set(columns: [ColumnInfo], forTableName tableName: String)
|
||||
func columns(in table: String) -> [ColumnInfo]?
|
||||
mutating func set(columns: [ColumnInfo], forTable table: String)
|
||||
|
||||
func indexes(on tableName: String) -> [IndexInfo]?
|
||||
mutating func set(indexes: [IndexInfo], forTableName tableName: String)
|
||||
func indexes(on table: String) -> [IndexInfo]?
|
||||
mutating func set(indexes: [IndexInfo], forTable table: String)
|
||||
|
||||
func foreignKeys(on table: String) -> [ForeignKeyInfo]?
|
||||
mutating func set(foreignKeys: [ForeignKeyInfo], forTable table: String)
|
||||
}
|
||||
|
||||
/// A thread-unsafe database schema cache
|
||||
@@ -22,35 +25,45 @@ final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
private var primaryKeys: [String: PrimaryKeyInfo?] = [:]
|
||||
private var columns: [String: [ColumnInfo]] = [:]
|
||||
private var indexes: [String: [IndexInfo]] = [:]
|
||||
private var foreignKeys: [String: [ForeignKeyInfo]] = [:]
|
||||
|
||||
func clear() {
|
||||
primaryKeys = [:]
|
||||
columns = [:]
|
||||
indexes = [:]
|
||||
foreignKeys = [:]
|
||||
}
|
||||
|
||||
func primaryKey(_ tableName: String) -> PrimaryKeyInfo?? {
|
||||
return primaryKeys[tableName]
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo?? {
|
||||
return primaryKeys[table]
|
||||
}
|
||||
|
||||
func set(primaryKey: PrimaryKeyInfo?, for tableName: String) {
|
||||
primaryKeys[tableName] = primaryKey
|
||||
func set(primaryKey: PrimaryKeyInfo?, forTable table: String) {
|
||||
primaryKeys[table] = primaryKey
|
||||
}
|
||||
|
||||
func columns(in tableName: String) -> [ColumnInfo]? {
|
||||
return columns[tableName]
|
||||
func columns(in table: String) -> [ColumnInfo]? {
|
||||
return columns[table]
|
||||
}
|
||||
|
||||
func set(columns: [ColumnInfo], forTableName tableName: String) {
|
||||
self.columns[tableName] = columns
|
||||
func set(columns: [ColumnInfo], forTable table: String) {
|
||||
self.columns[table] = columns
|
||||
}
|
||||
|
||||
func indexes(on tableName: String) -> [IndexInfo]? {
|
||||
return indexes[tableName]
|
||||
func indexes(on table: String) -> [IndexInfo]? {
|
||||
return indexes[table]
|
||||
}
|
||||
|
||||
func set(indexes: [IndexInfo], forTableName tableName: String) {
|
||||
self.indexes[tableName] = indexes
|
||||
func set(indexes: [IndexInfo], forTable table: String) {
|
||||
self.indexes[table] = indexes
|
||||
}
|
||||
|
||||
func foreignKeys(on table: String) -> [ForeignKeyInfo]? {
|
||||
return foreignKeys[table]
|
||||
}
|
||||
|
||||
func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
|
||||
self.foreignKeys[table] = foreignKeys
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,27 +75,35 @@ final class SharedDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
cache.write { $0.clear() }
|
||||
}
|
||||
|
||||
func primaryKey(_ tableName: String) -> PrimaryKeyInfo?? {
|
||||
return cache.read { $0.primaryKey(tableName) }
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo?? {
|
||||
return cache.read { $0.primaryKey(table) }
|
||||
}
|
||||
|
||||
func set(primaryKey: PrimaryKeyInfo?, for tableName: String) {
|
||||
cache.write { $0.set(primaryKey: primaryKey, for: tableName) }
|
||||
func set(primaryKey: PrimaryKeyInfo?, forTable table: String) {
|
||||
cache.write { $0.set(primaryKey: primaryKey, forTable: table) }
|
||||
}
|
||||
|
||||
func columns(in tableName: String) -> [ColumnInfo]? {
|
||||
return cache.read { $0.columns(in: tableName) }
|
||||
func columns(in table: String) -> [ColumnInfo]? {
|
||||
return cache.read { $0.columns(in: table) }
|
||||
}
|
||||
|
||||
func set(columns: [ColumnInfo], forTableName tableName: String) {
|
||||
cache.write { $0.set(columns: columns, forTableName: tableName) }
|
||||
func set(columns: [ColumnInfo], forTable table: String) {
|
||||
cache.write { $0.set(columns: columns, forTable: table) }
|
||||
}
|
||||
|
||||
func indexes(on tableName: String) -> [IndexInfo]? {
|
||||
return cache.read { $0.indexes(on: tableName) }
|
||||
func indexes(on table: String) -> [IndexInfo]? {
|
||||
return cache.read { $0.indexes(on: table) }
|
||||
}
|
||||
|
||||
func set(indexes: [IndexInfo], forTableName tableName: String) {
|
||||
cache.write { $0.set(indexes: indexes, forTableName: tableName) }
|
||||
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) }
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
/// DatabaseStore is responsible for applying Configuration.fileAttributes to
|
||||
/// all database files (db.sqlite, db.sqlite-wal, db.sqlite-shm,
|
||||
/// db.sqlite-journal, etc.)
|
||||
class DatabaseStore {
|
||||
let path: String
|
||||
private let source: DispatchSourceFileSystemObject?
|
||||
private let queue: DispatchQueue?
|
||||
|
||||
init(path: String, attributes: [FileAttributeKey: Any]?) throws {
|
||||
self.path = path
|
||||
|
||||
guard let attributes = attributes else {
|
||||
self.queue = nil
|
||||
self.source = nil
|
||||
return
|
||||
}
|
||||
|
||||
let databaseFileName = (path as NSString).lastPathComponent
|
||||
let directoryPath = (path as NSString).deletingLastPathComponent
|
||||
|
||||
// Apply file attributes on existing files
|
||||
try DatabaseStore.setFileAttributes(
|
||||
directoryPath: directoryPath,
|
||||
databaseFileName: databaseFileName,
|
||||
attributes: attributes)
|
||||
|
||||
// We use a dispatch_source to monitor the contents of the database file
|
||||
// parent directory, and apply file attributes.
|
||||
//
|
||||
// This require a file descriptor on the directory.
|
||||
let directoryDescriptor = open(directoryPath, O_EVTONLY)
|
||||
guard directoryDescriptor != -1 else {
|
||||
// Let FileManager throw a nice NSError
|
||||
try FileManager.default.contentsOfDirectory(atPath: directoryPath)
|
||||
// Come on, FileManager... OK just throw something that is somewhat relevant
|
||||
throw NSError(domain: NSCocoaErrorDomain, code: NSFileReadUnknownError, userInfo: nil)
|
||||
}
|
||||
|
||||
let queue = DispatchQueue(label: "GRDB.DatabaseStore")
|
||||
let source = DispatchSource.makeFileSystemObjectSource(fileDescriptor: Int32(directoryDescriptor), eventMask: [.write], queue: queue)
|
||||
self.queue = queue
|
||||
self.source = source
|
||||
|
||||
// Configure dispatch source
|
||||
source.setEventHandler {
|
||||
// Directory has been modified: apply file attributes on unprocessed files
|
||||
// TODO: handle error and don't crash
|
||||
try! DatabaseStore.setFileAttributes(
|
||||
directoryPath: directoryPath,
|
||||
databaseFileName: databaseFileName,
|
||||
attributes: attributes)
|
||||
}
|
||||
source.setCancelHandler {
|
||||
close(directoryDescriptor)
|
||||
}
|
||||
source.resume()
|
||||
}
|
||||
|
||||
deinit {
|
||||
if let source = source {
|
||||
source.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
private static func setFileAttributes(directoryPath: String, databaseFileName: String, attributes: [FileAttributeKey: Any]) throws {
|
||||
let fm = FileManager.default
|
||||
// TODO: handle symbolic links:
|
||||
//
|
||||
// According to https://www.sqlite.org/changes.html
|
||||
// > 2016-01-06 (3.10.0)
|
||||
// > On unix, if a symlink to a database file is opened, then the
|
||||
// > corresponding journal files are based on the actual filename,
|
||||
// > not the symlink name.
|
||||
let fileNames = try fm.contentsOfDirectory(atPath: directoryPath).filter({ $0.hasPrefix(databaseFileName) })
|
||||
for fileName in fileNames {
|
||||
do {
|
||||
try fm.setAttributes(attributes, ofItemAtPath: (directoryPath as NSString).appendingPathComponent(fileName))
|
||||
} catch let error as NSError {
|
||||
guard error.domain == NSCocoaErrorDomain && error.code == NSFileNoSuchFileError else {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+173
-85
@@ -1,21 +1,7 @@
|
||||
import Foundation
|
||||
|
||||
#if !USING_BUILTIN_SQLITE
|
||||
#if os(OSX)
|
||||
import SQLiteMacOSX
|
||||
#elseif os(iOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteiPhoneSimulator
|
||||
#else
|
||||
import SQLiteiPhoneOS
|
||||
#endif
|
||||
#elseif os(watchOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteWatchSimulator
|
||||
#else
|
||||
import SQLiteWatchOS
|
||||
#endif
|
||||
#endif
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#endif
|
||||
|
||||
// MARK: - DatabaseValue
|
||||
@@ -26,7 +12,7 @@ import Foundation
|
||||
public struct DatabaseValue {
|
||||
|
||||
/// An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB).
|
||||
public enum Storage {
|
||||
public enum Storage : Equatable {
|
||||
/// The NULL storage class.
|
||||
case null
|
||||
|
||||
@@ -41,6 +27,38 @@ public struct DatabaseValue {
|
||||
|
||||
/// The BLOB storage class, wrapping Data.
|
||||
case blob(Data)
|
||||
|
||||
/// Returns Int64, Double, String, Data or nil.
|
||||
public var value: DatabaseValueConvertible? {
|
||||
switch self {
|
||||
case .null:
|
||||
return nil
|
||||
case .int64(let int64):
|
||||
return int64
|
||||
case .double(let double):
|
||||
return double
|
||||
case .string(let string):
|
||||
return string
|
||||
case .blob(let data):
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
/// Return true if the storages are identical.
|
||||
///
|
||||
/// Unlike DatabaseValue equality that considers the integer 1 to be
|
||||
/// equal to the 1.0 double (as SQLite does), int64 and double storages
|
||||
/// are never equal.
|
||||
public static func == (_ lhs: Storage, _ rhs: Storage) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case (.null, .null): return true
|
||||
case (.int64(let lhs), .int64(let rhs)): return lhs == rhs
|
||||
case (.double(let lhs), .double(let rhs)): return lhs == rhs
|
||||
case (.string(let lhs), .string(let rhs)): return lhs == rhs
|
||||
case (.blob(let lhs), .blob(let rhs)): return lhs == rhs
|
||||
default: return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The SQLite storage
|
||||
@@ -72,57 +90,6 @@ public struct DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns Int64, Double, String, Data or nil.
|
||||
public func value() -> DatabaseValueConvertible? {
|
||||
switch storage {
|
||||
case .null:
|
||||
return nil
|
||||
case .int64(let int64):
|
||||
return int64
|
||||
case .double(let double):
|
||||
return double
|
||||
case .string(let string):
|
||||
return string
|
||||
case .blob(let data):
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the value, converted to the requested type.
|
||||
///
|
||||
/// If the SQLite value is NULL, the result is nil. Otherwise the SQLite
|
||||
/// value is converted to the requested type `Value`. Should this conversion
|
||||
/// fail, a fatal error is raised.
|
||||
///
|
||||
/// If this fatal error is unacceptable to you, use
|
||||
/// DatabaseValueConvertible.fromDatabaseValue() method.
|
||||
///
|
||||
/// - returns: An optional *Value*.
|
||||
public func value<Value: DatabaseValueConvertible>() -> Value? {
|
||||
if let value = Value.fromDatabaseValue(self) {
|
||||
return value
|
||||
}
|
||||
guard isNull else {
|
||||
// Programmer error
|
||||
fatalError("could not convert database value \(self) to \(Value.self)")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Returns the value, converted to the requested type.
|
||||
///
|
||||
/// This method crashes if the SQLite value is NULL, or if the SQLite value
|
||||
/// can not be converted to `Value`.
|
||||
///
|
||||
/// - returns: A *Value*.
|
||||
public func value<Value: DatabaseValueConvertible>() -> Value {
|
||||
guard let value = Value.fromDatabaseValue(self) else {
|
||||
// Programmer error
|
||||
fatalError("could not convert database value \(self) to \(Value.self)")
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Not Public
|
||||
|
||||
@@ -209,7 +176,12 @@ extension DatabaseValue : Hashable {
|
||||
/// not lose information:
|
||||
///
|
||||
/// 1.databaseValue == 1.0.databaseValue // true
|
||||
public static func ==(lhs: DatabaseValue, rhs: DatabaseValue) -> Bool {
|
||||
///
|
||||
/// For a comparison that distinguishes integer and doubles, compare
|
||||
/// storages instead:
|
||||
///
|
||||
/// 1.databaseValue.storage == 1.0.databaseValue.storage // false
|
||||
public static func == (lhs: DatabaseValue, rhs: DatabaseValue) -> Bool {
|
||||
switch (lhs.storage, rhs.storage) {
|
||||
case (.null, .null):
|
||||
return true
|
||||
@@ -234,10 +206,7 @@ extension DatabaseValue : Hashable {
|
||||
/// Returns true if i and d hold exactly the same value, and if converting one
|
||||
/// type to the other does not lose any information.
|
||||
private func int64EqualDouble(_ i: Int64, _ d: Double) -> Bool {
|
||||
// TODO: wait for https://github.com/apple/swift-evolution/blob/master/proposals/0080-failable-numeric-initializers.md
|
||||
// Bug: https://bugs.swift.org/browse/SR-1491
|
||||
//
|
||||
// For current implementation, see http://stackoverflow.com/questions/33719132/how-to-test-for-lossless-double-integer-conversion/33784296#33784296
|
||||
// See http://stackoverflow.com/questions/33719132/how-to-test-for-lossless-double-integer-conversion/33784296#33784296
|
||||
return (d >= Double(Int64.min))
|
||||
&& (d < Double(Int64.max))
|
||||
&& (round(d) == d)
|
||||
@@ -245,7 +214,86 @@ private func int64EqualDouble(_ i: Int64, _ d: Double) -> Bool {
|
||||
}
|
||||
|
||||
|
||||
// MARK: - DatabaseValueConvertible
|
||||
// MARK: - Lossless conversions
|
||||
|
||||
extension DatabaseValue {
|
||||
/// Converts the database value to the type T.
|
||||
///
|
||||
/// let dbValue = "foo".databaseValue
|
||||
/// let string = dbValue.losslessConvert() as String // "foo"
|
||||
///
|
||||
/// Conversion is successful if and only if T.fromDatabaseValue returns a
|
||||
/// non-nil value.
|
||||
///
|
||||
/// This method crashes with a fatal error when conversion fails.
|
||||
///
|
||||
/// let dbValue = "foo".databaseValue
|
||||
/// let int = dbValue.losslessConvert() as Int // fatalError
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: Optional SQL statement that enhances the eventual
|
||||
/// conversion error
|
||||
/// - arguments: Optional statement arguments that enhances the eventual
|
||||
/// conversion error
|
||||
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T where T : DatabaseValueConvertible {
|
||||
if let value = T.fromDatabaseValue(self) {
|
||||
return value
|
||||
}
|
||||
// Failed conversion: this is data loss, a programmer error.
|
||||
var error = "could not convert database value \(self) to \(T.self)"
|
||||
if let sql = sql {
|
||||
error += " with statement `\(sql)`"
|
||||
}
|
||||
if let arguments = arguments, !arguments.isEmpty {
|
||||
error += " arguments \(arguments)"
|
||||
}
|
||||
fatalError(error)
|
||||
}
|
||||
|
||||
/// Converts the database value to the type Optional<T>.
|
||||
///
|
||||
/// let dbValue = "foo".databaseValue
|
||||
/// let string = dbValue.losslessConvert() as String? // "foo"
|
||||
/// let null = DatabaseValue.null.losslessConvert() as String? // nil
|
||||
///
|
||||
/// Conversion is successful if and only if T.fromDatabaseValue returns a
|
||||
/// non-nil value.
|
||||
///
|
||||
/// This method crashes with a fatal error when conversion fails.
|
||||
///
|
||||
/// let dbValue = "foo".databaseValue
|
||||
/// let int = dbValue.losslessConvert() as Int? // fatalError
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: Optional SQL statement that enhances the eventual
|
||||
/// conversion error
|
||||
/// - arguments: Optional statement arguments that enhances the eventual
|
||||
/// conversion error
|
||||
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T? where T : DatabaseValueConvertible {
|
||||
// Use fromDatabaseValue first: this allows DatabaseValue to convert NULL to .null.
|
||||
if let value = T.fromDatabaseValue(self) {
|
||||
return value
|
||||
}
|
||||
if isNull {
|
||||
// Failed conversion from null: ok
|
||||
return nil
|
||||
} else {
|
||||
// Failed conversion from a non-null database value: this is data
|
||||
// loss, a programmer error.
|
||||
var error = "could not convert database value \(self) to \(T.self)"
|
||||
if let sql = sql {
|
||||
error += " with statement `\(sql)`"
|
||||
}
|
||||
if let arguments = arguments, !arguments.isEmpty {
|
||||
error += " arguments \(arguments)"
|
||||
}
|
||||
fatalError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - DatabaseValueConvertible & SQLExpressible & SQLExpression
|
||||
|
||||
/// DatabaseValue adopts DatabaseValueConvertible.
|
||||
extension DatabaseValue : DatabaseValueConvertible {
|
||||
@@ -254,24 +302,64 @@ extension DatabaseValue : DatabaseValueConvertible {
|
||||
return self
|
||||
}
|
||||
|
||||
/// Returns `databaseValue`
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> DatabaseValue? {
|
||||
return databaseValue
|
||||
/// Returns the database value
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> DatabaseValue? {
|
||||
return dbValue
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValue : SQLExpressible {
|
||||
|
||||
/// This property is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// See SQLExpression.sqlExpression
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public var sqlExpression: SQLExpression {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
/// DatabaseValue adopts SQLExpression.
|
||||
extension DatabaseValue : SQLExpression {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
// fast path for NULL
|
||||
if isNull {
|
||||
return "NULL"
|
||||
}
|
||||
|
||||
if arguments != nil {
|
||||
arguments!.values.append(self)
|
||||
return "?"
|
||||
} else {
|
||||
// Correctness above all: use SQLite to quote the value.
|
||||
// Assume that the Quote function always succeeds
|
||||
return DatabaseQueue().inDatabase { try! String.fetchOne($0, "SELECT QUOTE(?)", arguments: [self])! }
|
||||
}
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public var negated: SQLExpression {
|
||||
switch storage {
|
||||
case .null:
|
||||
// SELECT NOT NULL -- NULL
|
||||
return DatabaseValue.null
|
||||
case .int64(let int64):
|
||||
return (int64 == 0).sqlExpression
|
||||
case .double(let double):
|
||||
return (double == 0.0).sqlExpression
|
||||
case .string:
|
||||
// We can't assume all strings are true, and return false:
|
||||
//
|
||||
// SELECT NOT '1' -- 0 (because '1' is turned into the integer 1, which is negated into 0)
|
||||
// SELECT NOT '0' -- 1 (because '0' is turned into the integer 0, which is negated into 1)
|
||||
return SQLExpressionNot(self)
|
||||
case .blob:
|
||||
// We can't assume all blobs are true, and return false:
|
||||
//
|
||||
// SELECT NOT X'31' -- 0 (because X'31' is turned into the string '1', then into integer 1, which is negated into 0)
|
||||
// SELECT NOT X'30' -- 1 (because X'30' is turned into the string '0', then into integer 0, which is negated into 1)
|
||||
return SQLExpressionNot(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
|
||||
@@ -1,37 +1,3 @@
|
||||
#if !USING_BUILTIN_SQLITE
|
||||
#if os(OSX)
|
||||
import SQLiteMacOSX
|
||||
#elseif os(iOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteiPhoneSimulator
|
||||
#else
|
||||
import SQLiteiPhoneOS
|
||||
#endif
|
||||
#elseif os(watchOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteWatchSimulator
|
||||
#else
|
||||
import SQLiteWatchOS
|
||||
#endif
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// MARK: - SQLExpressible
|
||||
|
||||
/// The protocol for all types that can be turned into an SQL expression.
|
||||
///
|
||||
/// It is adopted by protocols like DatabaseValueConvertible, and types
|
||||
/// like Column.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
public protocol SQLExpressible {
|
||||
/// Returns an SQLExpression
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
var sqlExpression: SQLExpression { get }
|
||||
}
|
||||
|
||||
|
||||
// MARK: - DatabaseValueConvertible
|
||||
|
||||
/// Types that adopt DatabaseValueConvertible can be initialized from
|
||||
@@ -54,22 +20,14 @@ public protocol DatabaseValueConvertible : SQLExpressible {
|
||||
/// Returns a value that can be stored in the database.
|
||||
var databaseValue: DatabaseValue { get }
|
||||
|
||||
/// Returns a value initialized from *databaseValue*, if possible.
|
||||
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self?
|
||||
/// Returns a value initialized from *dbValue*, if possible.
|
||||
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self?
|
||||
}
|
||||
|
||||
|
||||
// SQLExpressible adoption
|
||||
extension DatabaseValueConvertible {
|
||||
|
||||
/// This property is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// See SQLExpression.sqlExpression
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public var sqlExpression: SQLExpression {
|
||||
return databaseValue
|
||||
}
|
||||
@@ -116,14 +74,10 @@ extension DatabaseValueConvertible {
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
|
||||
// Reuse a single mutable row for performance
|
||||
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
return statement.fetchCursor(arguments: arguments) { () -> Self in
|
||||
let dbv: DatabaseValue = row.value(atIndex: 0)
|
||||
if let value = Self.fromDatabaseValue(dbv) {
|
||||
return value
|
||||
} else {
|
||||
throw DatabaseError(code: SQLITE_ERROR, message: "could not convert database value \(dbv) to \(Self.self)", sql: statement.sql, arguments: arguments)
|
||||
}
|
||||
}
|
||||
return statement.cursor(arguments: arguments, next: {
|
||||
let dbValue: DatabaseValue = row.value(atIndex: 0)
|
||||
return dbValue.losslessConvert(sql: statement.sql, arguments: arguments) as Self
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from a prepared statement.
|
||||
@@ -158,16 +112,10 @@ extension DatabaseValueConvertible {
|
||||
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
|
||||
// Reuse a single mutable row for performance
|
||||
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
let cursor = statement.fetchCursor(arguments: arguments) { () -> Self? in
|
||||
let dbv: DatabaseValue = row.value(atIndex: 0)
|
||||
if let value = Self.fromDatabaseValue(dbv) {
|
||||
return value
|
||||
} else if dbv.isNull {
|
||||
return nil
|
||||
} else {
|
||||
throw DatabaseError(code: SQLITE_ERROR, message: "could not convert database value \(dbv) to \(Self.self)", sql: statement.sql, arguments: arguments)
|
||||
}
|
||||
}
|
||||
let cursor: DatabaseCursor<Self?> = statement.cursor(arguments: arguments, next: {
|
||||
let dbValue: DatabaseValue = row.value(atIndex: 0)
|
||||
return dbValue.losslessConvert(sql: statement.sql, arguments: arguments) as Self?
|
||||
})
|
||||
return try cursor.next() ?? nil
|
||||
}
|
||||
}
|
||||
@@ -329,16 +277,10 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Wrapped?> {
|
||||
// Reuse a single mutable row for performance
|
||||
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
return statement.fetchCursor(arguments: arguments) { () -> Wrapped? in
|
||||
let dbv: DatabaseValue = row.value(atIndex: 0)
|
||||
if let value = Wrapped.fromDatabaseValue(dbv) {
|
||||
return value
|
||||
} else if dbv.isNull {
|
||||
return nil
|
||||
} else {
|
||||
throw DatabaseError(code: SQLITE_ERROR, message: "could not convert database value \(dbv) to \(Wrapped.self)", sql: statement.sql, arguments: arguments)
|
||||
}
|
||||
}
|
||||
return statement.cursor(arguments: arguments, next: {
|
||||
let dbValue: DatabaseValue = row.value(atIndex: 0)
|
||||
return dbValue.losslessConvert(sql: statement.sql, arguments: arguments) as Wrapped?
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a prepared statement.
|
||||
|
||||
@@ -26,7 +26,16 @@ public protocol DatabaseWriter : DatabaseReader {
|
||||
/// This method is *not* reentrant.
|
||||
func write<T>(_ block: (Database) throws -> T) rethrows -> T
|
||||
|
||||
|
||||
/// Synchronously executes a block that takes a database connection, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// Synchronously or asynchronously executes a read-only block that takes a
|
||||
@@ -101,20 +110,16 @@ extension DatabaseWriter {
|
||||
/// Add a transaction observer, so that it gets notified of
|
||||
/// database changes.
|
||||
///
|
||||
/// The transaction observer is weakly referenced: it is not retained, and
|
||||
/// stops getting notifications after it is deallocated.
|
||||
///
|
||||
/// - parameter transactionObserver: A transaction observer.
|
||||
public func add(transactionObserver: TransactionObserver) {
|
||||
write { db in
|
||||
db.add(transactionObserver: transactionObserver)
|
||||
}
|
||||
/// - parameter extent: The duration of the observation. The default is
|
||||
/// the observer lifetime (observation lasts until observer
|
||||
/// is deallocated).
|
||||
public func add(transactionObserver: TransactionObserver, extent: Database.TransactionObservationExtent = .observerLifetime) {
|
||||
write { $0.add(transactionObserver: transactionObserver, extent: extent) }
|
||||
}
|
||||
|
||||
/// Remove a transaction observer.
|
||||
public func remove(transactionObserver: TransactionObserver) {
|
||||
write { db in
|
||||
db.remove(transactionObserver: transactionObserver)
|
||||
}
|
||||
write { $0.remove(transactionObserver: transactionObserver) }
|
||||
}
|
||||
}
|
||||
+175
-70
@@ -1,5 +1,4 @@
|
||||
/// The protocol for all types that define a way to fetch values from
|
||||
/// a database.
|
||||
/// The protocol for all types that define a way to fetch database rows.
|
||||
///
|
||||
/// Requests can feed the fetching methods of any fetchable type (Row,
|
||||
/// value, record):
|
||||
@@ -12,36 +11,90 @@ public protocol Request {
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
|
||||
|
||||
/// The number of rows fetched by the request.
|
||||
///
|
||||
/// Default implementation builds a naive SQL query based on the statement
|
||||
/// returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`.
|
||||
///
|
||||
/// Adopting types can refine this countRequest method and return more
|
||||
/// efficient SQL.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
func fetchCount(_ db: Database) throws -> Int
|
||||
}
|
||||
|
||||
extension Request {
|
||||
/// Returns a TypedRequest bound to type T.
|
||||
/// The number of rows fetched by the request.
|
||||
///
|
||||
/// This default implementation builds a naive SQL query based on the
|
||||
/// statement returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
let (statement, _) = try prepare(db)
|
||||
let sql = "SELECT COUNT(*) FROM (\(statement.sql))"
|
||||
return try Int.fetchOne(db, sql, arguments: statement.arguments)!
|
||||
}
|
||||
}
|
||||
|
||||
extension Request {
|
||||
/// Returns a request bound to type T.
|
||||
///
|
||||
/// The returned request can fetch if the type T is fetchable (Row,
|
||||
/// value, record).
|
||||
///
|
||||
/// // minHeight in Double?
|
||||
/// let minHeight = Person
|
||||
/// .select(min(heightColumn))
|
||||
/// .bound(to: Double.self) // <--
|
||||
/// .asRequest(of: Double.self) // <--
|
||||
/// .fetchOne(db)
|
||||
///
|
||||
/// - parameter type: The fetched type T
|
||||
/// - returns: A typed request bound to type T.
|
||||
public func bound<T>(to type: T.Type) -> AnyTypedRequest<T> {
|
||||
public func asRequest<T>(of type: T.Type) -> AnyTypedRequest<T> {
|
||||
return AnyTypedRequest { try self.prepare($0) }
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns an adapted request.
|
||||
public func adapted(_ makeAdapter: @escaping (Database) throws -> RowAdapter) -> AnyRequest {
|
||||
return AnyRequest { db in
|
||||
let (statement, adapter) = try self.prepare(db)
|
||||
if let adapter = adapter {
|
||||
return try (statement, ChainedAdapter(first: adapter, second: makeAdapter(db)))
|
||||
} else {
|
||||
return try (statement, makeAdapter(db))
|
||||
}
|
||||
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedRequest<Self> {
|
||||
return AdaptedRequest(self, adapter)
|
||||
}
|
||||
}
|
||||
|
||||
/// An adapted request.
|
||||
public struct AdaptedRequest<Base: Request> : Request {
|
||||
/// Creates an adapted request from a base request and a closure that builds
|
||||
/// a row adapter from a database connection.
|
||||
init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) {
|
||||
self.base = base
|
||||
self.adapter = adapter
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
let (statement, baseAdapter) = try base.prepare(db)
|
||||
if let baseAdapter = baseAdapter {
|
||||
return try (statement, ChainedAdapter(first: baseAdapter, second: adapter(db)))
|
||||
} else {
|
||||
return try (statement, adapter(db))
|
||||
}
|
||||
}
|
||||
|
||||
/// The number of rows fetched by the request.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try base.fetchCount(db)
|
||||
}
|
||||
|
||||
private let base: Base
|
||||
private let adapter: (Database) throws -> RowAdapter
|
||||
}
|
||||
|
||||
/// A type-erased Request.
|
||||
@@ -62,6 +115,8 @@ public struct AnyRequest : Request {
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try _prepare(db)
|
||||
}
|
||||
@@ -76,16 +131,48 @@ public struct SQLRequest : Request {
|
||||
///
|
||||
/// let request = SQLRequest("SELECT * FROM persons")
|
||||
/// let request = SQLRequest("SELECT * FROM persons WHERE id = ?", arguments: [1])
|
||||
public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) {
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: A SQLRequest
|
||||
public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) {
|
||||
self.init(sql, arguments: arguments, adapter: adapter, fromCache: cached ? .user : nil)
|
||||
}
|
||||
|
||||
/// Creates a new request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
///
|
||||
/// let request = SQLRequest("SELECT * FROM persons")
|
||||
/// let request = SQLRequest("SELECT * FROM persons WHERE id = ?", arguments: [1])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - statementCacheName: Optional statement cache name.
|
||||
/// - returns: A SQLRequest
|
||||
init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache statementCacheName: Database.StatementCacheName?) {
|
||||
self.sql = sql
|
||||
self.arguments = arguments
|
||||
self.adapter = adapter
|
||||
self.statementCacheName = statementCacheName
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
let statement = try db.makeSelectStatement(sql)
|
||||
let statement: SelectStatement
|
||||
if let statementCacheName = statementCacheName {
|
||||
statement = try db.selectStatement(sql, fromCache: statementCacheName)
|
||||
} else {
|
||||
statement = try db.makeSelectStatement(sql)
|
||||
}
|
||||
if let arguments = arguments {
|
||||
try statement.setArgumentsWithValidation(arguments)
|
||||
}
|
||||
@@ -95,48 +182,74 @@ public struct SQLRequest : Request {
|
||||
private let sql: String
|
||||
private let arguments: StatementArguments?
|
||||
private let adapter: RowAdapter?
|
||||
private let statementCacheName: Database.StatementCacheName?
|
||||
}
|
||||
|
||||
/// The protocol for all types that define a way to fetch values from
|
||||
/// a database, with an attached type.
|
||||
/// The protocol for requests that know how to decode database rows.
|
||||
///
|
||||
/// Typed requests can fetch if their associated type Fetched is fetchable
|
||||
/// (Row, value, record)
|
||||
/// Typed requests can fetch if their associated type RowDecoder is able to
|
||||
/// decode rows (Row, value, record)
|
||||
///
|
||||
/// struct Person: RowConvertible { ... }
|
||||
/// let request: ... // Some TypedRequest that fetches Person
|
||||
/// try request.fetchCursor(db) // DatabaseCursor<Person>
|
||||
/// try request.fetchAll(db) // [Person]
|
||||
/// try request.fetchOne(db) // Person?
|
||||
public protocol TypedRequest : Request {
|
||||
|
||||
/// The fetched type
|
||||
associatedtype Fetched
|
||||
/// The type that can convert raw database rows to fetched values
|
||||
associatedtype RowDecoder
|
||||
}
|
||||
|
||||
extension TypedRequest {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns an adapted typed request.
|
||||
public func adapted(_ makeAdapter: @escaping (Database) throws -> RowAdapter) -> AnyTypedRequest<Fetched> {
|
||||
return AnyTypedRequest { db in
|
||||
let (statement, adapter) = try self.prepare(db)
|
||||
if let adapter = adapter {
|
||||
return try (statement, ChainedAdapter(first: adapter, second: makeAdapter(db)))
|
||||
} else {
|
||||
return try (statement, makeAdapter(db))
|
||||
}
|
||||
}
|
||||
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedTypedRequest<Self> {
|
||||
return AdaptedTypedRequest(self, adapter)
|
||||
}
|
||||
}
|
||||
|
||||
/// An adapted typed request.
|
||||
public struct AdaptedTypedRequest<Base: TypedRequest> : TypedRequest {
|
||||
|
||||
/// The type that can convert raw database rows to fetched values
|
||||
public typealias RowDecoder = Base.RowDecoder
|
||||
|
||||
/// Creates an adapted request from a base request and a closure that builds
|
||||
/// a row adapter from a database connection.
|
||||
init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) {
|
||||
adaptedRequest = AdaptedRequest(base, adapter)
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try adaptedRequest.prepare(db)
|
||||
}
|
||||
|
||||
/// The number of rows fetched by the request.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try adaptedRequest.fetchCount(db)
|
||||
}
|
||||
|
||||
private let adaptedRequest: AdaptedRequest<Base>
|
||||
}
|
||||
|
||||
/// A type-erased TypedRequest.
|
||||
///
|
||||
/// An instance of AnyTypedRequest forwards its operations to an underlying
|
||||
/// typed request, hiding its specifics.
|
||||
public struct AnyTypedRequest<T> : TypedRequest {
|
||||
/// The fetched type
|
||||
public typealias Fetched = T
|
||||
/// The type that can convert raw database rows to fetched values
|
||||
public typealias RowDecoder = T
|
||||
|
||||
/// Creates a new request that wraps and forwards operations to `request`.
|
||||
public init<Request>(_ request: Request) where Request: TypedRequest, Request.Fetched == Fetched {
|
||||
public init<Request>(_ request: Request) where Request: TypedRequest, Request.RowDecoder == RowDecoder {
|
||||
self._prepare = { try request.prepare($0) }
|
||||
}
|
||||
|
||||
@@ -148,6 +261,8 @@ public struct AnyTypedRequest<T> : TypedRequest {
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try _prepare(db)
|
||||
}
|
||||
@@ -155,7 +270,7 @@ public struct AnyTypedRequest<T> : TypedRequest {
|
||||
private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?)
|
||||
}
|
||||
|
||||
extension TypedRequest where Fetched: RowConvertible {
|
||||
extension TypedRequest where RowDecoder: RowConvertible {
|
||||
|
||||
// MARK: Fetching Record and RowConvertible
|
||||
|
||||
@@ -175,8 +290,8 @@ extension TypedRequest where Fetched: RowConvertible {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<Fetched> {
|
||||
return try Fetched.fetchCursor(db, self)
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched records.
|
||||
@@ -187,8 +302,8 @@ extension TypedRequest where Fetched: RowConvertible {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [Fetched] {
|
||||
return try Fetched.fetchAll(db, self)
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
return try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched record.
|
||||
@@ -199,12 +314,12 @@ extension TypedRequest where Fetched: RowConvertible {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional record.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> Fetched? {
|
||||
return try Fetched.fetchOne(db, self)
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
return try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
extension TypedRequest where Fetched: DatabaseValueConvertible {
|
||||
extension TypedRequest where RowDecoder: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching Values
|
||||
|
||||
@@ -224,8 +339,8 @@ extension TypedRequest where Fetched: DatabaseValueConvertible {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<Fetched> {
|
||||
return try Fetched.fetchCursor(db, self)
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched values.
|
||||
@@ -236,8 +351,8 @@ extension TypedRequest where Fetched: DatabaseValueConvertible {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [Fetched] {
|
||||
return try Fetched.fetchAll(db, self)
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
return try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched value.
|
||||
@@ -251,12 +366,12 @@ extension TypedRequest where Fetched: DatabaseValueConvertible {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> Fetched? {
|
||||
return try Fetched.fetchOne(db, self)
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
return try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
extension TypedRequest where Fetched: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
extension TypedRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching Values
|
||||
|
||||
@@ -276,8 +391,8 @@ extension TypedRequest where Fetched: DatabaseValueConvertible & StatementColumn
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<Fetched> {
|
||||
return try Fetched.fetchCursor(db, self)
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched values.
|
||||
@@ -288,8 +403,8 @@ extension TypedRequest where Fetched: DatabaseValueConvertible & StatementColumn
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [Fetched] {
|
||||
return try Fetched.fetchAll(db, self)
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
return try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched value.
|
||||
@@ -303,22 +418,12 @@ extension TypedRequest where Fetched: DatabaseValueConvertible & StatementColumn
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> Fetched? {
|
||||
return try Fetched.fetchOne(db, self)
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
return try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
/// This protocol is an implementation detail of GRDB. Don't use it.
|
||||
public protocol _OptionalFetchable {
|
||||
associatedtype _Wrapped
|
||||
}
|
||||
|
||||
/// This conformance is an implementation detail of GRDB. Don't rely on it.
|
||||
extension Optional : _OptionalFetchable {
|
||||
public typealias _Wrapped = Wrapped
|
||||
}
|
||||
|
||||
extension TypedRequest where Fetched: _OptionalFetchable, Fetched._Wrapped: DatabaseValueConvertible {
|
||||
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching Optional values
|
||||
|
||||
@@ -338,8 +443,8 @@ extension TypedRequest where Fetched: _OptionalFetchable, Fetched._Wrapped: Data
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<Fetched._Wrapped?> {
|
||||
return try Optional<Fetched._Wrapped>.fetchCursor(db, self)
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder._Wrapped?> {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched optional values.
|
||||
@@ -350,12 +455,12 @@ extension TypedRequest where Fetched: _OptionalFetchable, Fetched._Wrapped: Data
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [Fetched._Wrapped?] {
|
||||
return try Optional<Fetched._Wrapped>.fetchAll(db, self)
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchAll(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
extension TypedRequest where Fetched: Row {
|
||||
extension TypedRequest where RowDecoder: Row {
|
||||
|
||||
// MARK: Fetching Rows
|
||||
|
||||
|
||||
+40
-42
@@ -1,21 +1,7 @@
|
||||
import Foundation
|
||||
|
||||
#if !USING_BUILTIN_SQLITE
|
||||
#if os(OSX)
|
||||
import SQLiteMacOSX
|
||||
#elseif os(iOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteiPhoneSimulator
|
||||
#else
|
||||
import SQLiteiPhoneOS
|
||||
#endif
|
||||
#elseif os(watchOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteWatchSimulator
|
||||
#else
|
||||
import SQLiteWatchOS
|
||||
#endif
|
||||
#endif
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#endif
|
||||
|
||||
/// A database row.
|
||||
@@ -43,10 +29,10 @@ public final class Row {
|
||||
guard let columnName = key as? String else {
|
||||
return nil
|
||||
}
|
||||
guard let databaseValue = DatabaseValue(value: value) else {
|
||||
guard let dbValue = DatabaseValue(value: value) else {
|
||||
return nil
|
||||
}
|
||||
initDictionary[columnName] = databaseValue
|
||||
initDictionary[columnName] = dbValue
|
||||
}
|
||||
self.init(initDictionary)
|
||||
}
|
||||
@@ -60,11 +46,11 @@ public final class Row {
|
||||
return impl.copy(self)
|
||||
}
|
||||
|
||||
|
||||
// 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
|
||||
}
|
||||
@@ -156,7 +142,7 @@ extension Row {
|
||||
/// righmost column.
|
||||
public func value(atIndex index: Int) -> DatabaseValueConvertible? {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
|
||||
return impl.databaseValue(atUncheckedIndex: index).value()
|
||||
return impl.databaseValue(atUncheckedIndex: index).storage.value
|
||||
}
|
||||
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
@@ -169,7 +155,7 @@ extension Row {
|
||||
/// fail, a fatal error is raised.
|
||||
public func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value? {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
|
||||
return impl.databaseValue(atUncheckedIndex: index).value()
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
@@ -187,7 +173,7 @@ extension Row {
|
||||
public func value<Value: DatabaseValueConvertible & StatementColumnConvertible>(atIndex index: Int) -> Value? {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
|
||||
guard let sqliteStatement = sqliteStatement else {
|
||||
return impl.databaseValue(atUncheckedIndex: index).value()
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
return Row.statementColumnConvertible(atUncheckedIndex: index, in: sqliteStatement)
|
||||
}
|
||||
@@ -201,7 +187,7 @@ extension Row {
|
||||
/// SQLite value can not be converted to `Value`.
|
||||
public func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
|
||||
return impl.databaseValue(atUncheckedIndex: index).value()
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
@@ -218,7 +204,7 @@ extension Row {
|
||||
public func value<Value: DatabaseValueConvertible & StatementColumnConvertible>(atIndex index: Int) -> Value {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
|
||||
guard let sqliteStatement = sqliteStatement else {
|
||||
return impl.databaseValue(atUncheckedIndex: index).value()
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
return Row.statementColumnConvertible(atUncheckedIndex: index, in: sqliteStatement)
|
||||
}
|
||||
@@ -241,7 +227,7 @@ extension Row {
|
||||
guard let index = impl.index(ofColumn: columnName) else {
|
||||
return nil
|
||||
}
|
||||
return impl.databaseValue(atUncheckedIndex: index).value()
|
||||
return impl.databaseValue(atUncheckedIndex: index).storage.value
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -256,7 +242,7 @@ extension Row {
|
||||
guard let index = impl.index(ofColumn: columnName) else {
|
||||
return nil
|
||||
}
|
||||
return impl.databaseValue(atUncheckedIndex: index).value()
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -276,7 +262,7 @@ extension Row {
|
||||
return nil
|
||||
}
|
||||
guard let sqliteStatement = sqliteStatement else {
|
||||
return impl.databaseValue(atUncheckedIndex: index).value()
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
return Row.statementColumnConvertible(atUncheckedIndex: index, in: sqliteStatement)
|
||||
}
|
||||
@@ -295,7 +281,7 @@ extension Row {
|
||||
// Programmer error
|
||||
fatalError("no such column: \(columnName)")
|
||||
}
|
||||
return impl.databaseValue(atUncheckedIndex: index).value()
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -317,7 +303,7 @@ extension Row {
|
||||
fatalError("no such column: \(columnName)")
|
||||
}
|
||||
guard let sqliteStatement = sqliteStatement else {
|
||||
return impl.databaseValue(atUncheckedIndex: index).value()
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
return Row.statementColumnConvertible(atUncheckedIndex: index, in: sqliteStatement)
|
||||
}
|
||||
@@ -541,7 +527,7 @@ extension Row {
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Row> {
|
||||
// Reuse a single mutable row for performance
|
||||
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
return statement.fetchCursor(arguments: arguments) { row }
|
||||
return statement.cursor(arguments: arguments, next: { row })
|
||||
}
|
||||
|
||||
/// Returns an array of rows fetched from a prepared statement.
|
||||
@@ -573,7 +559,7 @@ extension Row {
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? {
|
||||
// The cursor reuses a single mutable row. Return an immutable copy.
|
||||
return try fetchCursor(statement, arguments: arguments, adapter: adapter).next().flatMap { $0.copy() }
|
||||
return try fetchCursor(statement, arguments: arguments, adapter: adapter).next().map { $0.copy() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -766,11 +752,12 @@ extension Row : Collection {
|
||||
}
|
||||
}
|
||||
|
||||
/// Row adopts Equatable.
|
||||
extension Row : Equatable {
|
||||
|
||||
/// 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.
|
||||
public static func ==(lhs: Row, rhs: Row) -> Bool {
|
||||
public static func == (lhs: Row, rhs: Row) -> Bool {
|
||||
if lhs === rhs {
|
||||
return true
|
||||
}
|
||||
@@ -809,13 +796,22 @@ extension Row : Equatable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Row adopts Hashable.
|
||||
extension Row : Hashable {
|
||||
/// The hash value
|
||||
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`.
|
||||
public var description: String {
|
||||
return "<Row"
|
||||
+ map { (column, dbv) in
|
||||
" \(column):\(dbv)"
|
||||
+ map { (column, dbValue) in
|
||||
" \(column):\(dbValue)"
|
||||
}.joined(separator: "")
|
||||
+ ">"
|
||||
}
|
||||
@@ -824,16 +820,18 @@ extension Row: CustomStringConvertible {
|
||||
|
||||
// MARK: - RowIndex
|
||||
|
||||
/// Indexes to (columnName, databaseValue) pairs in a database row.
|
||||
/// Indexes to (columnName, dbValue) pairs in a database row.
|
||||
public struct RowIndex : Comparable {
|
||||
let index: Int
|
||||
init(_ index: Int) { self.index = index }
|
||||
|
||||
public static func ==(lhs: RowIndex, rhs: RowIndex) -> Bool {
|
||||
/// Equality operator
|
||||
public static func == (lhs: RowIndex, rhs: RowIndex) -> Bool {
|
||||
return lhs.index == rhs.index
|
||||
}
|
||||
|
||||
public static func <(lhs: RowIndex, rhs: RowIndex) -> Bool {
|
||||
// Comparison operator
|
||||
public static func < (lhs: RowIndex, rhs: RowIndex) -> Bool {
|
||||
return lhs.index < rhs.index
|
||||
}
|
||||
}
|
||||
@@ -878,7 +876,7 @@ private struct ArrayRowImpl : RowImpl {
|
||||
}
|
||||
|
||||
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
|
||||
return databaseValue(atUncheckedIndex: index).value()
|
||||
return databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
|
||||
@@ -912,12 +910,12 @@ private struct ArrayRowImpl : RowImpl {
|
||||
|
||||
/// See Row.init(copiedFromStatementRef:sqliteStatement:)
|
||||
private struct StatementCopyRowImpl : RowImpl {
|
||||
let databaseValues: ContiguousArray<DatabaseValue>
|
||||
let dbValues: ContiguousArray<DatabaseValue>
|
||||
let columnNames: [String]
|
||||
|
||||
init(sqliteStatement: SQLiteStatement, columnNames: [String]) {
|
||||
let sqliteStatement = sqliteStatement
|
||||
self.databaseValues = ContiguousArray((0..<sqlite3_column_count(sqliteStatement)).map { DatabaseValue(sqliteStatement: sqliteStatement, index: $0) } as [DatabaseValue])
|
||||
self.dbValues = ContiguousArray((0..<sqlite3_column_count(sqliteStatement)).map { DatabaseValue(sqliteStatement: sqliteStatement, index: $0) } as [DatabaseValue])
|
||||
self.columnNames = columnNames
|
||||
}
|
||||
|
||||
@@ -930,11 +928,11 @@ private struct StatementCopyRowImpl : RowImpl {
|
||||
}
|
||||
|
||||
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
|
||||
return databaseValue(atUncheckedIndex: index).value()
|
||||
return databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
|
||||
return databaseValues[index]
|
||||
return dbValues[index]
|
||||
}
|
||||
|
||||
func columnName(atUncheckedIndex index: Int) -> String {
|
||||
|
||||
+39
-29
@@ -1,23 +1,11 @@
|
||||
#if !USING_BUILTIN_SQLITE
|
||||
#if os(OSX)
|
||||
import SQLiteMacOSX
|
||||
#elseif os(iOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteiPhoneSimulator
|
||||
#else
|
||||
import SQLiteiPhoneOS
|
||||
#endif
|
||||
#elseif os(watchOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteWatchSimulator
|
||||
#else
|
||||
import SQLiteWatchOS
|
||||
#endif
|
||||
#endif
|
||||
#endif
|
||||
import Foundation
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// LayoutedColumnMapping is a type that supports the RowAdapter protocol.
|
||||
public struct LayoutedColumnMapping {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// An array of (baseIndex, mappedName) pairs, where baseIndex is the index
|
||||
/// of a column in a base row, and mappedName the mapped name of
|
||||
/// that column.
|
||||
@@ -26,7 +14,9 @@ public struct LayoutedColumnMapping {
|
||||
/// A cache for layoutIndex(ofColumn:)
|
||||
let lowercaseColumnIndexes: [String: Int] // [mappedColumn: layoutColumnIndex]
|
||||
|
||||
/// Creates an LayoutedColumnMapping from an array of (baseIndex, mappedName)
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Creates a LayoutedColumnMapping from an array of (baseIndex, mappedName)
|
||||
/// pairs. In each pair:
|
||||
///
|
||||
/// - baseIndex is the index of a column in a base row
|
||||
@@ -66,20 +56,26 @@ public struct LayoutedColumnMapping {
|
||||
|
||||
/// LayoutedColumnMapping adopts LayoutedRowAdapter
|
||||
extension LayoutedColumnMapping : LayoutedRowAdapter {
|
||||
/// Part of the LayoutedRowAdapter protocol; returns self.
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns self.
|
||||
public var mapping: LayoutedColumnMapping {
|
||||
return self
|
||||
}
|
||||
|
||||
/// Part of the LayoutedRowAdapter protocol; returns the empty dictionary.
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns the empty dictionary.
|
||||
public var scopes: [String: LayoutedRowAdapter] {
|
||||
return [:]
|
||||
}
|
||||
}
|
||||
|
||||
extension LayoutedColumnMapping : RowLayout {
|
||||
/// Part of the RowLayout protocol; returns the index of the leftmost column
|
||||
/// named `name`, in a case-insensitive way.
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns the index of the leftmost column named `name`, in a
|
||||
/// case-insensitive way.
|
||||
public func layoutIndex(ofColumn name: String) -> Int? {
|
||||
if let index = lowercaseColumnIndexes[name] {
|
||||
return index
|
||||
@@ -88,38 +84,50 @@ extension LayoutedColumnMapping : RowLayout {
|
||||
}
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// LayoutedRowAdapter is a protocol that supports the RowAdapter protocol.
|
||||
///
|
||||
/// GRBD ships with a ready-made type that adopts this protocol:
|
||||
/// LayoutedColumnMapping.
|
||||
public protocol LayoutedRowAdapter {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// A LayoutedColumnMapping that defines how to map a column name to a
|
||||
/// column in a base row.
|
||||
var mapping: LayoutedColumnMapping { get }
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The layouted row adapters for each scope.
|
||||
var scopes: [String: LayoutedRowAdapter] { get }
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// RowLayout is a protocol that supports the RowAdapter protocol. It describes
|
||||
/// a layout of a base row.
|
||||
public protocol RowLayout {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// An array of (baseIndex, name) pairs, where baseIndex is the index
|
||||
/// of a column in a base row, and name the name of that column.
|
||||
var layoutColumns: [(Int, String)] { get }
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns the index of the leftmost column named `name`, in a
|
||||
/// case-insensitive way.
|
||||
func layoutIndex(ofColumn name: String) -> Int?
|
||||
}
|
||||
|
||||
extension SelectStatement : RowLayout {
|
||||
/// Part of the RowLayout protocol.
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public var layoutColumns: [(Int, String)] {
|
||||
return Array(columnNames.enumerated())
|
||||
}
|
||||
|
||||
/// Part of the RowLayout protocol.
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func layoutIndex(ofColumn name: String) -> Int? {
|
||||
return index(ofColumn: name)
|
||||
}
|
||||
@@ -144,6 +152,8 @@ extension SelectStatement : RowLayout {
|
||||
/// try Row.fetchOne(db, sql, adapter: adapter)
|
||||
public protocol RowAdapter {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// You never call this method directly. It is called for you whenever an
|
||||
/// adapter has to be applied.
|
||||
///
|
||||
@@ -202,13 +212,13 @@ public struct ColumnMapping : RowAdapter {
|
||||
self.mapping = mapping
|
||||
}
|
||||
|
||||
/// Part of the RowAdapter protocol
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
let layoutColumns = try mapping
|
||||
.map { (mappedColumn, baseColumn) -> (Int, String) in
|
||||
guard let index = layout.layoutIndex(ofColumn: baseColumn) else {
|
||||
let columnNames = layout.layoutColumns.map { $0.1 }
|
||||
throw DatabaseError(code: SQLITE_MISUSE, message: "Mapping references missing column \(baseColumn). Valid column names are: \(columnNames.joined(separator: ", ")).")
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Mapping references missing column \(baseColumn). Valid column names are: \(columnNames.joined(separator: ", ")).")
|
||||
}
|
||||
let baseIndex = layout.layoutColumns[index].0
|
||||
return (baseIndex, mappedColumn)
|
||||
@@ -238,7 +248,7 @@ public struct SuffixRowAdapter : RowAdapter {
|
||||
self.index = index
|
||||
}
|
||||
|
||||
/// Part of the RowAdapter protocol
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
return LayoutedColumnMapping(layoutColumns: layout.layoutColumns.suffix(from: index))
|
||||
}
|
||||
@@ -267,7 +277,7 @@ public struct RangeRowAdapter : RowAdapter {
|
||||
self.range = range.lowerBound..<(range.upperBound + 1)
|
||||
}
|
||||
|
||||
/// Part of the RowAdapter protocol
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
return LayoutedColumnMapping(layoutColumns: layout.layoutColumns[range])
|
||||
}
|
||||
@@ -317,7 +327,7 @@ public struct ScopeAdapter : RowAdapter {
|
||||
self.scopes = scopes
|
||||
}
|
||||
|
||||
/// Part of the RowAdapter protocol
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
let layoutedAdapter = try mainAdapter.layoutedAdapter(from: layout)
|
||||
var layoutedScopes = layoutedAdapter.scopes
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
import Dispatch
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#endif
|
||||
|
||||
/// SchedulingWatchdog makes sure that databases connections are used on correct
|
||||
/// dispatch queues, and warns the user with a fatal error whenever she misuses
|
||||
/// a database connection.
|
||||
|
||||
@@ -10,6 +10,9 @@ final class SerializedDatabase {
|
||||
return db.configuration
|
||||
}
|
||||
|
||||
/// The path to the database file
|
||||
var path: String
|
||||
|
||||
/// The dispatch queue
|
||||
private let queue: DispatchQueue
|
||||
|
||||
@@ -36,6 +39,7 @@ final class SerializedDatabase {
|
||||
|
||||
db = try Database(path: path, configuration: config, schemaCache: schemaCache)
|
||||
queue = SchedulingWatchdog.makeSerializedQueue(allowingDatabase: db)
|
||||
self.path = path
|
||||
try queue.sync {
|
||||
try db.setup()
|
||||
}
|
||||
@@ -48,8 +52,8 @@ final class SerializedDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a block the serialized dispatch queue, and returns
|
||||
/// its result.
|
||||
/// Synchronously executes a block the serialized dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
func sync<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
@@ -92,7 +96,11 @@ final class SerializedDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
private func reentrantSync<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
/// Synchronously executes a block the serialized dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// This method is reentrant.
|
||||
func reentrantSync<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
// Three different cases:
|
||||
//
|
||||
// 1. A database is invoked from some queue like the main queue:
|
||||
@@ -141,6 +149,11 @@ final class SerializedDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if any only if the current dispatch queue is valid.
|
||||
var onValidQueue: Bool {
|
||||
return SchedulingWatchdog.allows(db)
|
||||
}
|
||||
|
||||
/// Executes the block in the current queue.
|
||||
///
|
||||
/// - precondition: the current dispatch queue is valid.
|
||||
|
||||
+124
-53
@@ -1,21 +1,7 @@
|
||||
import Foundation
|
||||
|
||||
#if !USING_BUILTIN_SQLITE
|
||||
#if os(OSX)
|
||||
import SQLiteMacOSX
|
||||
#elseif os(iOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteiPhoneSimulator
|
||||
#else
|
||||
import SQLiteiPhoneOS
|
||||
#endif
|
||||
#elseif os(watchOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteWatchSimulator
|
||||
#else
|
||||
import SQLiteWatchOS
|
||||
#endif
|
||||
#endif
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#endif
|
||||
|
||||
/// A raw SQLite statement, suitable for the SQLite C API.
|
||||
@@ -32,7 +18,9 @@ public class Statement {
|
||||
|
||||
/// The SQL query
|
||||
public var sql: String {
|
||||
// trim white space and semicolumn for homogeneous output
|
||||
return String(cString: sqlite3_sql(sqliteStatement))
|
||||
.trimmingCharacters(in: CharacterSet(charactersIn: ";").union(.whitespacesAndNewlines))
|
||||
}
|
||||
|
||||
/// The database
|
||||
@@ -62,12 +50,12 @@ public class Statement {
|
||||
}
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(code: code, message: database.lastErrorMessage, sql: sql)
|
||||
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql)
|
||||
}
|
||||
|
||||
guard remainingSQL.isEmpty else {
|
||||
sqlite3_finalize(sqliteStatement)
|
||||
throw DatabaseError(code: SQLITE_MISUSE, message: "Multiple statements found. To execute multiple statements, use Database.execute() instead.", sql: sql, arguments: nil)
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Multiple statements found. To execute multiple statements, use Database.execute() instead.", sql: sql, arguments: nil)
|
||||
}
|
||||
|
||||
self.database = database
|
||||
@@ -86,7 +74,7 @@ public class Statement {
|
||||
// throwing any error.
|
||||
let code = sqlite3_reset(sqliteStatement)
|
||||
guard code == SQLITE_OK else {
|
||||
fatalError(DatabaseError(code: code, message: database.lastErrorMessage, sql: sql).description)
|
||||
fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql).description)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,11 +126,11 @@ public class Statement {
|
||||
var valuesIterator = arguments.values.makeIterator()
|
||||
for (index, argumentName) in sqliteArgumentNames.enumerated() {
|
||||
if let argumentName = argumentName, let value = arguments.namedValues[argumentName] {
|
||||
bind(databaseValue: value, at: index)
|
||||
bind(value, at: index)
|
||||
} else if let value = valuesIterator.next() {
|
||||
bind(databaseValue: value, at: index)
|
||||
bind(value, at: index)
|
||||
} else {
|
||||
bind(databaseValue: .null, at: index)
|
||||
bind(.null, at: index)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -157,15 +145,15 @@ public class Statement {
|
||||
// Apply
|
||||
reset()
|
||||
clearBindings()
|
||||
for (index, databaseValue) in bindings.enumerated() {
|
||||
bind(databaseValue: databaseValue, at: index)
|
||||
for (index, dbValue) in bindings.enumerated() {
|
||||
bind(dbValue, at: index)
|
||||
}
|
||||
}
|
||||
|
||||
// 0-based index
|
||||
private func bind(databaseValue: DatabaseValue, at index: Int) {
|
||||
private func bind(_ dbValue: DatabaseValue, at index: Int) {
|
||||
let code: Int32
|
||||
switch databaseValue.storage {
|
||||
switch dbValue.storage {
|
||||
case .null:
|
||||
code = sqlite3_bind_null(sqliteStatement, Int32(index + 1))
|
||||
case .int64(let int64):
|
||||
@@ -183,7 +171,7 @@ public class Statement {
|
||||
// It looks like sqlite3_bind_xxx() functions do not access the file system.
|
||||
// They should thus succeed, unless a GRDB bug: there is no point throwing any error.
|
||||
guard code == SQLITE_OK else {
|
||||
fatalError(DatabaseError(code: code, message: database.lastErrorMessage, sql: sql).description)
|
||||
fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql).description)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -194,7 +182,7 @@ public class Statement {
|
||||
// no point throwing any error.
|
||||
let code = sqlite3_clear_bindings(sqliteStatement)
|
||||
guard code == SQLITE_OK else {
|
||||
fatalError(DatabaseError(code: code, message: database.lastErrorMessage, sql: sql).description)
|
||||
fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql).description)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,7 +208,8 @@ public class Statement {
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
/// }
|
||||
public final class SelectStatement : Statement {
|
||||
private(set) var selectionInfo: SelectionInfo
|
||||
/// Information about the table and columns read by a SelectStatement
|
||||
public private(set) var selectionInfo: SelectionInfo
|
||||
|
||||
init(database: Database, sql: String) throws {
|
||||
self.selectionInfo = SelectionInfo()
|
||||
@@ -253,7 +242,7 @@ public final class SelectStatement : Statement {
|
||||
}
|
||||
|
||||
/// Creates a DatabaseCursor
|
||||
func fetchCursor<Element>(arguments: StatementArguments? = nil, element: @escaping () throws -> Element) -> DatabaseCursor<Element> {
|
||||
func cursor<Element>(arguments: StatementArguments? = nil, next element: @escaping () throws -> Element) -> DatabaseCursor<Element> {
|
||||
// Check that cursor is built on a valid queue.
|
||||
SchedulingWatchdog.preconditionValidQueue(database, "Database was not used on the correct thread.")
|
||||
|
||||
@@ -266,29 +255,63 @@ public final class SelectStatement : Statement {
|
||||
}
|
||||
|
||||
/// Creates a cursor whose results are ignored
|
||||
func fetchCursor(arguments: StatementArguments? = nil) -> DatabaseCursor<Void> {
|
||||
return fetchCursor(arguments: arguments) { }
|
||||
func cursor(arguments: StatementArguments? = nil) -> DatabaseCursor<Void> {
|
||||
return cursor(arguments: arguments) { }
|
||||
}
|
||||
|
||||
/// Allows inspection of table and columns read by a SelectStatement
|
||||
struct SelectionInfo {
|
||||
/// Information about the table and columns read by a SelectStatement
|
||||
public struct SelectionInfo : CustomStringConvertible {
|
||||
mutating func insert(table: String) {
|
||||
tables.insert(table)
|
||||
}
|
||||
|
||||
mutating func insert(column: String, ofTable table: String) {
|
||||
if selection[table] != nil {
|
||||
selection[table]!.insert(column)
|
||||
if columns[table] != nil {
|
||||
columns[table]!.insert(column)
|
||||
} else {
|
||||
selection[table] = [column]
|
||||
columns[table] = [column]
|
||||
}
|
||||
}
|
||||
|
||||
/// If true, selection is unknown
|
||||
let isUnknown: Bool
|
||||
|
||||
/// Relevant iff isUnknown is false
|
||||
func contains(anyColumnFrom table: String) -> Bool {
|
||||
return selection.index(forKey: table) != nil
|
||||
return tables.contains(table) || columns.index(forKey: table) != nil
|
||||
}
|
||||
|
||||
/// Relevant iff isUnknown is false
|
||||
func contains(anyColumnIn columns: Set<String>, from table: String) -> Bool {
|
||||
return !(selection[table]?.isDisjoint(with: columns) ?? true)
|
||||
return tables.contains(table) || !(self.columns[table]?.isDisjoint(with: columns) ?? true)
|
||||
}
|
||||
|
||||
private var selection: [String: Set<String>] = [:] // [TableName: Set<ColumnName>]
|
||||
init() {
|
||||
self.init(isUnknown: false)
|
||||
}
|
||||
|
||||
static func unknown() -> SelectionInfo {
|
||||
return self.init(isUnknown: true)
|
||||
}
|
||||
|
||||
// `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 {
|
||||
// TODO: include tables in the description
|
||||
return columns
|
||||
.sorted { $0.key < $1.key }
|
||||
.map { (table, columns) in "\(table)(\(columns.sorted().joined(separator: ", ")))" }
|
||||
.joined(separator: ", ")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -325,9 +348,9 @@ public final class DatabaseCursor<Element> : Cursor {
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return try element()
|
||||
case let errorCode:
|
||||
case let code:
|
||||
statement.database.selectStatementDidFail(statement)
|
||||
throw DatabaseError(code: errorCode, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -426,13 +449,13 @@ public final class UpdateStatement : Statement {
|
||||
database.updateStatementDidExecute(self)
|
||||
return
|
||||
|
||||
case let errorCode:
|
||||
case let code:
|
||||
// Failure
|
||||
//
|
||||
// Let database rethrow eventual transaction observer error:
|
||||
try database.updateStatementDidFail(self)
|
||||
|
||||
throw DatabaseError(code: errorCode, message: database.lastErrorMessage, sql: sql, arguments: self.arguments) // Error uses self.arguments, not the optional arguments parameter.
|
||||
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql, arguments: self.arguments) // Error uses self.arguments, not the optional arguments parameter.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -552,10 +575,10 @@ public struct StatementArguments {
|
||||
public init?(_ array: [Any]) {
|
||||
var values = [DatabaseValueConvertible?]()
|
||||
for value in array {
|
||||
guard let databaseValue = DatabaseValue(value: value) else {
|
||||
guard let dbValue = DatabaseValue(value: value) else {
|
||||
return nil
|
||||
}
|
||||
values.append(databaseValue)
|
||||
values.append(dbValue)
|
||||
}
|
||||
self.init(values)
|
||||
}
|
||||
@@ -600,10 +623,10 @@ public struct StatementArguments {
|
||||
guard let columnName = key as? String else {
|
||||
return nil
|
||||
}
|
||||
guard let databaseValue = DatabaseValue(value: value) else {
|
||||
guard let dbValue = DatabaseValue(value: value) else {
|
||||
return nil
|
||||
}
|
||||
initDictionary[columnName] = databaseValue
|
||||
initDictionary[columnName] = dbValue
|
||||
}
|
||||
self.init(initDictionary)
|
||||
}
|
||||
@@ -775,23 +798,23 @@ public struct StatementArguments {
|
||||
let initialValuesCount = values.count
|
||||
let bindings = try statement.sqliteArgumentNames.map { argumentName -> DatabaseValue in
|
||||
if let argumentName = argumentName {
|
||||
if let databaseValue = namedValues[argumentName] {
|
||||
return databaseValue
|
||||
if let dbValue = namedValues[argumentName] {
|
||||
return dbValue
|
||||
} else if values.isEmpty {
|
||||
throw DatabaseError(code: SQLITE_MISUSE, message: "missing statement argument: \(argumentName)", sql: statement.sql, arguments: nil)
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "missing statement argument: \(argumentName)", sql: statement.sql, arguments: nil)
|
||||
} else {
|
||||
return values.removeFirst()
|
||||
}
|
||||
} else {
|
||||
if values.isEmpty {
|
||||
throw DatabaseError(code: SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)", sql: statement.sql, arguments: nil)
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)", sql: statement.sql, arguments: nil)
|
||||
} else {
|
||||
return values.removeFirst()
|
||||
}
|
||||
}
|
||||
}
|
||||
if !allowingRemainingValues && !values.isEmpty {
|
||||
throw DatabaseError(code: SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)", sql: statement.sql, arguments: nil)
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)", sql: statement.sql, arguments: nil)
|
||||
}
|
||||
return bindings
|
||||
}
|
||||
@@ -825,3 +848,51 @@ extension StatementArguments : CustomStringConvertible {
|
||||
return "[" + (namedValuesDescriptions + valuesDescriptions).joined(separator: ", ") + "]"
|
||||
}
|
||||
}
|
||||
|
||||
/// A thread-unsafe statement cache
|
||||
struct StatementCache {
|
||||
unowned let db: Database
|
||||
private var selectStatements: [String: SelectStatement] = [:]
|
||||
private var updateStatements: [String: UpdateStatement] = [:]
|
||||
|
||||
init(database: Database) {
|
||||
self.db = database
|
||||
}
|
||||
|
||||
mutating func selectStatement(_ sql: String) throws -> SelectStatement {
|
||||
if let statement = selectStatements[sql] {
|
||||
return statement
|
||||
}
|
||||
|
||||
let statement = try db.makeSelectStatement(sql)
|
||||
selectStatements[sql] = statement
|
||||
return statement
|
||||
}
|
||||
|
||||
mutating func updateStatement(_ sql: String) throws -> UpdateStatement {
|
||||
if let statement = updateStatements[sql] {
|
||||
return statement
|
||||
}
|
||||
|
||||
let statement = try db.makeUpdateStatement(sql)
|
||||
updateStatements[sql] = statement
|
||||
return statement
|
||||
}
|
||||
|
||||
mutating func clear() {
|
||||
updateStatements = [:]
|
||||
selectStatements = [:]
|
||||
}
|
||||
|
||||
mutating func remove(_ statement: SelectStatement) {
|
||||
if let index = selectStatements.index(where: { $0.1 === statement }) {
|
||||
selectStatements.remove(at: index)
|
||||
}
|
||||
}
|
||||
|
||||
mutating func remove(_ statement: UpdateStatement) {
|
||||
if let index = updateStatements.index(where: { $0.1 === statement }) {
|
||||
updateStatements.remove(at: index)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,5 @@
|
||||
#if !USING_BUILTIN_SQLITE
|
||||
#if os(OSX)
|
||||
import SQLiteMacOSX
|
||||
#elseif os(iOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteiPhoneSimulator
|
||||
#else
|
||||
import SQLiteiPhoneOS
|
||||
#endif
|
||||
#elseif os(watchOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteWatchSimulator
|
||||
#else
|
||||
import SQLiteWatchOS
|
||||
#endif
|
||||
#endif
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#endif
|
||||
|
||||
/// When a type adopts both DatabaseValueConvertible and
|
||||
@@ -75,12 +61,16 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
// We'll read from leftmost column at index 0, unless adapter mangles columns
|
||||
let columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
|
||||
let sqliteStatement = statement.sqliteStatement
|
||||
return statement.fetchCursor(arguments: arguments) {
|
||||
return statement.cursor(arguments: arguments, next: {
|
||||
if sqlite3_column_type(sqliteStatement, columnIndex) == SQLITE_NULL {
|
||||
throw DatabaseError(code: SQLITE_ERROR, message: "could not convert database value NULL to \(Self.self)", sql: statement.sql, arguments: arguments)
|
||||
var error = "could not convert database value NULL to \(Self.self) with statement `\(statement.sql)`"
|
||||
if let arguments = arguments, !arguments.isEmpty {
|
||||
error += " arguments \(arguments)"
|
||||
}
|
||||
fatalError(error)
|
||||
}
|
||||
return Self.init(sqliteStatement: sqliteStatement, index: columnIndex)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from a prepared statement.
|
||||
@@ -113,12 +103,12 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
// We'll read from leftmost column at index 0, unless adapter mangles columns
|
||||
let columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
|
||||
let sqliteStatement = statement.sqliteStatement
|
||||
let cursor = statement.fetchCursor(arguments: arguments) { () -> Self? in
|
||||
let cursor: DatabaseCursor<Self?> = statement.cursor(arguments: arguments, next: {
|
||||
if sqlite3_column_type(sqliteStatement, columnIndex) == SQLITE_NULL {
|
||||
return nil
|
||||
}
|
||||
return Self.init(sqliteStatement: sqliteStatement, index: columnIndex)
|
||||
}
|
||||
})
|
||||
return try cursor.next() ?? nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,9 +8,9 @@ extension CGFloat : DatabaseValueConvertible {
|
||||
return Double(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a CGFloat initialized from *databaseValue*, if possible.
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> CGFloat? {
|
||||
guard let double = Double.fromDatabaseValue(databaseValue) else {
|
||||
/// Returns a CGFloat initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> CGFloat? {
|
||||
guard let double = Double.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
}
|
||||
return CGFloat(double)
|
||||
|
||||
@@ -11,10 +11,10 @@ extension Data : DatabaseValueConvertible {
|
||||
return DatabaseValue(storage: .blob(self))
|
||||
}
|
||||
|
||||
/// Returns a Data initialized from *databaseValue*, if it contains
|
||||
/// Returns a Data initialized from *dbValue*, if it contains
|
||||
/// a Blob.
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Data? {
|
||||
guard case .blob(let data) = databaseValue.storage else {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Data? {
|
||||
guard case .blob(let data) = dbValue.storage else {
|
||||
return nil
|
||||
}
|
||||
return data
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
/// DatabaseCoder reads and stores objects that conform to NSCoding in
|
||||
/// the database.
|
||||
public struct DatabaseCoder: DatabaseValueConvertible {
|
||||
|
||||
/// The object
|
||||
public let object: Any
|
||||
|
||||
/// Creates a DatabaseCoder from an object that conforms to NSCoding.
|
||||
///
|
||||
/// The result is nil if and only if *object* is nil.
|
||||
public init?(_ object: Any?) {
|
||||
guard let object = object else {
|
||||
return nil
|
||||
}
|
||||
self.object = object
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return NSKeyedArchiver.archivedData(withRootObject: object).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a DatabaseCoder if *databaseValue* contains an archived object.
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> DatabaseCoder? {
|
||||
guard let data = Data.fromDatabaseValue(databaseValue) else {
|
||||
return nil
|
||||
}
|
||||
return DatabaseCoder(NSKeyedUnarchiver.unarchiveObject(with: data))
|
||||
}
|
||||
}
|
||||
@@ -108,9 +108,9 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
|
||||
return [dateString, timeString].flatMap { $0 }.joined(separator: " ").databaseValue
|
||||
}
|
||||
|
||||
/// Returns a DatabaseDateComponents if *databaseValue* contains a
|
||||
/// Returns a DatabaseDateComponents if *dbValue* contains a
|
||||
/// valid date.
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> DatabaseDateComponents? {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> DatabaseDateComponents? {
|
||||
// https://www.sqlite.org/lang_datefunc.html
|
||||
//
|
||||
// Supported formats are:
|
||||
@@ -127,7 +127,7 @@ public struct DatabaseDateComponents : DatabaseValueConvertible {
|
||||
// - HH:MM:SS.SSS
|
||||
|
||||
// We need a String
|
||||
guard let string = String.fromDatabaseValue(databaseValue) else {
|
||||
guard let string = String.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -9,12 +9,12 @@ extension NSDate : DatabaseValueConvertible {
|
||||
return storageDateFormatter.string(from: self as Date).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a Date initialized from *databaseValue*, if possible.
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
if let databaseDateComponents = DatabaseDateComponents.fromDatabaseValue(databaseValue) {
|
||||
/// Returns a Date initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
if let databaseDateComponents = DatabaseDateComponents.fromDatabaseValue(dbValue) {
|
||||
return cast(fromDatabaseDateComponents(databaseDateComponents))
|
||||
}
|
||||
if let julianDayNumber = Double.fromDatabaseValue(databaseValue) {
|
||||
if let julianDayNumber = Double.fromDatabaseValue(dbValue) {
|
||||
return cast(fromJulianDayNumber(julianDayNumber))
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -8,10 +8,10 @@ extension NSData : DatabaseValueConvertible {
|
||||
return (self as Data).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an NSData initialized from *databaseValue*, if it contains
|
||||
/// Returns an NSData initialized from *dbValue*, if it contains
|
||||
/// a Blob.
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
guard let data = Data.fromDatabaseValue(databaseValue) else {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
guard let data = Data.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
}
|
||||
return cast(data)
|
||||
|
||||
@@ -9,7 +9,7 @@ extension NSNull : DatabaseValueConvertible {
|
||||
}
|
||||
|
||||
/// Returns nil.
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -53,9 +53,9 @@ extension NSNumber : DatabaseValueConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an NSNumber initialized from *databaseValue*, if possible.
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
switch databaseValue.storage {
|
||||
/// Returns an NSNumber initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64):
|
||||
return self.init(value: int64)
|
||||
case .double(let double):
|
||||
|
||||
@@ -8,9 +8,9 @@ extension NSString : DatabaseValueConvertible {
|
||||
return (self as String).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an NSString initialized from *databaseValue*, if possible.
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
guard let string = String.fromDatabaseValue(databaseValue) else {
|
||||
/// Returns an NSString initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
guard let string = String.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
}
|
||||
return self.init(string: string)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import Foundation
|
||||
|
||||
/// DatabaseValueConvertible is free for ReferenceConvertible types whose
|
||||
/// ReferenceType is itself DatabaseValueConvertible.
|
||||
///
|
||||
@@ -18,8 +20,8 @@ extension ReferenceConvertible where Self: DatabaseValueConvertible, Self.Refere
|
||||
return (self as! ReferenceType).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a value initialized from *databaseValue*, if possible.
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
return ReferenceType.fromDatabaseValue(databaseValue).flatMap { cast($0) }
|
||||
/// Returns a value initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
return ReferenceType.fromDatabaseValue(dbValue).flatMap { cast($0) }
|
||||
}
|
||||
}
|
||||
@@ -9,9 +9,9 @@ extension NSURL : DatabaseValueConvertible {
|
||||
return absoluteString?.databaseValue ?? .null
|
||||
}
|
||||
|
||||
/// Returns an NSURL initialized from *databaseValue*, if possible.
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
guard let string = String.fromDatabaseValue(databaseValue) else {
|
||||
/// Returns an NSURL initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
guard let string = String.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
}
|
||||
return cast(URL(string: string))
|
||||
|
||||
@@ -7,14 +7,14 @@ extension NSUUID : DatabaseValueConvertible {
|
||||
public var databaseValue: DatabaseValue {
|
||||
var uuidBytes = ContiguousArray(repeating: UInt8(0), count: 16)
|
||||
return uuidBytes.withUnsafeMutableBufferPointer { buffer in
|
||||
getBytes(buffer.baseAddress)
|
||||
getBytes(buffer.baseAddress!)
|
||||
return NSData(bytes: buffer.baseAddress, length: 16).databaseValue
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an NSUUID initialized from *databaseValue*, if possible.
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
guard let data = NSData.fromDatabaseValue(databaseValue), data.length == 16 else {
|
||||
/// Returns an NSUUID initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
guard let data = NSData.fromDatabaseValue(dbValue), data.length == 16 else {
|
||||
return nil
|
||||
}
|
||||
return self.init(uuidBytes: data.bytes.assumingMemoryBound(to: UInt8.self))
|
||||
|
||||
@@ -17,8 +17,8 @@ extension RawRepresentable where Self: DatabaseValueConvertible, Self.RawValue:
|
||||
return rawValue.databaseValue
|
||||
}
|
||||
|
||||
/// Returns a value initialized from *databaseValue*, if possible.
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
return RawValue.fromDatabaseValue(databaseValue).flatMap { self.init(rawValue: $0) }
|
||||
/// Returns a value initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
return RawValue.fromDatabaseValue(dbValue).flatMap { self.init(rawValue: $0) }
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,7 @@
|
||||
#if !USING_BUILTIN_SQLITE
|
||||
#if os(OSX)
|
||||
import SQLiteMacOSX
|
||||
#elseif os(iOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteiPhoneSimulator
|
||||
#else
|
||||
import SQLiteiPhoneOS
|
||||
#endif
|
||||
#elseif os(watchOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteWatchSimulator
|
||||
#else
|
||||
import SQLiteWatchOS
|
||||
#endif
|
||||
#endif
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#endif
|
||||
|
||||
|
||||
// MARK: - Value Types
|
||||
|
||||
/// Bool adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -36,8 +21,8 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
return (self ? 1 : 0).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a Bool initialized from *databaseValue*, if possible.
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Bool? {
|
||||
/// Returns a Bool initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Bool? {
|
||||
// IMPLEMENTATION NOTE
|
||||
//
|
||||
// https://www.sqlite.org/lang_expr.html#booleanexpr
|
||||
@@ -94,7 +79,7 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
// the natural boolean storage class, and Real because Numeric affinity
|
||||
// store big numbers as Real.
|
||||
|
||||
switch databaseValue.storage {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64):
|
||||
return (int64 != 0)
|
||||
case .double(let double):
|
||||
@@ -115,8 +100,11 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
GRDBPrecondition(int64 >= Int64(Int.min) && int64 <= Int64(Int.max), "could not convert database value \(int64) to Int")
|
||||
self = Int(int64)
|
||||
if let v = Int(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalError("could not convert database value \(int64) to Int")
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@@ -124,24 +112,15 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
return Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an Int initialized from *databaseValue*, if possible.
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Int? {
|
||||
switch databaseValue.storage {
|
||||
/// Returns an Int initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64):
|
||||
guard int64 >= Int64(Int.min) else { return nil }
|
||||
guard int64 <= Int64(Int.max) else { return nil }
|
||||
return Int(int64)
|
||||
return Int(exactly: int64)
|
||||
case .double(let double):
|
||||
// Cast from Double to Int64 to Int
|
||||
// Why? Because on 32-bits platforms we'll convert more values this way (Swift bug?)
|
||||
// - Int(Int64(-2147483648.999999)) // -2147483648
|
||||
// - Int(-2147483648.999999) // fatal error
|
||||
guard double >= Double(Int64.min) else { return nil }
|
||||
guard double < Double(Int64.max) else { return nil }
|
||||
let int64 = Int64(double)
|
||||
guard int64 >= Int64(Int.min) else { return nil }
|
||||
guard int64 <= Int64(Int.max) else { return nil }
|
||||
return Int(int64)
|
||||
return Int(exactly: Int64(double))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
@@ -158,8 +137,11 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
GRDBPrecondition(int64 >= Int64(Int32.min) && int64 <= Int64(Int32.max), "could not convert database value \(int64) to Int32")
|
||||
self = Int32(int64)
|
||||
if let v = Int32(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalError("could not convert database value \(int64) to Int32")
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
@@ -167,24 +149,15 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
return Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an Int32 initialized from *databaseValue*, if possible.
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Int32? {
|
||||
switch databaseValue.storage {
|
||||
/// Returns an Int32 initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int32? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64):
|
||||
guard int64 >= Int64(Int32.min) else { return nil }
|
||||
guard int64 <= Int64(Int32.max) else { return nil }
|
||||
return Int32(int64)
|
||||
return Int32(exactly: int64)
|
||||
case .double(let double):
|
||||
// Cast from Double to Int64 to Int32
|
||||
// Why? Because we'll convert more values this way (Swift bug?)
|
||||
// - Int32(Int64(-2147483648.999999)) // -2147483648
|
||||
// - Int32(-2147483648.999999) // fatal error
|
||||
guard double >= Double(Int64.min) else { return nil }
|
||||
guard double < Double(Int64.max) else { return nil }
|
||||
let int64 = Int64(double)
|
||||
guard int64 >= Int64(Int32.min) else { return nil }
|
||||
guard int64 <= Int64(Int32.max) else { return nil }
|
||||
return Int32(int64)
|
||||
return Int32(exactly: Int64(double))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
@@ -208,9 +181,9 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
return DatabaseValue(storage: .int64(self))
|
||||
}
|
||||
|
||||
/// Returns an Int64 initialized from *databaseValue*, if possible.
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Int64? {
|
||||
switch databaseValue.storage {
|
||||
/// Returns an Int64 initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int64? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64):
|
||||
return int64
|
||||
case .double(let double):
|
||||
@@ -240,9 +213,9 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
return DatabaseValue(storage: .double(self))
|
||||
}
|
||||
|
||||
/// Returns a Double initialized from *databaseValue*, if possible.
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Double? {
|
||||
switch databaseValue.storage {
|
||||
/// Returns a Double initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Double? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64):
|
||||
return Double(int64)
|
||||
case .double(let double):
|
||||
@@ -270,9 +243,9 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
return Double(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a Float initialized from *databaseValue*, if possible.
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Float? {
|
||||
switch databaseValue.storage {
|
||||
/// Returns a Float initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Float? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64):
|
||||
return Float(int64)
|
||||
case .double(let double):
|
||||
@@ -300,9 +273,9 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
return DatabaseValue(storage: .string(self))
|
||||
}
|
||||
|
||||
/// Returns a String initialized from *databaseValue*, if possible.
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> String? {
|
||||
switch databaseValue.storage {
|
||||
/// Returns a String initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> String? {
|
||||
switch dbValue.storage {
|
||||
case .string(let string):
|
||||
return string
|
||||
default:
|
||||
@@ -327,8 +300,8 @@ extension DatabaseFunction {
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.capitalized)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
public static let capitalize = DatabaseFunction("swiftCapitalizedString", argumentCount: 1, pure: true) { databaseValues in
|
||||
guard let string = String.fromDatabaseValue(databaseValues[0]) else {
|
||||
public static let capitalize = DatabaseFunction("swiftCapitalizedString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
return nil
|
||||
}
|
||||
return string.capitalized
|
||||
@@ -346,8 +319,8 @@ extension DatabaseFunction {
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.lowercased())
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
public static let lowercase = DatabaseFunction("swiftLowercaseString", argumentCount: 1, pure: true) { databaseValues in
|
||||
guard let string = String.fromDatabaseValue(databaseValues[0]) else {
|
||||
public static let lowercase = DatabaseFunction("swiftLowercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
return nil
|
||||
}
|
||||
return string.lowercased()
|
||||
@@ -365,8 +338,8 @@ extension DatabaseFunction {
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.uppercased())
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
public static let uppercase = DatabaseFunction("swiftUppercaseString", argumentCount: 1, pure: true) { databaseValues in
|
||||
guard let string = String.fromDatabaseValue(databaseValues[0]) else {
|
||||
public static let uppercase = DatabaseFunction("swiftUppercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
return nil
|
||||
}
|
||||
return string.uppercased()
|
||||
@@ -387,8 +360,8 @@ extension DatabaseFunction {
|
||||
/// let request = Person.select(nameColumn.localizedCapitalized)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
|
||||
public static let localizedCapitalize = DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { databaseValues in
|
||||
guard let string = String.fromDatabaseValue(databaseValues[0]) else {
|
||||
public static let localizedCapitalize = DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
return nil
|
||||
}
|
||||
return string.localizedCapitalized
|
||||
@@ -407,8 +380,8 @@ extension DatabaseFunction {
|
||||
/// let request = Person.select(nameColumn.localizedLowercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
|
||||
public static let localizedLowercase = DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { databaseValues in
|
||||
guard let string = String.fromDatabaseValue(databaseValues[0]) else {
|
||||
public static let localizedLowercase = DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
return nil
|
||||
}
|
||||
return string.localizedLowercase
|
||||
@@ -427,8 +400,8 @@ extension DatabaseFunction {
|
||||
/// let request = Person.select(nameColumn.localizedUppercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
|
||||
public static let localizedUppercase = DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { databaseValues in
|
||||
guard let string = String.fromDatabaseValue(databaseValues[0]) else {
|
||||
public static let localizedUppercase = DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
return nil
|
||||
}
|
||||
return string.localizedUppercase
|
||||
|
||||
@@ -1,279 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
#if !USING_BUILTIN_SQLITE
|
||||
#if os(OSX)
|
||||
import SQLiteMacOSX
|
||||
#elseif os(iOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteiPhoneSimulator
|
||||
#else
|
||||
import SQLiteiPhoneOS
|
||||
#endif
|
||||
#elseif os(watchOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteWatchSimulator
|
||||
#else
|
||||
import SQLiteWatchOS
|
||||
#endif
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
// MARK: - Public
|
||||
|
||||
extension String {
|
||||
/// Returns the receiver, quoted for safe insertion as an identifier in an
|
||||
/// SQL query.
|
||||
///
|
||||
/// db.execute("SELECT * FROM \(tableName.quotedDatabaseIdentifier)")
|
||||
public var quotedDatabaseIdentifier: String {
|
||||
// See https://www.sqlite.org/lang_keywords.html
|
||||
return "\"" + self + "\""
|
||||
}
|
||||
}
|
||||
|
||||
/// Return as many question marks separated with commas as the *count* argument.
|
||||
///
|
||||
/// databaseQuestionMarks(count: 3) // "?,?,?"
|
||||
public func databaseQuestionMarks(count: Int) -> String {
|
||||
return Array(repeating: "?", count: count).joined(separator: ",")
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Internal
|
||||
|
||||
let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_destructor_type.self)
|
||||
|
||||
/// Custom precondition function which aims at solving
|
||||
/// https://bugs.swift.org/browse/SR-905 and
|
||||
/// https://github.com/groue/GRDB.swift/issues/37
|
||||
///
|
||||
/// TODO: remove this function when https://bugs.swift.org/browse/SR-905 is solved.
|
||||
func GRDBPrecondition(_ condition: @autoclosure() -> Bool, _ message: @autoclosure() -> String = "", file: StaticString = #file, line: UInt = #line) {
|
||||
if !condition() {
|
||||
fatalError(message, file: file, line: line)
|
||||
}
|
||||
}
|
||||
|
||||
// Workaround Swift inconvenience around factory methods of non-final classes
|
||||
func cast<T, U>(_ value: T) -> U? {
|
||||
return value as? U
|
||||
}
|
||||
|
||||
extension Array {
|
||||
/// Removes the first object that matches *predicate*.
|
||||
mutating func removeFirst(_ predicate: (Element) throws -> Bool) rethrows {
|
||||
if let index = try index(where: predicate) {
|
||||
remove(at: index)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Dictionary {
|
||||
|
||||
/// Create a dictionary with the keys and values in the given sequence.
|
||||
init<Sequence: Swift.Sequence>(keyValueSequence: Sequence) where Sequence.Iterator.Element == (Key, Value) {
|
||||
self.init(minimumCapacity: keyValueSequence.underestimatedCount)
|
||||
for (key, value) in keyValueSequence {
|
||||
self[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a dictionary from keys and a value builder.
|
||||
init<Sequence: Swift.Sequence>(keys: Sequence, value: (Key) -> Value) where Sequence.Iterator.Element == Key {
|
||||
self.init(minimumCapacity: keys.underestimatedCount)
|
||||
for key in keys {
|
||||
self[key] = value(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A ReadWriteBox grants multiple readers and single-writer guarantees on a value.
|
||||
final class ReadWriteBox<T> {
|
||||
var value: T {
|
||||
get { return read { $0 } }
|
||||
set { write { $0 = newValue } }
|
||||
}
|
||||
|
||||
init(_ value: T) {
|
||||
self._value = value
|
||||
self.queue = DispatchQueue(label: "GRDB.ReadWriteBox", attributes: [.concurrent])
|
||||
}
|
||||
|
||||
func read<U>(_ block: (T) -> U) -> U {
|
||||
var result: U? = nil
|
||||
queue.sync {
|
||||
result = block(self._value)
|
||||
}
|
||||
return result!
|
||||
}
|
||||
|
||||
func write(_ block: (inout T) -> Void) {
|
||||
queue.sync(flags: [.barrier]) {
|
||||
block(&self._value)
|
||||
}
|
||||
}
|
||||
|
||||
private var _value: T
|
||||
private var queue: DispatchQueue
|
||||
}
|
||||
|
||||
/// A Pool maintains a set of elements that are built them on demand. A pool has
|
||||
/// a maximum number of elements.
|
||||
///
|
||||
/// // A pool of 3 integers
|
||||
/// var number = 0
|
||||
/// let pool = Pool<Int>(maximumCount: 3, makeElement: {
|
||||
/// number = number + 1
|
||||
/// return number
|
||||
/// })
|
||||
///
|
||||
/// The function get() dequeues an available element and gives this element to
|
||||
/// the block argument. During the block execution, the element is not
|
||||
/// available. When the block is ended, the element is available again.
|
||||
///
|
||||
/// // got 1
|
||||
/// pool.get { n in
|
||||
/// print("got \(n)")
|
||||
/// }
|
||||
///
|
||||
/// If there is no available element, the pool builds a new element, unless the
|
||||
/// maximum number of elements is reached. In this case, the get() method
|
||||
/// blocks the current thread, until an element eventually turns available again.
|
||||
///
|
||||
/// DispatchQueue.concurrentPerform(iterations: 6) { _ in
|
||||
/// pool.get { n in
|
||||
/// print("got \(n)")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// got 1
|
||||
/// got 2
|
||||
/// got 3
|
||||
/// got 2
|
||||
/// got 1
|
||||
/// got 3
|
||||
final class Pool<T> {
|
||||
var makeElement: (() throws -> T)?
|
||||
private var items: [PoolItem<T>] = []
|
||||
private let queue: DispatchQueue // protects items
|
||||
private let semaphore: DispatchSemaphore // limits the number of elements
|
||||
|
||||
init(maximumCount: Int, makeElement: (() throws -> T)? = nil) {
|
||||
GRDBPrecondition(maximumCount > 0, "Pool size must be at least 1")
|
||||
self.makeElement = makeElement
|
||||
self.queue = DispatchQueue(label: "GRDB.Pool")
|
||||
self.semaphore = DispatchSemaphore(value: maximumCount)
|
||||
}
|
||||
|
||||
/// Returns a tuple (element, releaseElement())
|
||||
/// Client MUST call releaseElement() after the element has been used.
|
||||
func get() throws -> (T, () -> ()) {
|
||||
var item: PoolItem<T>! = nil
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
do {
|
||||
try queue.sync {
|
||||
if let availableItem = items.first(where: { $0.available }) {
|
||||
item = availableItem
|
||||
item.available = false
|
||||
} else {
|
||||
item = try PoolItem(element: makeElement!(), available: false)
|
||||
items.append(item)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
semaphore.signal()
|
||||
throw error
|
||||
}
|
||||
let unlock = {
|
||||
self.queue.sync {
|
||||
item.available = true
|
||||
}
|
||||
self.semaphore.signal()
|
||||
}
|
||||
return (item.element, unlock)
|
||||
}
|
||||
|
||||
/// Performs a synchronous block with an element. The element turns
|
||||
/// available after the block has executed.
|
||||
func get<U>(block: (T) throws -> U) throws -> U {
|
||||
let (element, release) = try get()
|
||||
defer { release() }
|
||||
return try block(element)
|
||||
}
|
||||
|
||||
/// Performs a block on each pool element, available or not.
|
||||
/// The block is run is some arbitrary queue.
|
||||
func forEach(_ body: (T) throws -> ()) rethrows {
|
||||
try queue.sync {
|
||||
for item in items {
|
||||
try body(item.element)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Empty the pool. Currently used items won't be reused.
|
||||
func clear() {
|
||||
clear {}
|
||||
}
|
||||
|
||||
/// Empty the pool. Currently used items won't be reused.
|
||||
/// Eventual block is executed before any other element is dequeued.
|
||||
func clear(andThen block: () throws -> ()) rethrows {
|
||||
try queue.sync {
|
||||
items = []
|
||||
try block()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class PoolItem<T> {
|
||||
let element: T
|
||||
var available: Bool
|
||||
|
||||
init(element: T, available: Bool) {
|
||||
self.element = element
|
||||
self.available = available
|
||||
}
|
||||
}
|
||||
|
||||
enum Result<Value> {
|
||||
case success(Value)
|
||||
case failure(Error)
|
||||
|
||||
static func wrap(_ value: () throws -> Value) -> Result<Value> {
|
||||
do {
|
||||
return try .success(value())
|
||||
} catch {
|
||||
return .failure(error)
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluates the given closure when this `Result` is a success, passing the
|
||||
/// unwrapped value as a parameter.
|
||||
///
|
||||
/// Use the `map` method with a closure that does not throw. For example:
|
||||
///
|
||||
/// let possibleData: Result<Data> = .success(Data())
|
||||
/// let possibleInt = possibleData.map { $0.count }
|
||||
/// try print(possibleInt.unwrap())
|
||||
/// // Prints "0"
|
||||
///
|
||||
/// let noData: Result<Data> = .failure(error)
|
||||
/// let noInt = noData.map { $0.count }
|
||||
/// try print(noInt.unwrap())
|
||||
/// // Throws error
|
||||
///
|
||||
/// - parameter transform: A closure that takes the success value of
|
||||
/// the instance.
|
||||
/// - returns: A `Result` containing the result of the given closure. If
|
||||
/// this instance is a failure, returns the same failure.
|
||||
func map<T>(_ transform: (Value) -> T) -> Result<T> {
|
||||
switch self {
|
||||
case .success(let value):
|
||||
return .success(transform(value))
|
||||
case .failure(let error):
|
||||
return .failure(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
+48
-63
@@ -24,13 +24,14 @@ public struct FTS3Pattern {
|
||||
}
|
||||
} catch let error as DatabaseError {
|
||||
// Remove private SQL & arguments from the thrown error
|
||||
throw DatabaseError(code: error.code, message: error.message, sql: nil, arguments: nil)
|
||||
throw DatabaseError(resultCode: error.extendedResultCode, message: error.message, sql: nil, arguments: nil)
|
||||
}
|
||||
|
||||
// Pattern is valid
|
||||
self.rawPattern = rawPattern
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// Creates a pattern that matches any token found in the input string;
|
||||
/// returns nil if no pattern could be built.
|
||||
///
|
||||
@@ -69,6 +70,49 @@ public struct FTS3Pattern {
|
||||
guard !tokens.isEmpty else { return nil }
|
||||
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
|
||||
}
|
||||
#else
|
||||
/// Creates a pattern that matches any token found in the input string;
|
||||
/// returns nil if no pattern could be built.
|
||||
///
|
||||
/// FTS3Pattern(matchingAnyTokenIn: "") // nil
|
||||
/// FTS3Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar
|
||||
///
|
||||
/// - parameter string: The string to turn into an FTS3 pattern
|
||||
@available(iOS 8.2, OSX 10.10, *)
|
||||
public init?(matchingAnyTokenIn string: String) {
|
||||
let tokens = FTS3TokenizerDescriptor.simple.tokenize(string)
|
||||
guard !tokens.isEmpty else { return nil }
|
||||
try? self.init(rawPattern: tokens.joined(separator: " OR "))
|
||||
}
|
||||
|
||||
/// Creates a pattern that matches all tokens found in the input string;
|
||||
/// returns nil if no pattern could be built.
|
||||
///
|
||||
/// FTS3Pattern(matchingAllTokensIn: "") // nil
|
||||
/// FTS3Pattern(matchingAllTokensIn: "foo bar") // foo bar
|
||||
///
|
||||
/// - parameter string: The string to turn into an FTS3 pattern
|
||||
@available(iOS 8.2, OSX 10.10, *)
|
||||
public init?(matchingAllTokensIn string: String) {
|
||||
let tokens = FTS3TokenizerDescriptor.simple.tokenize(string)
|
||||
guard !tokens.isEmpty else { return nil }
|
||||
try? self.init(rawPattern: tokens.joined(separator: " "))
|
||||
}
|
||||
|
||||
/// Creates a pattern that matches a contiguous string; returns nil if no
|
||||
/// pattern could be built.
|
||||
///
|
||||
/// FTS3Pattern(matchingPhrase: "") // nil
|
||||
/// FTS3Pattern(matchingPhrase: "foo bar") // "foo bar"
|
||||
///
|
||||
/// - parameter string: The string to turn into an FTS3 pattern
|
||||
@available(iOS 8.2, OSX 10.10, *)
|
||||
public init?(matchingPhrase string: String) {
|
||||
let tokens = FTS3TokenizerDescriptor.simple.tokenize(string)
|
||||
guard !tokens.isEmpty else { return nil }
|
||||
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
extension FTS3Pattern : DatabaseValueConvertible {
|
||||
@@ -77,70 +121,11 @@ extension FTS3Pattern : DatabaseValueConvertible {
|
||||
return rawPattern.databaseValue
|
||||
}
|
||||
|
||||
/// Returns an FTS3Pattern initialized from *databaseValue*, if it contains
|
||||
/// Returns an FTS3Pattern initialized from *dbValue*, if it contains
|
||||
/// a suitable value.
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> FTS3Pattern? {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> FTS3Pattern? {
|
||||
return String
|
||||
.fromDatabaseValue(databaseValue)
|
||||
.fromDatabaseValue(dbValue)
|
||||
.flatMap { try? FTS3Pattern(rawPattern: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
|
||||
// MARK: Full Text Search
|
||||
|
||||
/// Returns a new QueryInterfaceRequest with a matching predicate added
|
||||
/// to the eventual set of already applied predicates.
|
||||
///
|
||||
/// // SELECT * FROM books WHERE books MATCH '...'
|
||||
/// var request = Book.all()
|
||||
/// request = request.matching(pattern)
|
||||
///
|
||||
/// If the search pattern is nil, the request does not match any
|
||||
/// database row.
|
||||
public func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<T> {
|
||||
switch query.source {
|
||||
case .table(let name, let alias)?:
|
||||
return filter(SQLExpressionBinary(.match, Column(alias ?? name), pattern ?? DatabaseValue.null))
|
||||
default:
|
||||
// Programmer error
|
||||
fatalError("fts3 match requires a table")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
|
||||
// MARK: Full Text Search
|
||||
|
||||
/// Returns a QueryInterfaceRequest with a matching predicate.
|
||||
///
|
||||
/// // SELECT * FROM books WHERE books MATCH '...'
|
||||
/// var request = Book.matching(pattern)
|
||||
///
|
||||
/// If the `selectsRowID` type property is true, then the selection includes
|
||||
/// the hidden "rowid" column:
|
||||
///
|
||||
/// // SELECT *, rowid FROM books WHERE books MATCH '...'
|
||||
/// var request = Book.matching(pattern)
|
||||
///
|
||||
/// If the search pattern is nil, the request does not match any
|
||||
/// database row.
|
||||
public static func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<Self> {
|
||||
return all().matching(pattern)
|
||||
}
|
||||
}
|
||||
|
||||
extension Column {
|
||||
/// A matching SQL expression with the `MATCH` SQL operator.
|
||||
///
|
||||
/// // content MATCH '...'
|
||||
/// Column("content").match(pattern)
|
||||
///
|
||||
/// If the search pattern is nil, SQLite will evaluate the expression
|
||||
/// to false.
|
||||
public func match(_ pattern: FTS3Pattern?) -> SQLExpression {
|
||||
return SQLExpressionBinary(.match, self, pattern ?? DatabaseValue.null)
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,7 @@ public struct FTS3TokenizerDescriptor {
|
||||
/// See https://www.sqlite.org/fts3.html#tokenizer
|
||||
public static let porter = FTS3TokenizerDescriptor("porter")
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The "unicode61" tokenizer.
|
||||
///
|
||||
/// db.create(virtualTable: "books", using: FTS4()) { t in
|
||||
@@ -48,6 +49,33 @@ public struct FTS3TokenizerDescriptor {
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#tokenizer
|
||||
public static func unicode61(removeDiacritics: Bool = true, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor {
|
||||
return _unicode61(removeDiacritics: removeDiacritics, separators: separators, tokenCharacters: tokenCharacters)
|
||||
}
|
||||
#else
|
||||
/// The "unicode61" tokenizer.
|
||||
///
|
||||
/// db.create(virtualTable: "books", using: FTS4()) { t in
|
||||
/// t.tokenizer = .unicode61()
|
||||
/// }
|
||||
///
|
||||
/// - parameters:
|
||||
/// - removeDiacritics: If true (the default), then SQLite will strip
|
||||
/// diacritics from latin characters.
|
||||
/// - separators: Unless empty (the default), SQLite will consider these
|
||||
/// characters as token separators.
|
||||
/// - tokenCharacters: Unless empty (the default), SQLite will consider
|
||||
/// these characters as token characters.
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#tokenizer
|
||||
@available(iOS 8.2, OSX 10.10, *)
|
||||
public static func unicode61(removeDiacritics: Bool = true, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor {
|
||||
// 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)
|
||||
return _unicode61(removeDiacritics: removeDiacritics, separators: separators, tokenCharacters: tokenCharacters)
|
||||
}
|
||||
#endif
|
||||
|
||||
private static func _unicode61(removeDiacritics: Bool = true, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor {
|
||||
var arguments: [String] = []
|
||||
if !removeDiacritics {
|
||||
arguments.append("remove_diacritics=0")
|
||||
@@ -63,10 +91,23 @@ public struct FTS3TokenizerDescriptor {
|
||||
return FTS3TokenizerDescriptor("unicode61", arguments: arguments)
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
func tokenize(_ string: String) -> [String] {
|
||||
return _tokenize(string)
|
||||
}
|
||||
#else
|
||||
@available(iOS 8.2, OSX 10.10, *)
|
||||
func tokenize(_ string: String) -> [String] {
|
||||
return _tokenize(string)
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Returns an array of tokens found in the string argument.
|
||||
///
|
||||
/// FTS3TokenizerDescriptor.simple.tokenize("foo bar") // ["foo", "bar"]
|
||||
func tokenize(_ string: String) -> [String] {
|
||||
private func _tokenize(_ string: String) -> [String] {
|
||||
// fts3tokenize was introduced in SQLite 3.7.17 https://www.sqlite.org/changes.html#version_3_7_17
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
return DatabaseQueue().inDatabase { db in
|
||||
var tokenizerChunks: [String] = []
|
||||
tokenizerChunks.append(name)
|
||||
|
||||
@@ -263,6 +263,7 @@ public final class FTS4ColumnDefinition {
|
||||
self.isLanguageId = false
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// Excludes the column from the full-text index.
|
||||
///
|
||||
/// try db.create(virtualTable: "persons", using: FTS4()) { t in
|
||||
@@ -275,9 +276,31 @@ public final class FTS4ColumnDefinition {
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@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
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
self.isIndexed = false
|
||||
return self
|
||||
}
|
||||
#else
|
||||
/// Excludes the column from the full-text index.
|
||||
///
|
||||
/// try db.create(virtualTable: "persons", using: FTS4()) { t in
|
||||
/// t.column("a")
|
||||
/// t.column("b").notIndexed()
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#the_notindexed_option
|
||||
///
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@available(iOS 8.2, OSX 10.10, *)
|
||||
@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
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
self.isIndexed = false
|
||||
return self
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Uses the column as the Int32 language id hidden column.
|
||||
///
|
||||
|
||||
@@ -81,7 +81,7 @@
|
||||
tokenizerHandle.pointee = tokenizerPointer
|
||||
return SQLITE_OK
|
||||
} catch let error as DatabaseError {
|
||||
return error.code
|
||||
return error.extendedResultCode.rawValue
|
||||
} catch {
|
||||
return SQLITE_ERROR
|
||||
}
|
||||
@@ -134,7 +134,7 @@
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError(DatabaseError(code: code, message: lastErrorMessage).description)
|
||||
fatalError(DatabaseError(resultCode: code, message: lastErrorMessage).description)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,12 +62,12 @@
|
||||
}
|
||||
}
|
||||
try db.makeSelectStatement("SELECT * FROM documents WHERE documents MATCH ?")
|
||||
.fetchCursor(arguments: [rawPattern])
|
||||
.cursor(arguments: [rawPattern])
|
||||
.next() // error on next() for invalid patterns
|
||||
}
|
||||
} catch let error as DatabaseError {
|
||||
// Remove private SQL & arguments from the thrown error
|
||||
throw DatabaseError(code: error.code, message: error.message, sql: nil, arguments: nil)
|
||||
throw DatabaseError(resultCode: error.extendedResultCode, message: error.message, sql: nil, arguments: nil)
|
||||
}
|
||||
|
||||
// Pattern is valid
|
||||
@@ -95,62 +95,12 @@
|
||||
return rawPattern.databaseValue
|
||||
}
|
||||
|
||||
/// Returns an FTS5Pattern initialized from *databaseValue*, if it
|
||||
/// Returns an FTS5Pattern initialized from *dbValue*, if it
|
||||
/// contains a suitable value.
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> FTS5Pattern? {
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> FTS5Pattern? {
|
||||
return String
|
||||
.fromDatabaseValue(databaseValue)
|
||||
.fromDatabaseValue(dbValue)
|
||||
.flatMap { try? FTS5Pattern(rawPattern: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
|
||||
// MARK: Full Text Search
|
||||
|
||||
/// Returns a new QueryInterfaceRequest with a matching predicate added
|
||||
/// to the eventual set of already applied predicates.
|
||||
///
|
||||
/// // SELECT * FROM books WHERE books MATCH '...'
|
||||
/// var request = Book.all()
|
||||
/// request = request.matching(pattern)
|
||||
///
|
||||
/// If the search pattern is nil, the request does not match any
|
||||
/// database row.
|
||||
public func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest<T> {
|
||||
switch query.source {
|
||||
case .table(let name, let alias)?:
|
||||
if let pattern = pattern {
|
||||
return filter(SQLExpressionBinary(.match, Column(alias ?? name), pattern))
|
||||
} else {
|
||||
return filter(false)
|
||||
}
|
||||
default:
|
||||
// Programmer error
|
||||
fatalError("fts5 match requires a table")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
|
||||
// MARK: Full Text Search
|
||||
|
||||
/// Returns a QueryInterfaceRequest with a matching predicate.
|
||||
///
|
||||
/// // SELECT * FROM books WHERE books MATCH '...'
|
||||
/// var request = Book.matching(pattern)
|
||||
///
|
||||
/// If the `selectsRowID` type property is true, then the selection
|
||||
/// includes the hidden "rowid" column:
|
||||
///
|
||||
/// // SELECT *, rowid FROM books WHERE books MATCH '...'
|
||||
/// var request = Book.matching(pattern)
|
||||
///
|
||||
/// If the search pattern is nil, the request does not match any
|
||||
/// database row.
|
||||
public static func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest<Self> {
|
||||
return all().matching(pattern)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -87,7 +87,7 @@
|
||||
return SQLITE_OK
|
||||
})
|
||||
if (code != SQLITE_OK) {
|
||||
throw DatabaseError(code: code)
|
||||
throw DatabaseError(resultCode: code)
|
||||
}
|
||||
}
|
||||
return context.tokens
|
||||
@@ -116,7 +116,7 @@
|
||||
|
||||
init(xTokenizer: fts5_tokenizer, contextPointer: UnsafeMutableRawPointer?, arguments: [String]) throws {
|
||||
guard let xCreate = xTokenizer.xCreate else {
|
||||
throw DatabaseError(code: SQLITE_ERROR, message: "nil fts5_tokenizer.xCreate")
|
||||
throw DatabaseError(resultCode: .SQLITE_ERROR, message: "nil fts5_tokenizer.xCreate")
|
||||
}
|
||||
|
||||
self.xTokenizer = xTokenizer
|
||||
@@ -147,13 +147,13 @@
|
||||
}
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(code: code, message: "failed fts5_tokenizer.xCreate")
|
||||
throw DatabaseError(resultCode: code, message: "failed fts5_tokenizer.xCreate")
|
||||
}
|
||||
|
||||
if let tokenizerPointer = tokenizerPointer {
|
||||
self.tokenizerPointer = tokenizerPointer
|
||||
} else {
|
||||
throw DatabaseError(code: code, message: "nil tokenizer")
|
||||
throw DatabaseError(resultCode: code, message: "nil tokenizer")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -189,7 +189,7 @@
|
||||
/// }
|
||||
public func makeTokenizer(_ descriptor: FTS5TokenizerDescriptor) throws -> FTS5Tokenizer {
|
||||
guard let api = FTS5.api(self) else {
|
||||
throw DatabaseError(code: SQLITE_MISUSE, message: "FTS5 API not found")
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "FTS5 API not found")
|
||||
}
|
||||
|
||||
let xTokenizerPointer: UnsafeMutablePointer<fts5_tokenizer> = .allocate(capacity: 1)
|
||||
@@ -205,7 +205,7 @@
|
||||
xTokenizerPointer)
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(code: code)
|
||||
throw DatabaseError(resultCode: code)
|
||||
}
|
||||
|
||||
let contextPointer = contextHandle.pointee
|
||||
|
||||
@@ -123,14 +123,14 @@
|
||||
// Inject token bytes into SQLite
|
||||
let code = tokenCallback(context, flags.rawValue, pToken, nToken, iStart, iEnd)
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(code: code, message: "token callback failed")
|
||||
throw DatabaseError(resultCode: code, message: "token callback failed")
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return SQLITE_OK
|
||||
} catch let error as DatabaseError {
|
||||
return error.code
|
||||
return error.extendedResultCode.rawValue
|
||||
} catch {
|
||||
return SQLITE_ERROR
|
||||
}
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
extension DatabaseError {
|
||||
@available(*, unavailable, renamed:"resultCode")
|
||||
public var code: Int32 { return 0 }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
extension Database {
|
||||
@available(*, unavailable, renamed:"inTransaction")
|
||||
public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws { }
|
||||
}
|
||||
|
||||
extension DatabaseValue {
|
||||
@available(*, unavailable, message:"DatabaseSequence has been replaced by DatabaseCursor.")
|
||||
public func value() -> Any { preconditionFailure() }
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
extension Request {
|
||||
@available(*, unavailable, renamed:"asRequest(of:)")
|
||||
public func bound<T>(to type: T.Type) -> AnyTypedRequest<T> { preconditionFailure() }
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
/// A DatabaseMigrator registers and applies database migrations.
|
||||
///
|
||||
/// Migrations are named blocks of SQL statements that are guaranteed to be
|
||||
/// applied in order, once and only once.
|
||||
///
|
||||
/// When a user upgrades your application, only non-applied migration are run.
|
||||
///
|
||||
/// Usage:
|
||||
///
|
||||
/// var migrator = DatabaseMigrator()
|
||||
///
|
||||
/// // v1.0 database
|
||||
/// migrator.registerMigration("createPersons") { db in
|
||||
/// try db.execute(
|
||||
/// "CREATE TABLE persons (" +
|
||||
/// "id INTEGER PRIMARY KEY, " +
|
||||
/// "creationDate TEXT, " +
|
||||
/// "name TEXT NOT NULL" +
|
||||
/// ")")
|
||||
/// }
|
||||
///
|
||||
/// migrator.registerMigration("createBooks") { db in
|
||||
/// try db.execute(
|
||||
/// "CREATE TABLE books (" +
|
||||
/// "uuid TEXT PRIMARY KEY, " +
|
||||
/// "ownerID INTEGER NOT NULL " +
|
||||
/// " REFERENCES persons(id) " +
|
||||
/// " ON DELETE CASCADE ON UPDATE CASCADE, " +
|
||||
/// "title TEXT NOT NULL" +
|
||||
/// ")")
|
||||
/// }
|
||||
///
|
||||
/// // v2.0 database
|
||||
/// migrator.registerMigration("AddAgeToPersons") { db in
|
||||
/// try db.execute("ALTER TABLE persons ADD COLUMN age INT")
|
||||
/// }
|
||||
///
|
||||
/// try migrator.migrate(dbQueue)
|
||||
public struct DatabaseMigrator {
|
||||
|
||||
/// A new migrator.
|
||||
public init() {
|
||||
}
|
||||
|
||||
/// Registers a migration.
|
||||
///
|
||||
/// migrator.registerMigration("createPersons") { db in
|
||||
/// try db.execute(
|
||||
/// "CREATE TABLE persons (" +
|
||||
/// "id INTEGER PRIMARY KEY, " +
|
||||
/// "creationDate TEXT, " +
|
||||
/// "name TEXT NOT NULL" +
|
||||
/// ")")
|
||||
/// }
|
||||
///
|
||||
/// - parameters:
|
||||
/// - identifier: The migration identifier.
|
||||
/// - block: The migration block that performs SQL statements.
|
||||
/// - precondition: No migration with the same same as already been registered.
|
||||
public mutating func registerMigration(_ identifier: String, migrate: @escaping (Database) throws -> Void) {
|
||||
registerMigration(Migration(identifier: identifier, migrate: migrate))
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter
|
||||
///
|
||||
/// // Add a NOT NULL constraint on persons.name:
|
||||
/// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in
|
||||
/// try db.execute(
|
||||
/// "CREATE TABLE new_persons (id INTEGER PRIMARY KEY, name TEXT NOT NULL);" +
|
||||
/// "INSERT INTO new_persons SELECT * FROM persons;" +
|
||||
/// "DROP TABLE persons;" +
|
||||
/// "ALTER TABLE new_persons RENAME TO persons;")
|
||||
/// }
|
||||
///
|
||||
/// While your migration code runs with disabled foreign key checks, those
|
||||
/// are re-enabled and checked at the end of the migration, regardless of
|
||||
/// eventual errors.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - identifier: The migration identifier.
|
||||
/// - block: The migration block that performs SQL statements.
|
||||
/// - precondition: No migration with the same same as already been registered.
|
||||
public mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void) {
|
||||
registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate))
|
||||
}
|
||||
#else
|
||||
@available(iOS 8.2, OSX 10.10, *)
|
||||
/// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter
|
||||
///
|
||||
/// // Add a NOT NULL constraint on persons.name:
|
||||
/// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in
|
||||
/// try db.execute(
|
||||
/// "CREATE TABLE new_persons (id INTEGER PRIMARY KEY, name TEXT NOT NULL);" +
|
||||
/// "INSERT INTO new_persons SELECT * FROM persons;" +
|
||||
/// "DROP TABLE persons;" +
|
||||
/// "ALTER TABLE new_persons RENAME TO persons;")
|
||||
/// }
|
||||
///
|
||||
/// While your migration code runs with disabled foreign key checks, those
|
||||
/// are re-enabled and checked at the end of the migration, regardless of
|
||||
/// eventual errors.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - identifier: The migration identifier.
|
||||
/// - block: The migration block that performs SQL statements.
|
||||
/// - precondition: No migration with the same same as already been registered.
|
||||
public mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void) {
|
||||
registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate))
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Iterate migrations in the same order as they were registered. If a
|
||||
/// migration has not yet been applied, its block is executed in
|
||||
/// a transaction.
|
||||
///
|
||||
/// - parameter db: A DatabaseWriter (DatabaseQueue or DatabasePool) where
|
||||
/// migrations should apply.
|
||||
/// - throws: An eventual error thrown by the registered migration blocks.
|
||||
public func migrate(_ writer: DatabaseWriter) throws {
|
||||
try writer.write { db in
|
||||
try setupMigrations(db)
|
||||
try runMigrations(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterate migrations in the same order as they were registered, up to the
|
||||
/// provided target. If a migration has not yet been applied, its block is
|
||||
/// executed in a transaction.
|
||||
///
|
||||
/// - parameter db: A DatabaseWriter (DatabaseQueue or DatabasePool) where
|
||||
/// migrations should apply.
|
||||
/// - targetIdentifier: The identifier of a registered migration.
|
||||
/// - throws: An eventual error thrown by the registered migration blocks.
|
||||
public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws {
|
||||
try writer.write { db in
|
||||
try setupMigrations(db)
|
||||
try runMigrations(db, upTo: targetIdentifier)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Non public
|
||||
|
||||
private var migrations: [Migration] = []
|
||||
|
||||
private mutating func registerMigration(_ migration: Migration) {
|
||||
GRDBPrecondition(!migrations.map({ $0.identifier }).contains(migration.identifier), "already registered migration: \(String(reflecting: migration.identifier))")
|
||||
migrations.append(migration)
|
||||
}
|
||||
|
||||
private func setupMigrations(_ db: Database) throws {
|
||||
try db.execute("CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)")
|
||||
}
|
||||
|
||||
private func appliedIdentifiers(_ db: Database) throws -> Set<String> {
|
||||
return try Set(String.fetchAll(db, "SELECT identifier FROM grdb_migrations"))
|
||||
}
|
||||
|
||||
private func runMigrations(_ db: Database) throws {
|
||||
let appliedIdentifiers = try self.appliedIdentifiers(db)
|
||||
for migration in migrations where !appliedIdentifiers.contains(migration.identifier) {
|
||||
try migration.run(db)
|
||||
}
|
||||
}
|
||||
|
||||
private func runMigrations(_ db: Database, upTo targetIdentifier: String) throws {
|
||||
var prefixMigrations: [Migration] = []
|
||||
for migration in migrations {
|
||||
prefixMigrations.append(migration)
|
||||
if migration.identifier == targetIdentifier {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// targetIdentifier must refer to a registered migration
|
||||
GRDBPrecondition(prefixMigrations.last?.identifier == targetIdentifier, "undefined migration: \(String(reflecting: targetIdentifier))")
|
||||
|
||||
// Subsequent migration must not be applied
|
||||
let appliedIdentifiers = try self.appliedIdentifiers(db)
|
||||
if prefixMigrations.count < migrations.count {
|
||||
let nextIdentifier = migrations[prefixMigrations.count].identifier
|
||||
GRDBPrecondition(!appliedIdentifiers.contains(nextIdentifier), "database is already migrated beyond migration \(String(reflecting: targetIdentifier))")
|
||||
}
|
||||
|
||||
for migration in prefixMigrations where !appliedIdentifiers.contains(migration.identifier) {
|
||||
try migration.run(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,49 +1,35 @@
|
||||
#if !USING_BUILTIN_SQLITE
|
||||
#if os(OSX)
|
||||
import SQLiteMacOSX
|
||||
#elseif os(iOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteiPhoneSimulator
|
||||
#else
|
||||
import SQLiteiPhoneOS
|
||||
#endif
|
||||
#elseif os(watchOS)
|
||||
#if (arch(i386) || arch(x86_64))
|
||||
import SQLiteWatchSimulator
|
||||
#else
|
||||
import SQLiteWatchOS
|
||||
#endif
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/// An internal struct that defines a migration.
|
||||
struct Migration {
|
||||
// PRAGMA foreign_key_check = ON was introduced in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
let identifier: String
|
||||
let disabledForeignKeyChecks: Bool
|
||||
let migrate: (Database) throws -> Void
|
||||
|
||||
init(identifier: String, migrate: @escaping (Database) throws -> Void) {
|
||||
self.identifier = identifier
|
||||
self.disabledForeignKeyChecks = false
|
||||
self.migrate = migrate
|
||||
}
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
init(identifier: String, disabledForeignKeyChecks: Bool = false, migrate: @escaping (Database) throws -> Void) {
|
||||
self.identifier = identifier
|
||||
self.disabledForeignKeyChecks = disabledForeignKeyChecks
|
||||
self.migrate = migrate
|
||||
}
|
||||
#else
|
||||
init(identifier: String, migrate: @escaping (Database) throws -> Void) {
|
||||
self.identifier = identifier
|
||||
self.disabledForeignKeyChecks = false
|
||||
self.migrate = migrate
|
||||
}
|
||||
|
||||
@available(iOS 8.2, OSX 10.10, *)
|
||||
init(identifier: String, disabledForeignKeyChecks: Bool, migrate: @escaping (Database) throws -> Void) {
|
||||
self.identifier = identifier
|
||||
self.disabledForeignKeyChecks = disabledForeignKeyChecks
|
||||
self.migrate = migrate
|
||||
}
|
||||
@available(iOS 8.2, OSX 10.10, *)
|
||||
// PRAGMA foreign_key_check was introduced in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
init(identifier: String, disabledForeignKeyChecks: Bool, migrate: @escaping (Database) throws -> Void) {
|
||||
self.identifier = identifier
|
||||
self.disabledForeignKeyChecks = disabledForeignKeyChecks
|
||||
self.migrate = migrate
|
||||
}
|
||||
#endif
|
||||
|
||||
func run(_ db: Database) throws {
|
||||
if #available(iOS 8.2, OSX 10.10, *) {
|
||||
if try disabledForeignKeyChecks && (Bool.fetchOne(db, "PRAGMA foreign_keys") ?? false) {
|
||||
try runWithDisabledForeignKeys(db)
|
||||
} else {
|
||||
try runWithoutDisabledForeignKeys(db)
|
||||
}
|
||||
if try disabledForeignKeyChecks && (Bool.fetchOne(db, "PRAGMA foreign_keys") ?? false) {
|
||||
try runWithDisabledForeignKeys(db)
|
||||
} else {
|
||||
try runWithoutDisabledForeignKeys(db)
|
||||
}
|
||||
@@ -58,7 +44,6 @@ struct Migration {
|
||||
}
|
||||
}
|
||||
|
||||
@available(iOS 8.2, OSX 10.10, *)
|
||||
private func runWithDisabledForeignKeys(_ db: Database) throws {
|
||||
// Support for database alterations described at
|
||||
// https://www.sqlite.org/lang_altertable.html#otheralter
|
||||
@@ -83,7 +68,7 @@ struct Migration {
|
||||
//
|
||||
// Let's turn any violation into an SQLITE_CONSTRAINT
|
||||
// error, and rollback the transaction.
|
||||
throw DatabaseError(code: SQLITE_CONSTRAINT, message: "FOREIGN KEY constraint failed")
|
||||
throw DatabaseError(resultCode: .SQLITE_CONSTRAINT, message: "FOREIGN KEY constraint failed")
|
||||
}
|
||||
|
||||
// > 11. Commit the transaction started in step 2.
|
||||
@@ -1,122 +0,0 @@
|
||||
/// A DatabaseMigrator registers and applies database migrations.
|
||||
///
|
||||
/// Migrations are named blocks of SQL statements that are guaranteed to be
|
||||
/// applied in order, once and only once.
|
||||
///
|
||||
/// When a user upgrades your application, only non-applied migration are run.
|
||||
///
|
||||
/// Usage:
|
||||
///
|
||||
/// var migrator = DatabaseMigrator()
|
||||
///
|
||||
/// // v1.0 database
|
||||
/// migrator.registerMigration("createPersons") { db in
|
||||
/// try db.execute(
|
||||
/// "CREATE TABLE persons (" +
|
||||
/// "id INTEGER PRIMARY KEY, " +
|
||||
/// "creationDate TEXT, " +
|
||||
/// "name TEXT NOT NULL" +
|
||||
/// ")")
|
||||
/// }
|
||||
///
|
||||
/// migrator.registerMigration("createBooks") { db in
|
||||
/// try db.execute(
|
||||
/// "CREATE TABLE books (" +
|
||||
/// "uuid TEXT PRIMARY KEY, " +
|
||||
/// "ownerID INTEGER NOT NULL " +
|
||||
/// " REFERENCES persons(id) " +
|
||||
/// " ON DELETE CASCADE ON UPDATE CASCADE, " +
|
||||
/// "title TEXT NOT NULL" +
|
||||
/// ")")
|
||||
/// }
|
||||
///
|
||||
/// // v2.0 database
|
||||
/// migrator.registerMigration("AddAgeToPersons") { db in
|
||||
/// try db.execute("ALTER TABLE persons ADD COLUMN age INT")
|
||||
/// }
|
||||
///
|
||||
/// try migrator.migrate(dbQueue)
|
||||
public struct DatabaseMigrator {
|
||||
|
||||
/// A new migrator.
|
||||
public init() {
|
||||
}
|
||||
|
||||
/// Registers a migration.
|
||||
///
|
||||
/// migrator.registerMigration("createPersons") { db in
|
||||
/// try db.execute(
|
||||
/// "CREATE TABLE persons (" +
|
||||
/// "id INTEGER PRIMARY KEY, " +
|
||||
/// "creationDate TEXT, " +
|
||||
/// "name TEXT NOT NULL" +
|
||||
/// ")")
|
||||
/// }
|
||||
///
|
||||
/// - parameters:
|
||||
/// - identifier: The migration identifier.
|
||||
/// - block: The migration block that performs SQL statements.
|
||||
/// - precondition: No migration with the same same as already been registered.
|
||||
public mutating func registerMigration(_ identifier: String, migrate: @escaping (Database) throws -> Void) {
|
||||
registerMigration(Migration(identifier: identifier, migrate: migrate))
|
||||
}
|
||||
|
||||
@available(iOS 8.2, OSX 10.10, *)
|
||||
/// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter
|
||||
///
|
||||
/// // Add a NOT NULL constraint on persons.name:
|
||||
/// migrator.registerMigrationWithDisabledForeignKeyChecks("AddNotNullCheckOnName") { db in
|
||||
/// try db.execute(
|
||||
/// "CREATE TABLE new_persons (id INTEGER PRIMARY KEY, name TEXT NOT NULL);" +
|
||||
/// "INSERT INTO new_persons SELECT * FROM persons;" +
|
||||
/// "DROP TABLE persons;" +
|
||||
/// "ALTER TABLE new_persons RENAME TO persons;")
|
||||
/// }
|
||||
///
|
||||
/// While your migration code runs with disabled foreign key checks, those
|
||||
/// are re-enabled and checked at the end of the migration, regardless of
|
||||
/// eventual errors.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - identifier: The migration identifier.
|
||||
/// - block: The migration block that performs SQL statements.
|
||||
/// - precondition: No migration with the same same as already been registered.
|
||||
public mutating func registerMigrationWithDisabledForeignKeyChecks(_ identifier: String, migrate: @escaping (Database) throws -> Void) {
|
||||
registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate))
|
||||
}
|
||||
|
||||
/// Iterate migrations in the same order as they were registered. If a
|
||||
/// migration has not yet been applied, its block is executed in
|
||||
/// a transaction.
|
||||
///
|
||||
/// - parameter db: A DatabaseWriter (DatabaseQueue or DatabasePool) where
|
||||
/// migrations should apply.
|
||||
/// - throws: An eventual error thrown by the registered migration blocks.
|
||||
public func migrate(_ db: DatabaseWriter) throws {
|
||||
try db.write { db in
|
||||
try setupMigrations(db)
|
||||
try runMigrations(db)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Non public
|
||||
|
||||
private var migrations: [Migration] = []
|
||||
|
||||
private mutating func registerMigration(_ migration: Migration) {
|
||||
GRDBPrecondition(!migrations.map({ $0.identifier }).contains(migration.identifier), "already registered migration: \"\(migration.identifier)\"")
|
||||
migrations.append(migration)
|
||||
}
|
||||
|
||||
private func setupMigrations(_ db: Database) throws {
|
||||
try db.execute("CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)")
|
||||
}
|
||||
|
||||
private func runMigrations(_ db: Database) throws {
|
||||
let appliedIdentifiers = try String.fetchAll(db, "SELECT identifier FROM grdb_migrations")
|
||||
for migration in migrations where !appliedIdentifiers.contains(migration.identifier) {
|
||||
try migration.run(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/// A column in the database
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift#the-query-interface
|
||||
public struct Column {
|
||||
/// The hidden rowID column
|
||||
public static let rowID = Column("rowid")
|
||||
|
||||
/// The name of the column
|
||||
public let name: String
|
||||
|
||||
/// 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)
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return name.quotedDatabaseIdentifier
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
extension QueryInterfaceRequest {
|
||||
|
||||
// MARK: Full Text Search
|
||||
|
||||
/// Returns a new QueryInterfaceRequest with a matching predicate added
|
||||
/// to the eventual set of already applied predicates.
|
||||
///
|
||||
/// // SELECT * FROM books WHERE books MATCH '...'
|
||||
/// var request = Book.all()
|
||||
/// request = request.matching(pattern)
|
||||
///
|
||||
/// If the search pattern is nil, the request does not match any
|
||||
/// database row.
|
||||
public func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<T> {
|
||||
switch query.source {
|
||||
case .table(let name, let alias)?:
|
||||
return filter(SQLExpressionBinary(.match, Column(alias ?? name), pattern ?? DatabaseValue.null))
|
||||
default:
|
||||
// Programmer error
|
||||
fatalError("fts3 match requires a table")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
|
||||
// MARK: Full Text Search
|
||||
|
||||
/// Returns a QueryInterfaceRequest with a matching predicate.
|
||||
///
|
||||
/// // SELECT * FROM books WHERE books MATCH '...'
|
||||
/// var request = Book.matching(pattern)
|
||||
///
|
||||
/// If the `selectsRowID` type property is true, then the selection includes
|
||||
/// the hidden "rowid" column:
|
||||
///
|
||||
/// // SELECT *, rowid FROM books WHERE books MATCH '...'
|
||||
/// var request = Book.matching(pattern)
|
||||
///
|
||||
/// If the search pattern is nil, the request does not match any
|
||||
/// database row.
|
||||
public static func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<Self> {
|
||||
return all().matching(pattern)
|
||||
}
|
||||
}
|
||||
|
||||
extension Column {
|
||||
/// A matching SQL expression with the `MATCH` SQL operator.
|
||||
///
|
||||
/// // content MATCH '...'
|
||||
/// Column("content").match(pattern)
|
||||
///
|
||||
/// If the search pattern is nil, SQLite will evaluate the expression
|
||||
/// to false.
|
||||
public func match(_ pattern: FTS3Pattern?) -> SQLExpression {
|
||||
return SQLExpressionBinary(.match, self, pattern ?? DatabaseValue.null)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
extension QueryInterfaceRequest {
|
||||
|
||||
// MARK: Full Text Search
|
||||
|
||||
/// Returns a new QueryInterfaceRequest with a matching predicate added
|
||||
/// to the eventual set of already applied predicates.
|
||||
///
|
||||
/// // SELECT * FROM books WHERE books MATCH '...'
|
||||
/// var request = Book.all()
|
||||
/// request = request.matching(pattern)
|
||||
///
|
||||
/// If the search pattern is nil, the request does not match any
|
||||
/// database row.
|
||||
public func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest<T> {
|
||||
switch query.source {
|
||||
case .table(let name, let alias)?:
|
||||
if let pattern = pattern {
|
||||
return filter(SQLExpressionBinary(.match, Column(alias ?? name), pattern))
|
||||
} else {
|
||||
return filter(false)
|
||||
}
|
||||
default:
|
||||
// Programmer error
|
||||
fatalError("fts5 match requires a table")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
|
||||
// MARK: Full Text Search
|
||||
|
||||
/// Returns a QueryInterfaceRequest with a matching predicate.
|
||||
///
|
||||
/// // SELECT * FROM books WHERE books MATCH '...'
|
||||
/// var request = Book.matching(pattern)
|
||||
///
|
||||
/// If the `selectsRowID` type property is true, then the selection
|
||||
/// includes the hidden "rowid" column:
|
||||
///
|
||||
/// // SELECT *, rowid FROM books WHERE books MATCH '...'
|
||||
/// var request = Book.matching(pattern)
|
||||
///
|
||||
/// If the search pattern is nil, the request does not match any
|
||||
/// database row.
|
||||
public static func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest<Self> {
|
||||
return all().matching(pattern)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,9 +1,7 @@
|
||||
/// A QueryInterfaceRequest describes an SQL query.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift#the-query-interface
|
||||
public struct QueryInterfaceRequest<T> : TypedRequest {
|
||||
public typealias Fetched = T
|
||||
|
||||
public struct QueryInterfaceRequest<T> {
|
||||
let query: QueryInterfaceSelectQueryDefinition
|
||||
|
||||
init(query: QueryInterfaceSelectQueryDefinition) {
|
||||
@@ -11,18 +9,22 @@ public struct QueryInterfaceRequest<T> : TypedRequest {
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest : SQLSelectQuery {
|
||||
extension QueryInterfaceRequest : TypedRequest {
|
||||
public typealias RowDecoder = T
|
||||
|
||||
/// This function is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
/// - parameter db: A database connection.
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try query.prepare(db)
|
||||
}
|
||||
|
||||
/// The number of rows fetched by the request.
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// See SQLSelectQuery.selectQuerySQL(_)
|
||||
public func selectQuerySQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return query.selectQuerySQL(&arguments)
|
||||
/// - parameter db: A database connection.
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try query.fetchCount(db)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,6 +169,7 @@ extension QueryInterfaceRequest {
|
||||
/// // SELECT * FROM persons ORDER BY name
|
||||
/// request
|
||||
/// .order(Column("email"))
|
||||
/// .reversed()
|
||||
/// .order(Column("name"))
|
||||
public func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest<T> {
|
||||
return order(orderings)
|
||||
@@ -183,10 +186,12 @@ extension QueryInterfaceRequest {
|
||||
/// // SELECT * FROM persons ORDER BY name
|
||||
/// request
|
||||
/// .order([Column("email")])
|
||||
/// .reversed()
|
||||
/// .order([Column("name")])
|
||||
public func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest<T> {
|
||||
var query = self.query
|
||||
query.orderings = orderings
|
||||
query.isReversed = false
|
||||
return QueryInterfaceRequest(query: query)
|
||||
}
|
||||
|
||||
@@ -230,18 +235,6 @@ extension QueryInterfaceRequest {
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
|
||||
// MARK: Counting
|
||||
|
||||
/// The number of rows matched by the request.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try query.countRequest.fetchOne(db)!
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
|
||||
// MARK: Deleting
|
||||
@@ -275,9 +268,9 @@ extension TableMapping {
|
||||
public static func all() -> QueryInterfaceRequest<Self> {
|
||||
let selection: [SQLSelectable]
|
||||
if selectsRowID {
|
||||
selection = [star, Column.rowID]
|
||||
selection = [SQLStar(), Column.rowID]
|
||||
} else {
|
||||
selection = [star]
|
||||
selection = [SQLStar()]
|
||||
}
|
||||
return QueryInterfaceRequest(query: QueryInterfaceSelectQueryDefinition(select: selection, from: .table(name: databaseTableName, alias: nil)))
|
||||
}
|
||||
|
||||
@@ -90,48 +90,6 @@ struct QueryInterfaceSelectQueryDefinition {
|
||||
return sql
|
||||
}
|
||||
|
||||
/// Returns a fetch request that counts the number of rows matched by self.
|
||||
var countRequest: AnyTypedRequest<Int> {
|
||||
return countQuery.bound(to: Int.self)
|
||||
}
|
||||
|
||||
private var countQuery: QueryInterfaceSelectQueryDefinition {
|
||||
guard groupByExpressions.isEmpty && limit == nil else {
|
||||
// SELECT ... GROUP BY ...
|
||||
// SELECT ... LIMIT ...
|
||||
return trivialCountQuery
|
||||
}
|
||||
|
||||
guard let source = source, case .table(name: let tableName, alias: let alias) = source else {
|
||||
// SELECT ... FROM (something which is not a table)
|
||||
return trivialCountQuery
|
||||
}
|
||||
|
||||
assert(!selection.isEmpty)
|
||||
if selection.count == 1 {
|
||||
guard let selectable = self.selection[0].countingSelectable(distinct: isDistinct, from: tableName, aliased: alias) else {
|
||||
return trivialCountQuery
|
||||
}
|
||||
var countQuery = unorderedQuery
|
||||
countQuery.isDistinct = false
|
||||
countQuery.selection = [selectable]
|
||||
return countQuery
|
||||
} else {
|
||||
// SELECT [DISTINCT] expr1, expr2, ... FROM tableName ...
|
||||
|
||||
guard !isDistinct else {
|
||||
return trivialCountQuery
|
||||
}
|
||||
|
||||
// SELECT expr1, expr2, ... FROM tableName ...
|
||||
// ->
|
||||
// SELECT COUNT(*) FROM tableName ...
|
||||
var countQuery = unorderedQuery
|
||||
countQuery.selection = [SQLExpressionCount(star)]
|
||||
return countQuery
|
||||
}
|
||||
}
|
||||
|
||||
func makeDeleteStatement(_ db: Database) throws -> UpdateStatement {
|
||||
guard groupByExpressions.isEmpty else {
|
||||
// Programmer error
|
||||
@@ -164,15 +122,8 @@ struct QueryInterfaceSelectQueryDefinition {
|
||||
return statement
|
||||
}
|
||||
|
||||
// SELECT COUNT(*) FROM (self)
|
||||
private var trivialCountQuery: QueryInterfaceSelectQueryDefinition {
|
||||
return QueryInterfaceSelectQueryDefinition(
|
||||
select: [SQLExpressionCount(star)],
|
||||
from: .query(query: unorderedQuery, alias: nil))
|
||||
}
|
||||
|
||||
/// Remove ordering
|
||||
private var unorderedQuery: QueryInterfaceSelectQueryDefinition {
|
||||
var unorderedQuery: QueryInterfaceSelectQueryDefinition {
|
||||
var query = self
|
||||
query.isReversed = false
|
||||
query.orderings = []
|
||||
@@ -180,6 +131,64 @@ struct QueryInterfaceSelectQueryDefinition {
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceSelectQueryDefinition : Request {
|
||||
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
var arguments: StatementArguments? = StatementArguments()
|
||||
let sql = self.sql(&arguments)
|
||||
let statement = try db.makeSelectStatement(sql)
|
||||
try statement.setArgumentsWithValidation(arguments!)
|
||||
return (statement, nil)
|
||||
}
|
||||
|
||||
func fetchCount(_ db: Database) throws -> Int {
|
||||
return try Int.fetchOne(db, countQuery)!
|
||||
}
|
||||
|
||||
private var countQuery: QueryInterfaceSelectQueryDefinition {
|
||||
guard groupByExpressions.isEmpty && limit == nil else {
|
||||
// SELECT ... GROUP BY ...
|
||||
// SELECT ... LIMIT ...
|
||||
return trivialCountQuery
|
||||
}
|
||||
|
||||
guard let source = source, case .table = source else {
|
||||
// SELECT ... FROM (something which is not a table)
|
||||
return trivialCountQuery
|
||||
}
|
||||
|
||||
assert(!selection.isEmpty)
|
||||
if selection.count == 1 {
|
||||
guard let count = self.selection[0].count(distinct: isDistinct) else {
|
||||
return trivialCountQuery
|
||||
}
|
||||
var countQuery = unorderedQuery
|
||||
countQuery.isDistinct = false
|
||||
countQuery.selection = [count.sqlSelectable]
|
||||
return countQuery
|
||||
} else {
|
||||
// SELECT [DISTINCT] expr1, expr2, ... FROM tableName ...
|
||||
|
||||
guard !isDistinct else {
|
||||
return trivialCountQuery
|
||||
}
|
||||
|
||||
// SELECT expr1, expr2, ... FROM tableName ...
|
||||
// ->
|
||||
// SELECT COUNT(*) FROM tableName ...
|
||||
var countQuery = unorderedQuery
|
||||
countQuery.selection = [SQLExpressionCount(SQLStar())]
|
||||
return countQuery
|
||||
}
|
||||
}
|
||||
|
||||
// SELECT COUNT(*) FROM (self)
|
||||
private var trivialCountQuery: QueryInterfaceSelectQueryDefinition {
|
||||
return QueryInterfaceSelectQueryDefinition(
|
||||
select: [SQLExpressionCount(SQLStar())],
|
||||
from: .query(query: unorderedQuery, alias: nil))
|
||||
}
|
||||
}
|
||||
|
||||
indirect enum SQLSource {
|
||||
case table(name: String, alias: String?)
|
||||
case query(query: QueryInterfaceSelectQueryDefinition, alias: String?)
|
||||
@@ -214,3 +223,14 @@ struct SQLLimit {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLCount {
|
||||
var sqlSelectable: SQLSelectable {
|
||||
switch self {
|
||||
case .star:
|
||||
return SQLExpressionCount(SQLStar())
|
||||
case .distinct(let expression):
|
||||
return SQLExpressionCountDistinct(expression)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,3 +47,16 @@ public struct SQLCollatedExpression {
|
||||
return SQLExpressionCollate(expression, collationName: collationName)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLCollatedExpression : SQLOrderingTerm {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public var reversed: SQLOrderingTerm {
|
||||
return desc
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return sqlExpression.orderingTermSQL(&arguments)
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,10 @@
|
||||
// MARK: - SQLCollection
|
||||
|
||||
/// This protocol is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// SQLCollection is the protocol for types that can be checked for inclusion.
|
||||
public protocol SQLCollection {
|
||||
/// This function is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns an SQL string that represents the collection.
|
||||
///
|
||||
@@ -34,6 +24,8 @@ public protocol SQLCollection {
|
||||
/// arguments // [1,2,3]
|
||||
func collectionSQL(_ arguments: inout StatementArguments?) -> String
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns an expression that check whether the collection contains
|
||||
/// the expression.
|
||||
///
|
||||
@@ -49,6 +41,8 @@ public protocol SQLCollection {
|
||||
// MARK: Default Implementations
|
||||
|
||||
extension SQLCollection {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns a SQLExpressionContains which applies the `IN` operator:
|
||||
///
|
||||
/// let request = Person.select(Column("id"))
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// MARK: - SQLExpressible
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The protocol for all types that can be turned into an SQL expression.
|
||||
///
|
||||
/// It is adopted by protocols like DatabaseValueConvertible, and types
|
||||
/// like Column.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
public protocol SQLExpressible {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns an SQLExpression
|
||||
var sqlExpression: SQLExpression { get }
|
||||
}
|
||||
|
||||
// MARK: - SQLSpecificExpressible
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// SQLSpecificExpressible is a protocol for all database-specific types that can
|
||||
/// be turned into an SQL expression. Types whose existence is not purely
|
||||
/// dedicated to the database should adopt the SQLExpressible protocol instead.
|
||||
///
|
||||
/// For example, Column is a type that only exists to help you build requests,
|
||||
/// and it adopts SQLSpecificExpressible.
|
||||
///
|
||||
/// On the other side, Int adopts SQLExpressible (via DatabaseValueConvertible).
|
||||
public protocol SQLSpecificExpressible : SQLExpressible {
|
||||
// SQLExpressible can be adopted by Swift standard types, and user
|
||||
// types, through the DatabaseValueConvertible protocol which inherits
|
||||
// from SQLExpressible.
|
||||
//
|
||||
// For example, Int adopts SQLExpressible through
|
||||
// DatabaseValueConvertible.
|
||||
//
|
||||
// SQLSpecificExpressible, on the other side, is not adopted by any
|
||||
// Swift standard type or any user type. It is only adopted by GRDB types,
|
||||
// such as Column and SQLExpression.
|
||||
//
|
||||
// This separation lets us define functions and operators that do not
|
||||
// spill out. The three declarations below have no chance overloading a
|
||||
// Swift-defined operator, or a user-defined operator:
|
||||
//
|
||||
// - ==(SQLExpressible, SQLSpecificExpressible)
|
||||
// - ==(SQLSpecificExpressible, SQLExpressible)
|
||||
// - ==(SQLSpecificExpressible, SQLSpecificExpressible)
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressible & SQLOrderingTerm
|
||||
|
||||
extension SQLExpressible where Self: SQLOrderingTerm {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public var reversed: SQLOrderingTerm {
|
||||
return SQLOrdering.desc(sqlExpression)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return sqlExpression.expressionSQL(&arguments)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressible & SQLSelectable
|
||||
|
||||
extension SQLExpressible where Self: SQLSelectable {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func resultColumnSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return sqlExpression.expressionSQL(&arguments)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func countedSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return sqlExpression.expressionSQL(&arguments)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func count(distinct: Bool) -> SQLCount? {
|
||||
return sqlExpression.count(distinct: distinct)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
// MARK: - SQLExpression
|
||||
|
||||
extension SQLExpression {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Converts an expression to an SQLExpressionLiteral
|
||||
public var literal: SQLExpressionLiteral {
|
||||
var arguments: StatementArguments? = []
|
||||
let sql = expressionSQL(&arguments)
|
||||
return SQLExpressionLiteral(sql, arguments: arguments)
|
||||
}
|
||||
|
||||
/// The expression as a quoted SQL literal (not public in order to avoid abuses)
|
||||
///
|
||||
/// "foo'bar".databaseValue.sql // "'foo''bar'""
|
||||
var sql: String {
|
||||
var arguments: StatementArguments? = nil
|
||||
return expressionSQL(&arguments)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionLiteral
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// SQLExpressionLiteral is an expression built from a raw SQL snippet.
|
||||
///
|
||||
/// SQLExpressionLiteral("1 + 2")
|
||||
///
|
||||
/// The SQL literal may contain `?` and colon-prefixed tokens:
|
||||
///
|
||||
/// SQLExpressionLiteral("? + ?", arguments: [1, 2])
|
||||
/// SQLExpressionLiteral(":one + :two", arguments: ["one": 1, "two": 2])
|
||||
public struct SQLExpressionLiteral : SQLExpression {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The SQL literal
|
||||
public let sql: String
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Eventual arguments that feed the `?` and colon-prefixed tokens in the
|
||||
/// SQL literal
|
||||
public let arguments: StatementArguments?
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Creates an SQL literal expression.
|
||||
///
|
||||
/// SQLExpressionLiteral("1 + 2")
|
||||
/// SQLExpressionLiteral("? + ?", arguments: [1, 2])
|
||||
/// SQLExpressionLiteral(":one + :two", arguments: ["one": 1, "two": 2])
|
||||
public init(_ sql: String, arguments: StatementArguments? = nil) {
|
||||
self.sql = sql
|
||||
self.arguments = arguments
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
if let literalArguments = self.arguments {
|
||||
guard arguments != nil else {
|
||||
// GRDB limitation: we don't know how to look for `?` in sql and
|
||||
// replace them with with literals.
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
arguments! += literalArguments
|
||||
}
|
||||
return sql
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionUnary
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// SQLUnaryOperator is a SQLite unary operator.
|
||||
public struct SQLUnaryOperator : Hashable {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The SQL operator
|
||||
public let sql: String
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// If true GRDB puts a white space between the operator and the operand.
|
||||
public let needsRightSpace: Bool
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Creates an unary operator
|
||||
///
|
||||
/// SQLUnaryOperator("~", needsRightSpace: false)
|
||||
public init(_ sql: String, needsRightSpace: Bool) {
|
||||
self.sql = sql
|
||||
self.needsRightSpace = needsRightSpace
|
||||
}
|
||||
|
||||
/// The hash value
|
||||
public var hashValue: Int {
|
||||
return sql.hashValue
|
||||
}
|
||||
|
||||
/// Equality operator
|
||||
public static func == (lhs: SQLUnaryOperator, rhs: SQLUnaryOperator) -> Bool {
|
||||
return lhs.sql == rhs.sql
|
||||
}
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// SQLExpressionUnary is an expression made of an unary operator and
|
||||
/// an operand expression.
|
||||
///
|
||||
/// SQLExpressionUnary(.not, Column("favorite"))
|
||||
public struct SQLExpressionUnary : SQLExpression {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The unary operator
|
||||
public let op: SQLUnaryOperator
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The operand
|
||||
public let expression: SQLExpression
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Creates an expression made of an unary operator and
|
||||
/// an operand expression.
|
||||
///
|
||||
/// // NOT favorite
|
||||
/// SQLExpressionUnary(.not, Column("favorite"))
|
||||
public init(_ op: SQLUnaryOperator, _ value: SQLExpressible) {
|
||||
self.op = op
|
||||
self.expression = value.sqlExpression
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return op.sql + (op.needsRightSpace ? " " : "") + expression.expressionSQL(&arguments)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionBinary
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// SQLBinaryOperator is a SQLite binary operator.
|
||||
public struct SQLBinaryOperator : Hashable {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The SQL operator
|
||||
public let sql: String
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The SQL for the negated operator, if any
|
||||
public let negatedSQL: String?
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Creates a binary operator
|
||||
///
|
||||
/// SQLBinaryOperator("+")
|
||||
/// SQLBinaryOperator("IS", negated: "IS NOT")
|
||||
public init(_ sql: String, negated: String? = nil) {
|
||||
self.sql = sql
|
||||
self.negatedSQL = negated
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns the negated binary operator, if any
|
||||
///
|
||||
/// let operator = SQLBinaryOperator("IS", negated: "IS NOT")
|
||||
/// operator.negated!.sql // IS NOT
|
||||
public var negated: SQLBinaryOperator? {
|
||||
guard let negatedSQL = negatedSQL else {
|
||||
return nil
|
||||
}
|
||||
return SQLBinaryOperator(negatedSQL, negated: sql)
|
||||
}
|
||||
|
||||
/// The hash value
|
||||
public var hashValue: Int {
|
||||
return sql.hashValue
|
||||
}
|
||||
|
||||
/// Equality operator
|
||||
public static func == (lhs: SQLBinaryOperator, rhs: SQLBinaryOperator) -> Bool {
|
||||
return lhs.sql == rhs.sql
|
||||
}
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// SQLExpressionBinary is an expression made of two expressions joined with a
|
||||
/// binary operator.
|
||||
///
|
||||
/// SQLExpressionBinary(.multiply, Column("length"), Column("width"))
|
||||
public struct SQLExpressionBinary : SQLExpression {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The left operand
|
||||
public let lhs: SQLExpression
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The operator
|
||||
public let op: SQLBinaryOperator
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The right operand
|
||||
public let rhs: SQLExpression
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Creates an expression made of two expressions joined with a
|
||||
/// binary operator.
|
||||
///
|
||||
/// // length * width
|
||||
/// SQLExpressionBinary(.multiply, Column("length"), Column("width"))
|
||||
public init(_ op: SQLBinaryOperator, _ lhs: SQLExpressible, _ rhs: SQLExpressible) {
|
||||
self.lhs = lhs.sqlExpression
|
||||
self.op = op
|
||||
self.rhs = rhs.sqlExpression
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return "(" + lhs.expressionSQL(&arguments) + " " + op.sql + " " + rhs.expressionSQL(&arguments) + ")"
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public var negated: SQLExpression {
|
||||
if let negatedOp = op.negated {
|
||||
return SQLExpressionBinary(negatedOp, lhs, rhs)
|
||||
} else {
|
||||
return SQLExpressionNot(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionContains
|
||||
|
||||
/// SQLExpressionContains is an expression that checks the inclusion of a
|
||||
/// value in a collection with the `IN` operator.
|
||||
///
|
||||
/// // id IN (1,2,3)
|
||||
/// SQLExpressionContains(Column("id"), SQLExpressionsArray([1,2,3]))
|
||||
struct SQLExpressionContains : SQLExpression {
|
||||
let expression: SQLExpression
|
||||
let collection: SQLCollection
|
||||
let isNegated: Bool
|
||||
|
||||
init(_ value: SQLExpressible, _ collection: SQLCollection, negated: Bool = false) {
|
||||
self.expression = value.sqlExpression
|
||||
self.collection = collection
|
||||
self.isNegated = negated
|
||||
}
|
||||
|
||||
func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return "(" +
|
||||
expression.expressionSQL(&arguments) +
|
||||
(isNegated ? " NOT IN (" : " IN (") +
|
||||
collection.collectionSQL(&arguments) +
|
||||
"))"
|
||||
}
|
||||
|
||||
var negated: SQLExpression {
|
||||
return SQLExpressionContains(expression, collection, negated: !isNegated)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionBetween
|
||||
|
||||
/// SQLExpressionBetween is an expression that checks if a values is included
|
||||
/// in a range with the `BETWEEN` operator.
|
||||
///
|
||||
/// // id BETWEEN 1 AND 3
|
||||
/// SQLExpressionBetween(Column("id"), 1.databaseValue, 3.databaseValue)
|
||||
struct SQLExpressionBetween : SQLExpression {
|
||||
let expression: SQLExpression
|
||||
let lowerBound: SQLExpression
|
||||
let upperBound: SQLExpression
|
||||
let isNegated: Bool
|
||||
|
||||
init(_ expression: SQLExpression, _ lowerBound: SQLExpression, _ upperBound: SQLExpression, negated: Bool = false) {
|
||||
self.expression = expression
|
||||
self.lowerBound = lowerBound
|
||||
self.upperBound = upperBound
|
||||
self.isNegated = negated
|
||||
}
|
||||
|
||||
func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return "(" +
|
||||
expression.expressionSQL(&arguments) +
|
||||
(isNegated ? " NOT BETWEEN " : " BETWEEN ") +
|
||||
lowerBound.expressionSQL(&arguments) +
|
||||
" AND " +
|
||||
upperBound.expressionSQL(&arguments) +
|
||||
")"
|
||||
}
|
||||
|
||||
var negated: SQLExpression {
|
||||
return SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionFunction
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// SQLFunctionName is an SQL function name.
|
||||
public struct SQLFunctionName : Hashable {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The SQL function name
|
||||
public let sql: String
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Creates a function name
|
||||
///
|
||||
/// SQLFunctionName("ABS")
|
||||
public init(_ sql: String) {
|
||||
self.sql = sql
|
||||
}
|
||||
|
||||
/// The hash value
|
||||
public var hashValue: Int {
|
||||
return sql.hashValue
|
||||
}
|
||||
|
||||
/// Equality operator
|
||||
public static func == (lhs: SQLFunctionName, rhs: SQLFunctionName) -> Bool {
|
||||
return lhs.sql == rhs.sql
|
||||
}
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// SQLExpressionFunction is an SQL function call.
|
||||
///
|
||||
/// // ABS(-1)
|
||||
/// SQLExpressionFunction(.abs, [-1.databaseValue])
|
||||
public struct SQLExpressionFunction : SQLExpression {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The function name
|
||||
public let functionName: SQLFunctionName
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The function arguments
|
||||
public let arguments: [SQLExpression]
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Creates an SQL function call
|
||||
///
|
||||
/// // ABS(-1)
|
||||
/// SQLExpressionFunction(.abs, arguments: [-1.databaseValue])
|
||||
public init(_ functionName: SQLFunctionName, arguments: [SQLExpression]) {
|
||||
self.functionName = functionName
|
||||
self.arguments = arguments
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Creates an SQL function call
|
||||
///
|
||||
/// // ABS(-1)
|
||||
/// SQLExpressionFunction(.abs, arguments: -1)
|
||||
public init(_ functionName: SQLFunctionName, arguments: SQLExpressible...) {
|
||||
self.init(functionName, arguments: arguments.map { $0.sqlExpression })
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return functionName.sql + "(" + (self.arguments.map { $0.expressionSQL(&arguments) } as [String]).joined(separator: ", ") + ")"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionCount
|
||||
|
||||
/// SQLExpressionCount is a call to the SQL `COUNT` function.
|
||||
///
|
||||
/// // COUNT(name)
|
||||
/// SQLExpressionCount(Column("name"))
|
||||
struct SQLExpressionCount : SQLExpression {
|
||||
/// The counted value
|
||||
let counted: SQLSelectable
|
||||
|
||||
init(_ counted: SQLSelectable) {
|
||||
self.counted = counted
|
||||
}
|
||||
|
||||
func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return "COUNT(" + counted.countedSQL(&arguments) + ")"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionCountDistinct
|
||||
|
||||
/// SQLExpressionCountDistinct is a call to the SQL `COUNT(DISTINCT ...)` function.
|
||||
///
|
||||
/// // COUNT(DISTINCT name)
|
||||
/// SQLExpressionCountDistinct(Column("name"))
|
||||
struct SQLExpressionCountDistinct : SQLExpression {
|
||||
let counted: SQLExpression
|
||||
|
||||
init(_ counted: SQLExpression) {
|
||||
self.counted = counted
|
||||
}
|
||||
|
||||
func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return "COUNT(DISTINCT " + counted.expressionSQL(&arguments) + ")"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionCollate
|
||||
|
||||
/// SQLExpressionCollate is an expression tainted by an SQLite collation.
|
||||
///
|
||||
/// // email = 'arthur@example.com' COLLATE NOCASE
|
||||
/// SQLExpressionCollate(Column("email") == "arthur@example.com", "NOCASE")
|
||||
struct SQLExpressionCollate : SQLExpression {
|
||||
let expression: SQLExpression
|
||||
let collationName: Database.CollationName
|
||||
|
||||
init(_ expression: SQLExpression, collationName: Database.CollationName) {
|
||||
self.expression = expression
|
||||
self.collationName = collationName
|
||||
}
|
||||
|
||||
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 + ")"
|
||||
} else {
|
||||
return sql + " COLLATE " + collationName.rawValue
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,6 @@
|
||||
// MARK: - SQLExpression
|
||||
|
||||
/// This protocol is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// SQLExpression is the protocol for types that represent an SQL expression, as
|
||||
/// described at https://www.sqlite.org/lang_expr.html
|
||||
@@ -23,12 +18,7 @@
|
||||
/// - SQLExpressionCollate
|
||||
public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderingTerm {
|
||||
|
||||
/// This function is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns an SQL string that represents the expression.
|
||||
///
|
||||
@@ -48,12 +38,7 @@ public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderi
|
||||
/// arguments // ["foo'bar"]
|
||||
func expressionSQL(_ arguments: inout StatementArguments?) -> String
|
||||
|
||||
/// This property is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns the expression, negated. This property fuels the `!` operator.
|
||||
///
|
||||
@@ -70,16 +55,9 @@ public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderi
|
||||
var negated: SQLExpression { get }
|
||||
}
|
||||
|
||||
// MARK: Default Implementations
|
||||
|
||||
extension SQLExpression {
|
||||
|
||||
/// This property is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The default implementation returns the expression prefixed by `NOT`.
|
||||
///
|
||||
@@ -87,669 +65,54 @@ extension SQLExpression {
|
||||
/// column.negated // NOT favorite
|
||||
///
|
||||
public var negated: SQLExpression {
|
||||
return SQLExpressionUnary(.not, self)
|
||||
}
|
||||
|
||||
/// This property is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// Converts an expression to an SQLExpressionLiteral
|
||||
public var literal: SQLExpressionLiteral {
|
||||
var arguments: StatementArguments? = []
|
||||
let sql = expressionSQL(&arguments)
|
||||
return SQLExpressionLiteral(sql, arguments: arguments)
|
||||
}
|
||||
|
||||
/// The expression as a quoted SQL literal (not public in order to avoid abuses)
|
||||
///
|
||||
/// "foo'bar".databaseValue.sql // "'foo''bar'""
|
||||
var sql: String {
|
||||
var arguments: StatementArguments? = nil
|
||||
return expressionSQL(&arguments)
|
||||
return SQLExpressionNot(self)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: SQLExpressible Adoption
|
||||
// SQLExpression: SQLExpressible
|
||||
|
||||
extension SQLExpression {
|
||||
|
||||
/// This property is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// See SQLExpressible.sqlExpression
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public var sqlExpression: SQLExpression {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: SQLSelectable Adoption
|
||||
// SQLExpression: SQLSelectable
|
||||
|
||||
extension SQLExpression {
|
||||
|
||||
/// This function is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// See SQLSelectable.countingSelectable(distinct:from:aliased:)
|
||||
public func countingSelectable(distinct: Bool, from tableName: String, aliased alias: String?) -> SQLSelectable? {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func count(distinct: Bool) -> SQLCount? {
|
||||
if distinct {
|
||||
// SELECT DISTINCT expr FROM tableName ...
|
||||
// ->
|
||||
// SELECT COUNT(DISTINCT expr) FROM tableName ...
|
||||
return SQLExpressionCountDistinct(self)
|
||||
return .distinct(self)
|
||||
} else {
|
||||
// SELECT expr FROM tableName ...
|
||||
// ->
|
||||
// SELECT COUNT(*) FROM tableName ...
|
||||
return SQLExpressionCount(star)
|
||||
return .star
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionNot
|
||||
|
||||
// MARK: - Column
|
||||
|
||||
/// A column in the database
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift#the-query-interface
|
||||
public struct Column {
|
||||
/// The name of the column
|
||||
public let name: String
|
||||
|
||||
/// Creates a column given its name.
|
||||
public init(_ name: String) {
|
||||
self.name = name
|
||||
}
|
||||
}
|
||||
|
||||
extension Column : SQLExpression {
|
||||
|
||||
/// This function is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// See SQLExpression.expressionSQL(_:arguments:)
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return name.quotedDatabaseIdentifier
|
||||
}
|
||||
}
|
||||
|
||||
extension Column {
|
||||
/// The hidden rowID column
|
||||
public static let rowID = Column("rowid")
|
||||
}
|
||||
|
||||
|
||||
// MARK: - DatabaseValue
|
||||
|
||||
extension DatabaseValue : SQLExpression {
|
||||
/// This function is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// See SQLExpression.expressionSQL(_:arguments:)
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
// fast path for NULL
|
||||
if isNull {
|
||||
return "NULL"
|
||||
}
|
||||
|
||||
if arguments != nil {
|
||||
arguments!.values.append(self)
|
||||
return "?"
|
||||
} else {
|
||||
// Correctness above all: use SQLite to quote the value.
|
||||
// Assume that the Quote function always succeeds
|
||||
return DatabaseQueue().inDatabase { try! String.fetchOne($0, "SELECT QUOTE(?)", arguments: [self])! }
|
||||
}
|
||||
}
|
||||
|
||||
/// This property is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// See SQLExpression.negated
|
||||
public var negated: SQLExpression {
|
||||
switch storage {
|
||||
case .null:
|
||||
return SQLExpressionUnary(.not, self)
|
||||
case .int64(let int64):
|
||||
return (int64 == 0).databaseValue
|
||||
case .double(let double):
|
||||
return (double == 0.0).databaseValue
|
||||
case .string:
|
||||
return SQLExpressionUnary(.not, self)
|
||||
case .blob:
|
||||
return SQLExpressionUnary(.not, self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - SQLExpressionLiteral
|
||||
|
||||
/// This type is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// SQLExpressionLiteral is an expression built from a raw SQL snippet.
|
||||
///
|
||||
/// SQLExpressionLiteral("1 + 2")
|
||||
///
|
||||
/// The SQL literal may contain `?` and colon-prefixed tokens:
|
||||
///
|
||||
/// SQLExpressionLiteral("? + ?", arguments: [1, 2])
|
||||
/// SQLExpressionLiteral(":one + :two", arguments: ["one": 1, "two": 2])
|
||||
public struct SQLExpressionLiteral : SQLExpression {
|
||||
/// The SQL literal
|
||||
public let sql: String
|
||||
|
||||
/// Eventual arguments that feed the `?` and colon-prefixed tokens in the
|
||||
/// SQL literal
|
||||
public let arguments: StatementArguments?
|
||||
|
||||
/// Creates an SQL literal expression.
|
||||
///
|
||||
/// SQLExpressionLiteral("1 + 2")
|
||||
/// SQLExpressionLiteral("? + ?", arguments: [1, 2])
|
||||
/// SQLExpressionLiteral(":one + :two", arguments: ["one": 1, "two": 2])
|
||||
public init(_ sql: String, arguments: StatementArguments? = nil) {
|
||||
self.sql = sql
|
||||
self.arguments = arguments
|
||||
}
|
||||
|
||||
/// This function is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// See SQLExpression.expressionSQL(_:arguments:)
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
if let literalArguments = self.arguments {
|
||||
guard arguments != nil else {
|
||||
// GRDB limitation: we don't know how to look for `?` in sql and
|
||||
// replace them with with literals.
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
arguments! += literalArguments
|
||||
}
|
||||
return sql
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - SQLExpressionUnary
|
||||
|
||||
/// This type is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// SQLUnaryOperator is a SQLite unary operator.
|
||||
public struct SQLUnaryOperator : Hashable {
|
||||
/// The SQL operator
|
||||
public let sql: String
|
||||
|
||||
/// If true GRDB puts a white space between the operator and the operand.
|
||||
public let needsRightSpace: Bool
|
||||
|
||||
/// Creates an unary operator
|
||||
///
|
||||
/// SQLUnaryOperator("~", needsRightSpace: false)
|
||||
public init(_ sql: String, needsRightSpace: Bool) {
|
||||
self.sql = sql
|
||||
self.needsRightSpace = needsRightSpace
|
||||
}
|
||||
|
||||
public var hashValue: Int {
|
||||
return sql.hashValue
|
||||
}
|
||||
|
||||
public static func ==(lhs: SQLUnaryOperator, rhs: SQLUnaryOperator) -> Bool {
|
||||
return lhs.sql == rhs.sql
|
||||
}
|
||||
}
|
||||
|
||||
/// This type is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// SQLExpressionUnary is an expression made of an unary operator and
|
||||
/// an operand expression.
|
||||
///
|
||||
/// SQLExpressionUnary(.not, Column("favorite"))
|
||||
public struct SQLExpressionUnary : SQLExpression {
|
||||
/// The unary operator
|
||||
public let op: SQLUnaryOperator
|
||||
|
||||
/// The operand
|
||||
public let expression: SQLExpression
|
||||
|
||||
/// Creates an expression made of an unary operator and
|
||||
/// an operand expression.
|
||||
///
|
||||
/// // NOT favorite
|
||||
/// SQLExpressionUnary(.not, Column("favorite"))
|
||||
public init(_ op: SQLUnaryOperator, _ value: SQLExpressible) {
|
||||
self.op = op
|
||||
self.expression = value.sqlExpression
|
||||
}
|
||||
|
||||
/// This function is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// See SQLExpression.expressionSQL(_:arguments:)
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return op.sql + (op.needsRightSpace ? " " : "") + expression.expressionSQL(&arguments)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - SQLExpressionBinary
|
||||
|
||||
/// This type is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// SQLBinaryOperator is a SQLite binary operator.
|
||||
public struct SQLBinaryOperator : Hashable {
|
||||
/// The SQL operator
|
||||
public let sql: String
|
||||
|
||||
/// The SQL for the negated operator, if any
|
||||
public let negatedSQL: String?
|
||||
|
||||
/// Creates a binary operator
|
||||
///
|
||||
/// SQLBinaryOperator("+")
|
||||
/// SQLBinaryOperator("IS", negated: "IS NOT")
|
||||
public init(_ sql: String, negated: String? = nil) {
|
||||
self.sql = sql
|
||||
self.negatedSQL = negated
|
||||
}
|
||||
|
||||
public var hashValue: Int {
|
||||
return sql.hashValue
|
||||
}
|
||||
|
||||
/// Returns the negated binary operator, if any
|
||||
///
|
||||
/// let operator = SQLBinaryOperator("IS", negated: "IS NOT")
|
||||
/// operator.negated!.sql // IS NOT
|
||||
public var negated: SQLBinaryOperator? {
|
||||
guard let negatedSQL = negatedSQL else {
|
||||
return nil
|
||||
}
|
||||
return SQLBinaryOperator(negatedSQL, negated: sql)
|
||||
}
|
||||
|
||||
public static func ==(lhs: SQLBinaryOperator, rhs: SQLBinaryOperator) -> Bool {
|
||||
return lhs.sql == rhs.sql
|
||||
}
|
||||
}
|
||||
|
||||
/// This type is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// SQLExpressionBinary is an expression made of two expressions joined with a
|
||||
/// binary operator.
|
||||
///
|
||||
/// SQLExpressionBinary(.multiply, Column("length"), Column("width"))
|
||||
public struct SQLExpressionBinary : SQLExpression {
|
||||
/// The left operand
|
||||
public let lhs: SQLExpression
|
||||
|
||||
/// The operator
|
||||
public let op: SQLBinaryOperator
|
||||
|
||||
/// The right operand
|
||||
public let rhs: SQLExpression
|
||||
|
||||
/// Creates an expression made of two expressions joined with a
|
||||
/// binary operator.
|
||||
///
|
||||
/// // length * width
|
||||
/// SQLExpressionBinary(.multiply, Column("length"), Column("width"))
|
||||
public init(_ op: SQLBinaryOperator, _ lhs: SQLExpressible, _ rhs: SQLExpressible) {
|
||||
self.lhs = lhs.sqlExpression
|
||||
self.op = op
|
||||
self.rhs = rhs.sqlExpression
|
||||
}
|
||||
|
||||
/// This function is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// See SQLExpression.expressionSQL(_:arguments:)
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return "(" + lhs.expressionSQL(&arguments) + " " + op.sql + " " + rhs.expressionSQL(&arguments) + ")"
|
||||
}
|
||||
|
||||
/// This property is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// See SQLExpression.negated
|
||||
public var negated: SQLExpression {
|
||||
if let negatedOp = op.negated {
|
||||
return SQLExpressionBinary(negatedOp, lhs, rhs)
|
||||
} else {
|
||||
return SQLExpressionUnary(.not, self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - SQLExpressionContains
|
||||
|
||||
/// SQLExpressionContains is an expression that checks the inclusion of a
|
||||
/// value in a collection with the `IN` operator.
|
||||
///
|
||||
/// // id IN (1,2,3)
|
||||
/// SQLExpressionContains(Column("id"), SQLExpressionsArray([1,2,3]))
|
||||
struct SQLExpressionContains : SQLExpression {
|
||||
struct SQLExpressionNot : SQLExpression {
|
||||
let expression: SQLExpression
|
||||
let collection: SQLCollection
|
||||
let isNegated: Bool
|
||||
|
||||
init(_ value: SQLExpressible, _ collection: SQLCollection, negated: Bool = false) {
|
||||
self.expression = value.sqlExpression
|
||||
self.collection = collection
|
||||
self.isNegated = negated
|
||||
init(_ expression: SQLExpression) {
|
||||
self.expression = expression
|
||||
}
|
||||
|
||||
func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return "(" +
|
||||
expression.expressionSQL(&arguments) +
|
||||
(isNegated ? " NOT IN (" : " IN (") +
|
||||
collection.collectionSQL(&arguments) +
|
||||
"))"
|
||||
return "NOT \(expression.expressionSQL(&arguments))"
|
||||
}
|
||||
|
||||
var negated: SQLExpression {
|
||||
return SQLExpressionContains(expression, collection, negated: !isNegated)
|
||||
return expression
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - SQLExpressionExists
|
||||
|
||||
/// This type is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// SQLExpressionExists is an expression that checks if a subquery would return
|
||||
/// rows or not with the `EXISTS` operator.
|
||||
public struct SQLExpressionExists : SQLExpression {
|
||||
/// The query
|
||||
public let query: SQLSelectQuery
|
||||
|
||||
/// If true, uses `NOT EXISTS` instead of `EXISTS` operator
|
||||
public let isNegated: Bool
|
||||
|
||||
/// Creates an expression that checks if a subquery would return rows
|
||||
/// or not with the `EXISTS` operator.
|
||||
public init(_ query: SQLSelectQuery, negated: Bool = false) {
|
||||
self.query = query
|
||||
self.isNegated = negated
|
||||
}
|
||||
|
||||
/// This function is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// See SQLExpression.expressionSQL(_:arguments:)
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return "(" +
|
||||
(isNegated ? "NOT EXISTS (" : "EXISTS (") +
|
||||
query.selectQuerySQL(&arguments)
|
||||
+ "))"
|
||||
}
|
||||
|
||||
/// This property is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// See SQLExpression.negated
|
||||
public var negated: SQLExpression {
|
||||
return SQLExpressionExists(query, negated: !isNegated)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - SQLExpressionBetween
|
||||
|
||||
/// SQLExpressionBetween is an expression that checks if a values is included
|
||||
/// in a range with the `BETWEEN` operator.
|
||||
///
|
||||
/// // id BETWEEN 1 AND 3
|
||||
/// SQLExpressionBetween(Column("id"), 1.databaseValue, 3.databaseValue)
|
||||
struct SQLExpressionBetween : SQLExpression {
|
||||
let expression: SQLExpression
|
||||
let lowerBound: SQLExpression
|
||||
let upperBound: SQLExpression
|
||||
let isNegated: Bool
|
||||
|
||||
init(_ expression: SQLExpression, _ lowerBound: SQLExpression, _ upperBound: SQLExpression, negated: Bool = false) {
|
||||
self.expression = expression
|
||||
self.lowerBound = lowerBound
|
||||
self.upperBound = upperBound
|
||||
self.isNegated = negated
|
||||
}
|
||||
|
||||
func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return "(" +
|
||||
expression.expressionSQL(&arguments) +
|
||||
(isNegated ? " NOT BETWEEN " : " BETWEEN ") +
|
||||
lowerBound.expressionSQL(&arguments) +
|
||||
" AND " +
|
||||
upperBound.expressionSQL(&arguments) +
|
||||
")"
|
||||
}
|
||||
|
||||
var negated: SQLExpression {
|
||||
return SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - SQLExpressionFunction
|
||||
|
||||
/// This type is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// SQLFunctionName is an SQL function name.
|
||||
public struct SQLFunctionName : Hashable {
|
||||
/// The SQL function name
|
||||
public let sql: String
|
||||
|
||||
/// Creates a function name
|
||||
///
|
||||
/// SQLFunctionName("ABS")
|
||||
public init(_ sql: String) {
|
||||
self.sql = sql
|
||||
}
|
||||
|
||||
public var hashValue: Int {
|
||||
return sql.hashValue
|
||||
}
|
||||
|
||||
public static func ==(lhs: SQLFunctionName, rhs: SQLFunctionName) -> Bool {
|
||||
return lhs.sql == rhs.sql
|
||||
}
|
||||
}
|
||||
|
||||
/// This type is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// SQLExpressionFunction is an SQL function call.
|
||||
///
|
||||
/// // ABS(-1)
|
||||
/// SQLExpressionFunction(.abs, [-1.databaseValue])
|
||||
public struct SQLExpressionFunction : SQLExpression {
|
||||
/// The function name
|
||||
public let functionName: SQLFunctionName
|
||||
|
||||
/// The function arguments
|
||||
public let arguments: [SQLExpression]
|
||||
|
||||
/// Creates an SQL function call
|
||||
///
|
||||
/// // ABS(-1)
|
||||
/// SQLExpressionFunction(.abs, arguments: [-1.databaseValue])
|
||||
public init(_ functionName: SQLFunctionName, arguments: [SQLExpression]) {
|
||||
self.functionName = functionName
|
||||
self.arguments = arguments
|
||||
}
|
||||
|
||||
/// Creates an SQL function call
|
||||
///
|
||||
/// // ABS(-1)
|
||||
/// SQLExpressionFunction(.abs, arguments: -1)
|
||||
public init(_ functionName: SQLFunctionName, arguments: SQLExpressible...) {
|
||||
self.init(functionName, arguments: arguments.map { $0.sqlExpression })
|
||||
}
|
||||
|
||||
/// This function is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// See SQLExpression.expressionSQL(_:arguments:)
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return functionName.sql + "(" + (self.arguments.map { $0.expressionSQL(&arguments) } as [String]).joined(separator: ", ") + ")"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - SQLExpressionCount
|
||||
|
||||
/// SQLExpressionCount is a call to the SQL `COUNT` function.
|
||||
///
|
||||
/// // COUNT(name)
|
||||
/// SQLExpressionCount(Column("name"))
|
||||
struct SQLExpressionCount : SQLExpression {
|
||||
/// The counted value
|
||||
let counted: SQLSelectable
|
||||
|
||||
init(_ counted: SQLSelectable) {
|
||||
self.counted = counted
|
||||
}
|
||||
|
||||
func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return "COUNT(" + counted.countedSQL(&arguments) + ")"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - SQLExpressionCountDistinct
|
||||
|
||||
/// SQLExpressionCountDistinct is a call to the SQL `COUNT(DISTINCT ...)` function.
|
||||
///
|
||||
/// // COUNT(DISTINCT name)
|
||||
/// SQLExpressionCountDistinct(Column("name"))
|
||||
struct SQLExpressionCountDistinct : SQLExpression {
|
||||
let counted: SQLExpression
|
||||
|
||||
init(_ counted: SQLExpression) {
|
||||
self.counted = counted
|
||||
}
|
||||
|
||||
func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return "COUNT(DISTINCT " + counted.expressionSQL(&arguments) + ")"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - SQLExpressionCollate
|
||||
|
||||
/// SQLExpressionCollate is an expression tainted by an SQLite collation.
|
||||
///
|
||||
/// // email = 'arthur@example.com' COLLATE NOCASE
|
||||
/// SQLExpressionCollate(Column("email") == "arthur@example.com", "NOCASE")
|
||||
struct SQLExpressionCollate : SQLExpression {
|
||||
let expression: SQLExpression
|
||||
let collationName: Database.CollationName
|
||||
|
||||
init(_ expression: SQLExpression, collationName: Database.CollationName) {
|
||||
self.expression = expression
|
||||
self.collationName = collationName
|
||||
}
|
||||
|
||||
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 + ")"
|
||||
} else {
|
||||
return sql + " COLLATE " + collationName.rawValue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
// MARK: - SQLOrderingTerm
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// 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
|
||||
public protocol SQLOrderingTerm {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The ordering term, reversed
|
||||
var reversed: SQLOrderingTerm { get }
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns an SQL string that represents the ordering term.
|
||||
///
|
||||
/// When the arguments parameter is nil, any value must be written down as
|
||||
/// a literal in the returned SQL:
|
||||
///
|
||||
/// var arguments: StatementArguments? = nil
|
||||
/// let orderingTerm = Column("name") ?? "Anonymous"
|
||||
/// orderingTerm.orderingTermSQL(&arguments) // "IFNULL(name, 'Anonymous')"
|
||||
///
|
||||
/// When the arguments parameter is not nil, then values may be replaced by
|
||||
/// `?` or colon-prefixed tokens, and fed into arguments.
|
||||
///
|
||||
/// var arguments = StatementArguments()
|
||||
/// let orderingTerm = Column("name") ?? "Anonymous"
|
||||
/// orderingTerm.orderingTermSQL(&arguments) // "IFNULL(name, ?)"
|
||||
/// arguments // ["Anonymous"]
|
||||
func orderingTermSQL(_ arguments: inout StatementArguments?) -> String
|
||||
}
|
||||
|
||||
// MARK: - SQLOrdering
|
||||
|
||||
enum SQLOrdering : SQLOrderingTerm {
|
||||
case asc(SQLExpression)
|
||||
case desc(SQLExpression)
|
||||
|
||||
var reversed: SQLOrderingTerm {
|
||||
switch self {
|
||||
case .asc(let expression):
|
||||
return SQLOrdering.desc(expression)
|
||||
case .desc(let expression):
|
||||
return SQLOrdering.asc(expression)
|
||||
}
|
||||
}
|
||||
|
||||
func orderingTermSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
switch self {
|
||||
case .asc(let expression):
|
||||
return expression.expressionSQL(&arguments) + " ASC"
|
||||
case .desc(let expression):
|
||||
return expression.expressionSQL(&arguments) + " DESC"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
// MARK: - SQLOrderingTerm
|
||||
|
||||
/// This protocol is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// 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
|
||||
public protocol SQLOrderingTerm {
|
||||
var reversed: SQLOrderingTerm { get }
|
||||
func orderingTermSQL(_ arguments: inout StatementArguments?) -> String
|
||||
}
|
||||
|
||||
|
||||
// MARK: - SQLOrdering
|
||||
|
||||
enum SQLOrdering : SQLOrderingTerm {
|
||||
case asc(SQLExpression)
|
||||
case desc(SQLExpression)
|
||||
|
||||
var reversed: SQLOrderingTerm {
|
||||
switch self {
|
||||
case .asc(let expression):
|
||||
return SQLOrdering.desc(expression)
|
||||
case .desc(let expression):
|
||||
return SQLOrdering.asc(expression)
|
||||
}
|
||||
}
|
||||
|
||||
func orderingTermSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
switch self {
|
||||
case .asc(let expression):
|
||||
return expression.expressionSQL(&arguments) + " ASC"
|
||||
case .desc(let expression):
|
||||
return expression.expressionSQL(&arguments) + " DESC"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - SQLExpressible
|
||||
|
||||
extension SQLExpressible where Self: SQLOrderingTerm {
|
||||
|
||||
/// This property is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// See SQLOrderingTerm.reversed
|
||||
public var reversed: SQLOrderingTerm {
|
||||
return SQLOrdering.desc(sqlExpression)
|
||||
}
|
||||
|
||||
/// This method is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// See SQLOrderingTerm.orderingTermSQL(_)
|
||||
public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return sqlExpression.expressionSQL(&arguments)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - SQLCollatedExpression
|
||||
|
||||
extension SQLCollatedExpression : SQLOrderingTerm {
|
||||
|
||||
/// Returns self.desc
|
||||
public var reversed: SQLOrderingTerm {
|
||||
return desc
|
||||
}
|
||||
|
||||
/// This method is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return sqlExpression.orderingTermSQL(&arguments)
|
||||
}
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
// MARK: - SQLSelectQuery
|
||||
|
||||
/// This protocol is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// SQLSelectQuery is the protocol for types that represent a full select query.
|
||||
public protocol SQLSelectQuery : Request, SQLCollection {
|
||||
|
||||
/// This function is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// Returns the SQL string of the select query.
|
||||
///
|
||||
/// When the arguments parameter is nil, any value must be written down as
|
||||
/// a literal in the returned SQL.
|
||||
///
|
||||
/// When the arguments parameter is not nil, then values may be replaced by
|
||||
/// `?` or colon-prefixed tokens, and fed into arguments.
|
||||
func selectQuerySQL(_ arguments: inout StatementArguments?) -> String
|
||||
}
|
||||
|
||||
extension SQLSelectQuery {
|
||||
|
||||
/// Returns an SQL expression that checks whether the receiver, as a
|
||||
/// subquery, returns any row.
|
||||
///
|
||||
///
|
||||
/// let request = Person.all()
|
||||
/// request.exists() // EXISTS (SELECT * FROM persons)
|
||||
public func exists() -> SQLExpression {
|
||||
return SQLExpressionExists(self)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - SQLCollection adoption
|
||||
|
||||
extension SQLSelectQuery {
|
||||
|
||||
/// This function is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// See SQLCollection.collectionSQL(_)
|
||||
public func collectionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return selectQuerySQL(&arguments)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Request adoption
|
||||
|
||||
extension SQLSelectQuery {
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
var arguments: StatementArguments? = StatementArguments()
|
||||
let sql = self.selectQuerySQL(&arguments)
|
||||
let statement = try db.makeSelectStatement(sql)
|
||||
try statement.setArgumentsWithValidation(arguments!)
|
||||
return (statement, nil)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - QueryInterfaceSelectQueryDefinition
|
||||
|
||||
extension QueryInterfaceSelectQueryDefinition : SQLSelectQuery {
|
||||
/// This function is an implementation detail of the query interface.
|
||||
/// Do not use it directly.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
///
|
||||
/// # Low Level Query Interface
|
||||
///
|
||||
/// See SQLSelectQuery.selectQuerySQL(_:arguments:)
|
||||
func selectQuerySQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return sql(&arguments)
|
||||
}
|
||||
}
|
||||
Loaded 100 of 412 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user