Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ef07897ba4 | ||
|
|
dd7e7f39e8 | ||
|
|
8801adb21c | ||
|
|
f721af86cd | ||
|
|
23f4254ae3 | ||
|
|
2df6a17c1c | ||
|
|
5aeee0e429 | ||
|
|
3a61a8a0e0 | ||
|
|
e0766449f1 | ||
|
|
c1e752132c | ||
|
|
6ab90a03c4 | ||
|
|
23fa42a3e4 | ||
|
|
07eaeee123 | ||
|
|
0bfb4de02d | ||
|
|
d72b7109ad | ||
|
|
e1a63a4c05 | ||
|
|
caab403282 | ||
|
|
bbe94a9607 | ||
|
|
84bee1977e | ||
|
|
0aa561e61c | ||
|
|
b1b51c01f8 | ||
|
|
cc5196757d | ||
|
|
0e9766373d | ||
|
|
aacaa433c9 | ||
|
|
44ec3535c2 | ||
|
|
38c0d68db7 | ||
|
|
f3cc4add9f | ||
|
|
432670e13a | ||
|
|
3ba13b0af6 | ||
|
|
1a6228e2c5 | ||
|
|
e02f2c8aba | ||
|
|
c0e9c8746d | ||
|
|
d1cba5e5c8 | ||
|
|
bf824bf68c | ||
|
|
5e5b44aa7f | ||
|
|
806919b5be | ||
|
|
a289aecc3c | ||
|
|
3f7adec072 | ||
|
|
c9f3a1e17f | ||
|
|
cf2a79e12f | ||
|
|
a0212eb129 | ||
|
|
d5470b7278 | ||
|
|
cd6960f5e9 | ||
|
|
f72859b5b2 | ||
|
|
b947065d25 | ||
|
|
11f95806c4 | ||
|
|
2ac5c77353 | ||
|
|
2a849d380c | ||
|
|
fd31632203 | ||
|
|
4a98a53dad | ||
|
|
952ee0a137 | ||
|
|
ee92db9d6f | ||
|
|
de4266499c | ||
|
|
4b7a9bbe7b | ||
|
|
184d5aa4af | ||
|
|
6c48e492d1 | ||
|
|
26fedd2702 | ||
|
|
06216fd875 | ||
|
|
42050e5e28 | ||
|
|
9ed309b470 | ||
|
|
00d1a80b31 | ||
|
|
aaf3efe6df | ||
|
|
d8f2989542 | ||
|
|
28543109ea | ||
|
|
63c2bd0876 | ||
|
|
59bd10b1b5 | ||
|
|
758f561fbf | ||
|
|
40b0e98eb5 | ||
|
|
2ec0a4c69d | ||
|
|
ca43f1e803 | ||
|
|
0a7e7d1e5c | ||
|
|
1260980150 | ||
|
|
f0cfde682e | ||
|
|
096a3b2f0f | ||
|
|
f313a43ef9 | ||
|
|
fead2ea634 | ||
|
|
5b254eec16 | ||
|
|
3632edb238 | ||
|
|
752415b5fb | ||
|
|
f17a786165 | ||
|
|
b89ce00361 | ||
|
|
c5eba4741d | ||
|
|
fb18a3938f | ||
|
|
5082207bb0 | ||
|
|
06b5367053 | ||
|
|
819ee588c9 | ||
|
|
1b3f1ed393 | ||
|
|
f0fe7e86ca | ||
|
|
dd5ce280b5 | ||
|
|
744aa825a3 | ||
|
|
24f3de9dfa | ||
|
|
4472d3a60e | ||
|
|
dc03adb4e2 | ||
|
|
dea9bedacb | ||
|
|
83d243853b | ||
|
|
209192d3a5 | ||
|
|
15c06e0374 | ||
|
|
0324f592dc | ||
|
|
051787b17f | ||
|
|
feebc07101 | ||
|
|
80c15c6ef6 | ||
|
|
9014b3ebd0 | ||
|
|
bec58a32d4 | ||
|
|
b66374670c | ||
|
|
f3992a034d | ||
|
|
8b120fa9b6 | ||
|
|
8b58ec4cee | ||
|
|
9b7b603a69 | ||
|
|
a3a26bf88f | ||
|
|
770484b78d | ||
|
|
fafa74c246 | ||
|
|
62450b5817 | ||
|
|
e9b8df68ee | ||
|
|
9fa831b6bb | ||
|
|
43e1871005 | ||
|
|
8a6e784428 | ||
|
|
727ca68b98 | ||
|
|
fb3e08aba8 | ||
|
|
1c614e8de6 | ||
|
|
3f0a8e6730 | ||
|
|
6916a8feca | ||
|
|
e08dfdb0bf | ||
|
|
6236b8a068 | ||
|
|
55dea6f9d2 | ||
|
|
cdb08988f4 | ||
|
|
881bbd3f0d | ||
|
|
6ab3fea8fb | ||
|
|
287ceb8b07 | ||
|
|
4eefb9afbe | ||
|
|
4ea04ec978 | ||
|
|
c30b49117b | ||
|
|
ec975819b7 | ||
|
|
b974dfa9a7 | ||
|
|
e19f21be99 | ||
|
|
9b0e41ad58 | ||
|
|
d40474d2b7 | ||
|
|
685074932e | ||
|
|
f1a23bacc0 | ||
|
|
fbef103f01 | ||
|
|
fc9f0bcad1 | ||
|
|
1929e96d11 | ||
|
|
9d4eb8a6dd | ||
|
|
3914a9ec21 | ||
|
|
29bacc138c | ||
|
|
ba866359b2 | ||
|
|
ffced55d3c | ||
|
|
74caa96dcb | ||
|
|
f6bea21e80 | ||
|
|
27f6125099 | ||
|
|
70ea2027e4 | ||
|
|
e28658c574 | ||
|
|
c184b76849 | ||
|
|
d23d74f65f | ||
|
|
984a5b4c4c | ||
|
|
8e84beee36 | ||
|
|
95ce4a3f8a | ||
|
|
98ca653c6a | ||
|
|
e5a8e130d7 | ||
|
|
72e8dd2816 | ||
|
|
b5338650db | ||
|
|
75f72472ff | ||
|
|
09f7d4d952 | ||
|
|
c1c3cf6605 | ||
|
|
fc7f24ef6e | ||
|
|
3d0b34590f | ||
|
|
2d6c2873e0 | ||
|
|
4e65425c00 | ||
|
|
b82f92f726 | ||
|
|
b8c0e9d2c2 | ||
|
|
b2df255306 | ||
|
|
c60b8cfc53 | ||
|
|
9dc6fbd7f9 | ||
|
|
9a4e1f7806 | ||
|
|
5dde1409ad | ||
|
|
936fd3ed5f | ||
|
|
ed4471c5b9 | ||
|
|
dd025a14e4 | ||
|
|
29808e51ff | ||
|
|
426044154c | ||
|
|
d69db0b9a1 | ||
|
|
914bd14cd1 | ||
|
|
b5395a097c | ||
|
|
99c596f778 | ||
|
|
fd22fac5c0 | ||
|
|
6e3a15ebed | ||
|
|
bb8b39f7fd | ||
|
|
fc5138ae91 | ||
|
|
d3985c7ebf | ||
|
|
9f0ba49c93 | ||
|
|
09922c34ff | ||
|
|
3826003d93 | ||
|
|
9baa72cfd7 | ||
|
|
aacc69f485 | ||
|
|
301fb34702 | ||
|
|
6444285ee2 | ||
|
|
bd42dc69f0 | ||
|
|
14d8763a84 | ||
|
|
c46e8257d8 | ||
|
|
948c7870bd | ||
|
|
fa896eee23 | ||
|
|
c4023ccf0a | ||
|
|
fe92b93f0b | ||
|
|
28109a3947 | ||
|
|
124cba1b21 | ||
|
|
ca47426c61 | ||
|
|
90c85c6703 | ||
|
|
6d3f309cad | ||
|
|
06dbaba7cc | ||
|
|
daf44d9baa | ||
|
|
187a661626 | ||
|
|
55302cb937 | ||
|
|
869d776962 | ||
|
|
b53b43b1fc | ||
|
|
42d29b305e | ||
|
|
8f100a6395 | ||
|
|
44dd21690f | ||
|
|
6d31190c3f | ||
|
|
549f7ec66e | ||
|
|
3eea2967b3 | ||
|
|
8e6827070f | ||
|
|
d105b35750 | ||
|
|
149d5ac151 | ||
|
|
ed6c5438b9 | ||
|
|
bd67153095 | ||
|
|
3fff6b2f51 | ||
|
|
62a0b1c148 | ||
|
|
dfca044433 | ||
|
|
78df734f51 | ||
|
|
e72b7e4597 | ||
|
|
fb6c695658 | ||
|
|
a1c0c6d1f3 | ||
|
|
68f3e5586b | ||
|
|
8760033045 | ||
|
|
b2fabf5fc3 | ||
|
|
95f1d83d78 | ||
|
|
790c054a28 | ||
|
|
06a5d6f44b | ||
|
|
3145a916a0 | ||
|
|
94ff9f3e45 | ||
|
|
c172dac909 | ||
|
|
5b7ba122e8 | ||
|
|
0513e0acf8 | ||
|
|
b3d49de023 | ||
|
|
779e2c202f | ||
|
|
be45781cf9 | ||
|
|
c7d816b860 | ||
|
|
a0f6f7a9ab | ||
|
|
86c0180487 | ||
|
|
80c11d0bc4 | ||
|
|
66602ba2e2 | ||
|
|
8fdcc020e0 | ||
|
|
1bb2029e74 | ||
|
|
fc0e1bede1 | ||
|
|
823af1944e | ||
|
|
2093b477df | ||
|
|
29cd08cba4 | ||
|
|
76523db5b9 | ||
|
|
c0305853bc | ||
|
|
5d51f2a884 | ||
|
|
bdf54e80a9 | ||
|
|
e799c8534e | ||
|
|
536ad2ebff | ||
|
|
972f45295f | ||
|
|
b96bd52c38 | ||
|
|
2af0a74676 | ||
|
|
4aa37f6169 | ||
|
|
37571525e6 | ||
|
|
911b2a76d8 | ||
|
|
54b13de632 | ||
|
|
4a3232199f | ||
|
|
bf28abbb25 | ||
|
|
c945504a34 | ||
|
|
8217966215 | ||
|
|
c96a74658c | ||
|
|
042e220f49 | ||
|
|
a71639159b | ||
|
|
d633927999 | ||
|
|
8df7020ad7 | ||
|
|
bc95c5c977 | ||
|
|
ef4709d3f0 | ||
|
|
e1984721dc | ||
|
|
469898c5df | ||
|
|
0207aef4dc | ||
|
|
d7604d2174 | ||
|
|
89421c92fb | ||
|
|
0cf4c4efba | ||
|
|
710142edc0 | ||
|
|
7001b60cf7 | ||
|
|
dcc2d211b2 | ||
|
|
340203686d | ||
|
|
ae609cec3b | ||
|
|
8ba89a398a | ||
|
|
95b3f447e4 | ||
|
|
bc2a66e40f | ||
|
|
cb32a0d0cc | ||
|
|
effc991de1 | ||
|
|
3049b88fea | ||
|
|
c39db96521 | ||
|
|
d7514f84f1 | ||
|
|
1b62e06c4a | ||
|
|
bedf2dbcd4 | ||
|
|
13e195db40 | ||
|
|
087ad10086 | ||
|
|
f012c011b1 | ||
|
|
f829d46b7f | ||
|
|
ab6f18e46d | ||
|
|
9579671c02 | ||
|
|
01f4c04c4d | ||
|
|
7ac78a8ec1 | ||
|
|
97e00ab44f | ||
|
|
33d9ca0e97 | ||
|
|
b2985b77c4 | ||
|
|
ec882e8126 | ||
|
|
61b0df8017 | ||
|
|
103266d70c | ||
|
|
3f02724e60 | ||
|
|
ca05a93c98 | ||
|
|
48f6cee7a6 | ||
|
|
8ed16f4440 | ||
|
|
6ec3ebc398 | ||
|
|
86d0fedfbb | ||
|
|
0330365d49 | ||
|
|
ca2f36781e | ||
|
|
6c7f71f620 | ||
|
|
60bf5d30b0 | ||
|
|
94caf4ba97 | ||
|
|
a7002e1e09 | ||
|
|
54a991b3b9 | ||
|
|
54ca12437a | ||
|
|
3298cca75f | ||
|
|
4fe0b687d2 | ||
|
|
9df0f4cdbd | ||
|
|
e1dc24ac93 | ||
|
|
88e60ed0c6 | ||
|
|
b4ca103002 | ||
|
|
564c4cef5c | ||
|
|
7a77a1fd06 | ||
|
|
c7291db360 | ||
|
|
a52d1b1d21 | ||
|
|
89b1783220 | ||
|
|
76d2168988 | ||
|
|
e419bb55ca | ||
|
|
06eb45db65 | ||
|
|
6180e4b815 | ||
|
|
85747935c8 | ||
|
|
36fba9a79a | ||
|
|
6240585a03 | ||
|
|
ad66fbc666 | ||
|
|
e69092ca6a | ||
|
|
bb2ce74125 | ||
|
|
06bf3980b6 | ||
|
|
97d4a60148 | ||
|
|
811c41af6d | ||
|
|
a9036a4563 | ||
|
|
988c7bb62f | ||
|
|
51182fc862 | ||
|
|
485509a8cc | ||
|
|
a81f80cddb | ||
|
|
d590a06212 | ||
|
|
b3a1497791 | ||
|
|
c7f0a80a91 | ||
|
|
068081d043 | ||
|
|
01ba7de2f9 | ||
|
|
10e784bee3 | ||
|
|
21c6c9c794 | ||
|
|
dec515aceb | ||
|
|
9be04da707 | ||
|
|
6b02b4ca02 | ||
|
|
5983473aa5 | ||
|
|
1c4456a9fc | ||
|
|
82a2776acd | ||
|
|
c7fb5cb3e3 | ||
|
|
f726b670f9 | ||
|
|
62e710b9b1 | ||
|
|
66f953a21a | ||
|
|
ceed45cf22 | ||
|
|
861ca5f022 | ||
|
|
8bf45e5452 | ||
|
|
d85168dd3c | ||
|
|
7ed103d5e4 | ||
|
|
b44a9eb470 | ||
|
|
d240d8c5f0 | ||
|
|
74f268a378 | ||
|
|
f74ce91a17 | ||
|
|
65668cfc8e | ||
|
|
9249efbe6f | ||
|
|
19fd58f64f | ||
|
|
19c7ec568c | ||
|
|
bc8a31dcd2 | ||
|
|
62f568d932 | ||
|
|
640a67257f | ||
|
|
5be27dd90a | ||
|
|
485ce79293 | ||
|
|
5725d9db21 | ||
|
|
7897c6a799 | ||
|
|
5f549ef6af | ||
|
|
ac94a2f90e | ||
|
|
15b38353bc | ||
|
|
1a87faacfa | ||
|
|
f70b75633c | ||
|
|
3a44311b95 | ||
|
|
e0a6f43101 | ||
|
|
0c8c8cb1f4 | ||
|
|
fa8598d1e8 | ||
|
|
6cf5a2c33d | ||
|
|
0317c4e454 | ||
|
|
db78c22904 | ||
|
|
6b36c74de9 | ||
|
|
51ab275714 | ||
|
|
b9e1f4604e | ||
|
|
0b853c5447 | ||
|
|
691ee8f7fd | ||
|
|
c755dc70ef | ||
|
|
9cc30018b6 | ||
|
|
4616ef5229 | ||
|
|
10a741a346 | ||
|
|
3c78029b3c | ||
|
|
3ea6fb2201 | ||
|
|
450a7c2d71 | ||
|
|
2542ad7de8 | ||
|
|
2a665df672 | ||
|
|
0a65399a7b | ||
|
|
02f71cfecc | ||
|
|
00cd547ea6 | ||
|
|
66bbf15f58 | ||
|
|
dbb19979d6 | ||
|
|
0d8d40d683 | ||
|
|
5d69d2a35b | ||
|
|
128399871a | ||
|
|
4dd5677755 | ||
|
|
dbf3335188 | ||
|
|
048082f4b2 | ||
|
|
6a980f90da | ||
|
|
e4bfea8bcc | ||
|
|
329a7c8301 | ||
|
|
1ff5159d40 | ||
|
|
d6f8a9a9ea | ||
|
|
c711efc7e0 | ||
|
|
01d2bc89a9 | ||
|
|
6bcee422b7 | ||
|
|
07faea9cfe | ||
|
|
b76950f695 | ||
|
|
b9e79791a3 | ||
|
|
533cef692f | ||
|
|
0bed585fd0 | ||
|
|
54bef0bba6 | ||
|
|
a7820f9a35 | ||
|
|
bd89311f4d | ||
|
|
1e17bf011f | ||
|
|
ed8ff31b3e | ||
|
|
0ead20cdd6 | ||
|
|
2ad6131d08 | ||
|
|
646782d499 | ||
|
|
a888c46b1a | ||
|
|
046d1d6355 | ||
|
|
8936ef6a40 | ||
|
|
8754b10a40 | ||
|
|
1f73c20ae2 | ||
|
|
a827188881 | ||
|
|
64be4763f2 |
No files matched your search
@@ -1,5 +0,0 @@
|
||||
source 'https://rubygems.org'
|
||||
|
||||
gem 'xcpretty'
|
||||
gem 'xcpretty-travis-formatter'
|
||||
gem 'cocoapods', '~> 1.7'
|
||||
@@ -3,10 +3,12 @@
|
||||
### Pull Request Checklist
|
||||
|
||||
<!--
|
||||
Please verify that your pull request checks those boxes:
|
||||
Please check the boxes that apply to your pull request:
|
||||
-->
|
||||
|
||||
- [ ] This pull request is submitted against the `development` branch.
|
||||
- [ ] Inline documentation has been updated.
|
||||
- [ ] README.md or another dedicated guide has been updated.
|
||||
- [ ] Changes are tested.
|
||||
- [ ] CONTRIBUTING: You have read https://github.com/groue/GRDB.swift/blob/master/CONTRIBUTING.md
|
||||
- [ ] BRANCH: This pull request is submitted against the `development` branch.
|
||||
- [ ] DOCUMENTATION: Inline documentation has been updated.
|
||||
- [ ] DOCUMENTATION: README.md or another dedicated guide has been updated.
|
||||
- [ ] TESTS: Changes are tested.
|
||||
- [ ] TESTS: The `make smokeTest` terminal command runs without failure.
|
||||
@@ -0,0 +1,6 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
@@ -1,19 +1,172 @@
|
||||
name: CI
|
||||
name: "GRDB CI"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master, development ]
|
||||
branches:
|
||||
- master
|
||||
- development
|
||||
- GRDB5
|
||||
paths:
|
||||
- 'GRDB/**'
|
||||
- 'Tests/**'
|
||||
- '.github/workflows/**'
|
||||
- 'Package.swift'
|
||||
pull_request:
|
||||
branches: [ master, development ]
|
||||
paths:
|
||||
- 'GRDB/**'
|
||||
- 'Tests/**'
|
||||
- '.github/workflows/**'
|
||||
- 'Package.swift'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.ref_name }}
|
||||
cancel-in-progress: true
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
runs-on: macos-latest
|
||||
|
||||
macOS:
|
||||
name: macOS
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_13.2.1.app"
|
||||
runsOn: macOS-11
|
||||
name: "macOS 11, Xcode 13.2.1, Swift 5.5.2"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_13.1.app"
|
||||
runsOn: macOS-11
|
||||
name: "macOS 11, Xcode 13.1, Swift 5.5.1"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_13.0.app"
|
||||
runsOn: macOS-11
|
||||
name: "macOS 11, Xcode 13.0, Swift 5.5.0"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.5.1.app"
|
||||
runsOn: macOS-11
|
||||
name: "macOS 11, Xcode 12.5.1, Swift 5.4"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.4.app"
|
||||
runsOn: macOS-10.15
|
||||
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Build
|
||||
run: swift build -v
|
||||
- name: Run tests
|
||||
run: swift test -v
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_GRDBOSX_maxSwift
|
||||
iOS:
|
||||
name: iOS
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.4.app"
|
||||
runsOn: macOS-10.15
|
||||
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
SPM:
|
||||
name: SPM
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_SPM test_install_SPM
|
||||
SQLCipher3:
|
||||
name: SQLCipher3
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_SQLCipher3Encrypted
|
||||
SQLCipher4:
|
||||
name: SQLCipher4
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.4.app"
|
||||
runsOn: macOS-10.15
|
||||
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_SQLCipher4Encrypted
|
||||
CustomSQLite:
|
||||
name: CustomSQLite
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.4.app"
|
||||
runsOn: macOS-10.15
|
||||
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_GRDBCustomSQLiteOSX
|
||||
XCFramework:
|
||||
name: XCFramework
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_archive_GRDBOSX_xcframework
|
||||
|
||||
@@ -7,6 +7,18 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 5.x Releases
|
||||
|
||||
- `5.26.x` Releases - [5.26.0](#5260) | [5.26.1](#5261)
|
||||
- `5.25.x` Releases - [5.25.0](#5250)
|
||||
- `5.24.x` Releases - [5.24.0](#5240) | [5.24.1](#5241)
|
||||
- `5.23.x` Releases - [5.23.0](#5230)
|
||||
- `5.22.x` Releases - [5.22.0](#5220) | [5.22.1](#5221) | [5.22.2](#5222)
|
||||
- `5.21.x` Releases - [5.21.0](#5210)
|
||||
- `5.20.x` Releases - [5.20.0](#5200)
|
||||
- `5.19.x` Releases - [5.19.0](#5190)
|
||||
- `5.18.x` Releases - [5.18.0](#5180)
|
||||
- `5.17.x` Releases - [5.17.0](#5170)
|
||||
- `5.16.x` Releases - [5.16.0](#5160)
|
||||
- `5.15.x` Releases - [5.15.0](#5150)
|
||||
- `5.14.x` Releases - [5.14.0](#5140)
|
||||
- `5.13.x` Releases - [5.13.0](#5130)
|
||||
- `5.12.x` Releases - [5.12.0](#5120)
|
||||
@@ -81,6 +93,146 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 5.26.1
|
||||
|
||||
Released September 8, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.26.0...v5.26.1)
|
||||
|
||||
- **Fixed**: [#1276](https://github.com/groue/GRDB.swift/pull/1276) Fix build error with Xcode 14.0 RC (14A309)
|
||||
|
||||
## 5.26.0
|
||||
|
||||
Released July 9, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.25.0...v5.26.0)
|
||||
|
||||
- **New**: [#1248](https://github.com/groue/GRDB.swift/pull/1248) by [@groue](https://github.com/groue): Avoid double notification of the initial value for ValueObservation on DatabasePool
|
||||
- **New**: [#1253](https://github.com/groue/GRDB.swift/pull/1253) by [@george-signal](https://github.com/george-signal): Make memory management optional
|
||||
- **Fixed**: DatabasePool no longer prevents database reads when UIKit posts `UIApplication.didReceiveMemoryWarningNotification` (see [#1253](https://github.com/groue/GRDB.swift/pull/1253) for more information).
|
||||
|
||||
## 5.25.0
|
||||
|
||||
Released June 11, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.24.1...v5.25.0)
|
||||
|
||||
- **New**: [#1226](https://github.com/groue/GRDB.swift/pull/1226) by [@naveensrinivasan](https://github.com/naveensrinivasan): Included githubactions in the dependabot config
|
||||
- **New**: [#1228](https://github.com/groue/GRDB.swift/pull/1228) by [@naveensrinivasan](https://github.com/naveensrinivasan): Set permissions for GitHub actions
|
||||
- **New**: [#1235](https://github.com/groue/GRDB.swift/pull/1235) by [@groue](https://github.com/groue): Raise default Quality of Service to `.userInitiated`.
|
||||
- **Fixed**: [#1233](https://github.com/groue/GRDB.swift/pull/1233) by [@GetToSet](https://github.com/GetToSet): Fix warnings of redundant conformance constraint on Xcode 14.
|
||||
|
||||
## 5.24.1
|
||||
|
||||
Released May 26, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.24.0...v5.24.1)
|
||||
|
||||
- **Fixed**: [#1217](https://github.com/groue/GRDB.swift/pull/1217) by [@GetToSet](https://github.com/GetToSet): Fix doc issue on TableRequest.filter(keys:).
|
||||
- **Fixed**: [#1225](https://github.com/groue/GRDB.swift/pull/1225) by [@groue](https://github.com/groue): Prevent heavy DatabasePool concurrent reads from creating too many threads
|
||||
|
||||
## 5.24.0
|
||||
|
||||
Released May 1, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.23.0...v5.24.0)
|
||||
|
||||
- **Fixed**: [#1203](https://github.com/groue/GRDB.swift/pull/1203) by [@EvanHahn](https://github.com/EvanHahn): Fix changelog links
|
||||
- **Fixed**: [#1212](https://github.com/groue/GRDB.swift/pull/1212) by [@MartinP7r](https://github.com/MartinP7r): Fix apple docs links
|
||||
- **Fixed**: [#1213](https://github.com/groue/GRDB.swift/pull/1213) by [@groue](https://github.com/groue): Fix crash when the number of active ValueObservations is high
|
||||
- **Breaking Change**: Transactions performed during a read-only database access are no longer notified to transaction observers. This is, strictly speaking, a breaking change. However it should have no impact since read-only transactions have very little interest.
|
||||
|
||||
## 5.23.0
|
||||
|
||||
Released April 16, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.22.2...v5.23.0)
|
||||
|
||||
- **Breaking Change**: [#1200](https://github.com/groue/GRDB.swift/pull/1200) by [@groue](https://github.com/groue): Require Swift 5.6 Compiler for experimental Concurrency Support
|
||||
|
||||
## 5.22.2
|
||||
|
||||
Released April 2, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.22.1...v5.22.2)
|
||||
|
||||
- **Fixed** a 5.22.0 regression: [#1196](https://github.com/groue/GRDB.swift/pull/1196) by [@layoutSubviews](https://github.com/layoutSubviews): Fix a crash when an observation is quickly cancelled
|
||||
|
||||
## 5.22.1
|
||||
|
||||
Released March 26, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.22.0...v5.22.1)
|
||||
|
||||
- **Fixed** a 5.22.0 regression: [#1194](https://github.com/groue/GRDB.swift/issues/1194) ValueObservation could deadlock when the database is configured with a serial target DispatchQueue.
|
||||
|
||||
## 5.22.0
|
||||
|
||||
Released March 22, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.21.0...v5.22.0)
|
||||
|
||||
- **New**: [#1186](https://github.com/groue/GRDB.swift/pull/1186) by [@benrb](https://github.com/benrb): DatabaseError provide error message as localizedFailureReason
|
||||
- **Breaking Change**: [#1183](https://github.com/groue/GRDB.swift/pull/1183) by [@groue](https://github.com/groue): Starting a ValueObservation keeps a strong reference on the database connection.
|
||||
|
||||
## 5.21.0
|
||||
|
||||
Released February 6, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.20.0...v5.21.0)
|
||||
|
||||
- **New**: [#1165](https://github.com/groue/GRDB.swift/pull/1165) by [@guidedways](https://github.com/guidedways): Support dynamic linking via Swift Package Manager
|
||||
- **Breaking Change**: [#1164](https://github.com/groue/GRDB.swift/pull/1164) by [@groue](https://github.com/groue): Drop experimental async apis from DatabaseMigrator
|
||||
|
||||
|
||||
## 5.20.0
|
||||
|
||||
Released February 1, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.19.0...v5.20.0)
|
||||
|
||||
- **Fixed**: Fixed a bug of `including(all:)` for composite foreign keys and limited requests.
|
||||
- **Fixed**: [#1162](https://github.com/groue/GRDB.swift/pull/1162) by [@groue](https://github.com/groue): Fix truncate optimization handling.
|
||||
- **New**: [#1160](https://github.com/groue/GRDB.swift/pull/1160) by [@groue](https://github.com/groue): Hide statement arguments by default.
|
||||
- **New**: [#1161](https://github.com/groue/GRDB.swift/pull/1161) by [@groue](https://github.com/groue): Target DispatchQueue for non-read-only database connections.
|
||||
- **Documentation Update**: The [Database Configuration](README.md#database-configuration) chapter explains how to opt in for public statement arguments in DEBUG builds.
|
||||
|
||||
|
||||
## 5.19.0
|
||||
|
||||
Released January 19, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.18.0...v5.19.0)
|
||||
|
||||
- **New**: [#1144](https://github.com/groue/GRDB.swift/pull/1144) by [@TimAEllis](https://github.com/TimAEllis): Add drop column support
|
||||
- **Fixed**: [#1139](https://github.com/groue/GRDB.swift/pull/1139) by [@groue](https://github.com/groue): Deal with authorization callbacks from more cursors
|
||||
- **Fixed**: [#1149](https://github.com/groue/GRDB.swift/pull/1149) by [@BB9z](https://github.com/BB9z): Fix typos
|
||||
|
||||
|
||||
## 5.18.0
|
||||
|
||||
Released January 9, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.17.0...v5.18.0)
|
||||
|
||||
- **New**: [#1075](https://github.com/groue/GRDB.swift/pull/1075) by [@mallman](https://github.com/mallman): Progress-reporting database backups
|
||||
- **New**: [#1129](https://github.com/groue/GRDB.swift/pull/1129) by [@groue](https://github.com/groue): Detached columns
|
||||
- **New**: [#1132](https://github.com/groue/GRDB.swift/pull/1132) by [@groue](https://github.com/groue): Bump custom SQLite builds v3.37.2
|
||||
- **New**: [#1133](https://github.com/groue/GRDB.swift/pull/1133) by [@groue](https://github.com/groue): Support for STRICT tables
|
||||
- **Fixed**: [#1120](https://github.com/groue/GRDB.swift/pull/1120) by [@jnross](https://github.com/jnross): Fix typos
|
||||
- **Fixed**: [#1121](https://github.com/groue/GRDB.swift/pull/1121) by [@byohay](https://github.com/byohay): Quote PROJECT_DIR and SRCROOT environment variables
|
||||
- **Fixed**: [#1128](https://github.com/groue/GRDB.swift/pull/1128) by [@groue](https://github.com/groue): Deal with authorization callbacks from cursors of FetchableRecord
|
||||
- **Documentation Update**: A new [Embedding SQL in Query Interface Requests](README.md#embedding-sql-in-query-interface-requests) chapter describes the ways to leverage your SQL skills and extend GRDB apis.
|
||||
|
||||
|
||||
## 5.17.0
|
||||
|
||||
Released December 14, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.16.0...v5.17.0)
|
||||
|
||||
- **New**: :star: [#1079](https://github.com/groue/GRDB.swift/pull/1079) by [@groue](https://github.com/groue): Async / Await
|
||||
- **New**: `DatabaseRegion(table: tableName)` is deprecated. Use `Table(tableName)` instead.
|
||||
- **New**: The `ABS` and `LENGTH` SQL functions are now available on association aggregates, through `abs(aggregate)` and `length(aggregate)`.
|
||||
- **New**: Support for the [`TOTAL` aggregate function](https://www.sqlite.org/lang_aggfunc.html#sumunc). You can use `total` in Swift, at all places `sum` is available.
|
||||
- **New**: `ValueObservation.removeDuplicates(by:)` with a closure argument.
|
||||
- **New**: Testing for the existence of an associated record with `TableAlias.exists` now supports associated views, and associated tables WITHOUT ROWID that have a compound primary key.
|
||||
- **Fixed**: `Database.primaryKey(_:)` throws when given the name of a view.
|
||||
- **Documentation Update**: :star: The [Concurrency Guide](Documentation/Concurrency.md) was updated for the new support for asynchronous Swift.
|
||||
- **Documentation Update**: :star: [GRDBAsyncDemo](Documentation/DemoApps/GRDBAsyncDemo/README.md) is a new SwiftUI demo app that uses the new async apis.
|
||||
- **Documentation Update**: A new FAQ gives hints for avoiding a [Mutation of captured var in concurrently-executing code](README.md##mutation-of-captured-var-in-concurrently-executing-code) compiler error.
|
||||
- **Documentation Update**: [#1107](https://github.com/groue/GRDB.swift/pull/1107) by [@tcwalther](https://github.com/tcwalther): Fix docstring for Database.create(index: ...)
|
||||
- **Documentation Update**: [#1110](https://github.com/groue/GRDB.swift/pull/1110) by [@maxhumber](https://github.com/maxhumber): Minor changes to a tip in the README
|
||||
|
||||
## 5.16.0
|
||||
|
||||
Released December 5, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.15.0...v5.16.0)
|
||||
|
||||
- **New**: [#1106](https://github.com/groue/GRDB.swift/pull/1106) by [@groue](https://github.com/groue): Sugar for fetching only a few columns of associated records
|
||||
- **Documentation Update**: The [Joining And Prefetching Associated Records](Documentation/AssociationsBasics.md#joining-and-prefetching-associated-records) chapter was fully rewritten. The joining methods `including(required:)` and others are much more detailed, with an exploration of frequent use cases.
|
||||
- **Documentation Update**: The [Joining And Prefetching Associated Records](Documentation/AssociationsBasics.md#joining-and-prefetching-associated-records) chapter introduces the new `annotated(withRequired:)` and `annotated(withOptional:)` joining methods.
|
||||
- **Documentation Update**: The new [Choosing a Joining Method Given the Shape of the Decoded Type](Documentation/AssociationsBasics.md#choosing-a-joining-method-given-the-shape-of-the-decoded-type) chapter helps choosing a joining method, given the shape of the fetched data.
|
||||
|
||||
## 5.15.0
|
||||
|
||||
Released December 2, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.14.0...v5.15.0)
|
||||
|
||||
- **Fixed**: `ValueObservation` now always fetches fresh values in an isolated fashion. This prevents all risks of fetching inconsistent data even if an external connection modifies the database.
|
||||
- **New**: `Table` now conforms to `DatabaseRegionConvertible`. You can write `DatabaseRegionObservation(tracking: Table("player"))`.
|
||||
- **New**: [#1102](https://github.com/groue/GRDB.swift/pull/1102) by [@groue](https://github.com/groue): Explicit tracked region for ValueObservation
|
||||
|
||||
## 5.14.0
|
||||
|
||||
Released November 25, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.13.0...v5.14.0)
|
||||
@@ -395,7 +547,7 @@ Released September 27, 2020 • [diff](https://github.com/groue/GRDB.swift/co
|
||||
|
||||
Released September 20, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.11...v5.0.0)
|
||||
|
||||
- **Fixed**: [#838](https://github.com/groue/GRDB.swift/issues/838): Have indexed colums inherit the `ifNotExists` flag from table creation.
|
||||
- **Fixed**: [#838](https://github.com/groue/GRDB.swift/issues/838): Have indexed columns inherit the `ifNotExists` flag from table creation.
|
||||
|
||||
|
||||
## 5.0.0-beta.11
|
||||
@@ -546,7 +698,7 @@ Released May 2, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v
|
||||
|
||||
GRDB 5 is a release focused on **Swift 5.2**, and **removing technical debt**.
|
||||
|
||||
There are breaking changes, though as few as possible. They open the door for future library improvements. And they have GRDB, [GRDBCombine](http://github.com/groue/GRDBCombine), and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) offer a common behavior.
|
||||
There are breaking changes, though as few as possible. They open the door for future library improvements. And they have GRDB, [GRDBCombine](https://github.com/groue/GRDBCombine), and [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB) offer a common behavior.
|
||||
|
||||
New features include support for SQL subqueries, and a simplified handling of database errors. The most demanding users will also find it easier to switch between the system SQLite, SQLCipher, and custom SQLite builds.
|
||||
|
||||
@@ -2264,7 +2416,7 @@ It comes with new features, but also a few breaking changes, and a set of update
|
||||
- `DatabaseMigrator.appliedMigrations(in:)` returns the set of applied migrations identifiers in a database ([#321](https://github.com/groue/GRDB.swift/pull/321)).
|
||||
- `Database.isSQLiteInternalTable(_:)` returns whether a table name is an internal SQLite table ([#321](https://github.com/groue/GRDB.swift/pull/321)).
|
||||
- `Database.isGRDBInternalTable(_:)` returns whether a table name is an internal GRDB table ([#321](https://github.com/groue/GRDB.swift/pull/321)).
|
||||
- Upgrade custom SQLite builds to [v3.23.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Upgrade custom SQLite builds to [v3.23.0](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Improve Row descriptions ([#331](https://github.com/groue/GRDB.swift/pull/331)).
|
||||
- Request derivation protocols ([#329](https://github.com/groue/GRDB.swift/pull/329)).
|
||||
- Preliminary Linux support for the main framework ([#354](https://github.com/groue/GRDB.swift/pull/354)).
|
||||
@@ -2449,7 +2601,7 @@ Released January 29, 2018 • [diff](https://github.com/groue/GRDB.swift/comp
|
||||
|
||||
**New**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.22.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Upgrade custom SQLite builds to [v3.22.0](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- The FTS5 full-text search engine has been enhanced with [initial token queries](https://sqlite.org/fts5.html#carrotq), and FTS5Pattern has gained a new initializer: `FTS5Pattern(matchingPrefixPhrase:)`
|
||||
- The `Cursor` protocol is extended with more methods inspired by the standard Sequence protocol: `drop(while:)`, `dropFirst()`, `dropFirst(_:)`, `dropLast()`, `dropLast(_:)`, `joined(separator:)`, `prefix(_:)`, `max()`, `max(by:)`, `min()`, `min(by:)`, `prefix(while:)`, `reduce(into:_:)`, `suffix(_:)`,
|
||||
|
||||
@@ -2503,7 +2655,7 @@ Released January 18, 2018 • [diff](https://github.com/groue/GRDB.swift/comp
|
||||
- `TransactionObserver.stopObservingDatabaseChangesUntilNextTransaction()` allows transaction observers to stop observing the database for the remaining extent of a transaction.
|
||||
- GRDB no longer prevents the [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt) when no transaction observers are interested in deleted rows.
|
||||
- FetchedRecordsController now avoids checking for changes in untracked rowIds.
|
||||
- `DatabaseRegion` is a new public type that helps transaction observers recognize impactful database changes. This type is not documented in the main documentation. For more information, see [DatabaseRegion reference](http://groue.github.io/GRDB.swift/docs/2.6/Structs/DatabaseRegion.html), and look at [FetchedRecordsController implementation](https://github.com/groue/GRDB.swift/blob/master/GRDB/Record/FetchedRecordsController.swift).
|
||||
- `DatabaseRegion` is a new public type that helps transaction observers recognize impactful database changes. This type is not documented in the main documentation. For more information, see [DatabaseRegion reference](https://groue.github.io/GRDB.swift/docs/2.6/Structs/DatabaseRegion.html), and look at [FetchedRecordsController implementation](https://github.com/groue/GRDB.swift/blob/master/GRDB/Record/FetchedRecordsController.swift).
|
||||
- `TransactionObserver` protocol provides default implementations for rarely used callbacks.
|
||||
|
||||
- `Row` adopts RandomAccessCollection
|
||||
@@ -2590,7 +2742,7 @@ Released January 11, 2018 • [diff](https://github.com/groue/GRDB.swift/comp
|
||||
let player = try request.fetchOne(db) // Player?
|
||||
```
|
||||
|
||||
This feature has been introduced in order to ease the use of [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB):
|
||||
This feature has been introduced in order to ease the use of [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB):
|
||||
|
||||
```swift
|
||||
// New
|
||||
@@ -2659,7 +2811,7 @@ Released December 3, 2017 • [diff](https://github.com/groue/GRDB.swift/comp
|
||||
}
|
||||
```
|
||||
|
||||
- [#281](https://github.com/groue/GRDB.swift/pull/280): The `Database.dropFTS4SynchronizationTriggers` & `Database.dropFTS5SynchronizationTriggers` method help cleaning up synchronized full-text table ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#deleting-synchronized-full-text-tables))
|
||||
- [#281](https://github.com/groue/GRDB.swift/pull/281): The `Database.dropFTS4SynchronizationTriggers` & `Database.dropFTS5SynchronizationTriggers` method help cleaning up synchronized full-text table ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#deleting-synchronized-full-text-tables))
|
||||
|
||||
**Breaking Change**
|
||||
|
||||
@@ -2690,7 +2842,7 @@ Released November 5, 2017 • [diff](https://github.com/groue/GRDB.swift/comp
|
||||
|
||||
**New**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.21.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Upgrade custom SQLite builds to [v3.21.0](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
|
||||
|
||||
## 2.2.0
|
||||
@@ -2723,7 +2875,7 @@ Released October 24, 2017 • [diff](https://github.com/groue/GRDB.swift/comp
|
||||
### New
|
||||
|
||||
- GRDBCipher can now build from command line ([groue/sqlcipher/pull/1](https://github.com/groue/sqlcipher/pull/1) by [Darren Clark](https://github.com/darrenclark))
|
||||
- Upgrade custom SQLite builds to [v3.20.1](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Upgrade custom SQLite builds to [v3.20.1](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- The new method `Request.asSQLRequest` allows to inspect the sql and arguments of any request:
|
||||
|
||||
```swift
|
||||
@@ -2867,7 +3019,7 @@ Released September 16, 2017 • [diff](https://github.com/groue/GRDB.swift/co
|
||||
|
||||
### New
|
||||
|
||||
New features have been added in order to plug a few holes and support the [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) and [GRDBObjc](http://github.com/groue/GRDBObjc) companion projects:
|
||||
New features have been added in order to plug a few holes and support the [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB) and [GRDBObjc](https://github.com/groue/GRDBObjc) companion projects:
|
||||
|
||||
- Persistable records can export themselves as dictionaries:
|
||||
|
||||
@@ -3130,7 +3282,7 @@ Released August 18, 2017 • [diff](https://github.com/groue/GRDB.swift/compa
|
||||
|
||||
**New**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.20.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Upgrade custom SQLite builds to [v3.20.0](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Complete support for all signed and unsigned integer types: from Int8 toUInt64, all integers can be stored and loaded from the database.
|
||||
|
||||
**API diff**
|
||||
@@ -3161,7 +3313,7 @@ Released July 19, 2017 • [diff](https://github.com/groue/GRDB.swift/compare
|
||||
|
||||
**Fixed**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.19.3](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Upgrade custom SQLite builds to [v3.19.3](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- The [Query Interface](https://github.com/groue/GRDB.swift/#the-query-interface) now generates `IS NULL` SQL snippets for comparisons with `DatabaseValue.null`:
|
||||
|
||||
```swift
|
||||
@@ -3475,7 +3627,7 @@ 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 custom SQLite builds to [v3.19.2](https://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)
|
||||
|
||||
@@ -3565,7 +3717,7 @@ Released April 6, 2017
|
||||
|
||||
**New**
|
||||
|
||||
- `DatabaseWriter.availableDatabaseConnection` allows reentrant uses of GRDB, and improves support for [reactive](http://reactivex.io) programming.
|
||||
- `DatabaseWriter.availableDatabaseConnection` allows reentrant uses of GRDB, and improves support for [reactive](https://reactivex.io) programming.
|
||||
|
||||
|
||||
**Breaking Changes**
|
||||
@@ -3580,8 +3732,8 @@ 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:
|
||||
- Upgrade custom SQLite builds to [v3.18.0](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Support for [reactive](https://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.
|
||||
@@ -3675,7 +3827,7 @@ Released January 10, 2017
|
||||
|
||||
- `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)).
|
||||
- Upgrade custom SQLite builds to [v3.16.2](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
|
||||
**Breaking Changes**
|
||||
|
||||
@@ -3841,7 +3993,7 @@ Released December 4, 2016
|
||||
|
||||
**New**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.15.2](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Upgrade custom SQLite builds to [v3.15.2](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
|
||||
|
||||
## 0.92.1
|
||||
@@ -4078,7 +4230,7 @@ Released November 5, 2016
|
||||
|
||||
**New**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.15.1](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Upgrade custom SQLite builds to [v3.15.1](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
|
||||
**Fixed**
|
||||
|
||||
@@ -4166,7 +4318,7 @@ Released October 16, 2016
|
||||
}
|
||||
```
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.15.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Upgrade custom SQLite builds to [v3.15.0](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
|
||||
|
||||
**Breaking Change**
|
||||
@@ -4219,7 +4371,7 @@ Released October 8, 2016
|
||||
try Book.deleteOne(db, key: 1)
|
||||
```
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.14.2](http://www.sqlite.org/changes.html).
|
||||
- Upgrade custom SQLite builds to [v3.14.2](https://www.sqlite.org/changes.html).
|
||||
|
||||
**Breaking Changes**
|
||||
|
||||
@@ -4268,7 +4420,7 @@ Released September 16, 2016
|
||||
|
||||
**New**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.14.1](http://www.sqlite.org/changes.html).
|
||||
- Upgrade custom SQLite builds to [v3.14.1](https://www.sqlite.org/changes.html).
|
||||
|
||||
**Fixed**
|
||||
|
||||
@@ -5355,7 +5507,7 @@ Released April 5, 2016
|
||||
|
||||
**New**
|
||||
|
||||
- The new framework GRDBCipher embeds [SQLCipher](http://sqlcipher.net) and can encrypt databases ([documentation](https://github.com/groue/GRDB.swift#encryption))
|
||||
- The new framework GRDBCipher embeds [SQLCipher](https://www.zetetic.net/sqlcipher/) and can encrypt databases ([documentation](https://github.com/groue/GRDB.swift#encryption))
|
||||
- `DatabaseQueue.path` and `DatabasePool.path` give the path to the database.
|
||||
|
||||
**Fixed**
|
||||
@@ -5857,7 +6009,7 @@ Record ([documentation](https://github.com/groue/GRDB.swift#record-class)):
|
||||
- `Record.reload()` has been removed. You have to provide your own implementation, should you need reloading.
|
||||
- `Record.init(row: Row)` has been renamed `Record.init(_ row: Row)` (unlabelled row argument).
|
||||
- `Record.updateFromRow()` has been removed. Override `init(_ row: Row)` instead.
|
||||
- `Record.didInsertWithRowID(_:forColumn:)` should be overriden by Record subclasses that are interested in their row ids.
|
||||
- `Record.didInsertWithRowID(_:forColumn:)` should be overridden by Record subclasses that are interested in their row ids.
|
||||
- `Record.databaseEdited` has been renamed `hasPersistentChangedValues`.
|
||||
- `Record.databaseChanges` has been renamed `persistentChangedValues` and now returns `[String: DatabaseValue?]`, the dictionary of old values for changed columns.
|
||||
|
||||
@@ -6305,11 +6457,11 @@ Released August 18, 2015
|
||||
|
||||
- `RowModel.exists(db)` returns whether a row model has a matching row in the database.
|
||||
- `Statement.arguments` property gains a public setter.
|
||||
- `Database.executeMultiStatement(sql)` can execute several SQL statements separated by a semi-colon ([#6](http://github.com/groue/GRDB.swift/pull/6) by [peter-ss](https://github.com/peter-ss))
|
||||
- `Database.executeMultiStatement(sql)` can execute several SQL statements separated by a semi-colon ([#6](https://github.com/groue/GRDB.swift/pull/6) by [peter-ss](https://github.com/peter-ss))
|
||||
|
||||
**Breaking changes**
|
||||
|
||||
- `UpdateStatement.Changes` has been renamed `DatabaseChanges` ([#6](http://github.com/groue/GRDB.swift/pull/6) by [peter-ss](https://github.com/peter-ss)).
|
||||
- `UpdateStatement.Changes` has been renamed `DatabaseChanges` ([#6](https://github.com/groue/GRDB.swift/pull/6) by [peter-ss](https://github.com/peter-ss)).
|
||||
|
||||
|
||||
## 0.7.0
|
||||
|
||||
@@ -1,328 +1,99 @@
|
||||
Contributing to GRDB
|
||||
====================
|
||||
|
||||
**Thank you for coming!**
|
||||
|
||||
This guide is a set of tips and guidelines for contributing to the GitHub repository [groue/GRDB.swift](https://github.com/groue/GRDB.swift).
|
||||
|
||||
- [Report Bugs]
|
||||
- [Ask Questions]
|
||||
- [Suggest an Enhancement]
|
||||
- [Submit a Pull Request]
|
||||
- [Sponsoring and Professional Support]
|
||||
- [Suggested Contributions]
|
||||
- [Non-Goals]
|
||||
|
||||
|
||||
### Report Bugs
|
||||
|
||||
Please make sure the bug is not already reported by searching existing [issues](https://github.com/groue/GRDB.swift/issues).
|
||||
|
||||
If you're unable to find an existing issue addressing the problem, [open a new one](https://github.com/groue/GRDB.swift/issues/new). Be sure to include a title and clear description, as much relevant information as possible, and a code sample or an executable test case demonstrating the expected behavior that is not occurring.
|
||||
|
||||
|
||||
### Ask Questions
|
||||
|
||||
The information you are looking for is maybe already available. Check out:
|
||||
|
||||
- the [FAQ](README.md#faq)
|
||||
- the [general documentation](README.md#documentation)
|
||||
- the [answered questions](https://github.com/groue/GRDB.swift/issues?utf8=✓&q=label%3Aquestion+)
|
||||
|
||||
If not, your questions are welcome in the [GRDB forums](https://forums.swift.org/c/related-projects/grdb), or in a new [GitHub issue](https://github.com/groue/GRDB.swift/issues/new).
|
||||
|
||||
|
||||
### Suggest an Enhancement
|
||||
|
||||
Your idea may already be listed in [Suggested Contributions], waiting for someone to pick it up.
|
||||
|
||||
If not, contact [@groue](http://twitter.com/groue) on Twitter, or [open a new issue](https://github.com/groue/GRDB.swift/issues/new).
|
||||
|
||||
|
||||
### Submit a Pull Request
|
||||
|
||||
Discuss your idea first, so that your changes have a good chance of being merged in.
|
||||
|
||||
Submit your pull request against the `development` branch.
|
||||
|
||||
Pull requests that include tests for modified and new functionalities, inline documentation, and relevant updates to the main README.md are merged faster, because you won't have to wait for somebody else to complete your contribution.
|
||||
|
||||
|
||||
### Sponsoring and Professional Support
|
||||
|
||||
GRDB is free. It is openly developed by its contributors, on their free time, according to their will, needs, and availability. It is not controlled by any company.
|
||||
|
||||
When you have specific development or support needs, and are willing to financially contribute to GRDB, please send an email to [Gwendal Roué](mailto:gr@pierlis.com) so that we can enter a regular business relationship through the [Pierlis](http://pierlis.com/) company, based in Paris, France.
|
||||
|
||||
|
||||
## Suggested Contributions
|
||||
|
||||
You'll find below various ideas for enhancing and extending GRDB, in various areas. Your ideas can be added to this list: [Suggest an Enhancement].
|
||||
|
||||
Legend:
|
||||
|
||||
- :baby: **Starter Task**: get familiar with GRDB internals
|
||||
- :muscle: **Hard**: there are implementation challenges
|
||||
- :pencil: **Documentation**
|
||||
- :fire: **Experimental**: let's invent the future!
|
||||
- :bowtie: **Public API Challenge**: we'll need a very good public API
|
||||
- :hammer: **Tooling**: GRDB and its environment
|
||||
- :question: **Unknown Difficulty**
|
||||
|
||||
The ideas, in alphabetical order:
|
||||
|
||||
- [Associations]
|
||||
- [CloudKit]
|
||||
- [Concurrency]
|
||||
- [Custom FTS5 Auxiliary Functions]
|
||||
- [Date and Time Functions]
|
||||
- [Decode NSDecimalNumber from Text Columns]
|
||||
- [Documentation]
|
||||
- [Full Text Search Demo Application]
|
||||
- [JSON]
|
||||
- [Linux]
|
||||
- [More SQL Generation]
|
||||
- [SQL Console in the Debugger]
|
||||
- [SQLCipher in a Shared App Container]
|
||||
- [Typed Expressions]
|
||||
|
||||
|
||||
### Associations
|
||||
|
||||
:bowtie: Public API Challenge :muscle: Hard :fire: Experimental
|
||||
|
||||
Associations can be enhanced in several ways. See the "Known Issues" chapter of the [Associations Guide](Documentation/AssociationsBasics.md)
|
||||
|
||||
|
||||
### CloudKit
|
||||
|
||||
:bowtie: Public API Challenge :question: Unknown Difficulty :fire: Experimental
|
||||
|
||||
Integration with [CloudKit](https://developer.apple.com/icloud/cloudkit/) is a rich, interesting, and useful topic.
|
||||
|
||||
It is likely that CloudKit support would exist in a separate companion library.
|
||||
|
||||
Starting points:
|
||||
|
||||
- [caiyue1993/IceCream](https://github.com/caiyue1993/IceCream)
|
||||
- [mentrena/SyncKit](https://github.com/mentrena/SyncKit)
|
||||
- [nofelmahmood/Seam](https://github.com/nofelmahmood/Seam)
|
||||
- [Sorix/CloudCore](https://github.com/Sorix/CloudCore)
|
||||
- [Synchronizing data with CloudKit](https://medium.com/@guilhermerambo/synchronizing-data-with-cloudkit-94c6246a3fda)
|
||||
- WWDC CloudKit sessions, including [CloudKit Best Practices](https://developer.apple.com/videos/play/wwdc2016/231/)
|
||||
|
||||
|
||||
### Concurrency
|
||||
|
||||
:bowtie: Public API Challenge :muscle: Hard :pencil: Documentation
|
||||
|
||||
GRDB has a strong focus on safe concurrency. Not only safe as "does not crash", but safe as "actively protects your application data". The topic is discussed in (too) many places:
|
||||
|
||||
- [Concurrency Guide](Documentation/Concurrency.md)
|
||||
- [Why Adopt GRDB?](https://github.com/groue/GRDB.swift/blob/master/Documentation/WhyAdoptGRDB.md#strong-and-clear-multi-threading-guarantees)
|
||||
- [Four different ways to handle SQLite concurrency](https://medium.com/@gwendal.roue/four-different-ways-to-handle-sqlite-concurrency-db3bcc74d00e)
|
||||
- [Good Practices for Designing Record Types](https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md#fetch-in-time)
|
||||
- [Comparison between GRDB and Core Data concurrency](https://github.com/groue/GRDB.swift/issues/405)
|
||||
|
||||
Despite this abundant documention, I regularly meet developers who don't think about eventual multi-threading gotchas, and don't design their application against them.
|
||||
|
||||
This can be explained:
|
||||
|
||||
- Some developers disregard potential multi-threading bugs such as data races, even if the fix is "easy". Such bugs may never happen during the development of an application. They may only impact a few users in production. It is always easier not to think about them.
|
||||
|
||||
- Databases are often seen as plain CRUD tools, and some developers are not familiar with topics like isolation or transactions. This is especially true for developers who have experience in a managed ORM such as Core Data or Realm, or web frameworks like Rails or Django: switching to an unmanaged relational database is not an easy task.
|
||||
|
||||
- Not all applications need to be multi-threaded.
|
||||
|
||||
And this creates improvement opportunities:
|
||||
|
||||
- Better documentation of GRDB concurrency
|
||||
|
||||
- The introduction of an "ultra-safe" concurrency mode. Maybe something that restricts all database accesses to the main thread, like [FCModel](https://github.com/marcoarment/FCModel). Maybe in a separate companion library.
|
||||
|
||||
|
||||
### Custom FTS5 Auxiliary Functions
|
||||
|
||||
:question: Unknown Difficulty
|
||||
|
||||
The SQLite documentation provides [this description](https://www.sqlite.org/fts5.html) of FTS5 auxiliary functions:
|
||||
|
||||
> An application may use FTS5 auxiliary functions to retrieve extra information regarding the matched row. For example, an auxiliary function may be used to retrieve a copy of a column value for a matched row with all instances of the matched term surrounded by html <b></b> tags.
|
||||
|
||||
Applications can define their own [custom FTS5 auxiliary functions](https://www.sqlite.org/fts5.html#custom_auxiliary_functions) with SQLite, but GRDB does not yet provide any Swift API for that.
|
||||
|
||||
See issue [#421](https://github.com/groue/GRDB.swift/issues/421) for more information.
|
||||
|
||||
|
||||
### Date and Time Functions
|
||||
|
||||
:baby: Starter Task
|
||||
|
||||
Believe it or not, no one has ever asked support for SQLite [Date And Time Functions](https://www.sqlite.org/lang_datefunc.html). There is surely room for a nice Swift API that makes them available.
|
||||
|
||||
For more ideas, see:
|
||||
|
||||
- [SQLite Core Functions](https://www.sqlite.org/lang_corefunc.html)
|
||||
- [SQLite Aggregate Functions](https://www.sqlite.org/lang_aggfunc.html)
|
||||
- [SQLite JSON functions](https://www.sqlite.org/json1.html) and [JSON], below.
|
||||
|
||||
Functions are defined in [GRDB/QueryInterface/Support/SQLFunctions.swift](https://github.com/groue/GRDB.swift/blob/master/GRDB/QueryInterface/Support/SQLFunctions.swift).
|
||||
|
||||
|
||||
### Decode NSDecimalNumber from Text Columns
|
||||
|
||||
:baby: Starter Task
|
||||
|
||||
NSDecimalNumber currently only decodes integer and float decimal values. It would be nice if NSDecimalNumber would decode text values as well:
|
||||
|
||||
```swift
|
||||
let number = try NSDecimalNumber.fetchOne(db, "SELECT '12.3'")!
|
||||
print(number) // prints 12.3
|
||||
```
|
||||
|
||||
NSNumber and NSDecimalNumber support is found in [GRDB/Core/Support/Foundation/NSNumber.swift](https://github.com/groue/GRDB.swift/blob/master/GRDB/Core/Support/Foundation/NSNumber.swift)
|
||||
|
||||
|
||||
### Documentation
|
||||
|
||||
:baby: Starter Task :pencil: Documentation
|
||||
|
||||
General documentation can always be improved so that it reaches its goal: helping developers building applications.
|
||||
|
||||
- English: the documentation has mostly been written by [@groue](http://github.com/groue) who is not a native English speaker.
|
||||
- Clarity: any chapter that is not crystal clear should be enhanced.
|
||||
- Audience: documentation should talk to several populations of developers, from beginners who need positive guidance, to SQLite experts who need to build trust.
|
||||
- Typos
|
||||
- Inaccuracies
|
||||
- etc.
|
||||
|
||||
Inline documentation, the one which is embedded right into the source code and is displayed by Xcode when one alt-clicks an identifier, deserves the same care.
|
||||
|
||||
If you are a good writer, your help will be very warmly welcomed.
|
||||
|
||||
|
||||
### Full Text Search Demo Application
|
||||
|
||||
:baby: Starter Task :pencil: Documentation
|
||||
|
||||
There exists a GRDB demo app for the FTS5 full-text engine: [WWDCCompanion](https://github.com/groue/WWDCCompanion).
|
||||
|
||||
This application downloads the transcripts of WWDC sessions, and lets its user type keywords and find matching sessions, sorted by relevance.
|
||||
|
||||
The problem is that this demo app breaks every year :sweat_smile:
|
||||
|
||||
We'd need instead to index a stable corpus, in order to ease the maintenance of this demo app.
|
||||
|
||||
|
||||
### JSON
|
||||
|
||||
:bowtie: Public API Challenge :baby: Starter Task
|
||||
|
||||
[Codable Records] are granted with automatic JSON encoding and decoding of their complex properties. But there is still room for improvements. For example, could we put the [SQLite JSON1 extension](https://www.sqlite.org/json1.html) to some good use?
|
||||
|
||||
|
||||
### Linux
|
||||
|
||||
:muscle: Hard :hammer: Tooling
|
||||
|
||||
Swift on Linux is currently focused on the server (Vapor, Perfect, Kitura). While general server support is a [non-goal](#non-goals) of GRDB, there exists read-only servers, and Linux GUI applications, too. Linux is thus a desired platform.
|
||||
|
||||
|
||||
### More SQL Generation
|
||||
|
||||
:bowtie: Public API Challenge :question: Unknown Difficulty
|
||||
|
||||
There are several SQLite features that GRDB could natively support:
|
||||
|
||||
- [ALTER TABLE ... RENAME COLUMN ... TO ...](https://www.sqlite.org/lang_altertable.html)
|
||||
- [ATTACH DATABASE](https://www.sqlite.org/lang_attach.html)
|
||||
- [UPSERT](https://www.sqlite.org/lang_UPSERT.html)
|
||||
- [INSERT INTO ... SELECT ...](https://www.sqlite.org/lang_insert.html)
|
||||
- [WITH RECURSIVE ...](https://www.sqlite.org/lang_with.html)
|
||||
- [RTree](https://sqlite.org/rtree.html)
|
||||
- [Windows Functions](https://www.sqlite.org/windowfunctions.html)
|
||||
- [More ideas](https://www.sqlite.org/lang.html)
|
||||
|
||||
See [issue #575](https://github.com/groue/GRDB.swift/issues/575) for more information and guidance about the implementation of extra table alterations.
|
||||
|
||||
|
||||
### SQL Console in the Debugger
|
||||
|
||||
:question: Unknown Difficulty :hammer: Tooling
|
||||
|
||||
Sometimes one needs, in lldb, a console similar to the [Command Line Shell For SQLite](https://www.sqlite.org/cli.html).
|
||||
|
||||
|
||||
### SQLCipher in a Shared App Container
|
||||
|
||||
:question: Unknown Difficulty
|
||||
|
||||
See issue [#302](https://github.com/groue/GRDB.swift/issues/302).
|
||||
|
||||
|
||||
### Typed Expressions
|
||||
|
||||
:bowtie: Public API Challenge :muscle: Hard :fire: Experimental
|
||||
|
||||
The compiler currently does not spot type mistakes in query interface requests:
|
||||
|
||||
```swift
|
||||
Player.filter(Column("name") == "Arthur") // OK
|
||||
Player.filter(Column("name") == 1) // Sure
|
||||
Player.filter(Column("name") == Date()) // Legit
|
||||
```
|
||||
|
||||
This weak typing also prevents natural-looking Swift code from producing the expected results:
|
||||
|
||||
```swift
|
||||
// Performs arithmetic additions instead of string concatenation
|
||||
Player.select(Column("firstName") + " " + Column("lastName"))
|
||||
```
|
||||
|
||||
It would be interesting to see what typed expressions could bring to GRDB.
|
||||
|
||||
|
||||
## Non-Goals
|
||||
|
||||
GRDB is a "toolkit for SQLite databases, with a focus on application development".
|
||||
|
||||
This definition is the reason why GRDB can provide key features such as sharp multi-threading, database observation, and first-class support for raw SQL.
|
||||
|
||||
Features that blur this focus are non-goals:
|
||||
|
||||
- Support for MySQL, PostgreSQL, or other database engines
|
||||
- Support for Servers
|
||||
|
||||
|
||||
[Ask Questions]: #ask-questions
|
||||
[Associations]: #associations
|
||||
[CloudKit]: #cloudkit
|
||||
[Codable Records]: README.md#codable-records
|
||||
[Custom FTS5 Auxiliary Functions]: #custom-fts5-auxiliary-functions
|
||||
[Database Observation]: #database-observation
|
||||
[Date and Time Functions]: #date-and-time-functions
|
||||
[Decode NSDecimalNumber from Text Columns]: #decode-nsdecimalnumber-from-text-columns
|
||||
[Documentation]: #documentation
|
||||
[Full Text Search Demo Application]: #full-text-search-demo-application
|
||||
[How is the Library Organized?]: Documentation/LibraryOrganization.md
|
||||
[How is the Repository Organized?]: Documentation/RepositoryOrganization.md
|
||||
[JSON]: #json
|
||||
[Linux]: #linux
|
||||
[More SQL Generation]: #more-sql-generation
|
||||
[Records: Splitting Database Encoding from Ability to Write in the Database]: #records-splitting-database-encoding-from-ability-to-write-in-the-database
|
||||
[Non-Goals]: #non-goals
|
||||
[Report Bugs]: #report-bugs
|
||||
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
|
||||
[Concurrency]: Documentation/Concurrency.md
|
||||
[Sponsoring and Professional Support]: #sponsoring-and-professional-support
|
||||
[SQL Console in the Debugger]: #sql-console-in-the-debugger
|
||||
[SQLCipher in a Shared App Container]: #sqlcipher-in-a-shared-app-container
|
||||
[Submit a Pull Request]: #submit-a-pull-request
|
||||
[Suggest an Enhancement]: #suggest-an-enhancement
|
||||
[Suggested Contributions]: #suggested-contributions
|
||||
[Typed Expressions]: #typed-expressions
|
||||
[persistence methods]: README.md#persistence-methods
|
||||
[PersistableRecord]: README.md#persistablerecord-protocol
|
||||
[Record Comparison]: README.md#record-comparison
|
||||
[Requesting Associated Records]: Documentation/AssociationsBasics.md#requesting-associated-records
|
||||
[ValueObservation]: README.md#valueobservation
|
||||
How you can Contribute
|
||||
======================
|
||||
|
||||
- [Contribute to the GRDB codebase]
|
||||
- [Answer issues and contribute to discussions]
|
||||
- [Financial support and sponsoring]
|
||||
|
||||
## Contribute to the GRDB codebase
|
||||
|
||||
1. **Install** the following tools:
|
||||
|
||||
- For running tests:
|
||||
- Ruby
|
||||
- [CocoaPods](https://cocoapods.org) (gem)
|
||||
- [xcpretty](https://github.com/xcpretty/xcpretty) (gem)
|
||||
- For contributing code:
|
||||
- [Swiftlint](https://github.com/realm/SwiftLint) (present in the `$PATH` or in `/opt/homebrew/bin/`)
|
||||
- For generating documentation:
|
||||
- [Jazzy](https://github.com/realm/jazzy) (gem)
|
||||
|
||||
2. **Clone the `development` branch on your machine.**
|
||||
|
||||
3. **Run `make SQLiteCustom` in the terminal**, at the root of the repository.
|
||||
|
||||
This step is not strictly necessary if you do not plan to work on custom SQLite builds. But it will avoid a lot of warnings in Xcode.
|
||||
|
||||
4. **Open `GRDB.xcworkspace`.** This workspace contains six projects:
|
||||
|
||||
- `GRDB.xcodeproj`: the project which contains the GRDB framework and test targets. The sources are organized in two groups:
|
||||
- `GRDB`: GRDB sources
|
||||
- `Tests`: GRDB tests
|
||||
- `GRDBCustom.xcodeproj`: the project which builds GRDB with a custom SQLite build.
|
||||
- `GRDBProfiling.xcodeproj`: a project which helps profiling GRDB with Instruments. No code here is really precious.
|
||||
- `GRDBDemoiOS.xcodeproj`, `GRDBCombineDemo.xcodeproj`, `GRDBAsyncDemo.xcodeproj`: the demo apps.
|
||||
|
||||
To work with `GRDBCustom.xcodeproj`:
|
||||
|
||||
- Make sure Xcode is installed in `/Applications`.
|
||||
- Run `make SQLiteCustom` in the terminal so that SQLite sources are present.
|
||||
|
||||
5. **Run tests**
|
||||
|
||||
You can run tests from `GRDB.xcworkspace`, after selecting your target (GRDBOSX, GRDBiOS, GRDBtvOS, from `GRDB.xcodeproj` or `GRDBCustom.xcodeproj`).
|
||||
|
||||
Before submitting a pull request, please run in the terminal:
|
||||
|
||||
```sh
|
||||
make smokeTest
|
||||
```
|
||||
|
||||
The "smoke tests" perform minimal testing of the system SQLite, SQLCipher, custom SQLite builds, as well as SPM integration.
|
||||
|
||||
Before a release, the full test suite must pass:
|
||||
|
||||
```sh
|
||||
make test
|
||||
```
|
||||
|
||||
The full test suite performs many more checks, such as the ability to archive an XCFramework, various installation methods, the demo apps, etc.
|
||||
|
||||
6. **Please respect the existing coding style**
|
||||
|
||||
- Get familiar with the [Swift API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/).
|
||||
- Spaces, not tabs.
|
||||
- Whitespace-only lines are not trimmed.
|
||||
- Documentation comments are hard-wrapped at column 80 (Xcode > Preferences > Text Editing > Display > [X] Page guide at column: 80).
|
||||
- No Swiftlint warning after a build.
|
||||
|
||||
|
||||
7. **Please provide documentation for your changes**
|
||||
|
||||
GRDB documentation is provided as reference (inline doc comments starting with `///`, see [Documentation Comment Syntax](https://github.com/apple/swift/blob/main/docs/DocumentationComments.md)), and guides ([README.md](README.md) and the [Documentation](Documentation) folder).
|
||||
|
||||
GRDB is "documentation-driven", which means that nothing ships until it is supported by documentation that makes sense. Documentation makes sense when someone who is not you is able to figure out what is the purpose of your contribution, how to use it, and what are its eventual caveats and corner cases. When the documentation is hard to write, or reveals too many caveats, it is the sign that the api needs to be fixed.
|
||||
|
||||
8. **Open a pull request with your changes (targeting the `development` branch)!**
|
||||
|
||||
9. **If you are granted a push access to the repository**, check [ReleaseProcess.md](Documentation/ReleaseProcess.md) in order to publish a new GRDB version.
|
||||
|
||||
|
||||
## Answer issues and contribute to discussions
|
||||
|
||||
Answering [issues](https://github.com/groue/GRDB.swift/issues), participating in [discussions](https://github.com/groue/GRDB.swift/discussions) and in the [forum](https://forums.swift.org/c/related-projects/grdb/36) is a great way to help, get familiar with the library, and shape its direction.
|
||||
|
||||
|
||||
## Financial support and sponsoring
|
||||
|
||||
GRDB is free, and openly developed by its contributors, on their free time, according to their will, needs, and availability. It is not controlled by any company.
|
||||
|
||||
Support is free as well, as long as it happens publicly, and is available to everyone as well as internet search engines. This excludes the private channels of social networks, closed environments such as Slack, etc.
|
||||
|
||||
When you have specific development or support needs, please send an email to [Gwendal Roué](mailto:gr@pierlis.com) so that we can enter a regular business relationship through the [Pierlis](http://pierlis.com/) company, based in Paris, France.
|
||||
|
||||
You can also [sponsor @groue via GitHub](https://github.com/sponsors/groue).
|
||||
|
||||
|
||||
[Contribute to the GRDB codebase]: #contribute-to-the-grdb-codebase
|
||||
[Answer issues and contribute to discussions]: #answer-issues-and-contribute-to-discussions
|
||||
[Financial support and sponsoring]: #financial-support-and-sponsoring
|
||||
@@ -842,125 +842,512 @@ let novels = try author
|
||||
|
||||
## Joining And Prefetching Associated Records
|
||||
|
||||
**You build requests that involve several records with the following "joining methods":**
|
||||
You build requests that involve associations with one of the following "joining methods":
|
||||
|
||||
- `joining(optional: association)`
|
||||
- `joining(required: association)`
|
||||
- `including(optional: association)`
|
||||
- `including(required: association)`
|
||||
- `including(all: associationToMany)`
|
||||
- Prefetch associated records:
|
||||
- [`including(required:)`]
|
||||
- [`including(optional:)`]
|
||||
- [`including(all:)`]
|
||||
- Prefetch only a few columns of an associated record:
|
||||
- [`annotated(withRequired:)`]
|
||||
- [`annotated(withOptional:)`]
|
||||
- [`including(all:)`]
|
||||
- Join associated records without prefetching:
|
||||
- [`joining(required:)`]
|
||||
- [`joining(optional:)`]
|
||||
- [Choosing a Joining Method Given the Shape of the Decoded Type]
|
||||
|
||||
Before we describe them in detail, let's see a few requests they can build:
|
||||
### `including(required:)`
|
||||
|
||||
For example, fetch books along with their author:
|
||||
|
||||
```swift
|
||||
/// All authors with their respective books
|
||||
let request = Author
|
||||
.including(all: Author.books)
|
||||
|
||||
/// All authors with their awarded books
|
||||
let request = Author
|
||||
.including(all: Author.books.having(Book.awards.isEmpty == false))
|
||||
|
||||
/// All books with their respective author
|
||||
let request = Book
|
||||
.including(required: Book.author)
|
||||
|
||||
/// All books with their respective author, sorted by title
|
||||
let request = Book
|
||||
.including(required: Book.author)
|
||||
.order(Column("title"))
|
||||
|
||||
/// All books written by a French author
|
||||
let request = Book
|
||||
.joining(required: Book.author.filter(Column("countryCode") == "FR"))
|
||||
// SELECT book.*, author.*
|
||||
// FROM book
|
||||
// JOIN author ON author.id = book.authorId
|
||||
let request = Book.including(required: Book.author)
|
||||
```
|
||||
|
||||
The pattern is always the same: you start from a base request, that you extend with one of the joining methods.
|
||||
This method accepts any association. It has the base record fetched along with one associated record, which is "included" in the fetched results. When the associated record does not exist, records are not present in the fetched results: the associated record is "required".
|
||||
|
||||
**To choose the joining method you need, you ask yourself two questions:**
|
||||
**To fetch results from such a request**, you define a dedicated record type:
|
||||
|
||||
```swift
|
||||
// Fetch all books along with their author
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
var book: Book // The base record
|
||||
var author: Author // The required associated record
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.including(required: Book.author)
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
**The CodingKey for the `BookInfo.author` property must match the association key of the `Book.author` association.** The association key is, by default, the name of the associated database table. This can be configured with the association `forKey(_:)` method:
|
||||
|
||||
```swift
|
||||
struct Author: TableRecord {
|
||||
static let databaseTableName = "writer"
|
||||
}
|
||||
struct Book: TableRecord {
|
||||
// Replace the default "writer" association key with "author"
|
||||
static let author = belongsTo(Author.self).forKey("author")
|
||||
}
|
||||
|
||||
// Fetch all books along with their author
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
var book: Book
|
||||
var author: Author // Matches the "author" association key
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.including(required: Book.author)
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
**When you only need a few columns of the associated record**, you can define a partial type with one property per selected column of the associated record:
|
||||
|
||||
```swift
|
||||
// Fetch all books along with the name and country of their author
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
struct PartialAuthor: Decodable {
|
||||
var name: String
|
||||
var country: String
|
||||
}
|
||||
var book: Book
|
||||
var author: PartialAuthor
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.including(required: Book.author.select(Column("name"), Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
But if you'd rather avoid this extra partial type, prefer [`annotated(withRequired:)`]:
|
||||
|
||||
```swift
|
||||
// Fetch all books along with the country of their author
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
var book: Book
|
||||
var country: String
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withRequired: Book.author.select(Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
### `including(optional:)`
|
||||
|
||||
For example, fetch books along with their eventual author:
|
||||
|
||||
```swift
|
||||
// SELECT book.*, author.*
|
||||
// FROM book
|
||||
// LEFT JOIN author ON author.id = book.authorId
|
||||
let request = Book.including(optional: Book.author)
|
||||
```
|
||||
|
||||
This method accepts any association. It has the base record fetched along with one associated record, which is "included" in the fetched results. The associated record can be missing: it is "optional".
|
||||
|
||||
**To fetch results from such a request**, you define a dedicated record type:
|
||||
|
||||
```swift
|
||||
// Fetch all books along with their eventual author
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
var book: Book // The base record
|
||||
var author: Author? // The optional associated record
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.including(optional: Book.author)
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
**The CodingKey for the `BookInfo.author` property must match the association key of the `Book.author` association.** See [`including(required:)`] for more information.
|
||||
|
||||
**When you only need a few columns of the associated record**, you can define a partial type with one property per selected column of the associated record:
|
||||
|
||||
```swift
|
||||
// Fetch all books along with the name and country of their eventual author
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
struct PartialAuthor: Decodable {
|
||||
var name: String
|
||||
var country: String
|
||||
}
|
||||
var book: Book
|
||||
var author: PartialAuthor?
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.including(optional: Book.author.select(Column("name"), Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
But if you'd rather avoid this extra partial type, prefer [`annotated(withOptional:)`]:
|
||||
|
||||
```swift
|
||||
// Fetch all books along with the country of their eventual author
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
var book: Book
|
||||
var country: String?
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withOptional: Book.author.select(Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
### `including(all:)`
|
||||
|
||||
For example, fetch authors along with their books:
|
||||
|
||||
```swift
|
||||
// SELECT author.* FROM author
|
||||
// SELECT book.* FROM book WHERE authorId IN (...)
|
||||
let request = Author.including(all: Author.books)
|
||||
```
|
||||
|
||||
This method accepts any to-many association ([HasMany] or [HasManyThrough]). It has the base record fetched along with all its associated records, which are "included" in the fetched results.
|
||||
|
||||
**To fetch results from such a request**, you define a dedicated record type:
|
||||
|
||||
```swift
|
||||
// Fetch all authors along with their books
|
||||
struct AuthorInfo: Decodable, FetchableRecord {
|
||||
var author: Author // The base record
|
||||
var books: [Book] // A collection of associated records
|
||||
}
|
||||
let authorInfos = try Author
|
||||
.including(all: Author.books)
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
The associated records can be stored into an Array as in the above example, but also a Set, and generally speaking any decodable Swift collection.
|
||||
|
||||
**The CodingKey for the `AuthorInfo.books` property must match the association key of the `Author.books` association.** The association key is, by default, the pluralized name of the associated database table. This can be configured with the association `forKey(_:)` method:
|
||||
|
||||
```swift
|
||||
struct Book: TableRecord {
|
||||
static let databaseTableName = "publication"
|
||||
}
|
||||
struct Author: TableRecord {
|
||||
// Replace the default "publications" association key with "books"
|
||||
static let books = hasMany(Book.self).forKey("books")
|
||||
}
|
||||
|
||||
// Fetch all authors along with their books
|
||||
struct AuthorInfo: Decodable, FetchableRecord {
|
||||
var author: Author
|
||||
var books: [Book] // Matches the "books" association key
|
||||
}
|
||||
let authorInfos = try Author
|
||||
.including(all: Author.books)
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
**When you only need a few columns of the associated records**, you can define a partial type with one property per selected column of the associated record:
|
||||
|
||||
```swift
|
||||
// Fetch all authors along with the titles and years of their books
|
||||
struct AuthorInfo: Decodable, FetchableRecord {
|
||||
struct PartialBook: Decodable {
|
||||
var title: String
|
||||
var year: Int
|
||||
}
|
||||
var author: Author
|
||||
var books: [PartialBook]
|
||||
}
|
||||
let authorInfos = try Author
|
||||
.including(all: Author.books.select(Column("title"), Column("year")))
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
When you need a single column of the associated records, avoid the extra partial type, and instead use the association `forKey(_:)` method in order to match the name of the decoded property:
|
||||
|
||||
```swift
|
||||
// Fetch all authors along with the titles of their books
|
||||
struct AuthorInfo: Decodable, FetchableRecord {
|
||||
var author: Author
|
||||
var bookTitles: [String]
|
||||
}
|
||||
let authorInfos = try Author
|
||||
.including(all: Author.books
|
||||
.select(Column("title"))
|
||||
.forKey("bookTitles"))
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
### `annotated(withRequired:)`
|
||||
|
||||
For example, fetch books along with the name and country of their author:
|
||||
|
||||
```swift
|
||||
// SELECT book.*, author.name, author.country
|
||||
// FROM book
|
||||
// JOIN author ON author.id = book.authorId
|
||||
let request = Book.annotated(withRequired: Book.author.select(Column("name"), Column("country")))
|
||||
```
|
||||
|
||||
This method accepts any association. The base record is annotated with the selected columns of one associated record. When the associated record does not exist, records are not present in the fetched results: the associated record is "required".
|
||||
|
||||
**To fetch results from such a request**, you define a dedicated record type:
|
||||
|
||||
```swift
|
||||
// Fetch all books along with the name and country of their author
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
var book: Book // The base record
|
||||
var name: String // A column of the required associated record
|
||||
var country: String // A column of the required associated record
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withRequired: Book.author.select(Column("name"), Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
If the name of a column of the associated record is also the name of a column of the base record, rename the associated column with the column `forKey(_:)` method, and accordingly rename the property of the decoded record type:
|
||||
|
||||
```swift
|
||||
// Fetch all books along with the name of their author
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
var book: Book
|
||||
var authorName: String
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withRequired: Book.author.select(Column("name").forKey("authorName")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
### `annotated(withOptional:)`
|
||||
|
||||
For example, fetch books along with the name and country of their eventual author:
|
||||
|
||||
```swift
|
||||
// SELECT book.*, author.name, author.country
|
||||
// FROM book
|
||||
// LEFT JOIN author ON author.id = book.authorId
|
||||
let request = Book.annotated(withOptional: Book.author.select(Column("name"), Column("country")))
|
||||
```
|
||||
|
||||
This method accepts any association. The base record is annotated with the selected columns of one associated record. When the associated record does not exist, the columns of the associated record are NULL: the associated record is "optional".
|
||||
|
||||
**To fetch results from such a request**, you define a dedicated record type:
|
||||
|
||||
```swift
|
||||
// Fetch all books along with the name of their eventual author
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
var book: Book // The base record
|
||||
var name: String? // A column of the optional associated record
|
||||
var country: String? // A column of the optional associated record
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withOptional: Book.author.select(Column("name"), Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
If the name of a column of the associated record is also the name of a column of the base record, rename the associated column with the column `forKey(_:)` method, and accordingly rename the property of the decoded record type:
|
||||
|
||||
```swift
|
||||
// Fetch all books along with the name of their eventual author
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
var book: Book
|
||||
var authorName: String?
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withOptional: Book.author.select(Column("name").forKey("authorName")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
### `joining(required:)`
|
||||
|
||||
For example, fetch books by French authors:
|
||||
|
||||
```swift
|
||||
// SELECT book.*
|
||||
// FROM book
|
||||
// JOIN author ON author.id = book.authorId
|
||||
// AND author.country = 'France'
|
||||
let request = Book.joining(required: Book.author.filter(Column("country") == "France"))
|
||||
```
|
||||
|
||||
This method accepts any association. It has the base record "joined" with one associated record, which is not included in the fetched results. When the associated record does not exist, the base record is not present in the fetched results: the associated record is "required".
|
||||
|
||||
To fetch results from such a request, you do not need to define a dedicated record type:
|
||||
|
||||
```swift
|
||||
// Fetch all books by French authors
|
||||
let books = try Book
|
||||
.joining(required: Book.author.filter(Column("country") == "France"))
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
### `joining(optional:)`
|
||||
|
||||
```swift
|
||||
// SELECT book.*
|
||||
// FROM book
|
||||
// LEFT JOIN author ON author.id = book.authorId
|
||||
let request = Book.joining(optional: Book.author)
|
||||
```
|
||||
|
||||
This method accepts any association. It has the base record "joined" with one associated record, which is not included in the fetched results. The associated record can be missing: it is "optional".
|
||||
|
||||
This method has no observable effect unless the associated record is used in a way or another. We'll see examples later in this documentation.
|
||||
|
||||
|
||||
### Choosing a Joining Method Given the Shape of the Decoded Type
|
||||
|
||||
In the description of the [joining methods] above, we have seen that you need to define dedicated record types in order to prefetch associated records. Each joining method needs a dedicated record type that has a specific shape.
|
||||
|
||||
In this chapter, we take the reversed perspective. We list various shapes of decoded record types. When you find the type you want, you'll know the joining method you need.
|
||||
|
||||
> :point_up: **Note**: If you don't find the type you want, chances are that you are fighting the framework, and should reconsider your position. Your escape hatch is the low-level apis described in [Decoding a Joined Request with FetchableRecord].
|
||||
|
||||
- [`including(required:)`]
|
||||
|
||||
1. Should the associated records be fetched along with the base records?
|
||||
|
||||
If yes, use `including(...)`. Otherwise, use `joining(...)`.
|
||||
|
||||
For example, to load books with their respective author, you use `including(required:)`:
|
||||
|
||||
```swift
|
||||
// All books with their respective author
|
||||
let request = Book
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
var book: Book // The base record
|
||||
var author: Author // The associated record
|
||||
}
|
||||
|
||||
let bookInfos = try Book
|
||||
.including(required: Book.author)
|
||||
|
||||
// This request can feed the following record:
|
||||
struct BookInfo: FetchableRecord, Decodable {
|
||||
var book: Book
|
||||
var author: Author // the required associated author
|
||||
}
|
||||
let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
And to load authors with their respective books, you use `including(all:)`:
|
||||
|
||||
```swift
|
||||
// All authors with their respective books
|
||||
let request = Author
|
||||
.including(all: Author.books)
|
||||
|
||||
// This request can feed the following record:
|
||||
struct AuthorInfo: FetchableRecord, Decodable {
|
||||
var author: Author
|
||||
var books: [Book] // all associated books
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
struct PartialAuthor: Decodable {
|
||||
var name: String
|
||||
var country: String
|
||||
}
|
||||
var book: Book // The base record
|
||||
var author: PartialAuthor // The partial associated record
|
||||
}
|
||||
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
On the other side, to load all books written by a French author, you sure need to filter authors, but you don't need them to be present in the fetched results. You prefer `joining`:
|
||||
|
||||
```swift
|
||||
// All books written by a French author
|
||||
let request = Book
|
||||
.joining(required: Book.author.filter(Column("countryCode") == "FR"))
|
||||
|
||||
// This request feeds the Book record:
|
||||
let books: [Book] = try request.fetchAll(db)
|
||||
let bookInfos = try Book
|
||||
.including(required: Book.author.select(Column("name"), Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
2. For to-one associations, should the request allow missing associated records?
|
||||
|
||||
If yes, choose the `optional` variant. Otherwise, choose `required`.
|
||||
|
||||
For example, to load all books with their respective authors, even if the book has no recorded author, you'd use `including(optional:)`:
|
||||
- [`annotated(withRequired:)`]
|
||||
|
||||
```swift
|
||||
// All books with their respective (eventual) authors
|
||||
let request = Book
|
||||
.including(optional: Book.author)
|
||||
|
||||
// This request can feed the following record:
|
||||
struct BookInfo: FetchableRecord, Decodable {
|
||||
var book: Book
|
||||
var author: Author? // the optional associated author
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
var book: Book // The base record
|
||||
var authorName: String // A column of the associated record
|
||||
var country: String // A column of the associated record
|
||||
}
|
||||
let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
|
||||
|
||||
let bookInfos = try Book
|
||||
.annotated(withRequired: Book.author.select(
|
||||
Column("name").forKey("authorName"),
|
||||
Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
- [`including(optional:)`]
|
||||
|
||||
```swift
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
var book: Book // The base record
|
||||
var author: Author? // The eventual associated record
|
||||
}
|
||||
|
||||
let bookInfos = try Book
|
||||
.including(optional: Book.author)
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
You can remember to use `optional` when the fetched associated records should feed optional Swift values, of type `Author?`. Conversely, when the fetched results feed non-optional values of type `Author`, prefer `required`.
|
||||
```swift
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
struct PartialAuthor: Decodable {
|
||||
var name: String
|
||||
var country: String
|
||||
}
|
||||
var book: Book // The base record
|
||||
var author: PartialAuthor? // The eventual partial associated record
|
||||
}
|
||||
|
||||
Another way to describe the difference is that `required` filters the fetched results in order to discard missing associated records, when `optional` does not filter anything, and lets missing values pass through.
|
||||
|
||||
Finally, readers who speak SQL may compare `optional` with left joins, and `required` with inner joins:
|
||||
let bookInfos = try Book
|
||||
.including(optional: Book.author.select(Column("name"), Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
- [`annotated(withOptional:)`]
|
||||
|
||||
```swift
|
||||
// SELECT book.* FROM book LEFT JOIN author ON author.id = book.authorID
|
||||
Book.joining(optional: Book.author)
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
var book: Book // The base record
|
||||
var authorName: String? // A column of the eventual associated record
|
||||
var country: String? // A column of the eventual associated record
|
||||
}
|
||||
|
||||
// SELECT book.* FROM book JOIN author ON author.id = book.authorID
|
||||
Book.joining(required: Book.author)
|
||||
let bookInfos = try Book
|
||||
.annotated(withOptional: Book.author.select(
|
||||
Column("name").forKey("authorName"),
|
||||
Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
- [`including(all:)`]
|
||||
|
||||
// SELECT book.*, author.* FROM book LEFT JOIN author ON author.id = book.authorID
|
||||
Book.including(optional: Book.author)
|
||||
```swift
|
||||
struct AuthorInfo: Decodable, FetchableRecord {
|
||||
var author: Author // The base record
|
||||
var books: [Book] // A collection of associated records
|
||||
}
|
||||
|
||||
// SELECT book.*, author.* FROM book JOIN author ON author.id = book.authorID
|
||||
Book.including(required: Book.author)
|
||||
let authorInfos = try Author
|
||||
.including(all: Author.books)
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
```swift
|
||||
struct AuthorInfo: Decodable, FetchableRecord {
|
||||
struct PartialBook: Decodable {
|
||||
var title: String
|
||||
var year: Int
|
||||
}
|
||||
var author: Author // The base record
|
||||
var books: [PartialBook] // A collection of partial associated records
|
||||
}
|
||||
|
||||
let authorInfos = try Author
|
||||
.including(all: Author.books.select(Column("title"), Column("year")))
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
```swift
|
||||
struct AuthorInfo: Decodable, FetchableRecord {
|
||||
var author: Author // The base record
|
||||
var bookTitles: [String] // A collection of one column of the associated records
|
||||
}
|
||||
|
||||
let authorInfos = try Author
|
||||
.including(all: Author.books
|
||||
.select(Column("title"))
|
||||
.forKey("bookTitles"))
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
|
||||
@@ -1123,7 +1510,7 @@ let sortedAuthor = Book.author.order(Column("name"))
|
||||
let request = Book.including(required: sortedAuthor)
|
||||
```
|
||||
|
||||
When you sort both the base record on the associated record, the request is sorted on the base record first, and on the associated record next:
|
||||
When you sort both the base record and the associated record, the request is sorted on the base record first, and on the associated record next:
|
||||
|
||||
```swift
|
||||
// SELECT book.*, person.*
|
||||
@@ -1243,7 +1630,7 @@ let teamInfos = try Team
|
||||
|
||||
## Columns Selected by an Association
|
||||
|
||||
By default, associated records include all their columns:
|
||||
By default, associated records, like all records, include all their columns:
|
||||
|
||||
```swift
|
||||
// SELECT book.*, author.*
|
||||
@@ -1254,7 +1641,9 @@ let request = Book.including(required: Book.author)
|
||||
|
||||
**The selection can be changed for each individual request, or for all requests including a given type.**
|
||||
|
||||
To specify the selection of an associated record in a specific request, use the `select` method:
|
||||
To specify the default selection for a given record type, see [Columns Selected by a Request](../README.md#columns-selected-by-a-request).
|
||||
|
||||
To specify the selection in a specific request, use the `select` method:
|
||||
|
||||
```swift
|
||||
// SELECT book.*, author.id, author.name
|
||||
@@ -1264,7 +1653,7 @@ let restrictedAuthor = Book.author.select(Column("id"), Column("name"))
|
||||
let request = Book.including(required: restrictedAuthor)
|
||||
```
|
||||
|
||||
To specify the default selection for all inclusions of a given type, see [Columns Selected by a Request](../README.md#columns-selected-by-a-request).
|
||||
In order to fetch from such requests of partial records, see the documentation of the [joining methods].
|
||||
|
||||
|
||||
## Further Refinements to Associations
|
||||
@@ -1942,6 +2331,7 @@ for info in authorInfos {
|
||||
- `books.max(column)`
|
||||
- `books.average(column)`
|
||||
- `books.sum(column)`
|
||||
- `books.total(column)`
|
||||
|
||||
|
||||
### Annotating a Request with Aggregates
|
||||
@@ -1990,6 +2380,9 @@ The default name is built from the aggregating method, the **[association key](#
|
||||
| `Author.books.max(Column("year"))` | `books` | `year` | `maxBookYear` |
|
||||
| `Author.books.average(Column("price"))` | `books` | `price` | `averageBookPrice` |
|
||||
| `Author.books.sum(Column("awards"))` | `books` | `awards` | `bookAwardsSum` |
|
||||
| `Author.books.total(Column("awards"))` | `books` | `awards` | `bookAwardsSum` ¹ |
|
||||
|
||||
¹ The default name of the `total` aggregate has a `Sum` suffix, just like the `sum` aggregate. Both compute sums, one with the `SUM` SQL function, the other with `TOTAL`. See [SQLite documentation](https://www.sqlite.org/lang_aggfunc.html#sumunc) for the difference between these aggregate functions.
|
||||
|
||||
Those default names are lost whenever an aggregate is modified (negated, added, multiplied, whatever).
|
||||
|
||||
@@ -2264,6 +2657,23 @@ Aggregates can be modified and combined with Swift operators:
|
||||
let request = Team.annotated(with: Team.players.min(Column("score")) ?? 0)
|
||||
```
|
||||
|
||||
- SQL functions `ABS` and `LENGTH` are available as the `abs` and `length` Swift functions:
|
||||
|
||||
<details>
|
||||
<summary>SQL</summary>
|
||||
|
||||
```sql
|
||||
SELECT "team".*, ABS(MAX("player"."score"))
|
||||
FROM "team"
|
||||
LEFT JOIN "player" ON ("player"."teamId" = "team"."id")
|
||||
GROUP BY "team"."id"
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
```swift
|
||||
let request = Team.annotated(with: abs(Team.players.max(Column("score"))))
|
||||
```
|
||||
|
||||
### Isolation of Multiple Aggregates
|
||||
|
||||
@@ -2568,6 +2978,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
[Requesting Associated Records]: #requesting-associated-records
|
||||
[requests for associated records]: #requesting-associated-records
|
||||
[Joining And Prefetching Associated Records]: #joining-and-prefetching-associated-records
|
||||
[joining methods]: #joining-and-prefetching-associated-records
|
||||
[Filtering Associations]: #filtering-associations
|
||||
[Sorting Associations]: #sorting-associations
|
||||
[Columns Selected by an Association]: #columns-selected-by-an-association
|
||||
@@ -2603,3 +3014,11 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
[common table expressions]: CommonTableExpressions.md
|
||||
[Common Table Expressions]: CommonTableExpressions.md
|
||||
[Associations to Common Table Expressions]: CommonTableExpressions.md#associations-to-common-table-expressions
|
||||
[`including(required:)`]: #includingrequired
|
||||
[`including(optional:)`]: #includingoptional
|
||||
[`including(all:)`]: #includingall
|
||||
[`annotated(withRequired:)`]: #annotatedwithrequired
|
||||
[`annotated(withOptional:)`]: #annotatedwithoptional
|
||||
[`joining(required:)`]: #joiningrequired
|
||||
[`joining(optional:)`]: #joiningoptional
|
||||
[Choosing a Joining Method Given the Shape of the Decoded Type]: #choosing-a-joining-method-given-the-shape-of-the-decoded-type
|
||||
@@ -227,7 +227,7 @@ This publisher has the same behavior as ValueObservation:
|
||||
- It notifies an initial value before the eventual changes.
|
||||
- It may coalesce subsequent changes into a single notification.
|
||||
- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](../README.md#valueobservationremoveduplicates) GRDB operator also.
|
||||
- It stops emitting any value after the database connection is closed. But it never completes.
|
||||
- It only completes when it is cancelled.
|
||||
- By default, it notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously.
|
||||
|
||||
This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservation scheduler](../README.md#valueobservation-scheduling).
|
||||
@@ -317,7 +317,7 @@ In other words, whenever you need to perform some database access or observation
|
||||
|
||||
To this end, remember that *all database publishers can perform several requests*.
|
||||
|
||||
In the example below, we are totally sure that the published `HallOfFame` values will never contain inconsistent values, because it is produced by one and ony one publisher:
|
||||
In the example below, we are totally sure that the published `HallOfFame` values will never contain inconsistent values, because it is produced by one and only one publisher:
|
||||
|
||||
```swift
|
||||
struct HallOfFame {
|
||||
|
||||
@@ -132,7 +132,27 @@ try dbQueue.write { db in
|
||||
}
|
||||
```
|
||||
|
||||
:twisted_rightwards_arrows: **An async access does not block the current thread.** Instead, it notifies you when the database operations are completed. There are three ways to access the database asynchronously:
|
||||
:twisted_rightwards_arrows: **An async access does not block the current thread.** Instead, it notifies you when the database operations are completed. There are four ways to access the database asynchronously:
|
||||
|
||||
<details>
|
||||
<summary><b>Swift concurrency</b> (async/await)</summary>
|
||||
|
||||
[**:fire: EXPERIMENTAL**](../README.md#what-are-experimental-features) GRDB support for Swift concurrency requires Xcode 13.3.1+.
|
||||
|
||||
```swift
|
||||
let playerCount = try await dbQueue.read { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
|
||||
let newPlayerCount = try await dbQueue.write { db -> Int in
|
||||
try Player(id: 12, name: "Arthur").insert(db)
|
||||
return try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
Note the identical method names: `read`, `write`. The async version is only available in async Swift functions.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Combine publishers</b></summary>
|
||||
@@ -205,7 +225,7 @@ During one async access, all individual database operations grouped inside (fetc
|
||||
|
||||
```swift
|
||||
// One asynchronous access...
|
||||
dbQueue.writePublisher { db in
|
||||
try await dbQueue.write { db in
|
||||
// ... always performs synchronous database operations:
|
||||
try Player(...).insert(db)
|
||||
try Player(...).insert(db)
|
||||
@@ -237,7 +257,7 @@ Some applications need to relax this safety net, in order to achieve specific SQ
|
||||
try dbQueue.writeWithoutTransaction { db in ... }
|
||||
```
|
||||
|
||||
You can also use `asyncWriteWithoutTransaction`.
|
||||
`writeWithoutTransaction` is also available as an `async` function. You can also use `asyncWriteWithoutTransaction`.
|
||||
|
||||
- **Write outside of any transaction, and prevents concurrent reads**
|
||||
(Lifted guarantee: [Write Transactions])
|
||||
@@ -252,7 +272,7 @@ Some applications need to relax this safety net, in order to achieve specific SQ
|
||||
|
||||
You will use this method, for example, when you [change the password](../README.md#changing-the-passphrase-of-an-encrypted-database) of an encrypted database.
|
||||
|
||||
You can also use `asyncBarrierWriteWithoutTransaction`.
|
||||
`barrierWriteWithoutTransaction` is also available as an `async` function. You can also use `asyncBarrierWriteWithoutTransaction`.
|
||||
|
||||
- **Reentrant write outside of any transaction**
|
||||
(Lifted guarantees: [Write Transactions], [Non-Reentrancy])
|
||||
@@ -279,7 +299,7 @@ Some applications need to relax this safety net, in order to achieve specific SQ
|
||||
try dbQueue.unsafeRead { db in ... }
|
||||
```
|
||||
|
||||
`unsafeRead` has no async version.
|
||||
`unsafeRead` is also available as an `async` function.
|
||||
|
||||
- **Reentrant read, outside of any transaction**
|
||||
(Lifted guarantees: [Isolated Reads], [Forbidden Writes], [Non-Reentrancy])
|
||||
@@ -449,7 +469,7 @@ In the illustration below, the striped band shows the delay needed for the readi
|
||||
let snapshot = try dbPool.makeSnapshot()
|
||||
```
|
||||
|
||||
You can create as many snapshots as you need, regardless of the [maximum number of readers](../README.md#databasepool-configuration) in the pool. A snapshot database connection is closed when the snapshot is deinitialized.
|
||||
You can create as many snapshots as you need, regardless of the [maximum number of readers](../README.md#database-configuration) in the pool. A snapshot database connection is closed when the snapshot is deinitialized.
|
||||
|
||||
**A snapshot can be used from any thread.** It has the same [synchronous and asynchronous reading methods](#synchronous-and-asynchronous-database-accesses) as database queues and pools:
|
||||
|
||||
|
||||
@@ -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.33.0](https://www.sqlite.org/changes.html).**
|
||||
**You can build GRDB with a custom build of [SQLite 3.37.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).
|
||||
|
||||
|
||||
@@ -0,0 +1,727 @@
|
||||
// !$*UTF8*$!
|
||||
{
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 54;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
56026CAC25B8A7EF00D1DF3F /* PlayerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */; };
|
||||
56026CAD25B8A7EF00D1DF3F /* AppDatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */; };
|
||||
56519DCA274FC8E900ED16D8 /* GRDBQuery in Frameworks */ = {isa = PBXBuildFile; productRef = 56519DC9274FC8E900ED16D8 /* GRDBQuery */; };
|
||||
5671723A261B23C800423B6F /* PlayerList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717239261B23C800423B6F /* PlayerList.swift */; };
|
||||
56717252261B334D00423B6F /* PlayerRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717251261B334D00423B6F /* PlayerRequestTests.swift */; };
|
||||
567C3E1A2520B6DE0011F6E9 /* GRDBAsyncDemoApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E192520B6DE0011F6E9 /* GRDBAsyncDemoApp.swift */; };
|
||||
567C3E1E2520B6DF0011F6E9 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */; };
|
||||
567C3E212520B6DF0011F6E9 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */; };
|
||||
567C3E5D2520B75C0011F6E9 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E532520B75C0011F6E9 /* Player.swift */; };
|
||||
567C3E5E2520B75C0011F6E9 /* Persistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E542520B75C0011F6E9 /* Persistence.swift */; };
|
||||
567C3E612520B75D0011F6E9 /* PlayerFormView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E592520B75C0011F6E9 /* PlayerFormView.swift */; };
|
||||
567C3E622520B75D0011F6E9 /* AppView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5A2520B75C0011F6E9 /* AppView.swift */; };
|
||||
567C3E632520B75D0011F6E9 /* PlayerCreationView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */; };
|
||||
567C3E642520B75D0011F6E9 /* PlayerEditionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */; };
|
||||
567C3E662520B7880011F6E9 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E652520B7880011F6E9 /* AppDatabase.swift */; };
|
||||
567C3E792520BB650011F6E9 /* Localizable.stringsdict in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E752520BB650011F6E9 /* Localizable.stringsdict */; };
|
||||
567C3E7A2520BB650011F6E9 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */; };
|
||||
56B6D1092619EC1B003CC455 /* PlayerRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D1082619EC1B003CC455 /* PlayerRequest.swift */; };
|
||||
56F8A13527359A5A0011ACBE /* GRDB in Frameworks */ = {isa = PBXBuildFile; productRef = 56F8A13427359A5A0011ACBE /* GRDB */; };
|
||||
78E2F9E6261EEC22005D1F7F /* GRDBAsyncDemoUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78E2F9E5261EEC22005D1F7F /* GRDBAsyncDemoUITests.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
56026C9D25B8A7D000D1DF3F /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 567C3E0E2520B6DE0011F6E9 /* Project object */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 567C3E152520B6DE0011F6E9;
|
||||
remoteInfo = GRDBAsyncDemo;
|
||||
};
|
||||
78E2F9E8261EEC22005D1F7F /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 567C3E0E2520B6DE0011F6E9 /* Project object */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 567C3E152520B6DE0011F6E9;
|
||||
remoteInfo = GRDBAsyncDemo;
|
||||
};
|
||||
/* End PBXContainerItemProxy section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
567C3E502520B70E0011F6E9 /* Embed Frameworks */ = {
|
||||
isa = PBXCopyFilesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
dstPath = "";
|
||||
dstSubfolderSpec = 10;
|
||||
files = (
|
||||
);
|
||||
name = "Embed Frameworks";
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXCopyFilesBuildPhase section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
56026C9825B8A7D000D1DF3F /* GRDBAsyncDemoTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBAsyncDemoTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
56026C9C25B8A7D000D1DF3F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerTests.swift; sourceTree = "<group>"; };
|
||||
56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabaseTests.swift; sourceTree = "<group>"; };
|
||||
56717239261B23C800423B6F /* PlayerList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerList.swift; sourceTree = "<group>"; };
|
||||
56717251261B334D00423B6F /* PlayerRequestTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequestTests.swift; sourceTree = "<group>"; };
|
||||
567C3E162520B6DE0011F6E9 /* GRDBAsyncDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBAsyncDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
567C3E192520B6DE0011F6E9 /* GRDBAsyncDemoApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GRDBAsyncDemoApp.swift; sourceTree = "<group>"; };
|
||||
567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
|
||||
567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = "<group>"; };
|
||||
567C3E222520B6DF0011F6E9 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
567C3E532520B75C0011F6E9 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = "<group>"; };
|
||||
567C3E542520B75C0011F6E9 /* Persistence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistence.swift; sourceTree = "<group>"; };
|
||||
567C3E592520B75C0011F6E9 /* PlayerFormView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerFormView.swift; sourceTree = "<group>"; };
|
||||
567C3E5A2520B75C0011F6E9 /* AppView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppView.swift; sourceTree = "<group>"; };
|
||||
567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerCreationView.swift; sourceTree = "<group>"; };
|
||||
567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionView.swift; sourceTree = "<group>"; };
|
||||
567C3E652520B7880011F6E9 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
|
||||
567C3E762520BB650011F6E9 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.stringsdict; name = en; path = en.lproj/Localizable.stringsdict; sourceTree = "<group>"; };
|
||||
567C3E782520BB650011F6E9 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
|
||||
56B6D1082619EC1B003CC455 /* PlayerRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequest.swift; sourceTree = "<group>"; };
|
||||
56F8A12E27359A350011ACBE /* GRDB.swift */ = {isa = PBXFileReference; lastKnownFileType = folder; name = GRDB.swift; path = ../../..; sourceTree = "<group>"; };
|
||||
78E2F9E3261EEC22005D1F7F /* GRDBAsyncDemoUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBAsyncDemoUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
78E2F9E5261EEC22005D1F7F /* GRDBAsyncDemoUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GRDBAsyncDemoUITests.swift; sourceTree = "<group>"; };
|
||||
78E2F9E7261EEC22005D1F7F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
56026C9525B8A7D000D1DF3F /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
567C3E132520B6DE0011F6E9 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
56519DCA274FC8E900ED16D8 /* GRDBQuery in Frameworks */,
|
||||
56F8A13527359A5A0011ACBE /* GRDB in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
78E2F9E0261EEC22005D1F7F /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
56026C9925B8A7D000D1DF3F /* GRDBAsyncDemoTests */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56026C9C25B8A7D000D1DF3F /* Info.plist */,
|
||||
56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */,
|
||||
56717251261B334D00423B6F /* PlayerRequestTests.swift */,
|
||||
56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */,
|
||||
);
|
||||
path = GRDBAsyncDemoTests;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56185BC125B8047D00B9C30F /* Resources */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */,
|
||||
567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */,
|
||||
567C3E752520BB650011F6E9 /* Localizable.stringsdict */,
|
||||
);
|
||||
path = Resources;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
567C3E0D2520B6DE0011F6E9 = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567C3E182520B6DE0011F6E9 /* GRDBAsyncDemo */,
|
||||
56026C9925B8A7D000D1DF3F /* GRDBAsyncDemoTests */,
|
||||
78E2F9E4261EEC22005D1F7F /* GRDBAsyncDemoUITests */,
|
||||
567C3E172520B6DE0011F6E9 /* Products */,
|
||||
567C3E4D2520B70E0011F6E9 /* Frameworks */,
|
||||
56F8A12E27359A350011ACBE /* GRDB.swift */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
567C3E172520B6DE0011F6E9 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567C3E162520B6DE0011F6E9 /* GRDBAsyncDemo.app */,
|
||||
56026C9825B8A7D000D1DF3F /* GRDBAsyncDemoTests.xctest */,
|
||||
78E2F9E3261EEC22005D1F7F /* GRDBAsyncDemoUITests.xctest */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
567C3E182520B6DE0011F6E9 /* GRDBAsyncDemo */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567C3E222520B6DF0011F6E9 /* Info.plist */,
|
||||
567C3E652520B7880011F6E9 /* AppDatabase.swift */,
|
||||
567C3E192520B6DE0011F6E9 /* GRDBAsyncDemoApp.swift */,
|
||||
567C3E542520B75C0011F6E9 /* Persistence.swift */,
|
||||
567C3E532520B75C0011F6E9 /* Player.swift */,
|
||||
56B6D1082619EC1B003CC455 /* PlayerRequest.swift */,
|
||||
567C3E1F2520B6DF0011F6E9 /* Preview Content */,
|
||||
56185BC125B8047D00B9C30F /* Resources */,
|
||||
567C3E582520B75C0011F6E9 /* Views */,
|
||||
);
|
||||
path = GRDBAsyncDemo;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
567C3E1F2520B6DF0011F6E9 /* Preview Content */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */,
|
||||
);
|
||||
path = "Preview Content";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
567C3E4D2520B70E0011F6E9 /* Frameworks */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
);
|
||||
name = Frameworks;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
567C3E582520B75C0011F6E9 /* Views */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567C3E5A2520B75C0011F6E9 /* AppView.swift */,
|
||||
567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */,
|
||||
567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */,
|
||||
567C3E592520B75C0011F6E9 /* PlayerFormView.swift */,
|
||||
56717239261B23C800423B6F /* PlayerList.swift */,
|
||||
);
|
||||
path = Views;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
78E2F9E4261EEC22005D1F7F /* GRDBAsyncDemoUITests */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
78E2F9E5261EEC22005D1F7F /* GRDBAsyncDemoUITests.swift */,
|
||||
78E2F9E7261EEC22005D1F7F /* Info.plist */,
|
||||
);
|
||||
path = GRDBAsyncDemoUITests;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
56026C9725B8A7D000D1DF3F /* GRDBAsyncDemoTests */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 56026CA825B8A7D000D1DF3F /* Build configuration list for PBXNativeTarget "GRDBAsyncDemoTests" */;
|
||||
buildPhases = (
|
||||
56026C9425B8A7D000D1DF3F /* Sources */,
|
||||
56026C9525B8A7D000D1DF3F /* Frameworks */,
|
||||
56026C9625B8A7D000D1DF3F /* Resources */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
56026C9E25B8A7D000D1DF3F /* PBXTargetDependency */,
|
||||
);
|
||||
name = GRDBAsyncDemoTests;
|
||||
productName = GRDBAsyncDemoTests;
|
||||
productReference = 56026C9825B8A7D000D1DF3F /* GRDBAsyncDemoTests.xctest */;
|
||||
productType = "com.apple.product-type.bundle.unit-test";
|
||||
};
|
||||
567C3E152520B6DE0011F6E9 /* GRDBAsyncDemo */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 567C3E252520B6DF0011F6E9 /* Build configuration list for PBXNativeTarget "GRDBAsyncDemo" */;
|
||||
buildPhases = (
|
||||
567C3E122520B6DE0011F6E9 /* Sources */,
|
||||
567C3E132520B6DE0011F6E9 /* Frameworks */,
|
||||
567C3E142520B6DE0011F6E9 /* Resources */,
|
||||
567C3E502520B70E0011F6E9 /* Embed Frameworks */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
56F8A13127359A540011ACBE /* PBXTargetDependency */,
|
||||
);
|
||||
name = GRDBAsyncDemo;
|
||||
packageProductDependencies = (
|
||||
56F8A13427359A5A0011ACBE /* GRDB */,
|
||||
56519DC9274FC8E900ED16D8 /* GRDBQuery */,
|
||||
);
|
||||
productName = GRBCombineDemo;
|
||||
productReference = 567C3E162520B6DE0011F6E9 /* GRDBAsyncDemo.app */;
|
||||
productType = "com.apple.product-type.application";
|
||||
};
|
||||
78E2F9E2261EEC22005D1F7F /* GRDBAsyncDemoUITests */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 78E2F9F3261EEC22005D1F7F /* Build configuration list for PBXNativeTarget "GRDBAsyncDemoUITests" */;
|
||||
buildPhases = (
|
||||
78E2F9DF261EEC22005D1F7F /* Sources */,
|
||||
78E2F9E0261EEC22005D1F7F /* Frameworks */,
|
||||
78E2F9E1261EEC22005D1F7F /* Resources */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
78E2F9E9261EEC22005D1F7F /* PBXTargetDependency */,
|
||||
);
|
||||
name = GRDBAsyncDemoUITests;
|
||||
productName = GRDBAsyncDemoUITests;
|
||||
productReference = 78E2F9E3261EEC22005D1F7F /* GRDBAsyncDemoUITests.xctest */;
|
||||
productType = "com.apple.product-type.bundle.ui-testing";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
567C3E0E2520B6DE0011F6E9 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastSwiftUpdateCheck = 1250;
|
||||
LastUpgradeCheck = 1200;
|
||||
TargetAttributes = {
|
||||
56026C9725B8A7D000D1DF3F = {
|
||||
CreatedOnToolsVersion = 12.3;
|
||||
TestTargetID = 567C3E152520B6DE0011F6E9;
|
||||
};
|
||||
567C3E152520B6DE0011F6E9 = {
|
||||
CreatedOnToolsVersion = 12.0;
|
||||
};
|
||||
78E2F9E2261EEC22005D1F7F = {
|
||||
CreatedOnToolsVersion = 12.5;
|
||||
TestTargetID = 567C3E152520B6DE0011F6E9;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = 567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBAsyncDemo" */;
|
||||
compatibilityVersion = "Xcode 12.0";
|
||||
developmentRegion = en;
|
||||
hasScannedForEncodings = 0;
|
||||
knownRegions = (
|
||||
en,
|
||||
Base,
|
||||
);
|
||||
mainGroup = 567C3E0D2520B6DE0011F6E9;
|
||||
packageReferences = (
|
||||
56519DC8274FC8E900ED16D8 /* XCRemoteSwiftPackageReference "GRDBQuery" */,
|
||||
);
|
||||
productRefGroup = 567C3E172520B6DE0011F6E9 /* Products */;
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
567C3E152520B6DE0011F6E9 /* GRDBAsyncDemo */,
|
||||
56026C9725B8A7D000D1DF3F /* GRDBAsyncDemoTests */,
|
||||
78E2F9E2261EEC22005D1F7F /* GRDBAsyncDemoUITests */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXResourcesBuildPhase section */
|
||||
56026C9625B8A7D000D1DF3F /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
567C3E142520B6DE0011F6E9 /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
567C3E212520B6DF0011F6E9 /* Preview Assets.xcassets in Resources */,
|
||||
567C3E7A2520BB650011F6E9 /* LaunchScreen.storyboard in Resources */,
|
||||
567C3E1E2520B6DF0011F6E9 /* Assets.xcassets in Resources */,
|
||||
567C3E792520BB650011F6E9 /* Localizable.stringsdict in Resources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
78E2F9E1261EEC22005D1F7F /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
56026C9425B8A7D000D1DF3F /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
56026CAC25B8A7EF00D1DF3F /* PlayerTests.swift in Sources */,
|
||||
56026CAD25B8A7EF00D1DF3F /* AppDatabaseTests.swift in Sources */,
|
||||
56717252261B334D00423B6F /* PlayerRequestTests.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
567C3E122520B6DE0011F6E9 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
567C3E5E2520B75C0011F6E9 /* Persistence.swift in Sources */,
|
||||
567C3E5D2520B75C0011F6E9 /* Player.swift in Sources */,
|
||||
56B6D1092619EC1B003CC455 /* PlayerRequest.swift in Sources */,
|
||||
5671723A261B23C800423B6F /* PlayerList.swift in Sources */,
|
||||
567C3E612520B75D0011F6E9 /* PlayerFormView.swift in Sources */,
|
||||
567C3E632520B75D0011F6E9 /* PlayerCreationView.swift in Sources */,
|
||||
567C3E662520B7880011F6E9 /* AppDatabase.swift in Sources */,
|
||||
567C3E622520B75D0011F6E9 /* AppView.swift in Sources */,
|
||||
567C3E642520B75D0011F6E9 /* PlayerEditionView.swift in Sources */,
|
||||
567C3E1A2520B6DE0011F6E9 /* GRDBAsyncDemoApp.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
78E2F9DF261EEC22005D1F7F /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
78E2F9E6261EEC22005D1F7F /* GRDBAsyncDemoUITests.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXTargetDependency section */
|
||||
56026C9E25B8A7D000D1DF3F /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
target = 567C3E152520B6DE0011F6E9 /* GRDBAsyncDemo */;
|
||||
targetProxy = 56026C9D25B8A7D000D1DF3F /* PBXContainerItemProxy */;
|
||||
};
|
||||
56F8A13127359A540011ACBE /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
productRef = 56F8A13027359A540011ACBE /* GRDB */;
|
||||
};
|
||||
78E2F9E9261EEC22005D1F7F /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
target = 567C3E152520B6DE0011F6E9 /* GRDBAsyncDemo */;
|
||||
targetProxy = 78E2F9E8261EEC22005D1F7F /* PBXContainerItemProxy */;
|
||||
};
|
||||
/* End PBXTargetDependency section */
|
||||
|
||||
/* Begin PBXVariantGroup section */
|
||||
567C3E752520BB650011F6E9 /* Localizable.stringsdict */ = {
|
||||
isa = PBXVariantGroup;
|
||||
children = (
|
||||
567C3E762520BB650011F6E9 /* en */,
|
||||
);
|
||||
name = Localizable.stringsdict;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */ = {
|
||||
isa = PBXVariantGroup;
|
||||
children = (
|
||||
567C3E782520BB650011F6E9 /* Base */,
|
||||
);
|
||||
name = LaunchScreen.storyboard;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXVariantGroup section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
56026C9F25B8A7D000D1DF3F /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
INFOPLIST_FILE = GRDBAsyncDemoTests/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBAsyncDemoTests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBAsyncDemo.app/GRDBAsyncDemo";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
56026CA025B8A7D000D1DF3F /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
INFOPLIST_FILE = GRDBAsyncDemoTests/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBAsyncDemoTests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBAsyncDemo.app/GRDBAsyncDemo";
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
567C3E232520B6DF0011F6E9 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
CLANG_ANALYZER_NONNULL = YES;
|
||||
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
|
||||
CLANG_CXX_LIBRARY = "libc++";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
||||
CLANG_WARN_EMPTY_BODY = YES;
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu11;
|
||||
GCC_DYNAMIC_NO_PIC = NO;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
GCC_PREPROCESSOR_DEFINITIONS = (
|
||||
"DEBUG=1",
|
||||
"$(inherited)",
|
||||
);
|
||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
||||
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
|
||||
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
|
||||
MTL_FAST_MATH = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
567C3E242520B6DF0011F6E9 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
CLANG_ANALYZER_NONNULL = YES;
|
||||
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
|
||||
CLANG_CXX_LIBRARY = "libc++";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
||||
CLANG_WARN_EMPTY_BODY = YES;
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
ENABLE_NS_ASSERTIONS = NO;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu11;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
||||
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
MTL_FAST_MATH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
VALIDATE_PRODUCT = YES;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
567C3E262520B6DF0011F6E9 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_ASSET_PATHS = "\"GRDBAsyncDemo/Preview Content\"";
|
||||
DEVELOPMENT_TEAM = "";
|
||||
ENABLE_PREVIEWS = YES;
|
||||
INFOPLIST_FILE = GRDBAsyncDemo/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBAsyncDemo;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = 1;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
567C3E272520B6DF0011F6E9 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_ASSET_PATHS = "\"GRDBAsyncDemo/Preview Content\"";
|
||||
DEVELOPMENT_TEAM = "";
|
||||
ENABLE_PREVIEWS = YES;
|
||||
INFOPLIST_FILE = GRDBAsyncDemo/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBAsyncDemo;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = 1;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
78E2F9EA261EEC22005D1F7F /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_TEAM = "";
|
||||
INFOPLIST_FILE = GRDBAsyncDemoUITests/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.groue.GRDBAsyncDemoUITests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_TARGET_NAME = GRDBAsyncDemo;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
78E2F9EB261EEC22005D1F7F /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_TEAM = "";
|
||||
INFOPLIST_FILE = GRDBAsyncDemoUITests/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.groue.GRDBAsyncDemoUITests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_TARGET_NAME = GRDBAsyncDemo;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
56026CA825B8A7D000D1DF3F /* Build configuration list for PBXNativeTarget "GRDBAsyncDemoTests" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
56026C9F25B8A7D000D1DF3F /* Debug */,
|
||||
56026CA025B8A7D000D1DF3F /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBAsyncDemo" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
567C3E232520B6DF0011F6E9 /* Debug */,
|
||||
567C3E242520B6DF0011F6E9 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
567C3E252520B6DF0011F6E9 /* Build configuration list for PBXNativeTarget "GRDBAsyncDemo" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
567C3E262520B6DF0011F6E9 /* Debug */,
|
||||
567C3E272520B6DF0011F6E9 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
78E2F9F3261EEC22005D1F7F /* Build configuration list for PBXNativeTarget "GRDBAsyncDemoUITests" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
78E2F9EA261EEC22005D1F7F /* Debug */,
|
||||
78E2F9EB261EEC22005D1F7F /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
|
||||
/* Begin XCRemoteSwiftPackageReference section */
|
||||
56519DC8274FC8E900ED16D8 /* XCRemoteSwiftPackageReference "GRDBQuery" */ = {
|
||||
isa = XCRemoteSwiftPackageReference;
|
||||
repositoryURL = "https://github.com/groue/GRDBQuery";
|
||||
requirement = {
|
||||
kind = upToNextMajorVersion;
|
||||
minimumVersion = 0.1.0;
|
||||
};
|
||||
};
|
||||
/* End XCRemoteSwiftPackageReference section */
|
||||
|
||||
/* Begin XCSwiftPackageProductDependency section */
|
||||
56519DC9274FC8E900ED16D8 /* GRDBQuery */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = 56519DC8274FC8E900ED16D8 /* XCRemoteSwiftPackageReference "GRDBQuery" */;
|
||||
productName = GRDBQuery;
|
||||
};
|
||||
56F8A13027359A540011ACBE /* GRDB */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
productName = GRDB;
|
||||
};
|
||||
56F8A13427359A5A0011ACBE /* GRDB */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
productName = GRDB;
|
||||
};
|
||||
/* End XCSwiftPackageProductDependency section */
|
||||
};
|
||||
rootObject = 567C3E0E2520B6DE0011F6E9 /* Project object */;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
<FileRef
|
||||
location = "self:">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>IDEDidComputeMac32BitWarning</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"object": {
|
||||
"pins": [
|
||||
{
|
||||
"package": "GRDBQuery",
|
||||
"repositoryURL": "https://github.com/groue/GRDBQuery",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "4301166cd2aee9ce37b4057c9a58f5cc3bbeae06",
|
||||
"version": "0.1.0"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 1
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1230"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "567C3E152520B6DE0011F6E9"
|
||||
BuildableName = "GRDBAsyncDemo.app"
|
||||
BlueprintName = "GRDBAsyncDemo"
|
||||
ReferencedContainer = "container:GRDBAsyncDemo.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 = "56026C9725B8A7D000D1DF3F"
|
||||
BuildableName = "GRDBAsyncDemoTests.xctest"
|
||||
BlueprintName = "GRDBAsyncDemoTests"
|
||||
ReferencedContainer = "container:GRDBAsyncDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "78E2F9E2261EEC22005D1F7F"
|
||||
BuildableName = "GRDBAsyncDemoUITests.xctest"
|
||||
BlueprintName = "GRDBAsyncDemoUITests"
|
||||
ReferencedContainer = "container:GRDBAsyncDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
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 = "567C3E152520B6DE0011F6E9"
|
||||
BuildableName = "GRDBAsyncDemo.app"
|
||||
BlueprintName = "GRDBAsyncDemo"
|
||||
ReferencedContainer = "container:GRDBAsyncDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "567C3E152520B6DE0011F6E9"
|
||||
BuildableName = "GRDBAsyncDemo.app"
|
||||
BlueprintName = "GRDBAsyncDemo"
|
||||
ReferencedContainer = "container:GRDBAsyncDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -0,0 +1,168 @@
|
||||
import Foundation
|
||||
import GRDB
|
||||
|
||||
/// AppDatabase lets the application access the database.
|
||||
///
|
||||
/// It applies the pratices recommended at
|
||||
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
struct AppDatabase {
|
||||
/// Creates an `AppDatabase`, and make sure the database schema is ready.
|
||||
init(_ dbWriter: DatabaseWriter) throws {
|
||||
self.dbWriter = dbWriter
|
||||
try migrator.migrate(dbWriter)
|
||||
}
|
||||
|
||||
/// Provides access to the database.
|
||||
///
|
||||
/// Application can use a `DatabasePool`, while SwiftUI previews and tests
|
||||
/// can use a fast in-memory `DatabaseQueue`.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections>
|
||||
private let dbWriter: DatabaseWriter
|
||||
|
||||
/// The DatabaseMigrator that defines the database schema.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md>
|
||||
private var migrator: DatabaseMigrator {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
#if DEBUG
|
||||
// Speed up development by nuking the database when migrations change
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md#the-erasedatabaseonschemachange-option
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
#endif
|
||||
|
||||
migrator.registerMigration("createPlayer") { db in
|
||||
// Create a table
|
||||
// See https://github.com/groue/GRDB.swift#create-tables
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
}
|
||||
|
||||
// Migrations for future application versions will be inserted here:
|
||||
// migrator.registerMigration(...) { db in
|
||||
// ...
|
||||
// }
|
||||
|
||||
return migrator
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Database Access: Writes
|
||||
|
||||
extension AppDatabase {
|
||||
/// A validation error that prevents some players from being saved into
|
||||
/// the database.
|
||||
enum ValidationError: LocalizedError {
|
||||
case missingName
|
||||
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .missingName:
|
||||
return "Please provide a name"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Saves (inserts or updates) a player. When the method returns, the
|
||||
/// player is present in the database, and its id is not nil.
|
||||
func savePlayer(_ player: inout Player) async throws {
|
||||
if player.name.isEmpty {
|
||||
throw ValidationError.missingName
|
||||
}
|
||||
player = try await dbWriter.write { [player] db in
|
||||
try player.saved(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete the specified players
|
||||
func deletePlayers(ids: [Int64]) async throws {
|
||||
try await dbWriter.write { db in
|
||||
_ = try Player.deleteAll(db, ids: ids)
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete all players
|
||||
func deleteAllPlayers() async throws {
|
||||
try await dbWriter.write { db in
|
||||
_ = try Player.deleteAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Refresh all players (by performing some random changes, for demo purpose).
|
||||
func refreshPlayers() async throws {
|
||||
try await dbWriter.write { db in
|
||||
if try Player.all().isEmpty(db) {
|
||||
// When database is empty, insert new random players
|
||||
try createRandomPlayers(db)
|
||||
} else {
|
||||
// Insert a player
|
||||
if Bool.random() {
|
||||
_ = try Player.makeRandom().inserted(db) // insert but ignore inserted id
|
||||
}
|
||||
|
||||
// Delete a random player
|
||||
if Bool.random() {
|
||||
try Player.order(sql: "RANDOM()").limit(1).deleteAll(db)
|
||||
}
|
||||
|
||||
// Update some players
|
||||
for var player in try Player.fetchAll(db) where Bool.random() {
|
||||
try player.updateChanges(db) {
|
||||
$0.score = Player.randomScore()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create random players if the database is empty.
|
||||
func createRandomPlayersIfEmpty() throws {
|
||||
try dbWriter.write { db in
|
||||
if try Player.all().isEmpty(db) {
|
||||
try createRandomPlayers(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static let uiTestPlayers = [
|
||||
Player(id: nil, name: "Arthur", score: 5),
|
||||
Player(id: nil, name: "Barbara", score: 6),
|
||||
Player(id: nil, name: "Craig", score: 8),
|
||||
Player(id: nil, name: "David", score: 4),
|
||||
Player(id: nil, name: "Elena", score: 1),
|
||||
Player(id: nil, name: "Frederik", score: 2),
|
||||
Player(id: nil, name: "Gilbert", score: 7),
|
||||
Player(id: nil, name: "Henriette", score: 3)]
|
||||
|
||||
func createPlayersForUITests() throws {
|
||||
try dbWriter.write { db in
|
||||
try AppDatabase.uiTestPlayers.forEach { player in
|
||||
_ = try player.inserted(db) // insert but ignore inserted id
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Support for `createRandomPlayersIfEmpty()` and `refreshPlayers()`.
|
||||
private func createRandomPlayers(_ db: Database) throws {
|
||||
for _ in 0..<8 {
|
||||
_ = try Player.makeRandom().inserted(db) // insert but ignore inserted id
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Database Access: Reads
|
||||
|
||||
// This demo app does not provide any specific reading method, and instead
|
||||
// gives an unrestricted read-only access to the rest of the application.
|
||||
// In your app, you are free to choose another path, and define focused
|
||||
// reading methods.
|
||||
extension AppDatabase {
|
||||
/// Provides a read-only access to the database
|
||||
var databaseReader: DatabaseReader {
|
||||
dbWriter
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import GRDBQuery
|
||||
import SwiftUI
|
||||
|
||||
@main
|
||||
struct GRDBAsyncDemoApp: App {
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
AppView().environment(\.appDatabase, .shared)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Give SwiftUI access to the database
|
||||
//
|
||||
// Define a new environment key that grants access to an AppDatabase.
|
||||
//
|
||||
// The technique is documented at
|
||||
// <https://developer.apple.com/documentation/swiftui/environmentkey>.
|
||||
|
||||
private struct AppDatabaseKey: EnvironmentKey {
|
||||
static var defaultValue: AppDatabase { .empty() }
|
||||
}
|
||||
|
||||
extension EnvironmentValues {
|
||||
var appDatabase: AppDatabase {
|
||||
get { self[AppDatabaseKey.self] }
|
||||
set { self[AppDatabaseKey.self] = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
// In this demo app, views observe the database with the @Query property
|
||||
// wrapper, defined in the GRDBQuery package. Its documentation recommends to
|
||||
// define a dedicated initializer for `appDatabase` access, so we comply:
|
||||
|
||||
extension Query where Request.DatabaseContext == AppDatabase {
|
||||
/// Convenience initializer for requests that feed from `AppDatabase`.
|
||||
init(_ request: Request) {
|
||||
self.init(request, in: \.appDatabase)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>LSRequiresIPhoneOS</key>
|
||||
<true/>
|
||||
<key>UIApplicationSceneManifest</key>
|
||||
<dict>
|
||||
<key>UIApplicationSupportsMultipleScenes</key>
|
||||
<true/>
|
||||
</dict>
|
||||
<key>UIApplicationSupportsIndirectInputEvents</key>
|
||||
<true/>
|
||||
<key>UILaunchScreen</key>
|
||||
<dict/>
|
||||
<key>UILaunchStoryboardName</key>
|
||||
<string>LaunchScreen</string>
|
||||
<key>UIRequiredDeviceCapabilities</key>
|
||||
<array>
|
||||
<string>armv7</string>
|
||||
</array>
|
||||
<key>UISupportedInterfaceOrientations</key>
|
||||
<array>
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
</array>
|
||||
<key>UISupportedInterfaceOrientations~ipad</key>
|
||||
<array>
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
<string>UIInterfaceOrientationPortraitUpsideDown</string>
|
||||
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,72 @@
|
||||
import Foundation
|
||||
import GRDB
|
||||
|
||||
extension AppDatabase {
|
||||
/// The database for the application
|
||||
static let shared = makeShared()
|
||||
|
||||
private static func makeShared() -> AppDatabase {
|
||||
do {
|
||||
// Pick a folder for storing the SQLite database, as well as
|
||||
// the various temporary files created during normal database
|
||||
// operations (https://sqlite.org/tempfiles.html).
|
||||
let fileManager = FileManager()
|
||||
let folderURL = try fileManager
|
||||
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
.appendingPathComponent("database", isDirectory: true)
|
||||
|
||||
// Support for tests: delete the database if requested
|
||||
if CommandLine.arguments.contains("-reset") {
|
||||
try? fileManager.removeItem(at: folderURL)
|
||||
}
|
||||
|
||||
// Create the database folder if needed
|
||||
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
|
||||
|
||||
// Connect to a database on disk
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
let dbURL = folderURL.appendingPathComponent("db.sqlite")
|
||||
let dbPool = try DatabasePool(path: dbURL.path)
|
||||
|
||||
// Create the AppDatabase
|
||||
let appDatabase = try AppDatabase(dbPool)
|
||||
|
||||
// Prepare the database with test fixtures if requested
|
||||
if CommandLine.arguments.contains("-fixedTestData") {
|
||||
try appDatabase.createPlayersForUITests()
|
||||
} else {
|
||||
// Otherwise, populate the database if it is empty, for better
|
||||
// demo purpose.
|
||||
try appDatabase.createRandomPlayersIfEmpty()
|
||||
}
|
||||
|
||||
return appDatabase
|
||||
} catch {
|
||||
// Replace this implementation with code to handle the error appropriately.
|
||||
// fatalError() causes the application to generate a crash log and terminate.
|
||||
//
|
||||
// Typical reasons for an error here include:
|
||||
// * The parent directory cannot be created, or disallows writing.
|
||||
// * The database is not accessible, due to permissions or data protection when the device is locked.
|
||||
// * The device is out of space.
|
||||
// * The database could not be migrated to its latest schema version.
|
||||
// Check the error message to determine what the actual problem was.
|
||||
fatalError("Unresolved error \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an empty database for SwiftUI previews
|
||||
static func empty() -> AppDatabase {
|
||||
// Connect to an in-memory database
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
let dbQueue = DatabaseQueue()
|
||||
return try! AppDatabase(dbQueue)
|
||||
}
|
||||
|
||||
/// Creates a database full of random players for SwiftUI previews
|
||||
static func random() -> AppDatabase {
|
||||
let appDatabase = empty()
|
||||
try! appDatabase.createRandomPlayersIfEmpty()
|
||||
return appDatabase
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import GRDB
|
||||
|
||||
/// The Player struct.
|
||||
///
|
||||
/// Identifiable conformance supports SwiftUI list animations, and type-safe
|
||||
/// GRDB primary key methods.
|
||||
/// Equatable conformance supports tests.
|
||||
struct Player: Identifiable, Equatable {
|
||||
/// The player id.
|
||||
///
|
||||
/// Int64 is the recommended type for auto-incremented database ids.
|
||||
/// Use nil for players that are not inserted yet in the database.
|
||||
var id: Int64?
|
||||
var name: String
|
||||
var score: Int
|
||||
}
|
||||
|
||||
extension Player {
|
||||
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é"]
|
||||
|
||||
/// Creates a new player with empty name and zero score
|
||||
static func new() -> Player {
|
||||
Player(id: nil, name: "", score: 0)
|
||||
}
|
||||
|
||||
/// Creates a new player with random name and random score
|
||||
static func makeRandom() -> Player {
|
||||
Player(id: nil, name: randomName(), score: randomScore())
|
||||
}
|
||||
|
||||
/// Returns a random name
|
||||
static func randomName() -> String {
|
||||
names.randomElement()!
|
||||
}
|
||||
|
||||
/// Returns a random score
|
||||
static func randomScore() -> Int {
|
||||
10 * Int.random(in: 0...100)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Persistence
|
||||
|
||||
/// Make Player a Codable Record.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#records>
|
||||
extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
// Define database columns from CodingKeys
|
||||
fileprivate enum Columns {
|
||||
static let name = Column(CodingKeys.name)
|
||||
static let score = Column(CodingKeys.score)
|
||||
}
|
||||
|
||||
/// Updates a player id after it has been inserted in the database.
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Player Database Requests
|
||||
|
||||
/// Define some player requests used by the application.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
extension DerivableRequest where RowDecoder == Player {
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let players: [Player] = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByName().fetchAll(db)
|
||||
/// }
|
||||
func orderedByName() -> Self {
|
||||
// Sort by name in a localized case insensitive fashion
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
|
||||
order(Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
|
||||
/// A request of players ordered by score.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let players: [Player] = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByScore().fetchAll(db)
|
||||
/// }
|
||||
/// let bestPlayer: Player? = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByScore().fetchOne(db)
|
||||
/// }
|
||||
func orderedByScore() -> Self {
|
||||
// Sort by descending score, and then by name, in a
|
||||
// localized case insensitive fashion
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
|
||||
order(
|
||||
Player.Columns.score.desc,
|
||||
Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import Combine
|
||||
import GRDB
|
||||
import GRDBQuery
|
||||
|
||||
/// A player request can be used with the `@Query` property wrapper in order to
|
||||
/// feed a view with a list of players.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct MyView: View {
|
||||
/// @Query(PlayerRequest(ordering: .byName)) private var players: [Player]
|
||||
///
|
||||
/// var body: some View {
|
||||
/// List(players) { player in ... )
|
||||
/// }
|
||||
/// }
|
||||
struct PlayerRequest: Queryable {
|
||||
enum Ordering {
|
||||
case byScore
|
||||
case byName
|
||||
}
|
||||
|
||||
/// The ordering used by the player request.
|
||||
var ordering: Ordering
|
||||
|
||||
// MARK: - Queryable Implementation
|
||||
|
||||
static var defaultValue: [Player] { [] }
|
||||
|
||||
func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> {
|
||||
// Build the publisher from the general-purpose read-only access
|
||||
// granted by `appDatabase.databaseReader`.
|
||||
// Some apps will prefer to call a dedicated method of `appDatabase`.
|
||||
ValueObservation
|
||||
.tracking(fetchValue(_:))
|
||||
.publisher(
|
||||
in: appDatabase.databaseReader,
|
||||
// The `.immediate` scheduling feeds the view right on
|
||||
// subscription, and avoids an undesired animation when the
|
||||
// application starts.
|
||||
scheduling: .immediate)
|
||||
.eraseToAnyPublisher()
|
||||
}
|
||||
|
||||
// This method is not required by Queryable, but it makes it easier
|
||||
// to test PlayerRequest.
|
||||
func fetchValue(_ db: Database) throws -> [Player] {
|
||||
switch ordering {
|
||||
case .byScore:
|
||||
return try Player.all().orderedByScore().fetchAll(db)
|
||||
case .byName:
|
||||
return try Player.all().orderedByName().fetchAll(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"colors" : [
|
||||
{
|
||||
"idiom" : "universal"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"size" : "20x20",
|
||||
"idiom" : "iphone",
|
||||
"filename" : "icon_20pt@2x.png",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"size" : "20x20",
|
||||
"idiom" : "iphone",
|
||||
"filename" : "icon_20pt@3x.png",
|
||||
"scale" : "3x"
|
||||
},
|
||||
{
|
||||
"size" : "29x29",
|
||||
"idiom" : "iphone",
|
||||
"filename" : "icon_29pt@2x.png",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"size" : "29x29",
|
||||
"idiom" : "iphone",
|
||||
"filename" : "icon_29pt@3x.png",
|
||||
"scale" : "3x"
|
||||
},
|
||||
{
|
||||
"size" : "40x40",
|
||||
"idiom" : "iphone",
|
||||
"filename" : "icon_40pt@2x.png",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"size" : "40x40",
|
||||
"idiom" : "iphone",
|
||||
"filename" : "icon_40pt@3x.png",
|
||||
"scale" : "3x"
|
||||
},
|
||||
{
|
||||
"size" : "60x60",
|
||||
"idiom" : "iphone",
|
||||
"filename" : "icon_60pt@2x.png",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"size" : "60x60",
|
||||
"idiom" : "iphone",
|
||||
"filename" : "icon_60pt@3x.png",
|
||||
"scale" : "3x"
|
||||
},
|
||||
{
|
||||
"size" : "20x20",
|
||||
"idiom" : "ipad",
|
||||
"filename" : "icon_20pt.png",
|
||||
"scale" : "1x"
|
||||
},
|
||||
{
|
||||
"size" : "20x20",
|
||||
"idiom" : "ipad",
|
||||
"filename" : "icon_20pt@2x-1.png",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"size" : "29x29",
|
||||
"idiom" : "ipad",
|
||||
"filename" : "icon_29pt.png",
|
||||
"scale" : "1x"
|
||||
},
|
||||
{
|
||||
"size" : "29x29",
|
||||
"idiom" : "ipad",
|
||||
"filename" : "icon_29pt@2x-1.png",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"size" : "40x40",
|
||||
"idiom" : "ipad",
|
||||
"filename" : "icon_40pt.png",
|
||||
"scale" : "1x"
|
||||
},
|
||||
{
|
||||
"size" : "40x40",
|
||||
"idiom" : "ipad",
|
||||
"filename" : "icon_40pt@2x-1.png",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"size" : "76x76",
|
||||
"idiom" : "ipad",
|
||||
"filename" : "icon_76pt.png",
|
||||
"scale" : "1x"
|
||||
},
|
||||
{
|
||||
"size" : "76x76",
|
||||
"idiom" : "ipad",
|
||||
"filename" : "icon_76pt@2x.png",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"size" : "83.5x83.5",
|
||||
"idiom" : "ipad",
|
||||
"filename" : "icon_83.5@2x.png",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"size" : "1024x1024",
|
||||
"idiom" : "ios-marketing",
|
||||
"filename" : "Icon.png",
|
||||
"scale" : "1x"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"version" : 1,
|
||||
"author" : "xcode"
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 329 KiB |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 2.6 KiB |
|
After Width: | Height: | Size: 2.6 KiB |
|
After Width: | Height: | Size: 4.7 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 4.5 KiB |
|
After Width: | Height: | Size: 4.5 KiB |
|
After Width: | Height: | Size: 7.8 KiB |
|
After Width: | Height: | Size: 2.6 KiB |
|
After Width: | Height: | Size: 6.9 KiB |
|
After Width: | Height: | Size: 6.9 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 6.5 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 20 KiB |
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"filename" : "LaunchIcon.pdf",
|
||||
"idiom" : "universal"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="17156" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
|
||||
<device id="retina6_1" orientation="portrait" appearance="light"/>
|
||||
<dependencies>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="17125"/>
|
||||
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
|
||||
<capability name="System colors in document resources" minToolsVersion="11.0"/>
|
||||
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
|
||||
</dependencies>
|
||||
<scenes>
|
||||
<!--View Controller-->
|
||||
<scene sceneID="EHf-IW-A2E">
|
||||
<objects>
|
||||
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
|
||||
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
|
||||
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<subviews>
|
||||
<imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="LaunchIcon" translatesAutoresizingMaskIntoConstraints="NO" id="Sgi-te-PKu">
|
||||
<rect key="frame" x="123.5" y="334.5" width="167" height="237"/>
|
||||
</imageView>
|
||||
</subviews>
|
||||
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
|
||||
<color key="backgroundColor" systemColor="systemBackgroundColor"/>
|
||||
<constraints>
|
||||
<constraint firstItem="Sgi-te-PKu" firstAttribute="centerY" secondItem="6Tk-OE-BBY" secondAttribute="centerY" id="KT7-xd-gV4"/>
|
||||
<constraint firstItem="Sgi-te-PKu" firstAttribute="centerX" secondItem="6Tk-OE-BBY" secondAttribute="centerX" id="feL-Vs-SeN"/>
|
||||
</constraints>
|
||||
</view>
|
||||
</viewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="53" y="375"/>
|
||||
</scene>
|
||||
</scenes>
|
||||
<resources>
|
||||
<image name="LaunchIcon" width="167" height="237"/>
|
||||
<systemColor name="systemBackgroundColor">
|
||||
<color white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
|
||||
</systemColor>
|
||||
</resources>
|
||||
</document>
|
||||
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>%lld Players</key>
|
||||
<dict>
|
||||
<key>NSStringLocalizedFormatKey</key>
|
||||
<string>%#@VARIABLE@</string>
|
||||
<key>VARIABLE</key>
|
||||
<dict>
|
||||
<key>NSStringFormatSpecTypeKey</key>
|
||||
<string>NSStringPluralRuleType</string>
|
||||
<key>NSStringFormatValueTypeKey</key>
|
||||
<string>lld</string>
|
||||
<key>zero</key>
|
||||
<string>No Player</string>
|
||||
<key>one</key>
|
||||
<string>1 Player</string>
|
||||
<key>other</key>
|
||||
<string>%lld Players</string>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>%lld points</key>
|
||||
<dict>
|
||||
<key>NSStringLocalizedFormatKey</key>
|
||||
<string>%#@VARIABLE@</string>
|
||||
<key>VARIABLE</key>
|
||||
<dict>
|
||||
<key>NSStringFormatSpecTypeKey</key>
|
||||
<string>NSStringPluralRuleType</string>
|
||||
<key>NSStringFormatValueTypeKey</key>
|
||||
<string>lld</string>
|
||||
<key>zero</key>
|
||||
<string>0 point</string>
|
||||
<key>one</key>
|
||||
<string>1 point</string>
|
||||
<key>other</key>
|
||||
<string>%lld points</string>
|
||||
</dict>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,154 @@
|
||||
import GRDBQuery
|
||||
import SwiftUI
|
||||
|
||||
/// The main application view
|
||||
struct AppView: View {
|
||||
/// Write access to the database
|
||||
@Environment(\.appDatabase) private var appDatabase
|
||||
|
||||
/// The `players` property is automatically updated when the database changes
|
||||
@Query(PlayerRequest(ordering: .byScore)) private var players: [Player]
|
||||
|
||||
/// We'll need to leave edit mode in several occasions.
|
||||
@State private var editMode = EditMode.inactive
|
||||
|
||||
/// Tracks the presentation of the player creation sheet.
|
||||
@State private var newPlayerIsPresented = false
|
||||
|
||||
// If you want to define the query on initialization, you will prefer:
|
||||
//
|
||||
// @Query<PlayerRequest> private var players: [Player]
|
||||
//
|
||||
// init(initialOrdering: PlayerRequest.Ordering) {
|
||||
// _players = Query(PlayerRequest(ordering: initialOrdering))
|
||||
// }
|
||||
|
||||
var body: some View {
|
||||
NavigationView {
|
||||
PlayerList(players: players)
|
||||
.navigationBarTitle(Text("\(players.count) Players"))
|
||||
.navigationBarItems(
|
||||
leading: HStack {
|
||||
EditButton()
|
||||
newPlayerButton
|
||||
},
|
||||
trailing: ToggleOrderingButton(
|
||||
ordering: $players.ordering,
|
||||
willChange: {
|
||||
// onChange(of: $players.wrappedValue.ordering)
|
||||
// is not able to leave the editing mode during
|
||||
// the animation of the list content.
|
||||
// Workaround: stop editing before the ordering
|
||||
// is changed, and the list content is updated.
|
||||
stopEditing()
|
||||
}))
|
||||
.toolbar { toolbarContent }
|
||||
.onChange(of: players) { players in
|
||||
if players.isEmpty {
|
||||
stopEditing()
|
||||
}
|
||||
}
|
||||
.environment(\.editMode, $editMode)
|
||||
}
|
||||
}
|
||||
|
||||
private var toolbarContent: some ToolbarContent {
|
||||
ToolbarItemGroup(placement: .bottomBar) {
|
||||
Button {
|
||||
// Don't stopEditing() here because this is
|
||||
// performed `onChange(of: players)`
|
||||
Task {
|
||||
try? await appDatabase.deleteAllPlayers()
|
||||
}
|
||||
} label: {
|
||||
Image(systemName: "trash").imageScale(.large)
|
||||
}
|
||||
|
||||
Spacer()
|
||||
|
||||
Button {
|
||||
stopEditing()
|
||||
Task {
|
||||
try? await appDatabase.refreshPlayers()
|
||||
}
|
||||
} label: {
|
||||
Image(systemName: "arrow.clockwise").imageScale(.large)
|
||||
}
|
||||
|
||||
Spacer()
|
||||
|
||||
Button {
|
||||
stopEditing()
|
||||
// Perform 50 refreshes in parallel
|
||||
Task {
|
||||
try? await withThrowingTaskGroup(of: Void.self) { group in
|
||||
for _ in 0..<50 {
|
||||
_ = group.addTaskUnlessCancelled {
|
||||
try await appDatabase.refreshPlayers()
|
||||
}
|
||||
}
|
||||
try await group.waitForAll()
|
||||
}
|
||||
}
|
||||
} label: {
|
||||
Image(systemName: "tornado").imageScale(.large)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The button that presents the player creation sheet.
|
||||
private var newPlayerButton: some View {
|
||||
Button {
|
||||
stopEditing()
|
||||
newPlayerIsPresented = true
|
||||
} label: {
|
||||
Image(systemName: "plus")
|
||||
}
|
||||
.accessibility(label: Text("New Player"))
|
||||
.sheet(isPresented: $newPlayerIsPresented) {
|
||||
PlayerCreationView()
|
||||
}
|
||||
}
|
||||
|
||||
private func stopEditing() {
|
||||
withAnimation {
|
||||
editMode = .inactive
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct ToggleOrderingButton: View {
|
||||
@Binding var ordering: PlayerRequest.Ordering
|
||||
let willChange: () -> Void
|
||||
|
||||
var body: some View {
|
||||
switch ordering {
|
||||
case .byName:
|
||||
Button {
|
||||
willChange()
|
||||
ordering = .byScore
|
||||
} label: {
|
||||
Label("Name", systemImage: "arrowtriangle.up.fill").labelStyle(.titleAndIcon)
|
||||
}
|
||||
case .byScore:
|
||||
Button {
|
||||
willChange()
|
||||
ordering = .byName
|
||||
} label: {
|
||||
Label("Score", systemImage: "arrowtriangle.down.fill").labelStyle(.titleAndIcon)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct AppView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
Group {
|
||||
// Preview the default, empty database
|
||||
AppView()
|
||||
|
||||
// Preview a database of random players
|
||||
AppView().environment(\.appDatabase, .random())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import SwiftUI
|
||||
|
||||
/// The view that creates a new player.
|
||||
struct PlayerCreationView: View {
|
||||
/// Write access to the database
|
||||
@Environment(\.appDatabase) private var appDatabase
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@State private var form = PlayerForm(name: "", score: "")
|
||||
@State private var errorAlertIsPresented = false
|
||||
@State private var errorAlertTitle = ""
|
||||
|
||||
var body: some View {
|
||||
NavigationView {
|
||||
PlayerFormView(form: $form)
|
||||
.alert(
|
||||
isPresented: $errorAlertIsPresented,
|
||||
content: { Alert(title: Text(errorAlertTitle)) })
|
||||
.navigationBarTitle("New Player")
|
||||
.navigationBarItems(
|
||||
leading: Button(role: .cancel) {
|
||||
dismiss()
|
||||
} label: {
|
||||
Text("Cancel")
|
||||
},
|
||||
trailing: Button {
|
||||
Task { await save() }
|
||||
} label: {
|
||||
Text("Save")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private func save() async {
|
||||
do {
|
||||
var player = Player(id: nil, name: "", score: 0)
|
||||
form.apply(to: &player)
|
||||
try await appDatabase.savePlayer(&player)
|
||||
dismiss()
|
||||
} catch {
|
||||
errorAlertTitle = (error as? LocalizedError)?.errorDescription ?? "An error occurred"
|
||||
errorAlertIsPresented = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerCreationSheet_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
PlayerCreationView()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import SwiftUI
|
||||
|
||||
/// The view that edits an existing player.
|
||||
struct PlayerEditionView: View {
|
||||
/// Write access to the database
|
||||
@Environment(\.appDatabase) private var appDatabase
|
||||
@Environment(\.isPresented) private var isPresented
|
||||
private let player: Player
|
||||
@State private var form: PlayerForm
|
||||
|
||||
init(player: Player) {
|
||||
self.player = player
|
||||
self.form = PlayerForm(player)
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
PlayerFormView(form: $form)
|
||||
.onChange(of: isPresented) { isPresented in
|
||||
// Save when back button is pressed
|
||||
if !isPresented {
|
||||
Task {
|
||||
var savedPlayer = player
|
||||
form.apply(to: &savedPlayer)
|
||||
// Ignore error because I don't know how to cancel the
|
||||
// back button and present the error
|
||||
try? await appDatabase.savePlayer(&savedPlayer)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerEditionView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
NavigationView {
|
||||
PlayerEditionView(player: Player.makeRandom())
|
||||
.navigationBarTitle("Player Edition")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import SwiftUI
|
||||
|
||||
/// The Player editing form, embedded in both
|
||||
/// `PlayerCreationView` and `PlayerEditionView`.
|
||||
struct PlayerFormView: View {
|
||||
@Binding var form: PlayerForm
|
||||
|
||||
var body: some View {
|
||||
List {
|
||||
TextField("Name", text: $form.name)
|
||||
.accessibility(label: Text("Player Name"))
|
||||
TextField("Score", text: $form.score).keyboardType(.numberPad)
|
||||
.accessibility(label: Text("Player Score"))
|
||||
}
|
||||
.listStyle(InsetGroupedListStyle())
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerForm {
|
||||
var name: String
|
||||
var score: String
|
||||
}
|
||||
|
||||
extension PlayerForm {
|
||||
init(_ player: Player) {
|
||||
self.name = player.name
|
||||
self.score = "\(player.score)"
|
||||
}
|
||||
|
||||
func apply(to player: inout Player) {
|
||||
player.name = name
|
||||
player.score = Int(score) ?? 0
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerFormView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
Group {
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: "",
|
||||
score: "")))
|
||||
PlayerFormView(form: .constant(PlayerForm(
|
||||
name: Player.randomName(),
|
||||
score: "\(Player.randomScore())")))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import SwiftUI
|
||||
|
||||
struct PlayerList: View {
|
||||
/// Write access to the database
|
||||
@Environment(\.appDatabase) private var appDatabase
|
||||
|
||||
/// The players in the list
|
||||
var players: [Player]
|
||||
|
||||
var body: some View {
|
||||
List {
|
||||
ForEach(players) { player in
|
||||
NavigationLink(destination: editionView(for: player)) {
|
||||
PlayerRow(player: player)
|
||||
// Don't animate player update
|
||||
.animation(nil, value: player)
|
||||
}
|
||||
}
|
||||
.onDelete { offsets in
|
||||
let playerIds = offsets.compactMap { players[$0].id }
|
||||
Task {
|
||||
try? await appDatabase.deletePlayers(ids: playerIds)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Animate list updates
|
||||
.animation(.default, value: players)
|
||||
.listStyle(.plain)
|
||||
}
|
||||
|
||||
/// The view that edits a player in the list.
|
||||
private func editionView(for player: Player) -> some View {
|
||||
PlayerEditionView(player: player).navigationBarTitle(player.name)
|
||||
}
|
||||
}
|
||||
|
||||
private struct PlayerRow: View {
|
||||
var player: Player
|
||||
|
||||
var body: some View {
|
||||
HStack {
|
||||
Text(player.name)
|
||||
Spacer()
|
||||
Text("\(player.score) points").foregroundColor(.gray)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct PlayerList_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
NavigationView {
|
||||
PlayerList(players: [
|
||||
Player(id: 1, name: "Arthur", score: 100),
|
||||
Player(id: 2, name: "Barbara", score: 1000),
|
||||
])
|
||||
.navigationTitle("Preview")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
@testable import GRDBAsyncDemo
|
||||
|
||||
class AppDatabaseTests: XCTestCase {
|
||||
func test_database_schema() throws {
|
||||
// Given an empty database
|
||||
let dbQueue = DatabaseQueue()
|
||||
|
||||
// When we instantiate an AppDatabase
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// Then the player table exists, with id, name & score columns
|
||||
try dbQueue.read { db in
|
||||
try XCTAssert(db.tableExists("player"))
|
||||
let columns = try db.columns(in: "player")
|
||||
let columnNames = Set(columns.map { $0.name })
|
||||
XCTAssertEqual(columnNames, ["id", "name", "score"])
|
||||
}
|
||||
}
|
||||
|
||||
func test_savePlayer_inserts() async throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we save a new player
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try await appDatabase.savePlayer(&player)
|
||||
|
||||
// Then the player exists in the database
|
||||
try XCTAssertTrue(dbQueue.read(player.exists))
|
||||
}
|
||||
|
||||
func test_savePlayer_updates() async throws {
|
||||
// Given a players database that contains a player
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player = try await dbQueue.write { db in
|
||||
try Player(id: nil, name: "Arthur", score: 100).inserted(db)
|
||||
}
|
||||
|
||||
// When we modify and save the player
|
||||
player.name = "Barbara"
|
||||
player.score = 1000
|
||||
try await appDatabase.savePlayer(&player)
|
||||
|
||||
// Then the player has been updated in the database
|
||||
let fetchedPlayer = try await dbQueue.read { [player] db in
|
||||
try XCTUnwrap(Player.fetchOne(db, key: player.id))
|
||||
}
|
||||
XCTAssertEqual(fetchedPlayer, player)
|
||||
}
|
||||
|
||||
func test_deletePlayers() async throws {
|
||||
// Given a players database that contains four players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
let playerIds: [Int64] = try await dbQueue.write { db in
|
||||
_ = try Player(id: nil, name: "Arthur", score: 100).inserted(db)
|
||||
_ = try Player(id: nil, name: "Barbara", score: 200).inserted(db)
|
||||
_ = try Player(id: nil, name: "Craig", score: 150).inserted(db)
|
||||
_ = try Player(id: nil, name: "David", score: 120).inserted(db)
|
||||
return try Player.selectID().fetchAll(db)
|
||||
}
|
||||
|
||||
// When we delete two players
|
||||
let deletedId1 = playerIds[0]
|
||||
let deletedId2 = playerIds[2]
|
||||
try await appDatabase.deletePlayers(ids: [deletedId1, deletedId2])
|
||||
|
||||
// Then the deleted players no longer exist
|
||||
try await dbQueue.read { db in
|
||||
try XCTAssertFalse(Player.exists(db, id: deletedId1))
|
||||
try XCTAssertFalse(Player.exists(db, id: deletedId2))
|
||||
}
|
||||
|
||||
// Then the database still contains two players
|
||||
try XCTAssertEqual(dbQueue.read(Player.fetchCount), 2)
|
||||
}
|
||||
|
||||
func test_deleteAllPlayers() async throws {
|
||||
// Given a players database that contains players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
try await dbQueue.write { db in
|
||||
_ = try Player(id: nil, name: "Arthur", score: 100).inserted(db)
|
||||
_ = try Player(id: nil, name: "Barbara", score: 200).inserted(db)
|
||||
_ = try Player(id: nil, name: "Craig", score: 150).inserted(db)
|
||||
_ = try Player(id: nil, name: "David", score: 120).inserted(db)
|
||||
}
|
||||
|
||||
// When we delete all players
|
||||
try await appDatabase.deleteAllPlayers()
|
||||
|
||||
// Then the database does not contain any player
|
||||
try XCTAssertEqual(dbQueue.read(Player.fetchCount), 0)
|
||||
}
|
||||
|
||||
func test_refreshPlayers_populates_an_empty_database() async throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we refresh players
|
||||
try await appDatabase.refreshPlayers()
|
||||
|
||||
// Then the database is not empty
|
||||
try XCTAssert(dbQueue.read(Player.fetchCount) > 0)
|
||||
}
|
||||
|
||||
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we create random players
|
||||
try appDatabase.createRandomPlayersIfEmpty()
|
||||
|
||||
// Then the database is not empty
|
||||
try XCTAssert(dbQueue.read(Player.fetchCount) > 0)
|
||||
}
|
||||
|
||||
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
|
||||
// Given a players database that contains one player
|
||||
let dbQueue = DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try dbQueue.write { db in
|
||||
try player.insert(db)
|
||||
}
|
||||
|
||||
// When we create random players
|
||||
try appDatabase.createRandomPlayersIfEmpty()
|
||||
|
||||
// Then the database still only contains the original player
|
||||
let players = try dbQueue.read(Player.fetchAll)
|
||||
XCTAssertEqual(players, [player])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,43 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
@testable import GRDBAsyncDemo
|
||||
|
||||
class PlayerRequestTests: XCTestCase {
|
||||
func test_PlayerRequest_byName_fetches_well_ordered_players() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
}
|
||||
|
||||
// When we fetch players ordered by name
|
||||
let playerRequest = PlayerRequest(ordering: .byName)
|
||||
let players = try dbQueue.read(playerRequest.fetchValue)
|
||||
|
||||
// Then the players are the two players ordered by name
|
||||
XCTAssertEqual(players, [player1, player2])
|
||||
}
|
||||
|
||||
func test_PlayerRequest_byScore_fetches_well_ordered_players() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
}
|
||||
|
||||
// When we fetch players ordered by score
|
||||
let playerRequest = PlayerRequest(ordering: .byScore)
|
||||
let players = try dbQueue.read(playerRequest.fetchValue)
|
||||
|
||||
// Then the players are the two players ordered by score descending
|
||||
XCTAssertEqual(players, [player2, player1])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
@testable import GRDBAsyncDemo
|
||||
|
||||
class PlayerTests: XCTestCase {
|
||||
// MARK: - CRUD
|
||||
// Test that our Player type properly talks to GRDB.
|
||||
|
||||
func testInsert() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try dbQueue.write { db in
|
||||
try player.insert(db)
|
||||
}
|
||||
|
||||
// Then the player gets a non-nil id
|
||||
XCTAssertNotNil(player.id)
|
||||
}
|
||||
|
||||
func testRoundtrip() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player and fetch the player with the same id
|
||||
var insertedPlayer = Player(id: nil, name: "Arthur", score: 100)
|
||||
let fetchedPlayer: Player? = try dbQueue.write { db in
|
||||
try insertedPlayer.insert(db)
|
||||
return try Player.fetchOne(db, key: insertedPlayer.id)
|
||||
}
|
||||
|
||||
// Then the fetched player is equal to the inserted player
|
||||
XCTAssertEqual(insertedPlayer, fetchedPlayer)
|
||||
}
|
||||
|
||||
// MARK: - Requests
|
||||
// Test that requests defined on the Player type behave as expected.
|
||||
|
||||
func testOrderedByScore() throws {
|
||||
// Given a players database that contains players with distinct scores
|
||||
let dbQueue = DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
var player3 = Player(id: 3, name: "Craig", score: 150)
|
||||
var player4 = Player(id: 4, name: "David", score: 120)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
try player3.insert(db)
|
||||
try player4.insert(db)
|
||||
}
|
||||
|
||||
// When we fetch players ordered by score
|
||||
let players = try dbQueue.read(Player.all().orderedByScore().fetchAll)
|
||||
|
||||
// Then fetched players are ordered by score descending
|
||||
XCTAssertEqual(players, [player2, player3, player4, player1])
|
||||
}
|
||||
|
||||
func testOrderedByScoreSortsIdenticalScoresByName() throws {
|
||||
// Given a players database that contains players with common scores
|
||||
let dbQueue = DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
var player3 = Player(id: 3, name: "Craig", score: 200)
|
||||
var player4 = Player(id: 4, name: "David", score: 200)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
try player3.insert(db)
|
||||
try player4.insert(db)
|
||||
}
|
||||
|
||||
// When we fetch players ordered by score
|
||||
let players = try dbQueue.read(Player.all().orderedByScore().fetchAll)
|
||||
|
||||
// Then fetched players are ordered by score descending and by name
|
||||
XCTAssertEqual(players, [player2, player3, player4, player1])
|
||||
}
|
||||
|
||||
func testOrderedByName() throws {
|
||||
// Given a players database that contains players with distinct names
|
||||
let dbQueue = DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
var player3 = Player(id: 3, name: "Craig", score: 150)
|
||||
var player4 = Player(id: 4, name: "David", score: 120)
|
||||
try dbQueue.write { db in
|
||||
try player1.insert(db)
|
||||
try player2.insert(db)
|
||||
try player3.insert(db)
|
||||
try player4.insert(db)
|
||||
}
|
||||
|
||||
// When we fetch players ordered by name
|
||||
let players = try dbQueue.read(Player.all().orderedByName().fetchAll)
|
||||
|
||||
// Then fetched players are ordered by name
|
||||
XCTAssertEqual(players, [player1, player2, player3, player4])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
//
|
||||
// GRDBAsyncDemoUITests.swift
|
||||
// GRDBAsyncDemoUITests
|
||||
//
|
||||
// Created by Peter Steinberger on 08.04.21.
|
||||
//
|
||||
|
||||
import XCTest
|
||||
|
||||
class GRDBAsyncDemoUITests: XCTestCase {
|
||||
|
||||
override func setUpWithError() throws {
|
||||
// In UI tests it is usually best to stop immediately when a failure occurs.
|
||||
continueAfterFailure = false
|
||||
}
|
||||
|
||||
override func tearDownWithError() throws {
|
||||
}
|
||||
|
||||
func runApp() -> XCUIApplication {
|
||||
// UI tests must launch the application that they test.
|
||||
let app = XCUIApplication()
|
||||
// We enforce a fresh database to ensure 8 random players.
|
||||
app.launchArguments = ["-reset", "-fixedTestData"]
|
||||
app.launch()
|
||||
return app
|
||||
}
|
||||
|
||||
// This test, introduced in 481f6e93, tests the @Query fix added in
|
||||
// 68874412. The fix expresses itself when a view defines an @Query
|
||||
// property that is replaced in the view initializer, as in 481f6e93.
|
||||
//
|
||||
// It happens that I did not find that this particular view setup was suited
|
||||
// for a demo app. The demo has to find a delicate balance, not too trivial,
|
||||
// but without gratuitous complexity.
|
||||
//
|
||||
// I simplified the demo app in a5ffc52d, and we no longer have any view
|
||||
// that defines an @Query property which is replaced in the view
|
||||
// initializer. This means that this test no longer checks against
|
||||
// 68874412 regressions!
|
||||
//
|
||||
// Whenever the @Query property wrapper ships with GRDB itself, make sure
|
||||
// we test for those regressions!
|
||||
func testInitialSortingIsByScore() throws {
|
||||
let app = runApp()
|
||||
|
||||
let getFirstCell = { () -> XCUIElement in
|
||||
app.tables.element(boundBy: 0).cells.element(boundBy: 0)
|
||||
}
|
||||
|
||||
// Given default sorting, Henriette must be on top
|
||||
XCTAssertEqual(getFirstCell().label, "Craig, 8 points")
|
||||
|
||||
// Reverse sorting will bring Arthur on top (sort by name)
|
||||
app.buttons["Score"].tap()
|
||||
XCTAssertEqual(getFirstCell().label, "Arthur, 5 points")
|
||||
}
|
||||
|
||||
func testListAndAddPlayer() throws {
|
||||
let app = runApp()
|
||||
|
||||
// Ensure we have 8 players visible
|
||||
XCTAssert(app.tables.cells.count == 8)
|
||||
|
||||
// add a player
|
||||
app.buttons["New Player"].tap()
|
||||
|
||||
let playerNameField = app.textFields["Player Name"]
|
||||
playerNameField.tap()
|
||||
playerNameField.typeText("Tim Apple")
|
||||
|
||||
app.buttons["Save"].tap()
|
||||
|
||||
// This is suboptimal, but we need to wait for the animation to finish
|
||||
// A better way could be to disable animations globally,
|
||||
// and/or a hook to detect when the async fetch completes.
|
||||
sleep(2)
|
||||
|
||||
XCTAssert(app.tables.cells.count == 9)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,51 @@
|
||||
Async/Await + SwiftUI Demo Application
|
||||
======================================
|
||||
|
||||
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBCombineDemo/Screenshot.png" width="50%">
|
||||
|
||||
**This demo application is an Async/Await + SwiftUI application.** For a demo application that uses UIKit, see [GRDBDemoiOS](../GRDBDemoiOS/README.md), and for Combine + SwiftUI, see [GRDBCombineDemo](../GRDBCombineDemo/README.md).
|
||||
|
||||
**Requirements**: iOS 15.0+ / Xcode 13.1+
|
||||
|
||||
> :point_up: **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration.
|
||||
|
||||
The topics covered in this demo are:
|
||||
|
||||
- How to setup a database in an iOS app.
|
||||
- How to define a simple [Codable Record](../../../README.md#codable-records).
|
||||
- How to track database changes and animate a SwiftUI List with an async sequence built from [ValueObservation](../../../README.md#valueobservation).
|
||||
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
|
||||
- How to feed SwiftUI previews with a transient database.
|
||||
|
||||
**Files of interest:**
|
||||
|
||||
- [GRDBAsyncDemoApp.swift](GRDBAsyncDemo/GRDBAsyncDemoApp.swift)
|
||||
|
||||
`GRDBAsyncDemoApp` feeds the app views with a database, through the SwiftUI environment.
|
||||
|
||||
- [AppDatabase.swift](GRDBAsyncDemo/AppDatabase.swift)
|
||||
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema.
|
||||
|
||||
- [Persistence.swift](GRDBAsyncDemo/Persistence.swift)
|
||||
|
||||
This file instantiates various `AppDatabase` for the various projects needs: one database on disk for the application, and in-memory databases for SwiftUI previews.
|
||||
|
||||
- [Player.swift](GRDBAsyncDemo/Player.swift)
|
||||
|
||||
`Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records).
|
||||
|
||||
- [PlayerRequest.swift](GRDBAsyncDemo/PlayerRequest.swift), [AppView.swift](GRDBAsyncDemo/Views/AppView.swift)
|
||||
|
||||
`PlayerRequest` defines the player requests used by the app (sorted by score, or by name).
|
||||
|
||||
`PlayerRequest` feeds the `@Query` property wrapper (`@Query`, defined in [GRDBQuery](https://github.com/groue/GRDBQuery), allows SwiftUI views to display up-to-date database content).
|
||||
|
||||
`AppView` is the SwiftUI view that uses `@Query` in order to feed its player list.
|
||||
|
||||
- [GRDBAsyncDemoTests](GRDBAsyncDemoTests)
|
||||
|
||||
- Test the database schema
|
||||
- Test the `Player` record and its requests
|
||||
- Test the `PlayerRequest` methods that feed the list of players.
|
||||
- Test the `AppDatabase` methods that let the app access the database.
|
||||
|
After Width: | Height: | Size: 799 KiB |
@@ -3,7 +3,7 @@ Combine + SwiftUI Demo Application
|
||||
|
||||
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBCombineDemo/Screenshot.png" width="50%">
|
||||
|
||||
**This demo application is a Combine + SwiftUI application.** For a demo application that uses UIKit, see [GRDBDemoiOS](../GRDBDemoiOS/README.md).
|
||||
**This demo application is a Combine + SwiftUI application.** For a demo application that uses UIKit, see [GRDBDemoiOS](../GRDBDemoiOS/README.md), and for Async/Await + SwiftUI, see [GRDBAsyncDemo](../GRDBAsyncDemo/README.md).
|
||||
|
||||
**Requirements**: iOS 15.0+ / Xcode 12+
|
||||
|
||||
|
||||
@@ -78,10 +78,8 @@
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<RemoteRunnable
|
||||
runnableDebuggingMode = "2"
|
||||
BundleIdentifier = "com.apple.Carousel"
|
||||
RemotePath = "/GRDBDemoiOS">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
@@ -89,7 +87,7 @@
|
||||
BlueprintName = "GRDBDemoWatchOS"
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</RemoteRunnable>
|
||||
</BuildableProductRunnable>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
@@ -97,10 +95,8 @@
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<RemoteRunnable
|
||||
runnableDebuggingMode = "2"
|
||||
BundleIdentifier = "com.apple.Carousel"
|
||||
RemotePath = "/GRDBDemoiOS">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "568E5FBE1E926430002582E0"
|
||||
@@ -108,16 +104,7 @@
|
||||
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>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
|
||||
@@ -3,7 +3,7 @@ UIKit Demo Application
|
||||
|
||||
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBDemoiOS/Screenshot.png" width="50%">
|
||||
|
||||
**This demo application is a storyboard-based UIKit application.** For a demo application that uses Combine + SwiftUI, see [GRDBCombineDemo](../GRDBCombineDemo/README.md).
|
||||
**This demo application is a storyboard-based UIKit application.** For a demo application that uses Combine + SwiftUI, see [GRDBCombineDemo](../GRDBCombineDemo/README.md), and for Async/Await + SwiftUI, see [GRDBAsyncDemo](../GRDBAsyncDemo/README.md).
|
||||
|
||||
**Requirements**: iOS 15.0+ / Xcode 12+
|
||||
|
||||
|
||||
@@ -3,9 +3,11 @@ Demo Applications
|
||||
|
||||
- [GRDBDemoiOS]: a storyboard-based UIKit application.
|
||||
- [GRDBCombineDemo]: a Combine + SwiftUI application.
|
||||
- [GRDBAsyncDemo]: a Async/Await + SwiftUI application.
|
||||
|
||||
[GRDBCombineDemo] uses the `@Query` property wrapper, that lets SwiftUI views automatically update their content when the database changes. It is defined in the [GRDBQuery] package.
|
||||
[GRDBCombineDemo] and [GRDBAsyncDemo] use the same `@Query` property wrapper, that lets SwiftUI views automatically update their content when the database changes. It is defined in the [GRDBQuery] package.
|
||||
|
||||
[GRDBDemoiOS]: GRDBDemoiOS
|
||||
[GRDBCombineDemo]: GRDBCombineDemo
|
||||
[GRDBAsyncDemo]: GRDBAsyncDemo
|
||||
[GRDBQuery]: https://github.com/groue/GRDBQuery
|
||||
@@ -304,7 +304,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.14/Structs/StatementArguments.html):
|
||||
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -587,7 +587,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.14/Structs/StatementArguments.html):
|
||||
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -737,11 +737,11 @@ The SQLite built-in tokenizers for [FTS3, FTS4](#fts3-and-fts4-tokenizers) and [
|
||||
|
||||
Generally speaking, matches may fail when content and query don't use the same [unicode normalization](http://unicode.org/reports/tr15/). SQLite actually exhibits inconsistent behavior in this regard.
|
||||
|
||||
For example, for "aimé" to match "aimé", they better have the same normalization: the NFC "aim\u{00E9}" form may not match its NFD "aime\u{0301}" equivalent. Most strings that you get from Swift, UIKit and Cocoa use NFC, so be careful with NFD inputs (such as strings from the HFS+ file system, or strings that you can't trust like network inputs). Use [String.precomposedStringWithCanonicalMapping](https://developer.apple.com/reference/swift/string/1407210-precomposedstringwithcanonicalma) to turn a string into NFC.
|
||||
For example, for "aimé" to match "aimé", they better have the same normalization: the NFC "aim\u{00E9}" form may not match its NFD "aime\u{0301}" equivalent. Most strings that you get from Swift, UIKit and Cocoa use NFC, so be careful with NFD inputs (such as strings from the HFS+ file system, or strings that you can't trust like network inputs). Use [String.precomposedStringWithCanonicalMapping](https://developer.apple.com/documentation/foundation/nsstring/1412645-precomposedstringwithcanonicalma) to turn a string into NFC.
|
||||
|
||||
Besides, if you want "fi" to match the ligature "fi" (U+FB01), then you need to normalize your indexed contents and inputs to NFKC or NFKD. Use [String.precomposedStringWithCompatibilityMapping](https://developer.apple.com/reference/swift/string/1407834-precomposedstringwithcompatibili) to turn a string into NFKC.
|
||||
Besides, if you want "fi" to match the ligature "fi" (U+FB01), then you need to normalize your indexed contents and inputs to NFKC or NFKD. Use [String.precomposedStringWithCompatibilityMapping](https://developer.apple.com/documentation/foundation/nsstring/1412625-precomposedstringwithcompatibili) to turn a string into NFKC.
|
||||
|
||||
Unicode normalization is not the end of the story, because it won't help "Encyclopaedia" match "Encyclopædia", "Mueller", "Müller", "Grossmann", "Großmann", or "Diyarbakır", "DIYARBAKIR". The [String.applyingTransform](https://developer.apple.com/reference/swift/string/1643133-applyingtransform) method can help.
|
||||
Unicode normalization is not the end of the story, because it won't help "Encyclopaedia" match "Encyclopædia", "Mueller", "Müller", "Grossmann", "Großmann", or "Diyarbakır", "DIYARBAKIR". The [String.applyingTransform](https://developer.apple.com/documentation/foundation/nsstring/1407787-applyingtransform) method can help.
|
||||
|
||||
GRDB lets you write [custom FTS5 tokenizers](FTS5Tokenizers.md) that can transparently deal with all these issues. For FTS3 and FTS4, you'll need to pre-process your strings before injecting them in the full-text engine.
|
||||
|
||||
|
||||
@@ -422,7 +422,7 @@ let publisher = observation
|
||||
}
|
||||
```
|
||||
|
||||
6. The `TableRecord.selectionSQL()` method is no longer avaible. When you need to embed the columns selected by a record type in an SQL request, you now have to use [SQL Interpolation]:
|
||||
6. The `TableRecord.selectionSQL()` method is no longer available. When you need to embed the columns selected by a record type in an SQL request, you now have to use [SQL Interpolation]:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
|
||||
@@ -543,7 +543,7 @@ Those properties provide an alternative way to feed our application:
|
||||
|
||||
## How to Design Database Managers
|
||||
|
||||
Many developpers want to hide GRDB database queues and pools inside "database managers":
|
||||
Many developers want to hide GRDB database queues and pools inside "database managers":
|
||||
|
||||
```swift
|
||||
// LibraryManager grants access to the library database.
|
||||
|
||||
@@ -77,7 +77,7 @@ try dbQueue.read { db in
|
||||
}
|
||||
```
|
||||
|
||||
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.14/Structs/DatabaseMigrator.html) for more migrator methods.
|
||||
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.26/Structs/DatabaseMigrator.html) for more migrator methods.
|
||||
|
||||
|
||||
## The `eraseDatabaseOnSchemaChange` Option
|
||||
@@ -268,7 +268,7 @@ while let violation = try violations.next() {
|
||||
|
||||
## Asynchronous Migrations
|
||||
|
||||
`DatabaseMigrator` provides two ways to migrate a database in an asynchronous way.
|
||||
`DatabaseMigrator` provides the following ways to migrate a database in an asynchronous way.
|
||||
|
||||
The `asyncMigrate(_:completion:)` method:
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ import GRDB
|
||||
//: This playground demonstrates how one can implement **customized decoding of
|
||||
//: database rows**.
|
||||
//:
|
||||
//: Customized row decoding allows you to go beyong the built-in support for
|
||||
//: Customized row decoding allows you to go beyond the built-in support for
|
||||
//: requests of raw rows, values, or types that adopt the
|
||||
//: FetchableRecord protocol.
|
||||
//:
|
||||
@@ -116,7 +116,7 @@ extension Base {
|
||||
//: example, we could fetch all Base values from the database:
|
||||
//:
|
||||
//: try dbQueue.read { db in
|
||||
//: // An array [Base] that constains Foo and Bar instances
|
||||
//: // An array [Base] that contains Foo and Bar instances
|
||||
//: let bases = try Base.fetchAll(db)
|
||||
//: }
|
||||
//:
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
import GRDB
|
||||
|
||||
|
||||
// Create the databsae
|
||||
// Create the database
|
||||
|
||||
let dbQueue = DatabaseQueue() // Memory database
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
@@ -22,7 +22,7 @@ To release a new GRDB version:
|
||||
- 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 master & development branch
|
||||
- `pod trunk push --allow-warnings GRDB.swift.podspec`
|
||||
- `make doc`, and update index.html in the `gh-pages` branch
|
||||
- Update http://github.com/groue/WWDCCompanion
|
||||
|
||||
@@ -37,7 +37,7 @@ try db.create(table: "appConfiguration") { t in
|
||||
// Make sure the id column is always 1
|
||||
.check { $0 == 1 }
|
||||
|
||||
// The configuration colums
|
||||
// The configuration columns
|
||||
t.column("flag", .boolean).notNull()
|
||||
// ... other columns
|
||||
}
|
||||
@@ -78,7 +78,7 @@ migrator.registerMigration("appConfiguration") { db in
|
||||
// Single row guarantee
|
||||
t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 }
|
||||
|
||||
// The configuration colums
|
||||
// The configuration columns
|
||||
t.column("flag", .boolean).notNull()
|
||||
// ... other columns
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '5.14.0'
|
||||
s.version = '5.26.1'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -7,6 +7,13 @@
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
4E13D2F32769B87F0037588C /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */; };
|
||||
4E13D2F42769B87F0037588C /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */; };
|
||||
4E13D2F52769B87F0037588C /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */; };
|
||||
4E13D2F62769B87F0037588C /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */; };
|
||||
4ED4BB592731DD25008B127D /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB582731DD25008B127D /* BackupTestCase.swift */; };
|
||||
4ED4BB5A2731DD25008B127D /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB582731DD25008B127D /* BackupTestCase.swift */; };
|
||||
4ED4BB5B2731DD25008B127D /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB582731DD25008B127D /* BackupTestCase.swift */; };
|
||||
56012B552573EED000B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */; };
|
||||
56012B562573EED100B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */; };
|
||||
56012B572573EED100B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */; };
|
||||
@@ -280,9 +287,9 @@
|
||||
564448831EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
|
||||
564448871EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
|
||||
564A50C81BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */; };
|
||||
564CE43121AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
|
||||
564CE43221AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
|
||||
564CE43321AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
|
||||
564CE43121AA901800652B19 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */; };
|
||||
564CE43221AA901800652B19 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */; };
|
||||
564CE43321AA901800652B19 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */; };
|
||||
564CE4E921B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; };
|
||||
564CE4EA21B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; };
|
||||
564CE59D21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* RemoveDuplicates.swift */; };
|
||||
@@ -532,6 +539,10 @@
|
||||
56781B0C243F86E600650A83 /* Refinable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56781B0A243F86E600650A83 /* Refinable.swift */; };
|
||||
56781B0D243F86E600650A83 /* Refinable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56781B0A243F86E600650A83 /* Refinable.swift */; };
|
||||
56781B0E243F86E600650A83 /* Refinable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56781B0A243F86E600650A83 /* Refinable.swift */; };
|
||||
5679533327E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */; };
|
||||
5679533427E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */; };
|
||||
5679533527E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */; };
|
||||
5679533627E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */; };
|
||||
567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; };
|
||||
567DAF1C1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
|
||||
567DAF1F1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
|
||||
@@ -722,6 +733,10 @@
|
||||
56B14E831D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; };
|
||||
56B6EF56208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */; };
|
||||
56B6EF57208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */; };
|
||||
56B7EE832863781300C0525F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7EE822863781300C0525F /* WALSnapshot.swift */; };
|
||||
56B7EE842863781300C0525F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7EE822863781300C0525F /* WALSnapshot.swift */; };
|
||||
56B7EE852863781300C0525F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7EE822863781300C0525F /* WALSnapshot.swift */; };
|
||||
56B7EE862863781300C0525F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7EE822863781300C0525F /* WALSnapshot.swift */; };
|
||||
56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; };
|
||||
56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; };
|
||||
56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; };
|
||||
@@ -913,6 +928,9 @@
|
||||
56F5ABDA1D814330001F60CB /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; };
|
||||
56F5ABDC1D814330001F60CB /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; };
|
||||
56F5ABDD1D814330001F60CB /* UUID.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C22F1D1914540096E9D4 /* UUID.swift */; };
|
||||
56F61DD5283D344E00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DD4283D344E00AF9884 /* getThreadsCount.c */; };
|
||||
56F61DD6283D344E00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DD4283D344E00AF9884 /* getThreadsCount.c */; };
|
||||
56F61DD7283D344E00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DD4283D344E00AF9884 /* getThreadsCount.c */; };
|
||||
56FBFED92210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
|
||||
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
|
||||
56FBFEDB2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
|
||||
@@ -942,7 +960,7 @@
|
||||
AAA4DC85230F1E0600C74B15 /* Column.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5401EAA359A00BFAF62 /* Column.swift */; };
|
||||
AAA4DC87230F1E0600C74B15 /* Date.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F14F1C672E4000235C62 /* Date.swift */; };
|
||||
AAA4DC89230F1E0600C74B15 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
|
||||
AAA4DC8A230F1E0600C74B15 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
|
||||
AAA4DC8A230F1E0600C74B15 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */; };
|
||||
AAA4DC8B230F1E0600C74B15 /* Fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AACAA722ACED7100A40F2A /* Fetch.swift */; };
|
||||
AAA4DC8C230F1E0600C74B15 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */; };
|
||||
AAA4DC8D230F1E0600C74B15 /* FTS3+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterface.swift */; };
|
||||
@@ -1266,6 +1284,8 @@
|
||||
/* End PBXContainerItemProxy section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseBackupProgress.swift; sourceTree = "<group>"; };
|
||||
4ED4BB582731DD25008B127D /* BackupTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BackupTestCase.swift; sourceTree = "<group>"; };
|
||||
56012B542573EED000B4925B /* CommonTableExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpressionTests.swift; sourceTree = "<group>"; };
|
||||
56012B742574048B00B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = "<group>"; };
|
||||
560233C32724234F00529DF3 /* SharedValueObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservation.swift; sourceTree = "<group>"; };
|
||||
@@ -1376,7 +1396,7 @@
|
||||
5643676D272EDF2400C718C7 /* Scripts */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Scripts; sourceTree = "<group>"; };
|
||||
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
|
||||
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
|
||||
564CE43021AA901800652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = "<group>"; };
|
||||
564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueConcurrentObserver.swift; sourceTree = "<group>"; };
|
||||
564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = "<group>"; };
|
||||
564CE59621B7A8B500652B19 /* RemoveDuplicates.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RemoveDuplicates.swift; sourceTree = "<group>"; };
|
||||
564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = "<group>"; };
|
||||
@@ -1471,6 +1491,7 @@
|
||||
5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchableRecordDecodableTests.swift; sourceTree = "<group>"; };
|
||||
5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = "<group>"; };
|
||||
56781B0A243F86E600650A83 /* Refinable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Refinable.swift; sourceTree = "<group>"; };
|
||||
5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueWriteOnlyObserver.swift; sourceTree = "<group>"; };
|
||||
567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = "<group>"; };
|
||||
567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = "<group>"; };
|
||||
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1578,6 +1599,7 @@
|
||||
56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = "<group>"; };
|
||||
56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = "<group>"; };
|
||||
56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = "<group>"; };
|
||||
56B7EE822863781300C0525F /* WALSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshot.swift; sourceTree = "<group>"; };
|
||||
56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = "<group>"; };
|
||||
56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = "<group>"; };
|
||||
56B86E72220FF4E000524C16 /* SQLLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLLiteralTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1632,6 +1654,9 @@
|
||||
56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLExpressionIsConstantTests.swift; sourceTree = "<group>"; };
|
||||
56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLIdentifyingColumnsTests.swift; sourceTree = "<group>"; };
|
||||
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = "<group>"; };
|
||||
56F61DD0283D344D00AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "GRDBTests-Bridging-Header.h"; path = "GRDBTests/GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
|
||||
56F61DD3283D344E00AF9884 /* getThreadsCount.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = getThreadsCount.h; sourceTree = "<group>"; };
|
||||
56F61DD4283D344E00AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
|
||||
56FBFED82210731A00945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = "<group>"; };
|
||||
56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = "<group>"; };
|
||||
56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseTraceTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1782,6 +1807,8 @@
|
||||
569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */,
|
||||
56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */,
|
||||
563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */,
|
||||
56F61DD3283D344E00AF9884 /* getThreadsCount.h */,
|
||||
56F61DD4283D344E00AF9884 /* getThreadsCount.c */,
|
||||
);
|
||||
name = DatabasePool;
|
||||
sourceTree = "<group>";
|
||||
@@ -1806,9 +1833,10 @@
|
||||
children = (
|
||||
563082E32430B6BE00C14A05 /* DatabaseCancellable.swift */,
|
||||
560233C32724234F00529DF3 /* SharedValueObservation.swift */,
|
||||
564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */,
|
||||
563B06AA217EF0CC00B38F35 /* ValueObservation.swift */,
|
||||
56848972242DE36F002F9702 /* ValueObservationScheduler.swift */,
|
||||
564CE43021AA901800652B19 /* ValueObserver.swift */,
|
||||
5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */,
|
||||
56AACAA022ACEC9700A40F2A /* ValueReducer */,
|
||||
);
|
||||
path = ValueObservation;
|
||||
@@ -2218,6 +2246,7 @@
|
||||
56A238111B9C74A90082EB20 /* Core */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
4ED4BB582731DD25008B127D /* BackupTestCase.swift */,
|
||||
5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */,
|
||||
56DAA2C41DE99D8D006E10C8 /* Cursor */,
|
||||
56E4F7ED2392E2D000A611F6 /* DatabaseAbortedTransactionTests.swift */,
|
||||
@@ -2324,6 +2353,7 @@
|
||||
56A238711B9C75030082EB20 /* Database.swift */,
|
||||
566B91221FA4CF810012D5B0 /* Database+Schema.swift */,
|
||||
566B91081FA4C3960012D5B0 /* Database+Statements.swift */,
|
||||
4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */,
|
||||
566B91121FA4C3F50012D5B0 /* DatabaseCollation.swift */,
|
||||
56A238731B9C75030082EB20 /* DatabaseError.swift */,
|
||||
564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */,
|
||||
@@ -2351,6 +2381,7 @@
|
||||
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
|
||||
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
|
||||
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
|
||||
56B7EE822863781300C0525F /* WALSnapshot.swift */,
|
||||
5605F1471C672E4000235C62 /* Support */,
|
||||
);
|
||||
path = Core;
|
||||
@@ -2485,6 +2516,7 @@
|
||||
DC37740319C8CBB3004FCF85 /* Supporting Files */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56F61DD0283D344D00AF9884 /* GRDBTests-Bridging-Header.h */,
|
||||
DC37740419C8CBB3004FCF85 /* Info.plist */,
|
||||
);
|
||||
name = "Supporting Files";
|
||||
@@ -2572,9 +2604,9 @@
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 565490B31D5A4798005622CB /* Build configuration list for PBXNativeTarget "GRDBWatchOS" */;
|
||||
buildPhases = (
|
||||
5654909D1D5A4798005622CB /* Headers */,
|
||||
5654909B1D5A4798005622CB /* Sources */,
|
||||
5654909C1D5A4798005622CB /* Frameworks */,
|
||||
5654909D1D5A4798005622CB /* Headers */,
|
||||
5654909E1D5A4798005622CB /* Resources */,
|
||||
);
|
||||
buildRules = (
|
||||
@@ -2608,9 +2640,9 @@
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 56E5D7DB1B4D3FEE00430942 /* Build configuration list for PBXNativeTarget "GRDBiOS" */;
|
||||
buildPhases = (
|
||||
56E5D7C71B4D3FED00430942 /* Headers */,
|
||||
56E5D7C51B4D3FED00430942 /* Sources */,
|
||||
56E5D7C61B4D3FED00430942 /* Frameworks */,
|
||||
56E5D7C71B4D3FED00430942 /* Headers */,
|
||||
56E5D7C81B4D3FED00430942 /* Resources */,
|
||||
56EB54FA22C9115E00850069 /* Swiftlint */,
|
||||
);
|
||||
@@ -2663,9 +2695,9 @@
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = AAA4DCFB230F1E0600C74B15 /* Build configuration list for PBXNativeTarget "GRDBtvOS" */;
|
||||
buildPhases = (
|
||||
AAA4DCF5230F1E0600C74B15 /* Headers */,
|
||||
AAA4DC76230F1E0600C74B15 /* Sources */,
|
||||
AAA4DCF4230F1E0600C74B15 /* Frameworks */,
|
||||
AAA4DCF5230F1E0600C74B15 /* Headers */,
|
||||
AAA4DCF9230F1E0600C74B15 /* Resources */,
|
||||
AAA4DCFA230F1E0600C74B15 /* Swiftlint */,
|
||||
);
|
||||
@@ -2700,9 +2732,9 @@
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = DC37740919C8CBB3004FCF85 /* Build configuration list for PBXNativeTarget "GRDBOSX" */;
|
||||
buildPhases = (
|
||||
DC3773F019C8CBB3004FCF85 /* Headers */,
|
||||
DC3773EE19C8CBB3004FCF85 /* Sources */,
|
||||
DC3773EF19C8CBB3004FCF85 /* Frameworks */,
|
||||
DC3773F019C8CBB3004FCF85 /* Headers */,
|
||||
DC3773F119C8CBB3004FCF85 /* Resources */,
|
||||
56EB54F322C8ED5100850069 /* Swiftlint */,
|
||||
);
|
||||
@@ -2735,17 +2767,18 @@
|
||||
};
|
||||
56E5D7D21B4D3FEE00430942 = {
|
||||
CreatedOnToolsVersion = 7.0;
|
||||
LastSwiftMigration = 1130;
|
||||
LastSwiftMigration = 1340;
|
||||
ProvisioningStyle = Manual;
|
||||
};
|
||||
56E5D7F81B4D422D00430942 = {
|
||||
CreatedOnToolsVersion = 7.0;
|
||||
LastSwiftMigration = 1020;
|
||||
LastSwiftMigration = 1340;
|
||||
};
|
||||
AAA4DC75230F1E0600C74B15 = {
|
||||
ProvisioningStyle = Manual;
|
||||
};
|
||||
AAA4DD07230F262000C74B15 = {
|
||||
LastSwiftMigration = 1340;
|
||||
ProvisioningStyle = Manual;
|
||||
};
|
||||
DC3773F219C8CBB3004FCF85 = {
|
||||
@@ -2847,6 +2880,7 @@
|
||||
/* Begin PBXShellScriptBuildPhase section */
|
||||
56EB54F322C8ED5100850069 /* Swiftlint */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
alwaysOutOfDate = 1;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
@@ -2861,10 +2895,11 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "${PROJECT_DIR}/Scripts/swiftlint.sh\n";
|
||||
shellScript = "\"${PROJECT_DIR}/Scripts/swiftlint.sh\"\n";
|
||||
};
|
||||
56EB54FA22C9115E00850069 /* Swiftlint */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
alwaysOutOfDate = 1;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
@@ -2879,10 +2914,11 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "${PROJECT_DIR}/Scripts/swiftlint.sh\n";
|
||||
shellScript = "\"${PROJECT_DIR}/Scripts/swiftlint.sh\"\n";
|
||||
};
|
||||
AAA4DCFA230F1E0600C74B15 /* Swiftlint */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
alwaysOutOfDate = 1;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
@@ -2897,7 +2933,7 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "${PROJECT_DIR}/Scripts/swiftlint.sh\n";
|
||||
shellScript = "\"${PROJECT_DIR}/Scripts/swiftlint.sh\"\n";
|
||||
};
|
||||
/* End PBXShellScriptBuildPhase section */
|
||||
|
||||
@@ -2913,6 +2949,7 @@
|
||||
565490CE1D5AE252005622CB /* NSNull.swift in Sources */,
|
||||
5656A8202295B12F001FF3FF /* SQLAssociation.swift in Sources */,
|
||||
565490E41D5AE252005622CB /* TableRecord.swift in Sources */,
|
||||
4E13D2F52769B87F0037588C /* DatabaseBackupProgress.swift in Sources */,
|
||||
564CE5AE21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
|
||||
565490CF1D5AE252005622CB /* NSNumber.swift in Sources */,
|
||||
56CEB51F1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */,
|
||||
@@ -2931,11 +2968,12 @@
|
||||
564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */,
|
||||
5659F4961EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
|
||||
56894FD12606589C00268F4D /* Decimal.swift in Sources */,
|
||||
5679533527E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */,
|
||||
56172950223533F40006E219 /* EncodableRecord.swift in Sources */,
|
||||
56AE64142229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */,
|
||||
5613ED3721A95A5C00DC7A68 /* Map.swift in Sources */,
|
||||
5659F48E1EA8D94E004A4992 /* Utils.swift in Sources */,
|
||||
564CE43321AA901800652B19 /* ValueObserver.swift in Sources */,
|
||||
564CE43321AA901800652B19 /* ValueConcurrentObserver.swift in Sources */,
|
||||
563B8FC724A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
566B9C2225C6CC24004542CF /* RowDecodingError.swift in Sources */,
|
||||
565490B91D5AE236005622CB /* DatabasePool.swift in Sources */,
|
||||
@@ -2944,6 +2982,7 @@
|
||||
565490D81D5AE252005622CB /* DatabaseMigrator.swift in Sources */,
|
||||
5656A8AF2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */,
|
||||
565490C21D5AE236005622CB /* Row.swift in Sources */,
|
||||
56B7EE852863781300C0525F /* WALSnapshot.swift in Sources */,
|
||||
565490C71D5AE236005622CB /* StatementColumnConvertible.swift in Sources */,
|
||||
565490D91D5AE252005622CB /* Migration.swift in Sources */,
|
||||
56CEB5001EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
|
||||
@@ -3082,7 +3121,7 @@
|
||||
56CEB5481EAA359A00BFAF62 /* Column.swift in Sources */,
|
||||
5605F1641C672E4000235C62 /* Date.swift in Sources */,
|
||||
566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
564CE43221AA901800652B19 /* ValueObserver.swift in Sources */,
|
||||
564CE43221AA901800652B19 /* ValueConcurrentObserver.swift in Sources */,
|
||||
568ECA8B25D7013000B71526 /* SQLSelection.swift in Sources */,
|
||||
56AACAA922ACED7100A40F2A /* Fetch.swift in Sources */,
|
||||
5605F1721C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
|
||||
@@ -3113,9 +3152,11 @@
|
||||
5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
|
||||
56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
|
||||
56DDDDF5242F87C60025E381 /* ValueObservationScheduler.swift in Sources */,
|
||||
56B7EE842863781300C0525F /* WALSnapshot.swift in Sources */,
|
||||
560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */,
|
||||
56A2FA3B24424F4700E97D23 /* Export.swift in Sources */,
|
||||
569BBA4F229170F900478429 /* Inflections+English.swift in Sources */,
|
||||
4E13D2F42769B87F0037588C /* DatabaseBackupProgress.swift in Sources */,
|
||||
5656A81F2295B12F001FF3FF /* SQLAssociation.swift in Sources */,
|
||||
5617294F223533F40006E219 /* EncodableRecord.swift in Sources */,
|
||||
563B8FAD24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */,
|
||||
@@ -3166,6 +3207,7 @@
|
||||
C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */,
|
||||
5605F1681C672E4000235C62 /* NSNumber.swift in Sources */,
|
||||
564CE5AD21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
|
||||
5679533427E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */,
|
||||
56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
|
||||
563B8F93249E6171007A48C9 /* Trace.swift in Sources */,
|
||||
5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */,
|
||||
@@ -3347,6 +3389,7 @@
|
||||
563B8FA2249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */,
|
||||
56A238581B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
|
||||
56A5EF131EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */,
|
||||
4ED4BB5A2731DD25008B127D /* BackupTestCase.swift in Sources */,
|
||||
5653EAE920944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */,
|
||||
5698ACD21DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */,
|
||||
561CFA7923735016000C8BAA /* TableRecordUpdateTests.swift in Sources */,
|
||||
@@ -3410,6 +3453,7 @@
|
||||
56A2383A1B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift in Sources */,
|
||||
56A5E40A1BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift in Sources */,
|
||||
56677C1A241D217F0050755D /* ValueObservationRecorderTests.swift in Sources */,
|
||||
56F61DD6283D344E00AF9884 /* getThreadsCount.c in Sources */,
|
||||
5653EAF520944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */,
|
||||
563B06BE2185CCD300B38F35 /* ValueObservationTests.swift in Sources */,
|
||||
56FF455A1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */,
|
||||
@@ -3581,6 +3625,7 @@
|
||||
5665FA332129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
|
||||
563B8FA1249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */,
|
||||
56CC9246201E058100CB597E /* DropFirstCursorTests.swift in Sources */,
|
||||
4ED4BB592731DD25008B127D /* BackupTestCase.swift in Sources */,
|
||||
5698AC401DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */,
|
||||
562393571DEE013C00A6B01F /* FilterCursorTests.swift in Sources */,
|
||||
5653EAE820944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */,
|
||||
@@ -3644,6 +3689,7 @@
|
||||
56DF001D228DDBA300D611F3 /* AssociationPrefetchingCodableRecordTests.swift in Sources */,
|
||||
5653EAD820944B4F00F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */,
|
||||
562205F11E420E47005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */,
|
||||
56F61DD5283D344E00AF9884 /* getThreadsCount.c in Sources */,
|
||||
56677C19241D217F0050755D /* ValueObservationRecorderTests.swift in Sources */,
|
||||
5653EAF420944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */,
|
||||
563B06BD2185CCD300B38F35 /* ValueObservationTests.swift in Sources */,
|
||||
@@ -3684,7 +3730,7 @@
|
||||
AAA4DC85230F1E0600C74B15 /* Column.swift in Sources */,
|
||||
AAA4DC87230F1E0600C74B15 /* Date.swift in Sources */,
|
||||
AAA4DC89230F1E0600C74B15 /* TransactionObserver.swift in Sources */,
|
||||
AAA4DC8A230F1E0600C74B15 /* ValueObserver.swift in Sources */,
|
||||
AAA4DC8A230F1E0600C74B15 /* ValueConcurrentObserver.swift in Sources */,
|
||||
568ECA8D25D7013000B71526 /* SQLSelection.swift in Sources */,
|
||||
AAA4DC8B230F1E0600C74B15 /* Fetch.swift in Sources */,
|
||||
AAA4DC8C230F1E0600C74B15 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
|
||||
@@ -3715,9 +3761,11 @@
|
||||
AAA4DCA5230F1E0600C74B15 /* FTS3TokenizerDescriptor.swift in Sources */,
|
||||
AAA4DCA6230F1E0600C74B15 /* FetchableRecord+TableRecord.swift in Sources */,
|
||||
56DDDDF7242F87C70025E381 /* ValueObservationScheduler.swift in Sources */,
|
||||
56B7EE862863781300C0525F /* WALSnapshot.swift in Sources */,
|
||||
AAA4DCA7230F1E0600C74B15 /* TableRecord.swift in Sources */,
|
||||
56A2FA3D24424F4800E97D23 /* Export.swift in Sources */,
|
||||
AAA4DCA8230F1E0600C74B15 /* Inflections+English.swift in Sources */,
|
||||
4E13D2F62769B87F0037588C /* DatabaseBackupProgress.swift in Sources */,
|
||||
AAA4DCA9230F1E0600C74B15 /* SQLAssociation.swift in Sources */,
|
||||
AAA4DCAA230F1E0600C74B15 /* EncodableRecord.swift in Sources */,
|
||||
563B8FAF24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */,
|
||||
@@ -3768,6 +3816,7 @@
|
||||
AAA4DCD8230F1E0600C74B15 /* SQLiteDateParser.swift in Sources */,
|
||||
AAA4DCD9230F1E0600C74B15 /* NSNumber.swift in Sources */,
|
||||
AAA4DCDB230F1E0600C74B15 /* DatabaseRegionObservation.swift in Sources */,
|
||||
5679533627E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */,
|
||||
AAA4DCDC230F1E0600C74B15 /* FTS4.swift in Sources */,
|
||||
563B8F95249E6171007A48C9 /* Trace.swift in Sources */,
|
||||
AAA4DCDD230F1E0600C74B15 /* StandardLibrary.swift in Sources */,
|
||||
@@ -3949,6 +3998,7 @@
|
||||
563B8FA3249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */,
|
||||
AAA4DD8A230F262000C74B15 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
|
||||
AAA4DD8B230F262000C74B15 /* ForeignKeyInfoTests.swift in Sources */,
|
||||
4ED4BB5B2731DD25008B127D /* BackupTestCase.swift in Sources */,
|
||||
AAA4DD8C230F262000C74B15 /* AssociationChainSQLTests.swift in Sources */,
|
||||
AAA4DD8D230F262000C74B15 /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */,
|
||||
561CFA7A23735016000C8BAA /* TableRecordUpdateTests.swift in Sources */,
|
||||
@@ -4012,6 +4062,7 @@
|
||||
AAA4DDC0230F262000C74B15 /* DatabaseQueueInMemoryTests.swift in Sources */,
|
||||
AAA4DDC1230F262000C74B15 /* RecordWithColumnNameManglingTests.swift in Sources */,
|
||||
56677C1B241D217F0050755D /* ValueObservationRecorderTests.swift in Sources */,
|
||||
56F61DD7283D344E00AF9884 /* getThreadsCount.c in Sources */,
|
||||
AAA4DDC2230F262000C74B15 /* AssociationParallelSQLTests.swift in Sources */,
|
||||
AAA4DDC3230F262000C74B15 /* ValueObservationTests.swift in Sources */,
|
||||
AAA4DDC4230F262000C74B15 /* RecordUniqueIndexTests.swift in Sources */,
|
||||
@@ -4083,9 +4134,11 @@
|
||||
569BBA4E229170F800478429 /* Inflections+English.swift in Sources */,
|
||||
5656A81E2295B12F001FF3FF /* SQLAssociation.swift in Sources */,
|
||||
5617294E223533F40006E219 /* EncodableRecord.swift in Sources */,
|
||||
56B7EE832863781300C0525F /* WALSnapshot.swift in Sources */,
|
||||
5698AD181DAAD17A0056AF8C /* FTS5Tokenizer.swift in Sources */,
|
||||
56A2FA3624424D2A00E97D23 /* Export.swift in Sources */,
|
||||
56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
|
||||
4E13D2F32769B87F0037588C /* DatabaseBackupProgress.swift in Sources */,
|
||||
560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
|
||||
563B8FAC24A1CE43007A48C9 /* DatabasePublishers.swift in Sources */,
|
||||
5605F1691C672E4000235C62 /* NSString.swift in Sources */,
|
||||
@@ -4128,7 +4181,7 @@
|
||||
56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
|
||||
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */,
|
||||
563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */,
|
||||
564CE43121AA901800652B19 /* ValueObserver.swift in Sources */,
|
||||
564CE43121AA901800652B19 /* ValueConcurrentObserver.swift in Sources */,
|
||||
5605F1651C672E4000235C62 /* NSNull.swift in Sources */,
|
||||
56CEB5191EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */,
|
||||
568ECB1825D9161600B71526 /* SQLSubquery.swift in Sources */,
|
||||
@@ -4136,6 +4189,7 @@
|
||||
5653EB0620944C7C00F46237 /* SQLForeignKeyRequest.swift in Sources */,
|
||||
56E9FACB221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */,
|
||||
563B8F92249E6171007A48C9 /* Trace.swift in Sources */,
|
||||
5679533327E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */,
|
||||
5698AC781DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */,
|
||||
56A2387D1B9C75030082EB20 /* Database.swift in Sources */,
|
||||
566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
|
||||
@@ -4354,6 +4408,7 @@
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */;
|
||||
buildSettings = {
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
CODE_SIGN_STYLE = Manual;
|
||||
@@ -4372,6 +4427,9 @@
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
"PROVISIONING_PROFILE_SPECIFIER[sdk=macosx*]" = "";
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Tests/GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -4379,6 +4437,7 @@
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */;
|
||||
buildSettings = {
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
CODE_SIGN_STYLE = Manual;
|
||||
@@ -4399,7 +4458,9 @@
|
||||
"PROVISIONING_PROFILE_SPECIFIER[sdk=macosx*]" = "";
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Tests/GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
@@ -4407,6 +4468,7 @@
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */;
|
||||
buildSettings = {
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
@@ -4421,6 +4483,9 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = macosx;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Tests/GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -4428,6 +4493,7 @@
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */;
|
||||
buildSettings = {
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
@@ -4444,7 +4510,9 @@
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = macosx;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Tests/GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
@@ -4516,6 +4584,7 @@
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */;
|
||||
buildSettings = {
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
CODE_SIGN_IDENTITY = "iPhone Developer";
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
@@ -4534,6 +4603,9 @@
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
SDKROOT = appletvos;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Tests/GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -4541,6 +4613,7 @@
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */;
|
||||
buildSettings = {
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
CODE_SIGN_IDENTITY = "iPhone Developer";
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
@@ -4561,7 +4634,9 @@
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
SDKROOT = appletvos;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Tests/GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
|
||||
@@ -50,4 +50,7 @@
|
||||
<FileRef
|
||||
location = "group:Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
@@ -1,12 +1,13 @@
|
||||
import Foundation
|
||||
import Dispatch
|
||||
import Foundation
|
||||
|
||||
/// Configuration for a DatabaseQueue or DatabasePool.
|
||||
public struct Configuration {
|
||||
|
||||
// MARK: - Misc options
|
||||
|
||||
/// If true, foreign key constraints are checked.
|
||||
/// If true (the default), support for foreign keys is enabled.
|
||||
/// See <https://www.sqlite.org/foreignkeys.html> for more information.
|
||||
///
|
||||
/// Default: true
|
||||
public var foreignKeysEnabled = true
|
||||
@@ -101,6 +102,52 @@ public struct Configuration {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public var observesSuspensionNotifications = false
|
||||
|
||||
/// If false (the default), statement arguments are not visible in the
|
||||
/// description of database errors and trace events, preventing sensitive
|
||||
/// information from leaking in unexpected places.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // Error: sensitive information is not printed when an error occurs:
|
||||
/// do {
|
||||
/// let email = "..." // sensitive information
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// print(error)
|
||||
/// }
|
||||
///
|
||||
/// // Trace: sensitive information is not printed when a statement is traced:
|
||||
/// db.trace { event in
|
||||
/// print(event)
|
||||
/// }
|
||||
/// let email = "..." // sensitive information
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
///
|
||||
/// For debugging purpose, you can set this flag to true, and get more
|
||||
/// precise database reports. It is your responsibility to prevent sensitive
|
||||
/// information from leaking in unexpected locations, so you should not set
|
||||
/// this flag in release builds (think about GDPR and other
|
||||
/// privacy-related rules):
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// #if DEBUG
|
||||
/// // Protect sensitive information by enabling verbose debugging in DEBUG builds only
|
||||
/// config.publicStatementArguments = true
|
||||
/// #endif
|
||||
///
|
||||
/// // The descriptions of trace events and errors now contain the
|
||||
/// // sensitive information:
|
||||
/// db.trace { event in
|
||||
/// print(event)
|
||||
/// }
|
||||
/// do {
|
||||
/// let email = "..."
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// print(error)
|
||||
/// }
|
||||
public var publicStatementArguments = false
|
||||
|
||||
// MARK: - Managing SQLite Connections
|
||||
|
||||
private var setups: [(Database) throws -> Void] = []
|
||||
@@ -198,22 +245,45 @@ public struct Configuration {
|
||||
///
|
||||
/// The quality of service is ignored if you supply a target queue.
|
||||
///
|
||||
/// Default: .default
|
||||
public var qos: DispatchQoS = .default
|
||||
/// Default: .userInitiated
|
||||
public var qos: DispatchQoS = .userInitiated
|
||||
|
||||
/// The target queue for all database accesses.
|
||||
/// The quality of service of read accesses
|
||||
var readQoS: DispatchQoS {
|
||||
targetQueue?.qos ?? self.qos
|
||||
}
|
||||
|
||||
/// A target queue for database accesses.
|
||||
///
|
||||
/// When you use a database pool, make sure the queue is concurrent. If
|
||||
/// it is serial, no concurrent database access can happen, and you may
|
||||
/// experience deadlocks.
|
||||
/// Database connections which are not read-only will prefer
|
||||
/// `writeTargetQueue` instead, if it is not nil.
|
||||
///
|
||||
/// When you use a database pool, make sure this queue is concurrent. This
|
||||
/// is because in a serial dispatch queue, no concurrent database access can
|
||||
/// happen, and you may experience deadlocks.
|
||||
///
|
||||
/// If the queue is nil, all database accesses happen in unspecified
|
||||
/// dispatch queues whose quality of service and label are determined by the
|
||||
/// `qos` and `label` Configuration properties.
|
||||
/// dispatch queues whose quality of service is determined by the
|
||||
/// `qos` property.
|
||||
///
|
||||
/// Default: nil
|
||||
public var targetQueue: DispatchQueue? = nil
|
||||
|
||||
/// The target queue for database connections which are not read-only.
|
||||
///
|
||||
/// If this queue is nil, writer connections are controlled by `targetQueue`.
|
||||
///
|
||||
/// Default: nil
|
||||
public var writeTargetQueue: DispatchQueue? = nil
|
||||
|
||||
#if os(iOS)
|
||||
/// Sets whether GRDB will release memory when entering the background or
|
||||
/// upon receiving a memory warning in iOS.
|
||||
///
|
||||
/// Default: true
|
||||
public var automaticMemoryManagement = true
|
||||
#endif
|
||||
|
||||
// MARK: - Factory Configuration
|
||||
|
||||
/// Creates a factory configuration
|
||||
@@ -240,7 +310,19 @@ public struct Configuration {
|
||||
(self.label ?? defaultLabel) + (purpose.map { "." + $0 } ?? "")
|
||||
}
|
||||
|
||||
func makeDispatchQueue(label: String) -> DispatchQueue {
|
||||
/// Creates a DispatchQueue which has the quality of service and target
|
||||
/// queue of write accesses.
|
||||
func makeWriterDispatchQueue(label: String) -> DispatchQueue {
|
||||
if let targetQueue = writeTargetQueue ?? targetQueue {
|
||||
return DispatchQueue(label: label, target: targetQueue)
|
||||
} else {
|
||||
return DispatchQueue(label: label, qos: qos)
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a DispatchQueue which has the quality of service and target
|
||||
/// queue of read accesses.
|
||||
func makeReaderDispatchQueue(label: String) -> DispatchQueue {
|
||||
if let targetQueue = targetQueue {
|
||||
return DispatchQueue(label: label, target: targetQueue)
|
||||
} else {
|
||||
|
||||
@@ -21,9 +21,10 @@ extension RangeReplaceableCollection {
|
||||
/// - parameter cursor: The cursor whose elements feed the collection.
|
||||
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
|
||||
self.init()
|
||||
while let element = try cursor.next() {
|
||||
append(element)
|
||||
}
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
// database cursors.
|
||||
try cursor.forEach { append($0) }
|
||||
}
|
||||
|
||||
/// Creates a collection containing the elements of a cursor.
|
||||
@@ -38,9 +39,10 @@ extension RangeReplaceableCollection {
|
||||
public init<C: Cursor>(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element {
|
||||
self.init()
|
||||
reserveCapacity(minimumCapacity)
|
||||
while let element = try cursor.next() {
|
||||
append(element)
|
||||
}
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
// database cursors.
|
||||
try cursor.forEach { append($0) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,7 +62,10 @@ extension Dictionary {
|
||||
throws where Value == [C.Element]
|
||||
{
|
||||
self.init()
|
||||
while let value = try cursor.next() {
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
// database cursors.
|
||||
try cursor.forEach { value in
|
||||
try self[keyForValue(value), default: []].append(value)
|
||||
}
|
||||
}
|
||||
@@ -86,7 +91,10 @@ extension Dictionary {
|
||||
throws where Value == [C.Element]
|
||||
{
|
||||
self.init(minimumCapacity: minimumCapacity)
|
||||
while let value = try cursor.next() {
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
// database cursors.
|
||||
try cursor.forEach { value in
|
||||
try self[keyForValue(value), default: []].append(value)
|
||||
}
|
||||
}
|
||||
@@ -108,7 +116,10 @@ extension Dictionary {
|
||||
throws where C.Element == (Key, Value)
|
||||
{
|
||||
self.init()
|
||||
while let (key, value) = try keysAndValues.next() {
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
// database cursors.
|
||||
try keysAndValues.forEach { key, value in
|
||||
if updateValue(value, forKey: key) != nil {
|
||||
fatalError("Duplicate values for key: '\(String(describing: key))'")
|
||||
}
|
||||
@@ -137,7 +148,10 @@ extension Dictionary {
|
||||
throws where C.Element == (Key, Value)
|
||||
{
|
||||
self.init(minimumCapacity: minimumCapacity)
|
||||
while let (key, value) = try keysAndValues.next() {
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
// database cursors.
|
||||
try keysAndValues.forEach { key, value in
|
||||
if updateValue(value, forKey: key) != nil {
|
||||
fatalError("Duplicate values for key: '\(String(describing: key))'")
|
||||
}
|
||||
@@ -155,9 +169,10 @@ extension Set {
|
||||
/// - parameter cursor: A cursor of values to gather into a set.
|
||||
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
|
||||
self.init()
|
||||
while let element = try cursor.next() {
|
||||
insert(element)
|
||||
}
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
// database cursors.
|
||||
try cursor.forEach { insert($0) }
|
||||
}
|
||||
|
||||
/// Creates a set containing the elements of a cursor.
|
||||
@@ -172,9 +187,10 @@ extension Set {
|
||||
/// storage buffer.
|
||||
public init<C: Cursor>(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element {
|
||||
self.init(minimumCapacity: minimumCapacity)
|
||||
while let element = try cursor.next() {
|
||||
insert(element)
|
||||
}
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
// database cursors.
|
||||
try cursor.forEach { insert($0) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -225,6 +241,9 @@ public protocol Cursor: AnyObject {
|
||||
/// Advances to the next element and returns it, or nil if no next element
|
||||
/// exists. Once nil has been returned, all subsequent calls return nil.
|
||||
func next() throws -> Element?
|
||||
|
||||
/// Calls the given closure on each element in the cursor.
|
||||
func forEach(_ body: (Element) throws -> Void) throws
|
||||
}
|
||||
|
||||
extension Cursor {
|
||||
@@ -654,12 +673,14 @@ extension Cursor where Element: StringProtocol {
|
||||
/// having the same Element type, hiding the specifics of the underlying
|
||||
/// cursor.
|
||||
public final class AnyCursor<Element>: Cursor {
|
||||
private let element: () throws -> Element?
|
||||
private let _next: () throws -> Element?
|
||||
private let _forEach: ((Element) throws -> Void) throws -> Void
|
||||
|
||||
/// Creates a cursor that wraps a base cursor but whose type depends only on
|
||||
/// the base cursor’s element type
|
||||
public init<C: Cursor>(_ base: C) where C.Element == Element {
|
||||
element = base.next
|
||||
_next = base.next
|
||||
_forEach = base.forEach
|
||||
}
|
||||
|
||||
/// Creates a cursor that wraps a base iterator but whose type depends only
|
||||
@@ -676,12 +697,17 @@ public final class AnyCursor<Element>: Cursor {
|
||||
}
|
||||
|
||||
/// Creates a cursor that wraps the given closure in its next() method
|
||||
public init(_ body: @escaping () throws -> Element?) {
|
||||
element = body
|
||||
public init(_ next: @escaping () throws -> Element?) {
|
||||
_next = next
|
||||
_forEach = {
|
||||
while let element = try next() {
|
||||
try $0(element)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func next() throws -> Element? {
|
||||
try element()
|
||||
try _next()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -766,6 +792,13 @@ public final class EnumeratedCursor<Base: Cursor>: Cursor {
|
||||
defer { index += 1 }
|
||||
return (index, element)
|
||||
}
|
||||
|
||||
public func forEach(_ body: ((Int, Base.Element)) throws -> Void) throws {
|
||||
try base.forEach { element in
|
||||
defer { index += 1 }
|
||||
try body((index, element))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor whose elements consist of the elements of some base cursor that
|
||||
@@ -789,6 +822,14 @@ public final class FilterCursor<Base: Cursor>: Cursor {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
public func forEach(_ body: (Base.Element) throws -> Void) throws {
|
||||
try base.forEach { element in
|
||||
if try isIncluded(element) {
|
||||
try body(element)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor consisting of all the elements contained in each segment contained
|
||||
@@ -837,6 +878,12 @@ public final class MapCursor<Base: Cursor, Element>: Cursor {
|
||||
guard let element = try base.next() else { return nil }
|
||||
return try transform(element)
|
||||
}
|
||||
|
||||
public func forEach(_ body: (Element) throws -> Void) throws {
|
||||
try base.forEach { element in
|
||||
try body(transform(element))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor that only consumes up to `n` elements from an underlying
|
||||
|
||||
@@ -199,6 +199,12 @@ extension Database {
|
||||
return primaryKey.value
|
||||
}
|
||||
|
||||
if try !tableExists(table) {
|
||||
// Views, CTEs, etc.
|
||||
schemaCache[table.schemaID].set(primaryKey: .missing, forTable: table.name)
|
||||
return nil
|
||||
}
|
||||
|
||||
// https://www.sqlite.org/pragma.html
|
||||
//
|
||||
// > PRAGMA database.table_info(table-name);
|
||||
@@ -288,20 +294,18 @@ extension Database {
|
||||
private func tableHasRowID(_ table: TableIdentifier) throws -> Bool {
|
||||
// Not need to cache the result, because this information feeds
|
||||
// `PrimaryKeyInfo`, which is cached.
|
||||
do {
|
||||
// Use a distinctive alias so that we better understand in the
|
||||
// future why this query appears in the error log.
|
||||
// https://github.com/groue/GRDB.swift/issues/945#issuecomment-804896196
|
||||
//
|
||||
// TODO: find a way to know if a table is WITHOUT ROWID without
|
||||
// generating an error.
|
||||
_ = try makeStatement(sql: """
|
||||
SELECT rowid AS checkWithoutRowidOptimization FROM \(table.quotedDatabaseIdentifier)
|
||||
""")
|
||||
return true
|
||||
} catch DatabaseError.SQLITE_ERROR {
|
||||
return false
|
||||
}
|
||||
//
|
||||
// Use a distinctive alias so that we better understand in the
|
||||
// future why this query appears in the error log.
|
||||
// https://github.com/groue/GRDB.swift/issues/945#issuecomment-804896196
|
||||
//
|
||||
// We don't use `try makeStatement(sql:)` in order to avoid throwing an
|
||||
// error (this annoys users who set a breakpoint on Swift errors).
|
||||
let sql = "SELECT rowid AS checkWithoutRowidOptimization FROM \(table.quotedDatabaseIdentifier)"
|
||||
var statement: SQLiteStatement? = nil
|
||||
let code = sqlite3_prepare_v2(sqliteConnection, sql, -1, &statement, nil)
|
||||
defer { sqlite3_finalize(statement) }
|
||||
return code == SQLITE_OK
|
||||
}
|
||||
|
||||
/// The indexes on table named `tableName`.
|
||||
@@ -526,7 +530,7 @@ extension Database {
|
||||
|
||||
extension Database {
|
||||
|
||||
/// The columns in the table named `tableName`.
|
||||
/// The columns in the table, or view, named `tableName`.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
public func columns(in tableName: String) throws -> [ColumnInfo] {
|
||||
@@ -622,7 +626,7 @@ extension Database {
|
||||
}
|
||||
|
||||
/// If there exists a unique key on columns, return the columns
|
||||
/// ordered as the matching index (or primay key). Case of returned columns
|
||||
/// ordered as the matching index (or primary key). Case of returned columns
|
||||
/// is not guaranteed.
|
||||
func columnsForUniqueKey<T: Sequence>(
|
||||
_ columns: T,
|
||||
@@ -657,6 +661,29 @@ extension Database {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Returns the columns to check for NULL in order to check if the row exist.
|
||||
///
|
||||
/// The returned array is never empty.
|
||||
func existenceCheckColumns(in tableName: String) throws -> [String] {
|
||||
if try tableExists(tableName) {
|
||||
// Table: only check the primary key columns for existence
|
||||
let primaryKey = try self.primaryKey(tableName)
|
||||
if let rowIDColumn = primaryKey.rowIDColumn {
|
||||
// Prefer the user-provided name of the rowid
|
||||
return [rowIDColumn]
|
||||
} else if primaryKey.tableHasRowID {
|
||||
// Prefer the rowid
|
||||
return [Column.rowID.name]
|
||||
} else {
|
||||
// WITHOUT ROWID table: use primary key columns
|
||||
return primaryKey.columns
|
||||
}
|
||||
} else {
|
||||
// View: check all columns for existence
|
||||
return try columns(in: tableName).map(\.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A column of a database table.
|
||||
@@ -690,6 +717,9 @@ public struct ColumnInfo: FetchableRecord {
|
||||
public let name: String
|
||||
|
||||
/// The column data type
|
||||
///
|
||||
/// The casing of this string depends on the SQLite version: make sure you
|
||||
/// process this string in a case-insensitive way.
|
||||
public let type: String
|
||||
|
||||
/// True if and only if the column is constrained to be not null.
|
||||
@@ -1016,9 +1046,9 @@ struct SchemaInfo: Equatable {
|
||||
|
||||
/// - parameter masterTable: "sqlite_master" or "sqlite_temp_master"
|
||||
init(_ db: Database, masterTableName: String) throws { // swiftlint:disable:this inclusive_language
|
||||
objects = try Set(SchemaObject.fetchCursor(db, sql: """
|
||||
objects = try SchemaObject.fetchSet(db, sql: """
|
||||
SELECT type, name, tbl_name, sql FROM \(masterTableName)
|
||||
"""))
|
||||
""")
|
||||
}
|
||||
|
||||
/// All names for a given type
|
||||
|
||||
@@ -542,64 +542,21 @@ public class SQLStatementCursor: Cursor {
|
||||
}
|
||||
|
||||
extension Database {
|
||||
func executeStatement(_ statement: Statement) throws {
|
||||
let authorizer = try statementWillExecute(statement)
|
||||
let sqliteStatement = statement.sqliteStatement
|
||||
|
||||
var code: Int32 = SQLITE_OK
|
||||
withAuthorizer(authorizer) {
|
||||
while true {
|
||||
code = sqlite3_step(sqliteStatement)
|
||||
if code == SQLITE_ROW {
|
||||
// Statement returns a row, but the user ignores the
|
||||
// content of this row:
|
||||
//
|
||||
// try db.execute(sql: "SELECT ...")
|
||||
//
|
||||
// That's OK: maybe the selected rows perform side effects.
|
||||
// For example:
|
||||
//
|
||||
// try db.execute(sql: "SELECT sqlcipher_export(...)")
|
||||
//
|
||||
// Or maybe the user doesn't know that the executed statement
|
||||
// return rows (https://github.com/groue/GRDB.swift/issues/15);
|
||||
//
|
||||
// try db.execute(sql: "PRAGMA journal_mode=WAL")
|
||||
//
|
||||
// It is thus important that we consume *all* rows.
|
||||
continue
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Statement has been fully executed, and authorizer has been reset.
|
||||
// We can now move on further tasks.
|
||||
|
||||
if code == SQLITE_DONE {
|
||||
try statementDidExecute(statement)
|
||||
} else {
|
||||
assert(code != SQLITE_ROW)
|
||||
try statementDidFail(statement, withResultCode: code)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the authorizer that should be used during statement execution
|
||||
/// (this allows preventing the truncate optimization when there exists a
|
||||
/// transaction observer for row deletion).
|
||||
/// Makes sure statement can be executed, and prepares database observation.
|
||||
@usableFromInline
|
||||
func statementWillExecute(_ statement: Statement) throws -> StatementAuthorizer? {
|
||||
func statementWillExecute(_ statement: Statement) throws {
|
||||
// Two things must prevent the statement from executing: aborted
|
||||
// transactions, and database suspension.
|
||||
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
|
||||
try checkForSuspensionViolation(from: statement)
|
||||
|
||||
if _isRecordingSelectedRegion {
|
||||
_selectedRegion.formUnion(statement.databaseRegion)
|
||||
// Database observation: record what the statement is looking at.
|
||||
if isRecordingSelectedRegion {
|
||||
selectedRegion.formUnion(statement.databaseRegion)
|
||||
}
|
||||
|
||||
return observationBroker.statementWillExecute(statement)
|
||||
// Database observation: prepare transaction observers.
|
||||
observationBroker.statementWillExecute(statement)
|
||||
}
|
||||
|
||||
/// May throw a cancelled commit error, if a transaction observer cancels
|
||||
@@ -632,7 +589,8 @@ extension Database {
|
||||
resultCode: resultCode,
|
||||
message: lastErrorMessage,
|
||||
sql: statement.sql,
|
||||
arguments: statement.arguments)
|
||||
arguments: statement.arguments,
|
||||
publicStatementArguments: configuration.publicStatementArguments)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -682,4 +640,8 @@ struct StatementCache {
|
||||
mutating func remove(_ statement: Statement) {
|
||||
statements.removeFirst { $0.value === statement }
|
||||
}
|
||||
|
||||
mutating func removeAll(where shouldBeRemoved: (Statement) -> Bool) {
|
||||
statements = statements.filter { (_, statement) in !shouldBeRemoved(statement) }
|
||||
}
|
||||
}
|
||||
@@ -150,10 +150,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
lazy var internalStatementCache = StatementCache(database: self)
|
||||
lazy var publicStatementCache = StatementCache(database: self)
|
||||
|
||||
/// Statement authorizer. Use withAuthorizer(_:_:).
|
||||
fileprivate var _authorizer: StatementAuthorizer?
|
||||
|
||||
// Transaction observers management
|
||||
// Database observation
|
||||
lazy var authorizer = StatementAuthorizer(self)
|
||||
lazy var observationBroker = DatabaseObservationBroker(self)
|
||||
|
||||
/// The list of compile options used when building SQLite
|
||||
@@ -163,8 +161,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// If true, select statement execution is recorded.
|
||||
/// Use recordingSelectedRegion(_:), see `statementWillExecute(_:)`
|
||||
var _isRecordingSelectedRegion = false
|
||||
var _selectedRegion = DatabaseRegion()
|
||||
var isRecordingSelectedRegion = false
|
||||
var selectedRegion = DatabaseRegion()
|
||||
|
||||
/// Support for checkForAbortedTransaction()
|
||||
var isInsideTransactionBlock = false
|
||||
@@ -235,7 +233,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
setupDefaultFunctions()
|
||||
setupDefaultCollations()
|
||||
setupAuthorizer()
|
||||
observationBroker.installCommitAndRollbackHooks()
|
||||
if !configuration.readonly {
|
||||
observationBroker.installCommitAndRollbackHooks()
|
||||
}
|
||||
try activateExtendedCodes()
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
@@ -318,17 +318,16 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
//
|
||||
// - DatabaseCursorTests.testIssue583()
|
||||
// - http://sqlite.1065341.n5.nabble.com/Issue-report-sqlite3-set-authorizer-triggers-error-4-516-SQLITE-ABORT-ROLLBACK-during-statement-itern-td107972.html
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
let authorizerP = Unmanaged.passUnretained(authorizer).toOpaque()
|
||||
sqlite3_set_authorizer(
|
||||
sqliteConnection,
|
||||
{ (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer.unsafelyUnwrapped).takeUnretainedValue()
|
||||
guard let authorizer = db._authorizer else {
|
||||
return SQLITE_OK
|
||||
}
|
||||
return authorizer.authorize(actionCode, cString1, cString2, cString3, cString4)
|
||||
{ (authorizerP, actionCode, cString1, cString2, cString3, cString4) -> Int32 in
|
||||
Unmanaged<StatementAuthorizer>
|
||||
.fromOpaque(authorizerP.unsafelyUnwrapped)
|
||||
.takeUnretainedValue()
|
||||
.authorize(actionCode, cString1, cString2, cString3, cString4)
|
||||
},
|
||||
dbPointer)
|
||||
authorizerP)
|
||||
}
|
||||
|
||||
|
||||
@@ -549,46 +548,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
finally: endReadOnly)
|
||||
}
|
||||
|
||||
// MARK: - Snapshots
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT
|
||||
/// Returns a snapshot that must be freed with `sqlite3_snapshot_free`.
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/snapshot.html>
|
||||
func takeVersionSnapshot() throws -> UnsafeMutablePointer<sqlite3_snapshot> {
|
||||
var snapshot: UnsafeMutablePointer<sqlite3_snapshot>?
|
||||
let code = withUnsafeMutablePointer(to: &snapshot) {
|
||||
sqlite3_snapshot_get(sqliteConnection, "main", $0)
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: lastErrorMessage)
|
||||
}
|
||||
if let snapshot = snapshot {
|
||||
return snapshot
|
||||
} else {
|
||||
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
|
||||
}
|
||||
}
|
||||
|
||||
func wasChanged(since initialSnapshot: UnsafeMutablePointer<sqlite3_snapshot>) throws -> Bool {
|
||||
let secondSnapshot = try takeVersionSnapshot()
|
||||
defer {
|
||||
sqlite3_snapshot_free(secondSnapshot)
|
||||
}
|
||||
let cmp = sqlite3_snapshot_cmp(initialSnapshot, secondSnapshot)
|
||||
assert(cmp <= 0, "Unexpected snapshot ordering")
|
||||
return cmp < 0
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Authorizer
|
||||
|
||||
func withAuthorizer<T>(_ authorizer: StatementAuthorizer?, _ block: () throws -> T) rethrows -> T {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
let old = self._authorizer
|
||||
self._authorizer = authorizer
|
||||
defer { self._authorizer = old }
|
||||
return try block()
|
||||
/// Returns whether database connection is read-only.
|
||||
var isReadOnly: Bool {
|
||||
_readOnlyDepth > 0 || configuration.readonly
|
||||
}
|
||||
|
||||
// MARK: - Recording of the selected region
|
||||
@@ -598,17 +560,17 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
return try block()
|
||||
}
|
||||
|
||||
let oldFlag = self._isRecordingSelectedRegion
|
||||
let oldRegion = self._selectedRegion
|
||||
_isRecordingSelectedRegion = true
|
||||
_selectedRegion = DatabaseRegion()
|
||||
let oldFlag = self.isRecordingSelectedRegion
|
||||
let oldRegion = self.selectedRegion
|
||||
isRecordingSelectedRegion = true
|
||||
selectedRegion = DatabaseRegion()
|
||||
defer {
|
||||
region.formUnion(_selectedRegion)
|
||||
_isRecordingSelectedRegion = oldFlag
|
||||
if _isRecordingSelectedRegion {
|
||||
_selectedRegion = oldRegion.union(_selectedRegion)
|
||||
region.formUnion(selectedRegion)
|
||||
isRecordingSelectedRegion = oldFlag
|
||||
if isRecordingSelectedRegion {
|
||||
selectedRegion = oldRegion.union(selectedRegion)
|
||||
} else {
|
||||
_selectedRegion = oldRegion
|
||||
selectedRegion = oldRegion
|
||||
}
|
||||
}
|
||||
return try block()
|
||||
@@ -712,7 +674,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
impl: .trace_v2(
|
||||
sqliteStatement: OpaquePointer(sqliteStatement),
|
||||
unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)),
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql))
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql,
|
||||
publicStatementArguments: configuration.publicStatementArguments))
|
||||
trace(TraceEvent.statement(statement))
|
||||
}
|
||||
case SQLITE_TRACE_PROFILE:
|
||||
@@ -721,7 +684,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
impl: .trace_v2(
|
||||
sqliteStatement: OpaquePointer(sqliteStatement),
|
||||
unexpandedSQL: nil,
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql))
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql,
|
||||
publicStatementArguments: configuration.publicStatementArguments))
|
||||
let duration = TimeInterval(durationP.pointee) / 1.0e9
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
|
||||
@@ -896,7 +860,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
resultCode: .SQLITE_ABORT,
|
||||
message: "Database is suspended",
|
||||
sql: statement.sql,
|
||||
arguments: statement.arguments)
|
||||
arguments: statement.arguments,
|
||||
publicStatementArguments: configuration.publicStatementArguments)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -929,7 +894,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
resultCode: .SQLITE_ABORT,
|
||||
message: "Transaction was aborted",
|
||||
sql: sql(),
|
||||
arguments: arguments())
|
||||
arguments: arguments(),
|
||||
publicStatementArguments: configuration.publicStatementArguments)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -948,10 +914,16 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// This method is not reentrant: you can't nest transactions.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .deferred. See <https://www.sqlite.org/lang_transaction.html>
|
||||
/// for more information.
|
||||
/// - kind: The transaction type (default nil).
|
||||
///
|
||||
/// If nil, and the database connection is read-only, the transaction
|
||||
/// kind is `.deferred`.
|
||||
///
|
||||
/// If nil, and the database connection is not read-only, the
|
||||
/// transaction kind is `configuration.defaultTransactionKind`.
|
||||
///
|
||||
/// See <https://www.sqlite.org/lang_transaction.html> for
|
||||
/// more information.
|
||||
/// - block: A block that executes SQL statements and return either
|
||||
/// .commit or .rollback.
|
||||
/// - throws: The error thrown by the block.
|
||||
@@ -1008,6 +980,30 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the block with an isolation level equal or greater than
|
||||
/// snapshot isolation.
|
||||
///
|
||||
/// - parameter readOnly: If true, writes are forbidden.
|
||||
func isolated<T>(readOnly: Bool = false, _ block: () throws -> T) throws -> T {
|
||||
var result: T?
|
||||
if readOnly {
|
||||
// Enter read-only mode before starting a transaction, so that the
|
||||
// transaction commit does not trigger database observation.
|
||||
try self.readOnly {
|
||||
try inSavepoint {
|
||||
result = try block()
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
} else {
|
||||
try inSavepoint {
|
||||
result = try block()
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
return result!
|
||||
}
|
||||
|
||||
/// Executes a block inside a savepoint.
|
||||
///
|
||||
/// try dbQueue.inDatabase do {
|
||||
@@ -1047,7 +1043,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
//
|
||||
// For those two reasons, we open a transaction instead of a
|
||||
// top-level savepoint.
|
||||
try inTransaction(configuration.defaultTransactionKind, block)
|
||||
try inTransaction { try block() }
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1115,13 +1111,20 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// Begins a database transaction.
|
||||
///
|
||||
/// - parameter kind: The transaction type (default nil). If nil, the
|
||||
/// transaction type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .deferred. See <https://www.sqlite.org/lang_transaction.html>
|
||||
/// for more information.
|
||||
/// - throws: The error thrown by the block.
|
||||
/// - parameter kind: The transaction type (default nil).
|
||||
///
|
||||
/// If nil, and the database connection is read-only, the transaction kind
|
||||
/// is `.deferred`.
|
||||
///
|
||||
/// If nil, and the database connection is not read-only, the transaction
|
||||
/// kind is `configuration.defaultTransactionKind`.
|
||||
///
|
||||
/// See <https://www.sqlite.org/lang_transaction.html> for
|
||||
/// more information.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func beginTransaction(_ kind: TransactionKind? = nil) throws {
|
||||
let kind = kind ?? configuration.defaultTransactionKind
|
||||
// SQLite throws an error for non-deferred transactions when read-only.
|
||||
let kind = kind ?? (isReadOnly ? .deferred : configuration.defaultTransactionKind)
|
||||
try execute(sql: "BEGIN \(kind.rawValue) TRANSACTION")
|
||||
assert(sqlite3_get_autocommit(sqliteConnection) == 0)
|
||||
}
|
||||
@@ -1181,7 +1184,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// MARK: - Memory Management
|
||||
|
||||
func releaseMemory() {
|
||||
public func releaseMemory() {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
sqlite3_db_release_memory(sqliteConnection)
|
||||
schemaCache.clear()
|
||||
internalStatementCache.clear()
|
||||
@@ -1228,14 +1232,73 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// MARK: - Backup
|
||||
|
||||
func backup(
|
||||
to dbDest: Database,
|
||||
afterBackupInit: (() -> Void)? = nil,
|
||||
afterBackupStep: (() -> Void)? = nil)
|
||||
/// Copies the database contents into another database.
|
||||
///
|
||||
/// The `backup` method blocks the current thread until the destination
|
||||
/// database contains the same contents as the source database.
|
||||
///
|
||||
/// Usage:
|
||||
///
|
||||
/// let source: DatabaseQueue = ...
|
||||
/// let destination: DatabaseQueue = ...
|
||||
/// try source.write { sourceDb in
|
||||
/// try destination.barrierWriteWithoutTransaction { destDb in
|
||||
/// try sourceDb.backup(to: destDb)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
///
|
||||
/// When you're after progress reporting during backup, you'll want to
|
||||
/// perform the backup in several steps. Each step copies the number of
|
||||
/// _database pages_ you specify. See <https://www.sqlite.org/c3ref/backup_finish.html>
|
||||
/// for more information:
|
||||
///
|
||||
/// // Backup with progress reporting
|
||||
/// try sourceDb.backup(
|
||||
/// to: destDb,
|
||||
/// pagesPerStep: ...)
|
||||
/// { backupProgress in
|
||||
/// print("Database backup progress:", backupProgress)
|
||||
/// }
|
||||
///
|
||||
/// The `progress` callback will be called at least once—when
|
||||
/// `backupProgress.isCompleted == true`. If the callback throws
|
||||
/// when `backupProgress.isCompleted == false`, the backup is aborted
|
||||
/// and the error is rethrown. If the callback throws when
|
||||
/// `backupProgress.isCompleted == true`, backup completion is
|
||||
/// unaffected and the error is silently ignored.
|
||||
///
|
||||
/// See also `DatabaseReader.backup()`.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - destDb: The destination database.
|
||||
/// - pagesPerStep: The number of database pages copied on each backup
|
||||
/// step. By default, all pages are copied in one single step.
|
||||
/// - progress: An optional function that is notified of the backup
|
||||
/// progress.
|
||||
/// - throws: The error thrown by `progress` if the backup is abandoned, or
|
||||
/// any `DatabaseError` that would happen while performing the backup.
|
||||
public func backup(
|
||||
to destDb: Database,
|
||||
pagesPerStep: Int32 = -1,
|
||||
progress: ((DatabaseBackupProgress) throws -> Void)? = nil)
|
||||
throws
|
||||
{
|
||||
guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", sqliteConnection, "main") else {
|
||||
throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage)
|
||||
try backupInternal(
|
||||
to: destDb,
|
||||
pagesPerStep: pagesPerStep,
|
||||
afterBackupStep: progress)
|
||||
}
|
||||
|
||||
func backupInternal(
|
||||
to destDb: Database,
|
||||
pagesPerStep: Int32 = -1,
|
||||
afterBackupInit: (() -> Void)? = nil,
|
||||
afterBackupStep: ((DatabaseBackupProgress) throws -> Void)? = nil)
|
||||
throws
|
||||
{
|
||||
guard let backup = sqlite3_backup_init(destDb.sqliteConnection, "main", sqliteConnection, "main") else {
|
||||
throw DatabaseError(resultCode: destDb.lastErrorCode, message: destDb.lastErrorMessage)
|
||||
}
|
||||
guard Int(bitPattern: backup) != Int(SQLITE_ERROR) else {
|
||||
throw DatabaseError()
|
||||
@@ -1245,14 +1308,21 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
do {
|
||||
backupLoop: while true {
|
||||
switch sqlite3_backup_step(backup, -1) {
|
||||
let rc = sqlite3_backup_step(backup, pagesPerStep)
|
||||
let totalPageCount = Int(sqlite3_backup_pagecount(backup))
|
||||
let remainingPageCount = Int(sqlite3_backup_remaining(backup))
|
||||
let progress = DatabaseBackupProgress(
|
||||
remainingPageCount: remainingPageCount,
|
||||
totalPageCount: totalPageCount,
|
||||
isCompleted: rc == SQLITE_DONE)
|
||||
switch rc {
|
||||
case SQLITE_DONE:
|
||||
afterBackupStep?()
|
||||
try? afterBackupStep?(progress)
|
||||
break backupLoop
|
||||
case SQLITE_OK:
|
||||
afterBackupStep?()
|
||||
try afterBackupStep?(progress)
|
||||
case let code:
|
||||
throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage)
|
||||
throw DatabaseError(resultCode: code, message: destDb.lastErrorMessage)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
@@ -1264,11 +1334,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
case SQLITE_OK:
|
||||
break
|
||||
case let code:
|
||||
throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage)
|
||||
throw DatabaseError(resultCode: code, message: destDb.lastErrorMessage)
|
||||
}
|
||||
|
||||
// The schema of the destination database has changed:
|
||||
dbDest.clearSchemaCache()
|
||||
destDb.clearSchemaCache()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1456,6 +1526,9 @@ extension Database {
|
||||
/// The `DOUBLE` SQL column type
|
||||
public static let double = ColumnType(rawValue: "DOUBLE")
|
||||
|
||||
/// The `REAL` SQL column type
|
||||
public static let real = ColumnType(rawValue: "REAL")
|
||||
|
||||
/// The `NUMERIC` SQL column type
|
||||
public static let numeric = ColumnType(rawValue: "NUMERIC")
|
||||
|
||||
@@ -1470,6 +1543,9 @@ extension Database {
|
||||
|
||||
/// The `DATETIME` SQL column type
|
||||
public static let datetime = ColumnType(rawValue: "DATETIME")
|
||||
|
||||
/// The `ANY` SQL column type
|
||||
public static let any = ColumnType(rawValue: "ANY")
|
||||
}
|
||||
|
||||
/// An SQLite conflict resolution.
|
||||
@@ -1554,22 +1630,23 @@ extension Database {
|
||||
public enum TraceEvent: CustomStringConvertible {
|
||||
|
||||
/// Information about a statement reported by `Database.trace(options:_:)`
|
||||
public struct Statement {
|
||||
public struct Statement: CustomStringConvertible {
|
||||
enum Impl {
|
||||
case trace_v1(String)
|
||||
case trace_v2(
|
||||
sqliteStatement: SQLiteStatement,
|
||||
unexpandedSQL: UnsafePointer<CChar>?,
|
||||
sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
|
||||
sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?,
|
||||
publicStatementArguments: Bool) // See Configuration.publicStatementArguments
|
||||
}
|
||||
let impl: Impl
|
||||
var impl: Impl
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
|
||||
/// The executed SQL, where bound parameters are not expanded.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// UPDATE player SET score = ? WHERE id = ?
|
||||
/// SELECT * FROM player WHERE email = ?
|
||||
public var sql: String { _sql }
|
||||
#elseif os(Linux)
|
||||
#else
|
||||
@@ -1577,7 +1654,7 @@ extension Database {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// UPDATE player SET score = ? WHERE id = ?
|
||||
/// SELECT * FROM player WHERE email = ?
|
||||
@available(OSX 10.12, tvOS 10.0, watchOS 3.0, *)
|
||||
public var sql: String { _sql }
|
||||
#endif
|
||||
@@ -1585,10 +1662,10 @@ extension Database {
|
||||
var _sql: String {
|
||||
switch impl {
|
||||
case .trace_v1:
|
||||
// Likely a GRDB bug
|
||||
fatalError("Not get statement SQL")
|
||||
// Likely a GRDB bug: this api is not supposed to be available
|
||||
fatalError("Unavailable statement SQL")
|
||||
|
||||
case let .trace_v2(sqliteStatement, unexpandedSQL, _):
|
||||
case let .trace_v2(sqliteStatement, unexpandedSQL, _, _):
|
||||
if let unexpandedSQL = unexpandedSQL {
|
||||
return String(cString: unexpandedSQL)
|
||||
.trimmingCharacters(in: .sqlStatementSeparators)
|
||||
@@ -1603,13 +1680,17 @@ extension Database {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// UPDATE player SET score = 1000 WHERE id = 1
|
||||
/// SELECT * FROM player WHERE email = 'arthur@example.com'
|
||||
///
|
||||
/// - warning: It is your responsibility to prevent sensitive
|
||||
/// information from leaking in unexpected locations, so use this
|
||||
/// property with care.
|
||||
public var expandedSQL: String {
|
||||
switch impl {
|
||||
case let .trace_v1(expandedSQL):
|
||||
return expandedSQL
|
||||
|
||||
case let .trace_v2(sqliteStatement, _, sqlite3_expanded_sql):
|
||||
case let .trace_v2(sqliteStatement, _, sqlite3_expanded_sql, _):
|
||||
guard let cString = sqlite3_expanded_sql(sqliteStatement) else {
|
||||
return ""
|
||||
}
|
||||
@@ -1618,6 +1699,20 @@ extension Database {
|
||||
.trimmingCharacters(in: .sqlStatementSeparators)
|
||||
}
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
switch impl {
|
||||
case let .trace_v1(expandedSQL):
|
||||
return expandedSQL
|
||||
|
||||
case let .trace_v2(_, _, _, publicStatementArguments):
|
||||
if publicStatementArguments {
|
||||
return expandedSQL
|
||||
} else {
|
||||
return _sql
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An event reported by `TracingOptions.statement`.
|
||||
@@ -1626,7 +1721,39 @@ extension Database {
|
||||
/// An event reported by `TracingOptions.profile`.
|
||||
case profile(statement: Statement, duration: TimeInterval)
|
||||
|
||||
/// The trace event description.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// SELECT * FROM player WHERE email = ?
|
||||
/// 0.1s SELECT * FROM player WHERE email = ?
|
||||
///
|
||||
/// The format of the event description may change between GRDB releases,
|
||||
/// without notice: don't have your application rely on any specific format.
|
||||
public var description: String {
|
||||
switch self {
|
||||
case let .statement(statement):
|
||||
return statement.description
|
||||
case let .profile(statement: statement, duration: duration):
|
||||
let durationString = String(format: "%.3f", duration)
|
||||
return "\(durationString)s \(statement)"
|
||||
}
|
||||
}
|
||||
|
||||
/// The trace event description, where bound parameters are expanded.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// SELECT * FROM player WHERE email = 'arthur@example.com'
|
||||
/// 0.1s SELECT * FROM player WHERE email = 'arthur@example.com'
|
||||
///
|
||||
/// The format of the event description may change between GRDB releases,
|
||||
/// without notice: don't have your application rely on any specific format.
|
||||
///
|
||||
/// - warning: It is your responsibility to prevent sensitive
|
||||
/// information from leaking in unexpected locations, so use this
|
||||
/// property with care.
|
||||
public var expandedDescription: String {
|
||||
switch self {
|
||||
case let .statement(statement):
|
||||
return statement.expandedSQL
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/// An instance of `DatabaseBackupProgress` is passed to a callback of the
|
||||
/// `DatabaseReader.backup` or `Database.backup` methods to report
|
||||
/// database backup progress to the caller.
|
||||
///
|
||||
/// This is an advanced API for expert users. It is based directly on the SQLite
|
||||
/// [online backup API](https://www.sqlite.org/c3ref/backup_finish.html).
|
||||
public struct DatabaseBackupProgress {
|
||||
/// Total page count is defined by the `sqlite3_backup_remaining` function
|
||||
public let remainingPageCount: Int
|
||||
|
||||
/// Total page count is defined by the `sqlite3_backup_pagecount` function
|
||||
public let totalPageCount: Int
|
||||
|
||||
/// Completed page count is defined as `sqlite3_backup_pagecount() - sqlite3_backup_remaining()`
|
||||
public var completedPageCount: Int {
|
||||
totalPageCount - remainingPageCount
|
||||
}
|
||||
|
||||
/// This property is true if and only if `sqlite3_backup_step()` returns
|
||||
/// `SQLITE_DONE`
|
||||
public let isCompleted: Bool
|
||||
}
|
||||
@@ -116,17 +116,22 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
|
||||
public static let SQLITE_IOERR_BEGIN_ATOMIC = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (29<<8)))
|
||||
public static let SQLITE_IOERR_COMMIT_ATOMIC = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (30<<8)))
|
||||
public static let SQLITE_IOERR_ROLLBACK_ATOMIC = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (31<<8)))
|
||||
public static let SQLITE_IOERR_DATA = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (32<<8)))
|
||||
public static let SQLITE_IOERR_CORRUPTFS = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (33<<8)))
|
||||
public static let SQLITE_LOCKED_SHAREDCACHE = ResultCode(rawValue: (SQLITE_LOCKED.rawValue | (1<<8)))
|
||||
public static let SQLITE_LOCKED_VTAB = ResultCode(rawValue: (SQLITE_LOCKED.rawValue | (2<<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_BUSY_TIMEOUT = ResultCode(rawValue: (SQLITE_BUSY.rawValue | (3<<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_CANTOPEN_DIRTYWAL = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (5<<8))) /* Not Used */
|
||||
public static let SQLITE_CANTOPEN_SYMLINK = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (6<<8)))
|
||||
public static let SQLITE_CORRUPT_VTAB = ResultCode(rawValue: (SQLITE_CORRUPT.rawValue | (1<<8)))
|
||||
public static let SQLITE_CORRUPT_SEQUENCE = ResultCode(rawValue: (SQLITE_CORRUPT.rawValue | (2<<8)))
|
||||
public static let SQLITE_CORRUPT_INDEX = ResultCode(rawValue: (SQLITE_CORRUPT.rawValue | (3<<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)))
|
||||
@@ -144,11 +149,14 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
|
||||
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_CONSTRAINT_PINNED = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (11<<8)))
|
||||
public static let SQLITE_CONSTRAINT_DATATYPE = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (12<<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)))
|
||||
public static let SQLITE_OK_SYMLINK = ResultCode(rawValue: (SQLITE_OK.rawValue | (2<<8)))
|
||||
// swiftlint:enable operator_usage_whitespace line_length
|
||||
}
|
||||
|
||||
@@ -189,6 +197,8 @@ extension ResultCode {
|
||||
}
|
||||
}
|
||||
|
||||
extension ResultCode: GRDBSendable { }
|
||||
|
||||
/// DatabaseError wraps an SQLite error.
|
||||
public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
|
||||
@@ -231,17 +241,31 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
/// The query arguments that yielded the error (if relevant).
|
||||
public let arguments: StatementArguments?
|
||||
|
||||
/// Creates a Database Error
|
||||
/// See Configuration.publicStatementArguments
|
||||
var publicStatementArguments: Bool
|
||||
|
||||
/// Creates a DatabaseError.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - resultCode: A ResultCode (defaults to .SQLITE_ERROR).
|
||||
/// - message: An eventual error message. If nil, the error message is
|
||||
/// derived from the result code.
|
||||
/// - sql: An eventual SQL string.
|
||||
/// - arguments: Eventual Statement arguments.
|
||||
/// - publicStatementArguments: If false (the default), statement
|
||||
/// arguments are not visible in the error's `description` property.
|
||||
public init(
|
||||
resultCode: ResultCode = .SQLITE_ERROR,
|
||||
message: String? = nil,
|
||||
sql: String? = nil,
|
||||
arguments: StatementArguments? = nil)
|
||||
arguments: StatementArguments? = nil,
|
||||
publicStatementArguments: Bool = false)
|
||||
{
|
||||
self.extendedResultCode = resultCode
|
||||
self.message = message ?? resultCode.errorString
|
||||
self.sql = sql
|
||||
self.arguments = arguments
|
||||
self.publicStatementArguments = publicStatementArguments
|
||||
}
|
||||
|
||||
/// Creates a Database Error with a raw CInt result code.
|
||||
@@ -249,8 +273,31 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
/// This initializer is not public because library user is not supposed to
|
||||
/// be exposed to raw result codes.
|
||||
@usableFromInline
|
||||
init(resultCode: CInt, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
|
||||
self.init(resultCode: ResultCode(rawValue: resultCode), message: message, sql: sql, arguments: arguments)
|
||||
init(resultCode: CInt, message: String? = nil, sql: String? = nil) {
|
||||
self.init(
|
||||
resultCode: ResultCode(rawValue: resultCode),
|
||||
message: message,
|
||||
sql: sql)
|
||||
}
|
||||
|
||||
/// Creates a Database Error with a raw CInt result code.
|
||||
///
|
||||
/// This initializer is not public because library user is not supposed to
|
||||
/// be exposed to raw result codes.
|
||||
@usableFromInline
|
||||
init(
|
||||
resultCode: CInt,
|
||||
message: String? = nil,
|
||||
sql: String? = nil,
|
||||
arguments: StatementArguments?,
|
||||
publicStatementArguments: Bool)
|
||||
{
|
||||
self.init(
|
||||
resultCode: ResultCode(rawValue: resultCode),
|
||||
message: message,
|
||||
sql: sql,
|
||||
arguments: arguments,
|
||||
publicStatementArguments: publicStatementArguments)
|
||||
}
|
||||
|
||||
static func noSuchTable(_ tableName: String) -> Self {
|
||||
@@ -331,17 +378,22 @@ extension DatabaseError {
|
||||
public static let SQLITE_IOERR_BEGIN_ATOMIC = ResultCode.SQLITE_IOERR_BEGIN_ATOMIC
|
||||
public static let SQLITE_IOERR_COMMIT_ATOMIC = ResultCode.SQLITE_IOERR_COMMIT_ATOMIC
|
||||
public static let SQLITE_IOERR_ROLLBACK_ATOMIC = ResultCode.SQLITE_IOERR_ROLLBACK_ATOMIC
|
||||
public static let SQLITE_IOERR_DATA = ResultCode.SQLITE_IOERR_DATA
|
||||
public static let SQLITE_IOERR_CORRUPTFS = ResultCode.SQLITE_IOERR_CORRUPTFS
|
||||
public static let SQLITE_LOCKED_SHAREDCACHE = ResultCode.SQLITE_LOCKED_SHAREDCACHE
|
||||
public static let SQLITE_LOCKED_VTAB = ResultCode.SQLITE_LOCKED_VTAB
|
||||
public static let SQLITE_BUSY_RECOVERY = ResultCode.SQLITE_BUSY_RECOVERY
|
||||
public static let SQLITE_BUSY_SNAPSHOT = ResultCode.SQLITE_BUSY_SNAPSHOT
|
||||
public static let SQLITE_BUSY_TIMEOUT = ResultCode.SQLITE_BUSY_TIMEOUT
|
||||
public static let SQLITE_CANTOPEN_NOTEMPDIR = ResultCode.SQLITE_CANTOPEN_NOTEMPDIR
|
||||
public static let SQLITE_CANTOPEN_ISDIR = ResultCode.SQLITE_CANTOPEN_ISDIR
|
||||
public static let SQLITE_CANTOPEN_FULLPATH = ResultCode.SQLITE_CANTOPEN_FULLPATH
|
||||
public static let SQLITE_CANTOPEN_CONVPATH = ResultCode.SQLITE_CANTOPEN_CONVPATH
|
||||
public static let SQLITE_CANTOPEN_DIRTYWAL = ResultCode.SQLITE_CANTOPEN_DIRTYWAL
|
||||
public static let SQLITE_CANTOPEN_SYMLINK = ResultCode.SQLITE_CANTOPEN_SYMLINK
|
||||
public static let SQLITE_CORRUPT_VTAB = ResultCode.SQLITE_CORRUPT_VTAB
|
||||
public static let SQLITE_CORRUPT_SEQUENCE = ResultCode.SQLITE_CORRUPT_SEQUENCE
|
||||
public static let SQLITE_CORRUPT_INDEX = ResultCode.SQLITE_CORRUPT_INDEX
|
||||
public static let SQLITE_READONLY_RECOVERY = ResultCode.SQLITE_READONLY_RECOVERY
|
||||
public static let SQLITE_READONLY_CANTLOCK = ResultCode.SQLITE_READONLY_CANTLOCK
|
||||
public static let SQLITE_READONLY_ROLLBACK = ResultCode.SQLITE_READONLY_ROLLBACK
|
||||
@@ -359,11 +411,14 @@ extension DatabaseError {
|
||||
public static let SQLITE_CONSTRAINT_UNIQUE = ResultCode.SQLITE_CONSTRAINT_UNIQUE
|
||||
public static let SQLITE_CONSTRAINT_VTAB = ResultCode.SQLITE_CONSTRAINT_VTAB
|
||||
public static let SQLITE_CONSTRAINT_ROWID = ResultCode.SQLITE_CONSTRAINT_ROWID
|
||||
public static let SQLITE_CONSTRAINT_PINNED = ResultCode.SQLITE_CONSTRAINT_PINNED
|
||||
public static let SQLITE_CONSTRAINT_DATATYPE = ResultCode.SQLITE_CONSTRAINT_DATATYPE
|
||||
public static let SQLITE_NOTICE_RECOVER_WAL = ResultCode.SQLITE_NOTICE_RECOVER_WAL
|
||||
public static let SQLITE_NOTICE_RECOVER_ROLLBACK = ResultCode.SQLITE_NOTICE_RECOVER_ROLLBACK
|
||||
public static let SQLITE_WARNING_AUTOINDEX = ResultCode.SQLITE_WARNING_AUTOINDEX
|
||||
public static let SQLITE_AUTH_USER = ResultCode.SQLITE_AUTH_USER
|
||||
public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode.SQLITE_OK_LOAD_PERMANENTLY
|
||||
public static let SQLITE_OK_SYMLINK = ResultCode.SQLITE_OK_SYMLINK
|
||||
}
|
||||
|
||||
extension DatabaseError {
|
||||
@@ -386,8 +441,44 @@ extension DatabaseError {
|
||||
|
||||
// CustomStringConvertible
|
||||
extension DatabaseError {
|
||||
/// :nodoc:
|
||||
/// The error description.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// SQLite error 19: NOT NULL constraint failed: player.score
|
||||
/// - while executing `UPDATE player SET score = ? WHERE email = ?
|
||||
///
|
||||
/// The format of the error description may change between GRDB releases,
|
||||
/// without notice: don't have your application rely on any specific format.
|
||||
public var description: String {
|
||||
var description = "SQLite error \(resultCode.rawValue)"
|
||||
if let message = message {
|
||||
description += ": \(message)"
|
||||
}
|
||||
if let sql = sql {
|
||||
description += " - while executing `\(sql)`"
|
||||
}
|
||||
if publicStatementArguments, let arguments = arguments, !arguments.isEmpty {
|
||||
description += " with arguments \(arguments)"
|
||||
}
|
||||
return description
|
||||
}
|
||||
|
||||
/// The error description, where bound parameters, if present, are visible.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// SQLite error 19: NOT NULL constraint failed: player.score
|
||||
/// - while executing `UPDATE player SET score = ? WHERE email = ?
|
||||
/// with arguments [nil, "arthur@example.com"]
|
||||
///
|
||||
/// The format of the error description may change between GRDB releases,
|
||||
/// without notice: don't have your application rely on any specific format.
|
||||
///
|
||||
/// - warning: It is your responsibility to prevent sensitive
|
||||
/// information from leaking in unexpected locations, so use this
|
||||
/// property with care.
|
||||
public var expandedDescription: String {
|
||||
var description = "SQLite error \(resultCode.rawValue)"
|
||||
if let message = message {
|
||||
description += ": \(message)"
|
||||
@@ -415,5 +506,11 @@ extension DatabaseError {
|
||||
|
||||
/// NSError bridging: the user-info dictionary.
|
||||
/// :nodoc:
|
||||
public var errorUserInfo: [String: Any] { [NSLocalizedDescriptionKey: description] }
|
||||
public var errorUserInfo: [String: Any] {
|
||||
var userInfo = [NSLocalizedDescriptionKey: description]
|
||||
if let message = message {
|
||||
userInfo[NSLocalizedFailureReasonErrorKey] = message
|
||||
}
|
||||
return userInfo
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import Foundation
|
||||
import Dispatch
|
||||
import Foundation
|
||||
#if os(iOS)
|
||||
import UIKit
|
||||
#endif
|
||||
@@ -57,14 +57,17 @@ public final class DatabasePool: DatabaseWriter {
|
||||
readerConfiguration.allowsUnsafeTransactions = false
|
||||
|
||||
var readerCount = 0
|
||||
readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: {
|
||||
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
|
||||
return try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: readerConfiguration,
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "reader.\(readerCount)")
|
||||
})
|
||||
readerPool = Pool(
|
||||
maximumCount: configuration.maximumReaderCount,
|
||||
qos: configuration.readQoS,
|
||||
makeElement: {
|
||||
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
|
||||
return try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: readerConfiguration,
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "reader.\(readerCount)")
|
||||
})
|
||||
|
||||
// Activate WAL Mode unless readonly
|
||||
if !configuration.readonly {
|
||||
@@ -100,7 +103,9 @@ public final class DatabasePool: DatabaseWriter {
|
||||
// Be a nice iOS citizen, and don't consume too much memory
|
||||
// See https://github.com/groue/GRDB.swift/#memory-management
|
||||
#if os(iOS)
|
||||
setupMemoryManagement()
|
||||
if configuration.automaticMemoryManagement {
|
||||
setupMemoryManagement()
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -151,47 +156,80 @@ public final class DatabasePool: DatabaseWriter {
|
||||
|
||||
return configuration
|
||||
}
|
||||
|
||||
/// Blocks the current thread until all database connections have
|
||||
/// executed the *body* block.
|
||||
fileprivate func forEachConnection(_ body: (Database) -> Void) {
|
||||
writer.sync(body)
|
||||
readerPool?.forEach { $0.sync(body) }
|
||||
}
|
||||
}
|
||||
|
||||
#if swift(>=5.6) && canImport(_Concurrency)
|
||||
// @unchecked because of databaseSnapshotCount and readerPool
|
||||
extension DatabasePool: @unchecked Sendable { }
|
||||
#endif
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
// MARK: - Memory management
|
||||
|
||||
/// Free as much memory as possible.
|
||||
/// Frees as much memory as possible, by disposing non-essential memory from
|
||||
/// the writer connection, and closing all reader connections.
|
||||
///
|
||||
/// This method blocks the current thread until all database accesses
|
||||
/// are completed.
|
||||
/// This method is synchronous, and blocks the current thread until all
|
||||
/// database accesses are completed.
|
||||
///
|
||||
/// - warning: This method can prevent concurrent reads from executing,
|
||||
/// until it returns. Prefer ``releaseMemoryEventually()`` if you intend
|
||||
/// to keep on using the database while releasing memory.
|
||||
public func releaseMemory() {
|
||||
// Release writer memory
|
||||
writer.sync { $0.releaseMemory() }
|
||||
// Release readers memory by closing all connections
|
||||
|
||||
// Release readers memory by closing all connections.
|
||||
//
|
||||
// We must use a barrier in order to guarantee that memory has been
|
||||
// freed (reader connections closed) when the method exits, as
|
||||
// documented.
|
||||
//
|
||||
// Without the barrier, connections would only close _eventually_ (after
|
||||
// their eventual concurrent jobs have completed).
|
||||
readerPool?.barrier {
|
||||
readerPool?.removeAll()
|
||||
}
|
||||
}
|
||||
|
||||
/// Eventually frees as much memory as possible, by disposing non-essential
|
||||
/// memory from the writer connection, and closing all reader connections.
|
||||
///
|
||||
/// Unlike ``releaseMemory()``, this method does not prevent concurrent
|
||||
/// database accesses when it is executing. But it does not notify when
|
||||
/// non-essential memory has been freed.
|
||||
public func releaseMemoryEventually() {
|
||||
// Release readers memory by eventually closing all reader connections
|
||||
// (they will close after their current jobs have completed).
|
||||
readerPool?.removeAll()
|
||||
|
||||
// Release writer memory eventually.
|
||||
writer.async { db in
|
||||
db.releaseMemory()
|
||||
}
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
/// Listens to UIApplicationDidEnterBackgroundNotification and
|
||||
/// UIApplicationDidReceiveMemoryWarningNotification in order to release
|
||||
/// as much memory as possible.
|
||||
private func setupMemoryManagement() {
|
||||
let center = NotificationCenter.default
|
||||
|
||||
// Use raw notification names because of
|
||||
// FB9801372 (UIApplication.didReceiveMemoryWarningNotification should not be declared @MainActor)
|
||||
// TODO: Reuse UIApplication.didReceiveMemoryWarningNotification when possible.
|
||||
// TODO: Reuse UIApplication.didEnterBackgroundNotification when possible.
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabasePool.applicationDidReceiveMemoryWarning(_:)),
|
||||
name: UIApplication.didReceiveMemoryWarningNotification,
|
||||
name: NSNotification.Name(rawValue: "UIApplicationDidReceiveMemoryWarningNotification"),
|
||||
object: nil)
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabasePool.applicationDidEnterBackground(_:)),
|
||||
name: UIApplication.didEnterBackgroundNotification,
|
||||
name: NSNotification.Name(rawValue: "UIApplicationDidEnterBackgroundNotification"),
|
||||
object: nil)
|
||||
}
|
||||
|
||||
@@ -203,12 +241,20 @@ extension DatabasePool {
|
||||
|
||||
let task: UIBackgroundTaskIdentifier = application.beginBackgroundTask(expirationHandler: nil)
|
||||
if task == .invalid {
|
||||
// Perform releaseMemory() synchronously.
|
||||
// Release memory synchronously
|
||||
releaseMemory()
|
||||
} else {
|
||||
// Perform releaseMemory() asynchronously.
|
||||
DispatchQueue.global().async {
|
||||
self.releaseMemory()
|
||||
// Release memory eventually.
|
||||
//
|
||||
// We don't know when reader connections will be closed (because
|
||||
// they may be currently in use), so we don't quite know when
|
||||
// reader memory will be freed (which would be the ideal timing for
|
||||
// ending our background task).
|
||||
//
|
||||
// So let's just end the background task after the writer connection
|
||||
// has freed its memory. That's better than nothing.
|
||||
releaseMemoryEventually()
|
||||
writer.async { _ in
|
||||
application.endBackgroundTask(task)
|
||||
}
|
||||
}
|
||||
@@ -216,9 +262,7 @@ extension DatabasePool {
|
||||
|
||||
@objc
|
||||
private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
|
||||
DispatchQueue.global().async {
|
||||
self.releaseMemory()
|
||||
}
|
||||
releaseMemoryEventually()
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -303,6 +347,7 @@ extension DatabasePool: DatabaseReader {
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func read<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
guard let readerPool = readerPool else {
|
||||
@@ -310,104 +355,45 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
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) {
|
||||
try db.isolated {
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
result = try value(db)
|
||||
return .commit
|
||||
return try value(db)
|
||||
}
|
||||
return result!
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
// First async jump in order to grab a reader connection.
|
||||
// Honor configuration dispatching (qos/targetQueue).
|
||||
let label = configuration.identifier(
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "asyncRead")
|
||||
configuration
|
||||
.makeDispatchQueue(label: label)
|
||||
.async {
|
||||
do {
|
||||
guard let readerPool = self.readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
guard let readerPool = self.readerPool else {
|
||||
value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")))
|
||||
return
|
||||
}
|
||||
|
||||
readerPool.asyncGet { result in
|
||||
do {
|
||||
let (reader, releaseReader) = try result.get()
|
||||
// Second async jump because that's how `Pool.async` has to be used.
|
||||
reader.async { db in
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader()
|
||||
}
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
|
||||
// Second async jump because sync could deadlock if
|
||||
// configuration has a serial targetQueue.
|
||||
reader.async { db in
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader()
|
||||
}
|
||||
do {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
value(.success(db))
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
do {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
value(.success(db))
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncRead(_ value: @escaping (Result<Database, Error>?) -> Void) {
|
||||
// First async jump in order to grab a reader connection.
|
||||
// Honor configuration dispatching (qos/targetQueue).
|
||||
let label = configuration.identifier(
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "asyncRead")
|
||||
configuration
|
||||
.makeDispatchQueue(label: label)
|
||||
.async { [weak self] in
|
||||
guard let self = self else {
|
||||
value(nil)
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
guard let readerPool = self.readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
|
||||
// Second async jump because sync could deadlock if
|
||||
// configuration has a serial targetQueue.
|
||||
reader.weakAsync { db in
|
||||
guard let db = db else {
|
||||
value(nil)
|
||||
return
|
||||
}
|
||||
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader()
|
||||
}
|
||||
do {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
value(.success(db))
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
guard let readerPool = readerPool else {
|
||||
@@ -421,6 +407,34 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
guard let readerPool = self.readerPool else {
|
||||
value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")))
|
||||
return
|
||||
}
|
||||
|
||||
readerPool.asyncGet { result in
|
||||
do {
|
||||
let (reader, releaseReader) = try result.get()
|
||||
// Second async jump because that's how `Pool.async` has to be used.
|
||||
reader.async { db in
|
||||
defer {
|
||||
releaseReader()
|
||||
}
|
||||
do {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
value(.success(db))
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
if let reader = currentReader {
|
||||
return try reader.reentrantSync(value)
|
||||
@@ -633,10 +647,12 @@ extension DatabasePool: DatabaseReader {
|
||||
|
||||
// MARK: - Writing in Database
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
// TODO: throw instead of crashing when the database is closed
|
||||
try readerPool!.barrier {
|
||||
@@ -704,11 +720,6 @@ extension DatabasePool: DatabaseReader {
|
||||
writer.async(updates)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncWriteWithoutTransaction(_ updates: @escaping (Database?) -> Void) {
|
||||
writer.weakAsync(updates)
|
||||
}
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// :nodoc:
|
||||
@@ -719,25 +730,26 @@ extension DatabasePool: DatabaseReader {
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
// The easy case: the database does not change
|
||||
return _addReadOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
}
|
||||
|
||||
if observation.requiresWriteAccess {
|
||||
let observer = _addWriteOnly(
|
||||
|
||||
} else if observation.requiresWriteAccess {
|
||||
// Observe from the writer database connection.
|
||||
return _addWriteOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
|
||||
} else {
|
||||
// DatabasePool can perform concurrent observation
|
||||
return _addConcurrent(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
return AnyDatabaseCancellable(cancel: observer.cancel)
|
||||
}
|
||||
|
||||
let observer = _addConcurrent(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
return AnyDatabaseCancellable(cancel: observer.cancel)
|
||||
}
|
||||
|
||||
/// A concurrent observation fetches the initial value without waiting for
|
||||
@@ -746,178 +758,19 @@ extension DatabasePool: DatabaseReader {
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> ValueObserver<Reducer> // For testability
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
|
||||
assert(!observation.requiresWriteAccess, "Use _addWriteOnly(observation:) instead")
|
||||
|
||||
let reduceQueueLabel = configuration.identifier(
|
||||
defaultLabel: "GRDB",
|
||||
purpose: "ValueObservation")
|
||||
let observer = ValueObserver(
|
||||
observation: observation,
|
||||
writer: self,
|
||||
let observer = ValueConcurrentObserver(
|
||||
dbPool: self,
|
||||
scheduler: scheduler,
|
||||
reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel),
|
||||
trackingMode: observation.trackingMode,
|
||||
reducer: observation.makeReducer(),
|
||||
events: observation.events,
|
||||
onChange: onChange)
|
||||
|
||||
// Starting a concurrent observation means that we'll fetch the initial
|
||||
// value right away, without waiting for an access to the writer queue,
|
||||
// and the opportunity to install a transaction observer.
|
||||
//
|
||||
// This is how DatabasePool can start an observation and promptly notify
|
||||
// an initial value, even when there is a long-running write transaction
|
||||
// in the background.
|
||||
//
|
||||
// We thus have to deal with the fact that between this initial fetch,
|
||||
// and the beginning of transaction tracking, any number of untracked
|
||||
// writes may occur.
|
||||
//
|
||||
// We must notify changes that happen during this untracked window. But
|
||||
// how do we spot them, since we're not tracking database changes yet?
|
||||
//
|
||||
// A safe solution is to always perform a second fetch. We may fetch the
|
||||
// same initial value, if no change did happen. But we don't miss
|
||||
// possible changes.
|
||||
//
|
||||
// We can avoid this second fetch when SQLite is compiled with the
|
||||
// SQLITE_ENABLE_SNAPSHOT option:
|
||||
//
|
||||
// 1. Perform the initial fetch in a DatabaseSnapshot. Its long running
|
||||
// transaction acquires a lock that will prevent checkpointing until we
|
||||
// get a writer access, so that we can reliably compare database
|
||||
// versions with `sqlite3_snapshot`:
|
||||
// https://www.sqlite.org/c3ref/snapshot.html.
|
||||
//
|
||||
// 2. Get a writer access, and compare the versions of the initial
|
||||
// snapshot, and the current state of the database: if versions are
|
||||
// identical, we can avoid the second fetch. If they are not, we perform
|
||||
// the second fetch, even if the actual changes are unrelated to the
|
||||
// tracked database region (we have no way to know).
|
||||
//
|
||||
// 3. Install the transaction observer.
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
let initialSnapshot = try makeSnapshot()
|
||||
let initialValue = try initialSnapshot.read(observer.fetchInitialValue)
|
||||
onChange(initialValue)
|
||||
add(observer: observer, from: initialSnapshot)
|
||||
} catch {
|
||||
observer.complete()
|
||||
observation.events.didFail?(error)
|
||||
}
|
||||
} else {
|
||||
let label = configuration.identifier(
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "ValueObservation")
|
||||
configuration
|
||||
.makeDispatchQueue(label: label)
|
||||
.async { [weak self] in
|
||||
guard let self = self else { return }
|
||||
if observer.isCompleted { return }
|
||||
|
||||
do {
|
||||
let initialSnapshot = try self.makeSnapshot()
|
||||
let initialValue = try initialSnapshot.read(observer.fetchInitialValue)
|
||||
observer.notifyChange(initialValue)
|
||||
self.add(observer: observer, from: initialSnapshot)
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
#else
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
let initialValue = try read(observer.fetchInitialValue)
|
||||
onChange(initialValue)
|
||||
addObserver(observer: observer)
|
||||
} catch {
|
||||
observer.complete()
|
||||
observation.events.didFail?(error)
|
||||
}
|
||||
} else {
|
||||
_weakAsyncRead { [weak self] dbResult in
|
||||
guard let self = self, let dbResult = dbResult else { return }
|
||||
if observer.isCompleted { return }
|
||||
|
||||
do {
|
||||
let initialValue = try observer.fetchInitialValue(dbResult.get())
|
||||
observer.notifyChange(initialValue)
|
||||
self.addObserver(observer: observer)
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
return observer
|
||||
return observer.start()
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT
|
||||
// Support for _addConcurrent(observation:)
|
||||
private func add<Reducer: ValueReducer>(
|
||||
observer: ValueObserver<Reducer>,
|
||||
from initialSnapshot: DatabaseSnapshot)
|
||||
{
|
||||
_weakAsyncWriteWithoutTransaction { db in
|
||||
guard let db = db else { return }
|
||||
if observer.isCompleted { return }
|
||||
|
||||
do {
|
||||
// Transaction is needed for version snapshotting
|
||||
try db.inTransaction(.deferred) {
|
||||
// Keep DatabaseSnaphot alive until we have compared
|
||||
// database versions. It prevents database checkpointing,
|
||||
// and keeps versions (`sqlite3_snapshot`) valid
|
||||
// and comparable.
|
||||
let fetchNeeded: Bool = try withExtendedLifetime(initialSnapshot) {
|
||||
guard let initialVersion = initialSnapshot.version else {
|
||||
return true
|
||||
}
|
||||
return try db.wasChanged(since: initialVersion)
|
||||
}
|
||||
|
||||
if fetchNeeded {
|
||||
observer.events.databaseDidChange?()
|
||||
if let value = try observer.fetchValue(db) {
|
||||
observer.notifyChange(value)
|
||||
}
|
||||
}
|
||||
return .commit
|
||||
}
|
||||
|
||||
// Now we can start observation
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
#else
|
||||
// Support for _addConcurrent(observation:)
|
||||
private func addObserver<Reducer: ValueReducer>(observer: ValueObserver<Reducer>) {
|
||||
_weakAsyncWriteWithoutTransaction { db in
|
||||
guard let db = db else { return }
|
||||
if observer.isCompleted { return }
|
||||
|
||||
do {
|
||||
observer.events.databaseDidChange?()
|
||||
if let value = try observer.fetchValue(db) {
|
||||
observer.notifyChange(value)
|
||||
}
|
||||
|
||||
// Now we can start observation
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
@@ -6,7 +6,7 @@ import UIKit
|
||||
|
||||
/// A DatabaseQueue serializes access to an SQLite database.
|
||||
public final class DatabaseQueue: DatabaseWriter {
|
||||
private var writer: SerializedDatabase
|
||||
private let writer: SerializedDatabase
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
@@ -43,7 +43,9 @@ public final class DatabaseQueue: DatabaseWriter {
|
||||
// Be a nice iOS citizen, and don't consume too much memory
|
||||
// See https://github.com/groue/GRDB.swift/#memory-management
|
||||
#if os(iOS)
|
||||
setupMemoryManagement()
|
||||
if configuration.automaticMemoryManagement {
|
||||
setupMemoryManagement()
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -92,15 +94,20 @@ extension DatabaseQueue {
|
||||
/// as much memory as possible.
|
||||
private func setupMemoryManagement() {
|
||||
let center = NotificationCenter.default
|
||||
|
||||
// Use raw notification names because of
|
||||
// FB9801372 (UIApplication.didReceiveMemoryWarningNotification should not be declared @MainActor)
|
||||
// TODO: Reuse UIApplication.didReceiveMemoryWarningNotification when possible.
|
||||
// TODO: Reuse UIApplication.didEnterBackgroundNotification when possible.
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabaseQueue.applicationDidReceiveMemoryWarning(_:)),
|
||||
name: UIApplication.didReceiveMemoryWarningNotification,
|
||||
name: NSNotification.Name(rawValue: "UIApplicationDidReceiveMemoryWarningNotification"),
|
||||
object: nil)
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabaseQueue.applicationDidEnterBackground(_:)),
|
||||
name: UIApplication.didEnterBackgroundNotification,
|
||||
name: NSNotification.Name(rawValue: "UIApplicationDidEnterBackgroundNotification"),
|
||||
object: nil)
|
||||
}
|
||||
|
||||
@@ -112,12 +119,12 @@ extension DatabaseQueue {
|
||||
|
||||
let task: UIBackgroundTaskIdentifier = application.beginBackgroundTask(expirationHandler: nil)
|
||||
if task == .invalid {
|
||||
// Perform releaseMemory() synchronously.
|
||||
// Release memory synchronously
|
||||
releaseMemory()
|
||||
} else {
|
||||
// Perform releaseMemory() asynchronously.
|
||||
DispatchQueue.global().async {
|
||||
self.releaseMemory()
|
||||
// Release memory asynchronously
|
||||
writer.async { db in
|
||||
db.releaseMemory()
|
||||
application.endBackgroundTask(task)
|
||||
}
|
||||
}
|
||||
@@ -125,8 +132,8 @@ extension DatabaseQueue {
|
||||
|
||||
@objc
|
||||
private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
|
||||
DispatchQueue.global().async {
|
||||
self.releaseMemory()
|
||||
writer.async { db in
|
||||
db.releaseMemory()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -178,16 +185,12 @@ extension DatabaseQueue {
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func read<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try writer.sync { db in
|
||||
// The transaction guarantees snapshot isolation against eventual
|
||||
// external connection.
|
||||
var result: T?
|
||||
try db.inTransaction(.deferred) {
|
||||
result = try db.readOnly { try value(db) }
|
||||
return .commit
|
||||
try db.isolated(readOnly: true) {
|
||||
try value(db)
|
||||
}
|
||||
return result!
|
||||
}
|
||||
}
|
||||
|
||||
@@ -211,36 +214,14 @@ extension DatabaseQueue {
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncRead(_ value: @escaping (Result<Database, Error>?) -> Void) {
|
||||
writer.weakAsync { db in
|
||||
guard let db = db else {
|
||||
value(nil)
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
// The transaction guarantees snapshot isolation against eventual
|
||||
// external connection.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.beginReadOnly()
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
return
|
||||
}
|
||||
|
||||
value(.success(db))
|
||||
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.endReadOnly()
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) rethrows -> T {
|
||||
try writer.sync(value)
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
writer.async { value(.success($0)) }
|
||||
}
|
||||
|
||||
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) rethrows -> T {
|
||||
try writer.reentrantSync(value)
|
||||
}
|
||||
@@ -249,18 +230,11 @@ extension DatabaseQueue {
|
||||
// DatabaseQueue can't perform parallel reads.
|
||||
// Perform a blocking read instead.
|
||||
return DatabaseFuture(Result {
|
||||
// Check that we're on the writer queue...
|
||||
// Check that we're on the writer queue, as documented
|
||||
try writer.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
|
||||
// The transaction guarantees snapshot isolation against eventual
|
||||
// external connection.
|
||||
var result: T?
|
||||
try db.inTransaction(.deferred) {
|
||||
result = try db.readOnly { try value(db) }
|
||||
return .commit
|
||||
try db.isolated(readOnly: true) {
|
||||
try value(db)
|
||||
}
|
||||
return result!
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -329,10 +303,12 @@ extension DatabaseQueue {
|
||||
}
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
@@ -366,11 +342,6 @@ extension DatabaseQueue {
|
||||
writer.async(updates)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncWriteWithoutTransaction(_ updates: @escaping (Database?) -> Void) {
|
||||
writer.weakAsync(updates)
|
||||
}
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// :nodoc:
|
||||
@@ -381,16 +352,17 @@ extension DatabaseQueue {
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
// The easy case: the database does not change
|
||||
return _addReadOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
} else {
|
||||
// Observe from the writer database connection.
|
||||
return _addWriteOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
}
|
||||
|
||||
let observer = _addWriteOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
return AnyDatabaseCancellable(cancel: observer.cancel)
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ import Dispatch
|
||||
/// connection to the database. Should you have to cope with external
|
||||
/// connections, protect yourself with transactions, and be ready to setup a
|
||||
/// [busy handler](https://www.sqlite.org/c3ref/busy_handler.html).
|
||||
public protocol DatabaseReader: AnyObject {
|
||||
public protocol DatabaseReader: AnyObject, GRDBSendable {
|
||||
|
||||
/// The database configuration
|
||||
var configuration: Configuration { get }
|
||||
@@ -148,6 +148,7 @@ public protocol DatabaseReader: AnyObject {
|
||||
/// - parameter value: A function that accesses the database.
|
||||
/// - throws: The error thrown by `value`, or any `DatabaseError` that would
|
||||
/// happen while establishing the read access to the database.
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
func read<T>(_ value: (Database) throws -> T) throws -> T
|
||||
|
||||
/// Asynchronously executes a read-only function that accepts a
|
||||
@@ -177,11 +178,6 @@ public protocol DatabaseReader: AnyObject {
|
||||
/// that would prevent establishing the read access to the database.
|
||||
func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void)
|
||||
|
||||
/// Same as asyncRead, but without retaining self
|
||||
///
|
||||
/// :nodoc:
|
||||
func _weakAsyncRead(_ value: @escaping (Result<Database, Error>?) -> Void)
|
||||
|
||||
/// Synchronously executes a function that accepts a database
|
||||
/// connection, and returns its result.
|
||||
///
|
||||
@@ -218,8 +214,37 @@ public protocol DatabaseReader: AnyObject {
|
||||
/// - parameter value: A function that accesses the database.
|
||||
/// - throws: The error thrown by `value`, or any `DatabaseError` that would
|
||||
/// happen while establishing the read access to the database.
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T
|
||||
|
||||
/// Asynchronously executes a function that accepts a database connection.
|
||||
///
|
||||
/// The guarantees of the `asyncRead` method are lifted:
|
||||
///
|
||||
/// the `value` function is not isolated: eventual concurrent database
|
||||
/// updates are visible from the function:
|
||||
///
|
||||
/// reader.asyncUnsafeRead { dbResult in
|
||||
/// do {
|
||||
/// let db = try dbResult.get()
|
||||
/// // Those two values can be different, because some other
|
||||
/// // database connection or some other thread may modify the
|
||||
/// // database between the two requests.
|
||||
/// let count1 = try Player.fetchCount(db)
|
||||
/// let count2 = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // handle error
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// The `value` function is not prevented from writing (DatabaseQueue, in
|
||||
/// particular, will accept database modifications in `asyncUnsafeRead`).
|
||||
///
|
||||
/// - parameter value: A function that accesses the database. Its argument
|
||||
/// is a `Result` that provides the database connection, or the failure
|
||||
/// that would prevent establishing the read access to the database.
|
||||
func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void)
|
||||
|
||||
/// Synchronously executes a function that accepts a database
|
||||
/// connection, and returns its result.
|
||||
///
|
||||
@@ -278,27 +303,170 @@ extension DatabaseReader {
|
||||
/// When the source is a DatabasePool, concurrent writes can happen during
|
||||
/// the backup. Those writes may, or may not, be reflected in the backup,
|
||||
/// but they won't trigger any error.
|
||||
public func backup(to writer: DatabaseWriter) throws {
|
||||
try writer.writeWithoutTransaction { dbDest in
|
||||
try backup(to: dbDest)
|
||||
///
|
||||
/// Usage:
|
||||
///
|
||||
/// let source: DatabaseQueue = ...
|
||||
/// let destination: DatabaseQueue = ...
|
||||
/// try source.backup(to: destination)
|
||||
///
|
||||
/// When you're after progress reporting during backup, you'll want to
|
||||
/// perform the backup in several steps. Each step copies the number of
|
||||
/// _database pages_ you specify. See <https://www.sqlite.org/c3ref/backup_finish.html>
|
||||
/// for more information:
|
||||
///
|
||||
/// // Backup with progress reporting
|
||||
/// try source.backup(
|
||||
/// to: destination,
|
||||
/// pagesPerStep: ...)
|
||||
/// { backupProgress in
|
||||
/// print("Database backup progress:", backupProgress)
|
||||
/// }
|
||||
///
|
||||
/// The `progress` callback will be called at least once—when
|
||||
/// `backupProgress.isCompleted == true`. If the callback throws
|
||||
/// when `backupProgress.isCompleted == false`, the backup is aborted
|
||||
/// and the error is rethrown. If the callback throws when
|
||||
/// `backupProgress.isCompleted == true`, backup completion is
|
||||
/// unaffected and the error is silently ignored.
|
||||
///
|
||||
/// See also `Database.backup()`.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - writer: The destination database.
|
||||
/// - pagesPerStep: The number of database pages copied on each backup
|
||||
/// step. By default, all pages are copied in one single step.
|
||||
/// - progress: An optional function that is notified of the backup
|
||||
/// progress.
|
||||
/// - throws: The error thrown by `progress` if the backup is abandoned, or
|
||||
/// any `DatabaseError` that would happen while performing the backup.
|
||||
public func backup(
|
||||
to writer: DatabaseWriter,
|
||||
pagesPerStep: Int32 = -1,
|
||||
progress: ((DatabaseBackupProgress) throws -> Void)? = nil)
|
||||
throws
|
||||
{
|
||||
try writer.writeWithoutTransaction { destDb in
|
||||
try backup(
|
||||
to: destDb,
|
||||
pagesPerStep: pagesPerStep,
|
||||
afterBackupStep: progress)
|
||||
}
|
||||
}
|
||||
|
||||
func backup(
|
||||
to dbDest: Database,
|
||||
to destDb: Database,
|
||||
pagesPerStep: Int32 = -1,
|
||||
afterBackupInit: (() -> Void)? = nil,
|
||||
afterBackupStep: (() -> Void)? = nil)
|
||||
afterBackupStep: ((DatabaseBackupProgress) throws -> Void)? = nil)
|
||||
throws
|
||||
{
|
||||
try read { dbFrom in
|
||||
try dbFrom.backup(
|
||||
to: dbDest,
|
||||
try dbFrom.backupInternal(
|
||||
to: destDb,
|
||||
pagesPerStep: pagesPerStep,
|
||||
afterBackupInit: afterBackupInit,
|
||||
afterBackupStep: afterBackupStep)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=5.6) && canImport(_Concurrency)
|
||||
extension DatabaseReader {
|
||||
// MARK: - Asynchronous Database Access
|
||||
|
||||
// TODO: remove @escaping as soon as it is possible
|
||||
/// Asynchronously executes a read-only function that accepts a database
|
||||
/// connection, and returns its result.
|
||||
///
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let count = try await reader.read { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// The `value` function runs in an isolated fashion: eventual concurrent
|
||||
/// database updates are not visible from the function:
|
||||
///
|
||||
/// try await reader.read { db in
|
||||
/// // Those two values are guaranteed to be equal, even if the
|
||||
/// // `player` table is modified, between the two requests, by
|
||||
/// // some other database connection or some other thread.
|
||||
/// let count1 = try Player.fetchCount(db)
|
||||
/// let count2 = try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// try await reader.read { db in
|
||||
/// // Now this value may be different:
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// Attempts to write in the database throw a DatabaseError with
|
||||
/// resultCode `SQLITE_READONLY`.
|
||||
///
|
||||
/// - parameter value: A function that accesses the database.
|
||||
/// - throws: The error thrown by `value`, or any `DatabaseError` that would
|
||||
/// happen while establishing the read access to the database.
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func read<T>(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
asyncRead { result in
|
||||
do {
|
||||
try continuation.resume(returning: value(result.get()))
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: remove @escaping as soon as it is possible
|
||||
/// Asynchronously executes a function that accepts a database connection.
|
||||
///
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let count = try await reader.unsafeRead { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// The guarantees of the `read` method are lifted:
|
||||
///
|
||||
/// the `value` function is not isolated: eventual concurrent database
|
||||
/// updates are visible from the function:
|
||||
///
|
||||
/// try await reader.asyncRead { db in
|
||||
/// // Those two values can be different, because some other
|
||||
/// // database connection or some other thread may modify the
|
||||
/// // database between the two requests.
|
||||
/// let count1 = try Player.fetchCount(db)
|
||||
/// let count2 = try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// The `value` function is not prevented from writing (DatabaseQueue, in
|
||||
/// particular, will accept database modifications in `asyncUnsafeRead`).
|
||||
///
|
||||
/// - parameter value: A function that accesses the database.
|
||||
/// - throws: The error thrown by `value`, or any `DatabaseError` that would
|
||||
/// happen while establishing the read access to the database.
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func unsafeRead<T>(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
asyncUnsafeRead { result in
|
||||
do {
|
||||
try continuation.resume(returning: value(result.get()))
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if canImport(Combine)
|
||||
extension DatabaseReader {
|
||||
// MARK: - Publishing Database Values
|
||||
@@ -393,18 +561,22 @@ extension DatabaseReader {
|
||||
{
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
let value = try unsafeReentrantRead(observation.fetchValue)
|
||||
// Perform a reentrant read, in case the observation would be
|
||||
// started from a database access.
|
||||
let value = try unsafeReentrantRead { db in
|
||||
try db.isolated(readOnly: true) {
|
||||
try observation.fetchValue(db)
|
||||
}
|
||||
}
|
||||
onChange(value)
|
||||
} catch {
|
||||
observation.events.didFail?(error)
|
||||
}
|
||||
return AnyDatabaseCancellable(cancel: { })
|
||||
return AnyDatabaseCancellable(cancel: { /* nothing to cancel */ })
|
||||
} else {
|
||||
var isCancelled = false
|
||||
_weakAsyncRead { dbResult in
|
||||
guard !isCancelled,
|
||||
let dbResult = dbResult
|
||||
else { return }
|
||||
asyncRead { dbResult in
|
||||
guard !isCancelled else { return }
|
||||
|
||||
let result = dbResult.flatMap { db in
|
||||
Result { try observation.fetchValue(db) }
|
||||
@@ -452,6 +624,7 @@ public final class AnyDatabaseReader: DatabaseReader {
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func read<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try base.read(value)
|
||||
}
|
||||
@@ -460,15 +633,15 @@ public final class AnyDatabaseReader: DatabaseReader {
|
||||
base.asyncRead(value)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncRead(_ value: @escaping (Result<Database, Error>?) -> Void) {
|
||||
base._weakAsyncRead(value)
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try base.unsafeRead(value)
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
base.asyncUnsafeRead(value)
|
||||
}
|
||||
|
||||
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try base.unsafeReentrantRead(value)
|
||||
}
|
||||
|
||||
@@ -55,6 +55,14 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
/// from all tables.
|
||||
public static let fullDatabase = DatabaseRegion(tableRegions: nil)
|
||||
|
||||
// TODO: rename to init(table:) when this initializer is no longer public
|
||||
/// The region that covers a full database table: all columns and all rows
|
||||
/// from this table.
|
||||
static func fullTable(_ table: String) -> DatabaseRegion {
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
return DatabaseRegion(tableRegions: [table: TableRegion(columns: nil, rowIds: nil)])
|
||||
}
|
||||
|
||||
/// Creates an empty database region.
|
||||
public init() {
|
||||
self.init(tableRegions: [:])
|
||||
@@ -63,9 +71,9 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
/// Creates a region that spans all rows and columns of a database table.
|
||||
///
|
||||
/// - parameter table: A table name.
|
||||
@available(*, deprecated, message: "In order to specify a table region, prefer `Table(tableName)`")
|
||||
public init(table: String) {
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: nil)])
|
||||
self = .fullTable(table)
|
||||
}
|
||||
|
||||
/// Full columns in a table: (some columns in a table) × (all rows)
|
||||
@@ -261,7 +269,7 @@ extension DatabaseRegion {
|
||||
}
|
||||
return tableRegions
|
||||
.sorted(by: { (l, r) in l.key.rawValue < r.key.rawValue })
|
||||
.map({ (table, tableRegion) in
|
||||
.map { (table, tableRegion) in
|
||||
var desc = table.rawValue
|
||||
if let columns = tableRegion.columns {
|
||||
desc += "(" + columns.map(\.rawValue).sorted().joined(separator: ",") + ")"
|
||||
@@ -272,7 +280,7 @@ extension DatabaseRegion {
|
||||
desc += "[" + rowIds.sorted().map { "\($0)" }.joined(separator: ",") + "]"
|
||||
}
|
||||
return desc
|
||||
})
|
||||
}
|
||||
.joined(separator: ",")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ extension DatabaseRegionObservation {
|
||||
/// on subscription.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func publisher(in writer: DatabaseWriter) -> DatabasePublishers.DatabaseRegion {
|
||||
return DatabasePublishers.DatabaseRegion(self, in: writer)
|
||||
DatabasePublishers.DatabaseRegion(self, in: writer)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -6,19 +6,14 @@ import Dispatch
|
||||
/// See DatabasePool.makeSnapshot()
|
||||
///
|
||||
/// For more information, read about "snapshot isolation" at <https://sqlite.org/isolation.html>
|
||||
public class DatabaseSnapshot: DatabaseReader {
|
||||
private var serializedDatabase: SerializedDatabase
|
||||
public final class DatabaseSnapshot: DatabaseReader {
|
||||
private let serializedDatabase: SerializedDatabase
|
||||
|
||||
/// The database configuration
|
||||
public var configuration: Configuration {
|
||||
serializedDatabase.configuration
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT
|
||||
// Support for ValueObservation in DatabasePool
|
||||
private(set) var version: UnsafeMutablePointer<sqlite3_snapshot>?
|
||||
#endif
|
||||
|
||||
init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws {
|
||||
var configuration = DatabasePool.readerConfiguration(configuration)
|
||||
configuration.allowsUnsafeTransactions = true // Snaphost keeps a long-lived transaction
|
||||
@@ -41,23 +36,12 @@ public class DatabaseSnapshot: DatabaseReader {
|
||||
|
||||
// Acquire snapshot isolation
|
||||
try db.internalCachedStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next()
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT
|
||||
// We must expect an error: https://www.sqlite.org/c3ref/snapshot_get.html
|
||||
// > At least one transaction must be written to it first.
|
||||
version = try? db.takeVersionSnapshot()
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
// Leave snapshot isolation
|
||||
serializedDatabase.reentrantSync { db in
|
||||
#if SQLITE_ENABLE_SNAPSHOT
|
||||
if let version = version {
|
||||
sqlite3_snapshot_free(version)
|
||||
}
|
||||
#endif
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
@@ -86,15 +70,14 @@ extension DatabaseSnapshot {
|
||||
serializedDatabase.async { value(.success($0)) }
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncRead(_ value: @escaping (Result<Database, Error>?) -> Void) {
|
||||
serializedDatabase.weakAsync { value($0.map { .success($0) }) }
|
||||
}
|
||||
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) rethrows -> T {
|
||||
try serializedDatabase.sync(value)
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
serializedDatabase.async { value(.success($0)) }
|
||||
}
|
||||
|
||||
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try serializedDatabase.reentrantSync(value)
|
||||
}
|
||||
|
||||
@@ -157,6 +157,14 @@ extension DatabaseValue: StatementBinding {
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValue: GRDBSendable { }
|
||||
|
||||
#if swift(>=5.6) && canImport(_Concurrency)
|
||||
// @unchecked due to Foundation.Data not conforming to Sendable
|
||||
// TODO: Remove @unchecked when Foundation has been upgraded
|
||||
extension DatabaseValue.Storage: @unchecked Sendable { }
|
||||
#endif
|
||||
|
||||
// MARK: - Hashable & Equatable
|
||||
|
||||
// Hashable
|
||||
|
||||
@@ -126,74 +126,39 @@ extension DatabaseValueConvertible {
|
||||
/// print(url)
|
||||
/// }
|
||||
/// }
|
||||
public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor {
|
||||
private enum _State {
|
||||
case idle, busy, done, failed
|
||||
}
|
||||
|
||||
private let _statement: Statement
|
||||
private let _sqliteStatement: SQLiteStatement
|
||||
private let _columnIndex: Int32
|
||||
private var _state = _State.idle
|
||||
public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: DatabaseCursor {
|
||||
public typealias Element = Value
|
||||
public let statement: Statement
|
||||
/// :nodoc:
|
||||
public var _isDone = false
|
||||
private let columnIndex: Int32
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
_statement = statement
|
||||
_sqliteStatement = statement.sqliteStatement
|
||||
self.statement = statement
|
||||
if let adapter = adapter {
|
||||
// adapter may redefine the index of the leftmost column
|
||||
_columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
|
||||
columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
|
||||
} else {
|
||||
_columnIndex = 0
|
||||
columnIndex = 0
|
||||
}
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
statement.reset(withArguments: arguments)
|
||||
try statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
if _state == .busy {
|
||||
try? _statement.database.statementDidExecute(_statement)
|
||||
}
|
||||
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? _statement.reset()
|
||||
try? statement.reset()
|
||||
}
|
||||
|
||||
public func next() throws -> Value? {
|
||||
switch _state {
|
||||
case .done:
|
||||
// make sure this instance never yields a value again, even if the
|
||||
// statement is reset by another cursor.
|
||||
return nil
|
||||
case .idle:
|
||||
guard try _statement.database.statementWillExecute(_statement) == nil else {
|
||||
throw DatabaseError(
|
||||
resultCode: SQLITE_MISUSE,
|
||||
message: "Can't run statement that requires a customized authorizer from a cursor",
|
||||
sql: _statement.sql,
|
||||
arguments: _statement.arguments)
|
||||
}
|
||||
_state = .busy
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
switch sqlite3_step(_sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
_state = .done
|
||||
try _statement.database.statementDidExecute(_statement)
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
return try! Value.decode(
|
||||
fromStatement: _sqliteStatement,
|
||||
atUncheckedIndex: _columnIndex,
|
||||
context: RowDecodingContext(statement: _statement, index: Int(_columnIndex)))
|
||||
case let code:
|
||||
_state = .failed
|
||||
try _statement.database.statementDidFail(_statement, withResultCode: code)
|
||||
}
|
||||
/// :nodoc:
|
||||
public func _element(sqliteStatement: SQLiteStatement) -> Value {
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
try! Value.decode(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: columnIndex,
|
||||
context: RowDecodingContext(statement: statement, index: Int(columnIndex)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,74 +171,39 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor
|
||||
/// print(url)
|
||||
/// }
|
||||
/// }
|
||||
public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor {
|
||||
private enum _State {
|
||||
case idle, busy, done, failed
|
||||
}
|
||||
|
||||
private let _statement: Statement
|
||||
private let _sqliteStatement: SQLiteStatement
|
||||
private let _columnIndex: Int32
|
||||
private var _state = _State.idle
|
||||
public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>: DatabaseCursor {
|
||||
public typealias Element = Value?
|
||||
public let statement: Statement
|
||||
/// :nodoc:
|
||||
public var _isDone = false
|
||||
private let columnIndex: Int32
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
_statement = statement
|
||||
_sqliteStatement = statement.sqliteStatement
|
||||
self.statement = statement
|
||||
if let adapter = adapter {
|
||||
// adapter may redefine the index of the leftmost column
|
||||
_columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
|
||||
columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
|
||||
} else {
|
||||
_columnIndex = 0
|
||||
columnIndex = 0
|
||||
}
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
statement.reset(withArguments: arguments)
|
||||
try statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
if _state == .busy {
|
||||
try? _statement.database.statementDidExecute(_statement)
|
||||
}
|
||||
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? _statement.reset()
|
||||
try? statement.reset()
|
||||
}
|
||||
|
||||
public func next() throws -> Value?? {
|
||||
switch _state {
|
||||
case .done:
|
||||
// make sure this instance never yields a value again, even if the
|
||||
// statement is reset by another cursor.
|
||||
return nil
|
||||
case .idle:
|
||||
guard try _statement.database.statementWillExecute(_statement) == nil else {
|
||||
throw DatabaseError(
|
||||
resultCode: SQLITE_MISUSE,
|
||||
message: "Can't run statement that requires a customized authorizer from a cursor",
|
||||
sql: _statement.sql,
|
||||
arguments: _statement.arguments)
|
||||
}
|
||||
_state = .busy
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
switch sqlite3_step(_sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
_state = .done
|
||||
try _statement.database.statementDidExecute(_statement)
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
return try! Value.decodeIfPresent(
|
||||
fromStatement: _sqliteStatement,
|
||||
atUncheckedIndex: _columnIndex,
|
||||
context: RowDecodingContext(statement: _statement, index: Int(_columnIndex)))
|
||||
case let code:
|
||||
_state = .failed
|
||||
try _statement.database.statementDidFail(_statement, withResultCode: code)
|
||||
}
|
||||
/// :nodoc:
|
||||
public func _element(sqliteStatement: SQLiteStatement) -> Value? {
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
try! Value.decodeIfPresent(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: columnIndex,
|
||||
context: RowDecodingContext(statement: statement, index: Int(columnIndex)))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -46,6 +46,7 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates, or by the
|
||||
/// wrapping transaction.
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
func write<T>(_ updates: (Database) throws -> T) throws -> T
|
||||
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
@@ -67,6 +68,7 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
///
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates.
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T
|
||||
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
@@ -86,6 +88,7 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
///
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates.
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T
|
||||
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
@@ -131,12 +134,6 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// in a transaction.
|
||||
func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
|
||||
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, without retaining self.
|
||||
///
|
||||
/// :nodoc:
|
||||
func _weakAsyncWriteWithoutTransaction(_ updates: @escaping (Database?) -> Void)
|
||||
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, and returns the result.
|
||||
///
|
||||
@@ -296,14 +293,13 @@ extension DatabaseWriter {
|
||||
}
|
||||
|
||||
public func remove(transactionObserver: TransactionObserver) {
|
||||
_weakAsyncWriteWithoutTransaction {
|
||||
$0?.remove(transactionObserver: transactionObserver)
|
||||
}
|
||||
writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) }
|
||||
}
|
||||
|
||||
// MARK: - Erasing the content of the database
|
||||
|
||||
/// Erases the content of the database.
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func erase() throws {
|
||||
try barrierWriteWithoutTransaction { try $0.erase() }
|
||||
}
|
||||
@@ -314,6 +310,7 @@ extension DatabaseWriter {
|
||||
/// disk space.
|
||||
///
|
||||
/// See <https://www.sqlite.org/lang_vacuum.html> for more information.
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func vacuum() throws {
|
||||
try writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
|
||||
}
|
||||
@@ -338,6 +335,7 @@ extension DatabaseWriter {
|
||||
/// See <https://www.sqlite.org/lang_vacuum.html#vacuuminto> for more information.
|
||||
///
|
||||
/// - Parameter filePath: file path for new database
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func vacuum(into filePath: String) throws {
|
||||
try writeWithoutTransaction {
|
||||
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
|
||||
@@ -349,6 +347,7 @@ extension DatabaseWriter {
|
||||
/// See <https://www.sqlite.org/lang_vacuum.html#vacuuminto> for more information.
|
||||
///
|
||||
/// - Parameter filePath: file path for new database
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
@available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *)
|
||||
public func vacuum(into filePath: String) throws {
|
||||
try writeWithoutTransaction {
|
||||
@@ -359,54 +358,144 @@ extension DatabaseWriter {
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// A write-only observation only uses the serialized writer
|
||||
/// Starts an observation that fetches fresh database values synchronously,
|
||||
/// from the writer database connection, right after the database
|
||||
/// was modified.
|
||||
func _addWriteOnly<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> ValueObserver<Reducer> // For testability
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
|
||||
|
||||
let reduceQueueLabel = configuration.identifier(
|
||||
defaultLabel: "GRDB",
|
||||
purpose: "ValueObservation")
|
||||
let observer = ValueObserver(
|
||||
observation: observation,
|
||||
let observer = ValueWriteOnlyObserver(
|
||||
writer: self,
|
||||
scheduler: scheduler,
|
||||
reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel),
|
||||
readOnly: !observation.requiresWriteAccess,
|
||||
trackingMode: observation.trackingMode,
|
||||
reducer: observation.makeReducer(),
|
||||
events: observation.events,
|
||||
onChange: onChange)
|
||||
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
let initialValue: Reducer.Value = try unsafeReentrantWrite { db in
|
||||
let initialValue = try observer.fetchInitialValue(db)
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
return initialValue
|
||||
}
|
||||
onChange(initialValue)
|
||||
} catch {
|
||||
observer.complete()
|
||||
observation.events.didFail?(error)
|
||||
}
|
||||
} else {
|
||||
_weakAsyncWriteWithoutTransaction { db in
|
||||
guard let db = db else { return }
|
||||
if observer.isCompleted { return }
|
||||
return observer.start()
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=5.6) && canImport(_Concurrency)
|
||||
extension DatabaseWriter {
|
||||
// MARK: - Asynchronous Database Access
|
||||
|
||||
// TODO: remove @escaping as soon as it is possible
|
||||
/// Asynchronously executes database updates, wrapped inside a transaction,
|
||||
/// and returns the result.
|
||||
///
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// If the updates throw an error, the transaction is rollbacked and the
|
||||
/// error is rethrown.
|
||||
///
|
||||
/// Eventual concurrent reads are guaranteed to not see any partial updates
|
||||
/// of the database until the transaction has completed.
|
||||
///
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates, or by the
|
||||
/// wrapping transaction.
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func write<T>(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
asyncWrite(updates, completion: { _, result in
|
||||
continuation.resume(with: result)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: remove @escaping as soon as it is possible
|
||||
/// Asynchronously executes database updates, outside of any transaction,
|
||||
/// and returns the result.
|
||||
///
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Eventual concurrent reads may see partial updates unless you wrap them
|
||||
/// in a transaction.
|
||||
///
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates.
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func writeWithoutTransaction<T>(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
asyncWriteWithoutTransaction { db in
|
||||
do {
|
||||
let initialValue = try observer.fetchInitialValue(db)
|
||||
observer.notifyChange(initialValue)
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
try continuation.resume(returning: updates(db))
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return observer
|
||||
}
|
||||
|
||||
// TODO: remove @escaping as soon as it is possible
|
||||
/// Asynchronously executes database updates, outside of any transaction,
|
||||
/// and returns the result.
|
||||
///
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Updates are guaranteed an exclusive access to the database. They wait
|
||||
/// until all pending writes and reads are completed. They postpone all
|
||||
/// other writes and reads until they are completed.
|
||||
///
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates.
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func barrierWriteWithoutTransaction<T>(
|
||||
_ updates: @Sendable @escaping (Database) throws -> T)
|
||||
async throws -> T
|
||||
{
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
asyncBarrierWriteWithoutTransaction { db in
|
||||
do {
|
||||
try continuation.resume(returning: updates(db))
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Erases the content of the database.
|
||||
///
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func erase() async throws {
|
||||
try await writeWithoutTransaction { try $0.erase() }
|
||||
}
|
||||
|
||||
/// Rebuilds the database file, repacking it into a minimal amount of
|
||||
/// disk space.
|
||||
///
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// See <https://www.sqlite.org/lang_vacuum.html> for more information.
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func vacuum() async throws {
|
||||
try await writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
|
||||
}
|
||||
|
||||
/// Creates a new database file at the specified path with a minimum
|
||||
/// amount of disk space.
|
||||
///
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// See <https://www.sqlite.org/lang_vacuum.html#vacuuminto> for more information.
|
||||
///
|
||||
/// - Parameter filePath: file path for new database
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func vacuum(into filePath: String) async throws {
|
||||
try await writeWithoutTransaction {
|
||||
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
#if canImport(Combine)
|
||||
extension DatabaseWriter {
|
||||
@@ -452,11 +541,11 @@ extension DatabaseWriter {
|
||||
-> DatabasePublishers.Write<Output>
|
||||
where S: Scheduler
|
||||
{
|
||||
OnDemandFuture({ fulfill in
|
||||
OnDemandFuture { fulfill in
|
||||
self.asyncWrite(updates, completion: { _, result in
|
||||
fulfill(result)
|
||||
})
|
||||
})
|
||||
}
|
||||
// We don't want users to process emitted values on a
|
||||
// database dispatch queue.
|
||||
.receiveValues(on: scheduler)
|
||||
@@ -505,7 +594,7 @@ extension DatabaseWriter {
|
||||
-> DatabasePublishers.Write<Output>
|
||||
where S: Scheduler
|
||||
{
|
||||
OnDemandFuture({ fulfill in
|
||||
OnDemandFuture { fulfill in
|
||||
self.asyncWriteWithoutTransaction { db in
|
||||
var updatesValue: T?
|
||||
do {
|
||||
@@ -521,7 +610,7 @@ extension DatabaseWriter {
|
||||
fulfill(dbResult.flatMap { db in Result { try value(db, updatesValue!) } })
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
// We don't want users to process emitted values on a
|
||||
// database dispatch queue.
|
||||
.receiveValues(on: scheduler)
|
||||
@@ -627,6 +716,7 @@ public final class AnyDatabaseWriter: DatabaseWriter {
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func read<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try base.read(value)
|
||||
}
|
||||
@@ -635,15 +725,15 @@ public final class AnyDatabaseWriter: DatabaseWriter {
|
||||
base.asyncRead(value)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncRead(_ value: @escaping (Result<Database, Error>?) -> Void) {
|
||||
base._weakAsyncRead(value)
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try base.unsafeRead(value)
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
base.asyncUnsafeRead(value)
|
||||
}
|
||||
|
||||
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try base.unsafeReentrantRead(value)
|
||||
}
|
||||
@@ -659,14 +749,17 @@ public final class AnyDatabaseWriter: DatabaseWriter {
|
||||
|
||||
// MARK: - Writing in Database
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func write<T>(_ updates: (Database) throws -> T) throws -> T {
|
||||
try base.write(updates)
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try base.writeWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try base.barrierWriteWithoutTransaction(updates)
|
||||
}
|
||||
@@ -686,11 +779,6 @@ public final class AnyDatabaseWriter: DatabaseWriter {
|
||||
base.asyncWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncWriteWithoutTransaction(_ updates: @escaping (Database?) -> Void) {
|
||||
base._weakAsyncWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try base.unsafeReentrantWrite(updates)
|
||||
}
|
||||
|
||||
@@ -287,7 +287,7 @@ extension Row {
|
||||
/// The result is nil if the row does not contain the column.
|
||||
public subscript(_ columnName: String) -> DatabaseValueConvertible? {
|
||||
// IMPLEMENTATION NOTE
|
||||
// This method has a single know use case: checking if the value is nil,
|
||||
// This method has a single known use case: checking if the value is nil,
|
||||
// as in:
|
||||
//
|
||||
// if row["foo"] != nil { ... }
|
||||
@@ -1199,67 +1199,30 @@ extension Row {
|
||||
/// try dbQueue.read { db in
|
||||
/// let rows: RowCursor = try Row.fetchCursor(db, sql: "SELECT * FROM player")
|
||||
/// }
|
||||
public final class RowCursor: Cursor {
|
||||
private enum _State {
|
||||
case idle, busy, done, failed
|
||||
}
|
||||
|
||||
/// The statement iterated by this cursor
|
||||
public final class RowCursor: DatabaseCursor {
|
||||
public typealias Element = Row
|
||||
public let statement: Statement
|
||||
private let _sqliteStatement: SQLiteStatement
|
||||
private let _row: Row // Reused for performance
|
||||
private var _state = _State.idle
|
||||
/// :nodoc:
|
||||
public var _isDone = false
|
||||
@usableFromInline let _row: Row // Reused for performance
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
self._row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
self._sqliteStatement = statement.sqliteStatement
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
statement.reset(withArguments: arguments)
|
||||
try statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
if _state == .busy {
|
||||
try? statement.database.statementDidExecute(statement)
|
||||
}
|
||||
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? statement.reset()
|
||||
}
|
||||
|
||||
public func next() throws -> Row? {
|
||||
switch _state {
|
||||
case .done:
|
||||
// make sure this instance never yields a value again, even if the
|
||||
// statement is reset by another cursor.
|
||||
return nil
|
||||
case .idle:
|
||||
guard try statement.database.statementWillExecute(statement) == nil else {
|
||||
throw DatabaseError(
|
||||
resultCode: SQLITE_MISUSE,
|
||||
message: "Can't run statement that requires a customized authorizer from a cursor",
|
||||
sql: statement.sql,
|
||||
arguments: statement.arguments)
|
||||
}
|
||||
_state = .busy
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
switch sqlite3_step(_sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
_state = .done
|
||||
try statement.database.statementDidExecute(statement)
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return _row
|
||||
case let code:
|
||||
_state = .failed
|
||||
try statement.database.statementDidFail(statement, withResultCode: code)
|
||||
}
|
||||
}
|
||||
/// :nodoc:
|
||||
@inlinable
|
||||
public func _element(sqliteStatement: SQLiteStatement) -> Row { _row }
|
||||
}
|
||||
|
||||
extension Row {
|
||||
@@ -1322,7 +1285,7 @@ extension Row {
|
||||
throws -> [Row]
|
||||
{
|
||||
// The cursor reuses a single mutable row. Return immutable copies.
|
||||
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter).map { $0.copy() })
|
||||
try Array(fetchCursor(statement, arguments: arguments, adapter: adapter).map { $0.copy() })
|
||||
}
|
||||
|
||||
/// Returns a set of rows fetched from a prepared statement.
|
||||
@@ -1343,7 +1306,7 @@ extension Row {
|
||||
throws -> Set<Row>
|
||||
{
|
||||
// The cursor reuses a single mutable row. Return immutable copies.
|
||||
return try Set(fetchCursor(statement, arguments: arguments, adapter: adapter).map { $0.copy() })
|
||||
try Set(fetchCursor(statement, arguments: arguments, adapter: adapter).map { $0.copy() })
|
||||
}
|
||||
|
||||
/// Returns a single row fetched from a prepared statement.
|
||||
@@ -2126,27 +2089,27 @@ protocol RowImpl {
|
||||
extension RowImpl {
|
||||
func copiedRow(_ row: Row) -> Row {
|
||||
// unless customized, assume unsafe and unadapted row
|
||||
return Row(impl: ArrayRowImpl(columns: Array(row)))
|
||||
Row(impl: ArrayRowImpl(columns: Array(row)))
|
||||
}
|
||||
|
||||
func unscopedRow(_ row: Row) -> Row {
|
||||
// unless customized, assume unadapted row (see AdaptedRowImpl for customization)
|
||||
return row
|
||||
row
|
||||
}
|
||||
|
||||
func unadaptedRow(_ row: Row) -> Row {
|
||||
// unless customized, assume unadapted row (see AdaptedRowImpl for customization)
|
||||
return row
|
||||
row
|
||||
}
|
||||
|
||||
func scopes(prefetchedRows: Row.PrefetchedRowsView) -> Row.ScopesView {
|
||||
// unless customized, assume unuscoped row (see AdaptedRowImpl for customization)
|
||||
return Row.ScopesView()
|
||||
Row.ScopesView()
|
||||
}
|
||||
|
||||
func hasNull(atUncheckedIndex index: Int) -> Bool {
|
||||
// unless customized, use slow check (see StatementRowImpl and AdaptedRowImpl for customization)
|
||||
return databaseValue(atUncheckedIndex: index).isNull
|
||||
databaseValue(atUncheckedIndex: index).isNull
|
||||
}
|
||||
|
||||
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
@@ -2155,7 +2118,7 @@ extension RowImpl {
|
||||
throws -> Value
|
||||
{
|
||||
// unless customized, use slow decoding (see StatementRowImpl and AdaptedRowImpl for customization)
|
||||
return try Value.decode(
|
||||
try Value.decode(
|
||||
fromDatabaseValue: databaseValue(atUncheckedIndex: index),
|
||||
context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index)))
|
||||
}
|
||||
@@ -2166,21 +2129,21 @@ extension RowImpl {
|
||||
throws -> Value?
|
||||
{
|
||||
// unless customized, use slow decoding (see StatementRowImpl and AdaptedRowImpl for customization)
|
||||
return try Value.decodeIfPresent(
|
||||
try Value.decodeIfPresent(
|
||||
fromDatabaseValue: databaseValue(atUncheckedIndex: index),
|
||||
context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index)))
|
||||
}
|
||||
|
||||
func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data {
|
||||
// unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization)
|
||||
return try Data.decode(
|
||||
try Data.decode(
|
||||
fromDatabaseValue: databaseValue(atUncheckedIndex: index),
|
||||
context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index)))
|
||||
}
|
||||
|
||||
func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? {
|
||||
// unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization)
|
||||
return try Data.decodeIfPresent(
|
||||
try Data.decodeIfPresent(
|
||||
fromDatabaseValue: databaseValue(atUncheckedIndex: index),
|
||||
context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index)))
|
||||
}
|
||||
@@ -2188,11 +2151,13 @@ extension RowImpl {
|
||||
|
||||
// TODO: merge with StatementCopyRowImpl eventually?
|
||||
/// See Row.init(dictionary:)
|
||||
private struct ArrayRowImpl: RowImpl {
|
||||
struct ArrayRowImpl: RowImpl {
|
||||
let columns: [(String, DatabaseValue)]
|
||||
|
||||
init(columns: [(String, DatabaseValue)]) {
|
||||
self.columns = columns
|
||||
init<C>(columns: C)
|
||||
where C: Collection, C.Element == (String, DatabaseValue)
|
||||
{
|
||||
self.columns = Array(columns)
|
||||
}
|
||||
|
||||
var count: Int { columns.count }
|
||||
@@ -2217,6 +2182,12 @@ private struct ArrayRowImpl: RowImpl {
|
||||
}
|
||||
}
|
||||
|
||||
#if swift(>=5.6) && canImport(_Concurrency)
|
||||
// @unchecked because columns property is not inferred as Sendable
|
||||
// TODO: remove this @unchecked when compiler can handle tuples.
|
||||
extension ArrayRowImpl: @unchecked Sendable { }
|
||||
#endif
|
||||
|
||||
|
||||
// TODO: merge with ArrayRowImpl eventually?
|
||||
/// See Row.init(copiedFromStatementRef:sqliteStatement:)
|
||||
@@ -2283,7 +2254,7 @@ private struct StatementRowImpl: RowImpl {
|
||||
|
||||
func hasNull(atUncheckedIndex index: Int) -> Bool {
|
||||
// Avoid extracting values, because this modifies the SQLite statement.
|
||||
return sqlite3_column_type(sqliteStatement, Int32(index)) == SQLITE_NULL
|
||||
sqlite3_column_type(sqliteStatement, Int32(index)) == SQLITE_NULL
|
||||
}
|
||||
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
|
||||
|
||||
@@ -185,9 +185,11 @@ public protocol _RowAdapter {
|
||||
/// GRDB ships with four concrete types that adopt the RowAdapter protocol:
|
||||
///
|
||||
/// - `ColumnMapping`: renames row columns
|
||||
/// - `SuffixRowAdapter`: hides the first columns of a row
|
||||
/// - `RangeRowAdapter`: only exposes a range of columns
|
||||
/// - `EmptyRowAdapter`: hides all columns
|
||||
/// - `RangeRowAdapter`: exposes a range of columns
|
||||
/// - `RenameColumnAdapter`: transforms column names with a function
|
||||
/// - `ScopeAdapter`: defines row scopes
|
||||
/// - `SuffixRowAdapter`: hides the first columns of a row
|
||||
///
|
||||
/// To use a row adapter, provide it to any method that fetches:
|
||||
///
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/// A key that is used to decode a value in a row
|
||||
@usableFromInline
|
||||
enum RowKey: Hashable {
|
||||
enum RowKey: Hashable, GRDBSendable {
|
||||
/// A column name
|
||||
case columnName(String)
|
||||
|
||||
@@ -18,13 +18,15 @@ enum RowKey: Hashable {
|
||||
@usableFromInline
|
||||
enum RowDecodingError: Error {
|
||||
@usableFromInline
|
||||
struct Context: CustomDebugStringConvertible {
|
||||
struct Context: CustomDebugStringConvertible, GRDBSendable {
|
||||
/// A description of what went wrong, for debugging purposes.
|
||||
@usableFromInline
|
||||
let debugDescription: String
|
||||
|
||||
let rowImpl: ArrayRowImpl // Sendable
|
||||
|
||||
/// The row that could not be decoded
|
||||
let row: Row
|
||||
var row: Row { Row(impl: rowImpl) }
|
||||
|
||||
/// Nil for RowDecodingError.keyNotFound, in order to avoid redundancy
|
||||
let key: RowKey?
|
||||
@@ -37,7 +39,7 @@ enum RowDecodingError: Error {
|
||||
|
||||
init(decodingContext: RowDecodingContext, debugDescription: String) {
|
||||
self.debugDescription = debugDescription
|
||||
self.row = decodingContext.row
|
||||
self.rowImpl = ArrayRowImpl(columns: decodingContext.row)
|
||||
self.key = decodingContext.key
|
||||
self.sql = decodingContext.sql
|
||||
self.statementArguments = decodingContext.statementArguments
|
||||
@@ -175,15 +177,15 @@ extension RowDecodingError: CustomStringConvertible {
|
||||
chunks.append("column: \(String(reflecting: columnName))")
|
||||
chunks.append("column index: \(columnIndex)")
|
||||
} else {
|
||||
// column name is already mentionned in context.debugDescription
|
||||
// column name is already mentioned in context.debugDescription
|
||||
}
|
||||
|
||||
case .prefetchKey:
|
||||
// key is already mentionned in context.debugDescription
|
||||
// key is already mentioned in context.debugDescription
|
||||
break
|
||||
|
||||
case .scope:
|
||||
// scope is already mentionned in context.debugDescription
|
||||
// scope is already mentioned in context.debugDescription
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,7 +49,13 @@ final class SchedulingWatchdog {
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
{
|
||||
GRDBPrecondition(current?.allows(db) ?? false, message(), file: file, line: line)
|
||||
GRDBPrecondition(allows(db), message(), file: file, line: line)
|
||||
}
|
||||
|
||||
/// Returns true iff the database argument can be used in the current
|
||||
/// dispatch queue.
|
||||
static func allows(_ db: Database) -> Bool {
|
||||
current?.allows(db) ?? false
|
||||
}
|
||||
|
||||
static var current: SchedulingWatchdog? {
|
||||
|
||||
@@ -9,7 +9,7 @@ final class SerializedDatabase {
|
||||
var configuration: Configuration { db.configuration }
|
||||
|
||||
/// The path to the database file
|
||||
var path: String
|
||||
let path: String
|
||||
|
||||
/// The dispatch queue
|
||||
private let queue: DispatchQueue
|
||||
@@ -47,7 +47,11 @@ final class SerializedDatabase {
|
||||
path: path,
|
||||
description: identifier,
|
||||
configuration: config)
|
||||
self.queue = configuration.makeDispatchQueue(label: identifier)
|
||||
if config.readonly {
|
||||
self.queue = configuration.makeReaderDispatchQueue(label: identifier)
|
||||
} else {
|
||||
self.queue = configuration.makeWriterDispatchQueue(label: identifier)
|
||||
}
|
||||
SchedulingWatchdog.allowDatabase(db, onQueue: queue)
|
||||
try queue.sync {
|
||||
do {
|
||||
@@ -193,19 +197,6 @@ final class SerializedDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Asynchronously executes a block in the serialized dispatch queue,
|
||||
/// without retaining self.
|
||||
func weakAsync(_ block: @escaping (Database?) -> Void) {
|
||||
queue.async { [weak self] in
|
||||
if let self = self {
|
||||
block(self.db)
|
||||
self.preconditionNoUnsafeTransactionLeft(self.db)
|
||||
} else {
|
||||
block(nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if any only if the current dispatch queue is valid.
|
||||
var onValidQueue: Bool {
|
||||
SchedulingWatchdog.current?.allows(db) ?? false
|
||||
@@ -257,3 +248,10 @@ final class SerializedDatabase {
|
||||
line: line)
|
||||
}
|
||||
}
|
||||
|
||||
#if swift(>=5.6) && canImport(_Concurrency)
|
||||
// @unchecked because the wrapped `Database` itself is not Sendable.
|
||||
// It happens the job of SerializedDatabase is precisely to provide thread-safe
|
||||
// access to `Database`.
|
||||
extension SerializedDatabase: @unchecked Sendable { }
|
||||
#endif
|
||||
@@ -87,24 +87,26 @@ public final class Statement {
|
||||
{
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
|
||||
let authorizer = StatementCompilationAuthorizer()
|
||||
// Reset authorizer before preparing the statement
|
||||
let authorizer = database.authorizer
|
||||
authorizer.reset()
|
||||
|
||||
var sqliteStatement: SQLiteStatement? = nil
|
||||
let code: Int32 = database.withAuthorizer(authorizer) {
|
||||
// sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
return sqlite3_prepare_v3(
|
||||
let code: Int32
|
||||
// sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
code = sqlite3_prepare_v3(
|
||||
database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags),
|
||||
&sqliteStatement, statementEnd)
|
||||
#else
|
||||
if #available(iOS 12.0, OSX 10.14, tvOS 12.0, watchOS 5.0, *) {
|
||||
code = sqlite3_prepare_v3(
|
||||
database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags),
|
||||
&sqliteStatement, statementEnd)
|
||||
#else
|
||||
if #available(iOS 12.0, OSX 10.14, tvOS 12.0, watchOS 5.0, *) {
|
||||
return sqlite3_prepare_v3(
|
||||
database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags),
|
||||
&sqliteStatement, statementEnd)
|
||||
} else {
|
||||
return sqlite3_prepare_v2(database.sqliteConnection, statementStart, -1, &sqliteStatement, statementEnd)
|
||||
}
|
||||
#endif
|
||||
} else {
|
||||
code = sqlite3_prepare_v2(database.sqliteConnection, statementStart, -1, &sqliteStatement, statementEnd)
|
||||
}
|
||||
#endif
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(
|
||||
@@ -129,15 +131,6 @@ public final class Statement {
|
||||
sqlite3_finalize(sqliteStatement)
|
||||
}
|
||||
|
||||
final func reset() throws {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
let code = sqlite3_reset(sqliteStatement)
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: Arguments
|
||||
|
||||
private var argumentsNeedValidation = true
|
||||
@@ -278,14 +271,89 @@ public final class Statement {
|
||||
}
|
||||
}
|
||||
|
||||
func reset(withArguments arguments: StatementArguments?) {
|
||||
// MARK: Execution
|
||||
|
||||
func reset() throws {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
let code = sqlite3_reset(sqliteStatement)
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql)
|
||||
}
|
||||
}
|
||||
|
||||
func reset(withArguments arguments: StatementArguments?) throws {
|
||||
// Force arguments validity: it is a programmer error to provide
|
||||
// arguments that do not match the statement.
|
||||
if let arguments = arguments {
|
||||
try! setArguments(arguments)
|
||||
try setArguments(arguments)
|
||||
} else if argumentsNeedValidation {
|
||||
try! reset()
|
||||
try! validateArguments(self.arguments)
|
||||
try reset()
|
||||
try validateArguments(self.arguments)
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes the prepared statement.
|
||||
///
|
||||
/// - parameter arguments: Optional statement arguments.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func execute(arguments: StatementArguments? = nil) throws {
|
||||
try reset(withArguments: arguments)
|
||||
try database.statementWillExecute(self)
|
||||
|
||||
// Iterate all rows, since they may execute side effects.
|
||||
while true {
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
try database.statementDidExecute(self)
|
||||
return
|
||||
case SQLITE_ROW:
|
||||
break
|
||||
case let code:
|
||||
try database.statementDidFail(self, withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls the given closure after each successful call to `sqlite3_step()`.
|
||||
///
|
||||
/// This method is slighly faster than calling `step(_:)` repeatedly, due
|
||||
/// to the single `sqlite3_stmt_busy` check.
|
||||
@usableFromInline
|
||||
func forEachStep(_ body: (SQLiteStatement) throws -> Void) throws {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
|
||||
if sqlite3_stmt_busy(sqliteStatement) == 0 {
|
||||
try database.statementWillExecute(self)
|
||||
}
|
||||
|
||||
while true {
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
try database.statementDidExecute(self)
|
||||
return
|
||||
case SQLITE_ROW:
|
||||
try body(sqliteStatement)
|
||||
case let code:
|
||||
try database.statementDidFail(self, withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls the given closure after one successful call to `sqlite3_step()`.
|
||||
@usableFromInline
|
||||
func step<T>(_ body: (SQLiteStatement) throws -> T) throws -> T? {
|
||||
if sqlite3_stmt_busy(sqliteStatement) == 0 {
|
||||
try database.statementWillExecute(self)
|
||||
}
|
||||
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
try database.statementDidExecute(self)
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return try body(sqliteStatement)
|
||||
case let code:
|
||||
try database.statementDidFail(self, withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -298,7 +366,7 @@ public typealias UpdateStatement = Statement
|
||||
|
||||
extension Statement: CustomStringConvertible {
|
||||
public var description: String {
|
||||
"SQL: \(sql), Arguments: \(arguments)"
|
||||
SchedulingWatchdog.allows(database) ? sql : "Statement"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -324,6 +392,50 @@ extension Statement {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Cursors
|
||||
|
||||
/// Implementation details of `DatabaseCursor`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol _DatabaseCursor: Cursor {
|
||||
/// Reserved to `_DatabaseCursor` implementation.
|
||||
/// Must be initialized to false.
|
||||
var _isDone: Bool { get set }
|
||||
|
||||
/// Called after one successful call to `sqlite3_step()`. Returns the
|
||||
/// element for the current statement step.
|
||||
func _element(sqliteStatement: SQLiteStatement) throws -> Element
|
||||
}
|
||||
|
||||
/// A protocol for cursors that iterate a database statement.
|
||||
public protocol DatabaseCursor: _DatabaseCursor {
|
||||
/// The statement iterated by the cursor
|
||||
var statement: Statement { get }
|
||||
}
|
||||
|
||||
extension DatabaseCursor {
|
||||
@inlinable
|
||||
public func next() throws -> Element? {
|
||||
if _isDone {
|
||||
return nil
|
||||
}
|
||||
if let element = try statement.step(_element) {
|
||||
return element
|
||||
}
|
||||
_isDone = true
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Specific implementation of `forEach`, for a slight performance
|
||||
/// improvement due to the single `sqlite3_stmt_busy` check.
|
||||
@inlinable
|
||||
public func forEach(_ body: (Element) throws -> Void) throws {
|
||||
if _isDone { return }
|
||||
try statement.forEachStep { try body(_element(sqliteStatement: $0)) }
|
||||
_isDone = true
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor that iterates a database statement without producing any value.
|
||||
/// Each call to the next() cursor method calls the sqlite3_step() C function.
|
||||
///
|
||||
@@ -334,66 +446,27 @@ extension Statement {
|
||||
/// let cursor = statement.makeCursor()
|
||||
/// try cursor.next()
|
||||
/// }
|
||||
final class StatementCursor: Cursor {
|
||||
private enum _State {
|
||||
case idle, busy, done, failed
|
||||
}
|
||||
|
||||
/* private, internal for testability */ let _statement: Statement
|
||||
private let _sqliteStatement: SQLiteStatement
|
||||
private var _state = _State.idle
|
||||
final class StatementCursor: DatabaseCursor {
|
||||
typealias Element = Void
|
||||
let statement: Statement
|
||||
var _isDone = false
|
||||
|
||||
// Use Statement.makeCursor() instead
|
||||
init(statement: Statement, arguments: StatementArguments? = nil) throws {
|
||||
_statement = statement
|
||||
_sqliteStatement = statement.sqliteStatement
|
||||
self.statement = statement
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
statement.reset(withArguments: arguments)
|
||||
try statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
if _state == .busy {
|
||||
try? _statement.database.statementDidExecute(_statement)
|
||||
}
|
||||
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? _statement.reset()
|
||||
try? statement.reset()
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
func next() throws -> Void? {
|
||||
switch _state {
|
||||
case .done:
|
||||
// make sure this instance never yields a value again, even if the
|
||||
// statement is reset by another cursor.
|
||||
return nil
|
||||
case .idle:
|
||||
guard try _statement.database.statementWillExecute(_statement) == nil else {
|
||||
throw DatabaseError(
|
||||
resultCode: SQLITE_MISUSE,
|
||||
message: "Can't run statement that requires a customized authorizer from a cursor",
|
||||
sql: _statement.sql,
|
||||
arguments: _statement.arguments)
|
||||
}
|
||||
_state = .busy
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
switch sqlite3_step(_sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
_state = .done
|
||||
try _statement.database.statementDidExecute(_statement)
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return .some(())
|
||||
case let code:
|
||||
_state = .failed
|
||||
try _statement.database.statementDidFail(_statement, withResultCode: code)
|
||||
}
|
||||
}
|
||||
@usableFromInline
|
||||
func _element(sqliteStatement: SQLiteStatement) throws { }
|
||||
}
|
||||
|
||||
// MARK: - Update Statements
|
||||
@@ -417,20 +490,6 @@ extension Statement {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes the prepared statement.
|
||||
///
|
||||
/// - parameter arguments: Optional statement arguments.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func execute(arguments: StatementArguments? = nil) throws {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
reset(withArguments: arguments)
|
||||
|
||||
// Statement does not know how to execute itself, because it does not
|
||||
// know how to handle its errors, or if truncate optimisation should be
|
||||
// prevented or not. Database knows.
|
||||
try database.executeStatement(self)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - StatementBinding
|
||||
@@ -880,3 +939,5 @@ extension StatementArguments {
|
||||
return "[" + (namedValuesDescriptions + valuesDescriptions).joined(separator: ", ") + "]"
|
||||
}
|
||||
}
|
||||
|
||||
extension StatementArguments: GRDBSendable { }
|
||||
@@ -2,29 +2,19 @@
|
||||
import Glibc
|
||||
#endif
|
||||
|
||||
/// A protocol around sqlite3_set_authorizer
|
||||
@usableFromInline
|
||||
protocol StatementAuthorizer: AnyObject {
|
||||
func authorize(
|
||||
_ actionCode: Int32,
|
||||
_ cString1: UnsafePointer<Int8>?,
|
||||
_ cString2: UnsafePointer<Int8>?,
|
||||
_ cString3: UnsafePointer<Int8>?,
|
||||
_ cString4: UnsafePointer<Int8>?)
|
||||
-> Int32
|
||||
}
|
||||
|
||||
/// A class that gathers information about one statement during its compilation.
|
||||
final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
final class StatementAuthorizer {
|
||||
private unowned var database: Database
|
||||
|
||||
/// What this statements reads
|
||||
var selectedRegion = DatabaseRegion()
|
||||
|
||||
/// What this statements writes
|
||||
var databaseEventKinds: [DatabaseEventKind] = []
|
||||
|
||||
/// True if a statement alter the schema in a way that required schema cache
|
||||
/// invalidation. For example, adding a column to a table invalidates the
|
||||
/// schema cache, but not creating a table.
|
||||
/// True if a statement alters the schema in a way that requires
|
||||
/// invalidation of the schema cache. For example, adding a column to a
|
||||
/// table invalidates the schema cache.
|
||||
var invalidatesDatabaseSchemaCache = false
|
||||
|
||||
/// Not nil if a statement is a BEGIN/COMMIT/ROLLBACK/RELEASE transaction or
|
||||
@@ -33,6 +23,19 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
|
||||
private var isDropStatement = false
|
||||
|
||||
init(_ database: Database) {
|
||||
self.database = database
|
||||
}
|
||||
|
||||
/// Reset before compiling a new statement
|
||||
func reset() {
|
||||
selectedRegion = DatabaseRegion()
|
||||
databaseEventKinds = []
|
||||
invalidatesDatabaseSchemaCache = false
|
||||
transactionEffect = nil
|
||||
isDropStatement = false
|
||||
}
|
||||
|
||||
func authorize(
|
||||
_ actionCode: Int32,
|
||||
_ cString1: UnsafePointer<Int8>?,
|
||||
@@ -41,10 +44,11 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
_ cString4: UnsafePointer<Int8>?)
|
||||
-> Int32
|
||||
{
|
||||
// Uncomment when debugging
|
||||
// print("""
|
||||
// StatementCompilationAuthorizer: \
|
||||
// StatementAuthorizer: \
|
||||
// \(AuthorizerActionCode(rawValue: actionCode)) \
|
||||
// \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) })
|
||||
// \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) }.joined(separator: ", "))
|
||||
// """)
|
||||
|
||||
switch actionCode {
|
||||
@@ -70,7 +74,7 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
guard let columnName = cString2.map(String.init) else { return SQLITE_OK }
|
||||
if columnName.isEmpty {
|
||||
// SELECT COUNT(*) FROM table
|
||||
selectedRegion.formUnion(DatabaseRegion(table: tableName))
|
||||
selectedRegion.formUnion(DatabaseRegion.fullTable(tableName))
|
||||
} else {
|
||||
// SELECT column FROM table
|
||||
selectedRegion.formUnion(DatabaseRegion(table: tableName, columns: [columnName]))
|
||||
@@ -93,10 +97,16 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
guard strcmp(cString1, "sqlite_master") != 0 else { return SQLITE_OK }
|
||||
guard strcmp(cString1, "sqlite_temp_master") != 0 else { return SQLITE_OK }
|
||||
|
||||
let tableName = String(cString: cString1)
|
||||
databaseEventKinds.append(.delete(tableName: tableName))
|
||||
|
||||
// Now we prevent the truncate optimization so that transaction
|
||||
// observers are notified of individual row deletions.
|
||||
databaseEventKinds.append(.delete(tableName: String(cString: cString1)))
|
||||
return SQLITE_IGNORE
|
||||
if database.observationBroker.observesDeletions(on: tableName) {
|
||||
return SQLITE_IGNORE
|
||||
} else {
|
||||
return SQLITE_OK
|
||||
}
|
||||
|
||||
case SQLITE_UPDATE:
|
||||
guard let tableName = cString1.map(String.init) else { return SQLITE_OK }
|
||||
@@ -128,6 +138,21 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_FUNCTION:
|
||||
guard let cString2 = cString2 else { return SQLITE_OK }
|
||||
|
||||
// SQLite does not report ALTER TABLE DROP COLUMN with the
|
||||
// SQLITE_ALTER_TABLE action code. So we need to find another way
|
||||
// to set the `invalidatesDatabaseSchemaCache` flag for such
|
||||
// statement, and it is SQLITE_FUNCTION sqlite_drop_column.
|
||||
//
|
||||
// See <https://github.com/groue/GRDB.swift/pull/1144#issuecomment-1015155717>
|
||||
// See <https://sqlite.org/forum/forumpost/bd47580ec2>
|
||||
//
|
||||
// TODO: remove when SQLite properly reports SQLITE_ALTER_TABLE
|
||||
if strcmp(cString2, "sqlite_drop_column") == 0 {
|
||||
invalidatesDatabaseSchemaCache = true
|
||||
}
|
||||
|
||||
// Starting SQLite 3.19.0, `SELECT COUNT(*) FROM table` triggers
|
||||
// an authorization callback for SQLITE_READ with an empty
|
||||
// column: http://www.sqlite.org/changes.html#version_3_19_0
|
||||
@@ -137,7 +162,6 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
// counted table: any use of the COUNT function makes the
|
||||
// region undetermined (the full database).
|
||||
guard sqlite3_libversion_number() < 3019000 else { return SQLITE_OK }
|
||||
guard let cString2 = cString2 else { return SQLITE_OK }
|
||||
if sqlite3_stricmp(cString2, "COUNT") == 0 {
|
||||
selectedRegion = .fullDatabase
|
||||
}
|
||||
@@ -161,30 +185,6 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
}
|
||||
}
|
||||
|
||||
/// This authorizer prevents the [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
|
||||
/// which makes transaction observers unable to observe individual deletions
|
||||
/// when user runs `DELETE FROM t` statements.
|
||||
//
|
||||
/// Warning: to perform well, this authorizer must be used during statement
|
||||
/// execution, not during statement compilation.
|
||||
final class TruncateOptimizationBlocker: StatementAuthorizer {
|
||||
func authorize(
|
||||
_ actionCode: Int32,
|
||||
_ cString1: UnsafePointer<Int8>?,
|
||||
_ cString2: UnsafePointer<Int8>?,
|
||||
_ cString3: UnsafePointer<Int8>?,
|
||||
_ cString4: UnsafePointer<Int8>?)
|
||||
-> Int32
|
||||
{
|
||||
// print("""
|
||||
// TruncateOptimizationBlocker: \
|
||||
// \(AuthorizerActionCode(rawValue: actionCode)) \
|
||||
// \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) })
|
||||
// """)
|
||||
return (actionCode == SQLITE_DELETE) ? SQLITE_IGNORE : SQLITE_OK
|
||||
}
|
||||
}
|
||||
|
||||
private struct AuthorizerActionCode: RawRepresentable, CustomStringConvertible {
|
||||
let rawValue: Int32
|
||||
|
||||
|
||||
@@ -138,76 +138,42 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// print(name)
|
||||
/// }
|
||||
/// }
|
||||
public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
|
||||
@usableFromInline
|
||||
enum _State {
|
||||
case idle, busy, done, failed
|
||||
}
|
||||
|
||||
@usableFromInline let _statement: Statement
|
||||
@usableFromInline let _columnIndex: Int32
|
||||
@usableFromInline let _sqliteStatement: SQLiteStatement
|
||||
@usableFromInline var _state = _State.idle
|
||||
public final class FastDatabaseValueCursor<Value>: DatabaseCursor
|
||||
where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
{
|
||||
public typealias Element = Value
|
||||
public let statement: Statement
|
||||
/// :nodoc:
|
||||
public var _isDone = false
|
||||
@usableFromInline let columnIndex: Int32
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
_statement = statement
|
||||
_sqliteStatement = statement.sqliteStatement
|
||||
self.statement = statement
|
||||
if let adapter = adapter {
|
||||
// adapter may redefine the index of the leftmost column
|
||||
_columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
|
||||
columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
|
||||
} else {
|
||||
_columnIndex = 0
|
||||
columnIndex = 0
|
||||
}
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
statement.reset(withArguments: arguments)
|
||||
try statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
if _state == .busy {
|
||||
try? _statement.database.statementDidExecute(_statement)
|
||||
}
|
||||
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? _statement.reset()
|
||||
try? statement.reset()
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
@inlinable
|
||||
public func next() throws -> Value? {
|
||||
switch _state {
|
||||
case .done:
|
||||
// make sure this instance never yields a value again, even if the
|
||||
// statement is reset by another cursor.
|
||||
return nil
|
||||
case .idle:
|
||||
guard try _statement.database.statementWillExecute(_statement) == nil else {
|
||||
throw DatabaseError(
|
||||
resultCode: SQLITE_MISUSE,
|
||||
message: "Can't run statement that requires a customized authorizer from a cursor",
|
||||
sql: _statement.sql,
|
||||
arguments: _statement.arguments)
|
||||
}
|
||||
_state = .busy
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
switch sqlite3_step(_sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
_state = .done
|
||||
try _statement.database.statementDidExecute(_statement)
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
return try! Value.fastDecode(
|
||||
fromStatement: _sqliteStatement,
|
||||
atUncheckedIndex: _columnIndex,
|
||||
context: RowDecodingContext(statement: _statement, index: Int(_columnIndex)))
|
||||
case let code:
|
||||
_state = .failed
|
||||
try _statement.database.statementDidFail(_statement, withResultCode: code)
|
||||
}
|
||||
public func _element(sqliteStatement: SQLiteStatement) -> Value {
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
try! Value.fastDecode(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: columnIndex,
|
||||
context: RowDecodingContext(statement: statement, index: Int(columnIndex)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,78 +187,42 @@ public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & Sta
|
||||
/// print(email ?? "<NULL>")
|
||||
/// }
|
||||
/// }
|
||||
public final class FastNullableDatabaseValueCursor<Value>: Cursor
|
||||
public final class FastNullableDatabaseValueCursor<Value>: DatabaseCursor
|
||||
where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
{
|
||||
@usableFromInline
|
||||
enum _State {
|
||||
case idle, busy, done, failed
|
||||
}
|
||||
|
||||
@usableFromInline let _statement: Statement
|
||||
@usableFromInline let _columnIndex: Int32
|
||||
@usableFromInline let _sqliteStatement: SQLiteStatement
|
||||
@usableFromInline var _state = _State.idle
|
||||
public typealias Element = Value?
|
||||
public let statement: Statement
|
||||
/// :nodoc:
|
||||
public var _isDone = false
|
||||
@usableFromInline let columnIndex: Int32
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
_statement = statement
|
||||
_sqliteStatement = statement.sqliteStatement
|
||||
self.statement = statement
|
||||
if let adapter = adapter {
|
||||
// adapter may redefine the index of the leftmost column
|
||||
_columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
|
||||
columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
|
||||
} else {
|
||||
_columnIndex = 0
|
||||
columnIndex = 0
|
||||
}
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
statement.reset(withArguments: arguments)
|
||||
try statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
if _state == .busy {
|
||||
try? _statement.database.statementDidExecute(_statement)
|
||||
}
|
||||
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? _statement.reset()
|
||||
try? statement.reset()
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
@inlinable
|
||||
public func next() throws -> Value?? {
|
||||
switch _state {
|
||||
case .done:
|
||||
// make sure this instance never yields a value again, even if the
|
||||
// statement is reset by another cursor.
|
||||
return nil
|
||||
case .idle:
|
||||
guard try _statement.database.statementWillExecute(_statement) == nil else {
|
||||
throw DatabaseError(
|
||||
resultCode: SQLITE_MISUSE,
|
||||
message: "Can't run statement that requires a customized authorizer from a cursor",
|
||||
sql: _statement.sql,
|
||||
arguments: _statement.arguments)
|
||||
}
|
||||
_state = .busy
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
switch sqlite3_step(_sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
_state = .done
|
||||
try _statement.database.statementDidExecute(_statement)
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
return try! Value.fastDecodeIfPresent(
|
||||
fromStatement: _sqliteStatement,
|
||||
atUncheckedIndex: _columnIndex,
|
||||
context: RowDecodingContext(statement: _statement, index: Int(_columnIndex)))
|
||||
case let code:
|
||||
_state = .failed
|
||||
try _statement.database.statementDidFail(_statement, withResultCode: code)
|
||||
}
|
||||
public func _element(sqliteStatement: SQLiteStatement) -> Value? {
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
try! Value.fastDecodeIfPresent(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: columnIndex,
|
||||
context: RowDecodingContext(statement: statement, index: Int(columnIndex)))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -708,7 +708,7 @@ extension DatabaseCollation {
|
||||
/// """)
|
||||
public static let localizedCaseInsensitiveCompare =
|
||||
DatabaseCollation("swiftLocalizedCaseInsensitiveCompare") { (lhs, rhs) in
|
||||
return lhs.localizedCaseInsensitiveCompare(rhs)
|
||||
lhs.localizedCaseInsensitiveCompare(rhs)
|
||||
}
|
||||
|
||||
/// A collation, or SQL string comparison function, that compares strings
|
||||
|
||||