mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-01 04:38:44 +00:00
Compare commits
321
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ba709ef3c4 | ||
|
|
3bcae88483 | ||
|
|
0f8aa074e3 | ||
|
|
be7d06962a | ||
|
|
8ba19bc982 | ||
|
|
82d879e785 | ||
|
|
b43260a17d | ||
|
|
98c58f4eef | ||
|
|
bd7031ec9b | ||
|
|
909f7455e6 | ||
|
|
5d9e853f24 | ||
|
|
7a216d7d34 | ||
|
|
92a554cd0d | ||
|
|
47c8497269 | ||
|
|
d99e639c11 | ||
|
|
1d59d1656b | ||
|
|
5fe300b733 | ||
|
|
a8a5b431be | ||
|
|
b7b747c5bb | ||
|
|
62f4bfe5f3 | ||
|
|
9601d6ac9b | ||
|
|
dc101b2847 | ||
|
|
a0f184ec26 | ||
|
|
b983df96e2 | ||
|
|
94fa864eb7 | ||
|
|
e1a0c1afbe | ||
|
|
3f80cfccf4 | ||
|
|
6f64c72209 | ||
|
|
8e24aec8f2 | ||
|
|
de0ce29d73 | ||
|
|
9858de3249 | ||
|
|
fe774b3537 | ||
|
|
550ef55c90 | ||
|
|
e37c7cf306 | ||
|
|
1ff66c8382 | ||
|
|
8957148d4d | ||
|
|
23083c4668 | ||
|
|
dfa942e9c0 | ||
|
|
5d31cba4a0 | ||
|
|
533286eab0 | ||
|
|
ac1e5e66be | ||
|
|
6bf7ba8f03 | ||
|
|
9f2e3b7d6b | ||
|
|
c08767b500 | ||
|
|
8511cfd399 | ||
|
|
4373b3a49b | ||
|
|
d4713c1fa8 | ||
|
|
0d8cf958b4 | ||
|
|
0a9a55d15f | ||
|
|
b83108d10f | ||
|
|
468b8e81be | ||
|
|
a3a29aa921 | ||
|
|
f1d321139f | ||
|
|
7d489358e2 | ||
|
|
67530472a5 | ||
|
|
fe3b957e5f | ||
|
|
f1eb48b0cf | ||
|
|
9ed8c8457e | ||
|
|
656d1f4539 | ||
|
|
cc85b3d82d | ||
|
|
97f517a660 | ||
|
|
b49e990bdd | ||
|
|
27c7bda0e9 | ||
|
|
253cdfec8c | ||
|
|
e934c428b4 | ||
|
|
cdc2fb4200 | ||
|
|
47cb0b877b | ||
|
|
c637e04133 | ||
|
|
36e30a6f1e | ||
|
|
368514c33b | ||
|
|
21b1322e05 | ||
|
|
819f4572df | ||
|
|
7b01c9b72b | ||
|
|
7f9d1503a0 | ||
|
|
14567635e4 | ||
|
|
205387d2d2 | ||
|
|
c8f0328413 | ||
|
|
e784b10314 | ||
|
|
34fa177a47 | ||
|
|
67ebcb325c | ||
|
|
a3036feb48 | ||
|
|
14d4c842e4 | ||
|
|
79276d7f68 | ||
|
|
14fdba1ef3 | ||
|
|
8b5017714f | ||
|
|
a1a9c3aefe | ||
|
|
d664db9610 | ||
|
|
2c4492a098 | ||
|
|
c0ef0e0f99 | ||
|
|
81a699cae9 | ||
|
|
bd954c6791 | ||
|
|
2f94eb307a | ||
|
|
51083da42d | ||
|
|
c229891b6d | ||
|
|
c24bf5d118 | ||
|
|
ccfe3149d7 | ||
|
|
ce71d6c19f | ||
|
|
129e53d54e | ||
|
|
bc5dd31366 | ||
|
|
aa0079aeb8 | ||
|
|
74ef238376 | ||
|
|
9d7a487971 | ||
|
|
ac2f2e8643 | ||
|
|
e281149a2d | ||
|
|
3ee256e7e8 | ||
|
|
361599aacd | ||
|
|
64a024097d | ||
|
|
60ea10948b | ||
|
|
5dba64d545 | ||
|
|
2212a17950 | ||
|
|
24fa06d646 | ||
|
|
fd788900b6 | ||
|
|
b31be05ee3 | ||
|
|
3dd3bbf0c5 | ||
|
|
d7cf0f9e59 | ||
|
|
389c3e0d4a | ||
|
|
a212bf9e89 | ||
|
|
65186104cc | ||
|
|
2f108508fa | ||
|
|
5513eab099 | ||
|
|
2ad2d20a89 | ||
|
|
dd90fe6e62 | ||
|
|
691207567a | ||
|
|
c7f1dd7470 | ||
|
|
8e5b9ca9bd | ||
|
|
dc7d47c066 | ||
|
|
14f60ad48f | ||
|
|
e758fde941 | ||
|
|
7477e1cff8 | ||
|
|
2d6fe172c3 | ||
|
|
0526853dde | ||
|
|
a60810f28e | ||
|
|
c35095c6da | ||
|
|
f878d99733 | ||
|
|
48a17ce490 | ||
|
|
361a482b1e | ||
|
|
8cba324d6e | ||
|
|
17e1683b66 | ||
|
|
b1b83abd8b | ||
|
|
d06c9ed6b5 | ||
|
|
9a98ed6292 | ||
|
|
5cc85a98f3 | ||
|
|
edc1d646f0 | ||
|
|
ab09078842 | ||
|
|
267e1ea5a6 | ||
|
|
18497b68fd | ||
|
|
19e33e2e7d | ||
|
|
76e0815907 | ||
|
|
85ad232b0b | ||
|
|
db695cf7dc | ||
|
|
76a7be8404 | ||
|
|
196c33ba63 | ||
|
|
50a74f7b03 | ||
|
|
3f27fb9289 | ||
|
|
62fdd41d75 | ||
|
|
c5d02eac32 | ||
|
|
d1bfce829b | ||
|
|
edd292bcbd | ||
|
|
a0e101e683 | ||
|
|
9ef5e2c8eb | ||
|
|
f5dc68fc6f | ||
|
|
b210ec7428 | ||
|
|
a7e3acf409 | ||
|
|
ca27f75760 | ||
|
|
99ecf76a77 | ||
|
|
f4991273c2 | ||
|
|
1b98a964d7 | ||
|
|
1095d21abd | ||
|
|
eb2378a741 | ||
|
|
37dde39557 | ||
|
|
5786391dc9 | ||
|
|
e1abafaae3 | ||
|
|
93d0baeade | ||
|
|
26ebd7e147 | ||
|
|
75e99861af | ||
|
|
2e433a3cb2 | ||
|
|
9518d74fa6 | ||
|
|
c7bbebc80f | ||
|
|
38f5226e95 | ||
|
|
2b19803644 | ||
|
|
d7d61add23 | ||
|
|
d040588849 | ||
|
|
30313623eb | ||
|
|
aab2664431 | ||
|
|
f3acfecc16 | ||
|
|
aa2cdb7ec3 | ||
|
|
d90ba851fe | ||
|
|
7eea8ccb91 | ||
|
|
6a25b3538e | ||
|
|
7ec88b76e0 | ||
|
|
1a3842e4bc | ||
|
|
32ed290a1b | ||
|
|
f88c7202cd | ||
|
|
79ce0ff5f3 | ||
|
|
f435715f75 | ||
|
|
cf1702630f | ||
|
|
fd7adf7fb3 | ||
|
|
be0f0c6f25 | ||
|
|
cd84db3873 | ||
|
|
4cfa692ddd | ||
|
|
8dfbbb50f6 | ||
|
|
3f69614405 | ||
|
|
b4f3a83755 | ||
|
|
7cd2a4563c | ||
|
|
2698c55654 | ||
|
|
37065fb503 | ||
|
|
3801ab9ac6 | ||
|
|
26abd8ad79 | ||
|
|
827ab62bb6 | ||
|
|
fdeb88a6bd | ||
|
|
8ba1bc9a96 | ||
|
|
c4e39285a0 | ||
|
|
1622b72b62 | ||
|
|
215128390d | ||
|
|
c5283a0bd9 | ||
|
|
fb68849bfb | ||
|
|
c2bddde88a | ||
|
|
b4a21d63b2 | ||
|
|
6ca38eda3b | ||
|
|
d76922fe1a | ||
|
|
a46f3b69e9 | ||
|
|
b572982e34 | ||
|
|
5a8b025ee8 | ||
|
|
9a1914a813 | ||
|
|
4a92263c5e | ||
|
|
f72d0cecb2 | ||
|
|
24e0f5ddeb | ||
|
|
2b1b56ea47 | ||
|
|
ad704c58e5 | ||
|
|
3f928bcf9c | ||
|
|
c91c183354 | ||
|
|
c666393e63 | ||
|
|
d242421862 | ||
|
|
7a1e65b142 | ||
|
|
fb4578a7d6 | ||
|
|
6069e6d683 | ||
|
|
a703da9b27 | ||
|
|
684266b7b8 | ||
|
|
b24fb76610 | ||
|
|
cbbd0cb945 | ||
|
|
dd4227303a | ||
|
|
69b786dc9e | ||
|
|
9dd8b2cef7 | ||
|
|
c5ac6cdaa6 | ||
|
|
e154a652dc | ||
|
|
41d4f23a83 | ||
|
|
27b7400979 | ||
|
|
e6847886db | ||
|
|
c064515247 | ||
|
|
96236a3d44 | ||
|
|
01cd49b4ec | ||
|
|
9db14cb893 | ||
|
|
b26f60eae0 | ||
|
|
79a41dcbbb | ||
|
|
c7d50486ad | ||
|
|
93292d88f4 | ||
|
|
be22e0a2d0 | ||
|
|
d1a2cb0948 | ||
|
|
a5a1be26b4 | ||
|
|
b84d1eaeef | ||
|
|
e7a35dde06 | ||
|
|
c2e6c86934 | ||
|
|
7c2cbfe814 | ||
|
|
034b241e71 | ||
|
|
814146c40d | ||
|
|
fedcdef65e | ||
|
|
2316fb3831 | ||
|
|
98e2812089 | ||
|
|
8f6f1aa264 | ||
|
|
96d04716c2 | ||
|
|
004968517e | ||
|
|
f635aea2f2 | ||
|
|
5c9b772e65 | ||
|
|
d6ff3b14d4 | ||
|
|
fac0c22ecb | ||
|
|
5461caff04 | ||
|
|
6cc3116ff4 | ||
|
|
55edcff97f | ||
|
|
430141344d | ||
|
|
0567f69e66 | ||
|
|
be2fb76d77 | ||
|
|
503fb09270 | ||
|
|
ec6042e9c7 | ||
|
|
190ccda727 | ||
|
|
af1adff71d | ||
|
|
43e103d5f8 | ||
|
|
7b2e9d838a | ||
|
|
6b0faede2a | ||
|
|
ed402d5de6 | ||
|
|
db5c4cc458 | ||
|
|
352f77f225 | ||
|
|
ed98ac30e0 | ||
|
|
35fa28ab90 | ||
|
|
a89bd88340 | ||
|
|
b01f6da3cf | ||
|
|
e7fdd65072 | ||
|
|
ff15f30a3b | ||
|
|
f69ca1a573 | ||
|
|
e8b143e2ee | ||
|
|
5e9b965bee | ||
|
|
ce238b6643 | ||
|
|
787393db18 | ||
|
|
8774497f31 | ||
|
|
94e90e7e6c | ||
|
|
9064717b8a | ||
|
|
00f462292b | ||
|
|
5a0622e5b8 | ||
|
|
596db46407 | ||
|
|
0aaa2a4f37 | ||
|
|
04e73c26c4 | ||
|
|
a71c1d6e80 | ||
|
|
52b7b7bd26 | ||
|
|
9a9d2e9993 | ||
|
|
1ce8e38bea | ||
|
|
67b34dc57c | ||
|
|
515bd78d28 | ||
|
|
f2aa6b386f | ||
|
|
71e09a38d4 | ||
|
|
d800a79d5d | ||
|
|
4065ff58e8 | ||
|
|
18eab53f74 |
No files matched your search
+43
-43
@@ -1,4 +1,4 @@
|
||||
# https://github.com/actions/runner-images/blob/main/images/macos/macos-14-Readme.md
|
||||
# https://github.com/actions/runner-images/blob/main/images/macos/macos-15-Readme.md
|
||||
|
||||
name: "GRDB CI"
|
||||
|
||||
@@ -40,20 +40,20 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
destination: "platform=macOS"
|
||||
name: "macOS"
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
destination: "OS=18.1,name=iPhone 16 Pro"
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
destination: "OS=18.5,name=iPhone 16 Pro"
|
||||
name: "iOS"
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
destination: "OS=18.1,name=Apple TV"
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
destination: "OS=18.5,name=Apple TV"
|
||||
name: "tvOS"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- name: ${{ matrix.name }}
|
||||
run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project GRDB.xcodeproj -scheme GRDB -destination "${{ matrix.destination }}" OTHER_SWIFT_FLAGS='$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' GCC_PREPROCESSOR_DEFINITIONS='$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' clean test
|
||||
SPM:
|
||||
@@ -66,11 +66,11 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
name: "Xcode 16.4"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_SPM test_install_SPM
|
||||
SQLCipher3:
|
||||
@@ -83,11 +83,11 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
name: "Xcode 16.4"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_SQLCipher3Encrypted
|
||||
SQLCipher4:
|
||||
@@ -100,30 +100,30 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
name: "Xcode 16.4"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_SQLCipher4Encrypted
|
||||
CustomSQLite:
|
||||
name: CustomSQLite
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
env:
|
||||
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_GRDBCustomSQLiteOSX
|
||||
# CustomSQLite:
|
||||
# name: CustomSQLite
|
||||
# runs-on: ${{ matrix.runsOn }}
|
||||
# env:
|
||||
# DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
|
||||
# timeout-minutes: 60
|
||||
# strategy:
|
||||
# fail-fast: false
|
||||
# matrix:
|
||||
# include:
|
||||
# - xcode: "Xcode_16.4.app"
|
||||
# runsOn: macOS-15
|
||||
# name: "Xcode 16.4"
|
||||
# steps:
|
||||
# - uses: actions/checkout@v5
|
||||
# - name: ${{ matrix.name }}
|
||||
# run: make test_framework_GRDBCustomSQLiteOSX
|
||||
XCFramework:
|
||||
name: XCFramework
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
@@ -134,11 +134,11 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
name: "Xcode 16.4"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_universal_xcframework
|
||||
|
||||
@@ -2,4 +2,4 @@ version: 1
|
||||
builder:
|
||||
configs:
|
||||
- documentation_targets: [GRDB]
|
||||
swift_version: 6.0
|
||||
swift_version: 6.1
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"editor.formatOnSave": false,
|
||||
"editor.insertSpaces": true,
|
||||
"editor.tabSize": 4,
|
||||
"editor.detectIndentation": false,
|
||||
"editor.trimAutoWhitespace": false
|
||||
}
|
||||
+141
-1
@@ -7,6 +7,15 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 7.x Releases
|
||||
|
||||
- `7.12.x` Releases - [7.12.0](#7120) - [7.12.1](#7121)
|
||||
- `7.11.x` Releases - [7.11.0](#7110) - [7.11.1](#7111)
|
||||
- `7.10.x` Releases - [7.10.0](#7100)
|
||||
- `7.9.x` Releases - [7.9.0](#790)
|
||||
- `7.8.x` Releases - [7.8.0](#780)
|
||||
- `7.7.x` Releases - [7.7.0](#770) - [7.7.1](#771)
|
||||
- `7.6.x` Releases - [7.6.0](#760) - [7.6.1](#761)
|
||||
- `7.5.x` Releases - [7.5.0](#750)
|
||||
- `7.4.x` Releases - [7.4.0](#740) - [7.4.1](#741)
|
||||
- `7.3.x` Releases - [7.3.0](#730)
|
||||
- `7.2.x` Releases - [7.2.0](#720)
|
||||
- `7.1.x` Releases - [7.1.0](#710)
|
||||
@@ -135,6 +144,137 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 7.12.1
|
||||
|
||||
Released November 30, 2026
|
||||
|
||||
- **New**: Optimize database read reentrancy checks by [@groue](https://github.com/groue) and [@renchris](https://github.com/renchris) in [#1897](https://github.com/groue/GRDB.swift/pull/1897)
|
||||
- **Fixed**: Ignore interruptions when entering the read-only mode by [@uveshm003](https://github.com/uveshm003) in [#1900](https://github.com/groue/GRDB.swift/pull/1900)
|
||||
|
||||
## 7.12.0
|
||||
|
||||
Released November 1, 2026
|
||||
|
||||
- **New**: Add support for Strings that contain the NUL character by [@groue](https://github.com/groue) and [@nesevis](https://github.com/nesevis) in [#1885](https://github.com/groue/GRDB.swift/pull/1885)
|
||||
- **New**: Keep SQLite's error message when a database fails to open by [@builtbysharath](https://github.com/builtbysharath) in [#1889](https://github.com/groue/GRDB.swift/pull/1889)
|
||||
- **Fixed**: Fix doubled word in doc comment by [@latent-9](https://github.com/latent-9) in [#1876](https://github.com/groue/GRDB.swift/pull/1876)
|
||||
- **Fixed**: Fix an accidentally quadratic behavior in SQLite statement compilation by [@groue](https://github.com/groue) and [@guidedways](https://github.com/guidedways) in [#1881](https://github.com/groue/GRDB.swift/pull/1881)
|
||||
- **Fixed**: Work around an SQLite bug in WAL snapshot ordering by [@groue](https://github.com/groue) and [@vburojevic](https://github.com/vburojevic) in [#1884](https://github.com/groue/GRDB.swift/pull/1884)
|
||||
- **Fixed**: Fix upsert for WITHOUT ROWID tables with an INTEGER primary key by [@nesevis](https://github.com/nesevis) in [#1879](https://github.com/groue/GRDB.swift/pull/1879)
|
||||
- **Fixed**: Support for statement recompilation after the columns are modified in the database schema by [@groue](https://github.com/groue) in [#1893](https://github.com/groue/GRDB.swift/pull/1893)
|
||||
- **Fixed**: Fix SharedValueObservation deadlock, ordering, and cancellation by [@groue](https://github.com/groue) in [#1894](https://github.com/groue/GRDB.swift/pull/1894)
|
||||
|
||||
## 7.11.1
|
||||
|
||||
Released June 18, 2026
|
||||
|
||||
- **New**: Make migration registration an O(1) operation [@MarkusSintonen](https://github.com/MarkusSintonen) in [#1869](https://github.com/groue/GRDB.swift/pull/1869)
|
||||
|
||||
## 7.11.0
|
||||
|
||||
Released June 1, 2026
|
||||
|
||||
- **New**: Add option to disable database change filtering in `TransactionObserver` by [@simolus3](https://github.com/simolus3) in [#1864](https://github.com/groue/GRDB.swift/pull/1864)
|
||||
- **Fixed**: Fix upsert for WITHOUT ROWID tables by [@groue](https://github.com/groue) in [#1858](https://github.com/groue/GRDB.swift/pull/1858)
|
||||
|
||||
## 7.10.0
|
||||
|
||||
Released February 15, 2026
|
||||
|
||||
- **Documentation fixes** by [@bellebethcooper](https://github.com/bellebethcooper), [@Cykelero](https://github.com/Cykelero), and [@leejungyeob](https://github.com/leejungyeob) in [#1842](https://github.com/groue/GRDB.swift/pull/1842), [#1846](https://github.com/groue/GRDB.swift/pull/1846), [#1848](https://github.com/groue/GRDB.swift/pull/1848)
|
||||
- **New**: Linux adjustments by [@thinkpractice](https://github.com/thinkpractice) in [#1825](https://github.com/groue/GRDB.swift/pull/1825)
|
||||
- **New**: SQLCipher adjustments by [@R4N](https://github.com/R4N) in [#1845](https://github.com/groue/GRDB.swift/pull/1845)
|
||||
- **New**: Android and Windows adjustments by [@marcprux](https://github.com/marcprux) in [#1849](https://github.com/groue/GRDB.swift/pull/1849), [#1850](https://github.com/groue/GRDB.swift/pull/1850)
|
||||
- **New**: Configure whether UPSERT should update all columns, or no column by [@groue](https://github.com/groue) in [#1852](https://github.com/groue/GRDB.swift/pull/1852)
|
||||
|
||||
## 7.9.0
|
||||
|
||||
Released December 13, 2025
|
||||
|
||||
- **Breaking Change**: Simplify the compiler checks for the availability of SQLite snapshots by [@groue](https://github.com/groue) in [#1826](https://github.com/groue/GRDB.swift/pull/1826)
|
||||
|
||||
This change aims at easing Linux and Android compatibility.
|
||||
|
||||
**The library requirements are raised to Swift 6.1+, Xcode 16.3+.**
|
||||
|
||||
- **Breaking Change**: Accept multiple SQLCipher libraries by [@groue](https://github.com/groue) in [#1819](https://github.com/groue/GRDB.swift/pull/1819)
|
||||
|
||||
This change aims at easing building GRDB against various SQLCipher flavors.
|
||||
|
||||
**The compiler flag that enables new GRDB APIs for SQLCipher is now `SQLITE_HAS_CODEC`.**
|
||||
|
||||
- **Fixed**: Fix cancellation of async tasks that use the FTS5 full-text engine by [@groue](https://github.com/groue) in [#1839](https://github.com/groue/GRDB.swift/pull/1839)
|
||||
|
||||
This workarounds an [SQLite bug](https://sqlite.org/forum/forumpost/95413eb410) that would trigger a GRDB crash, and improves the robustness of the library regarding database accesses cancellation and database interruption.
|
||||
|
||||
- **New**: Improve the ergonomics of `DatabaseMigrator.registerMigration(_:foreignKeyChecks:merging:migrate)`, introduced in [#1818](https://github.com/groue/GRDB.swift/pull/1818), by accepting that the name of the merged migration is included in the set of merged migrations:
|
||||
|
||||
```swift
|
||||
// Used to fail, now OK:
|
||||
migrator.registerMigration("v3", merging: ["v1", "v2", "v3"]) { ... }
|
||||
// ~~~~ ~~~~
|
||||
|
||||
// The above code is equivalent to:
|
||||
migrator.registerMigration("v3", merging: ["v1", "v2"]) { ... }
|
||||
```
|
||||
|
||||
## 7.8.0
|
||||
|
||||
Released October 2, 2025
|
||||
|
||||
- **New**: Merged Migrations by [@groue](https://github.com/groue) in [#1818](https://github.com/groue/GRDB.swift/pull/1818)
|
||||
|
||||
## 7.7.1
|
||||
|
||||
Released September 29, 2025
|
||||
|
||||
- **Fixed**: Fix the save() method for record types with attached triggers by [@groue](https://github.com/groue) in [#1822](https://github.com/groue/GRDB.swift/pull/1822)
|
||||
|
||||
## 7.7.0
|
||||
|
||||
Released September 23, 2025
|
||||
|
||||
- **New**: Update GRDB7MigrationGuide.md reference by [@emmanuel-ferdman](https://github.com/emmanuel-ferdman) in [#1807](https://github.com/groue/GRDB.swift/pull/1807)
|
||||
- **New**: Persistable Database Views by [@groue](https://github.com/groue) in [#1810](https://github.com/groue/GRDB.swift/pull/1810)
|
||||
- **New**: Support for Xcode 26 by [@groue](https://github.com/groue) in [#1813](https://github.com/groue/GRDB.swift/pull/1813)
|
||||
- **Fixed**: Fix another race condition regarding Task cancellation, completing [#1797](https://github.com/groue/GRDB.swift/pull/1797)
|
||||
|
||||
## 7.6.1
|
||||
|
||||
Released July 23, 2025
|
||||
|
||||
- **Fixed**: Fix race condition regarding Task cancellation by [@groue](https://github.com/groue) in [#1797](https://github.com/groue/GRDB.swift/pull/1797)
|
||||
|
||||
## 7.6.0
|
||||
|
||||
Released July 20, 2025
|
||||
|
||||
- **New**: All closures that accept DatabaseComponents can throw by [@groue](https://github.com/groue) in [#1768](https://github.com/groue/GRDB.swift/pull/1768)
|
||||
- **New**: Add Sendable conformance to DatabasePreUpdateEvent.Kind, matching DatabaseEvent.Kind by [@Jason-Abbott](https://github.com/Jason-Abbott) in [#1773](https://github.com/groue/GRDB.swift/pull/1773)
|
||||
- **New**: Add custom build instruction for hardened runtime by [@Jason-Abbott](https://github.com/Jason-Abbott) in [#1776](https://github.com/groue/GRDB.swift/pull/1776)
|
||||
- **New**: Access task locals from asynchronous database accesses by [@groue](https://github.com/groue) in [#1794](https://github.com/groue/GRDB.swift/pull/1794)
|
||||
- **New**: Throwing row accessors by [@groue](https://github.com/groue) in [#1796](https://github.com/groue/GRDB.swift/pull/1796)
|
||||
|
||||
## 7.5.0
|
||||
|
||||
Released May 11, 2025
|
||||
|
||||
- **New**: Make it possible to create a raw FTS5Pattern without any database connection by [@groue](https://github.com/groue) in [#1764](https://github.com/groue/GRDB.swift/pull/1764)
|
||||
- **New**: Build request with closures by [@groue](https://github.com/groue) in [#1759](https://github.com/groue/GRDB.swift/pull/1759)
|
||||
|
||||
## 7.4.1
|
||||
|
||||
Released March 28, 2025
|
||||
|
||||
- Removed a compiler warning
|
||||
|
||||
## 7.4.0
|
||||
|
||||
Released March 22, 2025
|
||||
|
||||
- **New**: Add the MIN and MAX multi-argument SQL functions to the query interface by [@groue](https://github.com/groue) in [#1745](https://github.com/groue/GRDB.swift/pull/1745)
|
||||
- **Fixed**: Transaction observers are not impacted by Task Cancellation by [@groue](https://github.com/groue) in [#1747](https://github.com/groue/GRDB.swift/pull/1747). This fixes unexpected `ValueObservation` failures in applications that perform asynchronous writes.
|
||||
|
||||
## 7.3.0
|
||||
|
||||
Released February 23, 2025
|
||||
@@ -4308,7 +4448,7 @@ Released April 3, 2017
|
||||
|
||||
**Breaking Changes**
|
||||
|
||||
- SQLite C API is now available right from the GRBD module: you don't need any longer to import `SQLiteiPhoneOS` module et al (see documentation for [Raw SQLite Pointers](https://github.com/groue/GRDB.swift#raw-sqlite-pointers)).
|
||||
- SQLite C API is now available right from the GRDB module: you don't need any longer to import `SQLiteiPhoneOS` module et al (see documentation for [Raw SQLite Pointers](https://github.com/groue/GRDB.swift#raw-sqlite-pointers)).
|
||||
- The [manual installation procedure for WatchOS extensions](https://github.com/groue/GRDB.swift#installation) has changed.
|
||||
- [Carthage](https://github.com/Carthage/Carthage) is no longer supported. At the present time it is unable to support the various frameworks built by GRDB (system SQLite, SQLCipher, custom SQLite builds, etc.)
|
||||
|
||||
|
||||
+4
-4
@@ -28,7 +28,7 @@ How you can Contribute
|
||||
- `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.
|
||||
- `GRDBProfiling.xcodeproj`: a project which helps profile GRDB with Instruments. No code here is really precious.
|
||||
- `GRDBDemoiOS.xcodeproj`, `GRDBCombineDemo.xcodeproj`, `GRDBAsyncDemo.xcodeproj`: the demo apps.
|
||||
|
||||
To work with `GRDBCustom.xcodeproj`:
|
||||
@@ -71,11 +71,11 @@ How you can Contribute
|
||||
|
||||
Please keep the reference and the guides up-to-date. To control the quality of your DocC reference documentation, close the workspace, open `Package.swift` in Xcode, and use Product > Build Documentation.
|
||||
|
||||
GRDB is "documentation-driven", which means that nothing ships until it is supported by documentation that makes sense. Documentation makes sense when someone who is not you is able to figure out what is the purpose of your contribution, how to use it, and what are its eventual caveats and corner cases. When the documentation is hard to write, or reveals too many caveats, it is the sign that the api needs to be fixed.
|
||||
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 the purpose of your contribution is, how to use it, and what its caveats and corner cases are. When the documentation is hard to write, or reveals too many caveats, it is a 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.
|
||||
9. **If you are granted 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
|
||||
@@ -85,7 +85,7 @@ Answering [issues](https://github.com/groue/GRDB.swift/issues), participating in
|
||||
|
||||
## 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.
|
||||
GRDB is free, and openly developed by its contributors, in 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.
|
||||
|
||||
|
||||
+191
-175
File diff suppressed because it is too large.
Load diff
+10
-11
@@ -113,7 +113,7 @@ let cancellable = publisher.sink(
|
||||
|
||||
# Asynchronous Database Access
|
||||
|
||||
GRDB provide publishers that perform asynchronous database accesses:
|
||||
GRDB provides publishers that perform asynchronous database accesses:
|
||||
|
||||
- [`readPublisher(receiveOn:value:)`]
|
||||
- [`writePublisher(receiveOn:updates:)`]
|
||||
@@ -123,7 +123,7 @@ GRDB provide publishers that perform asynchronous database accesses:
|
||||
|
||||
#### `DatabaseReader.readPublisher(receiveOn:value:)`
|
||||
|
||||
This methods returns a publisher that completes after database values have been asynchronously fetched.
|
||||
This method returns a publisher that completes after database values have been asynchronously fetched.
|
||||
|
||||
```swift
|
||||
// DatabasePublishers.Read<[Player]>
|
||||
@@ -134,7 +134,7 @@ let players = dbQueue.readPublisher { db in
|
||||
|
||||
Any attempt at modifying the database completes subscriptions with an error.
|
||||
|
||||
When you use a [database queue] or a [database snapshot], the read has to wait for any eventual concurrent database access performed by this queue or snapshot to complete.
|
||||
When you use a [database queue] or a [database snapshot], the read has to wait for any concurrent database access performed by this queue or snapshot to complete.
|
||||
|
||||
When you use a [database pool], reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be [configured].
|
||||
|
||||
@@ -174,9 +174,8 @@ This method returns a publisher that completes after database updates have been
|
||||
```swift
|
||||
// DatabasePublishers.Write<Int>
|
||||
let newPlayerCount = dbQueue.writePublisher(
|
||||
updates: { db in try Player(...).insert(db) }
|
||||
updates: { db in try Player(...).insert(db) },
|
||||
thenRead: { db, _ in try Player.fetchCount(db) })
|
||||
}
|
||||
```
|
||||
|
||||
It publishes exactly the same values as [`writePublisher(receiveOn:updates:)`]:
|
||||
@@ -189,7 +188,7 @@ let newPlayerCount = dbQueue.writePublisher { db -> Int in
|
||||
}
|
||||
```
|
||||
|
||||
The difference is that the last fetches are performed in the `thenRead` function. This function accepts two arguments: a readonly database connection, and the result of the `updates` function. This allows you to pass information from a function to the other (it is ignored in the sample code above).
|
||||
The difference is that the last fetches are performed in the `thenRead` function. This function accepts two arguments: a readonly database connection, and the result of the `updates` function. This allows you to pass information from one function to the other (it is ignored in the sample code above).
|
||||
|
||||
When you use a [database pool], this method applies a scheduling optimization: the `thenRead` function sees the database in the state left by the `updates` function, and yet does not block any concurrent writes. This can reduce database write contention.
|
||||
|
||||
@@ -224,11 +223,11 @@ let publisher = observation.publisher(in: dbQueue)
|
||||
|
||||
This publisher has the same behavior as ValueObservation:
|
||||
|
||||
- It notifies an initial value before the eventual changes.
|
||||
- It notifies an initial value before subsequent 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()](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/removeduplicates()) GRDB operator also.
|
||||
- It only completes when it is cancelled.
|
||||
- By default, it notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously.
|
||||
- By default, it notifies the initial value, as well as subsequent 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 [ValueObservationScheduler](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservationscheduler).
|
||||
|
||||
@@ -311,7 +310,7 @@ When you compose database publishers together with Combine operators such as `co
|
||||
|
||||
This is because each database publisher is isolated from others: each one of them sees its own state of the database. Whenever some database change is interleaved between publisher operations, publishers will process or publish values that may not fit well together.
|
||||
|
||||
In other words, whenever you need to perform some database access or observation that depends on some database invariant, make sure you define one and only one database publisher instead of combining several publishers. This is how you will prevent eventual concurrent database writes from messing with your app, and introduce bugs.
|
||||
In other words, whenever you need to perform some database access or observation that depends on some database invariant, make sure you define one and only one database publisher instead of combining several publishers. This is how you will prevent concurrent database writes from messing with your app, and introducing bugs.
|
||||
|
||||
To this end, remember that *all database publishers can perform several requests*.
|
||||
|
||||
@@ -332,7 +331,7 @@ let hallOfFamePublisher = ValueObservation
|
||||
|
||||
// 2nd request
|
||||
let bestPlayers = try Player
|
||||
.order(Column("score").desc)
|
||||
.order(\.score.desc)
|
||||
.limit(10)
|
||||
.fetchAll(db)
|
||||
|
||||
@@ -358,7 +357,7 @@ let totalPlayerCountPublisher = ValueObservation
|
||||
// OK
|
||||
let bestPlayerPublisher = ValueObservation
|
||||
.tracking(Player
|
||||
.order(Column("score").desc)
|
||||
.order(\.score.desc)
|
||||
.limit(10)
|
||||
.fetchAll)
|
||||
.publisher(in: dbQueue)
|
||||
|
||||
@@ -31,7 +31,7 @@ The CTE request can be provided as a [query interface request]:
|
||||
// WITH playerName AS (SELECT name FROM player) ...
|
||||
let playerNameCTE = CommonTableExpression(
|
||||
named: "playerName",
|
||||
request: Player.select(Column("name")))
|
||||
request: Player.select(\.name))
|
||||
```
|
||||
|
||||
You can feed a CTE with raw SQL as well (second and third examples use [SQL Interpolation]):
|
||||
@@ -123,16 +123,16 @@ And we can then filter the `player` table with a subquery:
|
||||
// WHERE name = (SELECT * FROM playerName)
|
||||
let request = Player
|
||||
.with(playerNameCTE)
|
||||
.filter(Column("name") == playerNameCTE.all())
|
||||
.filter { $0.name == playerNameCTE.all() }
|
||||
```
|
||||
|
||||
> **Note**: the `with(_:)` method can be called as many times as a there are common table expressions in your request.
|
||||
> **Note**: the `with(_:)` method can be called as many times as there are common table expressions in your request.
|
||||
>
|
||||
> **Note**: the `with(_:)` method can be called at any time, as all request methods: `Player.with(...).filter(...).with(...)`.
|
||||
> **Note**: the `with(_:)` method can be called at any time, like all request methods: `Player.with(...).filter(...).with(...)`.
|
||||
>
|
||||
> **Note**: the `with(_:)` method replaces any previously embedded CTE that has the same table name. This allows you to embed the same CTE several times if you feel like it.
|
||||
>
|
||||
> **Note**: the `CommonTableExpression.all()` method builds a regular [query interface request] for the content of the CTE (like `SELECT * FROM <cte name>`, not to be mismatched with the request that was used to define the CTE). You can filter this request, sort it, etc, like all query interface requests:
|
||||
> **Note**: the `CommonTableExpression.all()` method builds a regular [query interface request] for the content of the CTE (like `SELECT * FROM <cte name>`, not to be confused with the request that was used to define the CTE). You can filter this request, sort it, etc, like all query interface requests:
|
||||
>
|
||||
> ```swift
|
||||
> cte.all().select(...).filter(...).group(...).order(...)
|
||||
@@ -167,13 +167,13 @@ Common table expressions can also be used as subqueries, when you update or dele
|
||||
// UPDATE player SET name = (SELECT * FROM playerName)
|
||||
try Player
|
||||
.with(playerNameCTE)
|
||||
.updateAll(db, Column("name").set(to: playerNameCTE.all()))
|
||||
.updateAll(db) { $0.name.set(to: playerNameCTE.all()) }
|
||||
|
||||
// WITH playerName AS (SELECT 'O''Brien')
|
||||
// DELETE FROM player WHERE name = (SELECT * FROM playerName)
|
||||
try Player
|
||||
.with(playerNameCTE)
|
||||
.filter(Column("name") == playerNameCTE.all())
|
||||
.filter { $0.name == playerNameCTE.all() }
|
||||
.deleteAll(db)
|
||||
```
|
||||
|
||||
@@ -270,7 +270,7 @@ LeftRecord
|
||||
|
||||
### CTE Association Example: a Chat App
|
||||
|
||||
As an example, let's build the classical main screen of a chat application: a list of all latest messages from all conversations.
|
||||
As an example, let's build the classic main screen of a chat application: a list of all latest messages from all conversations.
|
||||
|
||||
The database schema of the chat app contains a `chat` and a `message` table. The application defines the following records:
|
||||
|
||||
@@ -281,9 +281,15 @@ struct Chat: Codable, FetchableRecord, PersistableRecord {
|
||||
}
|
||||
|
||||
struct Message: Codable, FetchableRecord, PersistableRecord {
|
||||
var chatID: Int64
|
||||
var chatId: Int64
|
||||
var date: Date
|
||||
...
|
||||
|
||||
enum Columns {
|
||||
static let chatId = Column("chatId")
|
||||
static let date = Column("date")
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -315,8 +321,8 @@ We start by defining the CTE request, which loads the latest messages of all cha
|
||||
```swift
|
||||
// SELECT *, MAX(date) FROM message GROUP BY chatID
|
||||
let latestMessageRequest = Message
|
||||
.annotated(with: max(Column("date")))
|
||||
.group(Column("chatID"))
|
||||
.annotated { max($0.date) }
|
||||
.group(\.chatId)
|
||||
```
|
||||
|
||||
We can now define the CTE for the latest messages:
|
||||
@@ -324,7 +330,7 @@ We can now define the CTE for the latest messages:
|
||||
```swift
|
||||
// WITH latestMessage AS
|
||||
// (SELECT *, MAX(date) FROM message GROUP BY chatID)
|
||||
let latestMessageCTE = CommonTableExpression(
|
||||
let latestMessageCTE = CommonTableExpression<Message>(
|
||||
named: "latestMessage",
|
||||
request: latestMessageRequest)
|
||||
```
|
||||
@@ -337,9 +343,9 @@ The association from a chat to its latest message follows:
|
||||
let latestMessage = Chat.association(
|
||||
to: latestMessageCTE,
|
||||
on: { chat, latestMessage in
|
||||
chat[Column("id")] == latestMessage[Column("chatID")]
|
||||
chat.id == latestMessage.chatId
|
||||
})
|
||||
.order(Column("date").desc)
|
||||
.order(\.date.desc)
|
||||
```
|
||||
|
||||
The final request can now be defined:
|
||||
@@ -362,7 +368,7 @@ And we can fetch the data that feeds our application screen:
|
||||
|
||||
```swift
|
||||
|
||||
let chatInfos: [ChatInfos] = try dbQueue.read { db in
|
||||
let chatInfos: [ChatInfo] = try dbQueue.read { db in
|
||||
try request.fetchAll(db)
|
||||
}
|
||||
```
|
||||
@@ -389,8 +395,8 @@ let chatInfos: [ChatInfos] = try dbQueue.read { db in
|
||||
> // JOIN far ON ...
|
||||
> let request = BaseRecord
|
||||
> .with(cte1).with(cte2)
|
||||
> .joining(required: assoc1. // OK
|
||||
> .joining(required: assoc2. // OK
|
||||
> .joining(required: assoc1 // OK
|
||||
> .joining(required: assoc2 // OK
|
||||
> .joining(required: assoc3))) // OK
|
||||
>
|
||||
> // Compiler error
|
||||
|
||||
@@ -5,22 +5,24 @@ By default, GRDB uses the version of SQLite that ships with the target operating
|
||||
|
||||
**You can build GRDB with a custom build of [SQLite 3.47.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](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactionobserver).
|
||||
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](FullTextSearch.md), and [SQLite Pre-Update Hooks](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactionobserver).
|
||||
|
||||
GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfalling/SQLiteLib), which uses the same SQLite configuration as the one used by Apple in its operating systems, and lets you add extra compilation options that leverage the features you need.
|
||||
|
||||
> Warning: The technique described here is not compatible with the Swift Package Manager (SPM). It will create [build issues](https://github.com/groue/GRDB.swift/issues/1709) with SPM companion libraries such as [GRDBQuery](https://github.com/groue/GRDBQuery) or [GRDBSnapshotTesting](https://github.com/groue/GRDBSnapshotTesting).
|
||||
|
||||
**To install GRDB with a custom SQLite build:**
|
||||
|
||||
1. Clone the GRDB git repository, checkout the latest tagged version:
|
||||
|
||||
|
||||
```sh
|
||||
cd [GRDB directory]
|
||||
git checkout [latest tag]
|
||||
git submodule update --init SQLiteCustom/src
|
||||
```
|
||||
|
||||
|
||||
2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5`, `SQLITE_ENABLE_PREUPDATE_HOOK`.
|
||||
|
||||
|
||||
It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation) when you use a [Database Pool](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool).
|
||||
|
||||
3. Create a folder named `GRDBCustomSQLite` somewhere in your project directory.
|
||||
@@ -28,31 +30,31 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
4. Create four files in the `GRDBCustomSQLite` folder:
|
||||
|
||||
- `SQLiteLib-USER.xcconfig`: this file sets the extra SQLite compilation flags.
|
||||
|
||||
|
||||
```xcconfig
|
||||
// As many -D options as there are custom SQLite compilation options
|
||||
// Note: there is no space between -D and the option name.
|
||||
CUSTOM_SQLLIBRARY_CFLAGS = -DSQLITE_ENABLE_SNAPSHOT -DSQLITE_ENABLE_FTS5
|
||||
```
|
||||
|
||||
|
||||
- `GRDBCustomSQLite-USER.xcconfig`: this file lets GRDB know about extra compilation flags, and enables extra GRDB APIs.
|
||||
|
||||
|
||||
```xcconfig
|
||||
// As many -D options as there are custom SQLite compilation options
|
||||
// Note: there is one space between -D and the option name.
|
||||
CUSTOM_OTHER_SWIFT_FLAGS = -D SQLITE_ENABLE_SNAPSHOT -D SQLITE_ENABLE_FTS5
|
||||
```
|
||||
|
||||
|
||||
- `GRDBCustomSQLite-USER.h`: this file lets your application know about extra compilation flags.
|
||||
|
||||
|
||||
```c
|
||||
// As many #define as there are custom SQLite compilation options
|
||||
#define SQLITE_ENABLE_SNAPSHOT
|
||||
#define SQLITE_ENABLE_FTS5
|
||||
```
|
||||
|
||||
|
||||
- `GRDBCustomSQLite-INSTALL.sh`: this file installs the three other files.
|
||||
|
||||
|
||||
```sh
|
||||
# License: MIT License
|
||||
# https://github.com/swiftlyfalling/SQLiteLib/blob/master/LICENSE
|
||||
@@ -61,53 +63,53 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
# PROJECT PATHS
|
||||
# !! MODIFY THESE TO MATCH YOUR PROJECT HIERARCHY !!
|
||||
#######################################################
|
||||
|
||||
|
||||
# The path to the folder containing GRDBCustom.xcodeproj:
|
||||
GRDB_SOURCE_PATH="${PROJECT_DIR}/GRDB"
|
||||
|
||||
|
||||
# The path to your custom "SQLiteLib-USER.xcconfig":
|
||||
SQLITELIB_XCCONFIG_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/SQLiteLib-USER.xcconfig"
|
||||
|
||||
|
||||
# The path to your custom "GRDBCustomSQLite-USER.xcconfig":
|
||||
CUSTOMSQLITE_XCCONFIG_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/GRDBCustomSQLite-USER.xcconfig"
|
||||
|
||||
|
||||
# The path to your custom "GRDBCustomSQLite-USER.h":
|
||||
CUSTOMSQLITE_H_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/GRDBCustomSQLite-USER.h"
|
||||
|
||||
|
||||
#######################################################
|
||||
#
|
||||
#######################################################
|
||||
|
||||
|
||||
|
||||
|
||||
if [ ! -d "$GRDB_SOURCE_PATH" ];
|
||||
then
|
||||
echo "error: Path to GRDB source (GRDB_SOURCE_PATH) missing/incorrect: $GRDB_SOURCE_PATH"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
|
||||
SyncFileChanges () {
|
||||
SOURCE=$1
|
||||
DESTINATIONPATH=$2
|
||||
DESTINATIONFILENAME=$3
|
||||
DESTINATION="${DESTINATIONPATH}/${DESTINATIONFILENAME}"
|
||||
|
||||
|
||||
if [ ! -f "$SOURCE" ];
|
||||
then
|
||||
echo "error: Source file missing: $SOURCE"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
|
||||
rsync -a "$SOURCE" "$DESTINATION"
|
||||
}
|
||||
|
||||
|
||||
SyncFileChanges $SQLITELIB_XCCONFIG_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom/src" "SQLiteLib-USER.xcconfig"
|
||||
SyncFileChanges $CUSTOMSQLITE_XCCONFIG_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom" "GRDBCustomSQLite-USER.xcconfig"
|
||||
SyncFileChanges $CUSTOMSQLITE_H_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom" "GRDBCustomSQLite-USER.h"
|
||||
|
||||
|
||||
echo "Finished syncing"
|
||||
```
|
||||
|
||||
Modify the top of `GRDBCustomSQLite-INSTALL.sh` file so that it contains correct paths.
|
||||
|
||||
Modify the top of the `GRDBCustomSQLite-INSTALL.sh` file so that it contains correct paths.
|
||||
|
||||
5. Embed the `GRDBCustom.xcodeproj` project in your own project.
|
||||
|
||||
@@ -116,17 +118,21 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
7. Add the `GRDBCustom.framework` from the targeted platform to the **Embedded Binaries** section of the **General** tab of your **application target**.
|
||||
|
||||
8. Add a Run Script phase for your target in the **Pre-actions** section of the **Build** tab of your **application scheme**:
|
||||
|
||||
|
||||
```sh
|
||||
source "${PROJECT_DIR}/GRDBCustomSQLite/GRDBCustomSQLite-INSTALL.sh"
|
||||
```
|
||||
|
||||
|
||||
The path should be the path to your `GRDBCustomSQLite-INSTALL.sh` file.
|
||||
|
||||
|
||||
Select your application target in the "Provide build settings from" menu.
|
||||
|
||||
9. Check the "Shared" checkbox of your application scheme (this lets you commit the pre-action in your Version Control System).
|
||||
|
||||
10. If you have enabled "Hardened Runtime" for your target (**Build Settings**/**Signing**) then you may need to check **Disable Library Validation** under the **Hardened Runtime** section of the **Signing & Capabilities** tab.
|
||||
|
||||
(The build error without this exception is "Library not loaded ... different Team IDs")
|
||||
|
||||
Now you can use GRDB with your custom SQLite build:
|
||||
|
||||
```swift
|
||||
|
||||
@@ -158,7 +158,7 @@
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = 1;
|
||||
LastSwiftUpdateCheck = 1600;
|
||||
LastUpgradeCheck = 1600;
|
||||
LastUpgradeCheck = 2600;
|
||||
TargetAttributes = {
|
||||
56CFC6432C9F1DC9000B5023 = {
|
||||
CreatedOnToolsVersion = 16.0;
|
||||
@@ -293,6 +293,7 @@
|
||||
MTL_FAST_MATH = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
@@ -350,6 +351,7 @@
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
MTL_FAST_MATH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
VALIDATE_PRODUCT = YES;
|
||||
@@ -380,7 +382,7 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemo;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 6.0;
|
||||
SWIFT_VERSION = 6.1;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
};
|
||||
name = Debug;
|
||||
@@ -409,7 +411,7 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemo;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 6.0;
|
||||
SWIFT_VERSION = 6.1;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
};
|
||||
name = Release;
|
||||
@@ -425,7 +427,7 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoTests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = NO;
|
||||
SWIFT_VERSION = 6.0;
|
||||
SWIFT_VERSION = 6.1;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBDemo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/GRDBDemo";
|
||||
};
|
||||
@@ -442,7 +444,7 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoTests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = NO;
|
||||
SWIFT_VERSION = 6.0;
|
||||
SWIFT_VERSION = 6.1;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBDemo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/GRDBDemo";
|
||||
};
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1600"
|
||||
LastUpgradeVersion = "2600"
|
||||
version = "1.7">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -12,13 +12,13 @@ import os.log
|
||||
/// let dbQueue = try DatabaseQueue(configuration: config)
|
||||
/// let appDatabase = try AppDatabase(dbQueue)
|
||||
/// ```
|
||||
final class AppDatabase: Sendable {
|
||||
struct AppDatabase: Sendable {
|
||||
/// Access to the database.
|
||||
///
|
||||
/// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections>
|
||||
private let dbWriter: any DatabaseWriter
|
||||
|
||||
/// Creates a `AppDatabase`, and makes sure the database schema
|
||||
/// Creates an `AppDatabase`, and makes sure the database schema
|
||||
/// is ready.
|
||||
///
|
||||
/// - important: Create the `DatabaseWriter` with a configuration
|
||||
@@ -62,7 +62,7 @@ final class AppDatabase: Sendable {
|
||||
// MARK: - Database Configuration
|
||||
|
||||
extension AppDatabase {
|
||||
// Uncomment for enabling SQL logging
|
||||
// Uncomment to enable SQL logging
|
||||
// private static let sqlLogger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
|
||||
|
||||
/// Returns a database configuration suited for `AppDatabase`.
|
||||
@@ -76,7 +76,7 @@ extension AppDatabase {
|
||||
// db.add(function: ...)
|
||||
// }
|
||||
//
|
||||
// Uncomment for enabling SQL logging if the `SQL_TRACE` environment variable is set.
|
||||
// Uncomment to enable SQL logging if the `SQL_TRACE` environment variable is set.
|
||||
// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/database/trace(options:_:)>
|
||||
// if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil {
|
||||
// config.prepareDatabase { db in
|
||||
@@ -114,25 +114,25 @@ extension AppDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete the specified players
|
||||
/// Deletes the specified players
|
||||
func deletePlayers(ids: [Int64]) throws {
|
||||
try dbWriter.write { db in
|
||||
_ = try Player.deleteAll(db, keys: ids)
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete all players
|
||||
/// Deletes all players
|
||||
func deleteAllPlayers() throws {
|
||||
try dbWriter.write { db in
|
||||
_ = try Player.deleteAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Refresh all players (by performing some random changes, for demo purpose).
|
||||
/// Refreshes all players (by performing some random changes, for demo purposes).
|
||||
func refreshPlayers() async throws {
|
||||
try await dbWriter.write { [self] db in
|
||||
try await dbWriter.write { db in
|
||||
if try Player.all().isEmpty(db) {
|
||||
// When database is empty, insert new random players
|
||||
// When the database is empty, insert new random players
|
||||
try createRandomPlayers(db)
|
||||
} else {
|
||||
// Insert a player
|
||||
@@ -155,7 +155,7 @@ extension AppDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Create random players if the database is empty.
|
||||
/// Creates random players if the database is empty.
|
||||
func createRandomPlayersIfEmpty() throws {
|
||||
try dbWriter.write { db in
|
||||
if try Player.all().isEmpty(db) {
|
||||
@@ -175,11 +175,11 @@ extension AppDatabase {
|
||||
// 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.
|
||||
// gives 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.
|
||||
/// Provides read-only access to the database.
|
||||
var reader: any GRDB.DatabaseReader {
|
||||
dbWriter
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ struct Player: 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.
|
||||
/// Use nil for players that are not inserted in the database yet.
|
||||
var id: Int64?
|
||||
var name: String
|
||||
var score: Int
|
||||
@@ -64,45 +64,3 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
// Convenience access to player columns in this file
|
||||
private typealias Columns = Player.Columns
|
||||
|
||||
// MARK: - Player Database Requests
|
||||
|
||||
/// Define some player requests used by the application.
|
||||
///
|
||||
/// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices>
|
||||
extension DerivableRequest<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(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(
|
||||
Columns.score.desc,
|
||||
Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@ extension AppDatabase {
|
||||
// Create the AppDatabase
|
||||
let appDatabase = try AppDatabase(dbPool)
|
||||
|
||||
// Populate the database if it is empty, for better demo purpose.
|
||||
// Populate the database if it is empty, for a better demo.
|
||||
try appDatabase.createRandomPlayersIfEmpty()
|
||||
|
||||
return appDatabase
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
"zero" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "No Player"
|
||||
"value" : "No Players"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,7 @@
|
||||
"zero" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "0 point"
|
||||
"value" : "0 points"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+5
-8
@@ -1,7 +1,6 @@
|
||||
import SwiftUI
|
||||
|
||||
struct PlayerEditionView: View {
|
||||
@Environment(\.isPresented) var isPresented
|
||||
struct PlayerEditView: View {
|
||||
@Environment(\.appDatabase) var appDatabase
|
||||
@State var form: PlayerForm
|
||||
var player: Player
|
||||
@@ -16,11 +15,9 @@ struct PlayerEditionView: View {
|
||||
PlayerFormView(form: $form)
|
||||
}
|
||||
.navigationTitle(player.name)
|
||||
.onChange(of: isPresented) {
|
||||
if !isPresented {
|
||||
// Back button was pressed
|
||||
save()
|
||||
}
|
||||
.onDisappear {
|
||||
// Back button was pressed
|
||||
save()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +33,6 @@ struct PlayerEditionView: View {
|
||||
|
||||
#Preview {
|
||||
NavigationStack {
|
||||
PlayerEditionView(player: .makeRandom())
|
||||
PlayerEditView(player: .makeRandom())
|
||||
}
|
||||
}
|
||||
@@ -41,15 +41,22 @@ import GRDB
|
||||
let observation = ValueObservation.tracking { [ordering] db in
|
||||
switch ordering {
|
||||
case .byName:
|
||||
try Player.all().orderedByName().fetchAll(db)
|
||||
try Player
|
||||
.order { $0.name.collating(.localizedCaseInsensitiveCompare) }
|
||||
.fetchAll(db)
|
||||
case .byScore:
|
||||
try Player.all().orderedByScore().fetchAll(db)
|
||||
try Player
|
||||
.order { [
|
||||
$0.score.desc,
|
||||
$0.name.collating(.localizedCaseInsensitiveCompare),
|
||||
] }
|
||||
.fetchAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
// Start observing the database.
|
||||
// Previous observation, if any, is cancelled.
|
||||
cancellable = observation.start(in: appDatabase.reader) { error in
|
||||
cancellable = observation.start(in: appDatabase.reader, scheduling: .immediate) { error in
|
||||
// Handle error
|
||||
} onChange: { [unowned self] players in
|
||||
self.players = players
|
||||
@@ -58,7 +65,7 @@ import GRDB
|
||||
|
||||
// MARK: - Actions
|
||||
|
||||
/// Delete players at specified indexes in `self.players`.
|
||||
/// Delete players at the specified indexes in `self.players`.
|
||||
func deletePlayers(at offsets: IndexSet) throws {
|
||||
let playerIds = offsets.compactMap { players[$0].id }
|
||||
try appDatabase.deletePlayers(ids: playerIds)
|
||||
@@ -69,12 +76,12 @@ import GRDB
|
||||
try appDatabase.deleteAllPlayers()
|
||||
}
|
||||
|
||||
/// Refresh all players (by performing some random changes, for demo purpose).
|
||||
/// Refresh all players (by performing some random changes, for demo purposes).
|
||||
func refreshPlayers() async throws {
|
||||
try await appDatabase.refreshPlayers()
|
||||
}
|
||||
|
||||
/// Perform 50 refreshes in parallel, for demo purpose.
|
||||
/// Perform 50 refreshes in parallel, for demo purposes.
|
||||
func refreshPlayersManyTimes() async throws {
|
||||
try await withThrowingTaskGroup(of: Void.self) { group in
|
||||
for _ in 0..<50 {
|
||||
|
||||
@@ -8,7 +8,7 @@ struct PlayerListView: View {
|
||||
List {
|
||||
ForEach(model.players, id: \.id) { player in
|
||||
NavigationLink {
|
||||
PlayerEditionView(player: player)
|
||||
PlayerEditView(player: player)
|
||||
} label: {
|
||||
PlayerRow(player: player)
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ private struct ContentView: View {
|
||||
.buttonStyle(.borderedProminent)
|
||||
}
|
||||
// Hide the title, but set a string anyway in order to avoid
|
||||
// an odd relayout when player list becomes empty during
|
||||
// an odd relayout when the player list becomes empty during
|
||||
// the tornado.
|
||||
.navigationTitle("")
|
||||
}
|
||||
|
||||
@@ -5,11 +5,11 @@ GRDBDemo Application
|
||||
|
||||
**GRDBDemo demonstrates how GRDB can fuel a SwiftUI application.**
|
||||
|
||||
> **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.
|
||||
> **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 inspiration.
|
||||
|
||||
The topics covered in this demo are:
|
||||
|
||||
- How to setup a database in an iOS app.
|
||||
- How to set up a database in an iOS app.
|
||||
- How to define a simple [Codable Record](../../../README.md#codable-records).
|
||||
- How to track database changes and animate a SwiftUI List with [ValueObservation](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation).
|
||||
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices).
|
||||
@@ -23,21 +23,21 @@ The topics covered in this demo are:
|
||||
|
||||
- [AppDatabase.swift](GRDBDemo/Database/AppDatabase.swift)
|
||||
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasemigrator) in order to setup the database schema, and provides methods that read and write.
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasemigrator) in order to set up the database schema, and provides methods that read and write.
|
||||
|
||||
`AppDatabase` is [tested](GRDBDemoTests/AppDatabaseTests.swift).
|
||||
|
||||
- [Persistence.swift](GRDBDemo/Database/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.
|
||||
This file instantiates `AppDatabase` instances for the various needs of the project: one database on disk for the application, and in-memory databases for SwiftUI previews.
|
||||
|
||||
- [Player.swift](GRDBDemo/Database/Models/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).
|
||||
`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 the advantages of [Codable Records](../../../README.md#codable-records).
|
||||
|
||||
- [PlayerListModel.swift](GRDBDemo/Views/PlayerListModel.swift)
|
||||
|
||||
`PlayerListModel` is an `@Observable` object that observes the database, displays always fresh values on screen, and performs actions.
|
||||
`PlayerListModel` is an `@Observable` object that observes the database, always displays fresh values on screen, and performs actions.
|
||||
|
||||
`PlayerListModel` is [tested](GRDBDemoTests/PlayerListModelTests.swift).
|
||||
|
||||
|
||||
@@ -29,13 +29,13 @@ GRDB lets you define your own custom FTS5 tokenizers, and extend SQLite built-in
|
||||
|
||||
**A Tokenizer splits text into tokens**. For example, a tokenizer can split "SQLite is a database engine" into the five tokens "SQLite", "is", "a", "database", and "engine".
|
||||
|
||||
FTS5 use tokenizers to tokenize both indexed documents and search patterns. **A match between a document and a search pattern happens when both produce *identical* tokens.**
|
||||
FTS5 uses tokenizers to tokenize both indexed documents and search patterns. **A match between a document and a search pattern happens when both produce *identical* tokens.**
|
||||
|
||||
All SQLite [built-in tokenizers](https://www.sqlite.org/fts5.html#tokenizers) tokenize both "SQLite" and "sqlite" into the common lowercase token "sqlite". This is why they are case-insensitive. Generally speaking, different tokenizers achieve different matching by applying different transformations to the input text.
|
||||
|
||||
- The [ascii](https://www.sqlite.org/fts5.html#ascii_tokenizer) tokenizer turns all ASCII characters to lowercase. "SQLite is a database engine" gives "sqlite", "is", "a", "database", and "engine". The query "SQLITE DATABASE" will match, because its tokens "sqlite" and "database" are found in the document.
|
||||
|
||||
- The [unicode61](https://www.sqlite.org/fts5.html#unicode61_tokenizer) tokenizer remove diacritics from latin characters. Unlike the ascii tokenizer, it will match "Jérôme" with "Jerome", as both produce the same "jerome" token.
|
||||
- The [unicode61](https://www.sqlite.org/fts5.html#unicode61_tokenizer) tokenizer removes diacritics from latin characters. Unlike the ascii tokenizer, it will match "Jérôme" with "Jerome", as both produce the same "jerome" token.
|
||||
|
||||
- The [porter](https://www.sqlite.org/fts5.html#porter_tokenizer) tokenizer turns English words into their root: "database engine" gives the "databas" and "engin" tokens. The query "database engines" will match, because it produces the same tokens.
|
||||
|
||||
@@ -43,7 +43,7 @@ However, built-in tokenizers don't match "first" with "1st", because they produc
|
||||
|
||||
Nor do they match "Grossmann" with "Großmann", because they produce the different "grossmann" and "großmann" tokens.
|
||||
|
||||
Custom tokenizers help dealing with these situations. We'll see how to match "Grossmann" and "Großmann" by tokenizing them into "grossmann" (see [latin script](#example-latin-script)). We'll also see how to have "first" and "1st" emit *synonym tokens*, so that they can match too (see [synonyms](#example-synonyms)).
|
||||
Custom tokenizers help deal with these situations. We'll see how to match "Grossmann" and "Großmann" by tokenizing them into "grossmann" (see [latin script](#example-latin-script)). We'll also see how to have "first" and "1st" emit *synonym tokens*, so that they can match too (see [synonyms](#example-synonyms)).
|
||||
|
||||
|
||||
## The Tokenizer Protocols
|
||||
@@ -54,7 +54,7 @@ GRDB lets you use and define FTS5 tokenizers through three protocols:
|
||||
|
||||
- [FTS5CustomTokenizer](#fts5customtokenizer): the low-level protocol that lets custom tokenizers use the raw [FTS5 C API](https://www.sqlite.org/fts5.html#custom_tokenizers).
|
||||
|
||||
- [FTS5WrapperTokenizer](#fts5wrappertokenizer): the high-level protocol for custom tokenizers that post-processes the tokens produced by another FTS5Tokenizer.
|
||||
- [FTS5WrapperTokenizer](#fts5wrappertokenizer): the high-level protocol for custom tokenizers that post-process the tokens produced by another FTS5Tokenizer.
|
||||
|
||||
|
||||
## Using a Custom Tokenizer
|
||||
@@ -73,7 +73,7 @@ config.prepareDatabase { db in
|
||||
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
|
||||
```
|
||||
|
||||
**Create [full-text tables](../../../#create-fts5-virtual-tables) that use the custom tokenizer:**
|
||||
**Create [full-text tables](FullTextSearch.md#create-fts5-virtual-tables) that use the custom tokenizer:**
|
||||
|
||||
```swift
|
||||
try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
@@ -82,7 +82,7 @@ try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
}
|
||||
```
|
||||
|
||||
The full-text table can be fed and queried in [a regular way](../../../#full-text-search):
|
||||
The full-text table can be fed and queried in [a regular way](FullTextSearch.md):
|
||||
|
||||
```swift
|
||||
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["..."])
|
||||
@@ -161,7 +161,7 @@ try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
|
||||
FTS5CustomTokenizer inherits from [FTS5Tokenizer](#fts5tokenizer), and performs tokenization with its `tokenize(context:tokenization:pText:nText:tokenCallback:)` method. This low-level method matches the `xTokenize` C function documented at https://www.sqlite.org/fts5.html#custom_tokenizers.
|
||||
|
||||
This method arguments are:
|
||||
This method's arguments are:
|
||||
|
||||
- `context`: An opaque pointer that is the first argument to the `tokenCallback` function
|
||||
- `tokenization`: The reason why FTS5 is requesting tokenization.
|
||||
@@ -175,14 +175,14 @@ This method arguments are:
|
||||
- `iStart`: Byte offset of token within input text
|
||||
- `iEnd`: Byte offset of end of token within input text
|
||||
|
||||
Since tokenization is hard, and pointers to byte buffers uneasy to deal with, you may enjoy the [FTS5WrapperTokenizer](#fts5wrappertokenizer) protocol.
|
||||
Since tokenization is hard, and pointers to byte buffers difficult to deal with, you may enjoy the [FTS5WrapperTokenizer](#fts5wrappertokenizer) protocol.
|
||||
|
||||
|
||||
## FTS5WrapperTokenizer
|
||||
|
||||
**FTS5WrapperTokenizer** is the high-level protocol for your custom tokenizers. It provides a default implementation for the low-level `tokenize(context:tokenization:pText:nText:tokenCallback:)` method, so that the adopting type does not have to deal with raw byte buffers of the raw [FTS5 C API](https://www.sqlite.org/fts5.html#custom_tokenizers).
|
||||
|
||||
A FTS5WrapperTokenizer lets the hard tokenization job to another tokenizer, the "wrapped tokenizer", and post-processes the tokens produced by this wrapped tokenizer.
|
||||
An FTS5WrapperTokenizer leaves the hard tokenization job to another tokenizer, the "wrapped tokenizer", and post-processes the tokens produced by this wrapped tokenizer.
|
||||
|
||||
```swift
|
||||
protocol FTS5WrapperTokenizer : FTS5CustomTokenizer {
|
||||
@@ -195,7 +195,7 @@ protocol FTS5WrapperTokenizer : FTS5CustomTokenizer {
|
||||
}
|
||||
```
|
||||
|
||||
As all custom tokenizers, wrapper tokenizers must have a name:
|
||||
Like all custom tokenizers, wrapper tokenizers must have a name:
|
||||
|
||||
```swift
|
||||
final class MyTokenizer : FTS5WrapperTokenizer {
|
||||
@@ -236,11 +236,11 @@ final class MyTokenizer : FTS5WrapperTokenizer {
|
||||
|
||||
The token argument is a token produced by the wrapped tokenizer, ready to be ignored, modified, or multiplied into several [synonyms](#example-synonyms).
|
||||
|
||||
The tokenization parameter tells the reason why tokens are produced, if FTS5 is tokenizing a document, or a search pattern. Some tokenizers may produce different tokens depending on this parameter.
|
||||
The tokenization parameter tells the reason why tokens are produced: whether FTS5 is tokenizing a document, or a search pattern. Some tokenizers may produce different tokens depending on this parameter.
|
||||
|
||||
Finally, the tokenCallback is a function you call to output a custom token.
|
||||
|
||||
There are a two rules to observe when implementing the accept method:
|
||||
There are two rules to observe when implementing the accept method:
|
||||
|
||||
1. Errors thrown by the tokenCallback function must not be caught (they notify that FTS5 requires the tokenization process to stop immediately).
|
||||
2. The flags parameter should be given unmodified to the tokenCallback function along with the custom token, unless you union it with the `.colocated` flag when the tokenizer produces [synonyms](#example-synonyms).
|
||||
@@ -300,9 +300,9 @@ try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
|
||||
The topic of synonyms is documented at https://www.sqlite.org/fts5.html#synonym_support, which describes several methods. You should carefully read this documentation, and pick the method you prefer.
|
||||
|
||||
In the example below, we'll pick method (3), and implement a tokenizer that adds multiple synonyms for a single term to the FTS index. Using this method, when tokenizing document text, the tokenizer provides multiple synonyms for each token. So that when a document such as "I won first place" is tokenized, entries are added to the FTS index for "i", "won", "first", "1st" and "place".
|
||||
In the example below, we'll pick method (3), and implement a tokenizer that adds multiple synonyms for a single term to the FTS index. Using this method, when tokenizing document text, the tokenizer provides multiple synonyms for each token. So when a document such as "I won first place" is tokenized, entries are added to the FTS index for "i", "won", "first", "1st" and "place".
|
||||
|
||||
We'll also take care of the SQLite advice:
|
||||
We'll also follow the SQLite advice:
|
||||
|
||||
> When using methods (2) or (3), it is important that the tokenizer only provide synonyms when tokenizing document text or query text, not both. Doing so will not cause any errors, but is inefficient.
|
||||
|
||||
@@ -350,11 +350,11 @@ Languages that use the [latin script](https://en.wikipedia.org/wiki/Latin_script
|
||||
|
||||
Full-text search in such a corpus often needs input tolerance, so that "encyclopaedia" can match "Encyclopædia", "Grossmann", "Großmann", and "Jerome", "Jérôme".
|
||||
|
||||
German has something specific in that both "Mueller" and "Muller" should match "Müller", when "Bauer" should not match "Baur" (only "ü" accepts both "u" and "ue"). A pull request that adds a chapter about German will be welcome.
|
||||
German has something specific in that both "Mueller" and "Muller" should match "Müller", while "Bauer" should not match "Baur" (only "ü" accepts both "u" and "ue"). A pull request that adds a chapter about German will be welcome.
|
||||
|
||||
A custom FTS5 tokenizer lets you provide fuzzy latin matching: after "Grossmann", "Großmann", and "GROSSMANN" have all been turned into "grossmann", they will all match together.
|
||||
|
||||
We'll wrap the built-in [unicode61](https://www.sqlite.org/fts5.html#unicode61_tokenizer) tokenizer (the one that knows how to split text on spaces and punctuations), and transform its tokens into their bare lowercase ascii form.
|
||||
We'll wrap the built-in [unicode61](https://www.sqlite.org/fts5.html#unicode61_tokenizer) tokenizer (the one that knows how to split text on spaces and punctuation), and transform its tokens into their bare lowercase ascii form.
|
||||
|
||||
The tokenizer wrapping is provided by the [FTS5WrapperTokenizer](#fts5wrappertokenizer) protocol. The string transformation is provided by the [String.applyingTransform](https://developer.apple.com/reference/swift/string/1643133-applyingtransform) method:
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this do
|
||||
|
||||
For a full feature list, read the SQLite documentation. Some missing features can be achieved with extra application code.
|
||||
|
||||
- **The speed versus disk space constraints.** Roughly speaking, FTS4 and FTS5 are faster than FTS3, but use more space. FTS4 only supports content compression.
|
||||
- **The speed versus disk space constraints.** Roughly speaking, FTS4 and FTS5 are faster than FTS3, but use more space. Only FTS4 supports content compression.
|
||||
|
||||
- **The location of the indexed text in your database schema.** Only FTS4 and FTS5 support "contentless" and "external content" tables.
|
||||
|
||||
@@ -148,7 +148,7 @@ try db.create(virtualTable: "document", using: FTS4()) { t in
|
||||
}
|
||||
```
|
||||
|
||||
The `content` option is involved in "contentless" and "external content" full-text tables. GRDB can help you defining full-text tables that automatically synchronize with their content table. See [External Content Full-Text Tables](#external-content-full-text-tables).
|
||||
The `content` option is involved in "contentless" and "external content" full-text tables. GRDB can help you define full-text tables that automatically synchronize with their content table. See [External Content Full-Text Tables](#external-content-full-text-tables).
|
||||
|
||||
|
||||
See [SQLite documentation](https://www.sqlite.org/fts3.html) for more information.
|
||||
@@ -254,7 +254,7 @@ FTS3.tokenize("Gustave Doré", withTokenizer: .unicode61()) // ["gustave", "dore
|
||||
|
||||
**Not all search patterns are valid**: they must follow the [Full-Text Index Queries Grammar](https://www.sqlite.org/fts3.html#full_text_index_queries).
|
||||
|
||||
The FTS3Pattern type helps you validating patterns, and building valid patterns from untrusted strings (such as strings typed by users):
|
||||
The FTS3Pattern type helps you validate patterns, and build valid patterns from untrusted strings (such as strings typed by users):
|
||||
|
||||
```swift
|
||||
struct FTS3Pattern {
|
||||
@@ -301,7 +301,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](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
|
||||
FTS3Pattern instances are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -316,7 +316,7 @@ Use them in the [query interface](../README.md#the-query-interface):
|
||||
let documents = try Document.matching(pattern).fetchAll(db)
|
||||
|
||||
// Search in a specific column:
|
||||
let documents = try Document.filter(Column("content").match(pattern)).fetchAll(db)
|
||||
let documents = try Document.filter { $0.content.match(pattern) }.fetchAll(db)
|
||||
```
|
||||
|
||||
|
||||
@@ -377,7 +377,7 @@ try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
}
|
||||
```
|
||||
|
||||
The `content` and `contentRowID` options are involved in "contentless" and "external content" full-text tables. GRDB can help you defining full-text tables that automatically synchronize with their content table. See [External Content Full-Text Tables](#external-content-full-text-tables).
|
||||
The `content` and `contentRowID` options are involved in "contentless" and "external content" full-text tables. GRDB can help you define full-text tables that automatically synchronize with their content table. See [External Content Full-Text Tables](#external-content-full-text-tables).
|
||||
|
||||
See [SQLite documentation](https://www.sqlite.org/fts5.html) for more information.
|
||||
|
||||
@@ -493,7 +493,7 @@ See the `FTS5_TOKEN_*` flags in https://www.sqlite.org/fts5.html#custom_tokenize
|
||||
|
||||
**Not all search patterns are valid**: they must follow the [Full-Text Query Syntax](https://www.sqlite.org/fts5.html#full_text_query_syntax).
|
||||
|
||||
The FTS5Pattern type helps you validating patterns, and building valid patterns from untrusted strings (such as strings typed by users):
|
||||
The FTS5Pattern type helps you validate patterns, and build valid patterns from untrusted strings (such as strings typed by users):
|
||||
|
||||
```swift
|
||||
extension Database {
|
||||
@@ -550,7 +550,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](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
|
||||
FTS5Pattern instances are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -565,7 +565,7 @@ Use them in the [query interface](../README.md#the-query-interface):
|
||||
let documents = try Document.matching(pattern).fetchAll(db)
|
||||
|
||||
// Search in a specific column:
|
||||
let documents = try Document.filter(Column("content").match(pattern)).fetchAll(db)
|
||||
let documents = try Document.filter { $0.content.match(pattern) }.fetchAll(db)
|
||||
```
|
||||
|
||||
|
||||
@@ -583,7 +583,7 @@ let documents = try Document.fetchAll(db,
|
||||
let documents = try Document.matching(pattern).order(Column.rank).fetchAll(db)
|
||||
```
|
||||
|
||||
For more information about the ranking algorithm, as well as extra options, read [Sorting by Auxiliary Function Results](https://www.sqlite.org/fts5.html#sorting_by_auxiliary_function_results)
|
||||
For more information about the ranking algorithm, as well as extra options, read [Sorting by Auxiliary Function Results](https://www.sqlite.org/fts5.html#sorting_by_auxiliary_function_results).
|
||||
|
||||
GRDB does not provide any ranking for FTS3 and FTS4. See SQLite's [Search Application Tips](https://www.sqlite.org/fts3.html#appendix_a) if you really need it.
|
||||
|
||||
@@ -592,7 +592,7 @@ GRDB does not provide any ranking for FTS3 and FTS4. See SQLite's [Search Applic
|
||||
|
||||
**An external content table does not store the indexed text.** Instead, it indexes the text stored in another table.
|
||||
|
||||
This is very handy when you want to index a table that can not be declared as a full-text table (because it contains non-textual values, for example). You just have to define an external content full-text table that refers to the regular table.
|
||||
This is very handy when you want to index a table that cannot be declared as a full-text table (because it contains non-textual values, for example). You just have to define an external content full-text table that refers to the regular table.
|
||||
|
||||
The two tables must be kept up-to-date, so that the full-text index matches the content of the regular table. This synchronization happens automatically if you use the `synchronize(withTable:)` method in your full-text table definition:
|
||||
|
||||
@@ -614,7 +614,7 @@ try db.create(virtualTable: "book_ft", using: FTS4()) { t in // or FTS5()
|
||||
}
|
||||
```
|
||||
|
||||
The eventual content already present in the regular table is indexed, and every insert, update or delete that happens in the regular table is automatically applied to the full-text index.
|
||||
Any content already present in the regular table is indexed, and every insert, update or delete that happens in the regular table is automatically applied to the full-text index.
|
||||
|
||||
For more information, see the SQLite documentation about external content tables: [FTS4](https://www.sqlite.org/fts3.html#_external_content_fts4_tables_), [FTS5](https://sqlite.org/fts5.html#external_content_tables).
|
||||
|
||||
@@ -623,11 +623,11 @@ See also [WWDC Companion](https://github.com/groue/WWDCCompanion), a sample app
|
||||
|
||||
### Deleting Synchronized Full-Text Tables
|
||||
|
||||
Synchronization of full-text tables with their content table happens by the mean of SQL triggers.
|
||||
Synchronization of full-text tables with their content table happens by means of SQL triggers.
|
||||
|
||||
SQLite automatically deletes those triggers when the content (not full-text) table is dropped.
|
||||
|
||||
However, those triggers remain after the full-text table has been dropped. Unless they are dropped too, they will prevent future insertion, updates, and deletions in the content table, and the creation of a new full-text table.
|
||||
However, those triggers remain after the full-text table has been dropped. Unless they are dropped too, they will prevent future insertions, updates, and deletions in the content table, and the creation of a new full-text table.
|
||||
|
||||
To drop those triggers, use the `dropFTS4SynchronizationTriggers` or `dropFTS5SynchronizationTriggers` methods:
|
||||
|
||||
@@ -661,7 +661,7 @@ try db.dropFTS4SynchronizationTriggers(forTable: "book_ft")
|
||||
|
||||
When you need to perform a full-text search, and the external content table contains all the data you need, you can simply query the full-text table.
|
||||
|
||||
But if you need to load columns from the regular table, and in the same time perform a full-text search, then you will need to query both tables at the same time.
|
||||
But if you need to load columns from the regular table, and also perform a full-text search, then you will need to query both tables at the same time.
|
||||
|
||||
That is because SQLite will throw an error when you try to perform a full-text search on a regular table:
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
Migrating From GRDB 4 to GRDB 5
|
||||
===============================
|
||||
|
||||
**This guide aims at helping you upgrading your applications from GRDB 4 to GRDB 5.**
|
||||
**This guide aims at helping you upgrade your applications from GRDB 4 to GRDB 5.**
|
||||
|
||||
- [Preparing the Migration to GRDB 5](#preparing-the-migration-to-grdb-5)
|
||||
- [New requirements](#new-requirements)
|
||||
@@ -63,9 +63,9 @@ let dbQueue = try DatabaseQueue(dbPath, configuration: config)
|
||||
|
||||
## ValueObservation
|
||||
|
||||
[ValueObservation] is the database observation tool that tracks changes in database values. It has quite changed in GRDB 5.
|
||||
[ValueObservation] is the database observation tool that tracks changes in database values. It has changed quite a bit in GRDB 5.
|
||||
|
||||
Those changes have the vanilla GRDB, its [Combine publishers], and [RxGRDB] offer a common API, and a common behavior. This greatly helps choosing or switching your preferred database observation technique. In previous versions of GRDB, the three companion libraries used to have subtle differences that were just opportunities for bugs.
|
||||
Those changes make the vanilla GRDB, its [Combine publishers], and [RxGRDB] offer a common API, and a common behavior. This greatly helps choose or switch your preferred database observation technique. In previous versions of GRDB, the three companion libraries used to have subtle differences that were just opportunities for bugs.
|
||||
|
||||
In the end, this migration step might require some work. But it's for the benefit of all!
|
||||
|
||||
@@ -111,7 +111,7 @@ let observation = ValueObservation.tracking(someFetchFunction)
|
||||
let observation = ValueObservation.tracking { db in ... }
|
||||
```
|
||||
|
||||
Finally, ValueObservation used to let application define custom "reducers" based on a protocol name ValueReducer, which was removed in GRDB 5. See the [#731](https://github.com/groue/GRDB.swift/pull/731) conversation for a solution towards a replacement.
|
||||
Finally, ValueObservation used to let applications define custom "reducers" based on a protocol named ValueReducer, which was removed in GRDB 5. See the [#731](https://github.com/groue/GRDB.swift/pull/731) conversation for a solution towards a replacement.
|
||||
|
||||
<details>
|
||||
<summary>RxGRDB impact</summary>
|
||||
@@ -181,13 +181,13 @@ let cancellable = observation.start(
|
||||
|
||||
**The behavior of ValueObservation has changed**.
|
||||
|
||||
The changes can quite impact your application. We'll describe them below, as well as the strategies to restore the previous behavior when needed.
|
||||
The changes can have quite an impact on your application. We'll describe them below, as well as the strategies to restore the previous behavior when needed.
|
||||
|
||||
1. ValueObservation used to notify its initial value *immediately* when the observation starts. Now, it notifies fresh values on the main thread, *asynchronously*, by default.
|
||||
|
||||
This means that the parts of your application that rely on this immediate value to, say, set up their user interface, have to be modified. Otherwise, they may suffer from a brief flash of missing data, during the short amount of time between the beginning of the observation, and the asynchronous delivery of the initial value.
|
||||
|
||||
To be granted with an immediate, synchronous, delivery of the initial value, insert a `scheduling: .immediate` argument in the `start` method:
|
||||
To get an immediate, synchronous, delivery of the initial value, insert a `scheduling: .immediate` argument in the `start` method:
|
||||
|
||||
```swift
|
||||
let observation = ValueObservation.tracking(Player.fetchAll)
|
||||
@@ -273,7 +273,7 @@ The changes can quite impact your application. We'll describe them below, as wel
|
||||
observation.start(in: dbQueue, scheduling: .async(onQueue: queue), onError: ..., onChange: ...)
|
||||
```
|
||||
|
||||
The GRDB 4 `startImmediately` parameter is no longer supported: ValueObservation now always emits an initial value, without waiting for eventual changes. It is up to your application to ignore this initial value if it wants to.
|
||||
The GRDB 4 `startImmediately` parameter is no longer supported: ValueObservation now always emits an initial value, without waiting for changes. It is up to your application to ignore this initial value if it wants to.
|
||||
|
||||
|
||||
### Removed ValueObservation Methods
|
||||
@@ -319,7 +319,7 @@ The changes can quite impact your application. We'll describe them below, as wel
|
||||
}
|
||||
```
|
||||
|
||||
As is previous versions of GRDB, do not use the `combineLatest` operators of Combine or RxSwift in order to combine several ValueObservation. You would lose all guarantees of [data consistency](https://en.wikipedia.org/wiki/Consistency_(database_systems)).
|
||||
As in previous versions of GRDB, do not use the `combineLatest` operators of Combine or RxSwift in order to combine several ValueObservation instances. You would lose all guarantees of [data consistency](https://en.wikipedia.org/wiki/Consistency_(database_systems)).
|
||||
|
||||
|
||||
## Combine Integration
|
||||
@@ -344,7 +344,7 @@ let publisher = observation
|
||||
|
||||
## Other Changes
|
||||
|
||||
1. The `Configuration.trace` property has been removed. You know use the `Database.trace(options:_:)` method instead:
|
||||
1. The `Configuration.trace` property has been removed. You now use the `Database.trace(options:_:)` method instead:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
@@ -360,7 +360,7 @@ let publisher = observation
|
||||
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
|
||||
```
|
||||
|
||||
2. [Batch updates] used to rely of the `<-` operator. This operator has been removed. Use the `set(to:)` method instead:
|
||||
2. [Batch updates] used to rely on the `<-` operator. This operator has been removed. Use the `set(to:)` method instead:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
@@ -372,7 +372,7 @@ let publisher = observation
|
||||
|
||||
> :question: This change avoids conflicts with other libraries that define the same operator.
|
||||
|
||||
3. [SQL Interpolation] does no longer wrap subqueries in parenthesis:
|
||||
3. [SQL Interpolation] no longer wraps subqueries in parentheses:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
@@ -382,12 +382,12 @@ let publisher = observation
|
||||
// NEW: GRDB 5
|
||||
let maximumScore: SQLRequest<Int> = "SELECT MAX(score) FROM player"
|
||||
let bestPlayers: SQLRequest<Player> = "SELECT * FROM player WHERE score = (\(maximumScore))"
|
||||
// extra parenthesis required: ^ ^
|
||||
// extra parentheses required: ^ ^
|
||||
```
|
||||
|
||||
> :question: This change makes it possible to concatenate subqueries with the UNION operator.
|
||||
|
||||
4. In order to extract raw SQL string from an [SQL literal], you now need a database connection:
|
||||
4. In order to extract the raw SQL string from an [SQL literal], you now need a database connection:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
@@ -404,7 +404,7 @@ let publisher = observation
|
||||
print(arguments) // prints ["O'Brien", 42]
|
||||
```
|
||||
|
||||
5. In order to extract raw SQL string from a request ([SQLRequest] or [QueryInterfaceRequest]), you now need to call the `makePreparedRequest()` method:
|
||||
5. In order to extract the raw SQL string from a request ([SQLRequest] or [QueryInterfaceRequest]), you now need to call the `makePreparedRequest()` method:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
@@ -460,7 +460,7 @@ let publisher = observation
|
||||
import GRDB
|
||||
```
|
||||
|
||||
10. Importing the `GRDB` module grants access to the [SQLite C interface](https://www.sqlite.org/c3ref/intro.html). You don't need any longer to import the underlying SQLite library:
|
||||
10. Importing the `GRDB` module grants access to the [SQLite C interface](https://www.sqlite.org/c3ref/intro.html). You no longer need to import the underlying SQLite library:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
Migrating From GRDB 5 to GRDB 6
|
||||
===============================
|
||||
|
||||
**This guide aims at helping you upgrading your applications from GRDB 5 to GRDB 6.**
|
||||
**This guide aims at helping you upgrade your applications from GRDB 5 to GRDB 6.**
|
||||
|
||||
- [Preparing the Migration to GRDB 6](#preparing-the-migration-to-grdb-6)
|
||||
- [New requirements](#new-requirements)
|
||||
@@ -24,7 +24,7 @@ GRDB requirements have been bumped:
|
||||
- **Xcode 14.0+** (was Xcode 12.0+)
|
||||
- iOS 11.0+ (unchanged)
|
||||
- **macOS 10.13+** (was macOS 10.10+)
|
||||
- **tvOS 11.0+** (was tvOS 11.0+)
|
||||
- **tvOS 11.0+** (was tvOS 9.0+)
|
||||
- **watchOS 4.0+** (was watchOS 2.0+)
|
||||
- **SQLite 3.19.3+** (was SQLite 3.8.5+)
|
||||
|
||||
@@ -154,7 +154,7 @@ The record protocols have been refactored. We tried to keep the amount of modifi
|
||||
}
|
||||
```
|
||||
|
||||
If you subclass the `Record` class, you have to call `super` at some point of your implementation:
|
||||
If you subclass the `Record` class, you have to call `super` at some point in your implementation:
|
||||
|
||||
```diff
|
||||
class Player: Record {
|
||||
@@ -242,7 +242,7 @@ The record protocols have been refactored. We tried to keep the amount of modifi
|
||||
try link.upsert(db) // Calls the willSave callback
|
||||
```
|
||||
|
||||
If you subclass the `Record` class, you have to call `super` at some point of your implementation:
|
||||
If you subclass the `Record` class, you have to call `super` at some point in your implementation:
|
||||
|
||||
```swift
|
||||
// GRDB 6
|
||||
@@ -283,7 +283,7 @@ The record protocols have been refactored. We tried to keep the amount of modifi
|
||||
// How to detect failed `INSERT OR IGNORE`:
|
||||
// INSERT OR IGNORE INTO player ... RETURNING *
|
||||
if let insertedPlayer = try player.insertAndFetch(db) {
|
||||
// Succesful insertion
|
||||
// Successful insertion
|
||||
} else {
|
||||
// Ignored failure
|
||||
}
|
||||
@@ -317,7 +317,7 @@ The record protocols have been refactored. We tried to keep the amount of modifi
|
||||
|
||||
- The `Record.copy()` method was removed, without replacement.
|
||||
|
||||
- The `DerivableRequest.limit(_:offset_:)` method was removed, without replacement.
|
||||
- The `DerivableRequest.limit(_:offset:)` method was removed, without replacement.
|
||||
|
||||
You can still limit `QueryInterfaceRequest`, but associations can no longer be limited:
|
||||
|
||||
@@ -371,7 +371,7 @@ The record protocols have been refactored. We tried to keep the amount of modifi
|
||||
```diff
|
||||
-db.afterNextTransactionCommit { db in
|
||||
+db.afterNextTransaction { db in
|
||||
print("Succesful commit")
|
||||
print("Successful commit")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ Before upgrading, ensure you are using the [latest GRDB 6 release](https://githu
|
||||
|
||||
GRDB 7 requires Xcode 16+ and a Swift 6 compiler.
|
||||
|
||||
Depending of the language mode and level of concurrency checkings used by your application, you may see warnings or errors. See [Migrating to Swift 6] on swift.org for more information about Swift 6. See [Swift Concurrency and GRDB] for GRDB-focused advice.
|
||||
Depending on the language mode and level of concurrency checking used by your application, you may see warnings or errors. See [Migrating to Swift 6] on swift.org for more information about Swift 6. See [Swift Concurrency and GRDB] for GRDB-focused advice.
|
||||
|
||||
## New requirements
|
||||
|
||||
@@ -79,7 +79,7 @@ In GRDB 6, asynchronous database accesses such as `try await read { ... }` or `t
|
||||
|
||||
In GRDB 7, asynchronous database accesses respect Task cancellation. If a Task is cancelled, reads and writes throw a `CancellationError`, pending transactions are rolled back, and the database is not modified. The only SQL statement that can execute in a cancelled database access is `ROLLBACK`.
|
||||
|
||||
The effect of this change on your application depends on how it uses tasks. For example, take care of database jobs initiated frop the [`task`](https://developer.apple.com/documentation/swiftui/view/task(priority:_:)) SwiftUI modifier.
|
||||
The effect of this change on your application depends on how it uses tasks. For example, take care of database jobs initiated from the [`task`](https://developer.apple.com/documentation/swiftui/view/task(priority:_:)) SwiftUI modifier.
|
||||
|
||||
If you want an asynchronous database access to always complete, regardless of Task cancellation, wrap it in an unstructured Task:
|
||||
|
||||
@@ -95,7 +95,7 @@ let task = Task {
|
||||
try await task.value
|
||||
```
|
||||
|
||||
Other asynchronous database accesses, such as methods accepting a completion blocks (`asyncRead`, etc.), Combine publishers, RxSwift observables, do not handle cancellation and will proceed to completion by default.
|
||||
Other asynchronous database accesses, such as methods accepting a completion block (`asyncRead`, etc.), Combine publishers, RxSwift observables, do not handle cancellation and will proceed to completion by default.
|
||||
|
||||
## Associations to record types named Bias, Focus, Gas, and Lens
|
||||
|
||||
@@ -160,9 +160,9 @@ You can still specify a transaction kind explicitly when necessary. See [Transac
|
||||
|
||||
## ValueObservation and the Main Actor
|
||||
|
||||
In GRDB 7, `ValueObservation` fosters the main actor, because it is frequently used to automatically update database values on screen.
|
||||
In GRDB 7, `ValueObservation` favors the main actor, because it is frequently used to automatically update database values on screen.
|
||||
|
||||
By default, its [`start`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/start(in:scheduling:onerror:onchange:)) method must be started on the main actor, and its notification callbacks run on the main actor as well.
|
||||
By default, its [`start`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/start(in:scheduling:onerror:onchange:)) method must be called on the main actor, and its notification callbacks run on the main actor as well.
|
||||
|
||||
It is not necessary to call `MainActor.assumeIsolated` in `ValueObservation` callbacks:
|
||||
|
||||
@@ -235,9 +235,9 @@ In GRDB 7, you may need an additional import, depending on how GRDB is integrate
|
||||
|
||||
Subclassing the [Record] class is **discouraged** in GRDB 7. Present in GRDB 1.0, in 2017, it has served its purpose.
|
||||
|
||||
It is not recommended to define any new type that subclass `Record`.
|
||||
It is not recommended to define any new type that subclasses `Record`.
|
||||
|
||||
It is recommended to refactor `Record` subclasses into Swift structs, before you enable the strict concurrency checkings or the Swift 6 language mode. See [Migrating to Swift 6] for more information about Swift 6 language modes.
|
||||
It is recommended to refactor `Record` subclasses into Swift structs, before you enable the strict concurrency checking or the Swift 6 language mode. See [Migrating to Swift 6] for more information about Swift 6 language modes.
|
||||
|
||||
For example:
|
||||
|
||||
@@ -273,7 +273,7 @@ Do not miss [Swift Concurrency and GRDB], for more recommendations regarding non
|
||||
|
||||
- The `PersistenceContainer` subscript no longer guarantees that the value returned is the same as what was previously set. It only guarantees that both values are encoded identically in the database.
|
||||
|
||||
- The async sequence returned by [`ValueObservation.values`](https://swiftpackageindex.com/groue/GRDB.swiftdocumentation/grdb/valueobservation/values(in:scheduling:bufferingpolicy:)) now iterates on the cooperative thread pool by default. Use .mainActor as the scheduler if you need the previous behavior.
|
||||
- The async sequence returned by [`ValueObservation.values`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/values(in:scheduling:bufferingpolicy:)) now iterates on the cooperative thread pool by default. Use .mainActor as the scheduler if you need the previous behavior.
|
||||
|
||||
[Migrating to Swift 6]: https://www.swift.org/migration/documentation/migrationguide
|
||||
[Sharing a Database]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesharing
|
||||
|
||||
@@ -32,14 +32,14 @@ try dbQueue.inDatabase { db in
|
||||
CREATE TABLE place (
|
||||
id INTEGER PRIMARY KEY,
|
||||
title TEXT,
|
||||
favorite BOOLEAN NOT NULL,
|
||||
isFavorite BOOLEAN NOT NULL,
|
||||
latitude DOUBLE NOT NULL,
|
||||
longitude DOUBLE NOT NULL
|
||||
)
|
||||
""")
|
||||
|
||||
try db.execute(sql: """
|
||||
INSERT INTO place (title, favorite, latitude, longitude)
|
||||
INSERT INTO place (title, isFavorite, latitude, longitude)
|
||||
VALUES (?, ?, ?, ?)
|
||||
""", arguments: ["Paris", true, 48.85341, 2.3488])
|
||||
let parisId = db.lastInsertedRowID
|
||||
@@ -52,11 +52,11 @@ try! dbQueue.inDatabase { db in
|
||||
let rows = try Row.fetchCursor(db, sql: "SELECT * FROM place")
|
||||
while let row = try rows.next() {
|
||||
let title: String = row["title"]
|
||||
let favorite: Bool = row["favorite"]
|
||||
let isFavorite: Bool = row["isFavorite"]
|
||||
let coordinate = CLLocationCoordinate2D(
|
||||
latitude: row["latitude"],
|
||||
longitude: row["longitude"])
|
||||
print("Fetched", title, favorite, coordinate)
|
||||
print("Fetched", title, isFavorite, coordinate)
|
||||
}
|
||||
|
||||
let placeCount = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM place")! // Int
|
||||
@@ -69,35 +69,43 @@ try! dbQueue.inDatabase { db in
|
||||
struct Place {
|
||||
var id: Int64?
|
||||
var title: String?
|
||||
var favorite: Bool
|
||||
var isFavorite: Bool
|
||||
var coordinate: CLLocationCoordinate2D
|
||||
}
|
||||
|
||||
// Adopt FetchableRecord
|
||||
extension Place : FetchableRecord {
|
||||
init(row: Row) {
|
||||
id = row["id"]
|
||||
title = row["title"]
|
||||
favorite = row["favorite"]
|
||||
id = row[Columns.id]
|
||||
title = row[Columns.title]
|
||||
isFavorite = row[Columns.isFavorite]
|
||||
coordinate = CLLocationCoordinate2DMake(
|
||||
row["latitude"],
|
||||
row["longitude"])
|
||||
row[Columns.latitude],
|
||||
row[Columns.longitude])
|
||||
}
|
||||
}
|
||||
|
||||
// Adopt TableRecord
|
||||
extension Place : TableRecord {
|
||||
static let databaseTableName = "place"
|
||||
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
static let title = Column("title")
|
||||
static let isFavorite = Column("isFavorite")
|
||||
static let latitude = Column("latitude")
|
||||
static let longitude = Column("longitude")
|
||||
}
|
||||
}
|
||||
|
||||
// Adopt MutablePersistableRecord
|
||||
extension Place : MutablePersistableRecord {
|
||||
func encode(to container: inout PersistenceContainer) throws {
|
||||
container["id"] = id
|
||||
container["title"] = title
|
||||
container["favorite"] = favorite
|
||||
container["latitude"] = coordinate.latitude
|
||||
container["longitude"] = coordinate.longitude
|
||||
container[Columns.id] = id
|
||||
container[Columns.title] = title
|
||||
container[Columns.isFavorite] = isFavorite
|
||||
container[Columns.latitude] = coordinate.latitude
|
||||
container[Columns.longitude] = coordinate.longitude
|
||||
}
|
||||
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
@@ -109,13 +117,13 @@ try dbQueue.inDatabase { db in
|
||||
var berlin = Place(
|
||||
id: nil,
|
||||
title: "Berlin",
|
||||
favorite: false,
|
||||
isFavorite: false,
|
||||
coordinate: CLLocationCoordinate2DMake(52.52437, 13.41053))
|
||||
|
||||
try berlin.insert(db)
|
||||
berlin.id // some value
|
||||
|
||||
berlin.favorite = true
|
||||
berlin.isFavorite = true
|
||||
try berlin.update(db)
|
||||
|
||||
// Fetch from SQL
|
||||
@@ -124,13 +132,10 @@ try dbQueue.inDatabase { db in
|
||||
|
||||
//: Avoid SQL with the query interface:
|
||||
|
||||
let title = Column("title")
|
||||
let favorite = Column("favorite")
|
||||
|
||||
berlin = try Place.filter(title == "Berlin").fetchOne(db)! // Place
|
||||
berlin = try Place.filter { $0.title == "Berlin" }.fetchOne(db)! // Place
|
||||
let paris = try Place.fetchOne(db, key: 1) // Place?
|
||||
let favoritePlaces = try Place // [Place]
|
||||
.filter(favorite == true)
|
||||
.order(title)
|
||||
.filter { $0.isFavorite == true }
|
||||
.order { $0.title }
|
||||
.fetchAll(db)
|
||||
}
|
||||
@@ -3,7 +3,7 @@ Query Interface Organization
|
||||
|
||||
**The [query interface] is a Swift API that approximates the [SQLite SELECT query grammar](https://sqlite.org/lang_select.html) through a hierarchy of values and protocols.**
|
||||
|
||||
This document exposes its inner organization, so that you can leverage the most of those types and protocols when you want it.
|
||||
This document describes its inner organization, so that you can make the most of those types and protocols when you want it.
|
||||
|
||||
In the diagram below, protocols are pale blue and have rounded corners, and standard types are grey rectangles. Solid arrows read "inherits from", and dashed arrows read "produces". Generic types are marked as such, as well as "PATs" (protocols with associated types).
|
||||
|
||||
@@ -93,7 +93,7 @@ Columns are special expressions that allow some optimizations and niceties:
|
||||
ValueObservation.tracking { db in
|
||||
try Player.fetchOne(db, id: 1)
|
||||
// or
|
||||
try Player.filter(Column("id") == 1).fetchOne(db)
|
||||
try Player.filter { $0.id == 1 }.fetchOne(db)
|
||||
}
|
||||
|
||||
// Non-optimized observations
|
||||
@@ -110,7 +110,7 @@ Columns are special expressions that allow some optimizations and niceties:
|
||||
// Nicer SQL
|
||||
// SELECT * FROM player WHERE id = 1
|
||||
try Player.fetchOne(db, id: 1)
|
||||
try Player.filter(Column("id") == 1).fetchOne(db)
|
||||
try Player.filter { $0.id == 1 }.fetchOne(db)
|
||||
|
||||
// Less nice SQL
|
||||
// SELECT * FROM player WHERE id = 1 LIMIT 1
|
||||
@@ -132,7 +132,9 @@ DatabaseRegionConvertible feeds [DatabaseRegionObservation], which tracks databa
|
||||
```swift
|
||||
let request = Player.all()
|
||||
let observation = DatabaseRegionObservation(tracking: request)
|
||||
let observer = try observation.start(in: dbQueue) { (db: Database) in
|
||||
let cancellable = observation.start(in: dbQueue) { error in
|
||||
// Handle error
|
||||
} onChange: { (db: Database) in
|
||||
print("Players were changed")
|
||||
}
|
||||
```
|
||||
@@ -261,7 +263,7 @@ The basic value types conform to [DatabaseValueConvertible] so that they can fee
|
||||
```swift
|
||||
// SELECT * FROM player WHERE name = 'O''Brien'
|
||||
// ~~~~~~~~~~
|
||||
Player.filter(Column("name") == "O'Brien")
|
||||
Player.filter { $0.name == "O'Brien" }
|
||||
```
|
||||
|
||||
### QueryInterfaceRequest
|
||||
@@ -319,10 +321,10 @@ let players: [Player] = try request.fetchAll(db)
|
||||
SQL("name = \("O'Brien")").sqlExpression
|
||||
|
||||
// SQLOrdering
|
||||
SQL("name DESC)").sqlOrdering
|
||||
SQL("name DESC").sqlOrdering
|
||||
|
||||
// SQLSelection
|
||||
SQL("score + bonus AS total)").sqlSelection
|
||||
SQL("score + bonus AS total").sqlSelection
|
||||
SQL("*").sqlSelection
|
||||
|
||||
// SQLRequest
|
||||
@@ -346,8 +348,9 @@ Functions and methods that build an SQL expression should return an SQLExpressio
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player WHERE LENGTH(name) > 0
|
||||
let expression = length(Column("name")) > 0 // SQLExpression
|
||||
Player.filter(expression)
|
||||
Player.filter {
|
||||
length($0.name) > 0 // SQLExpression
|
||||
}
|
||||
```
|
||||
|
||||
When it looks like GRDB APIs are unable to build a particular expression, use [SQL]:
|
||||
@@ -358,7 +361,7 @@ func date(_ value: SQLSpecificExpressible) -> SQLExpression {
|
||||
}
|
||||
|
||||
// SELECT * FROM player WHERE DATE(createdAt) = '2020-01-23'
|
||||
let request = Player.filter(date(Column("createdAt")) == "2020-01-23")
|
||||
let request = Player.filter { date($0.createdAt) == "2020-01-23" }
|
||||
```
|
||||
|
||||
This technique, based on [SQL Interpolation], is composable and works well even when several tables are involved. See how the `createdAt` column below is correctly attributed to the `player` table:
|
||||
@@ -368,7 +371,7 @@ This technique, based on [SQL Interpolation], is composable and works well even
|
||||
// JOIN team ON team.id = player.teamId
|
||||
// WHERE DATE(player.createdAt) = '2020-01-23'
|
||||
let request = Player
|
||||
.filter(date(Column("createdAt")) == "2020-01-23")
|
||||
.filter { date($0.createdAt) == "2020-01-23" }
|
||||
.including(required: Player.team)
|
||||
```
|
||||
|
||||
@@ -583,7 +586,7 @@ SQLSubqueryable provides the GRDB support for subqueries. Its [SQLSpecificExpres
|
||||
// SELECT * FROM player
|
||||
// WHERE score >= (SELECT AVG(score) FROM player)
|
||||
let averageScore = Player.select(average(Column("score")))
|
||||
Player.filter(Column("score") >= averageScore)
|
||||
Player.filter { $0.score >= averageScore }
|
||||
```
|
||||
|
||||
SQLSubqueryable has the `contains(_:)` and `exists()` methods that support the `value IN (subquery)` and `EXISTS (subquery)` expressions.
|
||||
|
||||
@@ -40,7 +40,7 @@ try dbQueue.write { db in
|
||||
}
|
||||
```
|
||||
|
||||
SQL interpolation looks and feel just like regular [String interpolation]:
|
||||
SQL interpolation looks and feels just like regular [String interpolation]:
|
||||
|
||||
```swift
|
||||
let name = "World"
|
||||
@@ -84,7 +84,7 @@ try dbQueue.write { db in
|
||||
}
|
||||
```
|
||||
|
||||
**`SQL` is not a Swift String.** You can not use the `execute(literal:)` method with a String argument:
|
||||
**`SQL` is not a Swift String.** You cannot use the `execute(literal:)` method with a String argument:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
@@ -131,7 +131,7 @@ let query = SQL(
|
||||
arguments: [name, id])
|
||||
```
|
||||
|
||||
`SQL` can embed any [value], as we have seen above, but not only. Please keep on reading the next chapter, or jump directly to the [SQL Interpolation Reference].
|
||||
`SQL` can embed any [value], as we have seen above, and more. Please keep on reading the next chapter, or jump directly to the [SQL Interpolation Reference].
|
||||
|
||||
|
||||
## SQL Interpolation and the Query Interface
|
||||
@@ -175,7 +175,7 @@ func date(_ expression: SQLExpressible) -> SQLExpression {
|
||||
SQL("DATE(\(expression))").sqlExpression
|
||||
}
|
||||
|
||||
let request = Player.filter(date(Column("createdAt")) == "2020-01-23")
|
||||
let request = Player.filter { date($0.createdAt) == "2020-01-23" }
|
||||
```
|
||||
|
||||
|
||||
@@ -183,7 +183,7 @@ let request = Player.filter(date(Column("createdAt")) == "2020-01-23")
|
||||
|
||||
The [record protocols] extend your application types with database abilities.
|
||||
|
||||
**A record type knows everything about the schema of its underlying database table**. With the [TableRecord] protocol, the `databaseTableName` property contains the table name. With the [Decodable] protocol, the [CodingKeys] enum contain the column names. And with [FetchableRecord], you can decode raw database rows.
|
||||
**A record type knows everything about the schema of its underlying database table**. With the [TableRecord] protocol, the `databaseTableName` property contains the table name. With the [Decodable] protocol, the [CodingKeys] enum contains the column names. And with [FetchableRecord], you can decode raw database rows.
|
||||
|
||||
SQL Interpolation puts this knowledge to good use, so that you can build robust queries that consistently use correct table and column names. Let's start from this record:
|
||||
|
||||
@@ -203,7 +203,7 @@ Let's extend Player with database methods.
|
||||
|
||||
```swift
|
||||
extension Player {
|
||||
/// Deletes all player with no score
|
||||
/// Deletes all players with no score
|
||||
static func deleteAllWithoutScore(_ db: Database) throws {
|
||||
try db.execute(literal: "DELETE FROM \(self) WHERE \(CodingKeys.score) IS NULL")
|
||||
}
|
||||
@@ -247,12 +247,12 @@ Let's extend Player with database methods.
|
||||
|
||||
```swift
|
||||
let player = try dbQueue.read { db in
|
||||
// SELECT * player WHERE id = 42
|
||||
// SELECT * FROM player WHERE id = 42
|
||||
try Player.filter(id: 42).fetchOne(db) // Player?
|
||||
}
|
||||
```
|
||||
|
||||
The return type of this method is `SQLRequest<Player>`. It is one of the GRDB [request types]. It profits from SQL interpolation, and this is why this method simply returns an "SQL literal"".
|
||||
The return type of this method is `SQLRequest<Player>`. It is one of the GRDB [request types]. It profits from SQL interpolation, and this is why this method simply returns an "SQL literal".
|
||||
|
||||
The first "simple" version only embeds the `\(id)` [value].
|
||||
|
||||
@@ -357,7 +357,7 @@ Let's extend Player with database methods.
|
||||
}
|
||||
```
|
||||
|
||||
This last request shows how to build an SQLRequest from an [SQL Literal]. You will need `SQL` when the request can not be written in a single stroke.
|
||||
This last request shows how to build an SQLRequest from an [SQL Literal]. You will need `SQL` when the request cannot be written in a single stroke.
|
||||
|
||||
|
||||
|
||||
@@ -477,7 +477,7 @@ This chapter lists all kinds of supported interpolations.
|
||||
"SELECT * FROM player WHERE \(literal: condition)"
|
||||
```
|
||||
|
||||
- Plain SQL strings and eventual arguments:
|
||||
- Plain SQL strings and optional arguments:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
Why Adopt GRDB?
|
||||
===============
|
||||
|
||||
This document aims at exposing why GRDB could become your favorite database library.
|
||||
This document aims at explaining why GRDB could become your favorite database library.
|
||||
|
||||
We'll start with a few [core principles](#core-principles), so that you see where this library aims at. Then we'll see how GRDB [solves problems](#solving-problems) that developers often face when they use database libraries such as FMDB, FCModel, SQLite.swift, Core Data, or Realm.
|
||||
We'll start with a few [core principles](#core-principles), so that you see what this library aims at. Then we'll see how GRDB [solves problems](#solving-problems) that developers often face when they use database libraries such as FMDB, FCModel, SQLite.swift, Core Data, or Realm.
|
||||
|
||||
|
||||
## Core Principles
|
||||
@@ -12,7 +12,7 @@ We'll start with a few [core principles](#core-principles), so that you see wher
|
||||
|
||||
This is because a database row is not an easy type to deal with, and will never be, compared to a regular model. `player.name` looks and feels more natural than `playerRow["name"]`, doesn't it?
|
||||
|
||||
The reputation of "active records" and ORMs has been tarnished by the recent focus on immutability, memory safety, and functional idioms that comes with languages like Swift and Rust. Features of 1st-generation records such as auto-updating, uniquing, lazy loading of relations, etc. are now considered ill-advised, if not plain harmful because of the multi-threading headaches they cause.
|
||||
The reputation of "active records" and ORMs has been tarnished by the recent focus on immutability, memory safety, and functional idioms that come with languages like Swift and Rust. Features of 1st-generation records such as auto-updating, uniquing, lazy loading of relations, etc. are now considered ill-advised, if not plain harmful because of the multi-threading headaches they cause.
|
||||
|
||||
Yet recent ORMs such as Rust's [Diesel] have shown that it is possible to build record types that behave as plain and simple values. GRDB belongs to this family.
|
||||
|
||||
@@ -24,14 +24,14 @@ Complex database queries sometimes need to be prototyped and debugged in an SQL
|
||||
|
||||
### The database file is the single source of truth.
|
||||
|
||||
Each Core Data's managed object context has its own version of the database. This can be useful when developing a macOS application full of inspector panels and nested undo stacks. But that's about it.
|
||||
Each Core Data managed object context has its own version of the database. This can be useful when developing a macOS application full of inspector panels and nested undo stacks. But that's about it.
|
||||
|
||||
In the same vein, each application thread has its own version of a Realm database, with non trivial synchronization points.
|
||||
|
||||
Conversely, GRDB assumes that many apps want to use the database as a reliable and unambiguous storage.
|
||||
|
||||
|
||||
### Applications developers have specific needs.
|
||||
### Application developers have specific needs.
|
||||
|
||||
GRDB puts all bets on SQLite, and focuses on front-end GUI applications.
|
||||
|
||||
@@ -39,9 +39,9 @@ This means that dealing with servers, MySQL, or PostgreSQL is out of scope. GRDB
|
||||
|
||||
Focusing on SQLite and applications has allowed GRDB to build features usually only found in company-sponsored libraries: migrations, record comparison, database observation, multi-threading safety, table view animations, support for reactive streams...
|
||||
|
||||
The bet of GRDB is that developers can take great profit from a library that provides efficient and community-tested solutions to existing problems. For example, one can not address the multithreading difficulties of Core Data or Realm without looking at database concurrency and records straight in the face.
|
||||
The bet of GRDB is that developers can greatly benefit from a library that provides efficient and community-tested solutions to existing problems. For example, one cannot address the multithreading difficulties of Core Data or Realm without looking at database concurrency and records straight in the face.
|
||||
|
||||
Since you don't have to take my words for granted, we'll now see how GRDB actually solves common problems that developers face with other database libraries.
|
||||
Since you don't have to take my word for it, we'll now see how GRDB actually solves common problems that developers face with other database libraries.
|
||||
|
||||
|
||||
## Solving Problems
|
||||
@@ -88,14 +88,14 @@ try place.delete(db)
|
||||
|
||||
For your convenience, those record protocols can be derived from the [Decodable and Encodable](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types) protocols of the standard library. [Codable records] are even given free support for JSON columns and other niceties.
|
||||
|
||||
Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with **database change notifications**, with many advantages.
|
||||
Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. In particular, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with **database change notifications**, with many advantages.
|
||||
|
||||
See [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices) for some practical advice.
|
||||
|
||||
|
||||
### Allow database records to cross threads
|
||||
|
||||
As soon as records are immutable values, they can safely be used from different threads. You no longer have to pass object ids or references between threads, as in Core Data or Realm:
|
||||
Since records are immutable values, they can safely be used from different threads. You no longer have to pass object ids or references between threads, as in Core Data or Realm:
|
||||
|
||||
```swift
|
||||
if let player = try Player.fetchOne(db, key: 1) {
|
||||
@@ -115,7 +115,7 @@ let player = Player(name: "arthur", score: 1000)
|
||||
let players = try Player.fetchAll(db)
|
||||
```
|
||||
|
||||
**Fetched records behave just like an in-memory cache of the database content.** Your application is free to decide, on its own, how it should handle the lifetime of those cached values: by ignoring future database changes, or by observing database changes and react accordingly.
|
||||
**Fetched records behave just like an in-memory cache of the database content.** Your application is free to decide, on its own, how it should handle the lifetime of those cached values: by ignoring future database changes, or by observing database changes and reacting accordingly.
|
||||
|
||||
In order to keep your views synchronized with the database content, you can use [ValueObservation]. It notifies fresh values after each database change, with convenient support for [Combine](Combine.md) and [RxSwift](https://github.com/RxSwiftCommunity/RxGRDB).
|
||||
|
||||
@@ -137,13 +137,13 @@ let cancellable = observation.publisher(in: dbQueue).sink(
|
||||
|
||||
// RxGRDB
|
||||
let disposable = observation.rx.observe(in: dbQueue).subscribe(
|
||||
onNext: { (players: [Player]) in print("Fresh playerss") },
|
||||
onNext: { (players: [Player]) in print("Fresh players") },
|
||||
onError: { error in ... })
|
||||
```
|
||||
|
||||
No matter which observation technique you use, you have common guarantees:
|
||||
|
||||
First, notifications only come from database changes safely saved on disk. This is part of the "database as the single source of truth" core principle. You won't get notifications from unsaved changes or changes that have an opportunity to be rollbacked.
|
||||
First, notifications only come from database changes safely saved on disk. This is part of the "database as the single source of truth" core principle. You won't get notifications from unsaved changes or changes that have an opportunity to be rolled back.
|
||||
|
||||
Next, you choose the dispatch queue on which notifications happen (generally the main queue, by default, as in the examples above). GRDB makes sure notifications happen in the same order as database transactions.
|
||||
|
||||
@@ -184,7 +184,7 @@ The more threats are handled by the application, the more skilled and careful a
|
||||
|
||||
I had to omit [Realm] and [FCModel] from the list, because I don't know them well enough. Yet I'd bet that Realm shares some behaviors with Core Data, and FCModel shares some behaviors with FMDatabaseQueue.
|
||||
|
||||
We can see that the threat of conflicts is *always* left to the application. Core Data provides conflict policies, but no one can pretend that they are easy to plan, use, or test. This is an argument for leaving the application 100% responsible for conflict handling, in hope that simple ones can be handled in a simple way.
|
||||
We can see that the threat of conflicts is *always* left to the application. Core Data provides conflict policies, but no one can claim that they are easy to plan, use, or test. This is an argument for leaving the application 100% responsible for conflict handling, in the hope that simple ones can be handled in a simple way.
|
||||
|
||||
Finally, raw FMDatabase, SQLite.swift, and Core Data are the hardest tools, and you'd better be a very skilled developer in order to use them properly.
|
||||
|
||||
@@ -207,13 +207,13 @@ try player.updateChanges {
|
||||
|
||||
// SELECT * FROM player ORDER BY score DESC LIMIT 10
|
||||
let bestPlayers: [Player] = try Player
|
||||
.order(scoreColumn.desc)
|
||||
.order(\.score.desc)
|
||||
.limit(10)
|
||||
.fetchAll(db)
|
||||
|
||||
// SELECT MAX(score) FROM player
|
||||
let maximumScore: Int? = try Player
|
||||
.select(max(scoreColumn))
|
||||
.select { max($0.score) }
|
||||
.asRequestOf(Int.self)
|
||||
.fetchOne(db)
|
||||
|
||||
@@ -254,7 +254,7 @@ extension Player {
|
||||
let player = try Player.filter(name: "Arthur O'Brien").fetchOne(db)
|
||||
```
|
||||
|
||||
Custom SQL requests as the one above are welcome in database observation tools like the built-in [ValueObservation] and its [Combine](Combine.md) and [RxSwift](https://github.com/RxSwiftCommunity/RxGRDB) flavors:
|
||||
Custom SQL requests such as the one above are welcome in database observation tools like the built-in [ValueObservation] and its [Combine](Combine.md) and [RxSwift](https://github.com/RxSwiftCommunity/RxGRDB) flavors:
|
||||
|
||||
```swift
|
||||
let playerObservation = ValueObservation.tracking { db in
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '7.3.0'
|
||||
s.version = '7.12.1'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
@@ -9,7 +9,7 @@ Pod::Spec.new do |s|
|
||||
s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" }
|
||||
s.module_name = 'GRDB'
|
||||
|
||||
s.swift_versions = ['6']
|
||||
s.swift_versions = ['6.1']
|
||||
s.ios.deployment_target = '13.0'
|
||||
s.osx.deployment_target = '10.15'
|
||||
s.watchos.deployment_target = '7.0'
|
||||
@@ -21,7 +21,7 @@ Pod::Spec.new do |s|
|
||||
ss.framework = 'Foundation'
|
||||
ss.library = 'sqlite3'
|
||||
ss.xcconfig = {
|
||||
'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_ENABLE_FTS5',
|
||||
'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_ENABLE_FTS5 -D GRDBFRAMEWORK',
|
||||
}
|
||||
end
|
||||
|
||||
|
||||
+32
-2058
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1400"
|
||||
LastUpgradeVersion = "2600"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
#if !canImport(Darwin)
|
||||
@@ -87,10 +90,10 @@ public struct Configuration: Sendable {
|
||||
/// with the number of snapshots.
|
||||
///
|
||||
/// The default configuration label is nil.
|
||||
public var label: String? = nil
|
||||
public var label: String?
|
||||
|
||||
/// A boolean value indicating whether SQLite 3.29+ interprets
|
||||
/// double-quoted strings as string literals when they does not match any
|
||||
/// double-quoted strings as string literals when they do not match any
|
||||
/// valid identifier.
|
||||
///
|
||||
/// The default and recommended value is false:
|
||||
@@ -123,7 +126,7 @@ public struct Configuration: Sendable {
|
||||
///
|
||||
/// Set this flag to true when you apply the technique described in
|
||||
/// <doc:DatabaseSharing#How-to-limit-the-0xDEAD10CC-exception>. See
|
||||
/// ``Database/suspendNotification`` for more informations about
|
||||
/// ``Database/suspendNotification`` for more information about
|
||||
/// suspended databases.
|
||||
public var observesSuspensionNotifications = false
|
||||
|
||||
@@ -144,7 +147,7 @@ public struct Configuration: Sendable {
|
||||
/// do {
|
||||
/// // The sensitive information to protect
|
||||
/// let email = "..."
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// let player = try Player.filter { $0.email == email }.fetchOne(db)
|
||||
/// } catch {
|
||||
/// // By default, sensitive information is NOT printed
|
||||
/// // when an error occurs:
|
||||
@@ -152,7 +155,7 @@ public struct Configuration: Sendable {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// For debugging purpose, you can set this flag to true, and get more
|
||||
/// For debugging purposes, 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
|
||||
@@ -173,7 +176,7 @@ public struct Configuration: Sendable {
|
||||
/// do {
|
||||
/// // The sensitive information to protect
|
||||
/// let email = "..."
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// let player = try Player.filter { $0.email == email }.fetchOne(db)
|
||||
/// } catch {
|
||||
/// // Sensitive information is printed in DEBUG builds:
|
||||
/// print(error)
|
||||
@@ -233,7 +236,7 @@ public struct Configuration: Sendable {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// On newly created databases files, ``DatabasePool`` activates the WAL
|
||||
/// On newly created database files, ``DatabasePool`` activates the WAL
|
||||
/// mode after the preparation functions have run.
|
||||
public mutating func prepareDatabase(_ setup: @escaping @Sendable (Database) throws -> Void) {
|
||||
setups.append(setup)
|
||||
@@ -242,7 +245,7 @@ public struct Configuration: Sendable {
|
||||
// MARK: - Transactions
|
||||
|
||||
/// A boolean value indicating whether it is valid to leave a transaction
|
||||
/// opened at the end of a database access method.
|
||||
/// open at the end of a database access method.
|
||||
///
|
||||
/// The default value is false: not completing a transaction is a
|
||||
/// programmer error:
|
||||
@@ -250,13 +253,13 @@ public struct Configuration: Sendable {
|
||||
/// ```swift
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
///
|
||||
/// // fatal error: A transaction has been left opened at the end of a database access
|
||||
/// // fatal error: A transaction has been left open at the end of a database access
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.beginTransaction()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When true, one can leave opened transaction at the end of database
|
||||
/// When true, one can leave an open transaction at the end of a database
|
||||
/// access method:
|
||||
///
|
||||
/// ```swift
|
||||
@@ -274,7 +277,7 @@ public struct Configuration: Sendable {
|
||||
/// ```
|
||||
///
|
||||
/// This configuration flag has no effect on ``DatabasePool`` reader
|
||||
/// connections: those never allow leaving a transaction opened at the end
|
||||
/// connections: those never allow leaving a transaction open at the end
|
||||
/// of a read access.
|
||||
public var allowsUnsafeTransactions = false
|
||||
|
||||
@@ -320,7 +323,7 @@ public struct Configuration: Sendable {
|
||||
|
||||
// MARK: - Concurrency
|
||||
|
||||
/// Defines the how `SQLITE_BUSY` errors are handled.
|
||||
/// Defines how `SQLITE_BUSY` errors are handled.
|
||||
///
|
||||
/// The default is ``Database/BusyMode/immediateError``.
|
||||
///
|
||||
@@ -329,11 +332,11 @@ public struct Configuration: Sendable {
|
||||
|
||||
/// The behavior in case of SQLITE_BUSY error, for read-only connections.
|
||||
/// If nil, GRDB picks a default one.
|
||||
var readonlyBusyMode: Database.BusyMode? = nil
|
||||
var readonlyBusyMode: Database.BusyMode?
|
||||
|
||||
/// The maximum number of concurrent reader connections.
|
||||
///
|
||||
/// This configuration has effect on ``DatabasePool`` and
|
||||
/// This configuration has an effect on ``DatabasePool`` and
|
||||
/// ``DatabaseSnapshotPool`` only. The default value is 5.
|
||||
///
|
||||
/// You can query this value at runtime in order to get the actual capacity
|
||||
@@ -387,7 +390,7 @@ public struct Configuration: Sendable {
|
||||
/// ``qos`` property.
|
||||
///
|
||||
/// The default is nil.
|
||||
public var targetQueue: DispatchQueue? = nil
|
||||
public var targetQueue: DispatchQueue?
|
||||
|
||||
/// The target dispatch queue for write database accesses.
|
||||
///
|
||||
@@ -395,7 +398,7 @@ public struct Configuration: Sendable {
|
||||
/// by ``targetQueue``.
|
||||
///
|
||||
/// The default is nil.
|
||||
public var writeTargetQueue: DispatchQueue? = nil
|
||||
public var writeTargetQueue: DispatchQueue?
|
||||
|
||||
#if os(iOS)
|
||||
/// A boolean value indicating whether the database connection releases
|
||||
@@ -413,7 +416,7 @@ public struct Configuration: Sendable {
|
||||
/// default value is false.
|
||||
///
|
||||
/// When the flag is false, a `DatabasePool` closes read-only
|
||||
/// connections when requested to dispose non-essential memory with
|
||||
/// connections when requested to dispose of non-essential memory with
|
||||
/// ``DatabasePool/releaseMemory()``. When true, those connections are
|
||||
/// kept open.
|
||||
///
|
||||
@@ -421,6 +424,22 @@ public struct Configuration: Sendable {
|
||||
/// reveals that a lot of time is spent opening new SQLite connections.
|
||||
public var persistentReadOnlyConnections = false
|
||||
|
||||
// MARK: - Database Schema
|
||||
|
||||
/// A custom schema source.
|
||||
///
|
||||
/// The use case for a custom schema source is enabling GRDB features that
|
||||
/// would not work with the built-in schema introspection that is provided
|
||||
/// by SQLite. For example, a custom schema source can help record types
|
||||
/// that read or write in a database view.
|
||||
///
|
||||
/// The schema source is automatically disabled during database
|
||||
/// migrations performed by ``DatabaseMigrator``: those access the raw
|
||||
/// SQLite schema, unaltered. If a migration needs a schema source,
|
||||
/// you may call ``Database/withSchemaSource(_:execute:)`` from within
|
||||
/// the body of a migration.
|
||||
public var schemaSource: (any DatabaseSchemaSource)?
|
||||
|
||||
// MARK: - Factory Configuration
|
||||
|
||||
/// Creates a factory configuration.
|
||||
|
||||
+18
-18
@@ -41,7 +41,7 @@ extension RangeReplaceableCollection {
|
||||
|
||||
/// Adds the elements of a cursor to the end of this collection.
|
||||
///
|
||||
/// In case of error, an unspecified amount of elements have been added to
|
||||
/// In case of error, an unspecified number of elements have been added to
|
||||
/// the collection.
|
||||
///
|
||||
/// - parameter newElements: The elements to append to the collection.
|
||||
@@ -279,7 +279,7 @@ extension Sequence {
|
||||
///
|
||||
/// - Cursor types are classes, and have a lifetime.
|
||||
/// - Cursor iteration may throw errors.
|
||||
/// - A cursor can not be repeated.
|
||||
/// - A cursor cannot be repeated.
|
||||
///
|
||||
/// The protocol comes with default implementations for many operations similar
|
||||
/// to those defined by Swift's Sequence protocol: `contains`, `dropFirst`,
|
||||
@@ -346,7 +346,7 @@ extension Cursor {
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
|
||||
/// let c = cursor.enumerated()
|
||||
/// while let (n, x) = c.next() {
|
||||
/// while let (n, x) = try c.next() {
|
||||
/// print("\(n): \(x)")
|
||||
/// }
|
||||
/// // Prints: "0: foo"
|
||||
@@ -396,10 +396,10 @@ extension Cursor {
|
||||
/// If the number of elements to drop exceeds the number of elements in
|
||||
/// the cursor, the result is an empty cursor.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropFirst(2))
|
||||
/// let numbers = [1, 2, 3, 4, 5]
|
||||
/// try print(Array(AnyCursor(numbers).dropFirst(2)))
|
||||
/// // Prints "[3, 4, 5]"
|
||||
/// try print(numbers.dropFirst(10))
|
||||
/// try print(Array(AnyCursor(numbers).dropFirst(10)))
|
||||
/// // Prints "[]"
|
||||
///
|
||||
/// - Parameter n: The number of elements to drop from the beginning of
|
||||
@@ -415,7 +415,7 @@ extension Cursor {
|
||||
/// The following example drops the first element from a cursor of integers.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropFirst())
|
||||
/// try print(Array(numbers.dropFirst()))
|
||||
/// // Prints "[2, 3, 4, 5]"
|
||||
///
|
||||
/// If the cursor has no elements, the result is an empty cursor.
|
||||
@@ -431,10 +431,10 @@ extension Cursor {
|
||||
/// The cursor must be finite. If the number of elements to drop exceeds
|
||||
/// the number of elements in the cursor, the result is an empty array.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropLast(2))
|
||||
/// let numbers = [1, 2, 3, 4, 5]
|
||||
/// try print(AnyCursor(numbers).dropLast(2))
|
||||
/// // Prints "[1, 2, 3]"
|
||||
/// try print(numbers.dropLast(10))
|
||||
/// try print(AnyCursor(numbers).dropLast(10))
|
||||
/// // Prints "[]"
|
||||
///
|
||||
/// - Parameter n: The number of elements to drop off the end of the
|
||||
@@ -468,7 +468,7 @@ extension Cursor {
|
||||
/// try print(numbers.dropLast())
|
||||
/// // Prints "[1, 2, 3, 4]"
|
||||
///
|
||||
/// If the cursor has no elements, the result is an empty cursor.
|
||||
/// If the cursor has no elements, the result is an empty array.
|
||||
///
|
||||
/// - Returns: An array leaving off the last element of the cursor.
|
||||
public func dropLast() throws -> [Element] {
|
||||
@@ -552,10 +552,10 @@ extension Cursor {
|
||||
/// If the maximum length exceeds the number of elements in the cursor,
|
||||
/// the result contains all the elements in the cursor.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.prefix(2))
|
||||
/// let numbers = [1, 2, 3, 4, 5]
|
||||
/// try print(Array(AnyCursor(numbers).prefix(2)))
|
||||
/// // Prints "[1, 2]"
|
||||
/// try print(numbers.prefix(10))
|
||||
/// try print(Array(AnyCursor(numbers).prefix(10)))
|
||||
/// // Prints "[1, 2, 3, 4, 5]"
|
||||
///
|
||||
/// - Parameter maxLength: The maximum number of elements to return. The
|
||||
@@ -612,10 +612,10 @@ extension Cursor {
|
||||
/// elements in the cursor, the result contains all the elements in the
|
||||
/// cursor.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.suffix(2))
|
||||
/// let numbers = [1, 2, 3, 4, 5]
|
||||
/// try print(AnyCursor(numbers).suffix(2))
|
||||
/// // Prints "[4, 5]"
|
||||
/// try print(numbers.suffix(10))
|
||||
/// try print(AnyCursor(numbers).suffix(10))
|
||||
/// // Prints "[1, 2, 3, 4, 5]"
|
||||
///
|
||||
/// - Parameter maxLength: The maximum number of elements to return. The
|
||||
@@ -857,7 +857,7 @@ extension DropWhileCursor: Cursor {
|
||||
/// SELECT 'foo' UNION ALL SELECT 'bar'
|
||||
/// """)
|
||||
/// let cursor = base.enumerated()
|
||||
/// while let (n, x) = cursor.next() {
|
||||
/// while let (n, x) = try cursor.next() {
|
||||
/// print("\(n): \(x)")
|
||||
/// }
|
||||
/// // Prints: "0: foo"
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
#if SQLITE_HAS_CODEC
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else
|
||||
#error("No SQLCipher library configured")
|
||||
#endif
|
||||
import Foundation
|
||||
|
||||
extension Database {
|
||||
|
||||
/// Destination of SQLCipher logs.
|
||||
///
|
||||
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_log>
|
||||
public struct SQLCipherLogTarget: Sendable {
|
||||
public var rawValue: String
|
||||
public init(rawValue: String) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
public static let stdout = Self(rawValue: "stdout")
|
||||
public static let stderr = Self(rawValue: "stderr")
|
||||
public static let device = Self(rawValue: "device")
|
||||
public static func file(_ path: String) -> Self { Self(rawValue: path) }
|
||||
}
|
||||
|
||||
/// Granularity of SQLCipher log outputs.
|
||||
///
|
||||
/// Each log level is more verbose than the last. With ``debug`` and
|
||||
/// ``trace`` the logging system will generate a significant log volume.
|
||||
///
|
||||
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_log_level>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Log Levels
|
||||
///
|
||||
/// - ``none``
|
||||
/// - ``error``
|
||||
/// - ``warn``
|
||||
/// - ``info``
|
||||
/// - ``debug``
|
||||
/// - ``trace``
|
||||
public struct SQLCipherLogLevel: RawRepresentable, Sendable {
|
||||
public var rawValue: String
|
||||
public init(rawValue: String) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
public static let none = Self(rawValue: "NONE")
|
||||
public static let error = Self(rawValue: "ERROR")
|
||||
public static let warn = Self(rawValue: "WARN")
|
||||
public static let info = Self(rawValue: "INFO")
|
||||
public static let debug = Self(rawValue: "DEBUG")
|
||||
public static let trace = Self(rawValue: "TRACE")
|
||||
}
|
||||
|
||||
/// - Returns: the SQLCipher version
|
||||
///
|
||||
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_version>
|
||||
public var cipherVersion: String {
|
||||
get throws { try String.fetchOne(self, sql: "PRAGMA cipher_version")! }
|
||||
}
|
||||
|
||||
/// - Returns: the SQLCipher fips status: 1 for fips mode, 0 for non-fips mode
|
||||
/// The FIPS status will not be initialized until the database connection has been keyed
|
||||
///
|
||||
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_fips_status>
|
||||
public var cipherFipsStatus: String? {
|
||||
get throws { try String.fetchOne(self, sql: "PRAGMA cipher_fips_status") }
|
||||
}
|
||||
|
||||
/// - Returns: The compiled crypto provider.
|
||||
/// The database must be keyed before requesting the name of the crypto provider.
|
||||
///
|
||||
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_provider>
|
||||
public var cipherProvider: String? {
|
||||
get throws { try String.fetchOne(self, sql: "PRAGMA cipher_provider") }
|
||||
}
|
||||
|
||||
/// - Returns: the version number provided from the compiled crypto provider.
|
||||
/// This value, if known, is available only after the database has been keyed.
|
||||
///
|
||||
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_provider_version>
|
||||
public var cipherProviderVersion: String? {
|
||||
get throws { try String.fetchOne(self, sql: "PRAGMA cipher_provider_version") }
|
||||
}
|
||||
|
||||
/// Sets the passphrase used to encrypt and decrypt an SQLCipher database.
|
||||
///
|
||||
/// Call this method from `Configuration.prepareDatabase`,
|
||||
/// as in the example below:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// try db.usePassphrase("secret")
|
||||
/// }
|
||||
public func usePassphrase(_ passphrase: String) throws {
|
||||
guard var data = passphrase.data(using: .utf8) else {
|
||||
throw DatabaseError(message: "invalid passphrase")
|
||||
}
|
||||
defer {
|
||||
data.resetBytes(in: 0..<data.count)
|
||||
}
|
||||
try usePassphrase(data)
|
||||
}
|
||||
|
||||
/// Sets the passphrase used to encrypt and decrypt an SQLCipher database.
|
||||
///
|
||||
/// Call this method from `Configuration.prepareDatabase`,
|
||||
/// as in the example below:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// try db.usePassphrase(passphraseData)
|
||||
/// }
|
||||
public func usePassphrase(_ passphrase: Data) throws {
|
||||
let code = passphrase.withUnsafeBytes {
|
||||
sqlite3_key(sqliteConnection, $0.baseAddress, CInt($0.count))
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Changes the passphrase used by an SQLCipher encrypted database.
|
||||
public func changePassphrase(_ passphrase: String) throws {
|
||||
guard var data = passphrase.data(using: .utf8) else {
|
||||
throw DatabaseError(message: "invalid passphrase")
|
||||
}
|
||||
defer {
|
||||
data.resetBytes(in: 0..<data.count)
|
||||
}
|
||||
try changePassphrase(data)
|
||||
}
|
||||
|
||||
/// Changes the passphrase used by an SQLCipher encrypted database.
|
||||
public func changePassphrase(_ passphrase: Data) throws {
|
||||
// FIXME: sqlite3_rekey is discouraged.
|
||||
//
|
||||
// https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320
|
||||
//
|
||||
// > We (Zetetic) have been discouraging the use of sqlite3_rekey in
|
||||
// > favor of attaching a new database with the desired encryption
|
||||
// > options and using sqlcipher_export() to migrate the contents and
|
||||
// > schema of the original db into the new one:
|
||||
// > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/
|
||||
let code = passphrase.withUnsafeBytes {
|
||||
sqlite3_rekey(sqliteConnection, $0.baseAddress, CInt($0.count))
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: lastErrorMessage)
|
||||
}
|
||||
}
|
||||
|
||||
/// When using Commercial or Enterprise SQLCipher packages you must call
|
||||
/// `PRAGMA cipher_license` with a valid license code prior to executing
|
||||
/// cryptographic operations on an encrypted database.
|
||||
/// Failure to provide a license code, or use of an expired trial code,
|
||||
/// will result in an `SQLITE_AUTH (23)` error code reported from the SQLite API
|
||||
/// License Codes will activate SQLCipher Commercial or Enterprise packages
|
||||
/// from Zetetic: <https://www.zetetic.net/sqlcipher/buy/>
|
||||
/// 15-day free trials are available by request: <https://www.zetetic.net/sqlcipher/trial/>
|
||||
///
|
||||
/// Call this method from ``Configuration/prepareDatabase(_:)``,
|
||||
/// as in the example below:
|
||||
///
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// try db.applySQLCipherLicense(license)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_license>
|
||||
/// - Parameter license: base64 SQLCipher license code to activate SQLCipher commercial
|
||||
public func applySQLCipherLicense(_ license: String) throws {
|
||||
try execute(sql: "PRAGMA cipher_license = '\(license)'")
|
||||
}
|
||||
|
||||
/// Instructs SQLCipher to log internal debugging and operational information.
|
||||
///
|
||||
/// The supplied `logLevel` determines the granularity of the log output.
|
||||
///
|
||||
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_log>
|
||||
/// - Parameter logLevel: The granularity to use for the logging system - defaults to `DEBUG`.
|
||||
/// - Parameter target: The destination of SQLCipher logs - defaults to `.device`.
|
||||
public func enableCipherLogging(
|
||||
logLevel: SQLCipherLogLevel = .debug,
|
||||
target: SQLCipherLogTarget = .device
|
||||
) throws {
|
||||
// Pragma do not support SQL arguments. We need to generate SQL that contains literal values:
|
||||
// PRAGMA cipher_log = '/path/to/file'
|
||||
// PRAGMA cipher_log_level = 'xxx'
|
||||
let context = SQLGenerationContext(self, argumentsSink: .literalValues)
|
||||
try execute(sql: SQL("PRAGMA cipher_log = \(target.rawValue)").sql(context))
|
||||
try execute(sql: SQL("PRAGMA cipher_log_level = \(logLevel.rawValue.uppercased())").sql(context))
|
||||
}
|
||||
|
||||
/// Instructs SQLCipher to disable logging internal debugging and operational information.
|
||||
///
|
||||
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_log>
|
||||
public func disableCipherLogging() throws {
|
||||
try execute(sql: "PRAGMA cipher_log_level = NONE")
|
||||
}
|
||||
|
||||
internal func validateSQLCipher() throws {
|
||||
// https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688
|
||||
//
|
||||
// > In order to avoid situations where SQLite might be used
|
||||
// > improperly at runtime, we strongly recommend that
|
||||
// > applications institute a runtime test to ensure that the
|
||||
// > application is actually using SQLCipher on the active
|
||||
// > connection.
|
||||
if try String.fetchOne(self, sql: "PRAGMA cipher_version") == nil {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: """
|
||||
GRDB is not linked against SQLCipher. \
|
||||
Check https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
internal func dropAllDatabaseObjects() throws {
|
||||
// SQLCipher does not support the backup API:
|
||||
// https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631
|
||||
// So we'll drop all database objects one after the other.
|
||||
|
||||
// Prevent foreign keys from messing with drop table statements
|
||||
let foreignKeysEnabled = try Bool.fetchOne(self, sql: "PRAGMA foreign_keys")!
|
||||
if foreignKeysEnabled {
|
||||
try execute(sql: "PRAGMA foreign_keys = OFF")
|
||||
}
|
||||
|
||||
try throwingFirstError(
|
||||
execute: {
|
||||
// Remove all database objects, one after the other
|
||||
try inTransaction {
|
||||
let sql = "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'"
|
||||
while let row = try Row.fetchOne(self, sql: sql) {
|
||||
let type: String = row["type"]
|
||||
let name: String = row["name"]
|
||||
try execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)")
|
||||
}
|
||||
return .commit
|
||||
}
|
||||
},
|
||||
finally: {
|
||||
// Restore foreign keys if needed
|
||||
if foreignKeysEnabled {
|
||||
try execute(sql: "PRAGMA foreign_keys = ON")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
+440
-253
File diff suppressed because it is too large.
Load diff
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -48,8 +51,8 @@ extension Database {
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```
|
||||
///
|
||||
/// In the provided literal, no argument must be set, or all arguments must
|
||||
/// be set. An error is raised otherwise. For example:
|
||||
/// In the provided literal, either no argument is set, or all arguments
|
||||
/// are set. An error is raised otherwise. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // OK
|
||||
@@ -140,7 +143,7 @@ extension Database {
|
||||
/// ```
|
||||
///
|
||||
/// The returned statement may have already been used: it may or may not
|
||||
/// contain values for its eventual arguments.
|
||||
/// contain values for its arguments, if any.
|
||||
///
|
||||
/// - parameter sql: An SQL string.
|
||||
/// - returns: A prepared statement.
|
||||
@@ -163,8 +166,8 @@ extension Database {
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```
|
||||
///
|
||||
/// In the provided literal, no argument must be set, or all arguments must
|
||||
/// be set. An error is raised otherwise. For example:
|
||||
/// In the provided literal, either no argument is set, or all arguments
|
||||
/// are set. An error is raised otherwise. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // OK
|
||||
@@ -264,8 +267,8 @@ extension Database {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// In the provided literal, no argument must be set, or all arguments must
|
||||
/// be set. The returned cursor will throw an error otherwise. For example:
|
||||
/// In the provided literal, either no argument is set, or all arguments
|
||||
/// are set. The returned cursor will throw an error otherwise. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // OK
|
||||
@@ -387,7 +390,7 @@ extension SQLStatementCursor: Cursor {
|
||||
let baseAddress = buffer.baseAddress! // never nil because the buffer contains the trailing \0.
|
||||
|
||||
// Compile next statement
|
||||
var statementEnd: UnsafePointer<CChar>? = nil
|
||||
var statementEnd: UnsafePointer<CChar>?
|
||||
let statement = try Statement(
|
||||
database: database,
|
||||
statementStart: baseAddress + offset,
|
||||
@@ -469,7 +472,7 @@ extension Database {
|
||||
/// Always throws an error
|
||||
@usableFromInline
|
||||
func statementDidFail(_ statement: Statement, withResultCode resultCode: CInt) throws -> Never {
|
||||
// Failed statements can not be reused, because `sqlite3_reset` won't
|
||||
// Failed statements cannot be reused, because `sqlite3_reset` won't
|
||||
// be able to restore the statement to its initial state:
|
||||
// https://www.sqlite.org/c3ref/reset.html
|
||||
//
|
||||
@@ -494,11 +497,9 @@ extension Database {
|
||||
|
||||
switch ResultCode(rawValue: resultCode) {
|
||||
case .SQLITE_INTERRUPT, .SQLITE_ABORT:
|
||||
if suspensionMutex.load().isCancelled {
|
||||
// The only error that a user sees when a Task is cancelled
|
||||
// is CancellationError.
|
||||
throw CancellationError()
|
||||
}
|
||||
// The only error that a user sees when a Task is cancelled
|
||||
// is CancellationError.
|
||||
try suspensionMutex.load().checkCancellation()
|
||||
default:
|
||||
break
|
||||
}
|
||||
@@ -512,6 +513,27 @@ extension Database {
|
||||
publicStatementArguments: configuration.publicStatementArguments)
|
||||
}
|
||||
|
||||
/// Always throws an error
|
||||
func statementCompilationDidFail(
|
||||
at statementStart: UnsafePointer<CChar>,
|
||||
withResultCode resultCode: CInt
|
||||
) throws -> Never {
|
||||
switch ResultCode(rawValue: resultCode) {
|
||||
case .SQLITE_INTERRUPT, .SQLITE_ABORT:
|
||||
// The only error that a user sees when a Task is cancelled
|
||||
// is CancellationError.
|
||||
try suspensionMutex.load().checkCancellation()
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
// Throw compilation failure
|
||||
throw DatabaseError(
|
||||
resultCode: resultCode,
|
||||
message: lastErrorMessage,
|
||||
sql: String(cString: statementStart))
|
||||
}
|
||||
|
||||
private func checkForAutocommitTransition() {
|
||||
if sqlite3_get_autocommit(sqliteConnection) == 0 {
|
||||
if autocommitState == .on {
|
||||
|
||||
+216
-168
@@ -1,10 +1,14 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
import GRDBSQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -113,6 +117,11 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// - ``resumeNotification``
|
||||
/// - ``suspendNotification``
|
||||
///
|
||||
/// ### The Schema Source
|
||||
///
|
||||
/// - ``schemaSource``
|
||||
/// - ``withSchemaSource(_:execute:)``
|
||||
///
|
||||
/// ### Other Database Operations
|
||||
///
|
||||
/// - ``add(tokenizer:)``
|
||||
@@ -169,7 +178,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// connection has been opened is an SQLite misuse, and has no effect.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/errlog.html>
|
||||
nonisolated(unsafe) public static var logError: LogErrorFunction? = nil {
|
||||
nonisolated(unsafe) public static var logError: LogErrorFunction? {
|
||||
didSet {
|
||||
if logError != nil {
|
||||
_registerErrorLogCallback { (_, code, message) in
|
||||
@@ -187,6 +196,19 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// The database configuration.
|
||||
public let configuration: Configuration
|
||||
|
||||
/// The current schema source.
|
||||
///
|
||||
/// By default, it is the ``Configuration/schemaSource``
|
||||
/// of ``configuration``. To modify the schema source,
|
||||
/// use ``withSchemaSource(_:execute:)``.
|
||||
///
|
||||
/// The schema source is automatically disabled (nil) during database
|
||||
/// migrations performed by ``DatabaseMigrator``: those access the raw
|
||||
/// SQLite schema, unaltered. If a migration needs a schema source,
|
||||
/// you may call ``Database/withSchemaSource(_:execute:)`` from within
|
||||
/// the body of a migration.
|
||||
public internal(set) var schemaSource: (any DatabaseSchemaSource)?
|
||||
|
||||
/// A description of this database connection.
|
||||
///
|
||||
/// The returned string is based on the ``Configuration/label``
|
||||
@@ -341,10 +363,22 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// If true, the database access has been cancelled.
|
||||
var isCancelled: Bool
|
||||
|
||||
/// If true, the database throws an error when it is cancelled.
|
||||
var interruptsWhenCancelled: Bool
|
||||
|
||||
func checkCancellation() throws {
|
||||
if isCancelled, interruptsWhenCancelled {
|
||||
throw CancellationError()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Support for `checkForSuspensionViolation(from:)`
|
||||
let suspensionMutex = Mutex(Suspension(isSuspended: false, isCancelled: false))
|
||||
let suspensionMutex = Mutex(Suspension(
|
||||
isSuspended: false,
|
||||
isCancelled: false,
|
||||
interruptsWhenCancelled: true))
|
||||
|
||||
// MARK: - Transaction Date
|
||||
|
||||
@@ -365,7 +399,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
var autocommitState = AutocommitState.on
|
||||
|
||||
/// The date of the current transaction, wrapped in a result that is an
|
||||
/// error if there was an error grabbing this date when the transaction has
|
||||
/// error if there was an error grabbing this date when the transaction
|
||||
/// started.
|
||||
///
|
||||
/// Invariant: `transactionDateResult` is nil iff connection is not
|
||||
@@ -430,6 +464,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
|
||||
self.description = description
|
||||
self.configuration = configuration
|
||||
self.schemaSource = configuration.schemaSource
|
||||
self.path = path
|
||||
|
||||
// We do not report read-only transactions to transaction observers, so
|
||||
@@ -447,7 +482,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
private static func openConnection(path: String, flags: CInt) throws -> SQLiteConnection {
|
||||
// See <https://www.sqlite.org/c3ref/open.html>
|
||||
var sqliteConnection: SQLiteConnection? = nil
|
||||
var sqliteConnection: SQLiteConnection?
|
||||
let code = sqlite3_open_v2(path, &sqliteConnection, flags, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
// https://www.sqlite.org/c3ref/open.html
|
||||
@@ -459,8 +494,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// https://www.sqlite.org/c3ref/close.html
|
||||
// > Calling sqlite3_close() or sqlite3_close_v2() with a NULL
|
||||
// > pointer argument is a harmless no-op.
|
||||
//
|
||||
// Read the error message before the connection is closed.
|
||||
let message = sqliteConnection.map { String(cString: sqlite3_errmsg($0)) }
|
||||
_ = sqlite3_close(sqliteConnection) // ignore result code
|
||||
throw DatabaseError(resultCode: code)
|
||||
throw DatabaseError(resultCode: code, message: message)
|
||||
}
|
||||
guard let sqliteConnection else {
|
||||
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
|
||||
@@ -607,24 +645,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
private func validateSQLCipher() throws {
|
||||
// https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688
|
||||
//
|
||||
// > In order to avoid situations where SQLite might be used
|
||||
// > improperly at runtime, we strongly recommend that
|
||||
// > applications institute a runtime test to ensure that the
|
||||
// > application is actually using SQLCipher on the active
|
||||
// > connection.
|
||||
if try String.fetchOne(self, sql: "PRAGMA cipher_version") == nil {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: """
|
||||
GRDB is not linked against SQLCipher. \
|
||||
Check https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688
|
||||
""")
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
private func validateFormat() throws {
|
||||
// Users are surprised when they open a picture as a database and
|
||||
// see no error (https://github.com/groue/GRDB.swift/issues/54).
|
||||
@@ -794,7 +814,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
collationPointer,
|
||||
{ (collationPointer, length1, buffer1, length2, buffer2) in
|
||||
let collation = Unmanaged<DatabaseCollation>.fromOpaque(collationPointer!).takeUnretainedValue()
|
||||
return CInt(collation.function(length1, buffer1, length2, buffer2).rawValue)
|
||||
return collation.xCompare(length1, buffer1.unsafelyUnwrapped, length2, buffer2.unsafelyUnwrapped)
|
||||
}, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
@@ -818,7 +838,18 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
func beginReadOnly() throws {
|
||||
if configuration.readonly { return }
|
||||
if readOnlyDepth == 0 {
|
||||
try internalCachedStatement(sql: "PRAGMA query_only = 1").execute()
|
||||
// We MUST ignore interruptions when we enter the read-only mode.
|
||||
// An interruption could make the PRAGMA throw after it has
|
||||
// enabled `query_only`. `readOnlyDepth` would not be increased,
|
||||
// `endReadOnly()` would not run, and the user could not write
|
||||
// with this database connection again.
|
||||
//
|
||||
// It's OK to ignore interruption, since interruption is
|
||||
// concurrent and we can pretend it occurred before or after
|
||||
// the PRAGMA.
|
||||
try ignoringInterruption {
|
||||
try internalCachedStatement(sql: "PRAGMA query_only = 1").execute()
|
||||
}
|
||||
}
|
||||
readOnlyDepth += 1
|
||||
}
|
||||
@@ -829,7 +860,16 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
readOnlyDepth -= 1
|
||||
assert(readOnlyDepth >= 0, "unbalanced endReadOnly()")
|
||||
if readOnlyDepth == 0 {
|
||||
try internalCachedStatement(sql: "PRAGMA query_only = 0").execute()
|
||||
// We MUST ignore interruptions when we leave the read-only mode,
|
||||
// otherwise user could not write with this database
|
||||
// connection again.
|
||||
//
|
||||
// It's OK to ignore interruption, since interruption is
|
||||
// concurrent and we can pretend it occurred before or after
|
||||
// the PRAGMA.
|
||||
try ignoringInterruption {
|
||||
try internalCachedStatement(sql: "PRAGMA query_only = 0").execute()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -842,7 +882,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write do { db in
|
||||
/// try dbQueue.write { db in
|
||||
/// // Write OK
|
||||
/// try Player(...).insert(db)
|
||||
///
|
||||
@@ -879,7 +919,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// Reports the database region to ``ValueObservation``.
|
||||
///
|
||||
/// Calling this method does not fetch any database values. It just
|
||||
/// helps optimizing `ValueObservation`. See
|
||||
/// helps optimize `ValueObservation`. See
|
||||
/// ``ValueObservation/trackingConstantRegion(_:)`` for more
|
||||
/// information, and some examples of usage.
|
||||
///
|
||||
@@ -1137,7 +1177,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// See <https://www.sqlite.org/c3ref/interrupt.html>
|
||||
func interrupt() {
|
||||
sqlite3_interrupt(sqliteConnection)
|
||||
if let sqliteConnection {
|
||||
sqlite3_interrupt(sqliteConnection)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Database Suspension
|
||||
@@ -1148,7 +1190,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// A suspended database makes everything to avoid acquiring a lock on the
|
||||
/// A suspended database does everything to avoid acquiring a lock on the
|
||||
/// database. All database operations may throw a ``DatabaseError`` of code
|
||||
/// `SQLITE_INTERRUPT` or `SQLITE_ABORT`, except reads in WAL mode.
|
||||
///
|
||||
@@ -1211,22 +1253,31 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
/// Cancels the current database access. All statements but ROLLBACK
|
||||
/// will throw `CancellationError`, until `uncancel()` is called.
|
||||
///
|
||||
/// This method can be called from any thread.
|
||||
func cancel() {
|
||||
let needsInterrupt = suspensionMutex.withLock { suspension in
|
||||
if suspension.isCancelled {
|
||||
return false
|
||||
/// Returns a closure that cancels the current database access.
|
||||
/// Most statements will throw `CancellationError`, until `uncancel()`
|
||||
/// is called.
|
||||
var cancel: @Sendable () -> Void {
|
||||
// Workaround the fact that SQLiteConnection is not Sendable.
|
||||
struct Connection: @unchecked Sendable {
|
||||
var sqliteConnection: SQLiteConnection?
|
||||
}
|
||||
let connection = Connection(sqliteConnection: sqliteConnection)
|
||||
|
||||
return { [suspensionMutex, connection] in
|
||||
let needsInterrupt = suspensionMutex.withLock { suspension in
|
||||
if suspension.isCancelled {
|
||||
return false
|
||||
}
|
||||
|
||||
suspension.isCancelled = true
|
||||
return suspension.interruptsWhenCancelled
|
||||
}
|
||||
|
||||
suspension.isCancelled = true
|
||||
return true
|
||||
}
|
||||
|
||||
if needsInterrupt {
|
||||
interrupt()
|
||||
if needsInterrupt {
|
||||
if let sqliteConnection = connection.sqliteConnection {
|
||||
sqlite3_interrupt(sqliteConnection)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1237,6 +1288,49 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
/// Within the given closure, Task cancellation does not interrupt
|
||||
/// database accesses.
|
||||
func ignoringCancellation<T>(_ value: () throws -> T) rethrows -> T {
|
||||
let previous = suspensionMutex.withLock {
|
||||
let previous = $0.interruptsWhenCancelled
|
||||
$0.interruptsWhenCancelled = false
|
||||
return previous
|
||||
}
|
||||
|
||||
defer {
|
||||
suspensionMutex.withLock {
|
||||
$0.interruptsWhenCancelled = previous
|
||||
}
|
||||
}
|
||||
|
||||
return try value()
|
||||
}
|
||||
|
||||
/// Returns the result of `value`. If `value` throws an interruption
|
||||
/// error, it is retried a second time.
|
||||
func ignoringInterruption<T>(_ value: () throws -> T) rethrows -> T {
|
||||
do {
|
||||
return try value() // swiftlint:disable:next statement_position
|
||||
}
|
||||
catch is CancellationError,
|
||||
DatabaseError.SQLITE_INTERRUPT,
|
||||
DatabaseError.SQLITE_ABORT
|
||||
{
|
||||
// Maybe we were unlucky, and user has interrupted the database
|
||||
// during `value` execution.
|
||||
//
|
||||
// Another possible cause for this error is the FTS5 bug
|
||||
// described at <https://sqlite.org/forum/forumpost/137c7662b3>,
|
||||
// which leaves the database in a sticky interrupted state.
|
||||
// To workaround this bug, we must leave the interrupted state
|
||||
// before retrying:
|
||||
resetAllPreparedStatements()
|
||||
|
||||
// Retry
|
||||
return try value()
|
||||
}
|
||||
}
|
||||
|
||||
/// Support for `checkForSuspensionViolation(from:)`
|
||||
private func journalMode() throws -> String {
|
||||
if let journalMode = journalModeCache {
|
||||
@@ -1245,7 +1339,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// Don't return String.fetchOne(self, sql: "PRAGMA journal_mode"), so
|
||||
// that we don't create an infinite loop in checkForSuspensionViolation(from:)
|
||||
var statement: SQLiteStatement? = nil
|
||||
var statement: SQLiteStatement?
|
||||
let sql = "PRAGMA journal_mode"
|
||||
sqlite3_prepare_v2(sqliteConnection, sql, -1, &statement, nil)
|
||||
defer { sqlite3_finalize(statement) }
|
||||
@@ -1266,9 +1360,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// - When database access is cancelled, this method
|
||||
/// throws `CancellationError`.
|
||||
///
|
||||
/// - When database is suspensed, and if the statement would lock the
|
||||
/// - When database is suspended, and if the statement would lock the
|
||||
/// database in a way that may trigger the 0xDEAD10CC exception, this
|
||||
/// method rollbacks the current transaction and throws `SQLITE_ABORT`.
|
||||
/// method rolls back the current transaction and throws `SQLITE_ABORT`.
|
||||
///
|
||||
/// See `cancel()`, `suspend()` and
|
||||
/// ``Configuration/observesSuspensionNotifications``.
|
||||
@@ -1288,6 +1382,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
return
|
||||
}
|
||||
|
||||
// Commits when read-only are just like rollbacks above.
|
||||
if statement.transactionEffect == .commitTransaction && isReadOnly {
|
||||
return
|
||||
}
|
||||
|
||||
// Suspension should not prevent adjusting the read-only mode.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1715>.
|
||||
if statement.isQueryOnlyPragma {
|
||||
@@ -1303,7 +1402,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
let interrupt: Interrupt? = try suspensionMutex.withLock { suspension in
|
||||
// Check for cancellation first, so that the only error that
|
||||
// a user sees when a Task is cancelled is CancellationError.
|
||||
if suspension.isCancelled {
|
||||
if suspension.isCancelled, suspension.interruptsWhenCancelled {
|
||||
return .cancel
|
||||
}
|
||||
|
||||
@@ -1343,7 +1442,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
throw CancellationError()
|
||||
|
||||
case .abort:
|
||||
// Attempt at releasing an eventual lock with ROLLBACk,
|
||||
// Attempt to release a possible lock with ROLLBACK,
|
||||
// as explained in Database.suspend().
|
||||
try? rollback()
|
||||
|
||||
@@ -1359,14 +1458,14 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// MARK: - Transactions & Savepoint
|
||||
|
||||
/// Throws `SQLITE_ABORT` if called from a transaction-wrapping method and
|
||||
/// transaction has been aborted (for example, by `sqlite3_interrupt`, or a
|
||||
/// `ON CONFLICT ROLLBACK` clause.
|
||||
/// transaction has been aborted (for example, by `sqlite3_interrupt`, or an
|
||||
/// `ON CONFLICT ROLLBACK` clause).
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try db.inTransaction {
|
||||
/// do {
|
||||
/// // Throws an error because the transaction was rollbacked.
|
||||
/// // Throws an error because the transaction was rolled back.
|
||||
/// try ...
|
||||
/// } catch {
|
||||
/// // Catch the error and continue.
|
||||
@@ -1397,7 +1496,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.writeWithoutTransaction do { db in
|
||||
/// try dbQueue.writeWithoutTransaction { db in
|
||||
/// try db.inTransaction {
|
||||
/// try db.execute(sql: "INSERT ...")
|
||||
/// return .commit
|
||||
@@ -1405,13 +1504,13 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// If `operations` throws an error, the transaction is rollbacked and the
|
||||
/// If `operations` throws an error, the transaction is rolled back and the
|
||||
/// error is rethrown. If it returns ``TransactionCompletion/rollback``, the
|
||||
/// transaction is also rollbacked, but no error is thrown.
|
||||
/// transaction is also rolled back, but no error is thrown.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>
|
||||
///
|
||||
/// - warning: This method is not reentrant: you can not nest transactions.
|
||||
/// - warning: This method is not reentrant: you cannot nest transactions.
|
||||
/// Use ``inSavepoint(_:)`` instead.
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -1437,7 +1536,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// Now that transaction has begun, we'll rollback in case of error.
|
||||
// But we'll throw the first caught error, so that user knows
|
||||
// what happened.
|
||||
var firstError: Error? = nil
|
||||
var firstError: Error?
|
||||
let needsRollback: Bool
|
||||
do {
|
||||
let completion = try operations()
|
||||
@@ -1516,7 +1615,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write do {
|
||||
/// try dbQueue.write { db in
|
||||
/// try db.inSavepoint {
|
||||
/// try db.execute(sql: "INSERT ...")
|
||||
/// return .commit
|
||||
@@ -1524,9 +1623,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// If `operations` throws an error, the savepoint is rollbacked and the
|
||||
/// If `operations` throws an error, the savepoint is rolled back and the
|
||||
/// error is rethrown. If it returns ``TransactionCompletion/rollback``, the
|
||||
/// savepoint is also rollbacked, but no error is thrown.
|
||||
/// savepoint is also rolled back, but no error is thrown.
|
||||
///
|
||||
/// This method is reentrant: you can nest savepoints.
|
||||
///
|
||||
@@ -1580,7 +1679,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// Now that savepoint has begun, we'll rollback in case of error.
|
||||
// But we'll throw the first caught error, so that user knows
|
||||
// what happened.
|
||||
var firstError: Error? = nil
|
||||
var firstError: Error?
|
||||
let needsRollback: Bool
|
||||
do {
|
||||
let completion = try operations()
|
||||
@@ -1638,11 +1737,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
public func beginTransaction(_ kind: TransactionKind? = nil) throws {
|
||||
// SQLite throws an error for non-deferred transactions when read-only.
|
||||
// We prefer immediate transactions for writes, so that write
|
||||
// transactions can not overlap. This reduces the opportunity for
|
||||
// transactions cannot overlap. This reduces the opportunity for
|
||||
// SQLITE_BUSY, which is immediately thrown whenever a transaction
|
||||
// is upgraded after an initial read and a concurrent processes
|
||||
// has acquired the write lock beforehand. This SQLITE_BUSY error
|
||||
// can not be avoided with a busy timeout.
|
||||
// cannot be avoided with a busy timeout.
|
||||
//
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1483>.
|
||||
let kind = kind ?? (isReadOnly ? .deferred : .immediate)
|
||||
@@ -1650,7 +1749,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
assert(sqlite3_get_autocommit(sqliteConnection) == 0)
|
||||
}
|
||||
|
||||
/// Rollbacks a database transaction.
|
||||
/// Rolls back a database transaction.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>
|
||||
///
|
||||
@@ -1696,9 +1795,18 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// which rollback errors should be ignored, and which rollback errors
|
||||
// should be exposed to the library user.
|
||||
if isInsideTransaction {
|
||||
try execute(sql: "ROLLBACK TRANSACTION")
|
||||
// We MUST ignore interruptions during the rollback, otherwise
|
||||
// we could leave a transaction open, and trigger a fatal error in
|
||||
// `SerializedDatabase.preconditionNoUnsafeTransactionLeft`.
|
||||
//
|
||||
// It's OK to ignore interruption, since interruption is
|
||||
// concurrent and we can pretend it occurred before or after
|
||||
// the rollback.
|
||||
try ignoringInterruption {
|
||||
try execute(sql: "ROLLBACK TRANSACTION")
|
||||
}
|
||||
}
|
||||
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
|
||||
assert(!isInsideTransaction)
|
||||
}
|
||||
|
||||
/// Commits a database transaction.
|
||||
@@ -1711,6 +1819,19 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
|
||||
}
|
||||
|
||||
/// Resets all prepared statements.
|
||||
///
|
||||
/// This method helps clear the interrupted state, as a workaround
|
||||
/// for https://sqlite.org/forum/forumpost/137c7662b3, discovered
|
||||
/// in https://github.com/groue/GRDB.swift/issues/1838.
|
||||
func resetAllPreparedStatements() {
|
||||
var stmt: SQLiteStatement? = sqlite3_next_stmt(sqliteConnection, nil)
|
||||
while stmt != nil {
|
||||
sqlite3_reset(stmt)
|
||||
stmt = sqlite3_next_stmt(sqliteConnection, stmt)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Memory Management
|
||||
|
||||
/// Frees as much memory as possible.
|
||||
@@ -1728,35 +1849,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
func erase() throws {
|
||||
#if SQLITE_HAS_CODEC
|
||||
// SQLCipher does not support the backup API:
|
||||
// https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631
|
||||
// So we'll drop all database objects one after the other.
|
||||
|
||||
// Prevent foreign keys from messing with drop table statements
|
||||
let foreignKeysEnabled = try Bool.fetchOne(self, sql: "PRAGMA foreign_keys")!
|
||||
if foreignKeysEnabled {
|
||||
try execute(sql: "PRAGMA foreign_keys = OFF")
|
||||
}
|
||||
|
||||
try throwingFirstError(
|
||||
execute: {
|
||||
// Remove all database objects, one after the other
|
||||
try inTransaction {
|
||||
let sql = "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'"
|
||||
while let row = try Row.fetchOne(self, sql: sql) {
|
||||
let type: String = row["type"]
|
||||
let name: String = row["name"]
|
||||
try execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)")
|
||||
}
|
||||
return .commit
|
||||
}
|
||||
},
|
||||
finally: {
|
||||
// Restore foreign keys if needed
|
||||
if foreignKeysEnabled {
|
||||
try execute(sql: "PRAGMA foreign_keys = ON")
|
||||
}
|
||||
})
|
||||
try dropAllDatabaseObjects()
|
||||
#else
|
||||
try DatabaseQueue().backup(to: self)
|
||||
#endif
|
||||
@@ -1879,79 +1972,33 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
@available(*, unavailable)
|
||||
extension Database: Sendable { }
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
extension Database {
|
||||
|
||||
// MARK: - Encryption
|
||||
|
||||
/// Sets the passphrase used to crypt and decrypt an SQLCipher database.
|
||||
///
|
||||
/// Call this method from `Configuration.prepareDatabase`,
|
||||
/// as in the example below:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// try db.usePassphrase("secret")
|
||||
/// }
|
||||
public func usePassphrase(_ passphrase: String) throws {
|
||||
guard var data = passphrase.data(using: .utf8) else {
|
||||
throw DatabaseError(message: "invalid passphrase")
|
||||
}
|
||||
defer {
|
||||
data.resetBytes(in: 0..<data.count)
|
||||
}
|
||||
try usePassphrase(data)
|
||||
}
|
||||
|
||||
/// Sets the passphrase used to crypt and decrypt an SQLCipher database.
|
||||
///
|
||||
/// Call this method from `Configuration.prepareDatabase`,
|
||||
/// as in the example below:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// try db.usePassphrase(passphraseData)
|
||||
/// }
|
||||
public func usePassphrase(_ passphrase: Data) throws {
|
||||
let code = passphrase.withUnsafeBytes {
|
||||
sqlite3_key(sqliteConnection, $0.baseAddress, CInt($0.count))
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Changes the passphrase used by an SQLCipher encrypted database.
|
||||
public func changePassphrase(_ passphrase: String) throws {
|
||||
guard var data = passphrase.data(using: .utf8) else {
|
||||
throw DatabaseError(message: "invalid passphrase")
|
||||
}
|
||||
defer {
|
||||
data.resetBytes(in: 0..<data.count)
|
||||
}
|
||||
try changePassphrase(data)
|
||||
}
|
||||
|
||||
/// Changes the passphrase used by an SQLCipher encrypted database.
|
||||
public func changePassphrase(_ passphrase: Data) throws {
|
||||
// FIXME: sqlite3_rekey is discouraged.
|
||||
/// Returns the count of changes executed by one statement execution.
|
||||
func countChanges<T>(_ count: inout Int, forTable tableName: String, updates: () throws -> T) throws -> T {
|
||||
// Database.changesCount calls sqlite3_changes(), whose documentation says:
|
||||
//
|
||||
// https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320
|
||||
// > https://sqlite.org/c3ref/changes.html
|
||||
// > Changes to a view that are intercepted by INSTEAD OF triggers are not counted.
|
||||
//
|
||||
// > We (Zetetic) have been discouraging the use of sqlite3_rekey in
|
||||
// > favor of attaching a new database with the desired encryption
|
||||
// > options and using sqlcipher_export() to migrate the contents and
|
||||
// > schema of the original db into the new one:
|
||||
// > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/
|
||||
let code = passphrase.withUnsafeBytes {
|
||||
sqlite3_rekey(sqliteConnection, $0.baseAddress, CInt($0.count))
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: lastErrorMessage)
|
||||
// We want to support INSTEAD OF triggers, so we prefer to use
|
||||
// sqlite3_total_changes() for views.
|
||||
//
|
||||
// At the same time, FTS5 has sqlite3_total_changes() report changes
|
||||
// even when database is not changed (https://github.com/groue/GRDB.swift/issues/1820)
|
||||
//
|
||||
// Well, let's do our best:
|
||||
if try viewExists(tableName) {
|
||||
let prevCount = totalChangesCount
|
||||
let result = try updates()
|
||||
count = totalChangesCount - prevCount
|
||||
return result
|
||||
} else {
|
||||
let result = try updates()
|
||||
count = changesCount
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
extension Database {
|
||||
|
||||
@@ -1977,7 +2024,8 @@ extension Database {
|
||||
/// To set the busy mode of a database, use Configuration:
|
||||
///
|
||||
/// // Wait 1 second before failing with SQLITE_BUSY
|
||||
/// let configuration = Configuration(busyMode: .timeout(1))
|
||||
/// var configuration = Configuration()
|
||||
/// configuration.busyMode = .timeout(1)
|
||||
/// let dbQueue = try DatabaseQueue(path: ..., configuration: configuration)
|
||||
///
|
||||
/// Relevant SQLite documentation:
|
||||
@@ -2049,7 +2097,7 @@ extension Database {
|
||||
/// // CREATE TABLE player(
|
||||
/// // id INTEGER PRIMARY KEY,
|
||||
/// // name TEXT,
|
||||
/// // creationDate DATETIME,
|
||||
/// // creationDate DATETIME
|
||||
/// // )
|
||||
/// try db.create(table: "player") { t in
|
||||
/// t.primaryKey("id", .integer)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/// Describe the progress of a database backup.
|
||||
/// Describes the progress of a database backup.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/backup_finish.html>
|
||||
public struct DatabaseBackupProgress: Sendable {
|
||||
@@ -12,7 +12,7 @@ public struct DatabaseBackupProgress: Sendable {
|
||||
/// It is the result of the `sqlite3_backup_pagecount` function.
|
||||
public let totalPageCount: Int
|
||||
|
||||
/// The number of of backed up pages.
|
||||
/// The number of backed up pages.
|
||||
///
|
||||
/// It is equal to `totalPageCount - remainingPageCount`.
|
||||
public var completedPageCount: Int {
|
||||
@@ -21,7 +21,7 @@ public struct DatabaseBackupProgress: Sendable {
|
||||
|
||||
/// A boolean value indicating whether the backup is complete.
|
||||
///
|
||||
/// It is true if and only if the last call the `sqlite3_backup_step` has
|
||||
/// It is true if and only if the last call to `sqlite3_backup_step` has
|
||||
/// returned `SQLITE_DONE`.
|
||||
public let isCompleted: Bool
|
||||
}
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -53,12 +56,21 @@ public final class DatabaseCollation: Identifiable, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds the `xCompare` parameter of sqlite3_create_collation_v2
|
||||
/// <https://www.sqlite.org/c3ref/create_collation.html>
|
||||
typealias XCompare = @Sendable (
|
||||
_ length1: CInt,
|
||||
_ buffer1: UnsafeRawPointer,
|
||||
_ length2: CInt,
|
||||
_ buffer2: UnsafeRawPointer
|
||||
) -> CInt
|
||||
|
||||
/// The identifier of the collation.
|
||||
public var id: ID { ID(name: name) }
|
||||
|
||||
/// The name of the collation.
|
||||
public let name: String
|
||||
let function: @Sendable (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
|
||||
let xCompare: XCompare
|
||||
|
||||
/// Creates a collation.
|
||||
///
|
||||
@@ -69,27 +81,22 @@ public final class DatabaseCollation: Identifiable, Sendable {
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// db.add(collation: collation)
|
||||
/// try db.execute(sql: "CREATE TABLE file (name TEXT COLLATE localized_standard")
|
||||
/// try db.execute(sql: "CREATE TABLE file (name TEXT COLLATE localized_standard)")
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The collation name.
|
||||
/// - function: A function that compares two strings.
|
||||
public init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
|
||||
public convenience init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
|
||||
self.init(name, xCompare: { (length1, buffer1, length2, buffer2) in
|
||||
let string1 = String(decoding: UnsafeRawBufferPointer(start: buffer1, count: Int(length1)), as: UTF8.self)
|
||||
let string2 = String(decoding: UnsafeRawBufferPointer(start: buffer2, count: Int(length2)), as: UTF8.self)
|
||||
return CInt(function(string1, string2).rawValue)
|
||||
})
|
||||
}
|
||||
|
||||
init(_ name: String, xCompare: @escaping XCompare) {
|
||||
self.name = name
|
||||
self.function = { (length1, buffer1, length2, buffer2) in
|
||||
// Buffers are not C strings: they do not end with \0.
|
||||
let string1 = String(
|
||||
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped),
|
||||
length: Int(length1),
|
||||
encoding: .utf8,
|
||||
freeWhenDone: false)!
|
||||
let string2 = String(
|
||||
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped),
|
||||
length: Int(length2),
|
||||
encoding: .utf8,
|
||||
freeWhenDone: false)!
|
||||
return function(string1, string2)
|
||||
}
|
||||
self.xCompare = xCompare
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -26,7 +29,7 @@ public struct ResultCode: RawRepresentable, Equatable {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY
|
||||
/// let resultCode = ResultCode.SQLITE_CONSTRAINT_FOREIGNKEY
|
||||
/// resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true
|
||||
/// ```
|
||||
public var primaryResultCode: ResultCode {
|
||||
@@ -285,7 +288,7 @@ public struct DatabaseError: Error {
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch let error as DatabaseError where error.resultCode == .SQL_CONSTRAINT {
|
||||
/// } catch let error as DatabaseError where error.resultCode == .SQLITE_CONSTRAINT {
|
||||
/// // A constraint error
|
||||
/// }
|
||||
/// ```
|
||||
@@ -295,7 +298,7 @@ public struct DatabaseError: Error {
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch DatabaseError.SQL_CONSTRAINT {
|
||||
/// } catch DatabaseError.SQLITE_CONSTRAINT {
|
||||
/// // A constraint error
|
||||
/// }
|
||||
/// ```
|
||||
@@ -350,10 +353,10 @@ public struct DatabaseError: Error {
|
||||
///
|
||||
/// - parameters:
|
||||
/// - resultCode: A ResultCode (defaults to .SQLITE_ERROR).
|
||||
/// - message: An eventual error message. If nil, the error message is
|
||||
/// - message: An optional error message. If nil, the error message is
|
||||
/// derived from the result code.
|
||||
/// - sql: An eventual SQL string.
|
||||
/// - arguments: Eventual statement arguments.
|
||||
/// - sql: An optional SQL string.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - publicStatementArguments: If false (the default), statement
|
||||
/// arguments are not visible in the error's ``description`` property.
|
||||
public init(
|
||||
@@ -372,7 +375,7 @@ public struct DatabaseError: Error {
|
||||
|
||||
/// Creates a Database Error with a raw CInt result code.
|
||||
///
|
||||
/// This initializer is not public because library user is not supposed to
|
||||
/// This initializer is not public because library users are not supposed to
|
||||
/// be exposed to raw result codes.
|
||||
@usableFromInline
|
||||
init(resultCode: CInt, message: String? = nil, sql: String? = nil) {
|
||||
@@ -384,7 +387,7 @@ public struct DatabaseError: Error {
|
||||
|
||||
/// Creates a Database Error with a raw CInt result code.
|
||||
///
|
||||
/// This initializer is not public because library user is not supposed to
|
||||
/// This initializer is not public because library users are not supposed to
|
||||
/// be exposed to raw result codes.
|
||||
@usableFromInline
|
||||
init(
|
||||
@@ -556,7 +559,7 @@ extension DatabaseError: CustomStringConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// SQLite error 19: NOT NULL constraint failed: player.score
|
||||
/// - while executing `UPDATE player SET score = ? WHERE email = ?
|
||||
/// - 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.
|
||||
@@ -579,7 +582,7 @@ extension DatabaseError: CustomStringConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// SQLite error 19: NOT NULL constraint failed: player.score
|
||||
/// - while executing `UPDATE player SET score = ? WHERE email = ?
|
||||
/// - 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,
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
/// A custom SQL function or aggregate.
|
||||
///
|
||||
/// ## Topics
|
||||
@@ -74,7 +79,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// - argumentCount: The number of arguments of the function. If
|
||||
/// omitted, or nil, the function accepts any number of arguments.
|
||||
/// - pure: Whether the function is "pure", which means that its results
|
||||
/// only depends on its inputs. When a function is pure, SQLite has
|
||||
/// only depend on its inputs. When a function is pure, SQLite has
|
||||
/// the opportunity to perform additional optimizations. Default value
|
||||
/// is false.
|
||||
/// - function: A function that takes an array of ``DatabaseValue``
|
||||
@@ -82,20 +87,45 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// such as `Int`, `String`, `Date`, etc. The array is guaranteed to
|
||||
/// have exactly `argumentCount` elements, provided `argumentCount` is
|
||||
/// not nil.
|
||||
public init(
|
||||
public convenience init(
|
||||
_ name: String,
|
||||
argumentCount: Int? = nil,
|
||||
pure: Bool = false,
|
||||
function: @escaping @Sendable ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
|
||||
{
|
||||
self.init(name, argumentCount: argumentCount, pure: pure) { (argc, argv, context) in
|
||||
let arguments = (0..<Int(argc)).map { index in
|
||||
DatabaseValue(sqliteValue: argv[index]!)
|
||||
}
|
||||
let result = try function(arguments)
|
||||
switch result?.databaseValue.storage ?? .null {
|
||||
case .null:
|
||||
sqlite3_result_null(context)
|
||||
case .int64(let int64):
|
||||
sqlite3_result_int64(context, int64)
|
||||
case .double(let double):
|
||||
sqlite3_result_double(context, double)
|
||||
case .string(var string):
|
||||
string.withSQLiteText {
|
||||
sqlite3_result_text(context, $0, $1, SQLITE_TRANSIENT)
|
||||
}
|
||||
case .blob(let data):
|
||||
data.withUnsafeBytes {
|
||||
sqlite3_result_blob(context, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
init(
|
||||
_ name: String,
|
||||
argumentCount: Int? = nil,
|
||||
pure: Bool = false,
|
||||
xFunc: @escaping XFunc)
|
||||
{
|
||||
self.id = ID(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
|
||||
self.isPure = pure
|
||||
self.kind = .function { (argc, argv) in
|
||||
let arguments = (0..<Int(argc)).map { index in
|
||||
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
|
||||
}
|
||||
return try function(arguments)
|
||||
}
|
||||
self.kind = .function(xFunc)
|
||||
}
|
||||
|
||||
/// Creates an SQL aggregate function.
|
||||
@@ -137,7 +167,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// - argumentCount: The number of arguments of the aggregate. If
|
||||
/// omitted, or nil, the aggregate accepts any number of arguments.
|
||||
/// - pure: Whether the aggregate is "pure", which means that its
|
||||
/// results only depends on its inputs. When an aggregate is pure,
|
||||
/// results only depend on its inputs. When an aggregate is pure,
|
||||
/// SQLite has the opportunity to perform additional optimizations.
|
||||
/// Default value is false.
|
||||
/// - aggregate: A type that implements the ``DatabaseAggregate``
|
||||
@@ -173,13 +203,20 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// }
|
||||
/// return int * int
|
||||
/// }
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// try dbQueue.read { db in
|
||||
/// db.add(function: square)
|
||||
///
|
||||
/// // SELECT square(score) FROM player
|
||||
/// let squaredScores = let Player
|
||||
/// .select(square(Column("score")), as: Int.self)
|
||||
/// let squaredScores = try Player
|
||||
/// .select({ square($0.score) }, as: Int.self)
|
||||
/// .fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
@@ -249,11 +286,10 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
private class FunctionDefinition {
|
||||
let compute: (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?
|
||||
init(compute: @escaping (CInt, UnsafeMutablePointer<OpaquePointer?>?)
|
||||
throws -> (any DatabaseValueConvertible)?)
|
||||
let xFunc: XFunc
|
||||
init(xFunc: @escaping XFunc)
|
||||
{
|
||||
self.compute = compute
|
||||
self.xFunc = xFunc
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,11 +312,19 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds the `xFunc` parameter of sqlite3_create_function_v2
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
typealias XFunc = @Sendable (
|
||||
_ argc: CInt,
|
||||
_ argv: UnsafeMutablePointer<OpaquePointer?>,
|
||||
_ context: OpaquePointer?
|
||||
) throws -> Void
|
||||
|
||||
/// A function kind: an "SQL function" or an "aggregate".
|
||||
/// See <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
private enum Kind: Sendable {
|
||||
/// A regular function: SELECT f(1)
|
||||
case function(@Sendable (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?)
|
||||
case function(XFunc)
|
||||
|
||||
/// An aggregate: SELECT f(foo) FROM bar GROUP BY baz
|
||||
case aggregate(@Sendable () -> any DatabaseAggregate)
|
||||
@@ -289,8 +333,8 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
var definition: AnyObject {
|
||||
switch self {
|
||||
case .function(let compute):
|
||||
return FunctionDefinition(compute: compute)
|
||||
case .function(let xFunc):
|
||||
return FunctionDefinition(xFunc: xFunc)
|
||||
case .aggregate(let makeAggregate):
|
||||
return AggregateDefinition(makeAggregate: makeAggregate)
|
||||
}
|
||||
@@ -305,9 +349,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
.fromOpaque(sqlite3_user_data(sqliteContext))
|
||||
.takeUnretainedValue()
|
||||
do {
|
||||
try DatabaseFunction.report(
|
||||
result: definition.compute(argc, argv),
|
||||
in: sqliteContext)
|
||||
try definition.xFunc(argc, argv.unsafelyUnwrapped, sqliteContext)
|
||||
} catch {
|
||||
DatabaseFunction.report(error: error, in: sqliteContext)
|
||||
}
|
||||
@@ -407,8 +449,10 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
sqlite3_result_int64(sqliteContext, int64)
|
||||
case .double(let double):
|
||||
sqlite3_result_double(sqliteContext, double)
|
||||
case .string(let string):
|
||||
sqlite3_result_text(sqliteContext, string, -1, SQLITE_TRANSIENT)
|
||||
case .string(var string):
|
||||
string.withSQLiteText {
|
||||
sqlite3_result_text(sqliteContext, $0, $1, SQLITE_TRANSIENT)
|
||||
}
|
||||
case .blob(let data):
|
||||
data.withUnsafeBytes {
|
||||
sqlite3_result_blob(sqliteContext, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
|
||||
@@ -457,7 +501,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
|
||||
/// }
|
||||
/// ```
|
||||
public protocol DatabaseAggregate {
|
||||
public protocol DatabaseAggregate: GRDBSendableMetatype {
|
||||
/// Creates an aggregate.
|
||||
///
|
||||
/// A new instance is created for each aggregation.
|
||||
|
||||
@@ -59,7 +59,7 @@ public final class DatabasePool {
|
||||
|
||||
// Readers can't allow dangling transactions because there's no
|
||||
// guarantee that one can get the same reader later in order to close
|
||||
// an opened transaction.
|
||||
// an open transaction.
|
||||
readerConfiguration.allowsUnsafeTransactions = false
|
||||
|
||||
readerPool = Pool(
|
||||
@@ -149,7 +149,7 @@ extension DatabasePool {
|
||||
|
||||
// MARK: - Memory management
|
||||
|
||||
/// Frees as much memory as possible, by disposing non-essential memory.
|
||||
/// Frees as much memory as possible, by disposing of non-essential memory.
|
||||
///
|
||||
/// This method is synchronous, and blocks the current thread until all
|
||||
/// database accesses are completed.
|
||||
@@ -178,14 +178,14 @@ extension DatabasePool {
|
||||
// documented.
|
||||
//
|
||||
// Without the barrier, connections would only close _eventually_ (after
|
||||
// their eventual concurrent jobs have completed).
|
||||
// their concurrent jobs have completed).
|
||||
readerPool?.barrier {
|
||||
readerPool?.removeAll()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Eventually frees as much memory as possible, by disposing
|
||||
/// Eventually frees as much memory as possible, by disposing of
|
||||
/// non-essential memory.
|
||||
///
|
||||
/// This method eventually closes all read-only connections, unless the
|
||||
@@ -352,40 +352,29 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
|
||||
public func read<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
let dbAccess = CancellableDatabaseAccess()
|
||||
return try await dbAccess.withCancellableContinuation { continuation in
|
||||
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(.reuse)
|
||||
}
|
||||
do {
|
||||
let result = try dbAccess.inDatabase(db) {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
return try value(db)
|
||||
}
|
||||
continuation.resume(returning: result)
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
return try await readerPool.get { reader in
|
||||
try await reader.execute { db in
|
||||
defer {
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
}
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
return try value(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -403,7 +392,14 @@ extension DatabasePool: DatabaseReader {
|
||||
// Second async jump because that's how `Pool.async` has to be used.
|
||||
reader.async { db in
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
do {
|
||||
@@ -436,35 +432,16 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
let dbAccess = CancellableDatabaseAccess()
|
||||
return try await dbAccess.withCancellableContinuation { continuation in
|
||||
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(.reuse)
|
||||
}
|
||||
do {
|
||||
let result = try dbAccess.inDatabase(db) {
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
return try value(db)
|
||||
}
|
||||
continuation.resume(returning: result)
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
return try await readerPool.get { reader in
|
||||
try await reader.execute { db in
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
return try value(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -528,8 +505,8 @@ extension DatabasePool: DatabaseReader {
|
||||
/// any transaction. You'll get a fatal error otherwise.
|
||||
///
|
||||
/// The `value` function is guaranteed to see the database in the last
|
||||
/// committed state at the moment this method is called. Eventual
|
||||
/// concurrent database updates are not visible from the function.
|
||||
/// committed state at the moment this method is called. Concurrent
|
||||
/// database updates are not visible from the function.
|
||||
///
|
||||
/// This method returns as soon as the isolation guarantee described above
|
||||
/// has been established.
|
||||
@@ -540,7 +517,7 @@ extension DatabasePool: DatabaseReader {
|
||||
/// ```swift
|
||||
/// try writer.asyncWriteWithoutTransaction { db in
|
||||
/// // Delete all players
|
||||
/// try Player.deleteAll()
|
||||
/// try Player.deleteAll(db)
|
||||
///
|
||||
/// // Count players concurrently
|
||||
/// writer.asyncConcurrentRead { dbResult in
|
||||
@@ -584,7 +561,14 @@ extension DatabasePool: DatabaseReader {
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
reader.async { db in
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
do {
|
||||
@@ -662,7 +646,7 @@ extension DatabasePool: DatabaseReader {
|
||||
/// After this method is called, read-only database access methods will use
|
||||
/// new SQLite connections.
|
||||
///
|
||||
/// Eventual concurrent read-only accesses are not interrupted, and
|
||||
/// Concurrent read-only accesses are not interrupted, and
|
||||
/// proceed until completion.
|
||||
///
|
||||
/// - This method closes all read-only connections, even if the
|
||||
@@ -675,6 +659,10 @@ extension DatabasePool: DatabaseReader {
|
||||
/// Returns a reader that can be used from the current dispatch queue,
|
||||
/// if any.
|
||||
private var currentReader: SerializedDatabase? {
|
||||
if SchedulingWatchdog.current == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
guard let readerPool else {
|
||||
return nil
|
||||
}
|
||||
@@ -700,7 +688,7 @@ extension DatabasePool: DatabaseReader {
|
||||
|
||||
// MARK: - WAL Snapshot Transactions
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
/// Returns a long-lived WAL snapshot transaction on a reader connection.
|
||||
func walSnapshotTransaction() throws -> WALSnapshotTransaction {
|
||||
guard let readerPool else {
|
||||
@@ -802,7 +790,7 @@ extension DatabasePool: DatabaseWriter {
|
||||
}
|
||||
|
||||
public func writeWithoutTransaction<T: Sendable>(
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writer.execute(updates)
|
||||
}
|
||||
@@ -818,22 +806,32 @@ extension DatabasePool: DatabaseWriter {
|
||||
}
|
||||
|
||||
public func barrierWriteWithoutTransaction<T: Sendable>(
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
let dbAccess = CancellableDatabaseAccess()
|
||||
return try await dbAccess.withCancellableContinuation { continuation in
|
||||
asyncBarrierWriteWithoutTransaction { dbResult in
|
||||
do {
|
||||
try dbAccess.checkCancellation()
|
||||
let db = try dbResult.get()
|
||||
let result = try dbAccess.inDatabase(db) {
|
||||
try updates(db)
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
// Pool.barrier does not support async calls (yet?).
|
||||
// So we perform cancellation checks just as in
|
||||
// the async version of SerializedDatabase.execute().
|
||||
let cancelMutex = Mutex<(@Sendable () -> Void)?>(nil)
|
||||
return try await withTaskCancellationHandler {
|
||||
try Task.checkCancellation()
|
||||
return try await readerPool.barrier {
|
||||
try Task.checkCancellation()
|
||||
return try writer.sync { db in
|
||||
defer {
|
||||
cancelMutex.store(nil)
|
||||
db.uncancel()
|
||||
}
|
||||
continuation.resume(returning: result)
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
cancelMutex.store(db.cancel)
|
||||
try Task.checkCancellation()
|
||||
return try updates(db)
|
||||
}
|
||||
}
|
||||
} onCancel: {
|
||||
cancelMutex.withLock { $0?() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -854,10 +852,10 @@ extension DatabasePool: DatabaseWriter {
|
||||
/// The `updates` function runs in the writer dispatch queue, serialized
|
||||
/// with all database updates.
|
||||
///
|
||||
/// If `updates` throws an error, the transaction is rollbacked and the
|
||||
/// If `updates` throws an error, the transaction is rolled back and the
|
||||
/// error is rethrown. If it returns
|
||||
/// ``Database/TransactionCompletion/rollback``, the transaction is also
|
||||
/// rollbacked, but no error is thrown.
|
||||
/// rolled back, but no error is thrown.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -904,15 +902,15 @@ extension DatabasePool {
|
||||
|
||||
// MARK: - Snapshots
|
||||
|
||||
/// Creates a database snapshot that serializes accesses to an unchanging
|
||||
/// Creates a database snapshot that serializes accesses to unchanging
|
||||
/// database content, as it exists at the moment the snapshot is created.
|
||||
///
|
||||
/// It is a programmer error to create a snapshot from the writer dispatch
|
||||
/// queue when a transaction is opened:
|
||||
/// queue when a transaction is open:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbPool.write { db in
|
||||
/// try Player.deleteAll()
|
||||
/// try Player.deleteAll(db)
|
||||
///
|
||||
/// // fatal error: makeSnapshot() must not be called from inside a transaction
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
@@ -929,7 +927,7 @@ extension DatabasePool {
|
||||
/// let snapshot = try dbPool.makeSnapshot() // OK
|
||||
///
|
||||
/// try db.inTransaction {
|
||||
/// try Player.deleteAll()
|
||||
/// try Player.deleteAll(db)
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
@@ -956,8 +954,8 @@ extension DatabasePool {
|
||||
purpose: "snapshot.\(databaseSnapshotCountMutex.increment())")
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
/// Creates a database snapshot that allows concurrent accesses to an
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
/// Creates a database snapshot that allows concurrent accesses to
|
||||
/// unchanging database content, as it exists at the moment the snapshot
|
||||
/// is created.
|
||||
///
|
||||
|
||||
@@ -234,7 +234,7 @@ extension DatabaseQueue: DatabaseReader {
|
||||
}
|
||||
|
||||
public func read<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writer.execute { db in
|
||||
try db.isolated(readOnly: true) {
|
||||
@@ -248,8 +248,14 @@ extension DatabaseQueue: DatabaseReader {
|
||||
) {
|
||||
writer.async { db in
|
||||
defer {
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.commit()
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
|
||||
@@ -272,7 +278,7 @@ extension DatabaseQueue: DatabaseReader {
|
||||
}
|
||||
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writer.execute(value)
|
||||
}
|
||||
@@ -296,8 +302,14 @@ extension DatabaseQueue: DatabaseReader {
|
||||
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
|
||||
|
||||
defer {
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.commit()
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
|
||||
@@ -345,10 +357,10 @@ extension DatabaseQueue: DatabaseWriter {
|
||||
/// The `updates` function runs in the writer dispatch queue, serialized
|
||||
/// with all database updates.
|
||||
///
|
||||
/// If `updates` throws an error, the transaction is rollbacked and the
|
||||
/// If `updates` throws an error, the transaction is rolled back and the
|
||||
/// error is rethrown. If it returns
|
||||
/// ``Database/TransactionCompletion/rollback``, the transaction is also
|
||||
/// rollbacked, but no error is thrown.
|
||||
/// rolled back, but no error is thrown.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -385,7 +397,7 @@ extension DatabaseQueue: DatabaseWriter {
|
||||
}
|
||||
|
||||
public func writeWithoutTransaction<T: Sendable>(
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writer.execute(updates)
|
||||
}
|
||||
@@ -396,7 +408,7 @@ extension DatabaseQueue: DatabaseWriter {
|
||||
}
|
||||
|
||||
public func barrierWriteWithoutTransaction<T: Sendable>(
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writer.execute(updates)
|
||||
}
|
||||
|
||||
@@ -22,14 +22,14 @@ import Dispatch
|
||||
/// ### Reading from the Database
|
||||
///
|
||||
/// - ``read(_:)-3806d``
|
||||
/// - ``read(_:)-4d1da``
|
||||
/// - ``read(_:)-5mfwu``
|
||||
/// - ``readPublisher(receiveOn:value:)``
|
||||
/// - ``asyncRead(_:)``
|
||||
///
|
||||
/// ### Unsafe Methods
|
||||
///
|
||||
/// - ``unsafeRead(_:)-5i7tf``
|
||||
/// - ``unsafeRead(_:)-5gsav``
|
||||
/// - ``unsafeRead(_:)-90w0p``
|
||||
/// - ``unsafeReentrantRead(_:)``
|
||||
/// - ``asyncUnsafeRead(_:)``
|
||||
///
|
||||
@@ -74,12 +74,12 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// every future database access will throw a ``DatabaseError`` of
|
||||
/// code `SQLITE_MISUSE`.
|
||||
///
|
||||
/// Otherwise, there exists concurrent database accesses or living prepared
|
||||
/// Otherwise, there exist concurrent database accesses or living prepared
|
||||
/// statements that prevent the database from closing, and this method
|
||||
/// throws a ``DatabaseError`` of code `SQLITE_BUSY`.
|
||||
/// See <https://www.sqlite.org/c3ref/close.html> for more information.
|
||||
///
|
||||
/// After an error has been thrown, the database may still be opened, and
|
||||
/// After an error has been thrown, the database may still be open, and
|
||||
/// you can keep on accessing it. It may also remain in a "zombie" state,
|
||||
/// in which case it will throw `SQLITE_MISUSE` for all future
|
||||
/// database accesses.
|
||||
@@ -168,7 +168,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// ```
|
||||
///
|
||||
/// Database operations are isolated in a transaction: they do not see
|
||||
/// changes performed by eventual concurrent writes (even writes performed
|
||||
/// changes performed by concurrent writes (even writes performed
|
||||
/// by other processes).
|
||||
///
|
||||
/// The database connection is read-only: attempts to write throw a
|
||||
@@ -200,7 +200,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// ```
|
||||
///
|
||||
/// Database operations are isolated in a transaction: they do not see
|
||||
/// changes performed by eventual concurrent writes (even writes performed
|
||||
/// changes performed by concurrent writes (even writes performed
|
||||
/// by other processes).
|
||||
///
|
||||
/// The database connection is read-only: attempts to write throw a
|
||||
@@ -215,7 +215,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// database access, or the error thrown by `value`, or
|
||||
/// `CancellationError` if the task is cancelled.
|
||||
func read<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T
|
||||
|
||||
/// Schedules read-only database operations for execution, and
|
||||
@@ -235,7 +235,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// ```
|
||||
///
|
||||
/// Database operations are isolated in a transaction: they do not see
|
||||
/// changes performed by eventual concurrent writes (even writes performed
|
||||
/// changes performed by concurrent writes (even writes performed
|
||||
/// by other processes).
|
||||
///
|
||||
/// The database connection is read-only: attempts to write throw a
|
||||
@@ -319,7 +319,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// database access, or the error thrown by `value`, or
|
||||
/// `CancellationError` if the task is cancelled.
|
||||
func unsafeRead<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T
|
||||
|
||||
/// Schedules database operations for execution, and returns immediately.
|
||||
@@ -517,7 +517,7 @@ extension DatabaseReader {
|
||||
/// ```
|
||||
///
|
||||
/// Database operations are isolated in a transaction: they do not see
|
||||
/// changes performed by eventual concurrent writes (even writes performed
|
||||
/// changes performed by concurrent writes (even writes performed
|
||||
/// by other processes).
|
||||
///
|
||||
/// The database connection is read-only: attempts to write throw a
|
||||
@@ -652,7 +652,7 @@ extension AnyDatabaseReader: DatabaseReader {
|
||||
}
|
||||
|
||||
public func read<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.read(value)
|
||||
}
|
||||
@@ -669,7 +669,7 @@ extension AnyDatabaseReader: DatabaseReader {
|
||||
}
|
||||
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.unsafeRead(value)
|
||||
}
|
||||
@@ -696,7 +696,7 @@ extension AnyDatabaseReader: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
/// A type that sees an unchanging database content.
|
||||
/// A type that sees unchanging database content.
|
||||
///
|
||||
/// Do not declare new conformances to `DatabaseSnapshotReader`. Only the
|
||||
/// built-in conforming types are valid.
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
/// |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | |
|
||||
/// |x|x|x|x| |x| | | | | | | | | | | | | | | | | | |
|
||||
///
|
||||
/// It is dedicated to help ``TransactionObserver`` types detect impactful
|
||||
/// It is dedicated to helping ``TransactionObserver`` types detect impactful
|
||||
/// database changes.
|
||||
///
|
||||
/// You get `DatabaseRegion` instances from a ``DatabaseRegionConvertible``
|
||||
@@ -41,7 +41,8 @@
|
||||
/// - ``isModified(byEventsOfKind:)``
|
||||
/// - ``isModified(by:)``
|
||||
public struct DatabaseRegion: Sendable {
|
||||
private let tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
|
||||
/// Nil means that the region is the full database.
|
||||
private var tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
|
||||
|
||||
private init(tableRegions: [CaseInsensitiveIdentifier: TableRegion]?) {
|
||||
self.tableRegions = tableRegions
|
||||
@@ -77,19 +78,26 @@ public struct DatabaseRegion: Sendable {
|
||||
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: nil)])
|
||||
}
|
||||
|
||||
/// Full columns in a table: (some columns in a table) × (all rows)
|
||||
/// Some columns from all rows in a table.
|
||||
init(table: String, columns: Set<String>) {
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
let columns = Set(columns.map(CaseInsensitiveIdentifier.init))
|
||||
self.init(tableRegions: [table: TableRegion(columns: columns, rowIds: nil)])
|
||||
}
|
||||
|
||||
/// Full rows in a table: (all columns in a table) × (some rows)
|
||||
/// All columns from some rows in a table.
|
||||
init(table: String, rowIds: Set<Int64>) {
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: rowIds)])
|
||||
}
|
||||
|
||||
/// Some columns from some rows in a table.
|
||||
init(table: String, columns: Set<String>, rowIds: Set<Int64>) {
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
let columns = Set(columns.map(CaseInsensitiveIdentifier.init))
|
||||
self.init(tableRegions: [table: TableRegion(columns: columns, rowIds: rowIds)])
|
||||
}
|
||||
|
||||
/// Returns the intersection of this region and the given one.
|
||||
///
|
||||
/// This method is not public because there is no known public use case for
|
||||
@@ -162,6 +170,22 @@ public struct DatabaseRegion: Sendable {
|
||||
self = union(other)
|
||||
}
|
||||
|
||||
/// Inserts all columns and rows from the given table.
|
||||
mutating func insert(table: String) {
|
||||
guard tableRegions != nil else { return }
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
tableRegions![table, default: TableRegion()].insertAllRowsAndColumns()
|
||||
}
|
||||
|
||||
/// Inserts the specified column and all rows from the given table.
|
||||
mutating func insert(table: String, column: String) {
|
||||
assert(!column.isEmpty)
|
||||
guard tableRegions != nil else { return }
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
let column = CaseInsensitiveIdentifier(rawValue: column)
|
||||
tableRegions![table, default: TableRegion(columns: [column])].insertAllRowsAndColumn(column)
|
||||
}
|
||||
|
||||
/// Returns a region suitable for database observation
|
||||
func observableRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
// SQLite does not expose schema changes to the
|
||||
@@ -256,8 +280,8 @@ extension DatabaseRegion {
|
||||
}
|
||||
} else {
|
||||
// full database
|
||||
return try db.schemaIdentifiers().flatMap { schemaIdentifier in
|
||||
let schema = try db.schema(schemaIdentifier)
|
||||
return try db.fetchSchemaIdentifiers().flatMap { schemaID in
|
||||
let schema = try db.schema(schemaID)
|
||||
return try schema.objects
|
||||
.filter { $0.type == .table }
|
||||
.flatMap { table in
|
||||
@@ -370,6 +394,18 @@ private struct TableRegion: Equatable {
|
||||
return TableRegion(columns: columnsUnion, rowIds: rowIdsUnion)
|
||||
}
|
||||
|
||||
mutating func insertAllRowsAndColumns() {
|
||||
rowIds = nil
|
||||
columns = nil
|
||||
}
|
||||
|
||||
mutating func insertAllRowsAndColumn(_ column: CaseInsensitiveIdentifier) {
|
||||
rowIds = nil
|
||||
if columns != nil {
|
||||
columns!.insert(column)
|
||||
}
|
||||
}
|
||||
|
||||
func contains(rowID: Int64) -> Bool {
|
||||
guard let rowIds else {
|
||||
return true
|
||||
|
||||
@@ -59,7 +59,7 @@ extension DatabaseRegionObservation {
|
||||
/// ```swift
|
||||
/// let observation = DatabaseRegionObservation(tracking: Player.all())
|
||||
///
|
||||
/// let cancellable = try observation.start(in: dbQueue) { error in
|
||||
/// let cancellable = observation.start(in: dbQueue) { error in
|
||||
/// // handle error
|
||||
/// } onChange: { (db: Database) in
|
||||
/// print("A modification of the player table has just been committed.")
|
||||
@@ -201,7 +201,11 @@ extension DatabasePublishers {
|
||||
self.observation = observation
|
||||
}
|
||||
|
||||
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
|
||||
public func receive<S>(subscriber: S)
|
||||
where S: Subscriber & GRDBSendableMetatype,
|
||||
Failure == S.Failure,
|
||||
Output == S.Input
|
||||
{
|
||||
let subscription = DatabaseRegionSubscription(
|
||||
writer: writer,
|
||||
observation: observation,
|
||||
@@ -212,7 +216,7 @@ extension DatabasePublishers {
|
||||
|
||||
private class DatabaseRegionSubscription<Downstream>:
|
||||
Subscription, @unchecked Sendable
|
||||
where Downstream: Subscriber,
|
||||
where Downstream: Subscriber & GRDBSendableMetatype,
|
||||
Downstream.Failure == Error,
|
||||
Downstream.Input == Database
|
||||
{
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
/// A type that provides information about the database schema.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// The use case for a custom schema source is to enable GRDB features that
|
||||
/// would not work with the built-in schema introspection provided
|
||||
/// by SQLite.
|
||||
///
|
||||
/// For example, if your database schema contains a view and you wish to use
|
||||
/// GRDB features that need a primary key, such as the
|
||||
/// ``FetchableRecord/find(_:id:)`` record method, or the persistence
|
||||
/// methods of the ``PersistableRecord`` protocol, then use a schema source
|
||||
/// that implements the ``columnsForPrimaryKey(_:inView:)`` method. See
|
||||
/// <doc:ViewRecords> for a detailed guide about such views.
|
||||
///
|
||||
/// ## Enabling a Schema Source
|
||||
///
|
||||
/// To enable a schema source in a database connection, configure its
|
||||
/// ``Configuration/schemaSource``:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct MySchemaSource: DatabaseSchemaSource { ... }
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.schemaSource = MySchemaSource()
|
||||
/// let dbQueue = try DatabaseQueue(path: "/path/to/db.sqlite", configuration: config)
|
||||
/// ```
|
||||
///
|
||||
/// ## Schema Sources and Migrations
|
||||
///
|
||||
/// By default, schema sources are disabled during <doc:Migrations>. In
|
||||
/// migrations that need a schema source, you can use
|
||||
/// ``Database/withSchemaSource(_:execute:)``:
|
||||
///
|
||||
/// ```swift
|
||||
/// migrator.registerMigration("My migration") { db in
|
||||
/// // No schema source is enabled at this point.
|
||||
/// try db.withSchemaSource(MySchemaSource()) {
|
||||
/// // Here the provided schema source is in effect.
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Keep in mind that **a good migration is a migration that is never
|
||||
/// modified once it has shipped**: check
|
||||
/// <doc:Migrations#Good-Practices-for-Defining-Migrations>.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Customizing the Database Schema
|
||||
///
|
||||
/// - ``columnsForPrimaryKey(_:inView:)``
|
||||
///
|
||||
/// ### Chaining Schema Sources
|
||||
///
|
||||
/// - ``then(_:)``
|
||||
public protocol DatabaseSchemaSource: Sendable {
|
||||
/// Returns the names of the columns for the primary key in the
|
||||
/// provided database view.
|
||||
///
|
||||
/// Return `nil` if no customization should happen. Return an empty
|
||||
/// array to specify that the view has no primary key. The default
|
||||
/// implementation returns `nil`.
|
||||
///
|
||||
/// In your implementation, make sure that the returned columns define
|
||||
/// a genuine **primary key**:
|
||||
///
|
||||
/// - All columns exist in the provided view.
|
||||
/// - The set of columns reliably identifies and distinguishes between
|
||||
/// each individual row in the view.
|
||||
/// - No column contains NULL values.
|
||||
///
|
||||
/// It is a programmer error with undefined consequences to violate
|
||||
/// those requirements.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // A schema source that specifies that all views are identified by
|
||||
/// // their "id" column:
|
||||
/// struct MySchemaSource: DatabaseSchemaSource {
|
||||
/// func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
|
||||
/// ["id"]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // A database connection configured with the schema source.
|
||||
/// var config = Configuration()
|
||||
/// config.schemaSource = MySchemaSource()
|
||||
/// let dbQueue = try DatabaseQueue(path: "/path/to/db.sqlite", configuration: config)
|
||||
///
|
||||
/// // A record type that is decoded from a view.
|
||||
/// struct Player: Decodable, Identifiable, FetchableRecord {
|
||||
/// static let databaseTableName = "playerView"
|
||||
/// var id: String
|
||||
/// var name: String
|
||||
/// }
|
||||
///
|
||||
/// // Thanks to the schema source, we can fetch players by id:
|
||||
/// let player = try dbQueue.read { db in
|
||||
/// try Player.find(db, id: "alice")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ### Schema Sources in Libraries
|
||||
///
|
||||
/// When you are developing a schema source for a library, some extra
|
||||
/// care is necessary whenever the database file is owned by the users
|
||||
/// of your library. Your users may define views for their own purposes,
|
||||
/// and your library knows nothing about the possible primary key of
|
||||
/// those views.
|
||||
///
|
||||
/// In this case, make your schema source `public`, and have this method
|
||||
/// return `nil` for those unknown views. If needed, use the `db`
|
||||
/// argument and query the database schema with
|
||||
/// <doc:DatabaseSchemaIntrospection> methods.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // A well-behaved schema source defined by a library is public
|
||||
/// // and returns nil for unknown views.
|
||||
/// public struct MyLibrarySchemaSource: DatabaseSchemaSource {
|
||||
/// public func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
|
||||
/// if view.name == "playerView" {
|
||||
/// // This is a view managed by my library:
|
||||
/// return ["id"]
|
||||
/// } else if try db.tableExists(view.name + "MyLibrary") {
|
||||
/// // This is a view managed by my library:
|
||||
/// return ["uuid"]
|
||||
/// } else {
|
||||
/// // Not a view managed by my library:
|
||||
/// // don't mess with user's schema
|
||||
/// return nil
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// With such a setup, your user will be able to deal with their
|
||||
/// own views, by chaining your schema source with other ones
|
||||
/// (see ``DatabaseSchemaSource/then(_:)``):
|
||||
///
|
||||
/// ```swift
|
||||
/// // Application code
|
||||
/// import MyLibrary
|
||||
/// import GRDB
|
||||
///
|
||||
/// let myLibrarySchemaSource = MyLibrarySchemaSource()
|
||||
/// let customSchemaSource = TheirCustomSchemaSource()
|
||||
/// let schemaSource = myLibrarySchemaSource.then(customSchemaSource)
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.schemaSource = schemaSource
|
||||
/// let dbQueue = try DatabaseQueue(path: "...", configuration: config)
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - db: A database connection.
|
||||
/// - view: The identifier of a database view.
|
||||
func columnsForPrimaryKey(
|
||||
_ db: Database,
|
||||
inView view: DatabaseObjectID
|
||||
) throws -> [String]?
|
||||
}
|
||||
|
||||
extension DatabaseSchemaSource {
|
||||
public func columnsForPrimaryKey(
|
||||
_ db: Database,
|
||||
inView view: DatabaseObjectID
|
||||
) throws -> [String]? {
|
||||
nil
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Combined2SchemaSource
|
||||
|
||||
extension DatabaseSchemaSource {
|
||||
/// Returns a schema source that queries `other` when this source does
|
||||
/// not perform a customization.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let schemaSource1 = SomeSchemaSource()
|
||||
/// let schemaSource2 = AnotherSchemaSource()
|
||||
/// let schemaSource = schemaSource1.then(schemaSource2)
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.schemaSource = schemaSource
|
||||
/// let dbQueue = try DatabaseQueue(path: "...", configuration: config)
|
||||
/// ```
|
||||
public func then(_ other: some DatabaseSchemaSource) -> some DatabaseSchemaSource {
|
||||
Chained2SchemaSource(first: self, second: other)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: move to parameter packs eventually. Parameter packs in generic types
|
||||
// are only available in macOS 14.0.0 or newer.
|
||||
// This schema source is designed to tame bad citizens that customize tables
|
||||
// and views they do not own (such as insufficienly robust schema sources
|
||||
// exposed by external libraries). We should NEVER MERGE the results of the
|
||||
// schema sources.
|
||||
struct Chained2SchemaSource<Source1, Source2>: DatabaseSchemaSource
|
||||
where Source1: DatabaseSchemaSource,
|
||||
Source2: DatabaseSchemaSource
|
||||
{
|
||||
var first: Source1
|
||||
var second: Source2
|
||||
|
||||
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
|
||||
if let result = try first.columnsForPrimaryKey(db, inView: view) { return result }
|
||||
if let result = try second.columnsForPrimaryKey(db, inView: view) { return result }
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
import Dispatch
|
||||
|
||||
/// A database connection that serializes accesses to an unchanging
|
||||
/// A database connection that serializes accesses to unchanging
|
||||
/// database content, as it existed at the moment the snapshot was created.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// A `DatabaseSnapshot` never sees any database modification during all its
|
||||
/// A `DatabaseSnapshot` never sees any database modification during its whole
|
||||
/// lifetime. All database accesses performed from a snapshot always see the
|
||||
/// same identical database content.
|
||||
///
|
||||
@@ -39,7 +39,7 @@ import Dispatch
|
||||
/// snapshot from within a write access, outside of any transaction.
|
||||
///
|
||||
/// For example, compare the two snapshots below. The first one is guaranteed to
|
||||
/// see an empty table of players, because is is created after all players have
|
||||
/// see an empty table of players, because it is created after all players have
|
||||
/// been deleted, and from the serialized writer dispatch queue which prevents
|
||||
/// any concurrent write. The second is created without this concurrency
|
||||
/// protection, which means that some other threads may already have created
|
||||
@@ -48,7 +48,7 @@ import Dispatch
|
||||
/// ```swift
|
||||
/// let snapshot1 = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshot in
|
||||
/// try db.inTransaction {
|
||||
/// try Player.deleteAll()
|
||||
/// try Player.deleteAll(db)
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
@@ -70,7 +70,7 @@ import Dispatch
|
||||
/// ```
|
||||
///
|
||||
/// `DatabaseSnapshot` inherits its database access methods from the
|
||||
/// ``DatabaseReader`` protocols.
|
||||
/// ``DatabaseReader`` protocol.
|
||||
///
|
||||
/// `DatabaseSnapshot` serializes database accesses and can't perform concurrent
|
||||
/// reads. For concurrent reads, see ``DatabaseSnapshotPool``.
|
||||
@@ -113,7 +113,14 @@ public final class DatabaseSnapshot {
|
||||
deinit {
|
||||
// Leave snapshot isolation
|
||||
reader.reentrantSync { db in
|
||||
try? db.commit()
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,7 +159,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
|
||||
}
|
||||
|
||||
public func read<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await reader.execute(value)
|
||||
}
|
||||
@@ -173,7 +180,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
|
||||
// `DatabaseSnapshotReader`, because of
|
||||
// <https://github.com/apple/swift/issues/74469>.
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await read(value)
|
||||
}
|
||||
|
||||
@@ -1,28 +1,31 @@
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
/// A database connection that allows concurrent accesses to an unchanging
|
||||
/// A database connection that allows concurrent accesses to unchanging
|
||||
/// database content, as it existed at the moment the snapshot was created.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// A `DatabaseSnapshotPool` never sees any database modification during all its
|
||||
/// A `DatabaseSnapshotPool` never sees any database modification during its whole
|
||||
/// lifetime. All database accesses performed from a snapshot always see the
|
||||
/// same identical database content.
|
||||
///
|
||||
/// It creates a pool of up to ``Configuration/maximumReaderCount`` read-only
|
||||
/// SQLite connections. All read accesses are executed in **reader dispatch
|
||||
/// queues** (one per read-only SQLite connection). SQLite connections are
|
||||
/// closed when the `DatabasePool` is deallocated.
|
||||
/// closed when the `DatabaseSnapshotPool` is deallocated.
|
||||
///
|
||||
/// An SQLite database in the [WAL mode](https://www.sqlite.org/wal.html) is
|
||||
/// required for creating a `DatabaseSnapshotPool`.
|
||||
@@ -54,7 +57,7 @@ import SQLite3
|
||||
/// }
|
||||
///
|
||||
/// // Start observing the 'player' table
|
||||
/// let cancellable = try observation.start(in: dbPool) { error in
|
||||
/// let cancellable = observation.start(in: dbPool) { error in
|
||||
/// // Handle error
|
||||
/// } onChange: { (snapshot: DatabaseSnapshotPool) in
|
||||
/// // Handle a fresh snapshot
|
||||
@@ -62,7 +65,7 @@ import SQLite3
|
||||
/// ```
|
||||
///
|
||||
/// `DatabaseSnapshotPool` inherits its database access methods from the
|
||||
/// ``DatabaseReader`` protocols.
|
||||
/// ``DatabaseReader`` protocol.
|
||||
///
|
||||
/// Related SQLite documentation:
|
||||
///
|
||||
@@ -102,12 +105,12 @@ public final class DatabaseSnapshotPool {
|
||||
/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
/// let snapshot = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshotPool in
|
||||
/// try db.inTransaction {
|
||||
/// try Player.deleteAll()
|
||||
/// try Player.deleteAll(db)
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// // Create the snapshot after all players have been deleted.
|
||||
/// return DatabaseSnapshotPool(db)
|
||||
/// return try DatabaseSnapshotPool(db)
|
||||
/// }
|
||||
///
|
||||
/// // Later... Maybe some players have been created.
|
||||
@@ -137,7 +140,7 @@ public final class DatabaseSnapshotPool {
|
||||
let walSnapshot = try db.isolated(readOnly: true) {
|
||||
try WALSnapshot(db)
|
||||
}
|
||||
var holderConfig = Configuration()
|
||||
var holderConfig = configuration
|
||||
holderConfig.allowsUnsafeTransactions = true
|
||||
snapshotHolder = try DatabaseQueue(path: path, configuration: holderConfig)
|
||||
try snapshotHolder.inDatabase { db in
|
||||
@@ -196,7 +199,7 @@ public final class DatabaseSnapshotPool {
|
||||
var configuration = Self.configure(configuration)
|
||||
|
||||
// Acquire and hold WAL snapshot
|
||||
var holderConfig = Configuration()
|
||||
var holderConfig = configuration
|
||||
holderConfig.allowsUnsafeTransactions = true
|
||||
snapshotHolder = try DatabaseQueue(path: path, configuration: holderConfig)
|
||||
let walSnapshot = try snapshotHolder.inDatabase { db in
|
||||
@@ -294,36 +297,25 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
}
|
||||
|
||||
public func read<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
let dbAccess = CancellableDatabaseAccess()
|
||||
return try await dbAccess.withCancellableContinuation { continuation in
|
||||
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(self.poolCompletion(db))
|
||||
}
|
||||
do {
|
||||
let result = try dbAccess.inDatabase(db) {
|
||||
try value(db)
|
||||
}
|
||||
continuation.resume(returning: result)
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
let (reader, releaseReader) = try await readerPool.get()
|
||||
var readerCompletion: PoolCompletion?
|
||||
defer {
|
||||
// readerCompletion might be null in cancelled database accesses
|
||||
releaseReader(readerCompletion ?? .reuse)
|
||||
}
|
||||
let (result, completion) = try await reader.execute { db in
|
||||
let result = Result { try value(db) }
|
||||
let completion = poolCompletion(db)
|
||||
return (result, completion)
|
||||
}
|
||||
readerCompletion = completion
|
||||
return try result.get()
|
||||
}
|
||||
|
||||
public func asyncRead(
|
||||
@@ -353,7 +345,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
// `DatabaseSnapshotReader`, because of
|
||||
// <https://github.com/apple/swift/issues/74469>.
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await read(value)
|
||||
}
|
||||
@@ -384,6 +376,10 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
/// Returns a reader that can be used from the current dispatch queue,
|
||||
/// if any.
|
||||
private var currentReader: SerializedDatabase? {
|
||||
if SchedulingWatchdog.current == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
guard let readerPool else {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -13,7 +16,7 @@ import Foundation
|
||||
///
|
||||
/// To get `DatabaseValue` instances, you can:
|
||||
///
|
||||
/// - Fetch `DatabaseValue` from a ``Database`` instace:
|
||||
/// - Fetch `DatabaseValue` from a ``Database`` instance:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
@@ -118,7 +121,7 @@ public struct DatabaseValue: Hashable {
|
||||
|
||||
// MARK: - Extracting Value
|
||||
|
||||
/// A boolean value indicating is the database value is `NULL`.
|
||||
/// A boolean value indicating if the database value is `NULL`.
|
||||
public var isNull: Bool {
|
||||
switch storage {
|
||||
case .null:
|
||||
@@ -144,7 +147,10 @@ public struct DatabaseValue: Hashable {
|
||||
case SQLITE_FLOAT:
|
||||
storage = .double(sqlite3_value_double(sqliteValue))
|
||||
case SQLITE_TEXT:
|
||||
storage = .string(String(cString: sqlite3_value_text(sqliteValue)!))
|
||||
let text = sqlite3_value_text(sqliteValue)
|
||||
let byteCount = Int(sqlite3_value_bytes(sqliteValue))
|
||||
let string = String(decoding: UnsafeBufferPointer(start: text, count: byteCount), as: UTF8.self)
|
||||
storage = .string(string)
|
||||
case SQLITE_BLOB:
|
||||
if let bytes = sqlite3_value_blob(sqliteValue) {
|
||||
let count = Int(sqlite3_value_bytes(sqliteValue))
|
||||
@@ -168,7 +174,8 @@ public struct DatabaseValue: Hashable {
|
||||
case SQLITE_FLOAT:
|
||||
storage = .double(sqlite3_column_double(sqliteStatement, index))
|
||||
case SQLITE_TEXT:
|
||||
storage = .string(String(cString: sqlite3_column_text(sqliteStatement, index)))
|
||||
let string = String(sqliteStatement: sqliteStatement, index: index)
|
||||
storage = .string(string)
|
||||
case SQLITE_BLOB:
|
||||
if let bytes = sqlite3_column_blob(sqliteStatement, index) {
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, index))
|
||||
@@ -220,7 +227,7 @@ extension DatabaseValue: StatementBinding {
|
||||
let code = double.bind(to: sqliteStatement, at: index)
|
||||
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
|
||||
return try body()
|
||||
case .string(let string):
|
||||
case .string(var string):
|
||||
return try string.withBinding(to: sqliteStatement, at: index, do: body)
|
||||
case .blob(let data):
|
||||
return try data.withBinding(to: sqliteStatement, at: index, do: body)
|
||||
@@ -254,7 +261,7 @@ extension DatabaseValue.Storage: Equatable {
|
||||
}
|
||||
|
||||
extension DatabaseValue: Equatable {
|
||||
/// Returns whether two ``DatabaseValue`` are equal.
|
||||
/// Returns whether two ``DatabaseValue`` instances are equal.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -263,7 +270,7 @@ extension DatabaseValue: Equatable {
|
||||
/// 1.databaseValue == 1.databaseValue // true
|
||||
/// ```
|
||||
///
|
||||
/// When comparing integers and doubles, the result is true if and only
|
||||
/// When comparing integers and doubles, the result is true if and only if
|
||||
/// values are equal, and if converting one type to the other does
|
||||
/// not lose information:
|
||||
///
|
||||
@@ -271,7 +278,7 @@ extension DatabaseValue: Equatable {
|
||||
/// 1.databaseValue == 1.0.databaseValue // true
|
||||
/// ```
|
||||
///
|
||||
/// For a comparison that distinguishes integer and doubles, compare
|
||||
/// For a comparison that distinguishes integers and doubles, compare
|
||||
/// storages instead:
|
||||
///
|
||||
/// ```swift
|
||||
@@ -359,7 +366,7 @@ extension DatabaseValue: CustomStringConvertible {
|
||||
/// This comparison is not public because it does not handle text collations,
|
||||
/// and may be dangerous when put in user hands.
|
||||
///
|
||||
/// So far, the only goal of this sorting method so far is aesthetic, and
|
||||
/// So far, the only goal of this sorting method is aesthetic, and
|
||||
/// easier testing.
|
||||
func < (lhs: DatabaseValue, rhs: DatabaseValue) -> Bool {
|
||||
switch (lhs.storage, rhs.storage) {
|
||||
|
||||
@@ -64,13 +64,13 @@ public protocol DatabaseValueConvertible: SQLExpressible, StatementBinding {
|
||||
|
||||
/// Returns the `JSONDecoder` that decodes the value.
|
||||
///
|
||||
/// This method is dedicated to ``DatabaseValueConvertible`` types that
|
||||
/// This method is intended for ``DatabaseValueConvertible`` types that
|
||||
/// also conform to the standard `Decodable` protocol.
|
||||
static func databaseJSONDecoder() -> JSONDecoder
|
||||
|
||||
/// Returns the `JSONEncoder` that encodes the value.
|
||||
///
|
||||
/// This method is dedicated to ``DatabaseValueConvertible`` types that
|
||||
/// This method is intended for ``DatabaseValueConvertible`` types that
|
||||
/// also conform to the standard `Encodable` protocol.
|
||||
static func databaseJSONEncoder() -> JSONEncoder
|
||||
}
|
||||
@@ -184,7 +184,7 @@ extension DatabaseValueConvertible {
|
||||
/// let names: DatabaseValueCursor<String> = try String.fetchCursor(db, sql: """
|
||||
/// SELECT name FROM player
|
||||
/// """)
|
||||
/// while let name = names.next() { // String
|
||||
/// while let name = try names.next() { // String
|
||||
/// print(name)
|
||||
/// }
|
||||
/// }
|
||||
@@ -227,7 +227,7 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
|
||||
@available(*, unavailable)
|
||||
extension DatabaseValueCursor: Sendable { }
|
||||
|
||||
/// DatabaseValueConvertible comes with built-in methods that allow to fetch
|
||||
/// DatabaseValueConvertible comes with built-in methods that allow you to fetch
|
||||
/// cursors, arrays, or single values:
|
||||
///
|
||||
/// try String.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String
|
||||
@@ -237,7 +237,7 @@ extension DatabaseValueCursor: Sendable { }
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// try String.fetchCursor(statement, arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(statement, arguments:...) // [String]
|
||||
/// try String.fetchOne(statement, arguments:...) // String
|
||||
/// try String.fetchOne(statement, arguments:...) // String?
|
||||
///
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
extension DatabaseValueConvertible {
|
||||
@@ -541,13 +541,20 @@ extension DatabaseValueConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -584,13 +591,20 @@ extension DatabaseValueConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -623,13 +637,20 @@ extension DatabaseValueConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -657,13 +678,20 @@ extension DatabaseValueConvertible where Self: Hashable {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -696,13 +724,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -736,13 +771,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -772,13 +814,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -808,8 +857,8 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable {
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
|
||||
@@ -22,18 +22,18 @@ import Dispatch
|
||||
/// ### Writing into the Database
|
||||
///
|
||||
/// - ``write(_:)-76inz``
|
||||
/// - ``write(_:)-3db50``
|
||||
/// - ``write(_:)-4gnqx``
|
||||
/// - ``writePublisher(receiveOn:updates:)``
|
||||
/// - ``writePublisher(receiveOn:updates:thenRead:)``
|
||||
/// - ``writeWithoutTransaction(_:)-4qh1w``
|
||||
/// - ``writeWithoutTransaction(_:)-67mri``
|
||||
/// - ``writeWithoutTransaction(_:)-18zhj``
|
||||
/// - ``asyncWrite(_:completion:)``
|
||||
/// - ``asyncWriteWithoutTransaction(_:)``
|
||||
///
|
||||
/// ### Exclusive Access to the Database
|
||||
///
|
||||
/// - ``barrierWriteWithoutTransaction(_:)-280j1``
|
||||
/// - ``barrierWriteWithoutTransaction(_:)-48d63``
|
||||
/// - ``barrierWriteWithoutTransaction(_:)-11q6c``
|
||||
/// - ``asyncBarrierWriteWithoutTransaction(_:)``
|
||||
///
|
||||
/// ### Reading from the Latest Committed Database State
|
||||
@@ -130,7 +130,7 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// database access, or the error thrown by `updates`, or
|
||||
/// `CancellationError` if the task is cancelled.
|
||||
func writeWithoutTransaction<T: Sendable>(
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T
|
||||
|
||||
/// Executes database operations, and returns their result after they have
|
||||
@@ -213,7 +213,7 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// database access, or the error thrown by `updates`, or
|
||||
/// `CancellationError` if the task is cancelled.
|
||||
func barrierWriteWithoutTransaction<T: Sendable>(
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T
|
||||
|
||||
/// Schedules database operations for execution, and returns immediately.
|
||||
@@ -336,7 +336,7 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// any transaction. You'll get a fatal error otherwise.
|
||||
///
|
||||
/// Database operations performed by the `value` closure are isolated in a
|
||||
/// transaction: they do not see changes performed by eventual concurrent
|
||||
/// transaction: they do not see changes performed by concurrent
|
||||
/// writes (even writes performed by other processes).
|
||||
///
|
||||
/// They see the database in the state left by the last updates performed
|
||||
@@ -348,10 +348,10 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// ```swift
|
||||
/// try writer.writeWithoutTransaction { db in
|
||||
/// // Delete all players
|
||||
/// try Player.deleteAll()
|
||||
/// try Player.deleteAll(db)
|
||||
///
|
||||
/// // Count players concurrently
|
||||
/// writer.spawnConcurrentRead { db in
|
||||
/// writer.spawnConcurrentRead { dbResult in
|
||||
/// do {
|
||||
/// let db = try dbResult.get()
|
||||
/// // Guaranteed to be zero
|
||||
@@ -392,9 +392,9 @@ extension DatabaseWriter {
|
||||
/// ```
|
||||
///
|
||||
/// Database operations are wrapped in a transaction. If they throw an
|
||||
/// error, the transaction is rollbacked and the error is rethrown.
|
||||
/// error, the transaction is rolled back and the error is rethrown.
|
||||
///
|
||||
/// Concurrent database accesses can not see partial database updates (even
|
||||
/// Concurrent database accesses cannot see partial database updates (even
|
||||
/// when performed by other processes).
|
||||
///
|
||||
/// Database operations run in the writer dispatch queue, serialized
|
||||
@@ -438,17 +438,18 @@ extension DatabaseWriter {
|
||||
/// // Handle success
|
||||
/// case let .failure(error):
|
||||
/// // Handle error
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Database operations run by the `updates` closure are wrapped in
|
||||
/// a transaction. If they throw an error, the transaction is rollbacked.
|
||||
/// a transaction. If they throw an error, the transaction is rolled back.
|
||||
///
|
||||
/// The `completion` closure has two arguments: a database connection, and
|
||||
/// the result of the transaction. This result is a failure if the
|
||||
/// transaction could not be committed or if `updates` has thrown an error.
|
||||
///
|
||||
/// Concurrent database accesses can not see partial database updates
|
||||
/// Concurrent database accesses cannot see partial database updates
|
||||
/// performed by `updates` (even when performed by other processes).
|
||||
///
|
||||
/// Database operations run in the writer dispatch queue, serialized
|
||||
@@ -552,7 +553,7 @@ extension DatabaseWriter {
|
||||
// This method is declared on DatabaseWriter instead of DatabaseReader,
|
||||
// so that it is not available on DatabaseSnaphot. VACUUM INTO is not
|
||||
// available inside the transaction that is kept open by DatabaseSnaphot.
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Creates a new database file at the specified path with a minimum
|
||||
/// amount of disk space.
|
||||
///
|
||||
@@ -623,9 +624,9 @@ extension DatabaseWriter {
|
||||
/// ```
|
||||
///
|
||||
/// Database operations are wrapped in a transaction. If they throw an
|
||||
/// error, the transaction is rollbacked and the error is rethrown.
|
||||
/// error, the transaction is rolled back and the error is rethrown.
|
||||
///
|
||||
/// Concurrent database accesses can not see partial database updates (even
|
||||
/// Concurrent database accesses cannot see partial database updates (even
|
||||
/// when performed by other processes).
|
||||
///
|
||||
/// Database operations run in the writer dispatch queue, serialized
|
||||
@@ -640,7 +641,7 @@ extension DatabaseWriter {
|
||||
/// database access, or the error thrown by `updates`, or
|
||||
/// `CancellationError` if the task is cancelled.
|
||||
public func write<T: Sendable>(
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writeWithoutTransaction { db in
|
||||
var result: T?
|
||||
@@ -665,7 +666,7 @@ extension DatabaseWriter {
|
||||
try await writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Creates a new database file at the specified path with a minimum
|
||||
/// amount of disk space.
|
||||
///
|
||||
@@ -715,10 +716,10 @@ extension DatabaseWriter {
|
||||
/// ```
|
||||
///
|
||||
/// Database operations are wrapped in a transaction. If they throw an
|
||||
/// error, the transaction is rollbacked and the error completes
|
||||
/// error, the transaction is rolled back and the error completes
|
||||
/// the publisher.
|
||||
///
|
||||
/// Concurrent database accesses can not see partial database updates (even
|
||||
/// Concurrent database accesses cannot see partial database updates (even
|
||||
/// when performed by other processes).
|
||||
///
|
||||
/// Database operations are asynchronously dispatched in the writer dispatch
|
||||
@@ -776,7 +777,7 @@ extension DatabaseWriter {
|
||||
/// The difference is that the last fetches are performed in the `thenRead`
|
||||
/// closure. This closure accepts two arguments: a read-only database
|
||||
/// connection, and the result of the `updates` function. This allows you to
|
||||
/// pass information from a function to the other (it is ignored in the
|
||||
/// pass information from one function to the other (it is ignored in the
|
||||
/// sample code above).
|
||||
///
|
||||
/// When you use a ``DatabasePool``, this method applies a scheduling
|
||||
@@ -855,7 +856,7 @@ extension Publisher where Failure == Error {
|
||||
public final class AnyDatabaseWriter {
|
||||
private let base: any DatabaseWriter
|
||||
|
||||
/// Creates a new database reader that wraps and forwards operations
|
||||
/// Creates a new database writer that wraps and forwards operations
|
||||
/// to `base`.
|
||||
public init(_ base: any DatabaseWriter) {
|
||||
self.base = base
|
||||
@@ -885,7 +886,7 @@ extension AnyDatabaseWriter: DatabaseReader {
|
||||
}
|
||||
|
||||
public func read<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.read(value)
|
||||
}
|
||||
@@ -902,7 +903,7 @@ extension AnyDatabaseWriter: DatabaseReader {
|
||||
}
|
||||
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.unsafeRead(value)
|
||||
}
|
||||
@@ -936,7 +937,7 @@ extension AnyDatabaseWriter: DatabaseWriter {
|
||||
}
|
||||
|
||||
public func writeWithoutTransaction<T: Sendable>(
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.writeWithoutTransaction(updates)
|
||||
}
|
||||
@@ -947,7 +948,7 @@ extension AnyDatabaseWriter: DatabaseWriter {
|
||||
}
|
||||
|
||||
public func barrierWriteWithoutTransaction<T: Sendable>(
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.barrierWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
#if os(Linux)
|
||||
@preconcurrency import Dispatch
|
||||
#else
|
||||
import Dispatch
|
||||
#endif
|
||||
|
||||
/// An actor that runs in a DispatchQueue.
|
||||
///
|
||||
/// Inspired by <https://forums.swift.org/t/using-dispatchqueue-as-actors-serial-executor-under-linux/75260/3>
|
||||
actor DispatchQueueActor {
|
||||
private let executor: DispatchQueueExecutor
|
||||
|
||||
/// - precondition: the queue is serial, or flags contains `.barrier`.
|
||||
init(queue: DispatchQueue, flags: DispatchWorkItemFlags = []) {
|
||||
self.executor = DispatchQueueExecutor(queue: queue, flags: flags)
|
||||
}
|
||||
|
||||
nonisolated var unownedExecutor: UnownedSerialExecutor {
|
||||
executor.asUnownedSerialExecutor()
|
||||
}
|
||||
|
||||
func execute<T>(_ work: () throws -> T) rethrows -> T {
|
||||
try work()
|
||||
}
|
||||
}
|
||||
|
||||
private final class DispatchQueueExecutor: SerialExecutor {
|
||||
private let queue: DispatchQueue
|
||||
private let flags: DispatchWorkItemFlags
|
||||
|
||||
init(queue: DispatchQueue, flags: DispatchWorkItemFlags) {
|
||||
self.queue = queue
|
||||
self.flags = flags
|
||||
}
|
||||
|
||||
func enqueue(_ job: UnownedJob) {
|
||||
queue.async(flags: flags) {
|
||||
job.runSynchronously(on: self.asUnownedSerialExecutor())
|
||||
}
|
||||
}
|
||||
|
||||
func asUnownedSerialExecutor() -> UnownedSerialExecutor {
|
||||
UnownedSerialExecutor(ordinary: self)
|
||||
}
|
||||
|
||||
func checkIsolated() {
|
||||
dispatchPrecondition(condition: .onQueue(queue))
|
||||
}
|
||||
}
|
||||
|
||||
#if os(Linux) || os(Android) || os(Windows)
|
||||
extension DispatchQueueExecutor: @unchecked Sendable {}
|
||||
#endif
|
||||
@@ -97,7 +97,7 @@ public protocol FetchRequest<RowDecoder>: SQLSubqueryable, DatabaseRegionConvert
|
||||
}
|
||||
|
||||
extension FetchRequest {
|
||||
/// Returns the database region that the request feeds from.
|
||||
/// Returns the database region that the request looks into.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
@@ -134,7 +134,7 @@ public struct PreparedRequest {
|
||||
/// A prepared statement with bound parameters.
|
||||
public var statement: Statement
|
||||
|
||||
/// An eventual adapter for rows fetched by the select statement.
|
||||
/// An optional adapter for rows fetched by the select statement.
|
||||
public var adapter: (any RowAdapter)?
|
||||
|
||||
/// A closure that performs supplementary fetches.
|
||||
@@ -166,7 +166,7 @@ extension FetchRequest {
|
||||
///
|
||||
/// The returned request performs an identical database query, but adapts
|
||||
/// the fetched rows. See ``RowAdapter``, and
|
||||
/// ``splittingRowAdapters(columnCounts:)`` for a sample code that uses
|
||||
/// ``splittingRowAdapters(columnCounts:)`` for sample code that uses
|
||||
/// `adapted(_:)`.
|
||||
///
|
||||
/// - parameter adapter: A closure that accepts a database connection and
|
||||
|
||||
+428
-151
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -38,7 +41,7 @@ import Foundation
|
||||
///
|
||||
/// - ``copy()``
|
||||
///
|
||||
/// ### Row Informations
|
||||
/// ### Row Information
|
||||
///
|
||||
/// - ``columnNames``
|
||||
/// - ``containsNonNullValue``
|
||||
@@ -52,6 +55,8 @@ import Foundation
|
||||
/// - ``subscript(_:)-9c1fw``
|
||||
/// - ``subscript(_:)-3jhwm``
|
||||
/// - ``subscript(_:)-7krrg``
|
||||
/// - ``decode(_:atIndex:)-33ykh``
|
||||
/// - ``decode(_:atIndex:)-3btwn``
|
||||
/// - ``withUnsafeData(atIndex:_:)``
|
||||
/// - ``dataNoCopy(atIndex:)``
|
||||
///
|
||||
@@ -61,7 +66,8 @@ import Foundation
|
||||
/// - ``subscript(_:)-4k8od``
|
||||
/// - ``subscript(_:)-9rbo7``
|
||||
/// - ``coalesce(_:)-359k7``
|
||||
/// - ``coalesce(_:)-6nbah``
|
||||
/// - ``decode(_:forColumn:)-4i1o4``
|
||||
/// - ``decode(_:forColumn:)-4rhs4``
|
||||
/// - ``withUnsafeData(named:_:)``
|
||||
/// - ``dataNoCopy(named:)``
|
||||
///
|
||||
@@ -70,6 +76,9 @@ import Foundation
|
||||
/// - ``subscript(_:)-9txgm``
|
||||
/// - ``subscript(_:)-2esg7``
|
||||
/// - ``subscript(_:)-wl9a``
|
||||
/// - ``coalesce(_:)-6nbah``
|
||||
/// - ``decode(_:forColumn:)-1ljuo``
|
||||
/// - ``decode(_:forColumn:)-47qeg``
|
||||
/// - ``withUnsafeData(at:_:)``
|
||||
/// - ``dataNoCopy(_:)``
|
||||
///
|
||||
@@ -84,6 +93,10 @@ import Foundation
|
||||
/// - ``subscript(_:)-8god3``
|
||||
/// - ``subscript(_:)-jwnx``
|
||||
/// - ``subscript(_:)-6ge6t``
|
||||
/// - ``decode(_:forKey:)-9bbd3``
|
||||
/// - ``decode(_:forKey:)-2w6lc``
|
||||
/// - ``decode(_:forKey:)-2soc2``
|
||||
/// - ``decodeIfPresent(_:forKey:)``
|
||||
/// - ``PrefetchedRowsView``
|
||||
/// - ``ScopesTreeView``
|
||||
/// - ``ScopesView``
|
||||
@@ -119,6 +132,10 @@ import Foundation
|
||||
///
|
||||
/// - ``RowAdapter``
|
||||
///
|
||||
/// ### Errors
|
||||
///
|
||||
/// - ``RowDecodingError``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``RowCursor``
|
||||
@@ -137,7 +154,20 @@ public final class Row {
|
||||
let sqliteStatement: SQLiteStatement?
|
||||
|
||||
/// The number of columns in the row.
|
||||
public let count: Int
|
||||
@inlinable
|
||||
public var count: Int {
|
||||
// Rows that map an SQLite statement don't cache the number of
|
||||
// columns, because SQLite may recompile the statement after a
|
||||
// schema change, with a different number of columns.
|
||||
if let sqliteStatement {
|
||||
return Int(sqlite3_column_count(sqliteStatement))
|
||||
}
|
||||
return cachedCount
|
||||
}
|
||||
|
||||
/// The number of columns, when the row does not map an SQLite statement.
|
||||
@usableFromInline
|
||||
let cachedCount: Int
|
||||
|
||||
/// A view on the prefetched associated rows.
|
||||
///
|
||||
@@ -221,7 +251,7 @@ public final class Row {
|
||||
self.statement = statement
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
self.impl = StatementRowImpl(sqliteStatement: statement.sqliteStatement, statement: statement)
|
||||
self.count = Int(sqlite3_column_count(sqliteStatement))
|
||||
self.cachedCount = 0 // Unused because sqliteStatement is not nil: see `count`
|
||||
}
|
||||
|
||||
/// Creates a row that maps an SQLite statement. Further calls to
|
||||
@@ -230,10 +260,10 @@ public final class Row {
|
||||
self.statement = nil
|
||||
self.sqliteStatement = sqliteStatement
|
||||
self.impl = SQLiteStatementRowImpl(sqliteStatement: sqliteStatement)
|
||||
self.count = Int(sqlite3_column_count(sqliteStatement))
|
||||
self.cachedCount = 0 // Unused because sqliteStatement is not nil: see `count`
|
||||
}
|
||||
|
||||
/// Creates a row that contain a copy of the current state of the
|
||||
/// Creates a row that contains a copy of the current state of the
|
||||
/// SQLite statement. Further calls to sqlite3_step() do not modify the row.
|
||||
///
|
||||
/// The row is implemented on top of StatementCopyRowImpl, which *copies*
|
||||
@@ -252,7 +282,7 @@ public final class Row {
|
||||
self.statement = nil
|
||||
self.sqliteStatement = nil
|
||||
self.impl = impl
|
||||
self.count = impl.count
|
||||
self.cachedCount = impl.count
|
||||
}
|
||||
}
|
||||
|
||||
@@ -297,7 +327,7 @@ extension Row {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range", file: file, line: line)
|
||||
}
|
||||
|
||||
/// Returns a boolean value indicating if the row contains one value this
|
||||
/// Returns a boolean value indicating if the row contains one value that
|
||||
/// is not `NULL`.
|
||||
///
|
||||
/// For example:
|
||||
@@ -452,7 +482,7 @@ extension Row {
|
||||
/// ```
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value {
|
||||
try! decode(Value.self, forKey: columnName)
|
||||
try! decode(Value.self, forColumn: columnName)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -489,7 +519,7 @@ extension Row {
|
||||
/// ```
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value {
|
||||
try! decode(Value.self, forKey: columnName)
|
||||
try! decode(Value.self, forColumn: columnName)
|
||||
}
|
||||
|
||||
/// Returns `Int64`, `Double`, `String`, `Data` or nil, depending on the
|
||||
@@ -533,7 +563,7 @@ extension Row {
|
||||
/// ```
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible>(_ column: some ColumnExpression) -> Value {
|
||||
try! decode(Value.self, forKey: column.name)
|
||||
try! decode(Value.self, forColumn: column)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -573,7 +603,7 @@ extension Row {
|
||||
-> Value
|
||||
where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
{
|
||||
try! decode(Value.self, forKey: column.name)
|
||||
try! decode(Value.self, forColumn: column)
|
||||
}
|
||||
|
||||
/// Calls the given closure with the `Data` at given index.
|
||||
@@ -597,7 +627,7 @@ extension Row {
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the row does not contain any column with that name, or if the SQLite
|
||||
/// value is `NULL`, the data is nil. If the SQLite value can not be
|
||||
/// value is `NULL`, the data is nil. If the SQLite value cannot be
|
||||
/// converted to `Data`, an error is thrown.
|
||||
///
|
||||
/// - warning: The `Data` argument to the body must not be stored or used
|
||||
@@ -615,7 +645,7 @@ extension Row {
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the row does not contain any column with that name, or if the SQLite
|
||||
/// value is `NULL`, the data is nil. If the SQLite value can not be
|
||||
/// value is `NULL`, the data is nil. If the SQLite value cannot be
|
||||
/// converted to `Data`, an error is thrown.
|
||||
///
|
||||
/// - warning: The `Data` argument to the body must not be stored or used
|
||||
@@ -632,7 +662,7 @@ extension Row {
|
||||
/// If the SQLite value is NULL, the result is nil. If the SQLite value can
|
||||
/// not be converted to Data, a fatal error is raised.
|
||||
///
|
||||
/// The returned data does not owns its bytes: it must not be used longer
|
||||
/// The returned data does not own its bytes: it must not be used longer
|
||||
/// than the row's lifetime.
|
||||
@available(*, deprecated, message: "Use withUnsafeData(atIndex:_:) instead.")
|
||||
public func dataNoCopy(atIndex index: Int) -> Data? {
|
||||
@@ -645,10 +675,10 @@ extension Row {
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the column is missing or if the SQLite value is NULL, the result is
|
||||
/// nil. If the SQLite value can not be converted to Data, a fatal error
|
||||
/// nil. If the SQLite value cannot be converted to Data, a fatal error
|
||||
/// is raised.
|
||||
///
|
||||
/// The returned data does not owns its bytes: it must not be used longer
|
||||
/// The returned data does not own its bytes: it must not be used longer
|
||||
/// than the row's lifetime.
|
||||
@available(*, deprecated, message: "Use withUnsafeData(named:_:) instead.")
|
||||
public func dataNoCopy(named columnName: String) -> Data? {
|
||||
@@ -664,10 +694,10 @@ extension Row {
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the column is missing or if the SQLite value is NULL, the result is
|
||||
/// nil. If the SQLite value can not be converted to Data, a fatal error
|
||||
/// nil. If the SQLite value cannot be converted to Data, a fatal error
|
||||
/// is raised.
|
||||
///
|
||||
/// The returned data does not owns its bytes: it must not be used longer
|
||||
/// The returned data does not own its bytes: it must not be used longer
|
||||
/// than the row's lifetime.
|
||||
@available(*, deprecated, message: "Use withUnsafeData(at:_:) instead.")
|
||||
public func dataNoCopy(_ column: some ColumnExpression) -> Data? {
|
||||
@@ -739,12 +769,13 @@ extension Row {
|
||||
|
||||
// MARK: - Extracting Records
|
||||
|
||||
/// The record associated to the given scope.
|
||||
/// Returns the record associated with the given key.
|
||||
///
|
||||
/// Row scopes can be defined manually, with ``ScopeAdapter``.
|
||||
/// The ``JoinableRequest/including(required:)`` and
|
||||
/// ``JoinableRequest/including(optional:)`` request methods define scopes
|
||||
/// named after the key of included associations between record types.
|
||||
/// The key is a row scope that was either defined manually, with
|
||||
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
|
||||
/// and ``JoinableRequest/including(optional:)`` request methods. The
|
||||
/// latter define row scopes named after the key of included
|
||||
/// associations between record types.
|
||||
///
|
||||
/// A breadth-first search is performed in all available scopes in the row,
|
||||
/// recursively.
|
||||
@@ -769,26 +800,28 @@ extension Row {
|
||||
/// let request = Book
|
||||
/// .including(required: Book.author
|
||||
/// .including(required: Author.country))
|
||||
/// let bookRow = try Row.fetchOne(db, request)!
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let book = try Book(row: bookRow)
|
||||
/// let author: Author = bookRow["author"]
|
||||
/// let country: Country = bookRow["country"]
|
||||
/// let book = try Book(row: row)
|
||||
/// let author: Author = row["author"]
|
||||
/// let country: Country = row["country"]
|
||||
/// ```
|
||||
///
|
||||
/// See also: ``scopesTree``
|
||||
/// For more details about row scopes, see ``ScopeAdapter``,
|
||||
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
|
||||
///
|
||||
/// - parameter scope: A scope identifier.
|
||||
public subscript<Record: FetchableRecord>(_ scope: String) -> Record {
|
||||
try! decode(Record.self, forKey: scope)
|
||||
}
|
||||
|
||||
/// The eventual record associated to the given scope.
|
||||
/// Returns the record associated with the given key, if any.
|
||||
///
|
||||
/// Row scopes can be defined manually, with ``ScopeAdapter``.
|
||||
/// The ``JoinableRequest/including(required:)`` and
|
||||
/// ``JoinableRequest/including(optional:)`` request methods define scopes
|
||||
/// named after the key of included associations between record types.
|
||||
/// The key is a row scope that was either defined manually, with
|
||||
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
|
||||
/// and ``JoinableRequest/including(optional:)`` request methods. The
|
||||
/// latter define row scopes named after the key of included
|
||||
/// associations between record types.
|
||||
///
|
||||
/// A breadth-first search is performed in all available scopes in the row,
|
||||
/// recursively.
|
||||
@@ -809,25 +842,26 @@ extension Row {
|
||||
///
|
||||
/// struct Country: TableRecord, FetchableRecord { }
|
||||
///
|
||||
/// // Fetch a book, with its author, and the country of its author.
|
||||
/// // Fetch a book, with its optional author, and the country of its author.
|
||||
/// let request = Book
|
||||
/// .including(optional: Book.author
|
||||
/// .including(optional: Author.country))
|
||||
/// let bookRow = try Row.fetchOne(db, request)!
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let book = try Book(row: bookRow)
|
||||
/// let author: Author? = bookRow["author"]
|
||||
/// let country: Country? = bookRow["country"]
|
||||
/// let book = try Book(row: row)
|
||||
/// let author: Author? = row["author"]
|
||||
/// let country: Country? = row["country"]
|
||||
/// ```
|
||||
///
|
||||
/// See also: ``scopesTree``
|
||||
/// For more details about row scopes, see ``ScopeAdapter``,
|
||||
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
|
||||
///
|
||||
/// - parameter scope: A scope identifier.
|
||||
public subscript<Record: FetchableRecord>(_ scope: String) -> Record? {
|
||||
try! decodeIfPresent(Record.self, forKey: scope)
|
||||
}
|
||||
|
||||
/// A collection of prefetched records associated to the given
|
||||
/// Returns a collection of prefetched records associated with the given
|
||||
/// association key.
|
||||
///
|
||||
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
|
||||
@@ -843,10 +877,10 @@ extension Row {
|
||||
/// struct Book: TableRecord, FetchableRecord { }
|
||||
///
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let authorRow = try Row.fetchOne(db, request)!
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let author = try Author(row: authorRow)
|
||||
/// let books: [Book] = author["books"]
|
||||
/// let author = try Author(row: row)
|
||||
/// let books: [Book] = row["books"]
|
||||
/// ```
|
||||
///
|
||||
/// See also: ``prefetchedRows``
|
||||
@@ -861,7 +895,8 @@ extension Row {
|
||||
try! decode(Records.self, forKey: key)
|
||||
}
|
||||
|
||||
/// A set prefetched records associated to the given association key.
|
||||
/// Returns the set of prefetched records associated with the given
|
||||
/// association key.
|
||||
///
|
||||
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
|
||||
/// request method.
|
||||
@@ -876,10 +911,10 @@ extension Row {
|
||||
/// struct Book: TableRecord, FetchableRecord, Hashable { }
|
||||
///
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let authorRow = try Row.fetchOne(db, request)!
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let author = try Author(row: authorRow)
|
||||
/// let books: Set<Book> = author["books"]
|
||||
/// let author = try Author(row: row)
|
||||
/// let books: Set<Book> = row["books"]
|
||||
/// ```
|
||||
///
|
||||
/// See also: ``prefetchedRows``
|
||||
@@ -896,7 +931,7 @@ extension Row {
|
||||
|
||||
/// A view on the scopes defined by row adapters.
|
||||
///
|
||||
/// The returned object provides an access to all available scopes in
|
||||
/// The returned object provides access to all available scopes in
|
||||
/// the row.
|
||||
///
|
||||
/// Row scopes can be defined manually, with ``ScopeAdapter``.
|
||||
@@ -935,14 +970,15 @@ extension Row {
|
||||
/// // Prints [code:"US" name:"United States of America"]
|
||||
/// ```
|
||||
///
|
||||
/// See also ``scopesTree``.
|
||||
/// For more details about row scopes, see ``ScopeAdapter``,
|
||||
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
|
||||
public var scopes: ScopesView {
|
||||
impl.scopes(prefetchedRows: prefetchedRows)
|
||||
}
|
||||
|
||||
/// A view on the scopes tree defined by row adapters.
|
||||
///
|
||||
/// The returned object provides an access to all available scopes in
|
||||
/// The returned object provides access to all available scopes in
|
||||
/// the row, recursively. For any given scope identifier, a breadth-first
|
||||
/// search is performed.
|
||||
///
|
||||
@@ -985,7 +1021,7 @@ extension Row {
|
||||
ScopesTreeView(scopes: scopes)
|
||||
}
|
||||
|
||||
/// The row, without any scope of prefetched rows.
|
||||
/// The row, without any scope or prefetched rows.
|
||||
///
|
||||
/// This property is useful when testing the content of rows fetched from
|
||||
/// joined requests.
|
||||
@@ -1065,10 +1101,28 @@ extension Row {
|
||||
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
|
||||
/// rightmost column.
|
||||
///
|
||||
/// If the SQLite value is NULL, or if the conversion fails, a
|
||||
/// `RowDecodingError` is thrown.
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42")!
|
||||
/// let score = try row.decode(Int.self, atIndex: 0) // 42
|
||||
/// let score: Int = try row.decode(atIndex: 0) // 42
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")!
|
||||
/// let name = try row.decode(String.self, atIndex: 0) // "Alice"
|
||||
/// let name: String = try row.decode(atIndex: 0) // "Alice"
|
||||
/// ```
|
||||
///
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL")!
|
||||
/// let name: String? = try row.decode(atIndex: 0) // nil
|
||||
/// ```
|
||||
///
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
@inlinable
|
||||
func decode<Value: DatabaseValueConvertible>(
|
||||
public func decode<Value: DatabaseValueConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
atIndex index: Int)
|
||||
throws -> Value
|
||||
@@ -1082,13 +1136,37 @@ extension Row {
|
||||
/// Column name lookup is case-insensitive. When several columns exist with
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the row does not contain the column, or if the SQLite value is NULL,
|
||||
/// or if the SQLite value can not be converted to `Value`, a
|
||||
/// `RowDecodingError` is thrown.
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
|
||||
/// let score = try row.decode(Int.self, forColumn: "score") // 42
|
||||
/// let score: Int = try row.decode(forColumn: "score") // 42
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name = try row.decode(String.self, forColumn: "name") // "Alice"
|
||||
/// let name: String = try row.decode(forColumn: "name") // "Alice"
|
||||
/// ```
|
||||
///
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: "name") // nil
|
||||
/// ```
|
||||
///
|
||||
/// When the column does not exist, nil is returned:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: "missing") // nil
|
||||
/// ```
|
||||
///
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
@inlinable
|
||||
func decode<Value: DatabaseValueConvertible>(
|
||||
public func decode<Value: DatabaseValueConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
forKey columnName: String)
|
||||
forColumn columnName: String)
|
||||
throws -> Value
|
||||
{
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
@@ -1100,6 +1178,47 @@ extension Row {
|
||||
}
|
||||
return try Value.decode(fromRow: self, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
///
|
||||
/// Column name lookup is case-insensitive. When several columns exist with
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
|
||||
/// let score = try row.decode(Int.self, forColumn: Column("score")) // 42
|
||||
/// let score: Int = try row.decode(forColumn: Column("score")) // 42
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name = try row.decode(String.self, forColumn: Column("name")) // "Alice"
|
||||
/// let name: String = try row.decode(forColumn: Column("name")) // "Alice"
|
||||
/// ```
|
||||
///
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: Column("name")) // nil
|
||||
/// ```
|
||||
///
|
||||
/// When the column does not exist, nil is returned:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: Column("missing")) // nil
|
||||
/// ```
|
||||
///
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
@inlinable
|
||||
public func decode<Value: DatabaseValueConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
forColumn column: some ColumnExpression)
|
||||
throws -> Value
|
||||
{
|
||||
try decode(type, forColumn: column.name)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Throwing DatabaseValueConvertible & StatementColumnConvertible Decoding Methods
|
||||
@@ -1114,11 +1233,29 @@ extension Row {
|
||||
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
|
||||
/// rightmost column.
|
||||
///
|
||||
/// If the SQLite value is NULL, or if the conversion fails, a
|
||||
/// `RowDecodingError` is thrown.
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42")!
|
||||
/// let score = try row.decode(Int.self, atIndex: 0) // 42
|
||||
/// let score: Int = try row.decode(atIndex: 0) // 42
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")!
|
||||
/// let name = try row.decode(String.self, atIndex: 0) // "Alice"
|
||||
/// let name: String = try row.decode(atIndex: 0) // "Alice"
|
||||
/// ```
|
||||
///
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL")!
|
||||
/// let name: String? = try row.decode(atIndex: 0) // nil
|
||||
/// ```
|
||||
///
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
public func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
atIndex index: Int)
|
||||
throws -> Value
|
||||
@@ -1136,13 +1273,37 @@ extension Row {
|
||||
/// Column name lookup is case-insensitive. When several columns exist with
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the row does not contain the column, or if the SQLite value is NULL,
|
||||
/// or if the SQLite value can not be converted to `Value`, a
|
||||
/// `RowDecodingError` is thrown.
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
|
||||
/// let score = try row.decode(Int.self, forColumn: "score") // 42
|
||||
/// let score: Int = try row.decode(forColumn: "score") // 42
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name = try row.decode(String.self, forColumn: "name") // "Alice"
|
||||
/// let name: String = try row.decode(forColumn: "name") // "Alice"
|
||||
/// ```
|
||||
///
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: "name") // nil
|
||||
/// ```
|
||||
///
|
||||
/// When the column does not exist, nil is returned:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: "missing") // nil
|
||||
/// ```
|
||||
///
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
@inlinable
|
||||
func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
public func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
forKey columnName: String)
|
||||
forColumn columnName: String)
|
||||
throws -> Value
|
||||
{
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
@@ -1155,6 +1316,51 @@ extension Row {
|
||||
return try Value.fastDecode(fromRow: self, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// ``StatementColumnConvertible``. It can trigger [SQLite built-in
|
||||
/// conversions](https://www.sqlite.org/datatype3.html).
|
||||
///
|
||||
/// Column name lookup is case-insensitive. When several columns exist with
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
|
||||
/// let score = try row.decode(Int.self, forColumn: Column("score")) // 42
|
||||
/// let score: Int = try row.decode(forColumn: Column("score")) // 42
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name = try row.decode(String.self, forColumn: Column("name")) // "Alice"
|
||||
/// let name: String = try row.decode(forColumn: Column("name")) // "Alice"
|
||||
/// ```
|
||||
///
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: Column("name")) // nil
|
||||
/// ```
|
||||
///
|
||||
/// When the column does not exist, nil is returned:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: Column("missing")) // nil
|
||||
/// ```
|
||||
///
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
@inlinable
|
||||
public func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
forColumn column: some ColumnExpression)
|
||||
throws -> Value
|
||||
{
|
||||
try decode(type, forColumn: column.name)
|
||||
}
|
||||
|
||||
// Support for fast decoding in scoped rows
|
||||
@usableFromInline
|
||||
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
@@ -1187,37 +1393,51 @@ extension Row {
|
||||
// MARK: - Throwing Record Decoding Methods
|
||||
|
||||
extension Row {
|
||||
/// Returns the eventual record associated with the given scope.
|
||||
/// Returns the record associated with the given key, if any.
|
||||
///
|
||||
/// The key is a row scope that was either defined manually, with
|
||||
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
|
||||
/// and ``JoinableRequest/including(optional:)`` request methods. The
|
||||
/// latter define row scopes named after the key of included
|
||||
/// associations between record types.
|
||||
///
|
||||
/// A breadth-first search is performed in all available scopes in the row,
|
||||
/// recursively.
|
||||
///
|
||||
/// The result is nil if the scope is not available, or contains only
|
||||
/// `NULL` values.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let request = Book.including(optional: Book.author)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
/// ```swift
|
||||
/// struct Book: TableRecord, FetchableRecord {
|
||||
/// static let author = belongsTo(Author.self)
|
||||
/// }
|
||||
///
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
/// struct Author: TableRecord, FetchableRecord {
|
||||
/// static let country = belongsTo(Country.self)
|
||||
/// }
|
||||
///
|
||||
/// let author: Author? = row["author"]
|
||||
/// print(author.name)
|
||||
/// // Prints "Herman Melville"
|
||||
/// struct Country: TableRecord, FetchableRecord { }
|
||||
///
|
||||
/// Associated records stored in nested associations are available, too:
|
||||
/// // Fetch a book, with its optional author, and the country of its author.
|
||||
/// let request = Book
|
||||
/// .including(optional: Book.author
|
||||
/// .including(optional: Author.country))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let request = Book.including(optional: Book.author.including(optional: Author.country))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
/// let book = try Book(row: row)
|
||||
/// let author: Author? = try row.decode(forKey: "author")
|
||||
/// let country: Country? = try row.decode(forKey: "country")
|
||||
/// ```
|
||||
///
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
/// For more details about row scopes, see ``ScopeAdapter``,
|
||||
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
|
||||
///
|
||||
/// let country: Country? = row["country"]
|
||||
/// print(country.name)
|
||||
/// // Prints "United States"
|
||||
///
|
||||
/// Nil is returned if the scope is not available, or contains only
|
||||
/// null values.
|
||||
///
|
||||
/// See ``splittingRowAdapters(columnCounts:)`` for a sample code.
|
||||
func decodeIfPresent<Record: FetchableRecord>(
|
||||
/// - parameter type: The decoded type.
|
||||
/// - parameter scope: A scope identifier.
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
public func decodeIfPresent<Record: FetchableRecord>(
|
||||
_ type: Record.Type = Record.self,
|
||||
forKey scope: String)
|
||||
throws -> Record?
|
||||
@@ -1228,37 +1448,48 @@ extension Row {
|
||||
return try Record(row: scopedRow)
|
||||
}
|
||||
|
||||
/// Returns the record associated with the given scope.
|
||||
/// Returns the record associated with the given key.
|
||||
///
|
||||
/// The key is a row scope that was either defined manually, with
|
||||
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
|
||||
/// and ``JoinableRequest/including(optional:)`` request methods. The
|
||||
/// latter define row scopes named after the key of included
|
||||
/// associations between record types.
|
||||
///
|
||||
/// A breadth-first search is performed in all available scopes in the row,
|
||||
/// recursively.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let request = Book.including(required: Book.author)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
/// ```swift
|
||||
/// struct Book: TableRecord, FetchableRecord {
|
||||
/// static let author = belongsTo(Author.self)
|
||||
/// }
|
||||
///
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
/// struct Author: TableRecord, FetchableRecord {
|
||||
/// static let country = belongsTo(Country.self)
|
||||
/// }
|
||||
///
|
||||
/// let author: Author = row["author"]
|
||||
/// print(author.name)
|
||||
/// // Prints "Herman Melville"
|
||||
/// struct Country: TableRecord, FetchableRecord { }
|
||||
///
|
||||
/// Associated records stored in nested associations are available, too:
|
||||
/// // Fetch a book, with its author, and the country of its author.
|
||||
/// let request = Book
|
||||
/// .including(required: Book.author
|
||||
/// .including(required: Author.country))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let request = Book.including(required: Book.author.including(required: Author.country))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
/// let book = try Book(row: row)
|
||||
/// let author: Author = try row.decode(forKey: "author")
|
||||
/// let country: Country = try row.decode(forKey: "country")
|
||||
/// ```
|
||||
///
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
/// For more details about row scopes, see ``ScopeAdapter``,
|
||||
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
|
||||
///
|
||||
/// let country: Country = row["country"]
|
||||
/// print(country.name)
|
||||
/// // Prints "United States"
|
||||
///
|
||||
/// A fatal error is raised if the scope is not available, or contains only
|
||||
/// null values.
|
||||
///
|
||||
/// See ``splittingRowAdapters(columnCounts:)`` for a sample code.
|
||||
func decode<Record: FetchableRecord>(
|
||||
/// - parameter type: The decoded type.
|
||||
/// - parameter scope: A scope identifier.
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
public func decode<Record: FetchableRecord>(
|
||||
_ type: Record.Type = Record.self,
|
||||
forKey scope: String)
|
||||
throws -> Record
|
||||
@@ -1300,20 +1531,34 @@ extension Row {
|
||||
// MARK: - Throwing Record RangeReplaceableCollection and Set Methods
|
||||
|
||||
extension Row {
|
||||
/// Returns the records encoded in the given prefetched rows.
|
||||
/// Returns a collection of prefetched records associated with the given
|
||||
/// association key.
|
||||
///
|
||||
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
|
||||
/// request method.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
/// ```swift
|
||||
/// struct Author: TableRecord, FetchableRecord {
|
||||
/// static let books = hasMany(Book.self)
|
||||
/// }
|
||||
///
|
||||
/// try print(Author(row: row).name)
|
||||
/// // Prints "Herman Melville"
|
||||
/// struct Book: TableRecord, FetchableRecord { }
|
||||
///
|
||||
/// let books: [Book] = row["books"]
|
||||
/// print(books[0].title)
|
||||
/// // Prints "Moby-Dick"
|
||||
func decode<Collection>(
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let author = try Author(row: row)
|
||||
/// let books: [Book] = try row.decode(forKey: "books")
|
||||
/// ```
|
||||
///
|
||||
/// See also: ``prefetchedRows``
|
||||
///
|
||||
/// - parameter type: The type of the decoded collection.
|
||||
/// - parameter key: An association key.
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
public func decode<Collection>(
|
||||
_ type: Collection.Type = Collection.self,
|
||||
forKey key: String)
|
||||
throws -> Collection
|
||||
@@ -1321,6 +1566,7 @@ extension Row {
|
||||
Collection: RangeReplaceableCollection,
|
||||
Collection.Element: FetchableRecord
|
||||
{
|
||||
// TODO: test independently
|
||||
guard let rows = prefetchedRows[key] else {
|
||||
let availableKeys = prefetchedRows.keys
|
||||
if availableKeys.isEmpty {
|
||||
@@ -1351,24 +1597,39 @@ extension Row {
|
||||
return collection
|
||||
}
|
||||
|
||||
/// Returns the set of records encoded in the given prefetched rows.
|
||||
/// Returns the set of prefetched records associated with the given
|
||||
/// association key.
|
||||
///
|
||||
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
|
||||
/// request method.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
/// ```swift
|
||||
/// struct Author: TableRecord, FetchableRecord {
|
||||
/// static let books = hasMany(Book.self)
|
||||
/// }
|
||||
///
|
||||
/// try print(Author(row: row).name)
|
||||
/// // Prints "Herman Melville"
|
||||
/// struct Book: TableRecord, FetchableRecord, Hashable { }
|
||||
///
|
||||
/// let books: Set<Book> = row["books"]
|
||||
/// print(books.first!.title)
|
||||
/// // Prints "Moby-Dick"
|
||||
func decode<Record: FetchableRecord & Hashable>(
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let author = try Author(row: row)
|
||||
/// let books: Set<Book> = try row.decode(forKey: "books")
|
||||
/// ```
|
||||
///
|
||||
/// See also: ``prefetchedRows``
|
||||
///
|
||||
/// - parameter type: The type of the decoded set.
|
||||
/// - parameter key: An association key.
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
public func decode<Record: FetchableRecord & Hashable>(
|
||||
_ type: Set<Record>.Type = Set<Record>.self,
|
||||
forKey key: String)
|
||||
throws -> Set<Record>
|
||||
{
|
||||
// TODO: test independently
|
||||
guard let rows = prefetchedRows[key] else {
|
||||
let availableKeys = prefetchedRows.keys
|
||||
if availableKeys.isEmpty {
|
||||
@@ -1735,11 +1996,17 @@ extension Row {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
/// let request = Player.filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Row> = """
|
||||
@@ -1784,11 +2051,17 @@ extension Row {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
/// let request = Player.filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Row> = """
|
||||
@@ -1816,11 +2089,17 @@ extension Row {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
/// let request = Player.filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Row> = """
|
||||
@@ -1852,11 +2131,17 @@ extension Row {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
/// let request = Player.filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Row> = """
|
||||
@@ -2110,7 +2395,7 @@ extension Row: CustomDebugStringConvertible {
|
||||
|
||||
extension Row: ExpressibleByDictionaryLiteral {
|
||||
/// Creates a row initialized with elements. Column order is preserved, and
|
||||
/// duplicated columns names are allowed.
|
||||
/// duplicated column names are allowed.
|
||||
///
|
||||
/// let row: Row = ["foo": 1, "foo": "bar", "baz": nil]
|
||||
/// print(row)
|
||||
@@ -2282,7 +2567,7 @@ extension Row {
|
||||
// (we preserve the ordering of associations in the request)
|
||||
fileprivate var prefetches: OrderedDictionary<String, Prefetch> = [:]
|
||||
|
||||
/// A boolean value indicating if there is no prefetched
|
||||
/// A boolean value indicating if there are no prefetched
|
||||
/// associated rows.
|
||||
public var isEmpty: Bool {
|
||||
prefetches.isEmpty
|
||||
@@ -2440,7 +2725,7 @@ extension RowImpl {
|
||||
}
|
||||
|
||||
// TODO: merge with StatementCopyRowImpl eventually?
|
||||
/// See Row.init(dictionary:)
|
||||
/// See Row.init(_:)
|
||||
struct ArrayRowImpl: RowImpl {
|
||||
let columns: [(String, DatabaseValue)]
|
||||
|
||||
@@ -2473,7 +2758,7 @@ struct ArrayRowImpl: RowImpl {
|
||||
extension ArrayRowImpl: Sendable { }
|
||||
|
||||
// TODO: merge with ArrayRowImpl eventually?
|
||||
/// See Row.init(copiedFromStatementRef:sqliteStatement:)
|
||||
/// See Row.init(copiedFromSQLiteStatement:statement:)
|
||||
private struct StatementCopyRowImpl: RowImpl {
|
||||
let dbValues: ContiguousArray<DatabaseValue>
|
||||
let columnNames: [String]
|
||||
@@ -2513,19 +2798,10 @@ private struct StatementCopyRowImpl: RowImpl {
|
||||
private struct StatementRowImpl: RowImpl {
|
||||
let statement: Statement
|
||||
let sqliteStatement: SQLiteStatement
|
||||
let lowercaseColumnIndexes: [String: Int]
|
||||
|
||||
init(sqliteStatement: SQLiteStatement, statement: Statement) {
|
||||
self.statement = statement
|
||||
self.sqliteStatement = sqliteStatement
|
||||
// Optimize row[columnName]
|
||||
let lowercaseColumnNames = (0..<sqlite3_column_count(sqliteStatement))
|
||||
.map { String(cString: sqlite3_column_name(sqliteStatement, CInt($0))).lowercased() }
|
||||
self.lowercaseColumnIndexes = Dictionary(
|
||||
lowercaseColumnNames
|
||||
.enumerated()
|
||||
.map { ($0.element, $0.offset) },
|
||||
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
|
||||
}
|
||||
|
||||
var count: Int {
|
||||
@@ -2572,6 +2848,7 @@ private struct StatementRowImpl: RowImpl {
|
||||
}
|
||||
|
||||
func index(forColumn name: String) -> Int? {
|
||||
let lowercaseColumnIndexes = statement.columnIndexes
|
||||
if let index = lowercaseColumnIndexes[name] {
|
||||
return index
|
||||
}
|
||||
|
||||
+16
-17
@@ -16,7 +16,7 @@ import Foundation
|
||||
/// """
|
||||
/// ```
|
||||
///
|
||||
/// The resulting rows contains columns from both player and team tables:
|
||||
/// The resulting rows contain columns from both player and team tables:
|
||||
///
|
||||
/// ```swift
|
||||
/// // [id: 1, name: "Arthur", teamId: 42, id: 42, name: "Reds"]
|
||||
@@ -32,7 +32,7 @@ import Foundation
|
||||
/// access player and team columns independently, with row ``Row/scopes``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let adapters = try splittingRowAdapters([
|
||||
/// let adapters = try splittingRowAdapters(columnCounts: [
|
||||
/// db.columns(in: "player").count,
|
||||
/// db.columns(in: "team").count,
|
||||
/// ])
|
||||
@@ -60,12 +60,12 @@ import Foundation
|
||||
///
|
||||
/// // Team(id: 42, name: "Reds")
|
||||
/// // nil if the LEFT JOIN has fetched NULL team columns
|
||||
/// if let team: Team? = row["team"]
|
||||
/// let team: Team? = row["team"]
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// You can package this technique in a dedicated type, as in the next
|
||||
/// example. It enhances the previous sample codes with:
|
||||
/// example. It enhances the previous code samples with:
|
||||
///
|
||||
/// - Support for record types that customize their fetched columns
|
||||
/// with ``TableRecord/databaseSelection-7iphs``.
|
||||
@@ -96,7 +96,7 @@ import Foundation
|
||||
/// let request: SQLRequest<PlayerInfo> = """
|
||||
/// SELECT
|
||||
/// \(columnsOf: Player.self), -- Instead of player.*
|
||||
/// \(columnsOf: Team.self), -- Instead of team.*
|
||||
/// \(columnsOf: Team.self) -- Instead of team.*
|
||||
/// FROM player
|
||||
/// LEFT JOIN team ON team.id = player.teamId
|
||||
/// WHERE player.id = \(playerId)
|
||||
@@ -159,7 +159,7 @@ public struct _LayoutedColumnMapping {
|
||||
/// that column.
|
||||
public let _layoutColumns: [(Int, String)]
|
||||
|
||||
/// A cache for layoutIndex(ofColumn:)
|
||||
/// A cache for _layoutIndex(ofColumn:)
|
||||
let lowercaseColumnIndexes: [String: Int] // [mappedColumn: layoutColumnIndex]
|
||||
|
||||
/// Creates a _LayoutedColumnMapping from an array of (baseIndex, mappedName)
|
||||
@@ -176,7 +176,7 @@ public struct _LayoutedColumnMapping {
|
||||
/// Use it in your custom RowAdapter type:
|
||||
///
|
||||
/// struct FooBarAdapter : RowAdapter {
|
||||
/// func layoutAdapter(layout: _RowLayout) throws -> any _LayoutedRowAdapter {
|
||||
/// func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter {
|
||||
/// return _LayoutedColumnMapping(layoutColumns: [(1, "foo"), (2, "bar")])
|
||||
/// }
|
||||
/// }
|
||||
@@ -222,7 +222,7 @@ extension _LayoutedColumnMapping: _RowLayout {
|
||||
|
||||
/// `_LayoutedRowAdapter` is a protocol that supports the `RowAdapter` protocol.
|
||||
///
|
||||
/// GRBD ships with a ready-made type that adopts this protocol:
|
||||
/// GRDB ships with a ready-made type that adopts this protocol:
|
||||
/// `_LayoutedColumnMapping`.
|
||||
public protocol _LayoutedRowAdapter {
|
||||
/// A LayoutedColumnMapping that defines how to map a column name to a
|
||||
@@ -255,7 +255,7 @@ extension Statement: _RowLayout {
|
||||
}
|
||||
}
|
||||
|
||||
/// A type that helps two incompatible row interfaces working together.
|
||||
/// A type that helps two incompatible row interfaces work together.
|
||||
///
|
||||
/// Row adapters present database rows in the way expected by the
|
||||
/// row consumers.
|
||||
@@ -343,7 +343,7 @@ extension RowAdapter {
|
||||
/// Returns an adapter based on self, with added scopes.
|
||||
///
|
||||
/// If self already defines scopes, the added scopes replace
|
||||
/// eventual existing scopes with the same name.
|
||||
/// any existing scopes with the same name.
|
||||
///
|
||||
/// - parameter scopes: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
@@ -495,7 +495,7 @@ public struct RangeRowAdapter: RowAdapter, Sendable {
|
||||
/// `ScopeAdapter` is a row adapter that defines row scopes.
|
||||
///
|
||||
/// `ScopeAdapter` does not change the columns and values of the fetched
|
||||
/// row. Instead, it defines *scopes* based on other adapter, which you
|
||||
/// row. Instead, it defines *scopes* based on other adapters, which you
|
||||
/// access through the ``Row/scopes`` property of the fetched rows.
|
||||
///
|
||||
/// For example:
|
||||
@@ -559,7 +559,7 @@ public struct ScopeAdapter: RowAdapter {
|
||||
/// The scope adapters
|
||||
let scopes: [String: any RowAdapter]
|
||||
|
||||
/// Creates an adapter that preserves row contents and add scoped rows.
|
||||
/// Creates an adapter that preserves row contents and adds scoped rows.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -575,7 +575,7 @@ public struct ScopeAdapter: RowAdapter {
|
||||
self.init(base: SuffixRowAdapter(fromIndex: 0), scopes: scopes)
|
||||
}
|
||||
|
||||
/// Creates an adapter based on the base adapter, and add scoped rows.
|
||||
/// Creates an adapter based on the base adapter, and adds scoped rows.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -583,15 +583,14 @@ public struct ScopeAdapter: RowAdapter {
|
||||
/// let adapter = ScopeAdapter(base: baseAdapter, scopes: ["suffix": SuffixRowAdapter(fromIndex: 1)])
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 1, 2, 3", adapter: adapter)!
|
||||
/// row // [1]
|
||||
/// row.scopes["initial"] // [2, 3]
|
||||
/// row.scopes["suffix"] // [2, 3]
|
||||
///
|
||||
/// If the base adapter already defines scopes, the given scopes replace
|
||||
/// eventual existing scopes with the same name.
|
||||
/// any existing scopes with the same name.
|
||||
///
|
||||
/// This initializer is equivalent to `baseAdapter.addingScopes(scopes)`.
|
||||
///
|
||||
/// - parameter base: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
/// - parameter base: A row adapter.
|
||||
/// - parameter scopes: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
public init(base: some RowAdapter, scopes: [String: any RowAdapter]) {
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
/// A key that is used to decode a value in a row
|
||||
@@ -23,9 +26,21 @@ enum RowKey: Hashable, Sendable {
|
||||
case prefetchKey(String)
|
||||
}
|
||||
|
||||
/// A decoding error
|
||||
@usableFromInline
|
||||
enum RowDecodingError: Error {
|
||||
/// A decoding error thrown when decoding a database row.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
|
||||
/// // RowDecodingError: could not decode String from database value NULL.
|
||||
/// let name = try row.decode(String.self, forColumn: "name")
|
||||
/// ```
|
||||
public struct RowDecodingError: Error {
|
||||
enum Impl {
|
||||
case keyNotFound(RowKey, Context)
|
||||
case valueMismatch(Any.Type, Context)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
struct Context: CustomDebugStringConvertible, Sendable {
|
||||
/// A description of what went wrong, for debugging purposes.
|
||||
@@ -55,17 +70,19 @@ enum RowDecodingError: Error {
|
||||
}
|
||||
}
|
||||
|
||||
case keyNotFound(RowKey, Context)
|
||||
case valueMismatch(Any.Type, Context)
|
||||
|
||||
var impl: Impl
|
||||
var context: Context {
|
||||
switch self {
|
||||
switch impl {
|
||||
case .keyNotFound(_, let context),
|
||||
.valueMismatch(_, let context):
|
||||
return context
|
||||
}
|
||||
}
|
||||
|
||||
static func valueMismatch(_ type: Any.Type, _ context: Context) -> Self {
|
||||
self.init(impl: .valueMismatch(type, context))
|
||||
}
|
||||
|
||||
/// Convenience method that builds the
|
||||
/// `could not decode <Type> from database value <value>` error message.
|
||||
static func valueMismatch(
|
||||
@@ -74,11 +91,10 @@ enum RowDecodingError: Error {
|
||||
databaseValue: DatabaseValue)
|
||||
-> Self
|
||||
{
|
||||
valueMismatch(
|
||||
type,
|
||||
RowDecodingError.Context(decodingContext: context, debugDescription: """
|
||||
could not decode \(type) from database value \(databaseValue)
|
||||
"""))
|
||||
let context = RowDecodingError.Context(decodingContext: context, debugDescription: """
|
||||
could not decode \(type) from database value \(databaseValue)
|
||||
""")
|
||||
return self.init(impl: .valueMismatch(type, context))
|
||||
}
|
||||
|
||||
/// Convenience method that builds the
|
||||
@@ -115,11 +131,15 @@ enum RowDecodingError: Error {
|
||||
/// error message.
|
||||
@usableFromInline
|
||||
static func columnNotFound(_ columnName: String, context: RowDecodingContext) -> Self {
|
||||
keyNotFound(
|
||||
self.init(impl: .keyNotFound(
|
||||
.columnName(columnName),
|
||||
RowDecodingError.Context(decodingContext: context, debugDescription: """
|
||||
column not found: \(String(reflecting: columnName))
|
||||
"""))
|
||||
""")))
|
||||
}
|
||||
|
||||
static func keyNotFound(_ rowKey: RowKey, _ context: Context) -> Self {
|
||||
self.init(impl: .keyNotFound(rowKey, context))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,8 +187,7 @@ struct RowDecodingContext {
|
||||
}
|
||||
|
||||
extension RowDecodingError: CustomStringConvertible {
|
||||
@usableFromInline
|
||||
var description: String {
|
||||
public var description: String {
|
||||
let context = self.context
|
||||
let row = context.row
|
||||
var chunks: [String] = []
|
||||
|
||||
+6
-6
@@ -63,7 +63,7 @@ public struct SQL: Sendable {
|
||||
/// .filter(date(Column("createdAt")) == "2022-08-17")
|
||||
/// .including(required: Player.team)
|
||||
enum Element {
|
||||
/// A raw SQL literal with eventual arguments.
|
||||
/// A raw SQL literal with optional arguments.
|
||||
case sql(String, StatementArguments = StatementArguments())
|
||||
|
||||
/// A subquery.
|
||||
@@ -118,7 +118,7 @@ public struct SQL: Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func qualified(with alias: TableAlias) -> Element {
|
||||
fileprivate func qualified(with alias: TableAliasBase) -> Element {
|
||||
switch self {
|
||||
case .sql:
|
||||
// A raw SQL string can't be qualified with a table alias,
|
||||
@@ -144,7 +144,7 @@ public struct SQL: Sendable {
|
||||
}
|
||||
|
||||
/// Creates an `SQL` literal from a plain SQL string, and
|
||||
/// eventual arguments.
|
||||
/// optional arguments.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -192,7 +192,7 @@ public struct SQL: Sendable {
|
||||
try elements.map { try $0.sql(context) }.joined()
|
||||
}
|
||||
|
||||
func qualified(with alias: TableAlias) -> SQL {
|
||||
func qualified(with alias: TableAliasBase) -> SQL {
|
||||
SQL(elements: elements.map { $0.qualified(with: alias) })
|
||||
}
|
||||
}
|
||||
@@ -240,7 +240,7 @@ extension SQL {
|
||||
self += sqlLiteral
|
||||
}
|
||||
|
||||
/// Appends a plain SQL string to the receiver, and eventual arguments.
|
||||
/// Appends a plain SQL string to the receiver, and optional arguments.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -300,7 +300,7 @@ extension SQL: SQLOrderingTerm {
|
||||
/// let request = Player.order(ordering)
|
||||
/// ```
|
||||
///
|
||||
/// An ordering term is only valid if it represent a single ordering terms.
|
||||
/// An ordering term is only valid if it represents a single ordering term.
|
||||
///
|
||||
/// ```swift
|
||||
/// // Valid
|
||||
|
||||
@@ -11,7 +11,7 @@ public struct SQLInterpolation: StringInterpolationProtocol {
|
||||
elements.append(.sql(sql))
|
||||
}
|
||||
|
||||
/// Appends a raw SQL snippet, with eventual arguments.
|
||||
/// Appends a raw SQL snippet, with optional arguments.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
|
||||
@@ -48,7 +48,7 @@ public struct SQLRequest<RowDecoder> {
|
||||
/// There are two statement caches: one "public" for statements generated by
|
||||
/// the user, and one "internal" for the statements generated by GRDB. Those
|
||||
/// are separated so that GRDB has no opportunity to inadvertently modify
|
||||
/// the arguments of user's cached statements.
|
||||
/// the arguments of the user's cached statements.
|
||||
enum Cache {
|
||||
/// The public cache, for library user
|
||||
case `public`
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
#endif
|
||||
import Dispatch
|
||||
|
||||
/// SchedulingWatchdog makes sure that databases connections are used on correct
|
||||
/// SchedulingWatchdog makes sure that database connections are used on correct
|
||||
/// dispatch queues, and warns the user with a fatal error whenever she misuses
|
||||
/// a database connection.
|
||||
///
|
||||
@@ -12,14 +12,14 @@ import Dispatch
|
||||
/// <https://github.com/groue/GRDB.swift/issues/55>. To support this use case, a
|
||||
/// single dispatch queue can be temporarily shared by two or more connections.
|
||||
///
|
||||
/// - SchedulingWatchdog.makeSerializedQueue(allowingDatabase:) creates a
|
||||
/// dispatch queue that allows one database.
|
||||
/// - SchedulingWatchdog.allowDatabase(_:onQueue:) makes a dispatch queue
|
||||
/// allow one database.
|
||||
///
|
||||
/// It does so by registering one instance of SchedulingWatchdog as a specific
|
||||
/// of the dispatch queue, a SchedulingWatchdog that allows that database only.
|
||||
///
|
||||
/// Later on, the queue can be shared by several databases with the method
|
||||
/// inheritingAllowedDatabases(from:execute:). See SerializedDatabase.sync()
|
||||
/// inheritingAllowedDatabases(_:execute:). See SerializedDatabase.sync()
|
||||
/// for an example.
|
||||
///
|
||||
/// - preconditionValidQueue() crashes whenever a database is used in an invalid
|
||||
@@ -77,6 +77,7 @@ final class SchedulingWatchdog: @unchecked Sendable {
|
||||
allowedDatabases.contains { $0 === db }
|
||||
}
|
||||
|
||||
/// When nil, no database is allowed in the current execution context.
|
||||
static var current: SchedulingWatchdog? {
|
||||
DispatchQueue.getSpecific(key: watchDogKey)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,9 @@ final class SerializedDatabase {
|
||||
/// The database connection
|
||||
private let db: Database
|
||||
|
||||
/// The actor that performs asynchronous accesses
|
||||
private let actor: DispatchQueueActor
|
||||
|
||||
/// The database configuration
|
||||
var configuration: Configuration { db.configuration }
|
||||
|
||||
@@ -55,6 +58,8 @@ final class SerializedDatabase {
|
||||
} else {
|
||||
self.queue = configuration.makeWriterDispatchQueue(label: identifier)
|
||||
}
|
||||
self.actor = DispatchQueueActor(queue: queue)
|
||||
|
||||
SchedulingWatchdog.allowDatabase(db, onQueue: queue)
|
||||
try queue.sync {
|
||||
do {
|
||||
@@ -230,7 +235,7 @@ final class SerializedDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if any only if the current dispatch queue is valid.
|
||||
/// Returns true if and only if the current dispatch queue is valid.
|
||||
var onValidQueue: Bool {
|
||||
SchedulingWatchdog.current?.allows(db) ?? false
|
||||
}
|
||||
@@ -243,22 +248,24 @@ final class SerializedDatabase {
|
||||
return try block(db)
|
||||
}
|
||||
|
||||
/// Asynchrously executes the block.
|
||||
/// Asynchronously executes the block.
|
||||
func execute<T: Sendable>(
|
||||
_ block: @escaping @Sendable (Database) throws -> T
|
||||
_ block: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
let dbAccess = CancellableDatabaseAccess()
|
||||
return try await dbAccess.withCancellableContinuation { continuation in
|
||||
self.async { db in
|
||||
do {
|
||||
let result = try dbAccess.inDatabase(db) {
|
||||
try block(db)
|
||||
}
|
||||
continuation.resume(returning: result)
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
let cancelMutex = Mutex<(@Sendable () -> Void)?>(nil)
|
||||
return try await withTaskCancellationHandler {
|
||||
try await actor.execute {
|
||||
defer {
|
||||
cancelMutex.store(nil)
|
||||
db.uncancel()
|
||||
preconditionNoUnsafeTransactionLeft(db)
|
||||
}
|
||||
cancelMutex.store(db.cancel)
|
||||
try Task.checkCancellation()
|
||||
return try block(db)
|
||||
}
|
||||
} onCancel: {
|
||||
cancelMutex.withLock { $0?() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,10 +293,10 @@ final class SerializedDatabase {
|
||||
SchedulingWatchdog.preconditionValidQueue(db, message(), file: file, line: line)
|
||||
}
|
||||
|
||||
/// Fatal error if a transaction has been left opened.
|
||||
/// Fatal error if a transaction has been left open.
|
||||
private func preconditionNoUnsafeTransactionLeft(
|
||||
_ db: Database,
|
||||
_ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access",
|
||||
_ message: @autoclosure() -> String = "A transaction has been left open at the end of a database access",
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
{
|
||||
@@ -305,108 +312,3 @@ final class SerializedDatabase {
|
||||
// It happens the job of SerializedDatabase is precisely to provide thread-safe
|
||||
// access to `Database`.
|
||||
extension SerializedDatabase: @unchecked Sendable { }
|
||||
|
||||
// MARK: - Task Cancellation Support
|
||||
|
||||
enum DatabaseAccessCancellationState: @unchecked Sendable {
|
||||
// @unchecked Sendable because database is only accessed from its
|
||||
// dispatch queue.
|
||||
case notConnected
|
||||
case connected(Database)
|
||||
case cancelled
|
||||
case expired
|
||||
}
|
||||
|
||||
typealias CancellableDatabaseAccess = Mutex<DatabaseAccessCancellationState>
|
||||
|
||||
/// Supports Task cancellation in async database accesses.
|
||||
///
|
||||
/// Usage:
|
||||
///
|
||||
/// ```swift
|
||||
/// let dbAccess = CancellableDatabaseAccess()
|
||||
/// return try dbAccess.withCancellableContinuation { continuation in
|
||||
/// asyncDatabaseAccess { db in
|
||||
/// do {
|
||||
/// let result = try dbAccess.inDatabase(db) {
|
||||
/// // Perform database operations
|
||||
/// }
|
||||
/// continuation.resume(returning: result)
|
||||
/// } catch {
|
||||
/// continuation.resume(throwing: error)
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
extension CancellableDatabaseAccess: DatabaseCancellable {
|
||||
convenience init() {
|
||||
self.init(.notConnected)
|
||||
}
|
||||
|
||||
func cancel() {
|
||||
withLock { state in
|
||||
switch state {
|
||||
case let .connected(db):
|
||||
db.cancel()
|
||||
state = .cancelled
|
||||
case .notConnected:
|
||||
state = .cancelled
|
||||
case .cancelled, .expired:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func withCancellableContinuation<Value>(
|
||||
_ fn: (UnsafeContinuation<Value, any Error>) -> Void
|
||||
) async throws -> Value {
|
||||
try await withTaskCancellationHandler {
|
||||
try checkCancellation()
|
||||
return try await withUnsafeThrowingContinuation { continuation in
|
||||
fn(continuation)
|
||||
}
|
||||
} onCancel: {
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
func checkCancellation() throws {
|
||||
try withLock { state in
|
||||
if case .cancelled = state {
|
||||
throw CancellationError()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps a full database access with cancellation support. When this
|
||||
/// method returns, the database is NOT cancelled.
|
||||
func inDatabase<Value>(_ db: Database, execute work: () throws -> Value) throws -> Value {
|
||||
try withLock { state in
|
||||
switch state {
|
||||
case .connected, .expired:
|
||||
fatalError("Can't use a CancellableDatabaseAccess twice")
|
||||
case .notConnected:
|
||||
state = .connected(db)
|
||||
case .cancelled:
|
||||
throw CancellationError()
|
||||
}
|
||||
}
|
||||
|
||||
return try throwingFirstError {
|
||||
try work()
|
||||
} finally: {
|
||||
let cancelled = withLock { state in
|
||||
if case .cancelled = state {
|
||||
db.uncancel()
|
||||
return true
|
||||
} else {
|
||||
state = .expired
|
||||
return false
|
||||
}
|
||||
}
|
||||
if cancelled {
|
||||
throw CancellationError()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+88
-54
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -21,7 +24,7 @@ extension String {
|
||||
/// SQL statements with `String.trimmedSQLStatement`.
|
||||
private static let sqlStatementSeparators = CharacterSet(charactersIn: ";").union(.whitespacesAndNewlines)
|
||||
|
||||
/// Returns a string trimmed from SQL statement separators.
|
||||
/// Returns a string trimmed of SQL statement separators.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -44,6 +47,25 @@ public final class Statement {
|
||||
case rollbackSavepoint(String)
|
||||
}
|
||||
|
||||
/// The column names and indexes of a statement, for a given compilation
|
||||
/// of the statement.
|
||||
private struct ColumnCache {
|
||||
var reprepareCount: CInt
|
||||
var columnNames: [String]
|
||||
/// Indexes of the leftmost columns. Keys are lowercase.
|
||||
var columnIndexes: [String: Int]
|
||||
|
||||
init(sqliteStatement: SQLiteStatement, reprepareCount: CInt) {
|
||||
self.reprepareCount = reprepareCount
|
||||
self.columnNames = (0..<sqlite3_column_count(sqliteStatement)).map {
|
||||
String(cString: sqlite3_column_name(sqliteStatement, $0))
|
||||
}
|
||||
self.columnIndexes = Dictionary(
|
||||
columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
|
||||
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
|
||||
}
|
||||
}
|
||||
|
||||
/// The raw SQLite statement, suitable for the SQLite C API.
|
||||
public let sqliteStatement: SQLiteStatement
|
||||
|
||||
@@ -56,11 +78,9 @@ public final class Statement {
|
||||
}
|
||||
|
||||
/// The column names, ordered from left to right.
|
||||
public lazy var columnNames: [String] = {
|
||||
// swiftlint:disable:next redundant_self_in_closure
|
||||
let sqliteStatement = self.sqliteStatement
|
||||
return (0..<CInt(columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
|
||||
}()
|
||||
public var columnNames: [String] {
|
||||
columnCache.columnNames
|
||||
}
|
||||
|
||||
// The database region is reported by `sqlite3_set_authorizer`, and maybe
|
||||
// refined in `SQLQueryGenerator.makeStatement(_:)` when we have enough
|
||||
@@ -73,7 +93,7 @@ public final class Statement {
|
||||
///
|
||||
/// ```swift
|
||||
/// // Reads score, writes bonus
|
||||
/// let statement = db.makeStatement(sql: """
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// UPDATE player SET bonus = 0 WHERE score = 0
|
||||
/// """)
|
||||
///
|
||||
@@ -86,13 +106,13 @@ public final class Statement {
|
||||
/// is executed (reported by `sqlite3_set_authorizer`).
|
||||
private(set) var invalidatesDatabaseSchemaCache = false
|
||||
|
||||
/// The eventual effect of transactions, as reported by `sqlite3_set_authorizer`.
|
||||
/// The optional effect of transactions, as reported by `sqlite3_set_authorizer`.
|
||||
private(set) var transactionEffect: TransactionEffect?
|
||||
|
||||
/// The effects on the database (reported by `sqlite3_set_authorizer`).
|
||||
private(set) var authorizerEventKinds: [DatabaseEventKind] = []
|
||||
|
||||
/// If true, the statement executes is a `PRAGMA QUERY_ONLY` statement.
|
||||
/// If true, the statement is a `PRAGMA QUERY_ONLY` statement.
|
||||
private(set) var isQueryOnlyPragma = false
|
||||
|
||||
/// A boolean value indicating if the prepared statement makes no direct
|
||||
@@ -111,12 +131,29 @@ public final class Statement {
|
||||
@usableFromInline
|
||||
unowned let database: Database
|
||||
|
||||
/// Cache for index(ofColumn:). Keys are lowercase.
|
||||
private lazy var columnIndexes: [String: Int] = {
|
||||
Dictionary(
|
||||
columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
|
||||
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
|
||||
}()
|
||||
/// Indexes of the leftmost columns. Keys are lowercase.
|
||||
var columnIndexes: [String: Int] {
|
||||
columnCache.columnIndexes
|
||||
}
|
||||
|
||||
/// Storage for `columnCache`.
|
||||
private var _columnCache: ColumnCache?
|
||||
|
||||
/// The column names and indexes.
|
||||
///
|
||||
/// SQLite recompiles statements after schema changes (see
|
||||
/// <https://www.sqlite.org/c3ref/prepare.html>), and this can change
|
||||
/// the result columns (think `SELECT *` after a column was added).
|
||||
/// So the cache is rebuilt whenever the statement is recompiled.
|
||||
private var columnCache: ColumnCache {
|
||||
let reprepareCount = sqlite3_stmt_status(sqliteStatement, SQLITE_STMTSTATUS_REPREPARE, 0)
|
||||
if let _columnCache, _columnCache.reprepareCount == reprepareCount {
|
||||
return _columnCache
|
||||
}
|
||||
let columnCache = ColumnCache(sqliteStatement: sqliteStatement, reprepareCount: reprepareCount)
|
||||
_columnCache = columnCache
|
||||
return columnCache
|
||||
}
|
||||
|
||||
/// Creates a prepared statement. Returns nil if the compiled string is
|
||||
/// blank or empty.
|
||||
@@ -141,16 +178,13 @@ public final class Statement {
|
||||
let authorizer = database.authorizer
|
||||
authorizer.reset()
|
||||
|
||||
var sqliteStatement: SQLiteStatement? = nil
|
||||
var sqliteStatement: SQLiteStatement?
|
||||
let code = sqlite3_prepare_v3(
|
||||
database.sqliteConnection, statementStart, -1, prepFlags,
|
||||
&sqliteStatement, statementEnd)
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(
|
||||
resultCode: code,
|
||||
message: database.lastErrorMessage,
|
||||
sql: String(cString: statementStart))
|
||||
try database.statementCompilationDidFail(at: statementStart, withResultCode: code)
|
||||
}
|
||||
|
||||
guard let sqliteStatement else {
|
||||
@@ -243,7 +277,7 @@ public final class Statement {
|
||||
///
|
||||
/// ```swift
|
||||
/// // This statement expects two arguments
|
||||
/// let statement = try db.makeUpdateArgument(sql: """
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// INSERT INTO player (id, name) VALUES (?, ?)
|
||||
/// """)
|
||||
///
|
||||
@@ -254,7 +288,7 @@ public final class Statement {
|
||||
/// print(statement.arguments)
|
||||
/// ```
|
||||
///
|
||||
/// If is a programmer error to set arguments that do not provide all
|
||||
/// It is a programmer error to set arguments that do not provide all
|
||||
/// values expected by the statement:
|
||||
///
|
||||
/// ```swift
|
||||
@@ -275,23 +309,23 @@ public final class Statement {
|
||||
}
|
||||
}
|
||||
|
||||
/// Throws a ``DatabaseError`` of code `SQLITE_ERROR` if the provided
|
||||
/// Throws a ``DatabaseError`` of code `SQLITE_MISUSE` if the provided
|
||||
/// arguments do not provide all values expected by the statement.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // This statement expects two arguments
|
||||
/// let statement = try db.makeUpdateArgument(sql: """
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// INSERT INTO player (id, name) VALUES (?, ?)
|
||||
/// """)
|
||||
///
|
||||
/// // OK
|
||||
/// statement.validateArguments([1, "Arthur"])
|
||||
/// try statement.validateArguments([1, "Arthur"])
|
||||
///
|
||||
/// // Throws
|
||||
/// try statement.setArguments([1])
|
||||
/// try statement.setArguments([1, "Arthur", Date()])
|
||||
/// try statement.validateArguments([1])
|
||||
/// try statement.validateArguments([1, "Arthur", Date()])
|
||||
/// ```
|
||||
///
|
||||
/// See also ``setArguments(_:)``.
|
||||
@@ -311,7 +345,7 @@ public final class Statement {
|
||||
///
|
||||
/// ```swift
|
||||
/// // This statement expects two arguments
|
||||
/// let statement = try db.makeUpdateArgument(sql: """
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// INSERT INTO player (id, name) VALUES (?, ?)
|
||||
/// """)
|
||||
///
|
||||
@@ -354,7 +388,7 @@ public final class Statement {
|
||||
///
|
||||
/// ```swift
|
||||
/// // This statement expects two arguments
|
||||
/// let statement = try db.makeUpdateArgument(sql: """
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// INSERT INTO player (id, name) VALUES (?, ?)
|
||||
/// """)
|
||||
///
|
||||
@@ -442,7 +476,7 @@ public final class Statement {
|
||||
}
|
||||
|
||||
/// Convenience method that resets, sets arguments if needed, and checks
|
||||
/// arguments validity.
|
||||
/// argument validity.
|
||||
///
|
||||
/// - parameter newArguments: if not nil, this method sets arguments.
|
||||
func prepareExecution(withArguments newArguments: StatementArguments? = nil) throws {
|
||||
@@ -513,11 +547,11 @@ public final class Statement {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When arguments are set at the moment of execution, with an non-nil
|
||||
/// When arguments are set at the moment of execution, with a non-nil
|
||||
/// `arguments` parameter, it is assumed that the statement won't be
|
||||
/// reused with the same arguments. When the number of arguments is
|
||||
/// small, execution is performed with temporary SQLite bindings that
|
||||
/// avoid copying strings and blobs arguments.
|
||||
/// avoid copying string and blob arguments.
|
||||
///
|
||||
/// For more information, see [`SQLITE_STATIC` and `SQLITE_TRANSIENT`](https://www.sqlite.org/c3ref/c_static.html).
|
||||
/// Compare:
|
||||
@@ -533,7 +567,7 @@ public final class Statement {
|
||||
/// ```
|
||||
///
|
||||
/// Both techniques have the same results, but when you care about
|
||||
/// performances, monitor your application in order to make the
|
||||
/// performance, monitor your application in order to make the
|
||||
/// best choice.
|
||||
///
|
||||
/// - parameter arguments: Optional statement arguments.
|
||||
@@ -582,7 +616,7 @@ public final class Statement {
|
||||
|
||||
/// Calls the given closure after each successful call to `sqlite3_step()`.
|
||||
///
|
||||
/// This method is slighly faster than calling `step(_:)` repeatedly, due
|
||||
/// This method is slightly faster than calling `step(_:)` repeatedly, due
|
||||
/// to the single `sqlite3_stmt_busy` check.
|
||||
@usableFromInline
|
||||
func forEachStep(_ body: (SQLiteStatement) throws -> Void) throws {
|
||||
@@ -775,7 +809,7 @@ extension DatabaseCursor {
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let statement = try db.makeStatement(sql: "SELECT performSideEffect()")
|
||||
/// let cursor = statement.makeCursor()
|
||||
/// let cursor = try statement.makeCursor()
|
||||
/// try cursor.next()
|
||||
/// }
|
||||
/// ```
|
||||
@@ -891,13 +925,13 @@ func withBindings<T>(
|
||||
/// - `@AAAA` (e.g. `@name`): named argument
|
||||
/// - `$AAAA` (e.g. `$name`): named argument
|
||||
///
|
||||
/// All forms are supported, but GRDB does not allow to distinguish between
|
||||
/// All forms are supported, but GRDB does not allow you to distinguish between
|
||||
/// the `:AAAA`, `@AAAA`, and `$AAAA` syntaxes. You are encouraged to write
|
||||
/// named arguments with a colon prefix: `:name`.
|
||||
///
|
||||
/// ## Positional Arguments
|
||||
///
|
||||
/// To fill question marks placeholders, feed `StatementArguments` with an array:
|
||||
/// To fill question mark placeholders, feed `StatementArguments` with an array:
|
||||
///
|
||||
/// ```swift
|
||||
/// try db.execute(
|
||||
@@ -949,7 +983,7 @@ func withBindings<T>(
|
||||
/// arguments += ["name": "Barbara"]
|
||||
/// ```
|
||||
///
|
||||
/// On the other side, `&+` and ``StatementArguments/append(contentsOf:)``
|
||||
/// On the other hand, `&+` and ``StatementArguments/append(contentsOf:)``
|
||||
/// allow overriding named arguments:
|
||||
///
|
||||
/// ```swift
|
||||
@@ -974,7 +1008,7 @@ func withBindings<T>(
|
||||
/// print(row)
|
||||
/// ```
|
||||
///
|
||||
/// Mixed arguments exist as a support for requests like the following:
|
||||
/// Mixed arguments exist to support requests like the following:
|
||||
///
|
||||
/// ```swift
|
||||
/// let players = try Player
|
||||
@@ -1007,7 +1041,7 @@ public struct StatementArguments: Hashable {
|
||||
///
|
||||
/// ```swift
|
||||
/// let values: [(any DatabaseValueConvertible)?] = ["foo", 1, nil]
|
||||
/// db.execute(sql: "INSERT ... (?,?,?)", arguments: StatementArguments(values))
|
||||
/// try db.execute(sql: "INSERT ... (?,?,?)", arguments: StatementArguments(values))
|
||||
/// ```
|
||||
public init(_ values: some Sequence<(any DatabaseValueConvertible)?>) {
|
||||
self.values = values.map { $0?.databaseValue ?? .null }
|
||||
@@ -1020,7 +1054,7 @@ public struct StatementArguments: Hashable {
|
||||
///
|
||||
/// ```swift
|
||||
/// let values: [String] = ["foo", "bar"]
|
||||
/// db.execute(sql: "INSERT ... (?,?)", arguments: StatementArguments(values))
|
||||
/// try db.execute(sql: "INSERT ... (?,?)", arguments: StatementArguments(values))
|
||||
/// ```
|
||||
public init(_ values: some Sequence<some DatabaseValueConvertible>) {
|
||||
self.values = values.map(\.databaseValue)
|
||||
@@ -1055,7 +1089,7 @@ public struct StatementArguments: Hashable {
|
||||
///
|
||||
/// ```swift
|
||||
/// let values: [String: (any DatabaseValueConvertible)?] = ["firstName": nil, "lastName": "Miller"]
|
||||
/// db.execute(sql: "INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
|
||||
/// try db.execute(sql: "INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
|
||||
/// ```
|
||||
public init(_ dictionary: [String: (any DatabaseValueConvertible)?]) {
|
||||
namedValues = dictionary.mapValues { $0?.databaseValue ?? .null }
|
||||
@@ -1154,7 +1188,7 @@ public struct StatementArguments: Hashable {
|
||||
return replacedValues
|
||||
}
|
||||
|
||||
/// Creates a new `StatementArguments` by extending the left-hand size
|
||||
/// Creates a new `StatementArguments` by extending the left-hand side
|
||||
/// arguments with the right-hand side arguments.
|
||||
///
|
||||
/// Positional arguments are concatenated:
|
||||
@@ -1175,7 +1209,7 @@ public struct StatementArguments: Hashable {
|
||||
/// print(arguments)
|
||||
/// ```
|
||||
///
|
||||
/// If the arguments on the right-hand side has named parameters that are
|
||||
/// If the arguments on the right-hand side have named parameters that are
|
||||
/// already defined on the left, a fatal error is raised:
|
||||
///
|
||||
/// ```swift
|
||||
@@ -1202,7 +1236,7 @@ public struct StatementArguments: Hashable {
|
||||
return lhs
|
||||
}
|
||||
|
||||
/// Creates a new `StatementArguments` by extending the left-hand size
|
||||
/// Creates a new `StatementArguments` by extending the left-hand side
|
||||
/// arguments with the right-hand side arguments.
|
||||
///
|
||||
/// Positional arguments are concatenated:
|
||||
@@ -1223,7 +1257,7 @@ public struct StatementArguments: Hashable {
|
||||
/// print(arguments)
|
||||
/// ```
|
||||
///
|
||||
/// If a named arguments is defined in both arguments, the right-hand
|
||||
/// If a named argument is defined in both arguments, the right-hand
|
||||
/// side wins:
|
||||
///
|
||||
/// ```swift
|
||||
@@ -1248,7 +1282,7 @@ public struct StatementArguments: Hashable {
|
||||
return lhs
|
||||
}
|
||||
|
||||
/// Extends the left-hand size arguments with the right-hand side arguments.
|
||||
/// Extends the left-hand side arguments with the right-hand side arguments.
|
||||
///
|
||||
/// Positional arguments are concatenated:
|
||||
///
|
||||
@@ -1270,7 +1304,7 @@ public struct StatementArguments: Hashable {
|
||||
/// print(arguments)
|
||||
/// ```
|
||||
///
|
||||
/// If the arguments on the right-hand side has named parameters that are
|
||||
/// If the arguments on the right-hand side have named parameters that are
|
||||
/// already defined on the left, a fatal error is raised:
|
||||
///
|
||||
/// ```swift
|
||||
@@ -1357,7 +1391,7 @@ extension StatementArguments: ExpressibleByArrayLiteral {
|
||||
/// ```swift
|
||||
/// let arguments: StatementArguments = ["Arthur", 41]
|
||||
/// try db.execute(
|
||||
/// sql: "INSERT INTO player (name, score) VALUES (?, ?)"
|
||||
/// sql: "INSERT INTO player (name, score) VALUES (?, ?)",
|
||||
/// arguments: arguments)
|
||||
/// ```
|
||||
public init(arrayLiteral elements: (any DatabaseValueConvertible)?...) {
|
||||
@@ -1373,7 +1407,7 @@ extension StatementArguments: ExpressibleByDictionaryLiteral {
|
||||
/// ```swift
|
||||
/// let arguments: StatementArguments = ["name": "Arthur", "score": 41]
|
||||
/// try db.execute(
|
||||
/// sql: "INSERT INTO player (name, score) VALUES (:name, :score)"
|
||||
/// sql: "INSERT INTO player (name, score) VALUES (:name, :score)",
|
||||
/// arguments: arguments)
|
||||
/// ```
|
||||
public init(dictionaryLiteral elements: (String, (any DatabaseValueConvertible)?)...) {
|
||||
|
||||
@@ -1,16 +1,21 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
#if canImport(string_h)
|
||||
import string_h
|
||||
#elseif os(Linux)
|
||||
import Glibc
|
||||
#elseif os(Android)
|
||||
import Android
|
||||
#elseif os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(visionOS)
|
||||
import Darwin
|
||||
#elseif os(Windows)
|
||||
@@ -41,7 +46,7 @@ final class StatementAuthorizer {
|
||||
/// savepoint statement.
|
||||
var transactionEffect: Statement.TransactionEffect?
|
||||
|
||||
/// If true, the statement executes is a `PRAGMA QUERY_ONLY` statement.
|
||||
/// If true, the statement is a `PRAGMA QUERY_ONLY` statement.
|
||||
var isQueryOnlyPragma = false
|
||||
|
||||
private var isDropStatement = false
|
||||
@@ -112,10 +117,10 @@ final class 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.insert(table: tableName)
|
||||
} else {
|
||||
// SELECT column FROM table
|
||||
selectedRegion.formUnion(DatabaseRegion(table: tableName, columns: [columnName]))
|
||||
selectedRegion.insert(table: tableName, column: columnName)
|
||||
}
|
||||
return SQLITE_OK
|
||||
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
/// A type that can decode itself from the low-level C interface to
|
||||
@@ -19,7 +22,7 @@ import SQLite3
|
||||
///
|
||||
/// ```swift
|
||||
/// // Optimized
|
||||
/// let scores = Int.fetchAll(db, sql: "SELECT score FROM player")
|
||||
/// let scores = try Int.fetchAll(db, sql: "SELECT score FROM player")
|
||||
///
|
||||
/// let rows = try Row.fetchCursor(db, sql: "SELECT * FROM player")
|
||||
/// while let row = try rows.next() {
|
||||
@@ -100,7 +103,7 @@ public protocol StatementColumnConvertible {
|
||||
/// database values are handled
|
||||
/// in ``StatementColumnConvertible/fromStatement(_:atUncheckedIndex:)-2i8y6``.
|
||||
///
|
||||
/// For example, here is the how Int64 adopts StatementColumnConvertible:
|
||||
/// For example, here is how Int64 adopts StatementColumnConvertible:
|
||||
///
|
||||
/// ```swift
|
||||
/// extension Int64: StatementColumnConvertible {
|
||||
@@ -208,7 +211,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// let names: FastDatabaseValueCursor<String> = try String.fetchCursor(db, sql: """
|
||||
/// SELECT name FROM player
|
||||
/// """)
|
||||
/// while let name = names.next() { // String
|
||||
/// while let name = try names.next() { // String
|
||||
/// print(name)
|
||||
/// }
|
||||
/// }
|
||||
@@ -563,13 +566,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -608,13 +618,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -647,13 +664,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -681,20 +705,27 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
/// SELECT score FROM player WHERE lastName = \(lastName)
|
||||
/// """
|
||||
///
|
||||
/// let scores = try Int.fetchAll(db, request)
|
||||
/// let scores = try Int.fetchSet(db, request)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
@@ -720,13 +751,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -760,13 +798,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -796,13 +841,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -827,13 +879,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
#if canImport(CoreGraphics)
|
||||
import CoreGraphics
|
||||
#elseif !canImport(Darwin)
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
/// CGFloat adopts DatabaseValueConvertible
|
||||
extension CGFloat: DatabaseValueConvertible {
|
||||
@@ -15,4 +18,3 @@ extension CGFloat: DatabaseValueConvertible {
|
||||
return CGFloat(double)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux)
|
||||
/// NSDate is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
extension NSDate: DatabaseValueConvertible {
|
||||
@@ -38,7 +40,6 @@ extension NSDate: DatabaseValueConvertible {
|
||||
return cast(date)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Date is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
@@ -49,7 +50,7 @@ extension Date: DatabaseValueConvertible {
|
||||
storageDateFormatter.string(from: self).databaseValue
|
||||
}
|
||||
|
||||
/// Creates an `Date` with the specified database value.
|
||||
/// Creates a `Date` with the specified database value.
|
||||
///
|
||||
/// If the database value contains a number, that number is interpreted as a
|
||||
/// timeinterval since 00:00:00 UTC on 1 January 1970.
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
#if !os(Linux)
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -19,9 +21,9 @@ extension Decimal: DatabaseValueConvertible {
|
||||
.databaseValue
|
||||
}
|
||||
|
||||
/// Creates an `Decimal` with the specified database value.
|
||||
/// Creates a `Decimal` with the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer or a double, returns a
|
||||
/// If the database value contains an integer or a double, returns a
|
||||
/// `Decimal` initialized from this number.
|
||||
///
|
||||
/// If the database value contains a string, parses the string with the
|
||||
@@ -54,9 +56,8 @@ extension Decimal: StatementColumnConvertible {
|
||||
case SQLITE_FLOAT:
|
||||
self.init(sqlite3_column_double(sqliteStatement, index))
|
||||
case SQLITE_TEXT:
|
||||
self.init(
|
||||
string: String(cString: sqlite3_column_text(sqliteStatement, index)!),
|
||||
locale: _posixLocale)
|
||||
let string = String(sqliteStatement: sqliteStatement, index: index)
|
||||
self.init(string: string, locale: _posixLocale)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
@@ -65,4 +66,3 @@ extension Decimal: StatementColumnConvertible {
|
||||
|
||||
@usableFromInline
|
||||
let _posixLocale = Locale(identifier: "en_US_POSIX")
|
||||
#endif
|
||||
@@ -1,4 +1,3 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// NSData is convertible to and from DatabaseValue.
|
||||
@@ -9,7 +8,7 @@ extension NSData: DatabaseValueConvertible {
|
||||
(self as Data).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a `NSData` from the specified database value.
|
||||
/// Returns an `NSData` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a data blob, returns it.
|
||||
///
|
||||
@@ -24,4 +23,3 @@ extension NSData: DatabaseValueConvertible {
|
||||
return cast(data)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,4 +1,3 @@
|
||||
#if !os(Linux) && !os(Windows)
|
||||
import Foundation
|
||||
|
||||
private let integerRoundingBehavior = NSDecimalNumberHandler(
|
||||
@@ -20,7 +19,7 @@ extension NSNumber: DatabaseValueConvertible {
|
||||
/// Otherwise, returns an INTEGER or REAL database value, according to the
|
||||
/// value stored in the `NSNumber`.
|
||||
public var databaseValue: DatabaseValue {
|
||||
// Don't lose precision: store integers that fits in Int64 as Int64
|
||||
// Don't lose precision: store integers that fit in Int64 as Int64
|
||||
if let decimal = self as? NSDecimalNumber,
|
||||
decimal == decimal.rounding(accordingToBehavior: integerRoundingBehavior), // integer
|
||||
decimal.compare(NSDecimalNumber(value: Int64.max)) != .orderedDescending, // decimal <= Int64.max
|
||||
@@ -70,7 +69,7 @@ extension NSNumber: DatabaseValueConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a `NSNumber` from the specified database value.
|
||||
/// Returns an `NSNumber` from the specified database value.
|
||||
///
|
||||
/// If the database value is an integer or a double, returns an `NSNumber`
|
||||
/// initialized from this number.
|
||||
@@ -81,10 +80,18 @@ extension NSNumber: DatabaseValueConvertible {
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64) where self is NSDecimalNumber.Type:
|
||||
let number = NSDecimalNumber(value: int64)
|
||||
return number as? Self
|
||||
case .int64(let int64):
|
||||
return self.init(value: int64)
|
||||
let number = NSNumber(value: int64)
|
||||
return number as? Self
|
||||
case .double(let double) where self is NSDecimalNumber.Type:
|
||||
let number = NSDecimalNumber(value: double)
|
||||
return number as? Self
|
||||
case .double(let double):
|
||||
return self.init(value: double)
|
||||
let number = NSNumber(value: double)
|
||||
return number as? Self
|
||||
case let .string(string):
|
||||
// Must match Decimal.fromDatabaseValue(_:)
|
||||
guard let decimal = Decimal(string: string, locale: posixLocale) else { return nil }
|
||||
@@ -96,4 +103,3 @@ extension NSNumber: DatabaseValueConvertible {
|
||||
}
|
||||
|
||||
private let posixLocale = Locale(identifier: "en_US_POSIX")
|
||||
#endif
|
||||
@@ -1,4 +1,3 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// NSString adopts DatabaseValueConvertible
|
||||
@@ -9,11 +8,11 @@ extension NSString: DatabaseValueConvertible {
|
||||
(self as String).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a `NSString` from the specified database value.
|
||||
/// Returns an `NSString` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a string, returns it.
|
||||
///
|
||||
/// If the database value contains a data blob, parses this data as an
|
||||
/// If the database value contains a data blob, parses this data as a
|
||||
/// UTF8 string.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
@@ -24,4 +23,3 @@ extension NSString: DatabaseValueConvertible {
|
||||
return self.init(string: string)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,12 +1,15 @@
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux) && !os(Windows)
|
||||
/// NSURL stores its absoluteString in the database.
|
||||
extension NSURL: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a TEXT database value containing the absolute URL.
|
||||
public var databaseValue: DatabaseValue {
|
||||
absoluteString?.databaseValue ?? .null
|
||||
#if !canImport(Darwin)
|
||||
absoluteString.databaseValue
|
||||
#else
|
||||
absoluteString?.databaseValue ?? .null
|
||||
#endif
|
||||
}
|
||||
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
@@ -16,7 +19,6 @@ extension NSURL: DatabaseValueConvertible {
|
||||
return cast(URL(string: string))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// URL stores its absoluteString in the database.
|
||||
extension URL: DatabaseValueConvertible { }
|
||||
@@ -1,15 +1,17 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux) && !os(Windows)
|
||||
/// NSUUID adopts DatabaseValueConvertible
|
||||
extension NSUUID: DatabaseValueConvertible {
|
||||
/// Returns a BLOB database value containing the uuid bytes.
|
||||
@@ -21,9 +23,9 @@ extension NSUUID: DatabaseValueConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a `NSUUID` from the specified database value.
|
||||
/// Returns an `NSUUID` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a string, parses this string as an uuid.
|
||||
/// If the database value contains a string, parses this string as a uuid.
|
||||
///
|
||||
/// If the database value contains a data blob that contains 16 bytes,
|
||||
/// returns a uuid from those bytes.
|
||||
@@ -33,16 +35,22 @@ extension NSUUID: DatabaseValueConvertible {
|
||||
switch dbValue.storage {
|
||||
case .blob(let data) where data.count == 16:
|
||||
return data.withUnsafeBytes {
|
||||
self.init(uuidBytes: $0.bindMemory(to: UInt8.self).baseAddress)
|
||||
#if canImport(Darwin)
|
||||
self.init(uuidBytes: $0.bindMemory(to: UInt8.self).baseAddress)
|
||||
#else
|
||||
guard let uuidBytes = $0.bindMemory(to: UInt8.self).baseAddress else {
|
||||
return nil as Self?
|
||||
}
|
||||
return NSUUID(uuidBytes: uuidBytes) as? Self
|
||||
#endif
|
||||
}
|
||||
case .string(let string):
|
||||
return self.init(uuidString: string)
|
||||
return NSUUID(uuidString: string) as? Self
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// UUID adopts DatabaseValueConvertible
|
||||
extension UUID: DatabaseValueConvertible {
|
||||
@@ -55,7 +63,7 @@ extension UUID: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a `UUID` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a string, parses this string as an uuid.
|
||||
/// If the database value contains a string, parses this string as a uuid.
|
||||
///
|
||||
/// If the database value contains a data blob that contains 16 bytes,
|
||||
/// returns a uuid from those bytes.
|
||||
@@ -81,15 +89,15 @@ extension UUID: StatementColumnConvertible {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_TEXT:
|
||||
let string = String(cString: sqlite3_column_text(sqliteStatement, index)!)
|
||||
let string = String(sqliteStatement: sqliteStatement, index: index)
|
||||
guard let uuid = UUID(uuidString: string) else {
|
||||
return nil
|
||||
}
|
||||
self.init(uuid: uuid.uuid)
|
||||
case SQLITE_BLOB:
|
||||
guard sqlite3_column_bytes(sqliteStatement, index) == 16,
|
||||
let blob = sqlite3_column_blob(sqliteStatement, index) else
|
||||
{
|
||||
let blob = sqlite3_column_blob(sqliteStatement, index)
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
self.init(uuid: blob.assumingMemoryBound(to: uuid_t.self).pointee)
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
extension Optional: StatementBinding where Wrapped: StatementBinding {
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: - Value Types
|
||||
|
||||
/// Bool adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -125,9 +130,9 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a `Int` from the specified database value.
|
||||
/// Returns an `Int` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// If the database value contains an integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
@@ -164,9 +169,9 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a `Int8` from the specified database value.
|
||||
/// Returns an `Int8` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// If the database value contains an integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
@@ -203,9 +208,9 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a `Int16` from the specified database value.
|
||||
/// Returns an `Int16` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// If the database value contains an integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
@@ -242,9 +247,9 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a `Int32` from the specified database value.
|
||||
/// Returns an `Int32` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// If the database value contains an integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
@@ -277,9 +282,9 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
DatabaseValue(storage: .int64(self))
|
||||
}
|
||||
|
||||
/// Returns a `Int64` from the specified database value.
|
||||
/// Returns an `Int64` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer, returns this integer.
|
||||
/// If the database value contains an integer, returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
/// rounding toward zero, returns the conversion.
|
||||
@@ -326,7 +331,7 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a `UInt` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// If the database value contains an integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
@@ -365,7 +370,7 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a `UInt8` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// If the database value contains an integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
@@ -404,7 +409,7 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a `UInt16` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// If the database value contains an integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
@@ -443,7 +448,7 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a `UInt32` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// If the database value contains an integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
@@ -482,7 +487,7 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a `UInt64` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// If the database value contains an integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
@@ -517,7 +522,7 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a `Double` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer, returns the conversion.
|
||||
/// If the database value contains an integer, returns the conversion.
|
||||
///
|
||||
/// If the database value contains a double, returns this double.
|
||||
///
|
||||
@@ -557,7 +562,7 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a `Float` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer, returns the conversion.
|
||||
/// If the database value contains an integer, returns the conversion.
|
||||
///
|
||||
/// If the database value contains a double, returns the conversion.
|
||||
///
|
||||
@@ -587,7 +592,9 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
self = String(cString: sqlite3_column_text(sqliteStatement, index)!)
|
||||
let text = sqlite3_column_text(sqliteStatement, index)
|
||||
let byteCount = Int(sqlite3_column_bytes(sqliteStatement, index))
|
||||
self = String(decoding: UnsafeBufferPointer(start: text, count: byteCount), as: UTF8.self)
|
||||
}
|
||||
|
||||
/// Returns a TEXT database value.
|
||||
@@ -599,7 +606,7 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
///
|
||||
/// If the database value contains a string, returns it.
|
||||
///
|
||||
/// If the database value contains a data blob, parses this data as an
|
||||
/// If the database value contains a data blob, parses this data as a
|
||||
/// UTF8 string.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
@@ -617,23 +624,57 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_text(sqliteStatement, index, self, -1, SQLITE_TRANSIENT)
|
||||
var string = self
|
||||
return string.withSQLiteText {
|
||||
sqlite3_bind_text(sqliteStatement, index, $0, $1, SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls the given closure after binding a statement argument.
|
||||
///
|
||||
/// The binding is valid only during the execution of this method.
|
||||
///
|
||||
/// This method is mutating because the string is made contiguous
|
||||
/// if necessary.
|
||||
///
|
||||
/// - parameter sqliteStatement: An SQLite statement.
|
||||
/// - parameter index: 1-based index to statement arguments.
|
||||
/// - parameter body: The closure to execute when argument is bound.
|
||||
func withBinding<T>(to sqliteStatement: SQLiteStatement, at index: CInt, do body: () throws -> T) throws -> T {
|
||||
try withCString {
|
||||
let code = sqlite3_bind_text(sqliteStatement, index, $0, -1, nil /* SQLITE_STATIC */)
|
||||
mutating func withBinding<T>(
|
||||
to sqliteStatement: SQLiteStatement,
|
||||
at index: CInt,
|
||||
do body: () throws -> T
|
||||
) throws -> T {
|
||||
try withSQLiteText {
|
||||
let code = sqlite3_bind_text(sqliteStatement, index, $0, $1, nil /* SQLITE_STATIC */)
|
||||
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
|
||||
return try body()
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs body over the content of this string as a UTF8 string. This
|
||||
/// method exists because it deals with the ASCII NUL (\0) characters,
|
||||
/// unlike C strings.
|
||||
///
|
||||
/// This method is mutating because the string is made contiguous
|
||||
/// if necessary.
|
||||
mutating func withSQLiteText<T>(
|
||||
_ body: (UnsafePointer<CChar>, CInt) throws -> T
|
||||
) rethrows -> T {
|
||||
try withUTF8 { utf8 in
|
||||
guard let baseAddress = utf8.baseAddress else {
|
||||
// Empty string: yield a non-nil pointer to the NUL string
|
||||
// terminator, so that functions such as sqlite3_bind_text()
|
||||
// unambiguously interpret it as the empty string.
|
||||
return try withUnsafePointer(to: 0 as CChar) {
|
||||
try body($0, 0)
|
||||
}
|
||||
}
|
||||
return try baseAddress.withMemoryRebound(to: CChar.self, capacity: utf8.count) {
|
||||
try body($0, CInt(utf8.count))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -643,16 +684,15 @@ extension DatabaseFunction {
|
||||
/// An SQL function that calls the Foundation
|
||||
/// `String.capitalized` property.
|
||||
///
|
||||
/// `NULL` is returned for non-strings values.
|
||||
/// `NULL` is returned for non-string values.
|
||||
///
|
||||
/// This function is automatically added by GRDB to your database
|
||||
/// connections. It is the function used by the query interface's
|
||||
/// ``SQLSpecificExpressible/capitalized``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.capitalized)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// let request = Player.select { $0.name.capitalized }
|
||||
/// let names = try String.fetchAll(db, request) // [String]
|
||||
/// ```
|
||||
public static let capitalize =
|
||||
DatabaseFunction("swiftCapitalizedString", argumentCount: 1, pure: true) { dbValues in
|
||||
@@ -665,16 +705,15 @@ extension DatabaseFunction {
|
||||
/// An SQL function that calls the Swift
|
||||
/// `String.lowercased()` method.
|
||||
///
|
||||
/// `NULL` is returned for non-strings values.
|
||||
/// `NULL` is returned for non-string values.
|
||||
///
|
||||
/// This function is automatically added by GRDB to your database
|
||||
/// connections. It is the function used by the query interface's
|
||||
/// ``SQLSpecificExpressible/lowercased``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.lowercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// let request = Player.select { $0.name.lowercased }
|
||||
/// let names = try String.fetchAll(db, request) // [String]
|
||||
/// ```
|
||||
public static let lowercase =
|
||||
DatabaseFunction("swiftLowercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
@@ -687,16 +726,15 @@ extension DatabaseFunction {
|
||||
/// An SQL function that calls the Swift
|
||||
/// `String.uppercased()` method.
|
||||
///
|
||||
/// `NULL` is returned for non-strings values.
|
||||
/// `NULL` is returned for non-string values.
|
||||
///
|
||||
/// This function is automatically added by GRDB to your database
|
||||
/// connections. It is the function used by the query interface's
|
||||
/// ``SQLSpecificExpressible/uppercased``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.uppercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// let request = Player.select { $0.name.uppercased }
|
||||
/// let names = try String.fetchAll(db, request) // [String]
|
||||
/// ```
|
||||
public static let uppercase =
|
||||
DatabaseFunction("swiftUppercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
@@ -709,16 +747,15 @@ extension DatabaseFunction {
|
||||
/// An SQL function that calls the Foundation
|
||||
/// `String.localizedCapitalized` property.
|
||||
///
|
||||
/// `NULL` is returned for non-strings values.
|
||||
/// `NULL` is returned for non-string values.
|
||||
///
|
||||
/// This function is automatically added by GRDB to your database
|
||||
/// connections. It is the function used by the query interface's
|
||||
/// ``SQLSpecificExpressible/localizedCapitalized``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedCapitalized)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// let request = Player.select { $0.name.localizedCapitalized }
|
||||
/// let names = try String.fetchAll(db, request) // [String]
|
||||
/// ```
|
||||
public static let localizedCapitalize =
|
||||
DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { dbValues in
|
||||
@@ -732,16 +769,15 @@ extension DatabaseFunction {
|
||||
/// An SQL function that calls the Foundation
|
||||
/// `String.localizedLowercase` property.
|
||||
///
|
||||
/// `NULL` is returned for non-strings values.
|
||||
/// `NULL` is returned for non-string values.
|
||||
///
|
||||
/// This function is automatically added by GRDB to your database
|
||||
/// connections. It is the function used by the query interface's
|
||||
/// ``SQLSpecificExpressible/localizedLowercased``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedLowercase)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// let request = Player.select { $0.name.localizedLowercased }
|
||||
/// let names = try String.fetchAll(db, request) // [String]
|
||||
/// ```
|
||||
public static let localizedLowercase =
|
||||
DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
@@ -754,16 +790,15 @@ extension DatabaseFunction {
|
||||
/// An SQL function that calls the Foundation
|
||||
/// `String.localizedUppercase` property.
|
||||
///
|
||||
/// `NULL` is returned for non-strings values.
|
||||
/// `NULL` is returned for non-string values.
|
||||
///
|
||||
/// This function is automatically added by GRDB to your database
|
||||
/// connections. It is the function used by the query interface's
|
||||
/// ``SQLSpecificExpressible/localizedUppercased``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedUppercase)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// let request = Player.select { $0.name.localizedUppercased }
|
||||
/// let names = try String.fetchAll(db, request) // [String]
|
||||
/// ```
|
||||
public static let localizedUppercase =
|
||||
DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
@@ -807,7 +842,7 @@ extension DatabaseCollation {
|
||||
///
|
||||
/// ```swift
|
||||
/// let collationName = DatabaseCollation.unicodeCompare.name
|
||||
/// dbQueue.execute(sql: """
|
||||
/// try db.execute(sql: """
|
||||
/// CREATE TABLE player (
|
||||
/// name TEXT COLLATE \(collationName)
|
||||
/// )
|
||||
@@ -836,7 +871,7 @@ extension DatabaseCollation {
|
||||
///
|
||||
/// ```swift
|
||||
/// let collationName = DatabaseCollation.caseInsensitiveCompare.name
|
||||
/// dbQueue.execute(sql: """
|
||||
/// try db.execute(sql: """
|
||||
/// CREATE TABLE player (
|
||||
/// name TEXT COLLATE \(collationName)
|
||||
/// )
|
||||
@@ -865,7 +900,7 @@ extension DatabaseCollation {
|
||||
///
|
||||
/// ```swift
|
||||
/// let collationName = DatabaseCollation.localizedCaseInsensitiveCompare.name
|
||||
/// dbQueue.execute(sql: """
|
||||
/// try db.execute(sql: """
|
||||
/// CREATE TABLE player (
|
||||
/// name TEXT COLLATE \(collationName)
|
||||
/// )
|
||||
@@ -894,7 +929,7 @@ extension DatabaseCollation {
|
||||
///
|
||||
/// ```swift
|
||||
/// let collationName = DatabaseCollation.localizedCompare.name
|
||||
/// dbQueue.execute(sql: """
|
||||
/// try db.execute(sql: """
|
||||
/// CREATE TABLE player (
|
||||
/// name TEXT COLLATE \(collationName)
|
||||
/// )
|
||||
@@ -923,7 +958,7 @@ extension DatabaseCollation {
|
||||
///
|
||||
/// ```swift
|
||||
/// let collationName = DatabaseCollation.localizedStandardCompare.name
|
||||
/// dbQueue.execute(sql: """
|
||||
/// try db.execute(sql: """
|
||||
/// CREATE TABLE player (
|
||||
/// name TEXT COLLATE \(collationName)
|
||||
/// )
|
||||
|
||||
+220
-116
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
extension Database {
|
||||
@@ -69,7 +72,7 @@ extension Database {
|
||||
/// Registers closures to be executed after the next or current
|
||||
/// transaction completes.
|
||||
///
|
||||
/// This method helps synchronizing the database with other resources,
|
||||
/// This method helps synchronize the database with other resources,
|
||||
/// such as files, or system services.
|
||||
///
|
||||
/// In the example below, a `CLLocationManager` starts monitoring a
|
||||
@@ -77,7 +80,7 @@ extension Database {
|
||||
/// the database:
|
||||
///
|
||||
/// ```swift
|
||||
/// /// Inserts a region in the database, and start monitoring upon
|
||||
/// /// Inserts a region in the database, and starts monitoring upon
|
||||
/// /// successful insertion.
|
||||
/// func startMonitoring(_ db: Database, region: CLRegion) throws {
|
||||
/// // Make sure database is inside a transaction
|
||||
@@ -101,10 +104,10 @@ extension Database {
|
||||
/// ```
|
||||
///
|
||||
/// The method above won't trigger the location manager if the transaction
|
||||
/// is eventually rollbacked (explicitly, or because of an error).
|
||||
/// is eventually rolled back (explicitly, or because of an error).
|
||||
///
|
||||
/// The `onCommit` and `onRollback` closures are executed in the writer
|
||||
/// dispatch queue, serialized will all database updates.
|
||||
/// dispatch queue, serialized with all database updates.
|
||||
///
|
||||
/// - precondition: Database connection is not read-only.
|
||||
/// - parameter onCommit: A closure executed on transaction commit.
|
||||
@@ -171,7 +174,7 @@ extension Database {
|
||||
/// func databaseDidRollback(_ db: Database)
|
||||
/// }
|
||||
///
|
||||
/// First observer is added, and a transaction is started. At this point,
|
||||
/// First, an observer is added, and a transaction is started. At this point,
|
||||
/// there's not much to say:
|
||||
///
|
||||
/// let observer = MyObserver()
|
||||
@@ -184,16 +187,16 @@ extension Database {
|
||||
/// try db.execute(sql: "INSERT INTO document ...")
|
||||
///
|
||||
/// The observation process starts when the statement is *compiled*:
|
||||
/// sqlite3_set_authorizer tells that the statement performs insertion into the
|
||||
/// sqlite3_set_authorizer reports that the statement performs insertion into the
|
||||
/// `document` table. Generally speaking, statements may have many effects, by
|
||||
/// the mean of foreign key actions and SQL triggers. SQLite takes care of
|
||||
/// means of foreign key actions and SQL triggers. SQLite takes care of
|
||||
/// exposing all those effects to sqlite3_set_authorizer.
|
||||
///
|
||||
/// When the statement is *about to be executed*, the broker queries the
|
||||
/// observer.observes(eventsOfKind:) method. If it returns true, the observer is
|
||||
/// *activated*.
|
||||
///
|
||||
/// During the statement *execution*, SQLite tells that a row has been inserted
|
||||
/// During the statement *execution*, SQLite reports that a row has been inserted
|
||||
/// through sqlite3_update_hook: the broker calls the observer.databaseDidChange(with:)
|
||||
/// method, if and only if the observer has been activated at the previous step.
|
||||
///
|
||||
@@ -201,7 +204,7 @@ extension Database {
|
||||
///
|
||||
/// try db.execute(sql: "SAVEPOINT foo")
|
||||
///
|
||||
/// Statement compilation has sqlite3_set_authorizer tell that this statement
|
||||
/// Statement compilation has sqlite3_set_authorizer report that this statement
|
||||
/// begins a "foo" savepoint.
|
||||
///
|
||||
/// After the statement *has been executed*, the broker knows that the SQLite
|
||||
@@ -212,22 +215,22 @@ extension Database {
|
||||
///
|
||||
/// try db.execute(sql: "INSERT INTO document ...")
|
||||
///
|
||||
/// This time, when the statement is *executed* and SQLite tells that a row has
|
||||
/// This time, when the statement is *executed* and SQLite reports that a row has
|
||||
/// been inserted, the broker buffers the change event instead of immediately
|
||||
/// notifying the activated observers. That is because the savepoint can be
|
||||
/// rollbacked, and GRDB guarantees observers that they are only notified of
|
||||
/// rolled back, and GRDB guarantees observers that they are only notified of
|
||||
/// changes that have an opportunity to be committed.
|
||||
///
|
||||
/// The savepoint is released:
|
||||
///
|
||||
/// try db.execute(sql: "RELEASE SAVEPOINT foo")
|
||||
///
|
||||
/// Statement compilation has sqlite3_set_authorizer tell that this statement
|
||||
/// Statement compilation has sqlite3_set_authorizer report that this statement
|
||||
/// releases the "foo" savepoint.
|
||||
///
|
||||
/// After the statement *has been executed*, the broker knows that the SQLite
|
||||
/// [savepoint stack](https://www.sqlite.org/lang_savepoint.html) is now empty,
|
||||
/// and notifies the buffered changes to activated observers.
|
||||
/// and notifies activated observers of the buffered changes.
|
||||
///
|
||||
/// Finally the transaction is committed:
|
||||
///
|
||||
@@ -236,7 +239,7 @@ extension Database {
|
||||
/// During the statement *execution*, SQLite tells the broker that the
|
||||
/// transaction is about to be committed through sqlite3_commit_hook. The broker
|
||||
/// invokes observer.databaseWillCommit(). If the observer throws an error, the
|
||||
/// broker asks SQLite to rollback the transaction. Otherwise, the broker lets
|
||||
/// broker asks SQLite to roll back the transaction. Otherwise, the broker lets
|
||||
/// the transaction complete.
|
||||
///
|
||||
/// After the statement *has been executed*, the broker calls
|
||||
@@ -294,6 +297,10 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
}
|
||||
|
||||
/// Notifies that some changes were performed in the provided
|
||||
/// database region.
|
||||
///
|
||||
/// Support for the public ``Database/notifyChanges(in:)`` method.
|
||||
func notifyChanges(withEventsOfKind eventKinds: [DatabaseEventKind]) throws {
|
||||
// Support for stopObservingDatabaseChangesUntilNextTransaction()
|
||||
SchedulingWatchdog.current!.databaseObservationBroker = self
|
||||
@@ -322,7 +329,7 @@ class DatabaseObservationBroker {
|
||||
func statementWillExecute(_ statement: Statement) {
|
||||
if !database.isReadOnly && !transactionObservations.isEmpty {
|
||||
// As statement executes, it may trigger database changes that will
|
||||
// be notified to transaction observers. As a consequence, observers
|
||||
// be reported to transaction observers. As a consequence, observers
|
||||
// may disable themselves with stopObservingDatabaseChangesUntilNextTransaction()
|
||||
//
|
||||
// This method takes no argument, and requires access to the "current
|
||||
@@ -331,65 +338,14 @@ class DatabaseObservationBroker {
|
||||
SchedulingWatchdog.current!.databaseObservationBroker = self
|
||||
|
||||
// Fill statementObservations with observations that are interested
|
||||
// in the kind of database events performed by the statement, as
|
||||
// reported by `sqlite3_set_authorizer`.
|
||||
//
|
||||
// in the kind of database events performed by the statement.
|
||||
// Those statementObservations will be notified of individual changes
|
||||
// in databaseWillChange() and databaseDidChange().
|
||||
let authorizerEventKinds = statement.authorizerEventKinds
|
||||
|
||||
switch authorizerEventKinds.count {
|
||||
case 0:
|
||||
// Statement has no effect on any database table.
|
||||
//
|
||||
// For example: PRAGMA foreign_keys = ON
|
||||
statementObservations = []
|
||||
case 1:
|
||||
// We'll execute a simple statement without any side effect.
|
||||
// Eventual database events will thus all have the same kind. All
|
||||
// detabase events can be notified to interested observations.
|
||||
//
|
||||
// For example, if one observes all deletions in the table T, then
|
||||
// all individual deletions of DELETE FROM T are notified:
|
||||
let eventKind = authorizerEventKinds[0]
|
||||
statementObservations = transactionObservations.compactMap { observation in
|
||||
guard observation.observes(eventsOfKind: eventKind) else {
|
||||
// observation is not interested
|
||||
return nil
|
||||
}
|
||||
|
||||
// Observation will be notified of all individual events
|
||||
return StatementObservation(
|
||||
transactionObservation: observation,
|
||||
trackingEvents: .all)
|
||||
}
|
||||
default:
|
||||
// We'll execute a complex statement with side effects performed by
|
||||
// an SQL trigger or a foreign key action. Eventual database events
|
||||
// may not all have the same kind: we need to filter them before
|
||||
// notifying interested observations.
|
||||
//
|
||||
// For example, if DELETE FROM T1 generates deletions in T1 and T2
|
||||
// by the mean of a foreign key action, then when one only observes
|
||||
// deletions in T1, one must not be notified of deletions in T2:
|
||||
statementObservations = transactionObservations.compactMap { observation in
|
||||
let observedEventKinds = authorizerEventKinds.filter(observation.observes)
|
||||
if observedEventKinds.isEmpty {
|
||||
// observation is not interested
|
||||
return nil
|
||||
}
|
||||
|
||||
// Observation will only be notified of individual events
|
||||
// it is interested into.
|
||||
return StatementObservation(
|
||||
transactionObservation: observation,
|
||||
trackingEvents: .matching(
|
||||
observedEventKinds: observedEventKinds,
|
||||
authorizerEventKinds: authorizerEventKinds))
|
||||
}
|
||||
statementObservations = transactionObservations.compactMap { observation in
|
||||
observation.statementObservation(for: statement)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
transactionCompletion = .none
|
||||
}
|
||||
|
||||
@@ -400,7 +356,7 @@ class DatabaseObservationBroker {
|
||||
statementObservations = []
|
||||
SchedulingWatchdog.current!.databaseObservationBroker = nil
|
||||
|
||||
// Reset transactionCompletion before databaseDidRollback eventually
|
||||
// Reset transactionCompletion before databaseDidRollback possibly
|
||||
// executes other statements.
|
||||
let transactionCompletion = self.transactionCompletion
|
||||
self.transactionCompletion = .none
|
||||
@@ -477,7 +433,7 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
|
||||
// Reset transactionCompletion before databaseDidCommit or
|
||||
// databaseDidRollback eventually execute other statements.
|
||||
// databaseDidRollback possibly execute other statements.
|
||||
let transactionCompletion = self.transactionCompletion
|
||||
self.transactionCompletion = .none
|
||||
|
||||
@@ -549,8 +505,12 @@ class DatabaseObservationBroker {
|
||||
savepointStack.clear()
|
||||
|
||||
if !database.isReadOnly {
|
||||
for observation in transactionObservations {
|
||||
observation.databaseDidCommit(database)
|
||||
// Observers must be able to access the database, even if the
|
||||
// task that has performed the commit is cancelled.
|
||||
database.ignoringCancellation {
|
||||
for observation in transactionObservations {
|
||||
observation.databaseDidCommit(database)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -613,8 +573,13 @@ class DatabaseObservationBroker {
|
||||
|
||||
if notifyTransactionObservers {
|
||||
assert(!database.isReadOnly, "Read-only transactions are not notified")
|
||||
for observation in transactionObservations {
|
||||
observation.databaseDidRollback(database)
|
||||
|
||||
// Observers must be able to access the database, even if the
|
||||
// task that has performed the commit is cancelled.
|
||||
database.ignoringCancellation {
|
||||
for observation in transactionObservations {
|
||||
observation.databaseDidRollback(database)
|
||||
}
|
||||
}
|
||||
}
|
||||
databaseDidEndTransaction()
|
||||
@@ -768,34 +733,96 @@ class DatabaseObservationBroker {
|
||||
#endif
|
||||
}
|
||||
|
||||
/// The various SQLite transactions completions, as reported by the
|
||||
/// The various SQLite transaction completions, as reported by the
|
||||
/// `sqlite3_commit_hook` and `sqlite3_rollback_hook` callbacks.
|
||||
fileprivate enum TransactionCompletion {
|
||||
/// Transaction state is unchanged.
|
||||
case none
|
||||
|
||||
/// Transaction turns committed.
|
||||
/// Transaction is committed.
|
||||
case commit
|
||||
|
||||
/// Transaction turns rollbacked.
|
||||
/// Transaction is rolled back.
|
||||
case rollback
|
||||
|
||||
/// Transaction turns rollbacked because a transaction observer has
|
||||
/// Transaction is rolled back because a transaction observer has
|
||||
/// cancelled a commit by throwing an error.
|
||||
case cancelledCommit(Error)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - DatabaseEventObservationStrategy
|
||||
|
||||
/// Controls which database changes are reported to a `TransactionObserver`.
|
||||
public struct DatabaseEventObservationStrategy: Sendable {
|
||||
/// A boolean value indicating whether a ``TransactionObserver`` focuses
|
||||
/// on database changes filtered by its
|
||||
/// ``TransactionObserver/observes(eventsOfKind:)`` method.
|
||||
///
|
||||
/// When this flag is true (the default), the only notified changes are
|
||||
/// those performed by `DELETE`, `INSERT` and `UPDATE` statements that
|
||||
/// are compiled and executed by GRDB. Other changes are not: changes
|
||||
/// performed by `SELECT` statements (through a database function),
|
||||
/// changes performed by statements compiled or executed with the SQLite
|
||||
/// C API.
|
||||
///
|
||||
/// Set this flag to false in order to be notified of all database events.
|
||||
///
|
||||
/// When this flag is false, an observer prevents the
|
||||
/// [truncate optimization](https://www.sqlite.org/lang_delete.html#the_truncate_optimization)
|
||||
/// from being applied on all database tables.
|
||||
public var requiresDatabaseEventKind: Bool
|
||||
|
||||
/// The default strategy for observing database change events.
|
||||
///
|
||||
/// In this default strategy, only the `DELETE`, `INSERT` and `UPDATE`
|
||||
/// statements that are compiled and executed by GRDB are observed.
|
||||
public static let `default` = DatabaseEventObservationStrategy(requiresDatabaseEventKind: true)
|
||||
}
|
||||
|
||||
// MARK: - TransactionObserver
|
||||
|
||||
public protocol TransactionObserver: AnyObject {
|
||||
|
||||
/// Controls which database changes should be reported to the observer.
|
||||
///
|
||||
/// The default value is ``DatabaseEventObservationStrategy/default``,
|
||||
/// which only detects changes performed by `DELETE`, `INSERT` and
|
||||
/// `UPDATE` statements that are compiled and executed by GRDB.
|
||||
///
|
||||
/// You can define a universal observer that observes changes performed
|
||||
/// by `SELECT` statements (through a database function), changes
|
||||
/// performed by statements compiled or executed with the SQLite C API,
|
||||
/// as below:
|
||||
///
|
||||
/// ```swift
|
||||
/// // An observer that observes all database changes.
|
||||
/// class UniversalObserver: TransactionObserver {
|
||||
/// var databaseEventObservationStrategy: DatabaseEventObservationStrategy {
|
||||
/// var strategy = DatabaseEventObservationStrategy.default
|
||||
/// // Don't filter on database event kind, so that we are
|
||||
/// // notified of changes performed through the SQLite C API:
|
||||
/// strategy.requiresDatabaseEventKind = false
|
||||
/// return strategy
|
||||
/// }
|
||||
///
|
||||
/// // You still have to provide an implementation for this method,
|
||||
/// // but it will never be called since `requiresDatabaseEventKind`
|
||||
/// // is false.
|
||||
/// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
/// false // ignored
|
||||
/// }
|
||||
///
|
||||
/// func databaseDidChange(with event: DatabaseEvent) {
|
||||
/// // Handle the change
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
var databaseEventObservationStrategy: DatabaseEventObservationStrategy { get }
|
||||
|
||||
/// Returns whether specific kinds of database changes should be notified
|
||||
/// to the observer.
|
||||
///
|
||||
/// When this method returns false, database events of this kind are not
|
||||
/// notified to the ``databaseDidChange(with:)`` method.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
@@ -811,6 +838,11 @@ public protocol TransactionObserver: AnyObject {
|
||||
/// prevents the
|
||||
/// [truncate optimization](https://www.sqlite.org/lang_delete.html#the_truncate_optimization)
|
||||
/// from being applied on the observed tables.
|
||||
///
|
||||
/// - Note: This method is not called when the result of
|
||||
/// ``databaseEventObservationStrategy`` has the
|
||||
/// ``DatabaseEventObservationStrategy/requiresDatabaseEventKind``
|
||||
/// flag set to false.
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
|
||||
|
||||
/// Called when the database was modified in some unspecified way.
|
||||
@@ -819,15 +851,19 @@ public protocol TransactionObserver: AnyObject {
|
||||
/// not automatically detected. See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes>
|
||||
/// and ``Database/notifyChanges(in:)`` for more information.
|
||||
///
|
||||
/// The exact nature of changes is unknown, but they comply to the
|
||||
/// The exact nature of changes is unknown, but they comply with the
|
||||
/// ``observes(eventsOfKind:)`` test.
|
||||
func databaseDidChange()
|
||||
|
||||
/// Called when the database is changed by an insert, update, or
|
||||
/// delete event.
|
||||
///
|
||||
/// The change is pending until the current transaction ends. See
|
||||
/// ``databaseWillCommit()-7mksu``, ``databaseDidCommit(_:)`` and
|
||||
/// Whether this method is called or not for any given change is
|
||||
/// controlled by ``databaseEventObservationStrategy`` and
|
||||
/// ``observes(eventsOfKind:)``.
|
||||
///
|
||||
/// The notified change is pending until the current transaction ends.
|
||||
/// See ``databaseWillCommit()-7mksu``, ``databaseDidCommit(_:)`` and
|
||||
/// ``databaseDidRollback(_:)``.
|
||||
///
|
||||
/// The observer has an opportunity to stop receiving further change events
|
||||
@@ -843,18 +879,18 @@ public protocol TransactionObserver: AnyObject {
|
||||
|
||||
/// Called when a transaction is about to be committed.
|
||||
///
|
||||
/// The transaction observer has an opportunity to rollback pending changes
|
||||
/// The transaction observer has an opportunity to roll back pending changes
|
||||
/// by throwing an error from this method.
|
||||
///
|
||||
/// - precondition: This method must not access the observed writer
|
||||
/// database connection.
|
||||
/// - throws: The eventual error that rollbacks pending changes.
|
||||
/// - throws: The error that rolls back pending changes.
|
||||
func databaseWillCommit() throws
|
||||
|
||||
/// Called when a transaction has been committed on disk.
|
||||
func databaseDidCommit(_ db: Database)
|
||||
|
||||
/// Called when a transaction has been rollbacked.
|
||||
/// Called when a transaction has been rolled back.
|
||||
func databaseDidRollback(_ db: Database)
|
||||
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
@@ -890,6 +926,11 @@ public protocol TransactionObserver: AnyObject {
|
||||
}
|
||||
|
||||
extension TransactionObserver {
|
||||
/// The default implementation does not observe statements.
|
||||
public var databaseEventObservationStrategy: DatabaseEventObservationStrategy {
|
||||
.default
|
||||
}
|
||||
|
||||
/// The default implementation does nothing.
|
||||
public func databaseWillCommit() throws { }
|
||||
|
||||
@@ -955,7 +996,7 @@ final class TransactionObservation {
|
||||
let extent: Database.TransactionObservationExtent
|
||||
|
||||
/// A disabled observation is not interested in individual database changes.
|
||||
/// It is still interested in transactions commits & rollbacks.
|
||||
/// It is still interested in transaction commits & rollbacks.
|
||||
var isEnabled = true
|
||||
|
||||
private weak var weakObserver: (any TransactionObserver)?
|
||||
@@ -984,7 +1025,69 @@ final class TransactionObservation {
|
||||
}
|
||||
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
observer?.observes(eventsOfKind: eventKind) ?? false
|
||||
guard let observer else {
|
||||
return false
|
||||
}
|
||||
return !observer.databaseEventObservationStrategy.requiresDatabaseEventKind || observer.observes(eventsOfKind: eventKind)
|
||||
}
|
||||
|
||||
func statementObservation(for statement: Statement) -> StatementObservation? {
|
||||
guard let observer else {
|
||||
return nil
|
||||
}
|
||||
|
||||
if !observer.databaseEventObservationStrategy.requiresDatabaseEventKind {
|
||||
return StatementObservation(
|
||||
transactionObservation: self,
|
||||
trackingEvents: .all)
|
||||
}
|
||||
|
||||
let authorizerEventKinds = statement.authorizerEventKinds
|
||||
|
||||
switch authorizerEventKinds.count {
|
||||
case 0:
|
||||
// Statement has no effect on any database table.
|
||||
//
|
||||
// For example: PRAGMA foreign_keys = ON
|
||||
return nil
|
||||
case 1:
|
||||
// We'll execute a simple statement without any side effect.
|
||||
// All database events will thus have the same kind. All
|
||||
// database events can be reported to interested observations.
|
||||
//
|
||||
// For example, if one observes all deletions in the table T, then
|
||||
// all individual deletions of DELETE FROM T are notified:
|
||||
guard observer.observes(eventsOfKind: authorizerEventKinds[0]) else {
|
||||
// observation is not interested
|
||||
return nil
|
||||
}
|
||||
|
||||
// Observation will be notified of all individual events
|
||||
return StatementObservation(
|
||||
transactionObservation: self,
|
||||
trackingEvents: .all)
|
||||
default:
|
||||
// We'll execute a complex statement with side effects performed by
|
||||
// an SQL trigger or a foreign key action. Any database events
|
||||
// may not all have the same kind: we need to filter them before
|
||||
// notifying interested observations.
|
||||
//
|
||||
// For example, if DELETE FROM T1 generates deletions in T1 and T2
|
||||
// by the mean of a foreign key action, then when one only observes
|
||||
// deletions in T1, one must not be notified of deletions in T2:
|
||||
let observedEventKinds = authorizerEventKinds.filter(observer.observes)
|
||||
if observedEventKinds.isEmpty {
|
||||
// observation is not interested
|
||||
return nil
|
||||
}
|
||||
// Observation will only be notified of individual events
|
||||
// it is interested into.
|
||||
return StatementObservation(
|
||||
transactionObservation: self,
|
||||
trackingEvents: .matching(
|
||||
observedEventKinds: observedEventKinds,
|
||||
authorizerEventKinds: authorizerEventKinds))
|
||||
}
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
@@ -1016,7 +1119,7 @@ final class TransactionObservation {
|
||||
if let observer = self.observer {
|
||||
// Observer must not get any further notification.
|
||||
// So we "forget" the observer before its `databaseDidCommit`
|
||||
// implementation eventually triggers another database change.
|
||||
// implementation possibly triggers another database change.
|
||||
assert(weakObserver == nil, "expected observer to be stored in strongObserver")
|
||||
strongObserver = nil
|
||||
observer.databaseDidCommit(db)
|
||||
@@ -1032,7 +1135,7 @@ final class TransactionObservation {
|
||||
if let observer = self.observer {
|
||||
// Observer must not get any further notification.
|
||||
// So we "forget" the observer before its `databaseDidRollback`
|
||||
// implementation eventually triggers another database change.
|
||||
// implementation possibly triggers another database change.
|
||||
assert(weakObserver == nil, "expected observer to be stored in strongObserver")
|
||||
strongObserver = nil
|
||||
observer.databaseDidRollback(db)
|
||||
@@ -1243,16 +1346,16 @@ private struct CopiedDatabaseEventImpl: DatabaseEventImpl {
|
||||
|
||||
public struct DatabasePreUpdateEvent {
|
||||
|
||||
/// An event kind
|
||||
public enum Kind: CInt {
|
||||
/// SQLITE_INSERT
|
||||
case insert = 18
|
||||
/// An event kind.
|
||||
public enum Kind: CInt, Sendable {
|
||||
/// An insertion event
|
||||
case insert = 18 // SQLITE_INSERT
|
||||
|
||||
/// SQLITE_DELETE
|
||||
case delete = 9
|
||||
/// A deletion event
|
||||
case delete = 9 // SQLITE_DELETE
|
||||
|
||||
/// SQLITE_UPDATE
|
||||
case update = 23
|
||||
/// An update event
|
||||
case update = 23 // SQLITE_UPDATE
|
||||
}
|
||||
|
||||
/// The event kind
|
||||
@@ -1276,19 +1379,19 @@ public struct DatabasePreUpdateEvent {
|
||||
/// ... and so forth
|
||||
public var depth: CInt { impl.depth }
|
||||
|
||||
/// The initial rowID of the row being changed for .Update and .Delete changes,
|
||||
/// and nil for .Insert changes.
|
||||
/// The initial rowID of the row being changed for .update and .delete changes,
|
||||
/// and nil for .insert changes.
|
||||
public let initialRowID: Int64?
|
||||
|
||||
/// The final rowID of the row being changed for .Update and .Insert changes,
|
||||
/// and nil for .Delete changes.
|
||||
/// The final rowID of the row being changed for .update and .insert changes,
|
||||
/// and nil for .delete changes.
|
||||
public let finalRowID: Int64?
|
||||
|
||||
/// The initial database values in the row.
|
||||
///
|
||||
/// Values appear in the same order as the columns in the table.
|
||||
///
|
||||
/// The result is nil if the event is an .Insert event.
|
||||
/// The result is nil if the event is an .insert event.
|
||||
public var initialDatabaseValues: [DatabaseValue]? {
|
||||
guard kind == .update || kind == .delete else { return nil }
|
||||
return impl.initialDatabaseValues
|
||||
@@ -1299,7 +1402,7 @@ public struct DatabasePreUpdateEvent {
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
/// rightmost column.
|
||||
///
|
||||
/// The result is nil if the event is an .Insert event.
|
||||
/// The result is nil if the event is an .insert event.
|
||||
public func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
|
||||
guard kind == .update || kind == .delete else { return nil }
|
||||
@@ -1310,7 +1413,7 @@ public struct DatabasePreUpdateEvent {
|
||||
///
|
||||
/// Values appear in the same order as the columns in the table.
|
||||
///
|
||||
/// The result is nil if the event is a .Delete event.
|
||||
/// The result is nil if the event is a .delete event.
|
||||
public var finalDatabaseValues: [DatabaseValue]? {
|
||||
guard kind == .update || kind == .insert else { return nil }
|
||||
return impl.finalDatabaseValues
|
||||
@@ -1321,7 +1424,7 @@ public struct DatabasePreUpdateEvent {
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
/// rightmost column.
|
||||
///
|
||||
/// The result is nil if the event is a .Delete event.
|
||||
/// The result is nil if the event is a .delete event.
|
||||
public func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
|
||||
guard kind == .update || kind == .insert else { return nil }
|
||||
@@ -1485,7 +1588,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
|
||||
sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt)
|
||||
-> DatabaseValue?
|
||||
{
|
||||
var value: SQLiteValue? = nil
|
||||
var value: SQLiteValue?
|
||||
guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil }
|
||||
if let value {
|
||||
return DatabaseValue(sqliteValue: value)
|
||||
@@ -1533,6 +1636,7 @@ enum DatabaseEventPredicate {
|
||||
case all
|
||||
|
||||
/// Filters events that match `observedEventKinds`, or are not
|
||||
/// reported by the statement authorizer.
|
||||
///
|
||||
/// - parameter observedEventKinds: Event kinds observed by
|
||||
/// the TransactionObserver.
|
||||
@@ -1586,13 +1690,13 @@ enum DatabaseEventPredicate {
|
||||
/// - know if there are currently active savepoints (isEmpty)
|
||||
/// - buffer database events when a savepoint is active, in order to avoid
|
||||
/// notifying transaction observers of database events that could be
|
||||
/// rollbacked.
|
||||
/// rolled back.
|
||||
class SavepointStack {
|
||||
/// The buffered events (see DatabaseObservationBroker.databaseDidChange(with:))
|
||||
var eventsBuffer: [(event: any DatabaseEventProtocol, statementObservations: [StatementObservation])] = []
|
||||
|
||||
/// The savepoint stack, as an array of tuples (savepointName, index in the eventsBuffer array).
|
||||
/// Indexes let us drop rollbacked events from the event buffer.
|
||||
/// Indexes let us drop rolled-back events from the event buffer.
|
||||
private var savepoints: [(name: String, index: Int)] = []
|
||||
|
||||
/// If true, there is no current save point.
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#elseif SQLCipher
|
||||
import SQLCipher
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
/// An instance of WALSnapshot records the state of a WAL mode database for some
|
||||
@@ -16,18 +19,6 @@ import SQLite3
|
||||
/// actual observation. This class has no other purpose, and is not intended to
|
||||
/// become public.
|
||||
///
|
||||
/// It does not work with SQLCipher, because SQLCipher does not support
|
||||
/// `SQLITE_ENABLE_SNAPSHOT` correctly: we have linker errors.
|
||||
/// See <https://github.com/ericsink/SQLitePCL.raw/issues/452>.
|
||||
///
|
||||
/// With custom SQLite builds, it only works if `SQLITE_ENABLE_SNAPSHOT`
|
||||
/// is defined.
|
||||
///
|
||||
/// With system SQLite, it works because the SDK exposes the C apis and
|
||||
/// since XCode 14.
|
||||
///
|
||||
/// Yes, this is an awfully complex logic.
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/snapshot.html>.
|
||||
final class WALSnapshot: @unchecked Sendable {
|
||||
// @unchecked because sqlite3_snapshot has no threading requirements.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
/// A long-live read-only WAL transaction.
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
/// A long-lived read-only WAL transaction.
|
||||
///
|
||||
/// `WALSnapshotTransaction` **takes ownership** of its reader
|
||||
/// `SerializedDatabase` (TODO: make it a move-only type eventually).
|
||||
@@ -15,7 +15,13 @@ final class WALSnapshotTransaction: @unchecked Sendable {
|
||||
// WALSnapshotTransaction may be deinitialized in the dispatch
|
||||
// queue of its reader: allow reentrancy.
|
||||
let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in
|
||||
try? db.commit()
|
||||
// Commit or rollback, but try hard to leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
return db.isInsideTransaction
|
||||
}
|
||||
release(isInsideTransaction)
|
||||
@@ -29,7 +35,7 @@ final class WALSnapshotTransaction: @unchecked Sendable {
|
||||
/// The state of the database at the beginning of the transaction.
|
||||
let walSnapshot: WALSnapshot
|
||||
|
||||
/// Creates a long-live WAL transaction on a read-only connection.
|
||||
/// Creates a long-lived WAL transaction on a read-only connection.
|
||||
///
|
||||
/// The `release` closure is always called. It is called when the
|
||||
/// `WALSnapshotTransaction` is deallocated, or if the initializer
|
||||
@@ -43,8 +49,8 @@ final class WALSnapshotTransaction: @unchecked Sendable {
|
||||
/// Usage:
|
||||
///
|
||||
/// ```swift
|
||||
/// let transaction = WALSnapshotTransaction(
|
||||
/// reader: reader,
|
||||
/// let transaction = try WALSnapshotTransaction(
|
||||
/// onReader: reader,
|
||||
/// release: { isInsideTransaction in
|
||||
/// ...
|
||||
/// })
|
||||
|
||||
@@ -20,7 +20,7 @@ Open one single ``DatabaseQueue`` or ``DatabasePool`` per database file, for the
|
||||
|
||||
- *Why does this rule exist?* - Since SQLite does not support parallel writes, each `DatabaseQueue` and `DatabasePool` makes sure application threads perform writes one by one, without overlap.
|
||||
|
||||
- *Practical advice* - An app that uses a single database will connect only once. A document-based app will connect each time a document is opened, and disconnect when the document is closed. See the [demo apps] in order to see how to setup a UIKit or SwiftUI application for a single database.
|
||||
- *Practical advice* - An app that uses a single database will connect only once. A document-based app will connect each time a document is opened, and disconnect when the document is closed. See the [demo apps] in order to see how to set up a UIKit or SwiftUI application for a single database.
|
||||
|
||||
- *What if you do not follow this rule?*
|
||||
|
||||
@@ -29,9 +29,9 @@ Open one single ``DatabaseQueue`` or ``DatabasePool`` per database file, for the
|
||||
|
||||
#### Rule 2: Mind your transactions
|
||||
|
||||
Database operations that are grouped in a transaction are guaranteed to be either fully saved on disk, or not at all. Read-only transactions guarantee a stable and immutable view of the database, and do not see changes performed by eventual concurrent writes.
|
||||
Database operations that are grouped in a transaction are guaranteed to be either fully saved on disk, or not at all. Read-only transactions guarantee a stable and immutable view of the database, and do not see changes performed by concurrent writes.
|
||||
|
||||
In other words, transactions are the one and single tool that helps you enforce and rely on the invariants of your database (such as "all authors must have at least one book").
|
||||
In other words, transactions are the one and only tool that helps you enforce and rely on the invariants of your database (such as "all authors must have at least one book").
|
||||
|
||||
**You are responsible**, in your Swift code, for delimiting transactions. You do so by grouping database accesses inside a pair of `{ db in ... }` brackets:
|
||||
|
||||
@@ -40,18 +40,18 @@ try dbQueue.write { db in
|
||||
// Inside a transaction
|
||||
}
|
||||
|
||||
try dbQueue.read { db
|
||||
try dbQueue.read { db in
|
||||
// Inside a transaction
|
||||
}
|
||||
```
|
||||
|
||||
Alternatively, you can open an explicit transaction or savepoint: see <doc:Transactions>.
|
||||
|
||||
- *Why does this rule exist?* - Because GRDB and SQLite can not guess where to insert the transaction boundaries that protect the invariants of your database. This is your task. Transactions also avoid concurrency problems, as described in the <doc:Concurrency#Safe-and-Unsafe-Database-Accesses> section below.
|
||||
- *Why does this rule exist?* - Because GRDB and SQLite cannot guess where to insert the transaction boundaries that protect the invariants of your database. This is your task. Transactions also avoid concurrency problems, as described in the <doc:Concurrency#Safe-and-Unsafe-Database-Accesses> section below.
|
||||
|
||||
- *Practical advice* - Take the time to identify the invariants of your database. Some of them can be enforced in the database schema itself, such as "all books must have a non-empty title", or "all books must have an author" (see <doc:DatabaseSchema>). Some invariants can only be enforced by transactions, such as "all account credits must have a matching debit", or "all authors must have at least one book".
|
||||
|
||||
- *What if you do not follow this rule?* - You will see broken database invariants, at runtime, or when your apps wakes up after a crash. These bugs corrupt user data, and are very difficult to fix.
|
||||
- *What if you do not follow this rule?* - You will see broken database invariants, at runtime, or when your app wakes up after a crash. These bugs corrupt user data, and are very difficult to fix.
|
||||
|
||||
|
||||
## Synchronous and Asynchronous Database Accesses
|
||||
@@ -97,11 +97,11 @@ try dbQueue.write { db in
|
||||
}
|
||||
```
|
||||
|
||||
See ``DatabaseReader/read(_:)-4d1da`` and ``DatabaseWriter/write(_:)-3db50``.
|
||||
See ``DatabaseReader/read(_:)-5mfwu`` and ``DatabaseWriter/write(_:)-4gnqx``.
|
||||
|
||||
Note the identical method names: `read`, `write`. The async version is only available in async Swift functions.
|
||||
|
||||
The async database access methods honor task cancellation. Once an async Task is cancelled, reads and writes throw `CancellationError`, and any transaction is rollbacked.
|
||||
The async database access methods honor task cancellation. Once an async Task is cancelled, reads and writes throw `CancellationError`, and any transaction is rolled back.
|
||||
|
||||
See <doc:SwiftConcurrency> for more information about GRDB and Swift 6.
|
||||
|
||||
@@ -162,13 +162,13 @@ This guarantee prevents [`SQLITE_BUSY`] errors during concurrent writes.
|
||||
|
||||
**All writes are wrapped in a transaction.**
|
||||
|
||||
Concurrent reads can not see partial database updates (even reads performed by other processes).
|
||||
Concurrent reads cannot see partial database updates (even reads performed by other processes).
|
||||
|
||||
#### Isolated Reads
|
||||
|
||||
**All reads are wrapped in a transaction.**
|
||||
|
||||
An isolated read sees a stable and immutable state of the database, and does not see changes performed by eventual concurrent writes (even writes performed by other processes). See [Isolation In SQLite](https://www.sqlite.org/isolation.html) for more information.
|
||||
An isolated read sees a stable and immutable state of the database, and does not see changes performed by concurrent writes (even writes performed by other processes). See [Isolation In SQLite](https://www.sqlite.org/isolation.html) for more information.
|
||||
|
||||
#### Forbidden Writes
|
||||
|
||||
@@ -178,7 +178,7 @@ This enforces the immutability of the database during a read.
|
||||
|
||||
#### Non-Reentrancy
|
||||
|
||||
**Database accesses methods are not reentrant.**
|
||||
**Database access methods are not reentrant.**
|
||||
|
||||
This reduces the opportunities for deadlocks, and fosters the clear transaction boundaries of <doc:Concurrency#Rule-2:-Mind-your-transactions>.
|
||||
|
||||
@@ -202,7 +202,7 @@ Some applications need to relax this safety net, in order to achieve specific SQ
|
||||
|
||||
See ``DatabaseReader/unsafeReentrantRead(_:)``.
|
||||
|
||||
> Important: By using one of the methods above, you become responsible of the thread-safety of your application. Please understand the consequences of lifting each concurrency guarantee.
|
||||
> Important: By using one of the methods above, you become responsible for the thread-safety of your application. Please understand the consequences of lifting each concurrency guarantee.
|
||||
|
||||
Some concurrency guarantees can be restored at your convenience:
|
||||
|
||||
@@ -228,7 +228,7 @@ Despite the common guarantees and rules shared by database queues and pools, tho
|
||||
|
||||

|
||||
|
||||
See how, with database pools, two reads can see different database states at the same time. This may look scary! Please see the next chapter below for a relief.
|
||||
See how, with database pools, two reads can see different database states at the same time. This may look scary! Please see the next chapter below for some relief.
|
||||
|
||||
## Concurrent Thinking
|
||||
|
||||
@@ -248,7 +248,7 @@ All you need is a little "concurrent thinking", based on those two basic facts:
|
||||
|
||||
```swift
|
||||
// or dbQueue.write, for that matter
|
||||
let cookieCount = dbPool.read { db in
|
||||
let cookieCount = try dbPool.read { db in
|
||||
try Cookie.fetchCount(db)
|
||||
}
|
||||
|
||||
@@ -259,13 +259,13 @@ All you need is a little "concurrent thinking", based on those two basic facts:
|
||||
|
||||
Does this mean you can't rely on anything? Of course not:
|
||||
|
||||
- If you intend to display some database value on screen, use ``ValueObservation``: it always eventually notifies the latest state of the database. Your application won't display stale values for a long time: after the database has been changed on disk, the fresh value if fetched, and soon notified on the main thread where the screen can be updated.
|
||||
- If you intend to display some database value on screen, use ``ValueObservation``: it always eventually notifies the latest state of the database. Your application won't display stale values for a long time: after the database has been changed on disk, the fresh value is fetched, and soon notified on the main thread where the screen can be updated.
|
||||
|
||||
- As said above, the moment of truth is the next write access!
|
||||
|
||||
## Advanced DatabasePool
|
||||
|
||||
``DatabasePool`` is very concurrent, since all reads can run in parallel, and can even run during write operations. But writes are still serialized: at any given point in time, there is no more than a single thread that is writing into the database.
|
||||
``DatabasePool`` is highly concurrent, since all reads can run in parallel, and can even run during write operations. But writes are still serialized: at any given point in time, there is no more than a single thread that is writing into the database.
|
||||
|
||||
When your application modifies the database, and then reads some value that depends on those modifications, you may want to avoid blocking concurrent writes longer than necessary - especially when the read is slow:
|
||||
|
||||
@@ -302,7 +302,7 @@ try dbPool.writeWithoutTransaction { db in
|
||||
}
|
||||
```
|
||||
|
||||
The ``DatabasePool/asyncConcurrentRead(_:)`` method blocks until it can guarantee its closure argument an isolated access to the database, in the exact state left by the last transaction. It then asynchronously executes the closure.
|
||||
The ``DatabasePool/asyncConcurrentRead(_:)`` method blocks until it can guarantee its closure argument isolated access to the database, in the exact state left by the last transaction. It then asynchronously executes the closure.
|
||||
|
||||
In the illustration below, the striped band shows the delay needed for the reading thread to acquire isolation. Until then, no other thread can write:
|
||||
|
||||
|
||||
@@ -33,27 +33,27 @@ You need a path to a database file in order to open a database connection.
|
||||
|
||||
// Get the path to the database resource.
|
||||
// Replace `Bundle.main` with `Bundle.module` when you write a Swift Package.
|
||||
if let dbPath = Bundle.main.path(forResource: "db", ofType: "sqlite")
|
||||
let dbPath = Bundle.main.path(forResource: "db", ofType: "sqlite")
|
||||
|
||||
if let dbPath {
|
||||
// If the resource exists, open a read-only connection.
|
||||
// Writes are disallowed because resources can not be modified.
|
||||
// Writes are disallowed because resources cannot be modified.
|
||||
var config = Configuration()
|
||||
config.readonly = true
|
||||
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
|
||||
} else {
|
||||
// The database resource can not be found.
|
||||
// The database resource cannot be found.
|
||||
// Fix your setup, or report the problem to the user.
|
||||
}
|
||||
```
|
||||
|
||||
**If the application creates or writes in the database**, then first choose a proper location for the database file. Document-based applications will let the user pick a location. Apps that use the database as a global storage will prefer the Application Support directory.
|
||||
**If the application creates or writes in the database**, then first choose a proper location for the database file. Document-based applications will let the user pick a location. Apps that use the database as global storage will prefer the Application Support directory.
|
||||
|
||||
> Tip: Regardless of the database location, it is recommended that you wrap the database file inside a dedicated directory. This directory will bundle the main database file and its related [SQLite temporary files](https://www.sqlite.org/tempfiles.html) together.
|
||||
>
|
||||
> The dedicated directory helps moving or deleting the whole database when needed: just move or delete the directory.
|
||||
> The dedicated directory helps move or delete the whole database when needed: just move or delete the directory.
|
||||
>
|
||||
> On iOS, the directory can be encrypted with [data protection](https://developer.apple.com/documentation/uikit/protecting_the_user_s_privacy/encrypting_your_app_s_files), in order to help securing all database files in one shot. When a database is protected, an application that runs in the background on a locked device won't be able to read or write from it. Instead, it will catch ``DatabaseError`` with code [`SQLITE_IOERR`](https://www.sqlite.org/rescode.html#ioerr) (10) "disk I/O error", or [`SQLITE_AUTH`](https://www.sqlite.org/rescode.html#auth) (23) "not authorized".
|
||||
> On iOS, the directory can be encrypted with [data protection](https://developer.apple.com/documentation/uikit/protecting_the_user_s_privacy/encrypting_your_app_s_files), in order to help secure all database files in one shot. When a database is protected, an application that runs in the background on a locked device won't be able to read or write from it. Instead, it will catch ``DatabaseError`` with code [`SQLITE_IOERR`](https://www.sqlite.org/rescode.html#ioerr) (10) "disk I/O error", or [`SQLITE_AUTH`](https://www.sqlite.org/rescode.html#auth) (23) "not authorized".
|
||||
|
||||
The sample code below creates or opens a database file inside its dedicated directory. On the first run, a new empty database file is created. On subsequent runs, the directory and database file already exist, so it just opens a connection:
|
||||
|
||||
|
||||
@@ -4,13 +4,13 @@ Observe database changes and transactions.
|
||||
|
||||
## Overview
|
||||
|
||||
**SQLite notifies its host application of changes performed to the database, as well of transaction commits and rollbacks.**
|
||||
**SQLite notifies its host application of changes performed to the database, as well as of transaction commits and rollbacks.**
|
||||
|
||||
GRDB puts this SQLite feature to some good use, and lets you observe the database in various ways:
|
||||
|
||||
- ``ValueObservation``: Get notified when database values change.
|
||||
- ``DatabaseRegionObservation``: Get notified when a transaction impacts a database region.
|
||||
- ``Database/afterNextTransaction(onCommit:onRollback:)``: Handle transactions commits or rollbacks, one by one.
|
||||
- ``Database/afterNextTransaction(onCommit:onRollback:)``: Handle transaction commits or rollbacks, one by one.
|
||||
- ``TransactionObserver``: The low-level protocol that supports all database observation features.
|
||||
|
||||
## Topics
|
||||
|
||||
@@ -29,6 +29,8 @@ Get information about schema objects such as tables, columns, indexes, foreign k
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``DatabaseSchemaID``
|
||||
- ``DatabaseObjectID``
|
||||
- ``ColumnInfo``
|
||||
- ``ForeignKeyInfo``
|
||||
- ``IndexInfo``
|
||||
|
||||
@@ -4,7 +4,7 @@ How to modify the database schema
|
||||
|
||||
## Overview
|
||||
|
||||
For modifying the database schema, prefer Swift methods over raw SQL queries. They allow the compiler to check if a schema change is available on the target operating system. Only use a raw SQL query when no Swift method exist (when creating triggers, for example).
|
||||
For modifying the database schema, prefer Swift methods over raw SQL queries. They allow the compiler to check if a schema change is available on the target operating system. Only use a raw SQL query when no Swift method exists (when creating triggers, for example).
|
||||
|
||||
When a schema change is not directly supported by SQLite, or not available on the target operating system, database tables have to be recreated. See <doc:Migrations> for the detailed procedure.
|
||||
|
||||
@@ -17,8 +17,8 @@ The ``Database/create(table:options:body:)`` method covers nearly all SQLite tab
|
||||
// id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
// title TEXT,
|
||||
// favorite BOOLEAN NOT NULL DEFAULT 0,
|
||||
// latitude DOUBLE NOT NULL,
|
||||
// longitude DOUBLE NOT NULL
|
||||
// longitude DOUBLE NOT NULL,
|
||||
// latitude DOUBLE NOT NULL
|
||||
// )
|
||||
try db.create(table: "place") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
@@ -35,13 +35,13 @@ try db.create(table: "place") { t in
|
||||
// CREATE TABLE player ( ... )
|
||||
try db.create(table: "player") { t in ... }
|
||||
|
||||
// CREATE TEMPORARY TABLE player IF NOT EXISTS (
|
||||
// CREATE TEMPORARY TABLE IF NOT EXISTS player (
|
||||
try db.create(table: "player", options: [.temporary, .ifNotExists]) { t in ... }
|
||||
```
|
||||
|
||||
Reference: ``TableOptions``
|
||||
|
||||
**Add regular columns** with their name and eventual type (`text`, `integer`, `double`, `real`, `numeric`, `boolean`, `blob`, `date`, `datetime`, `any`, and `json`) - see [SQLite data types](https://www.sqlite.org/datatype3.html) and <doc:JSON>:
|
||||
**Add regular columns** with their name and optional type (`text`, `integer`, `double`, `real`, `numeric`, `boolean`, `blob`, `date`, `datetime`, `any`, and `jsonText`) - see [SQLite data types](https://www.sqlite.org/datatype3.html) and <doc:JSON>:
|
||||
|
||||
```swift
|
||||
// CREATE TABLE player (
|
||||
@@ -53,7 +53,7 @@ try db.create(table: "player") { t in
|
||||
t.column("score")
|
||||
t.column("name", .text)
|
||||
t.column("creationDate", .datetime)
|
||||
t.column("address", .json)
|
||||
t.column("address", .jsonText)
|
||||
```
|
||||
|
||||
Reference: ``TableDefinition/column(_:_:)``
|
||||
@@ -244,7 +244,7 @@ try db.create(
|
||||
])
|
||||
```
|
||||
|
||||
Unique constraints and unique indexes are somewhat different: don't miss the tip in <doc:DatabaseSchemaRecommendations/Unique-keys-should-be-supported-by-unique-indexes> below.
|
||||
Unique constraints and unique indexes are somewhat different: don't miss the tip in <doc:DatabaseSchemaRecommendations#Unique-keys-should-be-supported-by-unique-indexes> below.
|
||||
|
||||
## Topics
|
||||
|
||||
|
||||
@@ -4,9 +4,9 @@ Recommendations for an ideal integration of the database schema with GRDB
|
||||
|
||||
## Overview
|
||||
|
||||
Even though all schema are supported, some features of the library and of the Swift language are easier to use when the schema follows a few conventions described below.
|
||||
Even though all schemas are supported, some features of the library and of the Swift language are easier to use when the schema follows a few conventions described below.
|
||||
|
||||
When those conventions are not applied, or not applicable, you will have to perform extra configurations.
|
||||
When those conventions are not applied, or not applicable, you will have to perform extra configuration.
|
||||
|
||||
For recommendations specific to JSON columns, see <doc:JSON>.
|
||||
|
||||
@@ -139,7 +139,7 @@ try db.create(table: "player") { t in
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
|
||||
// The record type for the 'player' table'
|
||||
// The record type for the 'player' table
|
||||
struct Player: Codable {
|
||||
// Uniquely identifies a player.
|
||||
var rowid: Int64?
|
||||
@@ -160,9 +160,9 @@ extension Player: FetchableRecord, MutablePersistableRecord {
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.read { db in
|
||||
try dbQueue.write { db in
|
||||
// SELECT *, rowid FROM player WHERE rowid = 1
|
||||
if let player = try Player.fetchOne(db, id: 1) {
|
||||
if let player = try Player.fetchOne(db, key: 1) {
|
||||
// DELETE FROM player WHERE rowid = 1
|
||||
let deleted = try player.delete(db)
|
||||
print(deleted) // true
|
||||
@@ -214,7 +214,7 @@ struct Player: Identifiable {
|
||||
|
||||
## Unique keys should be supported by unique indexes
|
||||
|
||||
Unique indexes makes sure SQLite prevents the insertion of conflicting rows:
|
||||
Unique indexes make sure SQLite prevents the insertion of conflicting rows:
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
@@ -235,10 +235,10 @@ try db.create(
|
||||
|
||||
> Tip: SQLite does not support deferred unique indexes, and this creates undesired churn when you need to temporarily break them. This may happen, for example, when you want to reorder player positions in our above example.
|
||||
>
|
||||
> There exist several workarounds; one of them involves dropping and recreating the unique index after the temporary violations have been fixed. If you plan to use this technique, take care that only actual indexes can be dropped. Unique constraints created inside the table body can not:
|
||||
> There exist several workarounds; one of them involves dropping and recreating the unique index after the temporary violations have been fixed. If you plan to use this technique, be aware that only actual indexes can be dropped. Unique constraints created inside the table body cannot:
|
||||
>
|
||||
> ```swift
|
||||
> // Unique constraint on player(name) can not be dropped.
|
||||
> // Unique constraint on player(name) cannot be dropped.
|
||||
> try db.create(table: "player") { t in
|
||||
> t.column("name", .text).unique()
|
||||
> }
|
||||
@@ -252,7 +252,7 @@ try db.create(
|
||||
>
|
||||
> If you want to turn an undroppable constraint into a droppable index, you'll need to recreate the database table. See <doc:Migrations> for the detailed procedure.
|
||||
|
||||
☝️ **If a table misses unique indexes**, some record methods such as ``FetchableRecord/fetchOne(_:key:)-92b9m`` and ``TableRecord/deleteOne(_:key:)-5pdh5`` will raise a fatal error:
|
||||
☝️ **If a table lacks unique indexes**, some record methods such as ``FetchableRecord/fetchOne(_:key:)-92b9m`` and ``TableRecord/deleteOne(_:key:)-5pdh5`` will raise a fatal error:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
@@ -262,11 +262,11 @@ try dbQueue.write { db in
|
||||
|
||||
// Use instead:
|
||||
let player = try Player
|
||||
.filter(Column("teamId") == 42 && Column("position") == 1)
|
||||
.filter { $0.teamId == 42 && $0.position == 1 }
|
||||
.fetchOne(db)
|
||||
|
||||
try Player
|
||||
.filter(Column("name") == "Arthur")
|
||||
.filter { $0.name == "Arthur" }
|
||||
.deleteAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
@@ -23,7 +23,7 @@ We'll address all of those challenges below.
|
||||
|
||||
## Use the WAL mode
|
||||
|
||||
In order to access a shared database, use a ``DatabasePool``. It opens the database in the [WAL mode], which helps sharing a database because it allows multiple processes to access the database concurrently.
|
||||
In order to access a shared database, use a ``DatabasePool``. It opens the database in the [WAL mode], which helps share a database because it allows multiple processes to access the database concurrently.
|
||||
|
||||
It is also possible to use a ``DatabaseQueue``, with the `.wal` ``Configuration/journalMode``.
|
||||
|
||||
@@ -141,7 +141,7 @@ Since several processes may open the database at the same time, protect the crea
|
||||
|
||||
Read-only connections will fail unless two extra files ending in `-shm` and `-wal` are present next to the database file ([source](https://www.sqlite.org/walformat.html#operations_that_require_locks_and_which_locks_those_operations_use)). Those files are regular companions of databases in the [WAL mode]. But they are deleted, under regular operations, when database connections are closed. Precisely speaking, they *may* be deleted: it depends on the SQLite and the operating system versions ([source](https://github.com/groue/GRDB.swift/issues/739#issuecomment-604363998)). And when they are deleted, read-only connections fail.
|
||||
|
||||
The solution is to enable the "persistent WAL mode", as shown in the sample code above, by setting the [SQLITE_FCNTL_PERSIST_WAL](https://www.sqlite.org/c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntlpersistwal) flag. This mode makes sure the `-shm` and `-wal` files are never deleted, and guarantees a database access to read-only connections.
|
||||
The solution is to enable the "persistent WAL mode", as shown in the sample code above, by setting the [SQLITE_FCNTL_PERSIST_WAL](https://www.sqlite.org/c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntlpersistwal) flag. This mode makes sure the `-shm` and `-wal` files are never deleted, and guarantees database access to read-only connections.
|
||||
|
||||
|
||||
## How to limit the SQLITE_BUSY error
|
||||
@@ -224,7 +224,7 @@ do {
|
||||
|
||||
Post ``Database/resumeNotification`` in order to resume suspended databases. You can safely post this notification when the app comes back to foreground.
|
||||
|
||||
In applications that use the background modes supported by iOS, post `resumeNotification` method from each and every background mode callback that may use the database, and don't forget to post `suspendNotification` again before the app turns suspended.
|
||||
In applications that use the background modes supported by iOS, post `resumeNotification` from each and every background mode callback that may use the database, and don't forget to post `suspendNotification` again before the app is suspended.
|
||||
|
||||
## How to perform cross-process database observation
|
||||
|
||||
@@ -235,13 +235,17 @@ Whenever you need to notify other processes that the database has been changed,
|
||||
```swift
|
||||
// Notify all changes made to the database
|
||||
let observation = DatabaseRegionObservation(tracking: .fullDatabase)
|
||||
let observer = try observation.start(in: dbPool) { db in
|
||||
let cancellable = observation.start(in: dbPool) { error in
|
||||
// Handle error
|
||||
} onChange: { db in
|
||||
// Notify other processes
|
||||
}
|
||||
|
||||
// Notify changes made to the "player" and "team" tables only
|
||||
let observation = DatabaseRegionObservation(tracking: Player.all(), Team.all())
|
||||
let observer = try observation.start(in: dbPool) { db in
|
||||
let cancellable = observation.start(in: dbPool) { error in
|
||||
// Handle error
|
||||
} onChange: { db in
|
||||
// Notify other processes
|
||||
}
|
||||
```
|
||||
|
||||
@@ -22,7 +22,7 @@ See <doc:DatabaseConnections>.
|
||||
|
||||
#### Tracing SQL Statements
|
||||
|
||||
You can setup a tracing function that prints out all executed SQL requests with ``prepareDatabase(_:)`` and ``Database/trace(options:_:)``:
|
||||
You can set up a tracing function that prints out all executed SQL requests with ``prepareDatabase(_:)`` and ``Database/trace(options:_:)``:
|
||||
|
||||
```swift
|
||||
var config = Configuration()
|
||||
@@ -35,7 +35,7 @@ let dbQueue = try DatabaseQueue(
|
||||
configuration: config)
|
||||
|
||||
// Prints "SQL> SELECT COUNT(*) FROM player"
|
||||
let playerCount = dbQueue.read { db in
|
||||
let playerCount = try dbQueue.read { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
@@ -96,6 +96,7 @@ do {
|
||||
- ``persistentReadOnlyConnections``
|
||||
- ``prepareDatabase(_:)``
|
||||
- ``publicStatementArguments``
|
||||
- ``schemaSource``
|
||||
- ``transactionClock``
|
||||
- ``TransactionClock``
|
||||
|
||||
@@ -106,3 +107,7 @@ do {
|
||||
- ``writeQoS``
|
||||
- ``targetQueue``
|
||||
- ``writeTargetQueue``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``DatabaseSchemaSource``
|
||||
@@ -12,7 +12,7 @@ import GRDB
|
||||
let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
```
|
||||
|
||||
SQLite creates the database file if it does not already exist. The connection is closed when the database queue gets deallocated.
|
||||
SQLite creates the database file if it does not already exist. The connection is closed when the database pool gets deallocated.
|
||||
|
||||
**A `DatabasePool` can be used from any thread.** The ``DatabaseWriter/write(_:)-76inz`` and ``DatabaseReader/read(_:)-3806d`` methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue:
|
||||
|
||||
@@ -33,7 +33,7 @@ Database access methods can return values:
|
||||
|
||||
```swift
|
||||
let playerCount = try dbPool.read { db in
|
||||
try Place.fetchCount(db)
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
|
||||
let newPlayerCount = try dbPool.write { db -> Int in
|
||||
@@ -42,7 +42,7 @@ let newPlayerCount = try dbPool.write { db -> Int in
|
||||
}
|
||||
```
|
||||
|
||||
The ``DatabaseWriter/write(_:)-76inz`` method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rollbacked, and the error is rethrown.
|
||||
The ``DatabaseWriter/write(_:)-76inz`` method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rolled back, and the error is rethrown.
|
||||
|
||||
When you don't need to modify the database, prefer the ``DatabaseReader/read(_:)-3806d`` method, because several threads can perform reads in parallel.
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ Database access methods can return values:
|
||||
|
||||
```swift
|
||||
let playerCount = try dbQueue.read { db in
|
||||
try Place.fetchCount(db)
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
|
||||
let newPlayerCount = try dbQueue.write { db -> Int in
|
||||
@@ -42,7 +42,7 @@ let newPlayerCount = try dbQueue.write { db -> Int in
|
||||
}
|
||||
```
|
||||
|
||||
The ``DatabaseWriter/write(_:)-76inz`` method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rollbacked, and the error is rethrown.
|
||||
The ``DatabaseWriter/write(_:)-76inz`` method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rolled back, and the error is rethrown.
|
||||
|
||||
When you don't need to modify the database, prefer the ``DatabaseReader/read(_:)-3806d`` method: it prevents any modification to the database.
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## Overview
|
||||
|
||||
`DatabaseRegionObservation` tracks insertions, updates, and deletions that impact the tracked region, whether performed with raw SQL, or <doc:QueryInterface>. This includes indirect changes triggered by [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
|
||||
`DatabaseRegionObservation` tracks insertions, updates, and deletions that impact the tracked region, whether performed with raw SQL, or <doc:QueryInterface>. This includes indirect changes triggered by [foreign key actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
|
||||
|
||||
See <doc:GRDB/DatabaseRegionObservation#Dealing-with-Undetected-Changes> below for the list of exceptions.
|
||||
|
||||
@@ -22,14 +22,14 @@ let observation = DatabaseRegionObservation(tracking: Player.all())
|
||||
Then start the observation from a ``DatabaseQueue`` or ``DatabasePool``:
|
||||
|
||||
```swift
|
||||
let cancellable = try observation.start(in: dbQueue) { error in
|
||||
let cancellable = observation.start(in: dbQueue) { error in
|
||||
// Handle error
|
||||
} onChange: { (db: Database) in
|
||||
print("Players were changed")
|
||||
}
|
||||
```
|
||||
|
||||
Enjoy the changes notifications:
|
||||
Enjoy the change notifications:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
@@ -59,7 +59,7 @@ You can feed `DatabaseRegionObservation` with any type that conforms to the ``Da
|
||||
```swift
|
||||
// Observe the score column of the 'player' table
|
||||
let observation = DatabaseRegionObservation(
|
||||
tracking: Player.select(Column("score")))
|
||||
tracking: Player.select(\.score))
|
||||
|
||||
// Observe the 'score' column of the 'player' table
|
||||
let observation = DatabaseRegionObservation(
|
||||
@@ -79,7 +79,7 @@ let observation = DatabaseRegionObservation(
|
||||
`DatabaseRegionObservation` will not notify impactful transactions whenever the database is modified in an undetectable way:
|
||||
|
||||
- Changes performed by external database connections.
|
||||
- Changes performed by SQLite statements that are not compiled and executed by GRDB.
|
||||
- Changes performed by SQLite statements that are not a `DELETE`, `INSERT` or `UPDATE` statement compiled and executed by GRDB.
|
||||
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
|
||||
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ A type that can convert itself into and out of a database value.
|
||||
|
||||
A `DatabaseValueConvertible` type supports conversion to and from database values (null, integers, doubles, strings, and blobs). `DatabaseValueConvertible` is adopted by `Bool`, `Int`, `String`, `Date`, etc.
|
||||
|
||||
> Note: Types that converts to and from multiple columns in a database row must not conform to the `DatabaseValueConvertible` protocol. Those types are called **record types**, and should conform to record protocols instead. See <doc:QueryInterface>.
|
||||
> Note: Types that convert to and from multiple columns in a database row must not conform to the `DatabaseValueConvertible` protocol. Those types are called **record types**, and should conform to record protocols instead. See <doc:QueryInterface>.
|
||||
|
||||
> Note: Standard collections `Array`, `Set`, and `Dictionary` do not conform to `DatabaseValueConvertible`. To store arrays, sets, or dictionaries in individual database values, wrap them as properties of `Codable` record types. They will automatically be stored as JSON objects and arrays. See <doc:QueryInterface>.
|
||||
|
||||
@@ -14,7 +14,7 @@ A `DatabaseValueConvertible` type supports conversion to and from database value
|
||||
|
||||
To conform to `DatabaseValueConvertible`, implement the two requirements ``fromDatabaseValue(_:)-21zzv`` and ``databaseValue-1ob9k``. Do not customize the ``fromMissingColumn()-7iamp`` requirement. If your type `MyValue` conforms, then the conformance of the optional type `MyValue?` is automatic.
|
||||
|
||||
The implementation of `fromDatabaseValue` must return nil if the type can not be decoded from the raw database value. This nil value will have GRDB throw a decoding error accordingly.
|
||||
The implementation of `fromDatabaseValue` must return nil if the type cannot be decoded from the raw database value. This nil value will have GRDB throw a decoding error accordingly.
|
||||
|
||||
For example:
|
||||
|
||||
@@ -59,7 +59,7 @@ extension Grape: DatabaseValueConvertible { }
|
||||
|
||||
### Built-in Codable support
|
||||
|
||||
`DatabaseValueConvertible` is also ready-made for `Codable` types, which are automatically coded and decoded from JSON arrays and objects:
|
||||
`DatabaseValueConvertible` is also ready-made for `Codable` types, which are automatically encoded and decoded from JSON arrays and objects:
|
||||
|
||||
```swift
|
||||
struct Color: Codable {
|
||||
@@ -91,7 +91,7 @@ protocol DatabaseValueConvertible {
|
||||
import Tagged
|
||||
|
||||
struct Player: Identifiable {
|
||||
// Thanks to Tagged, Player.ID can not be mismatched with Team.ID or
|
||||
// Thanks to Tagged, Player.ID cannot be confused with Team.ID or
|
||||
// Award.ID, even though they all wrap strings.
|
||||
typealias ID = Tagged<Player, String>
|
||||
var id: ID
|
||||
|
||||
@@ -66,9 +66,9 @@ try insertStatement.execute(arguments: ["name": "Arthur", "score": 1000])
|
||||
let player = try Player.fetchOne(selectStatement, arguments: ["Arthur"])
|
||||
```
|
||||
|
||||
> Note: A prepared statement that has failed with an error can not be recovered. Create a new instance, or use a cached statement as described below.
|
||||
> Note: A prepared statement that has failed with an error cannot be recovered. Create a new instance, or use a cached statement as described below.
|
||||
|
||||
> Tip: When you look after the best performance, take care about a difference between setting the arguments before execution, and setting the arguments at the moment of execution:
|
||||
> Tip: When you look for the best performance, be aware of a difference between setting the arguments before execution, and setting the arguments at the moment of execution:
|
||||
>
|
||||
> ```swift
|
||||
> // First option
|
||||
@@ -81,8 +81,8 @@ let player = try Player.fetchOne(selectStatement, arguments: ["Arthur"])
|
||||
>
|
||||
> Both perform exactly the same action, and most applications should not care about the difference. Yet:
|
||||
>
|
||||
> - ``setArguments(_:)`` performs a copy of string and blob arguments. It uses the low-level [`SQLITE_TRANSIENT`](https://www.sqlite.org/c3ref/c_static.html) option, and fits well the reuse of a given statement with the same arguments.
|
||||
> - ``execute(arguments:)`` avoids a temporary allocation for string and blob arguments if the number of arguments is small. Instead of `SQLITE_TRANSIENT`, it uses the low-level [`SQLITE_STATIC`](https://www.sqlite.org/c3ref/c_static.html) option. This fits well the reuse of a given statement with various arguments.
|
||||
> - ``setArguments(_:)`` performs a copy of string and blob arguments. It uses the low-level [`SQLITE_TRANSIENT`](https://www.sqlite.org/c3ref/c_static.html) option, and is well suited to the reuse of a given statement with the same arguments.
|
||||
> - ``execute(arguments:)`` avoids a temporary allocation for string and blob arguments if the number of arguments is small. Instead of `SQLITE_TRANSIENT`, it uses the low-level [`SQLITE_STATIC`](https://www.sqlite.org/c3ref/c_static.html) option. This is well suited to the reuse of a given statement with various arguments.
|
||||
>
|
||||
> Don't make a blind choice, and monitor your app performance if it really matters!
|
||||
|
||||
@@ -154,7 +154,7 @@ let statements = try db.allStatements(sql: """
|
||||
let players = try statements.flatMap { statement in
|
||||
try Player.fetchCursor(statement)
|
||||
}
|
||||
for let player = try players.next() {
|
||||
while let player = try players.next() {
|
||||
print(player.name)
|
||||
}
|
||||
```
|
||||
@@ -190,7 +190,7 @@ let statements = try Array(db.allStatements(sql: """
|
||||
- ``validateArguments(_:)``
|
||||
- ``StatementArguments``
|
||||
|
||||
### Statement Informations
|
||||
### Statement Information
|
||||
|
||||
- ``columnCount``
|
||||
- ``columnNames``
|
||||
|
||||
@@ -17,17 +17,17 @@ let observer = MyObserver()
|
||||
dbQueue.add(transactionObserver: observer)
|
||||
```
|
||||
|
||||
By default, database holds weak references to its transaction observers: they are not retained, and stop getting notifications after they are deallocated. See <doc:TransactionObserver#Observation-Extent> for more options.
|
||||
By default, the database holds weak references to its transaction observers: they are not retained, and stop getting notifications after they are deallocated. See <doc:TransactionObserver#Observation-Extent> for more options.
|
||||
|
||||
## Database Changes And Transactions
|
||||
|
||||
Database changes are notified to the ``databaseDidChange(with:)`` callback. This includes indirect changes triggered by `ON DELETE` and `ON UPDATE` actions associated to [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions), and [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
|
||||
Database changes are reported to the ``databaseDidChange(with:)`` callback. This includes indirect changes triggered by `ON DELETE` and `ON UPDATE` actions associated with [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions), and [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
|
||||
|
||||
Transaction completions are notified to the ``databaseWillCommit()-7mksu``, ``databaseDidCommit(_:)`` and ``databaseDidRollback(_:)`` callbacks.
|
||||
Transaction completions are reported to the ``databaseWillCommit()-7mksu``, ``databaseDidCommit(_:)`` and ``databaseDidRollback(_:)`` callbacks.
|
||||
|
||||
> Important: Some changes and transactions are not automatically notified. See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes> below.
|
||||
|
||||
Notified changes are not actually written to disk until the transaction commits, and the `databaseDidCommit` callback is called. On the other side, `databaseDidRollback` confirms their invalidation:
|
||||
Notified changes are not actually written to disk until the transaction commits, and the `databaseDidCommit` callback is called. On the other hand, `databaseDidRollback` confirms their invalidation:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
@@ -76,7 +76,7 @@ try dbQueue.inTransaction { db in
|
||||
}
|
||||
```
|
||||
|
||||
Eventual errors thrown from `databaseWillCommit` are exposed to the application code:
|
||||
Errors thrown from `databaseWillCommit` are exposed to the application code:
|
||||
|
||||
```swift
|
||||
do {
|
||||
@@ -97,7 +97,7 @@ do {
|
||||
|
||||
**Transaction observers can choose the database changes they are interested in.**
|
||||
|
||||
The ``observes(eventsOfKind:)`` method filters events that are notified to ``databaseDidChange(with:)``. It is the most efficient and recommended change filtering technique, because it is only called once before a database query is executed, and can completely disable change tracking:
|
||||
By default, the ``observes(eventsOfKind:)`` method filters events that are reported to ``databaseDidChange(with:)``. It is the most efficient and recommended change filtering technique, because it is only called once before a database query is executed, and can completely disable change tracking:
|
||||
|
||||
```swift
|
||||
// Calls `observes(eventsOfKind:)` once.
|
||||
@@ -125,6 +125,8 @@ class PlayerObserver: TransactionObserver {
|
||||
|
||||
When the `observes(eventsOfKind:)` method returns false for all event kinds, the observer is still notified of transactions.
|
||||
|
||||
The filtering performed by ``observes(eventsOfKind:)`` makes a transaction observer unaware of changes performed by SQLite statements that are not a `DELETE`, `INSERT` or `UPDATE` statement compiled and executed by GRDB. You can lift this limitation with the ``TransactionObserver/databaseEventObservationStrategy``.
|
||||
|
||||
## Observation Extent
|
||||
|
||||
**You can specify how long an observer is notified of database changes and transactions.**
|
||||
@@ -160,7 +162,7 @@ dbQueue.inDatabase { db in
|
||||
|
||||
- The default extent is `.observerLifetime`: the database holds a weak reference to the observer, and the observation automatically ends when the observer is deallocated. Meanwhile, the observer is notified of all changes and transactions.
|
||||
|
||||
- `.nextTransaction` activates the observer until the current or next transaction completes. The database keeps a strong reference to the observer until its `databaseDidCommit` or `databaseDidRollback` callback is called. Hereafter the observer won't get any further notification.
|
||||
- `.nextTransaction` activates the observer until the current or next transaction completes. The database keeps a strong reference to the observer until its `databaseDidCommit` or `databaseDidRollback` callback is called. After that, the observer won't get any further notification.
|
||||
|
||||
- `.databaseLifetime` has the database retain and notify the observer until the database connection is closed.
|
||||
|
||||
@@ -228,11 +230,11 @@ This extra API can be activated in two ways:
|
||||
|
||||
## Dealing with Undetected Changes
|
||||
|
||||
The changes and transactions that are not automatically notified to transaction observers are:
|
||||
The changes and transactions that are not automatically reported to transaction observers are:
|
||||
|
||||
- Read-only transactions.
|
||||
- Changes and transactions performed by external database connections.
|
||||
- Changes performed by SQLite statements that are not both compiled and executed through GRDB APIs.
|
||||
- Changes performed by SQLite statements that are not a `DELETE`, `INSERT` or `UPDATE` statement compiled and executed by GRDB (this limitation can be lifted, in your custom `TransactionObserver` type, with ``TransactionObserver/databaseEventObservationStrategy``).
|
||||
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
|
||||
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
- The deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite).
|
||||
@@ -265,8 +267,10 @@ try dbQueue.write { db in
|
||||
|
||||
### Filtering Database Changes
|
||||
|
||||
- ``databaseEventObservationStrategy``
|
||||
- ``observes(eventsOfKind:)``
|
||||
- ``DatabaseEventKind``
|
||||
- ``DatabaseEventObservationStrategy``
|
||||
|
||||
### Handling Database Changes
|
||||
|
||||
|
||||
@@ -4,13 +4,13 @@
|
||||
|
||||
## Overview
|
||||
|
||||
`ValueObservation` tracks insertions, updates, and deletions that impact the tracked value, whether performed with raw SQL, or <doc:QueryInterface>. This includes indirect changes triggered by [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
|
||||
`ValueObservation` tracks insertions, updates, and deletions that impact the tracked value, whether performed with raw SQL, or <doc:QueryInterface>. This includes indirect changes triggered by [foreign key actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
|
||||
|
||||
See <doc:GRDB/ValueObservation#Dealing-with-Undetected-Changes> below for the list of exceptions.
|
||||
|
||||
## ValueObservation Usage
|
||||
|
||||
1. Make sure that a unique database connection, ``DatabaseQueue`` or ``DatabasePool``, is kept open during the whole duration of the observation.
|
||||
1. Make sure that a single database connection, ``DatabaseQueue`` or ``DatabasePool``, is kept open during the whole duration of the observation.
|
||||
|
||||
2. Create a `ValueObservation` with a closure that fetches the observed value:
|
||||
|
||||
@@ -72,13 +72,13 @@ See <doc:GRDB/ValueObservation#Dealing-with-Undetected-Changes> below for the li
|
||||
|
||||
## ValueObservation Behavior
|
||||
|
||||
`ValueObservation` notifies an initial value before the eventual changes.
|
||||
`ValueObservation` notifies an initial value before subsequent changes.
|
||||
|
||||
`ValueObservation` only notifies changes committed to disk.
|
||||
|
||||
By default, `ValueObservation` notifies a fresh value whenever any component of its fetched value is modified (any fetched column, row, etc.). This can be configured: see <doc:ValueObservation#Specifying-the-Tracked-Region>.
|
||||
|
||||
By default, `ValueObservation` notifies the initial value, as well as eventual changes and errors, on the main actor, asynchronously. This can be configured: see <doc:ValueObservation#ValueObservation-Scheduling>.
|
||||
By default, `ValueObservation` notifies the initial value, as well as subsequent changes and errors, on the main actor, asynchronously. This can be configured: see <doc:ValueObservation#ValueObservation-Scheduling>.
|
||||
|
||||
By default, `ValueObservation` fetches a fresh value immediately after a change is committed in the database. In particular, modifying the database on the main thread triggers a fetch on the main thread as well. This behavior can be configured: see <doc:ValueObservation#ValueObservation-Scheduling>.
|
||||
|
||||
@@ -90,7 +90,7 @@ Starting an observation retains the database connection, until it is stopped. As
|
||||
|
||||
The database observation stops when the cancellable returned by the `start` method is cancelled or deallocated, or if an error occurs.
|
||||
|
||||
> Important: Take care that there are use cases that `ValueObservation` is unfit for.
|
||||
> Important: Be aware that there are use cases that `ValueObservation` is unfit for.
|
||||
>
|
||||
> For example, an application may need to process absolutely all changes, and avoid any coalescing. An application may also need to process changes before any further modifications could be performed in the database file. In those cases, the application needs to track *individual transactions*, not values: use ``DatabaseRegionObservation``.
|
||||
>
|
||||
@@ -98,7 +98,7 @@ The database observation stops when the cancellable returned by the `start` meth
|
||||
|
||||
## ValueObservation Scheduling
|
||||
|
||||
By default, `ValueObservation` notifies the initial value, as well as eventual changes and errors, on the main actor, asynchronously:
|
||||
By default, `ValueObservation` notifies the initial value, as well as subsequent changes and errors, on the main actor, asynchronously:
|
||||
|
||||
```swift
|
||||
// The default scheduling
|
||||
@@ -114,7 +114,7 @@ You can change this behavior by adding a `scheduling` argument to the `start()`
|
||||
|
||||
For example, the ``ValueObservationMainActorScheduler/immediate`` scheduler notifies all values on the main actor, and notifies the first one immediately when the observation starts.
|
||||
|
||||
It is very useful in graphic applications, because you can configure views right away, without waiting for the initial value to be fetched eventually. You don't have to implement any empty or loading screen, or to prevent some undesired initial animation. Take care that the user interface is not responsive during the fetch of the first value, so only use the `immediate` scheduling for very fast database requests!
|
||||
It is very useful in graphical applications, because you can configure views right away, without waiting for the initial value to be fetched eventually. You don't have to implement any empty or loading screen, or to prevent some undesired initial animation. Be aware that the user interface is not responsive during the fetch of the first value, so only use the `immediate` scheduling for very fast database requests!
|
||||
|
||||
```swift
|
||||
// Immediate scheduling notifies
|
||||
@@ -129,7 +129,7 @@ let cancellable = observation
|
||||
// <- Here "Fresh value" has already been printed.
|
||||
```
|
||||
|
||||
The ``ValueObservationScheduler/async(onQueue:)`` scheduler asynchronously schedules values and errors on the dispatch queue of your choice. Make sure you provide a serial dispatch queue, because a concurrent one such as `DispachQueue.global(qos: .default)` would mess with the ordering of fresh value notifications:
|
||||
The ``ValueObservationScheduler/async(onQueue:)`` scheduler asynchronously schedules values and errors on the dispatch queue of your choice. Make sure you provide a serial dispatch queue, because a concurrent one such as `DispatchQueue.global(qos: .default)` would mess with the ordering of fresh value notifications:
|
||||
|
||||
```swift
|
||||
// Async scheduling notifies all values
|
||||
@@ -168,11 +168,11 @@ do {
|
||||
|
||||
```
|
||||
|
||||
As described above, the `scheduling` argument controls the execution of the change and error callbacks. You also have some control on the execution of the database fetch:
|
||||
As described above, the `scheduling` argument controls the execution of the change and error callbacks. You also have some control over the execution of the database fetch:
|
||||
|
||||
- With the `.immediate` scheduling, the initial fetch is always performed synchronously, on the main actor, when the observation starts, so that the initial value can be notified immediately.
|
||||
|
||||
- With the default `.async` scheduling, the initial fetch is always performed asynchronouly. It never blocks the main thread.
|
||||
- With the default `.async` scheduling, the initial fetch is always performed asynchronously. It never blocks the main thread.
|
||||
|
||||
- By default, fresh values are fetched immediately after the database was changed. In particular, modifying the database on the main thread triggers a fetch on the main thread as well.
|
||||
|
||||
@@ -183,7 +183,7 @@ As described above, the `scheduling` argument controls the execution of the chan
|
||||
|
||||
## ValueObservation Sharing
|
||||
|
||||
Sharing a `ValueObservation` spares database resources. When a database change happens, a fresh value is fetched only once, and then notified to all clients of the shared observation.
|
||||
Sharing a `ValueObservation` saves database resources. When a database change happens, a fresh value is fetched only once, and then delivered to all clients of the shared observation.
|
||||
|
||||
You build a shared observation with ``shared(in:scheduling:extent:)``:
|
||||
|
||||
@@ -214,7 +214,7 @@ Consider a scenario where you'd like to get a specific Player's row, but only wh
|
||||
let observation = ValueObservation.tracking(
|
||||
// Define the tracked database region
|
||||
// (the score column of the player with id 1)
|
||||
region: Player.select(Column("score")).filter(id: 1),
|
||||
region: Player.select(\.score).filter(id: 1),
|
||||
// Define what to fetch upon such change to the tracked region
|
||||
// (the player with id 1)
|
||||
fetch: { db in try Player.fetchOne(db, id: 1) }
|
||||
@@ -228,11 +228,11 @@ This ``tracking(region:_:fetch:)`` method lets you entirely separate the **obser
|
||||
`ValueObservation` will not fetch and notify a fresh value whenever the database is modified in an undetectable way:
|
||||
|
||||
- Changes performed by external database connections.
|
||||
- Changes performed by SQLite statements that are not compiled and executed by GRDB.
|
||||
- Changes performed by SQLite statements that are not a `DELETE`, `INSERT` or `UPDATE` statement compiled and executed by GRDB.
|
||||
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
|
||||
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
|
||||
To have observations notify a fresh values after such an undetected change was performed, applications can take explicit action. For example, cancel and restart observations. Alternatively, call the ``Database/notifyChanges(in:)`` `Database` method from a write transaction:
|
||||
To have observations notify fresh values after such an undetected change was performed, applications can take explicit action. For example, cancel and restart observations. Alternatively, call the ``Database/notifyChanges(in:)`` `Database` method from a write transaction:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
@@ -263,15 +263,19 @@ You can filter out undesired duplicate notifications with the ``removeDuplicates
|
||||
|
||||
When needed, you can help GRDB optimize observations and reduce database contention:
|
||||
|
||||
> Important: **Keep your number of observations bounded.**
|
||||
>
|
||||
> In particular, do not independently observe all elements in a list. Instead, observe the whole list in a single observation.
|
||||
|
||||
> Tip: Stop observations when possible.
|
||||
>
|
||||
> For example, if a `UIViewController` needs to display database values, it can start the observation in `viewWillAppear`, and stop it in `viewWillDisappear`.
|
||||
>
|
||||
> In a SwiftUI application, you can profit from the [GRDBQuery](https://github.com/groue/GRDBQuery) companion library, and its [`View.queryObservation(_:)`](https://swiftpackageindex.com/groue/grdbquery/documentation/grdbquery/queryobservation) method.
|
||||
> In a SwiftUI application, you can benefit from the [GRDBQuery](https://github.com/groue/GRDBQuery) companion library, and its [`View.queryObservation(_:)`](https://swiftpackageindex.com/groue/grdbquery/documentation/grdbquery/queryobservation) method.
|
||||
|
||||
> Tip: Share observations when possible.
|
||||
>
|
||||
> Each call to `ValueObservation.start` method triggers independent values refreshes. When several components of your app are interested in the same value, consider sharing the observation with ``shared(in:scheduling:extent:)``.
|
||||
> Each call to the `ValueObservation.start` method triggers independent value refreshes. When several components of your app are interested in the same value, consider sharing the observation with ``shared(in:scheduling:extent:)``.
|
||||
|
||||
> Tip: When the observation processes some raw fetched values, use the ``map(_:)`` operator:
|
||||
>
|
||||
@@ -284,7 +288,7 @@ When needed, you can help GRDB optimize observations and reduce database content
|
||||
>
|
||||
> // Optimized observation
|
||||
> let observation = ValueObservation
|
||||
> .tracking { db try Player.fetchAll(db) }
|
||||
> .tracking { db in try Player.fetchAll(db) }
|
||||
> .map { players in computeMyValue(players) }
|
||||
> ```
|
||||
>
|
||||
@@ -292,7 +296,7 @@ When needed, you can help GRDB optimize observations and reduce database content
|
||||
|
||||
> Tip: When the observation tracks a constant database region, create an optimized observation with the ``tracking(regions:fetch:)`` or ``trackingConstantRegion(_:)`` methods. Make sure you read the documentation of those methods, or you might write an observation that misses some database changes.
|
||||
|
||||
**Truncating WAL checkpoints impact ValueObservation.** Such checkpoints are performed with ``Database/checkpoint(_:on:)`` or [`PRAGMA wal_checkpoint`](https://www.sqlite.org/pragma.html#pragma_wal_checkpoint). When an observation is started on a ``DatabasePool``, from a database that has a missing or empty [wal file](https://www.sqlite.org/tempfiles.html#write_ahead_log_wal_files), the observation will always notify two values when it starts, even if the database content is not changed. This is a consequence of the impossibility to create the [wal snapshot](https://www.sqlite.org/c3ref/snapshot_get.html) needed for detecting that no changes were performed during the observation startup. If your application performs truncating checkpoints, you will avoid this behavior if you recreate a non-empty wal file before starting observations. To do so, perform any kind of no-op transaction (such a creating and dropping a dummy table).
|
||||
**Truncating WAL checkpoints impact ValueObservation.** Such checkpoints are performed with ``Database/checkpoint(_:on:)`` or [`PRAGMA wal_checkpoint`](https://www.sqlite.org/pragma.html#pragma_wal_checkpoint). When an observation is started on a ``DatabasePool``, from a database that has a missing or empty [wal file](https://www.sqlite.org/tempfiles.html#write_ahead_log_wal_files), the observation will always notify two values when it starts, even if the database content is not changed. This is a consequence of the impossibility of creating the [wal snapshot](https://www.sqlite.org/c3ref/snapshot_get.html) needed for detecting that no changes were performed during the observation startup. If your application performs truncating checkpoints, you will avoid this behavior if you recreate a non-empty wal file before starting observations. To do so, perform any kind of no-op transaction (such as creating and dropping a dummy table).
|
||||
|
||||
|
||||
## Topics
|
||||
|
||||
@@ -28,7 +28,7 @@ Use this library to save your application’s permanent data into SQLite databas
|
||||
|
||||
- **Leverage your SQLite skills**
|
||||
|
||||
Not all developers need advanced SQLite features. But when you do, GRDB is as sharp as you want it to be. Come with your SQL and SQLite skills, or learn new ones as you go!
|
||||
Not all developers need advanced SQLite features. But when you do, GRDB is as sharp as you want it to be. Bring your SQL and SQLite skills, or learn new ones as you go!
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -94,6 +94,7 @@ let players: [Player] = try dbQueue.read { db in
|
||||
- <doc:RecordRecommendedPractices>
|
||||
- <doc:RecordTimestamps>
|
||||
- <doc:SingleRowTables>
|
||||
- <doc:ViewRecords>
|
||||
|
||||
### Application Tools
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ Store and use JSON values in SQLite databases.
|
||||
|
||||
## Overview
|
||||
|
||||
SQLite and GRDB can store and fetch JSON values in database columns. Starting iOS 16+, macOS 10.15+, tvOS 17+, and watchOS 9+, JSON values can be manipulated at the database level.
|
||||
SQLite and GRDB can store and fetch JSON values in database columns. Starting with iOS 16, macOS 10.15, tvOS 17, and watchOS 9, JSON values can be manipulated at the database level.
|
||||
|
||||
## Store and fetch JSON values
|
||||
|
||||
@@ -36,10 +36,16 @@ try db.create(table: "player") { t in
|
||||
> JSONColumn("address")["country"],
|
||||
> ])
|
||||
>
|
||||
> struct Player: FetchableRecord, TableRecord {
|
||||
> enum Columns {
|
||||
> static let address = JSONColumn("address")
|
||||
> }
|
||||
> }
|
||||
>
|
||||
> // SELECT * FROM player
|
||||
> // WHERE address ->> 'country' = 'DE'
|
||||
> let germanPlayers = try Player
|
||||
> .filter(JSONColumn("address")["country"] == "DE")
|
||||
> .filter { $0.address["country"] == "DE" }
|
||||
> .fetchAll(db)
|
||||
> ```
|
||||
|
||||
@@ -104,18 +110,24 @@ extension Team: FetchableRecord, PersistableRecord {
|
||||
> struct Address: Codable { ... }
|
||||
> extension Address: DatabaseValueConvertible {}
|
||||
>
|
||||
> struct Player: FetchableRecord, TableRecord {
|
||||
> enum Columns {
|
||||
> static let address = JSONColumn("address")
|
||||
> }
|
||||
> }
|
||||
>
|
||||
> // SELECT * FROM player
|
||||
> // WHERE address = '{"street": "...", "city": "...", "country": "..."}'
|
||||
> let players = try Player
|
||||
> .filter(JSONColumn("address") == Address(...))
|
||||
> .filter { $0.address == Address(...) }
|
||||
> .fetchAll(db)
|
||||
> ```
|
||||
>
|
||||
> Take care that SQLite will compare strings, not JSON objects: white-space and key ordering matter. For this comparison to succeed, make sure that the database contains values that are formatted exactly like a serialized `Address`.
|
||||
> Be aware that SQLite will compare strings, not JSON objects: white-space and key ordering matter. For this comparison to succeed, make sure that the database contains values that are formatted exactly like a serialized `Address`.
|
||||
|
||||
## Manipulate JSON values at the database level
|
||||
|
||||
[SQLite JSON functions and operators](https://www.sqlite.org/json1.html) are available starting iOS 16+, macOS 10.15+, tvOS 17+, and watchOS 9+.
|
||||
[SQLite JSON functions and operators](https://www.sqlite.org/json1.html) are available starting with iOS 16, macOS 10.15, tvOS 17, and watchOS 9.
|
||||
|
||||
Functions such as `JSON`, `JSON_EXTRACT`, `JSON_PATCH` and others are available as static methods on `Database`: ``Database/json(_:)``, ``Database/jsonExtract(_:atPath:)``, ``Database/jsonPatch(_:with:)``, etc.
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ You can think of migrations as being 'versions' of the database. A database sche
|
||||
|
||||
GRDB can update the database schema along this timeline, bringing it from whatever point it is in the history to the latest version. When a user upgrades your application, only non-applied migrations are run.
|
||||
|
||||
You setup migrations in a ``DatabaseMigrator`` instance. For example:
|
||||
You set up migrations in a ``DatabaseMigrator`` instance. For example:
|
||||
|
||||
```swift
|
||||
var migrator = DatabaseMigrator()
|
||||
@@ -74,11 +74,11 @@ try dbQueue.read { db in
|
||||
}
|
||||
```
|
||||
|
||||
**Each migration runs in a separate transaction.** Should one throw an error, its transaction is rollbacked, subsequent migrations do not run, and the error is eventually thrown by ``DatabaseMigrator/migrate(_:)``.
|
||||
**Each migration runs in a separate transaction.** Should one throw an error, its transaction is rolled back, subsequent migrations do not run, and the error is eventually thrown by ``DatabaseMigrator/migrate(_:)``.
|
||||
|
||||
**Migrations run with deferred foreign key checks.** This means that eventual foreign key violations are only checked at the end of the migration (and they make the migration fail). See <doc:Migrations#Foreign-Key-Checks> below for more information.
|
||||
**Migrations run with deferred foreign key checks.** This means that foreign key violations are only checked at the end of the migration (and they make the migration fail). See <doc:Migrations#Foreign-Key-Checks> below for more information.
|
||||
|
||||
**The memory of applied migrations is stored in the database itself** (in a reserved table).
|
||||
**The record of applied migrations is stored in the database itself** (in a reserved table).
|
||||
|
||||
## Defining the Database Schema from a Migration
|
||||
|
||||
@@ -94,6 +94,26 @@ migrator.registerMigration("Create authors") { db in
|
||||
}
|
||||
```
|
||||
|
||||
#### How to Rename a Foreign Key
|
||||
|
||||
When a migration **renames a foreign key**, make sure the migration runs with `.immediate` foreign key checks, in order to avoid database integrity problems:
|
||||
|
||||
```swift
|
||||
// IMPORTANT: rename foreign keys with immediate foreign key checks.
|
||||
migrator.registerMigration("Guilds", foreignKeyChecks: .immediate) { db in
|
||||
try db.rename(table: "team", to: "guild")
|
||||
|
||||
try db.alter(table: "player") { t in
|
||||
// Rename a foreign key
|
||||
t.rename(column: "teamId", to: "guildId")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Note: migrations that run with `.immediate` foreign key checks cannot be used to recreate database tables, as described below. When needed, define two migrations instead of one.
|
||||
|
||||
#### How to Recreate a Database Table
|
||||
|
||||
When you need to modify a table in a way that is not directly supported by SQLite, or not available on your target operating system, you will need to recreate the database table.
|
||||
|
||||
For example:
|
||||
@@ -113,19 +133,39 @@ migrator.registerMigration("Add NOT NULL check on author.name") { db in
|
||||
|
||||
The detailed sequence of operations for recreating a database table from a migration is:
|
||||
|
||||
1. When relevant, remember the format of all indexes, triggers, and views associated with table X. This information will be needed in steps 6 and 7 below. One way to do this is to run a query like the following: `SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'`.
|
||||
1. When relevant, remember the format of all indexes, triggers, and views associated with table `X`. This information will be needed in step 6 below. One way to do this is to run the following statement and examine the output in the console:
|
||||
|
||||
2. Use `CREATE TABLE` to construct a new table "new_X" that is in the desired revised format of table X. Make sure that the name "new_X" does not collide with any existing table name, of course.
|
||||
```swift
|
||||
try db.dumpSQL("SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'")
|
||||
```
|
||||
|
||||
3. Transfer content from X into new_X using a statement like: `INSERT INTO new_X SELECT ... FROM X`.
|
||||
2. Construct a new table `new_X` that is in the desired revised format of table `X`. Make sure that the name `new_X` does not collide with any existing table name, of course.
|
||||
|
||||
4. Drop the old table X: `DROP TABLE X`.
|
||||
```swift
|
||||
try db.create(table: "new_X") { t in ... }
|
||||
```
|
||||
|
||||
5. Change the name of new_X to X using: `ALTER TABLE new_X RENAME TO X`.
|
||||
3. Transfer content from `X` into `new_X` using a statement like:
|
||||
|
||||
6. When relevant, use `CREATE INDEX`, `CREATE TRIGGER`, and `CREATE VIEW` to reconstruct indexes, triggers, and views associated with table X. Perhaps use the old format of the triggers, indexes, and views saved from step 3 above as a guide, making changes as appropriate for the alteration.
|
||||
```swift
|
||||
try db.execute(sql: "INSERT INTO new_X SELECT ... FROM X")
|
||||
```
|
||||
|
||||
7. If any views refer to table X in a way that is affected by the schema change, then drop those views using `DROP VIEW` and recreate them with whatever changes are necessary to accommodate the schema change using `CREATE VIEW`.
|
||||
4. Drop the old table `X`:
|
||||
|
||||
```swift
|
||||
try db.drop(table: "X")
|
||||
```
|
||||
|
||||
5. Change the name of `new_X` to `X` using:
|
||||
|
||||
```swift
|
||||
try db.rename(table: "new_X", to: "X")
|
||||
```
|
||||
|
||||
6. When relevant, reconstruct indexes, triggers, and views associated with table `X`.
|
||||
|
||||
7. If any views refer to table `X` in a way that is affected by the schema change, then drop those views using `DROP VIEW` and recreate them with whatever changes are necessary to accommodate the schema change using `CREATE VIEW`.
|
||||
|
||||
> Important: When recreating a table, be sure to follow the above procedure exactly, in the given order, or you might corrupt triggers, views, and foreign key constraints.
|
||||
>
|
||||
@@ -153,7 +193,7 @@ migrator.registerMigration("Create authors") { db in
|
||||
}
|
||||
```
|
||||
|
||||
In other words, migrations should talk to the database, only to the database, and use the database language. This makes sure the Swift code of any given migrations will never have to change in the future.
|
||||
In other words, migrations should talk to the database, only to the database, and use the database language. This makes sure the Swift code of any given migration will never have to change in the future.
|
||||
|
||||
Migrations and the rest of the application code do not live at the same "moment". Migrations describe the past states of the database, while the rest of the application code targets the latest one only. This difference is the reason why **migrations should not depend on application types.**
|
||||
|
||||
@@ -182,7 +222,7 @@ migrator.eraseDatabaseOnSchemaChange = true
|
||||
|
||||
By default, each migration temporarily disables foreign keys, and performs a full check of all foreign keys in the database before it is committed on disk.
|
||||
|
||||
When the database becomes very big, those checks may have a noticeable impact on migration performances. You'll know this by profiling migrations, and looking for the time spent in the `checkForeignKeys` method.
|
||||
When the database becomes very big, those checks may have a noticeable impact on migration performance. You'll know this by profiling migrations, and looking for the time spent in the `checkForeignKeys` method.
|
||||
|
||||
You can make those migrations faster, but this requires a little care.
|
||||
|
||||
@@ -194,7 +234,7 @@ When you register a migration with `.immediate` foreign key checks, the migratio
|
||||
migrator.registerMigration("Fast migration", foreignKeyChecks: .immediate) { db in ... }
|
||||
```
|
||||
|
||||
Such a migration is faster, and it still guarantees database integrity. But it must only execute schema alterations directly supported by SQLite. Migrations that recreate tables as described in <doc:Migrations#Defining-the-Database-Schema-from-a-Migration> **must not** run with immediate foreign keys checks. You'll need to use the second mitigation technique:
|
||||
Such a migration is faster, and it still guarantees database integrity. But it must only execute schema alterations directly supported by SQLite. Migrations that recreate tables as described in <doc:Migrations#Defining-the-Database-Schema-from-a-Migration> **must not** run with immediate foreign key checks. You'll need to use the second mitigation technique:
|
||||
|
||||
**Your second mitigation technique is to disable deferred foreign key checks.**
|
||||
|
||||
|
||||
@@ -44,14 +44,14 @@ try migrator.migrate(dbQueue)
|
||||
3. An author must have a name.
|
||||
4. The country of an author is not always known.
|
||||
5. A book must have a title.
|
||||
6. The `book.authorId` column is used to link a book to the author it belongs to. This column is indexed in order to ease the selection of an author's books. A foreign key is defined from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions](https://sqlite.org/foreignkeys.html#fk_actions) for more information.
|
||||
6. The `book.authorId` column is used to link a book to the author it belongs to. This column is indexed in order to ease the selection of an author's books. A foreign key is defined from `book.authorId` column to `author.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions](https://sqlite.org/foreignkeys.html#fk_actions) for more information.
|
||||
7. The `book.authorId` column is not null so that SQLite guarantees that all books have an author.
|
||||
|
||||
Thanks to this database schema, the application will always process *consistent data*, no matter how wrong the Swift code can get. Even after a hard crash, all books will have an author, a non-nil title, etc.
|
||||
|
||||
> Tip: **A local SQLite database is not a JSON payload loaded from a remote server.**
|
||||
>
|
||||
> The JSON format and content can not be controlled, and an application must defend itself against wacky servers. But a local database is under your full control. It is trustable. A relational database such as SQLite guarantees the quality of users data, as long as enough energy is put in the proper definition of the database schema.
|
||||
> The JSON format and content cannot be controlled, and an application must defend itself against wacky servers. But a local database is under your full control. It is trustworthy. A relational database such as SQLite guarantees the quality of users' data, as long as enough energy is put in the proper definition of the database schema.
|
||||
|
||||
> Tip: **Plan early for future versions of your application**: use <doc:Migrations>.
|
||||
|
||||
@@ -120,7 +120,7 @@ let books = try dbQueue.read { db in
|
||||
}
|
||||
```
|
||||
|
||||
> Tip: When a column of a database table can't be NULL, define a non-optional property in the record type. On the other side, when the database may contain NULL, define an optional property. Compare:
|
||||
> Tip: When a column of a database table can't be NULL, define a non-optional property in the record type. On the other hand, when the database may contain NULL, define an optional property. Compare:
|
||||
>
|
||||
> ```swift
|
||||
> try db.create(table: "author") { t in
|
||||
@@ -138,7 +138,7 @@ let books = try dbQueue.read { db in
|
||||
>
|
||||
> There are exceptions to this rule.
|
||||
>
|
||||
> For example, the `id` column is never NULL in the database. And yet, `Author` as an optional `id` property. That is because we want to create instances of `Author` before they could be inserted in the database, and be assigned an auto-incremented id. If the `id` property was not optional, the `Author` type could not profit from auto-incremented ids!
|
||||
> For example, the `id` column is never NULL in the database. And yet, `Author` has an optional `id` property. That is because we want to create instances of `Author` before they could be inserted in the database, and be assigned an auto-incremented id. If the `id` property was not optional, the `Author` type could not benefit from auto-incremented ids!
|
||||
>
|
||||
> Another exception to this rule is described in <doc:RecordTimestamps>, where the creation date of a record is never NULL in the database, but optional in the Swift type.
|
||||
|
||||
@@ -151,7 +151,7 @@ let books = try dbQueue.read { db in
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> Take care that **`Identifiable` is not a good fit for optional ids**. You will frequently meet optional ids for records with auto-incremented ids:
|
||||
> Be aware that **`Identifiable` is not a good fit for optional ids**. You will frequently meet optional ids for records with auto-incremented ids:
|
||||
>
|
||||
> ```swift
|
||||
> struct Player: Codable {
|
||||
@@ -172,9 +172,9 @@ let books = try dbQueue.read { db in
|
||||
|
||||
### Record Types Hide Intimate Database Details
|
||||
|
||||
In the previous sample codes, the `Book` and `Author` structs have one property per database column, and their types are natively supported by SQLite (`String`, `Int`, etc.)
|
||||
In the previous code samples, the `Book` and `Author` structs have one property per database column, and their types are natively supported by SQLite (`String`, `Int`, etc.)
|
||||
|
||||
But it happens that raw database column names, or raw column types, are not a very good fit for the application.
|
||||
But sometimes raw database column names, or raw column types, are not a very good fit for the application.
|
||||
|
||||
When this happens, it's time to **distinguish the Swift and database representations**. Record types are the dedicated place where raw database values can be transformed into Swift types that are well-suited for the rest of the application.
|
||||
|
||||
@@ -214,13 +214,13 @@ extension Book.Kind: DatabaseValueConvertible { }
|
||||
|
||||
// Fetch all novels
|
||||
let novels = try dbQueue.read { db in
|
||||
try Book.filter(Column("kind") == Book.Kind.novel).fetchAll(db)
|
||||
try Book.filter { $0.kind == Book.Kind.novel }.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
#### Second Example: GPS Coordinates
|
||||
|
||||
GPS coordinates can be stored in two distinct `latitude` and `longitude` columns. But the standard way to deal with such coordinate is a single `CLLocationCoordinate2D` struct.
|
||||
GPS coordinates can be stored in two distinct `latitude` and `longitude` columns. But the standard way to deal with such coordinates is a single `CLLocationCoordinate2D` struct.
|
||||
|
||||
When this happens, keep column properties private, and provide sensible accessors instead:
|
||||
|
||||
@@ -256,11 +256,11 @@ Generally speaking, private properties make it possible to hide raw columns from
|
||||
|
||||
#### Third Example: Money Amounts
|
||||
|
||||
Before storing money amounts in an SQLite database, take care that [floating-point numbers are never a good fit](https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency).
|
||||
Before storing money amounts in an SQLite database, be aware that [floating-point numbers are never a good fit](https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency).
|
||||
|
||||
SQLite only supports two kinds of numbers: integers and doubles, so we'll store amounts as integers. $12.00 will be represented by 1200, a quantity of cents. This allows SQLite to compute exact sums of price, for example.
|
||||
|
||||
On the other side, an amount of cents is not very practical for the rest of the Swift application. The [`Decimal`] type looks like a better fit.
|
||||
On the other hand, an amount of cents is not very practical for the rest of the Swift application. The [`Decimal`] type looks like a better fit.
|
||||
|
||||
That's why the `Product` record type has a `price: Decimal` property, backed by a `priceCents` integer column:
|
||||
|
||||
@@ -297,7 +297,7 @@ Once we have record types that are able to read and write in the database, we'd
|
||||
|
||||
### Columns
|
||||
|
||||
Requests that filter or sort records are defined with **columns**, defined in a dedicated enumeration. When the record type conforms to [`Codable`], columns can be derived from the `CodingKeys` enum:
|
||||
Requests that filter or sort records are defined with **columns**, defined in a dedicated enumeration, with the name `Columns`, nested inside the record type. When the record type conforms to [`Codable`], columns can be derived from the `CodingKeys` enum:
|
||||
|
||||
```swift
|
||||
// HOW TO define columns for a Codable record
|
||||
@@ -310,13 +310,15 @@ extension Author {
|
||||
}
|
||||
```
|
||||
|
||||
For other record types, declare a plain `String` enum that conforms to the ``ColumnExpression`` protocol:
|
||||
For non-Codable record types, declare columns with their names:
|
||||
|
||||
```swift
|
||||
// HOW TO define columns for a non-Codable record
|
||||
extension Author {
|
||||
enum Columns: String, ColumnExpression {
|
||||
case id, name, countryCode
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
static let name = Column("name")
|
||||
static let countryCode = Column("countryCode")
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -328,12 +330,12 @@ try dbQueue.read { db in
|
||||
// Fetch all authors, ordered by name,
|
||||
// in a localized case-insensitive fashion
|
||||
let sortedAuthors: [Author] = try Author.all()
|
||||
.order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
.order { $0.name.collating(.localizedCaseInsensitiveCompare) }
|
||||
.fetchAll(db)
|
||||
|
||||
// Count French authors
|
||||
let frenchAuthorCount: Int = try Author.all()
|
||||
.filter(Author.Columns.countryCode == "FR")
|
||||
.filter { $0.countryCode == "FR" }
|
||||
.fetchCount(db)
|
||||
}
|
||||
```
|
||||
@@ -349,13 +351,12 @@ Define those methods in extensions of the ``DerivableRequest`` protocol, as belo
|
||||
extension DerivableRequest<Author> {
|
||||
/// Order authors by name, in a localized case-insensitive fashion
|
||||
func orderByName() -> Self {
|
||||
let name = Author.Columns.name
|
||||
return order(name.collating(.localizedCaseInsensitiveCompare))
|
||||
order { $0.name.collating(.localizedCaseInsensitiveCompare) }
|
||||
}
|
||||
|
||||
/// Filters authors from a country
|
||||
func filter(countryCode: String) -> Self {
|
||||
filter(Author.Columns.countryCode == countryCode)
|
||||
filter { $0.countryCode == countryCode }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -363,13 +364,12 @@ extension DerivableRequest<Author> {
|
||||
extension DerivableRequest<Book> {
|
||||
/// Order books by title, in a localized case-insensitive fashion
|
||||
func orderByTitle() -> Self {
|
||||
let title = Book.Columns.title
|
||||
return order(title.collating(.localizedCaseInsensitiveCompare))
|
||||
order { $0.title.collating(.localizedCaseInsensitiveCompare) }
|
||||
}
|
||||
|
||||
/// Filters books by kind
|
||||
func filter(kind: Book.Kind) -> Self {
|
||||
filter(Book.Columns.kind == kind)
|
||||
filter { $0.kind == kind }
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -389,13 +389,13 @@ try dbQueue.read { db in
|
||||
}
|
||||
```
|
||||
|
||||
Extensions to the `DerivableRequest` protocol can not change the type of requests. They remain requests of the base record. To define requests of another type, use an extension to ``QueryInterfaceRequest``, as in the example below:
|
||||
Extensions to the `DerivableRequest` protocol cannot change the type of requests. They remain requests of the base record. To define requests of another type, use an extension to ``QueryInterfaceRequest``, as in the example below:
|
||||
|
||||
```swift
|
||||
extension QueryInterfaceRequest<Author> {
|
||||
// Selects authors' name
|
||||
func selectName() -> QueryInterfaceRequest<String> {
|
||||
select(Author.Columns.name)
|
||||
select(\.name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -408,7 +408,7 @@ let names: Set<String> = try Author.all()
|
||||
|
||||
## Associations
|
||||
|
||||
[Associations] help navigating from authors to their books and vice versa. Because the `book` table has an `authorId` column, we say that each book **belongs to** its author, and each author **has many** books:
|
||||
[Associations] help navigate from authors to their books and vice versa. Because the `book` table has an `authorId` column, we say that each book **belongs to** its author, and each author **has many** books:
|
||||
|
||||
```swift
|
||||
extension Book {
|
||||
@@ -515,9 +515,9 @@ let authorships: [Authorship] = try dbQueue.read { db in
|
||||
}
|
||||
```
|
||||
|
||||
In the above sample codes, requests that fetch values from several tables are decoded into additional record types: `AuthorInfo`, `LiteraryCareer`, and `Authorship`.
|
||||
In the above code samples, requests that fetch values from several tables are decoded into additional record types: `AuthorInfo`, `LiteraryCareer`, and `Authorship`.
|
||||
|
||||
Those record type conform to both [`Decodable`] and ``FetchableRecord``, so that they can feed from database rows. They do not provide any persistence methods, though. **All database writes are performed from persistable record instances** (of type `Author` or `Book`).
|
||||
Those record types conform to both [`Decodable`] and ``FetchableRecord``, so that they can be decoded from database rows. They do not provide any persistence methods, though. **All database writes are performed from persistable record instances** (of type `Author` or `Book`).
|
||||
|
||||
For more information about associations, see the [Associations] guide.
|
||||
|
||||
@@ -536,7 +536,7 @@ author.books.each do |book| # Lazily fetch books on demand
|
||||
end
|
||||
```
|
||||
|
||||
**GRDB does not perform lazy loading.** In a GUI application, lazy loading can not be achieved without record management (as in [Core Data]), which in turn comes with non-trivial pain points for developers regarding concurrency. Instead of lazy loading, the library provides the tooling needed to fetch data, even complex graphs, in an [isolated] fashion, so that fetched values accurately represent the database content, and all database invariants are preserved. See the <doc:Concurrency> guide for more information.
|
||||
**GRDB does not perform lazy loading.** In a GUI application, lazy loading cannot be achieved without record management (as in [Core Data]), which in turn comes with non-trivial pain points for developers regarding concurrency. Instead of lazy loading, the library provides the tooling needed to fetch data, even complex graphs, in an [isolated] fashion, so that fetched values accurately represent the database content, and all database invariants are preserved. See the <doc:Concurrency> guide for more information.
|
||||
|
||||
Vapor [Fluent] uses **eager loading**, which means that relationships are only fetched if explicitly requested:
|
||||
|
||||
|
||||
Loaded 100 of 473 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user