mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-03 04:58:44 +00:00
Compare commits
199
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
60beb7cd9c | ||
|
|
284a4ee1ac | ||
|
|
b27e378cfa | ||
|
|
459726f9af | ||
|
|
4f00e405c3 | ||
|
|
87f4d816e6 | ||
|
|
ea7ebe1ff5 | ||
|
|
89899432ba | ||
|
|
3a1c211746 | ||
|
|
c3664e2b16 | ||
|
|
ea1353bd6c | ||
|
|
4a5d4d6e49 | ||
|
|
c85abdba86 | ||
|
|
57aa4c30bf | ||
|
|
67b7941129 | ||
|
|
db01b0063c | ||
|
|
e1ddc8154f | ||
|
|
e637c156a2 | ||
|
|
60ad8a809a | ||
|
|
84ac401886 | ||
|
|
26b875f64c | ||
|
|
fdc8abfdbe | ||
|
|
fc641092f7 | ||
|
|
63d360053b | ||
|
|
dc440d5a8f | ||
|
|
5ab0d18055 | ||
|
|
437b800d8c | ||
|
|
b840babb55 | ||
|
|
725d4a3fba | ||
|
|
4ab8ac8d3f | ||
|
|
73b279b5c1 | ||
|
|
fa681fb8c6 | ||
|
|
cedcfbe330 | ||
|
|
abd3ba39b1 | ||
|
|
d66d2118b5 | ||
|
|
0a92a99223 | ||
|
|
19e5e62098 | ||
|
|
d948e37388 | ||
|
|
60de81633e | ||
|
|
c02139c045 | ||
|
|
93bd527984 | ||
|
|
157d02b55c | ||
|
|
82d28b3167 | ||
|
|
717c2836ec | ||
|
|
cf8fa0e5f8 | ||
|
|
84ef0a92da | ||
|
|
2ae000df43 | ||
|
|
738a187f68 | ||
|
|
4ff057ac3b | ||
|
|
0d49d7612f | ||
|
|
342b81f65e | ||
|
|
a651f34f67 | ||
|
|
5475dc98dc | ||
|
|
3692ba2293 | ||
|
|
266efa041c | ||
|
|
ebb2f7346d | ||
|
|
f955e5fabc | ||
|
|
65c803a110 | ||
|
|
8b1b3b0396 | ||
|
|
bf28d1bd85 | ||
|
|
45edf58f9e | ||
|
|
d07e8bd3a0 | ||
|
|
7feaa748a4 | ||
|
|
c159638498 | ||
|
|
5aa385094b | ||
|
|
1cd20176c6 | ||
|
|
06891e99e1 | ||
|
|
d5f38a6a24 | ||
|
|
68d23a5f33 | ||
|
|
75f92f6f14 | ||
|
|
6c70ee6b77 | ||
|
|
c8ae3cb61c | ||
|
|
dd4d3e35f3 | ||
|
|
7b2619e757 | ||
|
|
a7b9a27c51 | ||
|
|
fcfd6e9028 | ||
|
|
9011f71247 | ||
|
|
069bce217d | ||
|
|
5a91340671 | ||
|
|
ba2e3cb468 | ||
|
|
f633be4ba1 | ||
|
|
4074fcfcc7 | ||
|
|
18cdf4956e | ||
|
|
18e06a78a3 | ||
|
|
065ca71876 | ||
|
|
859a1d6184 | ||
|
|
f2ea4e91db | ||
|
|
1add9a9752 | ||
|
|
17c3f82f50 | ||
|
|
52a3d6ba23 | ||
|
|
54007a9ce1 | ||
|
|
77d8a46039 | ||
|
|
f6e695a21d | ||
|
|
3184334535 | ||
|
|
12e3923af1 | ||
|
|
b81e858ca0 | ||
|
|
82f300e534 | ||
|
|
9df1cfd110 | ||
|
|
373fe467d6 | ||
|
|
81eb6b128f | ||
|
|
c7ee12eff7 | ||
|
|
89330daa52 | ||
|
|
e408bd17d8 | ||
|
|
99ddc5e13c | ||
|
|
4c0cc84c2d | ||
|
|
4762f8bb36 | ||
|
|
7e6f71912c | ||
|
|
6b311941b1 | ||
|
|
5facc24ebb | ||
|
|
018ae03f8e | ||
|
|
52aef76b63 | ||
|
|
2fa5ca767f | ||
|
|
a1b76f9e06 | ||
|
|
2d19cab2b5 | ||
|
|
a551fbf443 | ||
|
|
c6e220a531 | ||
|
|
600d1b84b6 | ||
|
|
5629cfe6ff | ||
|
|
5d9b9edfe1 | ||
|
|
449c243a36 | ||
|
|
6ca4986bc2 | ||
|
|
063877d49c | ||
|
|
2f4d0c4588 | ||
|
|
0a544dc0d2 | ||
|
|
d64274474b | ||
|
|
e66dfacab8 | ||
|
|
0d4c6e592e | ||
|
|
5d7fdeae5a | ||
|
|
378c6785ea | ||
|
|
6d392f0a87 | ||
|
|
7c81c37e1f | ||
|
|
3f876978a1 | ||
|
|
a0ed1bfd33 | ||
|
|
be41d2dd03 | ||
|
|
e6c3a8d07a | ||
|
|
5e41ca7e4e | ||
|
|
0f942c014c | ||
|
|
40bebda712 | ||
|
|
37fd4c18b0 | ||
|
|
d5a41bd11b | ||
|
|
c22fc202a9 | ||
|
|
a0f14d816a | ||
|
|
ad33dfcfbf | ||
|
|
840fa3b5da | ||
|
|
397a008237 | ||
|
|
f7559d4c76 | ||
|
|
8cd71ac832 | ||
|
|
0ffd25bc74 | ||
|
|
ff7f9073fc | ||
|
|
93616775f6 | ||
|
|
81751625e0 | ||
|
|
9798f9f9fa | ||
|
|
db165581ea | ||
|
|
b4e851aa49 | ||
|
|
0169e340dc | ||
|
|
1d5d1aea68 | ||
|
|
0c333b6e22 | ||
|
|
6a24d835d3 | ||
|
|
3382280cc3 | ||
|
|
60fa8a630f | ||
|
|
9ba64c2426 | ||
|
|
29b5b99b89 | ||
|
|
725d38ea06 | ||
|
|
6509f7ed40 | ||
|
|
67bdc740bd | ||
|
|
1e2b454c4c | ||
|
|
a77f9d3f6a | ||
|
|
229bd98b9c | ||
|
|
692eac43a9 | ||
|
|
4f398a3457 | ||
|
|
44c13e5bff | ||
|
|
7b2393f2cd | ||
|
|
67dfdc1bbb | ||
|
|
cc8ed5ccb5 | ||
|
|
441823d5f4 | ||
|
|
1e5ee4b292 | ||
|
|
159a34bdf2 | ||
|
|
e936d6b42d | ||
|
|
cc567f2555 | ||
|
|
b3763ad08e | ||
|
|
c824b42757 | ||
|
|
d3862c0424 | ||
|
|
f6cb77a489 | ||
|
|
a1faa88579 | ||
|
|
43ff278748 | ||
|
|
5ed44b94bc | ||
|
|
e683df3494 | ||
|
|
9f0bd4944b | ||
|
|
3fab2db88d | ||
|
|
5f013b6ee7 | ||
|
|
734d911416 | ||
|
|
86bde428bf | ||
|
|
c5045dbe7a | ||
|
|
b0d73f3126 | ||
|
|
9e2eb6c599 | ||
|
|
3bf73e9f66 | ||
|
|
9bd26a5a1b | ||
|
|
84f5a91f7b | ||
|
|
c9ae697a44 |
No files matched your search
+32
-12
@@ -38,6 +38,18 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_14.2.app"
|
||||
runsOn: macOS-12
|
||||
destination: "platform=macOS"
|
||||
name: "macOS"
|
||||
- xcode: "Xcode_14.2.app"
|
||||
runsOn: macOS-12
|
||||
destination: "OS=16.2,name=iPhone 14"
|
||||
name: "iOS"
|
||||
- xcode: "Xcode_14.2.app"
|
||||
runsOn: macOS-12
|
||||
destination: "OS=16.1,name=Apple TV"
|
||||
name: "tvOS"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-12
|
||||
destination: "platform=macOS"
|
||||
@@ -46,10 +58,6 @@ jobs:
|
||||
runsOn: macOS-12
|
||||
destination: "OS=16.1,name=iPhone 14"
|
||||
name: "iOS"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-12
|
||||
destination: "OS=16.1,name=Apple TV"
|
||||
name: "tvOS"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
destination: "platform=macOS"
|
||||
@@ -72,6 +80,9 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_14.2.app"
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.2"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.1"
|
||||
@@ -92,9 +103,9 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_14.1.app"
|
||||
- xcode: "Xcode_14.2.app"
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.1"
|
||||
name: "Xcode 14.2"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
@@ -109,9 +120,12 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_14.1.app"
|
||||
- xcode: "Xcode_14.2.app"
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.1"
|
||||
name: "Xcode 14.2"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.0.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
@@ -126,9 +140,12 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_14.1.app"
|
||||
- xcode: "Xcode_14.2.app"
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.1"
|
||||
name: "Xcode 14.2"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.0.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
@@ -143,9 +160,12 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_14.1.app"
|
||||
- xcode: "Xcode_14.2.app"
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.1"
|
||||
name: "Xcode 14.2"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.0.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
|
||||
+125
-19
@@ -7,6 +7,14 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 6.x Releases
|
||||
|
||||
- `6.15.x` Releases - [6.15.0](#6150) - [6.15.1](#6151)
|
||||
- `6.14.x` Releases - [6.14.0](#6140)
|
||||
- `6.13.x` Releases - [6.13.0](#6130)
|
||||
- `6.12.x` Releases - [6.12.0](#6120)
|
||||
- `6.11.x` Releases - [6.11.0](#6110)
|
||||
- `6.10.x` Releases - [6.10.0](#6100) - [6.10.1](#6101) - [6.10.2](#6102)
|
||||
- `6.9.x` Releases - [6.9.0](#690) - [6.9.1](#691) - [6.9.2](#692)
|
||||
- `6.8.x` Releases - [6.8.0](#680)
|
||||
- `6.7.x` Releases - [6.7.0](#670)
|
||||
- `6.6.x` Releases - [6.6.0](#660) - [6.6.1](#661)
|
||||
- `6.5.x` Releases - [6.5.0](#650)
|
||||
@@ -15,15 +23,15 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
- `6.2.x` Releases - [6.2.0](#620)
|
||||
- `6.1.x` Releases - [6.1.0](#610)
|
||||
- `6.0.x` Releases - [6.0.0](#600)
|
||||
- `6.0.0` Betas - [6.0.0-beta](#600-beta) | [6.0.0-beta.2](#600-beta2) | [6.0.0-beta.3](#600-beta3) | [6.0.0-beta.4](#600-beta4)
|
||||
- `6.0.0` Betas - [6.0.0-beta](#600-beta) - [6.0.0-beta.2](#600-beta2) - [6.0.0-beta.3](#600-beta3) - [6.0.0-beta.4](#600-beta4)
|
||||
|
||||
#### 5.x Releases
|
||||
|
||||
- `5.26.x` Releases - [5.26.0](#5260) - [5.26.1](#5261)
|
||||
- `5.25.x` Releases - [5.25.0](#5250)
|
||||
- `5.24.x` Releases - [5.24.0](#5240) | [5.24.1](#5241)
|
||||
- `5.24.x` Releases - [5.24.0](#5240) - [5.24.1](#5241)
|
||||
- `5.23.x` Releases - [5.23.0](#5230)
|
||||
- `5.22.x` Releases - [5.22.0](#5220) | [5.22.1](#5221) | [5.22.2](#5222)
|
||||
- `5.22.x` Releases - [5.22.0](#5220) - [5.22.1](#5221) - [5.22.2](#5222)
|
||||
- `5.21.x` Releases - [5.21.0](#5210)
|
||||
- `5.20.x` Releases - [5.20.0](#5200)
|
||||
- `5.19.x` Releases - [5.19.0](#5190)
|
||||
@@ -38,41 +46,41 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
- `5.10.x` Releases - [5.10.0](#5100)
|
||||
- `5.9.x` Releases - [5.9.0](#590)
|
||||
- `5.8.x` Releases - [5.8.0](#580)
|
||||
- `5.7.x` Releases - [5.7.0](#570) | [5.7.1](#571) | [5.7.2](#572) | [5.7.3](#573) | [5.7.4](#574)
|
||||
- `5.7.x` Releases - [5.7.0](#570) - [5.7.1](#571) - [5.7.2](#572) - [5.7.3](#573) - [5.7.4](#574)
|
||||
- `5.6.x` Releases - [5.6.0](#560)
|
||||
- `5.5.x` Releases - [5.5.0](#550)
|
||||
- `5.4.x` Releases - [5.4.0](#540)
|
||||
- `5.3.x` Releases - [5.3.0](#530)
|
||||
- `5.2.x` Releases - [5.2.0](#520)
|
||||
- `5.1.x` Releases - [5.1.0](#510)
|
||||
- `5.0.x` Releases - [5.0.0](#500) | [5.0.1](#501) | [5.0.2](#502) | [5.0.3](#503)
|
||||
- `5.0.0` Betas - [5.0.0-beta](#500-beta) | [5.0.0-beta.2](#500-beta2) | [5.0.0-beta.3](#500-beta3) | [5.0.0-beta.4](#500-beta4) | [5.0.0-beta.5](#500-beta5) | [5.0.0-beta.6](#500-beta6) | [5.0.0-beta.7](#500-beta7) | [5.0.0-beta.8](#500-beta8) | [5.0.0-beta.9](#500-beta9) | [5.0.0-beta.10](#500-beta10) | [5.0.0-beta.11](#500-beta11)
|
||||
- `5.0.x` Releases - [5.0.0](#500) - [5.0.1](#501) - [5.0.2](#502) - [5.0.3](#503)
|
||||
- `5.0.0` Betas - [5.0.0-beta](#500-beta) - [5.0.0-beta.2](#500-beta2) - [5.0.0-beta.3](#500-beta3) - [5.0.0-beta.4](#500-beta4) - [5.0.0-beta.5](#500-beta5) - [5.0.0-beta.6](#500-beta6) - [5.0.0-beta.7](#500-beta7) - [5.0.0-beta.8](#500-beta8) - [5.0.0-beta.9](#500-beta9) - [5.0.0-beta.10](#500-beta10) - [5.0.0-beta.11](#500-beta11)
|
||||
|
||||
#### 4.x Releases
|
||||
|
||||
- `4.14.x` Releases - [4.14.0](#4140)
|
||||
- `4.13.x` Releases - [4.13.0](#4130)
|
||||
- `4.12.x` Releases - [4.12.0](#4120) | [4.12.1](#4121) | [4.12.2](#4122)
|
||||
- `4.12.x` Releases - [4.12.0](#4120) - [4.12.1](#4121) - [4.12.2](#4122)
|
||||
- `4.11.x` Releases - [4.11.0](#4110)
|
||||
- `4.10.x` Releases - [4.10.0](#4100)
|
||||
- `4.9.x` Releases - [4.9.0](#490)
|
||||
- `4.8.x` Releases - [4.8.0](#480) | [4.8.1](#481)
|
||||
- `4.8.x` Releases - [4.8.0](#480) - [4.8.1](#481)
|
||||
- `4.7.x` Releases - [4.7.0](#470)
|
||||
- `4.6.x` Releases - [4.6.0](#460) | [4.6.1](#461) | [4.6.2](#462)
|
||||
- `4.6.x` Releases - [4.6.0](#460) - [4.6.1](#461) - [4.6.2](#462)
|
||||
- `4.5.x` Releases - [4.5.0](#450)
|
||||
- `4.4.x` Releases - [4.4.0](#440)
|
||||
- `4.3.x` Releases - [4.3.0](#430)
|
||||
- `4.2.x` Releases - [4.2.0](#420) | [4.2.1](#421)
|
||||
- `4.1.x` Releases - [4.1.0](#410) | [4.1.1](#411)
|
||||
- `4.0.x` Releases - [4.0.0](#400) | [4.0.1](#401)
|
||||
- `4.2.x` Releases - [4.2.0](#420) - [4.2.1](#421)
|
||||
- `4.1.x` Releases - [4.1.0](#410) - [4.1.1](#411)
|
||||
- `4.0.x` Releases - [4.0.0](#400) - [4.0.1](#401)
|
||||
|
||||
#### 3.x Releases
|
||||
|
||||
- `3.7.x` Releases - [3.7.0](#370)
|
||||
- `3.6.x` Releases - [3.6.0](#360) | [3.6.1](#361) | [3.6.2](#362)
|
||||
- `3.6.x` Releases - [3.6.0](#360) - [3.6.1](#361) - [3.6.2](#362)
|
||||
- `3.5.x` Releases - [3.5.0](#350)
|
||||
- `3.4.x` Releases - [3.4.0](#340)
|
||||
- `3.3.x` Releases - [3.3.0](#330) | [3.3.1](#331)
|
||||
- `3.3.x` Releases - [3.3.0](#330) - [3.3.1](#331)
|
||||
- `3.3.0` Betas - [3.3.0-beta1](#330-beta1)
|
||||
- `3.2.x` Releases - [3.2.0](#320)
|
||||
- `3.1.x` Releases - [3.1.0](#310)
|
||||
@@ -84,18 +92,18 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
- `2.9.x` Releases - [2.9.0](#290)
|
||||
- `2.8.x` Releases - [2.8.0](#280)
|
||||
- `2.7.x` Releases - [2.7.0](#270)
|
||||
- `2.6.x` Releases - [2.6.0](#260) | [2.6.1](#261)
|
||||
- `2.6.x` Releases - [2.6.0](#260) - [2.6.1](#261)
|
||||
- `2.5.x` Releases - [2.5.0](#250)
|
||||
- `2.4.x` Releases - [2.4.0](#240) | [2.4.1](#241) | [2.4.2](#242)
|
||||
- `2.3.x` Releases - [2.3.0](#230) | [2.3.1](#231)
|
||||
- `2.4.x` Releases - [2.4.0](#240) - [2.4.1](#241) - [2.4.2](#242)
|
||||
- `2.3.x` Releases - [2.3.0](#230) - [2.3.1](#231)
|
||||
- `2.2.x` Releases - [2.2.0](#220)
|
||||
- `2.1.x` Releases - [2.1.0](#210)
|
||||
- `2.0.x` Releases - [2.0.0](#200) | [2.0.1](#201) | [2.0.2](#202) | [2.0.3](#203)
|
||||
- `2.0.x` Releases - [2.0.0](#200) - [2.0.1](#201) - [2.0.2](#202) - [2.0.3](#203)
|
||||
|
||||
#### 1.x Releases
|
||||
|
||||
- `1.3.x` Releases - [1.3.0](#130)
|
||||
- `1.2.x` Releases - [1.2.0](#120) | [1.2.1](#121) | [1.2.2](#122)
|
||||
- `1.2.x` Releases - [1.2.0](#120) - [1.2.1](#121) - [1.2.2](#122)
|
||||
- `1.1.x` Releases - [1.1.0](#110)
|
||||
- `1.0.x` Releases - [1.0.0](#100)
|
||||
|
||||
@@ -105,6 +113,104 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 6.15.1
|
||||
|
||||
Released June 17, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.15.0...v6.15.1)
|
||||
|
||||
- **Fixed**: Fixed Xcode 15 warnings
|
||||
- **Fixed**: [#1391](https://github.com/groue/GRDB.swift/pull/1391) Fix upsert in FTS5-synchronized tables
|
||||
|
||||
|
||||
## 6.15.0
|
||||
|
||||
Released June 2, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.14.0...v6.15.0)
|
||||
|
||||
- **New**: [#1382](https://github.com/groue/GRDB.swift/pull/1382) Add `DerivableRequest.all()`
|
||||
- **New**: [#1384](https://github.com/groue/GRDB.swift/pull/1384) Allow ValueObservation to start from a truncated wal file
|
||||
- **Documentation Update**: The [ValueObservation Performance](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation#ValueObservation-Performance) documentation chapter explains how truncating WAL checkpoints impact `ValueObservation`.
|
||||
|
||||
|
||||
## 6.14.0
|
||||
|
||||
Released May 25, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.13.0...v6.14.0)
|
||||
|
||||
- **New**: [#1376](https://github.com/groue/GRDB.swift/pull/1376) Bitwise operations
|
||||
- **New**: [#1379](https://github.com/groue/GRDB.swift/pull/1379) Create indexes with a default name
|
||||
|
||||
|
||||
## 6.13.0
|
||||
|
||||
Released May 15, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.12.0...v6.13.0)
|
||||
|
||||
- **New**: [#1373](https://github.com/groue/GRDB.swift/pull/1373) Deprecate string literal arguments for `TableDefinition.check()`
|
||||
|
||||
|
||||
## 6.12.0
|
||||
|
||||
Released April 29, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.11.0...v6.12.0)
|
||||
|
||||
- **Fixed**: [#1364](https://github.com/groue/GRDB.swift/pull/1364) Fix a regression introduced with version 6.10.0, where starting multiple observations while performing writes could create a deadlock.
|
||||
- **New**: `FetchableRecordDecoder` is an object that decodes `Decodable` fetchable records from database rows. You may want to use this decoder when you want to use the `Decodable` initializer from `init(row: Row)`.
|
||||
|
||||
## 6.11.0
|
||||
|
||||
Released April 17, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.10.2...v6.11.0)
|
||||
|
||||
- **New**: [#1361](https://github.com/groue/GRDB.swift/pull/1361) `DatabaseMigrator.eraseDatabaseOnSchemaChange` ignores internal schema objects
|
||||
|
||||
## 6.10.2
|
||||
|
||||
Released April 10, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.10.1...v6.10.2)
|
||||
|
||||
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) guide has moved to DocC.
|
||||
- **Documentation Update**: The [Demo Applications](Documentation/DemoApps/) demonstrate how their `AppDatabase` "database manager" can provide a base database configuration.
|
||||
|
||||
## 6.10.1
|
||||
|
||||
Released April 1, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.10.0...v6.10.1)
|
||||
|
||||
- **Fixed**: [#1357](https://github.com/groue/GRDB.swift/pull/1357) `QueryInterfaceRequest.fetchCount` no longer executes invalid SQL queries for some requests.
|
||||
|
||||
## 6.10.0
|
||||
|
||||
Released March 20, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.9.2...v6.10.0)
|
||||
|
||||
- **New**: [#1350](https://github.com/groue/GRDB.swift/pull/1350) by [@groue](https://github.com/groue): DatabasePool won't close read-only connections if requested, and ValueObservation no longer opens a new database connection when it starts.
|
||||
|
||||
## 6.9.2
|
||||
|
||||
Released March 14, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.9.1...v6.9.2)
|
||||
|
||||
- **Fixed**: [#1349](https://github.com/groue/GRDB.swift/pull/1349) by [@JonLz](https://github.com/JonLz): Fix Migrations.md example so it compiles
|
||||
- **Fixed**: Avoid the risk for pathologically deep stack trace, or stack overflow, introduced by [#1348](https://github.com/groue/GRDB.swift/pull/1348).
|
||||
|
||||
## 6.9.1
|
||||
|
||||
Released March 12, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.9.0...v6.9.1)
|
||||
|
||||
- **Documentation Updates**: Moved more README chapters into DocC:
|
||||
- [`RowAdapter`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter)
|
||||
- [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/splittingrowadapters(columncounts:))
|
||||
|
||||
## 6.9.0
|
||||
|
||||
Released March 12, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.8.0...v6.9.0)
|
||||
|
||||
- **New**: [#1348](https://github.com/groue/GRDB.swift/pull/1348) by [@groue](https://github.com/groue): SQLite argument binding optimization
|
||||
- **New**: `FTS5.api(db)` returns a pointer to the `fts5_api` structure, useful for low-level [FTS5 customization](https://www.sqlite.org/fts5.html#extending_fts5).
|
||||
- **Documentation Updates**: Moved more README chapters into DocC, enhanced and extended DocC articles:
|
||||
- [Database Connections](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections)
|
||||
- [Prepared Statements](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statement)
|
||||
- [DatabaseValueConvertible](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasevalueconvertible)
|
||||
|
||||
## 6.8.0
|
||||
|
||||
Released February 24, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.7.0...v6.8.0)
|
||||
|
||||
- **New**: [#1338](https://github.com/groue/GRDB.swift/pull/1338) by [@groue](https://github.com/groue): TimestampedRecord sample code
|
||||
- **New**: `EncodableRecord.databaseChanges(modify:)` modifies a record and returns a dictionary of applied changes.
|
||||
- **Documentation Update**: The [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordtimestamps) article provides a sample `TimestampedRecord` protocol that application may adapt for their own use.
|
||||
|
||||
## 6.7.0
|
||||
|
||||
Released February 19, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.6.1...v6.7.0)
|
||||
|
||||
@@ -130,7 +130,7 @@ let request = Book.including(optional: Book.author)
|
||||
let bookInfos = BookInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
Before we dive in, please remember that associations can not generate all possible SQL queries that involve several tables. You may also *prefer* writing SQL, and this is just OK, because your SQL skills are welcome: see the [Joined Queries Support](../README.md#joined-queries-support) chapter.
|
||||
Before we dive in, please remember that associations can not generate all possible SQL queries that involve several tables. You may also *prefer* writing SQL, and this is just OK, because your SQL skills are welcome. The [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/splittingrowadapters(columncounts:)) method can help you consume the rows fetched from joined queries, as in `SELECT book.*, author.* FROM ...`.
|
||||
|
||||
|
||||
## Required Protocols
|
||||
@@ -2000,7 +2000,7 @@ Each association included in the request can feed a property of the decoded reco
|
||||
- [Decoding a Joined Request with a Decodable Record]
|
||||
- [Decoding a Joined Request with FetchableRecord]
|
||||
- [Debugging Request Decoding]
|
||||
- [Good Practices for Designing Record Types] - in this general guide about records, check out the "Compose Records" chapter.
|
||||
- [Recommended Practices for Designing Record Types] - in this general guide about records, check out the "Associations" chapter.
|
||||
|
||||
|
||||
## The Structure of a Joined Request
|
||||
@@ -2860,7 +2860,7 @@ extension DerivableRequest<Book> {
|
||||
}
|
||||
```
|
||||
|
||||
See [Good Practices for Designing Record Types] for more information.
|
||||
See [Recommended Practices for Designing Record Types] for more information.
|
||||
|
||||
|
||||
## Known Issues
|
||||
@@ -2996,10 +2996,10 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
[Isolation of Multiple Aggregates]: #isolation-of-multiple-aggregates
|
||||
[DerivableRequest Protocol]: #derivablerequest-protocol
|
||||
[Known Issues]: #known-issues
|
||||
[Row Adapters]: ../README.md#row-adapters
|
||||
[Row Adapters]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter
|
||||
[query interface requests]: ../README.md#requests
|
||||
[TableRecord]: ../README.md#tablerecord-protocol
|
||||
[Good Practices for Designing Record Types]: GoodPracticesForDesigningRecordTypes.md
|
||||
[Recommended Practices for Designing Record Types]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices
|
||||
[regular aggregating methods]: ../README.md#fetching-aggregated-values
|
||||
[Record class]: ../README.md#record-class
|
||||
[EncodableRecord]: ../README.md#persistablerecord-protocol
|
||||
|
||||
@@ -230,6 +230,7 @@
|
||||
567C3E0E2520B6DE0011F6E9 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = YES;
|
||||
LastSwiftUpdateCheck = 1250;
|
||||
LastUpgradeCheck = 1200;
|
||||
TargetAttributes = {
|
||||
@@ -583,7 +584,7 @@
|
||||
repositoryURL = "https://github.com/groue/GRDBQuery";
|
||||
requirement = {
|
||||
kind = upToNextMajorVersion;
|
||||
minimumVersion = 0.1.0;
|
||||
minimumVersion = 0.6.0;
|
||||
};
|
||||
};
|
||||
/* End XCRemoteSwiftPackageReference section */
|
||||
|
||||
+2
-2
@@ -5,8 +5,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/groue/GRDBQuery",
|
||||
"state" : {
|
||||
"revision" : "df514f2bd74548f94e082f3233022190e594fce4",
|
||||
"version" : "0.5.1"
|
||||
"revision" : "aefc0d7e7a64e841da33e1c8be7429da1bd9b5d6",
|
||||
"version" : "0.6.0"
|
||||
}
|
||||
}
|
||||
],
|
||||
|
||||
+7
@@ -61,6 +61,13 @@
|
||||
ReferencedContainer = "container:GRDBAsyncDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
<EnvironmentVariables>
|
||||
<EnvironmentVariable
|
||||
key = "SQL_TRACE"
|
||||
value = "1"
|
||||
isEnabled = "NO">
|
||||
</EnvironmentVariable>
|
||||
</EnvironmentVariables>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
|
||||
@@ -1,12 +1,29 @@
|
||||
import Foundation
|
||||
import GRDB
|
||||
import os.log
|
||||
|
||||
/// AppDatabase lets the application access the database.
|
||||
/// A database of players.
|
||||
///
|
||||
/// It applies the pratices recommended at
|
||||
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
/// You create an `AppDatabase` with a connection to an SQLite database
|
||||
/// (see <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>).
|
||||
///
|
||||
/// Create those connections with a configuration returned from
|
||||
/// `AppDatabase/makeConfiguration(_:)`.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create an in-memory AppDatabase
|
||||
/// let config = AppDatabase.makeConfiguration()
|
||||
/// let dbQueue = try DatabaseQueue(configuration: config)
|
||||
/// let appDatabase = try AppDatabase(dbQueue)
|
||||
/// ```
|
||||
struct AppDatabase {
|
||||
/// Creates an `AppDatabase`, and make sure the database schema is ready.
|
||||
/// Creates an `AppDatabase`, and makes sure the database schema
|
||||
/// is ready.
|
||||
///
|
||||
/// - important: Create the `DatabaseWriter` with a configuration
|
||||
/// returned by ``makeConfiguration(_:)``.
|
||||
init(_ dbWriter: any DatabaseWriter) throws {
|
||||
self.dbWriter = dbWriter
|
||||
try migrator.migrate(dbWriter)
|
||||
@@ -19,18 +36,67 @@ struct AppDatabase {
|
||||
///
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
|
||||
private let dbWriter: any DatabaseWriter
|
||||
}
|
||||
|
||||
// MARK: - Database Configuration
|
||||
|
||||
extension AppDatabase {
|
||||
private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
|
||||
|
||||
/// Returns a database configuration suited for `PlayerRepository`.
|
||||
///
|
||||
/// SQL statements are logged if the `SQL_TRACE` environment variable
|
||||
/// is set.
|
||||
///
|
||||
/// - parameter base: A base configuration.
|
||||
public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration {
|
||||
var config = base
|
||||
|
||||
// An opportunity to add required custom SQL functions or
|
||||
// collations, if needed:
|
||||
// config.prepareDatabase { db in
|
||||
// db.add(function: ...)
|
||||
// }
|
||||
|
||||
// Log SQL statements 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
|
||||
db.trace {
|
||||
// It's ok to log statements publicly. Sensitive
|
||||
// information (statement arguments) are not logged
|
||||
// unless config.publicStatementArguments is set
|
||||
// (see below).
|
||||
os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
// Protect sensitive information by enabling verbose debugging in
|
||||
// DEBUG builds only.
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/publicstatementarguments>
|
||||
config.publicStatementArguments = true
|
||||
#endif
|
||||
|
||||
return config
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Database Migrations
|
||||
|
||||
extension AppDatabase {
|
||||
/// The DatabaseMigrator that defines the database schema.
|
||||
///
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
|
||||
private var migrator: DatabaseMigrator {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
#if DEBUG
|
||||
#if DEBUG
|
||||
// Speed up development by nuking the database when migrations change
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
#endif
|
||||
#endif
|
||||
|
||||
migrator.registerMigration("createPlayer") { db in
|
||||
// Create a table
|
||||
@@ -52,6 +118,7 @@ struct AppDatabase {
|
||||
}
|
||||
|
||||
// MARK: - Database Access: Writes
|
||||
// The write methods execute invariant-preserving database transactions.
|
||||
|
||||
extension AppDatabase {
|
||||
/// A validation error that prevents some players from being saved into
|
||||
@@ -127,8 +194,8 @@ extension AppDatabase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static let uiTestPlayers = [
|
||||
|
||||
private static let uiTestPlayers = [
|
||||
Player(id: nil, name: "Arthur", score: 5),
|
||||
Player(id: nil, name: "Barbara", score: 6),
|
||||
Player(id: nil, name: "Craig", score: 8),
|
||||
@@ -137,7 +204,7 @@ extension AppDatabase {
|
||||
Player(id: nil, name: "Frederik", score: 2),
|
||||
Player(id: nil, name: "Gilbert", score: 7),
|
||||
Player(id: nil, name: "Henriette", score: 3)]
|
||||
|
||||
|
||||
func createPlayersForUITests() throws {
|
||||
try dbWriter.write { db in
|
||||
try AppDatabase.uiTestPlayers.forEach { player in
|
||||
|
||||
@@ -7,26 +7,31 @@ extension AppDatabase {
|
||||
|
||||
private static func makeShared() -> AppDatabase {
|
||||
do {
|
||||
// Pick a folder for storing the SQLite database, as well as
|
||||
// the various temporary files created during normal database
|
||||
// operations (https://sqlite.org/tempfiles.html).
|
||||
let fileManager = FileManager()
|
||||
let folderURL = try fileManager
|
||||
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
.appendingPathComponent("database", isDirectory: true)
|
||||
|
||||
// Apply recommendations from
|
||||
// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
|
||||
//
|
||||
// Create the "Application Support/Database" directory if needed
|
||||
let fileManager = FileManager.default
|
||||
let appSupportURL = try fileManager.url(
|
||||
for: .applicationSupportDirectory, in: .userDomainMask,
|
||||
appropriateFor: nil, create: true)
|
||||
let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true)
|
||||
|
||||
// Support for tests: delete the database if requested
|
||||
if CommandLine.arguments.contains("-reset") {
|
||||
try? fileManager.removeItem(at: folderURL)
|
||||
try? fileManager.removeItem(at: directoryURL)
|
||||
}
|
||||
|
||||
// Create the database folder if needed
|
||||
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
|
||||
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
|
||||
|
||||
// Connect to a database on disk
|
||||
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
|
||||
let dbURL = folderURL.appendingPathComponent("db.sqlite")
|
||||
let dbPool = try DatabasePool(path: dbURL.path)
|
||||
// Open or create the database
|
||||
let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
|
||||
NSLog("Database stored at \(databaseURL.path)")
|
||||
let dbPool = try DatabasePool(
|
||||
path: databaseURL.path,
|
||||
// Use default AppDatabase configuration
|
||||
configuration: AppDatabase.makeConfiguration())
|
||||
|
||||
// Create the AppDatabase
|
||||
let appDatabase = try AppDatabase(dbPool)
|
||||
@@ -59,7 +64,7 @@ extension AppDatabase {
|
||||
static func empty() -> AppDatabase {
|
||||
// Connect to an in-memory database
|
||||
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
|
||||
let dbQueue = try! DatabaseQueue()
|
||||
let dbQueue = try! DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
return try! AppDatabase(dbQueue)
|
||||
}
|
||||
|
||||
|
||||
@@ -69,8 +69,7 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
|
||||
/// Define some player requests used by the application.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
|
||||
extension DerivableRequest<Player> {
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
|
||||
@@ -5,7 +5,7 @@ import GRDB
|
||||
class AppDatabaseTests: XCTestCase {
|
||||
func test_database_schema() throws {
|
||||
// Given an empty database
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
|
||||
// When we instantiate an AppDatabase
|
||||
_ = try AppDatabase(dbQueue)
|
||||
@@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_savePlayer_inserts() async throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we save a new player
|
||||
@@ -35,7 +35,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_savePlayer_updates() async throws {
|
||||
// Given a players database that contains a player
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player = try await dbQueue.write { db in
|
||||
try Player(id: nil, name: "Arthur", score: 100).inserted(db)
|
||||
@@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_deletePlayers() async throws {
|
||||
// Given a players database that contains four players
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
let playerIds: [Int64] = try await dbQueue.write { db in
|
||||
_ = try Player(id: nil, name: "Arthur", score: 100).inserted(db)
|
||||
@@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_deleteAllPlayers() async throws {
|
||||
// Given a players database that contains players
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
try await dbQueue.write { db in
|
||||
_ = try Player(id: nil, name: "Arthur", score: 100).inserted(db)
|
||||
@@ -102,7 +102,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_refreshPlayers_populates_an_empty_database() async throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we refresh players
|
||||
@@ -115,7 +115,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we create random players
|
||||
@@ -127,7 +127,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
|
||||
// Given a players database that contains one player
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try dbQueue.write { db in
|
||||
|
||||
@@ -5,7 +5,7 @@ import GRDB
|
||||
class PlayerRequestTests: XCTestCase {
|
||||
func test_PlayerRequest_byName_fetches_well_ordered_players() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
@@ -24,7 +24,7 @@ class PlayerRequestTests: XCTestCase {
|
||||
|
||||
func test_PlayerRequest_byScore_fetches_well_ordered_players() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
|
||||
@@ -8,7 +8,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testInsert() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player
|
||||
@@ -23,7 +23,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testRoundtrip() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player and fetch the player with the same id
|
||||
@@ -42,7 +42,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByScore() throws {
|
||||
// Given a players database that contains players with distinct scores
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
@@ -64,7 +64,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByScoreSortsIdenticalScoresByName() throws {
|
||||
// Given a players database that contains players with common scores
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
@@ -86,7 +86,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByName() throws {
|
||||
// Given a players database that contains players with distinct names
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
|
||||
@@ -14,7 +14,7 @@ The topics covered in this demo are:
|
||||
- How to setup a database in an iOS app.
|
||||
- How to define a simple [Codable Record](../../../README.md#codable-records).
|
||||
- How to track database changes and animate a SwiftUI List with an async sequence built from [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation).
|
||||
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
|
||||
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
|
||||
- How to feed SwiftUI previews with a transient database.
|
||||
|
||||
**Files of interest:**
|
||||
|
||||
@@ -230,6 +230,7 @@
|
||||
567C3E0E2520B6DE0011F6E9 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = YES;
|
||||
LastSwiftUpdateCheck = 1250;
|
||||
LastUpgradeCheck = 1200;
|
||||
TargetAttributes = {
|
||||
@@ -581,7 +582,7 @@
|
||||
repositoryURL = "https://github.com/groue/GRDBQuery";
|
||||
requirement = {
|
||||
kind = upToNextMajorVersion;
|
||||
minimumVersion = 0.1.0;
|
||||
minimumVersion = 0.6.0;
|
||||
};
|
||||
};
|
||||
/* End XCRemoteSwiftPackageReference section */
|
||||
|
||||
+2
-2
@@ -5,8 +5,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/groue/GRDBQuery",
|
||||
"state" : {
|
||||
"revision" : "df514f2bd74548f94e082f3233022190e594fce4",
|
||||
"version" : "0.5.1"
|
||||
"revision" : "aefc0d7e7a64e841da33e1c8be7429da1bd9b5d6",
|
||||
"version" : "0.6.0"
|
||||
}
|
||||
}
|
||||
],
|
||||
|
||||
+7
@@ -61,6 +61,13 @@
|
||||
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
<EnvironmentVariables>
|
||||
<EnvironmentVariable
|
||||
key = "SQL_TRACE"
|
||||
value = "1"
|
||||
isEnabled = "NO">
|
||||
</EnvironmentVariable>
|
||||
</EnvironmentVariables>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
|
||||
@@ -1,13 +1,29 @@
|
||||
import Combine
|
||||
import Foundation
|
||||
import GRDB
|
||||
import os.log
|
||||
|
||||
/// AppDatabase lets the application access the database.
|
||||
/// A database of players.
|
||||
///
|
||||
/// It applies the pratices recommended at
|
||||
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
/// You create an `AppDatabase` with a connection to an SQLite database
|
||||
/// (see <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>).
|
||||
///
|
||||
/// Create those connections with a configuration returned from
|
||||
/// `AppDatabase/makeConfiguration(_:)`.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create an in-memory AppDatabase
|
||||
/// let config = AppDatabase.makeConfiguration()
|
||||
/// let dbQueue = try DatabaseQueue(configuration: config)
|
||||
/// let appDatabase = try AppDatabase(dbQueue)
|
||||
/// ```
|
||||
struct AppDatabase {
|
||||
/// Creates an `AppDatabase`, and make sure the database schema is ready.
|
||||
/// Creates an `AppDatabase`, and makes sure the database schema
|
||||
/// is ready.
|
||||
///
|
||||
/// - important: Create the `DatabaseWriter` with a configuration
|
||||
/// returned by ``makeConfiguration(_:)``.
|
||||
init(_ dbWriter: any DatabaseWriter) throws {
|
||||
self.dbWriter = dbWriter
|
||||
try migrator.migrate(dbWriter)
|
||||
@@ -20,18 +36,67 @@ struct AppDatabase {
|
||||
///
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
|
||||
private let dbWriter: any DatabaseWriter
|
||||
}
|
||||
|
||||
// MARK: - Database Configuration
|
||||
|
||||
extension AppDatabase {
|
||||
private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
|
||||
|
||||
/// Returns a database configuration suited for `PlayerRepository`.
|
||||
///
|
||||
/// SQL statements are logged if the `SQL_TRACE` environment variable
|
||||
/// is set.
|
||||
///
|
||||
/// - parameter base: A base configuration.
|
||||
public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration {
|
||||
var config = base
|
||||
|
||||
// An opportunity to add required custom SQL functions or
|
||||
// collations, if needed:
|
||||
// config.prepareDatabase { db in
|
||||
// db.add(function: ...)
|
||||
// }
|
||||
|
||||
// Log SQL statements 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
|
||||
db.trace {
|
||||
// It's ok to log statements publicly. Sensitive
|
||||
// information (statement arguments) are not logged
|
||||
// unless config.publicStatementArguments is set
|
||||
// (see below).
|
||||
os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
// Protect sensitive information by enabling verbose debugging in
|
||||
// DEBUG builds only.
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/publicstatementarguments>
|
||||
config.publicStatementArguments = true
|
||||
#endif
|
||||
|
||||
return config
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Database Migrations
|
||||
|
||||
extension AppDatabase {
|
||||
/// The DatabaseMigrator that defines the database schema.
|
||||
///
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
|
||||
private var migrator: DatabaseMigrator {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
#if DEBUG
|
||||
#if DEBUG
|
||||
// Speed up development by nuking the database when migrations change
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
#endif
|
||||
#endif
|
||||
|
||||
migrator.registerMigration("createPlayer") { db in
|
||||
// Create a table
|
||||
@@ -53,6 +118,7 @@ struct AppDatabase {
|
||||
}
|
||||
|
||||
// MARK: - Database Access: Writes
|
||||
// The write methods execute invariant-preserving database transactions.
|
||||
|
||||
extension AppDatabase {
|
||||
/// A validation error that prevents some players from being saved into
|
||||
@@ -128,8 +194,8 @@ extension AppDatabase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static let uiTestPlayers = [
|
||||
|
||||
private static let uiTestPlayers = [
|
||||
Player(id: nil, name: "Arthur", score: 5),
|
||||
Player(id: nil, name: "Barbara", score: 6),
|
||||
Player(id: nil, name: "Craig", score: 8),
|
||||
@@ -138,7 +204,7 @@ extension AppDatabase {
|
||||
Player(id: nil, name: "Frederik", score: 2),
|
||||
Player(id: nil, name: "Gilbert", score: 7),
|
||||
Player(id: nil, name: "Henriette", score: 3)]
|
||||
|
||||
|
||||
func createPlayersForUITests() throws {
|
||||
try dbWriter.write { db in
|
||||
try AppDatabase.uiTestPlayers.forEach { player in
|
||||
|
||||
@@ -7,26 +7,31 @@ extension AppDatabase {
|
||||
|
||||
private static func makeShared() -> AppDatabase {
|
||||
do {
|
||||
// Pick a folder for storing the SQLite database, as well as
|
||||
// the various temporary files created during normal database
|
||||
// operations (https://sqlite.org/tempfiles.html).
|
||||
let fileManager = FileManager()
|
||||
let folderURL = try fileManager
|
||||
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
.appendingPathComponent("database", isDirectory: true)
|
||||
|
||||
// Apply recommendations from
|
||||
// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
|
||||
//
|
||||
// Create the "Application Support/Database" directory if needed
|
||||
let fileManager = FileManager.default
|
||||
let appSupportURL = try fileManager.url(
|
||||
for: .applicationSupportDirectory, in: .userDomainMask,
|
||||
appropriateFor: nil, create: true)
|
||||
let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true)
|
||||
|
||||
// Support for tests: delete the database if requested
|
||||
if CommandLine.arguments.contains("-reset") {
|
||||
try? fileManager.removeItem(at: folderURL)
|
||||
try? fileManager.removeItem(at: directoryURL)
|
||||
}
|
||||
|
||||
// Create the database folder if needed
|
||||
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
|
||||
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
|
||||
|
||||
// Connect to a database on disk
|
||||
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
|
||||
let dbURL = folderURL.appendingPathComponent("db.sqlite")
|
||||
let dbPool = try DatabasePool(path: dbURL.path)
|
||||
// Open or create the database
|
||||
let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
|
||||
NSLog("Database stored at \(databaseURL.path)")
|
||||
let dbPool = try DatabasePool(
|
||||
path: databaseURL.path,
|
||||
// Use default AppDatabase configuration
|
||||
configuration: AppDatabase.makeConfiguration())
|
||||
|
||||
// Create the AppDatabase
|
||||
let appDatabase = try AppDatabase(dbPool)
|
||||
@@ -59,7 +64,7 @@ extension AppDatabase {
|
||||
static func empty() -> AppDatabase {
|
||||
// Connect to an in-memory database
|
||||
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
|
||||
let dbQueue = try! DatabaseQueue()
|
||||
let dbQueue = try! DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
return try! AppDatabase(dbQueue)
|
||||
}
|
||||
|
||||
|
||||
@@ -69,8 +69,7 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
|
||||
/// Define some player requests used by the application.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
|
||||
extension DerivableRequest<Player> {
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
|
||||
@@ -5,7 +5,7 @@ import GRDB
|
||||
class AppDatabaseTests: XCTestCase {
|
||||
func test_database_schema() throws {
|
||||
// Given an empty database
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
|
||||
// When we instantiate an AppDatabase
|
||||
_ = try AppDatabase(dbQueue)
|
||||
@@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_savePlayer_inserts() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we save a new player
|
||||
@@ -34,7 +34,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_savePlayer_updates() throws {
|
||||
// Given a players database that contains a player
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try dbQueue.write { db in
|
||||
@@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_deletePlayers() throws {
|
||||
// Given a players database that contains four players
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 200)
|
||||
@@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_deleteAllPlayers() throws {
|
||||
// Given a players database that contains players
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 200)
|
||||
@@ -105,7 +105,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_refreshPlayers_populates_an_empty_database() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we refresh players
|
||||
@@ -117,7 +117,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we create random players
|
||||
@@ -129,7 +129,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
|
||||
// Given a players database that contains one player
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try dbQueue.write { db in
|
||||
|
||||
+2
-2
@@ -5,7 +5,7 @@ import GRDB
|
||||
class PlayerRequestTests: XCTestCase {
|
||||
func test_PlayerRequest_byName_fetches_well_ordered_players() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
@@ -24,7 +24,7 @@ class PlayerRequestTests: XCTestCase {
|
||||
|
||||
func test_PlayerRequest_byScore_fetches_well_ordered_players() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
|
||||
@@ -8,7 +8,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testInsert() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player
|
||||
@@ -23,7 +23,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testRoundtrip() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player and fetch the player with the same id
|
||||
@@ -42,7 +42,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByScore() throws {
|
||||
// Given a players database that contains players with distinct scores
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
@@ -64,7 +64,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByScoreSortsIdenticalScoresByName() throws {
|
||||
// Given a players database that contains players with common scores
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
@@ -86,7 +86,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByName() throws {
|
||||
// Given a players database that contains players with distinct names
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
|
||||
@@ -14,7 +14,7 @@ The topics covered in this demo are:
|
||||
- How to setup a database in an iOS app.
|
||||
- How to define a simple [Codable Record](../../../README.md#codable-records).
|
||||
- How to track database changes and animate a SwiftUI List with [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) Combine publishers.
|
||||
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
|
||||
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
|
||||
- How to feed SwiftUI previews with a transient database.
|
||||
|
||||
**Files of interest:**
|
||||
|
||||
+7
@@ -61,6 +61,13 @@
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
<EnvironmentVariables>
|
||||
<EnvironmentVariable
|
||||
key = "SQL_TRACE"
|
||||
value = "1"
|
||||
isEnabled = "NO">
|
||||
</EnvironmentVariable>
|
||||
</EnvironmentVariables>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
|
||||
@@ -1,11 +1,28 @@
|
||||
import GRDB
|
||||
import os.log
|
||||
|
||||
/// AppDatabase lets the application access the database.
|
||||
/// `AppDatabase` lets the application access the database.
|
||||
///
|
||||
/// It applies the pratices recommended at
|
||||
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
final class AppDatabase {
|
||||
/// Creates an `AppDatabase`, and make sure the database schema is ready.
|
||||
/// You create an `AppDatabase` with a connection to an SQLite database
|
||||
/// (see <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>).
|
||||
///
|
||||
/// Create those connections with a configuration returned from
|
||||
/// `AppDatabase/makeConfiguration(_:)`.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create an in-memory AppDatabase
|
||||
/// let config = AppDatabase.makeConfiguration()
|
||||
/// let dbQueue = try DatabaseQueue(configuration: config)
|
||||
/// let appDatabase = try AppDatabase(dbQueue)
|
||||
/// ```
|
||||
struct AppDatabase {
|
||||
/// Creates an `AppDatabase`, and makes sure the database schema
|
||||
/// is ready.
|
||||
///
|
||||
/// - important: Create the `DatabaseWriter` with a configuration
|
||||
/// returned by ``makeConfiguration(_:)``.
|
||||
init(_ dbWriter: any DatabaseWriter) throws {
|
||||
self.dbWriter = dbWriter
|
||||
try migrator.migrate(dbWriter)
|
||||
@@ -18,18 +35,67 @@ final class AppDatabase {
|
||||
///
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
|
||||
private let dbWriter: any DatabaseWriter
|
||||
}
|
||||
|
||||
// MARK: - Database Configuration
|
||||
|
||||
extension AppDatabase {
|
||||
private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
|
||||
|
||||
/// Returns a database configuration suited for `PlayerRepository`.
|
||||
///
|
||||
/// SQL statements are logged if the `SQL_TRACE` environment variable
|
||||
/// is set.
|
||||
///
|
||||
/// - parameter base: A base configuration.
|
||||
public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration {
|
||||
var config = base
|
||||
|
||||
// An opportunity to add required custom SQL functions or
|
||||
// collations, if needed:
|
||||
// config.prepareDatabase { db in
|
||||
// db.add(function: ...)
|
||||
// }
|
||||
|
||||
// Log SQL statements 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
|
||||
db.trace {
|
||||
// It's ok to log statements publicly. Sensitive
|
||||
// information (statement arguments) are not logged
|
||||
// unless config.publicStatementArguments is set
|
||||
// (see below).
|
||||
os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
// Protect sensitive information by enabling verbose debugging in
|
||||
// DEBUG builds only.
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/publicstatementarguments>
|
||||
config.publicStatementArguments = true
|
||||
#endif
|
||||
|
||||
return config
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Database Migrations
|
||||
|
||||
extension AppDatabase {
|
||||
/// The DatabaseMigrator that defines the database schema.
|
||||
///
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
|
||||
private var migrator: DatabaseMigrator {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
#if DEBUG
|
||||
#if DEBUG
|
||||
// Speed up development by nuking the database when migrations change
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
#endif
|
||||
#endif
|
||||
|
||||
migrator.registerMigration("createPlayer") { db in
|
||||
// Create a table
|
||||
@@ -51,6 +117,7 @@ final class AppDatabase {
|
||||
}
|
||||
|
||||
// MARK: - Database Access: Writes
|
||||
// The write methods execute invariant-preserving database transactions.
|
||||
|
||||
extension AppDatabase {
|
||||
/// Saves (inserts or updates) a player. When the method returns, the
|
||||
|
||||
@@ -7,19 +7,24 @@ extension AppDatabase {
|
||||
|
||||
private static func makeShared() -> AppDatabase {
|
||||
do {
|
||||
// Create a folder for storing the SQLite database, as well as
|
||||
// the various temporary files created during normal database
|
||||
// operations (https://sqlite.org/tempfiles.html).
|
||||
let fileManager = FileManager()
|
||||
let folderURL = try fileManager
|
||||
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
.appendingPathComponent("database", isDirectory: true)
|
||||
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
|
||||
// Apply recommendations from
|
||||
// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
|
||||
//
|
||||
// Create the "Application Support/Database" directory if needed
|
||||
let fileManager = FileManager.default
|
||||
let appSupportURL = try fileManager.url(
|
||||
for: .applicationSupportDirectory, in: .userDomainMask,
|
||||
appropriateFor: nil, create: true)
|
||||
let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true)
|
||||
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
|
||||
|
||||
// Connect to a database on disk
|
||||
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
|
||||
let dbURL = folderURL.appendingPathComponent("db.sqlite")
|
||||
let dbPool = try DatabasePool(path: dbURL.path)
|
||||
// Open or create the database
|
||||
let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
|
||||
NSLog("Database stored at \(databaseURL.path)")
|
||||
let dbPool = try DatabasePool(
|
||||
path: databaseURL.path,
|
||||
// Use default AppDatabase configuration
|
||||
configuration: AppDatabase.makeConfiguration())
|
||||
|
||||
// Create the AppDatabase
|
||||
let appDatabase = try AppDatabase(dbPool)
|
||||
|
||||
@@ -68,8 +68,7 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
|
||||
/// Define some player requests used by the application.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
|
||||
extension DerivableRequest<Player> {
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
|
||||
@@ -5,7 +5,7 @@ import GRDB
|
||||
class AppDatabaseTests: XCTestCase {
|
||||
func test_database_schema() throws {
|
||||
// Given an empty database
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
|
||||
// When we instantiate an AppDatabase
|
||||
_ = try AppDatabase(dbQueue)
|
||||
@@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_savePlayer_inserts() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we save a new player
|
||||
@@ -34,7 +34,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_savePlayer_updates() throws {
|
||||
// Given a players database that contains a player
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try dbQueue.write { db in
|
||||
@@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_deletePlayers() throws {
|
||||
// Given a players database that contains four players
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 200)
|
||||
@@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_deleteAllPlayers() throws {
|
||||
// Given a players database that contains players
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 200)
|
||||
@@ -105,7 +105,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_refreshPlayers_populates_an_empty_database() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we refresh players
|
||||
@@ -117,7 +117,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we create random players
|
||||
@@ -129,7 +129,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
|
||||
// Given a players database that contains one player
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try dbQueue.write { db in
|
||||
|
||||
@@ -8,7 +8,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testInsert() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player
|
||||
@@ -23,7 +23,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testRoundtrip() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player and fetch the player with the same id
|
||||
@@ -42,7 +42,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByScore() throws {
|
||||
// Given a players database that contains players with distinct scores
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
@@ -64,7 +64,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByScoreSortsIdenticalScoresByName() throws {
|
||||
// Given a players database that contains players with common scores
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
@@ -86,7 +86,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByName() throws {
|
||||
// Given a players database that contains players with distinct names
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
|
||||
@@ -14,7 +14,7 @@ The topics covered in this demo are:
|
||||
- How to setup a database in an iOS app.
|
||||
- How to define a simple [Codable Record](../../../README.md#codable-records).
|
||||
- How to track database changes and animate a table view with [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation).
|
||||
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
|
||||
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
|
||||
|
||||
**Files of interest:**
|
||||
|
||||
|
||||
@@ -28,7 +28,6 @@ let books = try Book.fetchAll(db,
|
||||
```
|
||||
|
||||
- **[Choosing the Full-Text Engine](#choosing-the-full-text-engine)**
|
||||
- **[Enabling FTS5 Support](#enabling-fts5-support)**
|
||||
- **Create Full-Text Virtual Tables**: [FTS3/4](#create-fts3-and-fts4-virtual-tables), [FTS5](#create-fts5-virtual-tables)
|
||||
- **Choosing a Tokenizer**: [FTS3/4](#fts3-and-fts4-tokenizers), [FTS5](#fts5-tokenizers)
|
||||
- **Tokenization**: [FTS3/4](#fts3-and-fts4-tokenization), [FTS5](#fts5-tokenization)
|
||||
@@ -83,8 +82,6 @@ Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this do
|
||||
|
||||
- **The location of the indexed text in your database schema.** Only FTS4 and FTS5 support "contentless" and "external content" tables.
|
||||
|
||||
- **The SQLite library integrated in your application.** The version of SQLite that ships with iOS, macOS, tvOS and watchOS supports FTS3 and FTS4 out of the box, but not always FTS5. To use FTS5, see [Enabling FTS5 Support](#enabling-fts5-support).
|
||||
|
||||
- See [FST3 vs. FTS4](https://www.sqlite.org/fts3.html#differences_between_fts3_and_fts4) and [FTS5 vs. FTS3/4](https://www.sqlite.org/fts5.html#appendix_a) for more differences.
|
||||
|
||||
> **Note**: In case you were still wondering, it is recommended to read the SQLite documentation: [FTS3 & FTS4](https://www.sqlite.org/fts3.html) and [FTS5](https://www.sqlite.org/fts5.html).
|
||||
@@ -323,40 +320,6 @@ let documents = try Document.filter(Column("content").match(pattern)).fetchAll(d
|
||||
```
|
||||
|
||||
|
||||
## Enabling FTS5 Support
|
||||
|
||||
When the FTS3 and FTS4 full-text engines don't suit your needs, you may want to use FTS5. See [Choosing the Full-Text Engine](#choosing-the-full-text-engine) to help you make a decision.
|
||||
|
||||
The version of SQLite that ships with iOS, macOS, tvOS and watchOS does not always support the FTS5 engine. To enable FTS5 support, you'll need to install GRDB with one of those installation techniques:
|
||||
|
||||
1. Use the GRDB.swift CocoaPod with a custom compilation option, as below. It uses the system SQLite, which is compiled with FTS5 support, but only on iOS 11.4+ / macOS 10.13+ / tvOS 11.4+ / watchOS 4.3+:
|
||||
|
||||
```ruby
|
||||
pod 'GRDB.swift'
|
||||
platform :ios, '11.4' # or above
|
||||
|
||||
post_install do |installer|
|
||||
installer.pods_project.targets.select { |target| target.name == "GRDB.swift" }.each do |target|
|
||||
target.build_configurations.each do |config|
|
||||
config.build_settings['OTHER_SWIFT_FLAGS'] = "$(inherited) -D SQLITE_ENABLE_FTS5"
|
||||
end
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
> **Warning**: make sure you use the right platform version! You will get runtime errors on devices with a lower version.
|
||||
|
||||
> **Note**: there used to be a GRDBPlus CocoaPod with pre-enabled FTS5 support. This CocoaPod is deprecated: please switch to the above technique.
|
||||
|
||||
2. Use the GRDB.swift/SQLCipher CocoaPod subspec (see [encryption](../README.md#encryption)):
|
||||
|
||||
```ruby
|
||||
pod 'GRDB.swift/SQLCipher'
|
||||
```
|
||||
|
||||
3. Use a [custom SQLite build] and activate the `SQLITE_ENABLE_FTS5` compilation option.
|
||||
|
||||
|
||||
## Create FTS5 Virtual Tables
|
||||
|
||||
**FTS5 full-text tables store and index textual content.**
|
||||
|
||||
@@ -1,836 +1,4 @@
|
||||
Good Practices for Designing Record Types
|
||||
=========================================
|
||||
|
||||
This guide aims at helping you leverage the best of GRDB [records] and [associations].
|
||||
|
||||
Since GRDB sits right between low-level libraries like SQLite itself or [FMDB], and high-level ORM like [Core Data] or [Realm], you may face questions when designing the model layer of your application.
|
||||
|
||||
To support this guide, we'll design a simple library application that lets the user crawl through books and their authors.
|
||||
|
||||
- [Trust SQLite More Than Yourself]
|
||||
- [Persistable Record Types are Responsible for Their Tables]
|
||||
- [Record Types Hide Intimate Database Details]
|
||||
- [Singleton Records]
|
||||
- [Define Record Requests]
|
||||
- [Compose Records]
|
||||
- [How to Design Database Managers]
|
||||
- [Observe the Database and Refetch when Needed]
|
||||
|
||||
|
||||
## Trust SQLite More Than Yourself
|
||||
|
||||
It is important to put things in the right order. An SQLite database stored on one of your user's device is more important than the Swift code that accesses it. When a user installs a new version of your application, all the code may change, but the database remains the same.
|
||||
|
||||
This is why we recommend defining a **robust database schema** even before playing with record types.
|
||||
|
||||
SQLite is a battle-tested database. Even if you don't know it well, and aren't familiar with the SQL language, you are able to take profit from its solid foundation. It is very difficult to corrupt an SQLite database file. And it can make sure that only valid information is persisted on disk.
|
||||
|
||||
This is important because we developers write bugs, and some of them will ship in the wild, affecting the users of our applications. But SQLite will prevent many of those bugs from corrupting our precious users' data.
|
||||
|
||||
For example, if we were to define a [migration] that sets up our library database, made of books and their authors, we could write:
|
||||
|
||||
```swift
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
migrator.registerMigration("createLibrary") { db in
|
||||
try db.create(table: "author") { t in // (1)
|
||||
t.autoIncrementedPrimaryKey("id") // (2)
|
||||
t.column("name", .text).notNull() // (3)
|
||||
t.column("country", .text) // (4)
|
||||
}
|
||||
|
||||
try db.create(table: "book") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("title", .text).notNull() // (5)
|
||||
t.column("authorId", .integer) // (6)
|
||||
.notNull() // (7)
|
||||
.indexed() // (8)
|
||||
.references("author", onDelete: .cascade) // (9)
|
||||
}
|
||||
}
|
||||
|
||||
try migrator.migrate(dbQueue)
|
||||
```
|
||||
|
||||
1. Our database table names follow the [recommended convention]: they are English, singular, and camelCased. They look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`.
|
||||
2. Each author has a unique id.
|
||||
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.
|
||||
7. The `book.authorId` column is not null so that SQLite guarantees that all books have an author.
|
||||
8. The `book.authorId` column is indexed in order to ease the selection of an author's books.
|
||||
9. We define a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book can refer to a missing author. On top of that, the `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
|
||||
|
||||
Thanks to this database schema, you can be confident that no matter how wrong our application goes, it will always process *consistent data*. Even after a hard crash, application will always find the author of any book, all books will have a non-nil title, etc.
|
||||
|
||||
> :bulb: **Tip**: Don't look at your local SQLite database as you look at the JSON you load from a remote server. You can't control the JSON, its format and content: your application must defend itself against wacky servers. But you can control the database. Put the database on your side, make it trustable. Learn about relational databases, and how they can help you guarantee the quality of your application data. Put as much energy as you can in the proper definition of your database schema.
|
||||
>
|
||||
> :bulb: **Tip**: Plan early for future versions of your application, and use [migrations].
|
||||
>
|
||||
> :bulb: **Tip**: In the definition of your migrations, define tables and their columns with **strings**:
|
||||
>
|
||||
> ```swift
|
||||
> migrator.registerMigration("createLibrary") { db in
|
||||
> // RECOMMENDED
|
||||
> try db.create(table: "author") { t in
|
||||
> t.autoIncrementedPrimaryKey("id")
|
||||
> ...
|
||||
> }
|
||||
>
|
||||
> // NOT RECOMMENDED
|
||||
> try db.create(table: Author.databaseTableName) { t in
|
||||
> t.autoIncrementedPrimaryKey(Author.Columns.id.name)
|
||||
> ...
|
||||
> }
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> By using strings, you make sure that you will not have to change the Swift code of your migrations in the future. Even if author columns eventually change. Even if the Author type eventually gets replaced with another type. Even when your startup eventually pivots and starts selling pet food. A good migration that never changes is easy to test once and for good. A good migration that never changes will run smoothly on all devices in the wild, even if a user upgrades straight from version 1.0 to version 5.0 of your application.
|
||||
>
|
||||
> So make sure that migrations don't use application types and values: migrations should talk to the database, only to the database, and use the database language: **strings**.
|
||||
|
||||
|
||||
## Persistable Record Types are Responsible for Their Tables
|
||||
|
||||
Define one record type per database table, and make it adopt a [PersistableRecord] protocol.
|
||||
|
||||
In this sample code, we'll use Codable structs, but there are [other ways](../README.md#examples-of-record-definitions) to define records.
|
||||
|
||||
```swift
|
||||
struct Author: Codable, Identifiable {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
var country: String?
|
||||
}
|
||||
|
||||
struct Book: Codable, Identifiable {
|
||||
var id: Int64?
|
||||
var authorId: Int64
|
||||
var title: String
|
||||
}
|
||||
```
|
||||
|
||||
We add database powers to our types with [record protocols]. Since our records use auto-incremented ids, we provide an implementation of the `didInsert` method:
|
||||
|
||||
```swift
|
||||
// Add Database access
|
||||
|
||||
extension Author: FetchableRecord, MutablePersistableRecord {
|
||||
// Update auto-incremented id upon successful insertion
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
extension Book: FetchableRecord, MutablePersistableRecord {
|
||||
// Update auto-incremented id upon successful insertion
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
That's it. The `Author` type can read and write in the `author` database table. `Book` as well, in `book`.
|
||||
|
||||
> :bulb: **Tip**: When a column of a database table can't be NULL, store it in a non-optional property of your record type. On the other side, when the database may contain NULL, define an optional property.
|
||||
>
|
||||
> :bulb: **Tip**: When a database table uses an auto-incremented identifier, make the `id` property optional (so that you can instantiate a record before it gets inserted and gains an id), and implement the `didInsert(_:)` method:
|
||||
>
|
||||
> ```swift
|
||||
> try dbQueue.write { db in
|
||||
> var author = Author(id: nil, name: "Hermann Melville", country: "United States")
|
||||
> try author.insert(db)
|
||||
> print(author.id!) // Guaranteed non-nil id
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> :bulb: **Tip**: When the database table has a single-column primary key, have your record type adopt the standard [Identifiable] protocol. This allows GRDB to define type-safe id-related methods:
|
||||
>
|
||||
> ```swift
|
||||
> let authorID: Int64 = ...
|
||||
> let author: Author? = try dbQueue.read { db in
|
||||
> try Author.fetchOne(db, id: authorID)
|
||||
> }
|
||||
> ```
|
||||
|
||||
Now that `Author` and `Book` can read and write in their own database tables, they are responsible for it. Make sure each record type deals with one database table, and only one database table!
|
||||
|
||||
|
||||
## Record Types Hide Intimate Database Details
|
||||
|
||||
The application uses `Book` and `Author` as regular structs, using their properties. Each of those properties matches a column in the database (`Book.title`, `Author.id`), and is defined with a Swift type that is natively supported by SQLite (`String`, `Int`, etc.)
|
||||
|
||||
Sometimes, it happens that raw database column names and types are not a very good fit for the application.
|
||||
|
||||
Let's look at three examples:
|
||||
|
||||
1. Authors write books, and more specifically novels, poems, essays, or theatre plays. Let's add a `kind` column in the database. For easy debugging of the database contents, a book kind is represented as a string ("novel", "essay", etc.):
|
||||
|
||||
```swift
|
||||
try db.create(table: "book") { t in
|
||||
...
|
||||
t.column("kind", .text).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
In Swift, it is not a good practice to use `String` for the type of the `kind` property. We want an enum instead:
|
||||
|
||||
```swift
|
||||
struct Book: Codable {
|
||||
enum Kind: String, Codable {
|
||||
case novel, poems, essay, play
|
||||
}
|
||||
var id: Int64?
|
||||
var authorId: Int64
|
||||
var title: String
|
||||
var kind: Kind
|
||||
}
|
||||
```
|
||||
|
||||
In order to make it possible to use `Book.Kind` in book requests (see [Define Record Requests] below), we add this conformance:
|
||||
|
||||
```swift
|
||||
extension Book.Kind: DatabaseValueConvertible { }
|
||||
```
|
||||
|
||||
> :bulb: Records can pick the best suited [Value] type for their column properties (Bool, Int, String, Date, etc.) Thanks to its enum property, the `Book` record prevents unknown book kinds from entering the database.
|
||||
|
||||
2. GPS coordinates are usually stored in two distinct `latitude` and `longitude` columns. But the standard way to deal with such coordinate is a single `CLLocationCoordinate2D` struct.
|
||||
|
||||
When this happens, keep column properties private, and provide sensible accessors instead:
|
||||
|
||||
```swift
|
||||
struct Place: Codable {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
private var latitude: CLLocationDegrees
|
||||
private var longitude: CLLocationDegrees
|
||||
|
||||
var coordinate: CLLocationCoordinate2D {
|
||||
get {
|
||||
CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
|
||||
}
|
||||
set {
|
||||
latitude = newValue.latitude
|
||||
longitude = newValue.longitude
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: Private properties make it possible to hide raw columns from the rest of the application.
|
||||
|
||||
3. The record below exposes a `price: Decimal` property ($12.00), backed by an integer column that stores a quantity of cents (1200). An integer column is preferred because it allows SQLite to compute exact sums of prices.
|
||||
|
||||
```swift
|
||||
struct Product: Codable {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
private var priceCents: Int
|
||||
|
||||
var price: Decimal {
|
||||
get { Decimal(priceCents) / 100 }
|
||||
set { priceCents = NSDecimalNumber(decimal: newValue * 100).intValue }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: Private properties allow records to choose both their best database representation, and at the same time, their best Swift interface.
|
||||
|
||||
**Generally speaking**, record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. When needed, you can even [validate values](../README.md#persistence-callbacks) before they enter the database.
|
||||
|
||||
|
||||
## Singleton Records
|
||||
|
||||
**Singleton Records** are records that store configuration values, user preferences, and generally some global application state. They are backed by a database table that contains a single row.
|
||||
|
||||
The recommended setup for such records is described in the [Single-Row Tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables) guide. Go check it, and come back when you're done!
|
||||
|
||||
|
||||
## Define Record Requests
|
||||
|
||||
Now that we have record types that are able to read and write in the database, we'd like to put them to good use.
|
||||
|
||||
> :bulb: **Tip**: Define an enumeration of columns that you will use in order to filter, sort, etc.
|
||||
|
||||
When your record type is a [Codable Record], derive columns from the [CodingKeys] enum:
|
||||
|
||||
```swift
|
||||
// For a codable record
|
||||
extension Author {
|
||||
// Define database columns from CodingKeys
|
||||
enum Columns {
|
||||
static let id = Column(CodingKeys.id)
|
||||
static let name = Column(CodingKeys.name)
|
||||
static let country = Column(CodingKeys.country)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Otherwise, declare a plain `String` enum that conforms to the `ColumnExpression` protocol:
|
||||
|
||||
```swift
|
||||
// For a non-codable record
|
||||
extension Author {
|
||||
// Define database columns as an enum
|
||||
enum Columns: String, ColumnExpression {
|
||||
case id, name, country
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Those columns let you define requests:
|
||||
|
||||
```swift
|
||||
try dbQueue.read { db in
|
||||
// Order authors by name, in a localized case-insensitive fashion
|
||||
let sortedAuthors: [Author] = try Author.all()
|
||||
.order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
.fetchAll(db)
|
||||
|
||||
// French authors
|
||||
let frenchAuthors: [Author] = try Author.all()
|
||||
.filter(Author.Columns.country == "France")
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: **Tip**: Define commonly used requests in a constrained extension of the `DerivableRequest` protocol.
|
||||
|
||||
When you find yourself build similar requests over and over in your application, you may want to define a reusable and composable request vocabulary. This will avoid repetition in your app, ease refactoring, and enable [testability](DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift).
|
||||
|
||||
To do so, extend the `DerivableRequest` protocol. It generally lets you filter, sort, leverage associations (we'll talk about associations in the [Compose Records] chapter below), etc:
|
||||
|
||||
```swift
|
||||
// Author requests
|
||||
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))
|
||||
}
|
||||
|
||||
/// Filters authors from a country
|
||||
func filter(country: String) -> Self {
|
||||
filter(Author.Columns.country == country)
|
||||
}
|
||||
|
||||
/// Filters authors with at least one book
|
||||
func havingBooks() -> Self {
|
||||
having(Author.books.isEmpty == false)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Those methods encapsulate intimate database details, and allow you to compose database requests in a fluent and legible style:
|
||||
|
||||
```swift
|
||||
try dbQueue.read { db in
|
||||
let sortedAuthors: [Author] = try Author.all()
|
||||
.orderByName()
|
||||
.fetchAll(db)
|
||||
|
||||
let frenchAuthors: [Author] = try Author.all()
|
||||
.filter(country: "France")
|
||||
.fetchAll(db)
|
||||
|
||||
let sortedSpanishAuthorsHavingBooks: [Author] = try Author.all()
|
||||
.filter(country: "Spain")
|
||||
.havingBooks()
|
||||
.orderByName()
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
Because they are defined in an extension of the `DerivableRequest` protocol, our customized methods can decorate both requests and associations. See how the implementation of `filter(authorCountry:)` for books, below, uses the `filter(country:)` for authors:
|
||||
|
||||
```swift
|
||||
// Book requests
|
||||
extension DerivableRequest<Book> {
|
||||
/// Filters books by kind
|
||||
func filter(kind: Book.Kind) -> Self {
|
||||
filter(Book.Columns.kind == kind)
|
||||
}
|
||||
|
||||
/// Filters books from a country
|
||||
func filter(authorCountry: String) -> Self {
|
||||
// Books do not have any country column. But their author has one.
|
||||
// A book is from a country if it can be joined to an author from this country:
|
||||
joining(required: Book.author.filter(country: authorCountry))
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.read { db in
|
||||
let italianNovels: [Book] = try Book.all()
|
||||
.filter(kind: .novel)
|
||||
.filter(authorCountry: "Italy")
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
Extensions to the `DerivableRequest` protocol can not change the type of requests. This has to be expressed in an extension to `QueryInterfaceRequest`. For example:
|
||||
|
||||
```swift
|
||||
// Author requests
|
||||
extension QueryInterfaceRequest<Author> {
|
||||
// Selects author ids
|
||||
func selectId() -> QueryInterfaceRequest<Int64> {
|
||||
selectPrimaryKey(as: Int64.self)
|
||||
}
|
||||
}
|
||||
|
||||
// IDs of French authors
|
||||
let ids: [Int64] = try Author.all().filter(country: "France").selectId().fetchAll(db)
|
||||
```
|
||||
|
||||
## Compose Records
|
||||
|
||||
We'd like to navigate from books to authors and vice-versa: we may want to know an author's books, or a book's author.
|
||||
|
||||
GRDB can help you do this with [associations]. In our case, each author **has many** books, and each book **belongs to** its author. Here is how you define those associations:
|
||||
|
||||
```swift
|
||||
extension Author {
|
||||
static let books = hasMany(Book.self)
|
||||
}
|
||||
|
||||
extension Book {
|
||||
static let author = belongsTo(Author.self)
|
||||
}
|
||||
```
|
||||
|
||||
Thanks to this setup, you can fetch associated records, or compute aggregated values from associated records. For example:
|
||||
|
||||
```swift
|
||||
// Fetch all authors and their number of books
|
||||
struct AuthorInfo: Decodable, FetchableRecord {
|
||||
var author: Author
|
||||
var bookCount: Int
|
||||
}
|
||||
let authorInfos: [AuthorInfo] = try dbQueue.read { db in
|
||||
let request = Author.annotated(with: Author.books.count)
|
||||
return try AuthorInfo.fetchAll(db, request)
|
||||
}
|
||||
|
||||
// Fetch all Colombian books and their authors:
|
||||
struct Authorship: Decodable, FetchableRecord {
|
||||
var book: Book
|
||||
var author: Author
|
||||
}
|
||||
let authorships: [Authorship] = try dbQueue.read { db in
|
||||
let request = Book.including(required: Book.author.filter(country: "Colombia"))
|
||||
return try Authorship.fetchAll(db, request)
|
||||
}
|
||||
```
|
||||
|
||||
As in the sample code above, requests which feed from several associated records will often have you define extra record types, such as `AuthorInfo` and `Authorship`. Those extra record types are designed to be able to decode database requests. The names and types of their properties follow the conventions defined by [associations]. Make them conform to the Decodable and FetchableRecord protocols so that they can decode database rows in a breeze.
|
||||
|
||||
Unlike the primitive persistable record types `Author` and `Book`, those records can not write in the database. They are simple data types, passive views on the database content. Remember, only [Persistable Record Types are Responsible for Their Tables].
|
||||
|
||||
> **Note**: The example `AuthorInfo` and `Authorship` types above may look superfluous to you. After all, other ORMs out there are able to navigate in complex graphs of records without much fuss, aren't they?
|
||||
>
|
||||
> That is because other ORMs perform lazy loading:
|
||||
>
|
||||
> ```ruby
|
||||
> # Ruby's Active Record
|
||||
> author = Author.find(123) # fetch author
|
||||
> book_count = author.books.count # lazily counts books on demand
|
||||
> ```
|
||||
>
|
||||
> GRDB does not perform lazy loading. Lazy loading either requires records to be *managed* (as in [Core Data] and [Realm]), or that all data processing happens in a *single function* (think of an HTTP request handled with a web-oriented ORM like [Active Record] and [Django]). The underlying issue is *data consistency*: you always want your memory objects to accurately represent your application data, without any glitch, ever. This involves the subtle database concept of [isolation] against concurrent changes. In a GUI application, this can't be achieved without a very complex record management, and non-trivial pain points for the application developer.
|
||||
>
|
||||
> This is why GRDB has removed lazy loading from the list of desirable features. Instead, it provides the tooling needed to fetch data, even complex ones, in a single and safe stroke. See the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more information.
|
||||
|
||||
Granted with primitive and derived record types, your application will load the data it needs, at the moment it needs it, as below:
|
||||
|
||||
1. Prepare the application screen that lists all authors:
|
||||
|
||||
```swift
|
||||
let authors: [Author] = try dbQueue.read { db in
|
||||
try Author.all().orderByName().fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
2. Prepare the application screen that displays an author and her books:
|
||||
|
||||
```swift
|
||||
struct AuthorInfo: Codable, FetchableRecord {
|
||||
var author: Author
|
||||
var books: [Book]
|
||||
}
|
||||
let authorId = 123
|
||||
let authorInfo: AuthorInfo? = try dbQueue.read { db in
|
||||
let request = Author
|
||||
.filter(id: authorId)
|
||||
.including(all: Author.books)
|
||||
return try AuthorInfo.fetchOne(db, request)
|
||||
}
|
||||
```
|
||||
|
||||
3. Prepare the application screen that displays a book information:
|
||||
|
||||
```swift
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
var book: Book
|
||||
var author: Author
|
||||
}
|
||||
let bookId = 123
|
||||
let bookInfo: BookInfo? = try dbQueue.read { db in
|
||||
let request = Book
|
||||
.filter(id: bookId)
|
||||
.including(required: Book.author)
|
||||
return try BookInfo.fetchOne(db, request)
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: **Tip**: Identify the various **graph of objects** needed by the various parts of your application. Design them independently, by composing primitive record types linked by associations. Fetch the data your application needs, at the moment it needs it, no more, no less.
|
||||
|
||||
A last extension on your record types will further help navigation from records to associated ones:
|
||||
|
||||
```swift
|
||||
extension Author {
|
||||
/// The request for the author's books
|
||||
var books: QueryInterfaceRequest<Book> {
|
||||
request(for: Author.books)
|
||||
}
|
||||
}
|
||||
|
||||
extension Book {
|
||||
/// The request for the author of the book
|
||||
var author: QueryInterfaceRequest<Author> {
|
||||
request(for: Book.author)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Those properties provide an alternative way to feed our application:
|
||||
|
||||
1. Prepare the application screen that displays an author and her books:
|
||||
|
||||
```swift
|
||||
struct AuthorInfo {
|
||||
var author: Author
|
||||
var books: [Book]
|
||||
}
|
||||
let authorId = 123
|
||||
let authorInfo: AuthorInfo? = try dbQueue.read { db in
|
||||
guard let author = try Author.fetchOne(db, id: authorId) else {
|
||||
return nil
|
||||
}
|
||||
let books = try author.books.fetchAll(db)
|
||||
return AuthorInfo(
|
||||
author: author,
|
||||
books: books)
|
||||
}
|
||||
```
|
||||
|
||||
2. Prepare the application screen that displays a book information:
|
||||
|
||||
```swift
|
||||
struct BookInfo {
|
||||
var book: Book
|
||||
var author: Author
|
||||
}
|
||||
let bookId = 123
|
||||
let bookInfo: BookInfo? = try dbQueue.read { db in
|
||||
guard let book = try Book.fetchOne(db, id: bookId) else {
|
||||
return nil
|
||||
}
|
||||
guard let author = try book.author.fetchOne(db) else {
|
||||
return nil
|
||||
}
|
||||
return BookInfo(book: book, author: author)
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## How to Design Database Managers
|
||||
|
||||
Many developers want to hide GRDB database queues and pools inside "database managers":
|
||||
|
||||
```swift
|
||||
// LibraryManager grants access to the library database.
|
||||
class LibraryManager {
|
||||
private let dbQueue: DatabaseQueue
|
||||
init(dbQueue: DatabaseQueue) {
|
||||
self.dbQueue = dbQueue
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: **Tip**: Don't let your database managers create their own databases. Instead, give them a database created by, say, the ApplicationDelegate. This will allow you to efficiently test the database manager with an in-memory database, for example.
|
||||
|
||||
Design your database managers with the [GRDB concurrency rules] in mind.
|
||||
|
||||
Practically, let's start with a naive example, and gradually improve it:
|
||||
|
||||
```swift
|
||||
// A naive manager that we will improve
|
||||
class NaiveLibraryManager {
|
||||
private let dbQueue: DatabaseQueue
|
||||
init(dbQueue: DatabaseQueue) {
|
||||
self.dbQueue = dbQueue
|
||||
}
|
||||
|
||||
func author(id: Int64) -> Author? {
|
||||
do {
|
||||
return try dbQueue.read { db in
|
||||
try Author.fetchOne(db, id: id)
|
||||
}
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func book(id: Int64) -> Book? {
|
||||
do {
|
||||
return try dbQueue.read { db in
|
||||
try Book.fetchOne(db, id: id)
|
||||
}
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func books(writtenBy author: Author) -> [Book] {
|
||||
do {
|
||||
return try dbQueue.read { db in
|
||||
try author.books.fetchAll(db)
|
||||
}
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**This manager can be improved in two ways.**
|
||||
|
||||
- [Embrace Errors]
|
||||
- [Thread-Safety is also an Application Concern]
|
||||
|
||||
### Embrace Errors
|
||||
|
||||
Have database managers throw database errors instead of catching them.
|
||||
|
||||
Consider Apple's [CNContactStore](https://developer.apple.com/documentation/contacts/cncontactstore), for example. Does it hide errors when you fetch or save address book contacts? No it does not. Keychain, Media assets, File system, Core Data? No they do not hide errors either. Follow the practices of Apple engineers: do not hide errors :muscle:
|
||||
|
||||
Exposing errors will help you building your application:
|
||||
|
||||
- You will be able to inspect errors during development, and fix bugs. `do { ... } catch { print(error) }` will save you hours of clueless questioning.
|
||||
- You will be able to opt in for advanced OS features like [data protection].
|
||||
|
||||
> :bulb: **Tip**: Don't hide database errors. Let the application handle them, because only application can decide how to handle them.
|
||||
|
||||
This gives the improved manager below. And it has less code, which means less bugs :bowtie:
|
||||
|
||||
```swift
|
||||
// An improved manager that does not hide errors
|
||||
class ImprovedLibraryManager {
|
||||
private let dbQueue: DatabaseQueue
|
||||
init(dbQueue: DatabaseQueue) {
|
||||
self.dbQueue = dbQueue
|
||||
}
|
||||
|
||||
func author(id: Int64) throws -> Author? {
|
||||
try dbQueue.read { db in
|
||||
try Author.fetchOne(db, id: id)
|
||||
}
|
||||
}
|
||||
|
||||
func book(id: Int64) throws -> Book? {
|
||||
try dbQueue.read { db in
|
||||
try Book.fetchOne(db, id: id)
|
||||
}
|
||||
}
|
||||
|
||||
func books(writtenBy author: Author) throws -> [Book] {
|
||||
try dbQueue.read { db in
|
||||
try author.books.fetchAll(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Thread-Safety is also an Application Concern
|
||||
|
||||
Now, let's make our database manager **thread-safe**.
|
||||
|
||||
This one is more subtle. In order to understand what is wrong in our naive manager, one has to consider how it is used by the application.
|
||||
|
||||
For example, in the screen that displays an author and her books, we would write:
|
||||
|
||||
```swift
|
||||
let authorId = 123
|
||||
if let author = libraryManager.author(id: authorId) {
|
||||
let books = libraryManager.books(writtenBy: author)
|
||||
// Use author and books
|
||||
}
|
||||
```
|
||||
|
||||
This code is not thread-safe, because other application threads may have modified the database between the two database accesses. You may end up with an author without any book, and this sure does not make a pretty application screen.
|
||||
|
||||
Such bugs are uneasy to reproduce. Sometimes your application will refresh the library content from the network, and delete an author right at the wrong time. The more users your application has, the more users will see weird screens. And of course, you'll be bitten right on the day of the demo in front of the boss.
|
||||
|
||||
Fortunately, GRDB has all the tools you need to prevent such nasty data races:
|
||||
|
||||
> :bulb: **Tip**: Make sure you fetch all the data your application needs at a given moment of time, in a **single database read**.
|
||||
|
||||
This gives a much safer manager:
|
||||
|
||||
```swift
|
||||
// A manager that actually manages
|
||||
class LibraryManager {
|
||||
private let dbQueue: DatabaseQueue
|
||||
init(dbQueue: DatabaseQueue) {
|
||||
self.dbQueue = dbQueue
|
||||
}
|
||||
}
|
||||
|
||||
// Feeds the list of authors
|
||||
extension LibraryManager {
|
||||
struct AuthorListItem: Decodable, FetchableRecord {
|
||||
let author: Author
|
||||
let bookCount: Int
|
||||
}
|
||||
|
||||
func authorList() throws -> [AuthorListItem] {
|
||||
try dbQueue.read { db in
|
||||
let request = Author
|
||||
.annotated(with: Author.books.count)
|
||||
.orderByName()
|
||||
return try AuthorListItem.fetchAll(db, request)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Feeds a book screen
|
||||
extension LibraryManager {
|
||||
struct BookInfo {
|
||||
var book: Book
|
||||
var author: Author
|
||||
}
|
||||
|
||||
func bookInfo(bookId: Int64) throws -> BookInfo? {
|
||||
try dbQueue.read { db in
|
||||
guard let book = try Book.fetchOne(db, id: bookId) else {
|
||||
return nil
|
||||
}
|
||||
guard let author = try book.author.fetchOne(db) else {
|
||||
return nil
|
||||
}
|
||||
return BookInfo(book: book, author: author)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Feeds an author screen
|
||||
extension LibraryManager {
|
||||
struct AuthorInfo {
|
||||
var author: Author
|
||||
var books: [Book]
|
||||
}
|
||||
|
||||
func authorInfo(authorId: Int64) throws -> AuthorInfo? {
|
||||
try dbQueue.read { db in
|
||||
guard let author = try Author.fetchOne(db, id: authorId) else {
|
||||
return nil
|
||||
}
|
||||
let books = try author.books.fetchAll(db)
|
||||
return AuthorInfo(author: author, books: books)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The `AuthorListItem`, `BookInfo`, `AuthorInfo` types returned by the manager are designed to feed your views.
|
||||
|
||||
When a new screen is added to your application, and you want to make sure it displays **consistent data** free from any data race, make sure you update the manager if needed. The rule is very simple: consumed data must come from a **single** database access method (`dbQueue.read`, `write`, etc.), or [ValueObservation].
|
||||
|
||||
In other words: since GRDB is an unmanaged ORM, some amount of management must be imported into your application in order to make it fully thread-safe.
|
||||
|
||||
> **Note**: Wrapping several fetches in a single `read` method may look like an inconvenience to you. After all, other ORMs don't require that much ceremony:
|
||||
>
|
||||
> ```ruby
|
||||
> # Ruby's Active Record
|
||||
> book = Book.find(123) # fetch book
|
||||
> author = book.author # fetch author
|
||||
> # use book and author
|
||||
> ```
|
||||
>
|
||||
> The problem is that it is very hard to guarantee that you will surely fetch an author after you have fetched a book, despite the constraints of the database schema. One has to perform subsequent fetches in the proper [isolation] level, so that eventual concurrent writes that modify the database are unable to mess with subsequent requests.
|
||||
>
|
||||
> This isolation can be achieved with record management, as in [Core Data] or [Realm], that target long-running multi-threaded applications. On the other side, most web-oriented ORMs rely on short-lived database transactions, so that each HTTP request can be processed independently of others.
|
||||
>
|
||||
> GRDB is not a managed ORM. It thus has to use the same isolation techniques as web-oriented ORMs. But unlike web-oriented ORMs, GRDB can't provide implicit isolation: the application must decide when it wants to safely read information in the database, and this decision is made explicit, in your application code, with database access methods such as `dbQueue.read`.
|
||||
>
|
||||
> See the [Concurrency Guide] for detailed information, and the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more rationale.
|
||||
|
||||
|
||||
## Observe the Database and Refetch when Needed
|
||||
|
||||
We have seen above that the primitive Author and Book record types are [responsible](#persistable-record-types-are-responsible-for-their-tables) for their own database tables. Later we built [requests](#define-record-requests) and [composed](#compose-records) records into more complex ones such as BookInfo or AuthorInfo. We have shown how [database managers](#how-to-design-database-managers) should expose database content to the rest of the application.
|
||||
|
||||
Database content which has been fetched into memory eventually becomes obsoleted, as the application modifies the database content.
|
||||
|
||||
It is up to the application to decide how long it should keep fetched information in memory. Very often though, the application will want to keep memory information synchronized with the database content.
|
||||
|
||||
This synchronization is not automatic with GRDB: records do not "auto-update". That is because applications do not always want this feature, and because it is difficult to write correct multi-threaded applications when values can change in unexpected ways.
|
||||
|
||||
Instead, have a look at [Database Observation]:
|
||||
|
||||
> :bulb: **Tip**: [ValueObservation] performs automated tracking of database changes.
|
||||
>
|
||||
> :bulb: **Tip**: [Combine Support] allows automated tracking of database changes, in the [Combine](https://developer.apple.com/documentation/combine) way.
|
||||
>
|
||||
> :bulb: **Tip**: [RxGRDB] performs automated tracking of database changes, in the [RxSwift](https://github.com/ReactiveX/RxSwift) way.
|
||||
>
|
||||
> :bulb: **Tip**: [TransactionObserver] provides low-level database observation, for your most advanced needs.
|
||||
>
|
||||
> :bulb: **Tip**: Don't try to write complex methods that both modify the database and the values in memory at the same time. Instead, modify the database with plain record types, and rely on database observation for automatically refreshing values, even complex ones.
|
||||
|
||||
[records]: ../README.md#records
|
||||
[associations]: AssociationsBasics.md
|
||||
[FMDB]: https://github.com/ccgus/fmdb
|
||||
[Core Data]: https://developer.apple.com/documentation/coredata
|
||||
[Realm]: https://realm.io
|
||||
[Active Record]: http://guides.rubyonrails.org/active_record_basics.html
|
||||
[Django]: https://docs.djangoproject.com/en/2.0/topics/db/
|
||||
[record protocols]: ../README.md#record-protocols-overview
|
||||
[Separation of Concerns]: https://en.wikipedia.org/wiki/Separation_of_concerns
|
||||
[Single Source of Truth]: https://en.wikipedia.org/wiki/Single_source_of_truth
|
||||
[Divide and Conquer]: https://en.wikipedia.org/wiki/Divide_and_rule
|
||||
[Why Adopt GRDB?]: WhyAdoptGRDB.md
|
||||
[isolation]: https://en.wikipedia.org/wiki/Isolation_(database_systems)
|
||||
[migrations]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations
|
||||
[migration]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations
|
||||
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
|
||||
[Concurrency Guide]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency
|
||||
[GRDB concurrency rules]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency
|
||||
[PersistableRecord]: ../README.md#persistablerecord-protocol
|
||||
[Database Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
|
||||
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
|
||||
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
|
||||
[TransactionObserver]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver
|
||||
[Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself
|
||||
[Persistable Record Types are Responsible for Their Tables]: #persistable-record-types-are-responsible-for-their-tables
|
||||
[Record Types Hide Intimate Database Details]: #record-types-hide-intimate-database-details
|
||||
[Singleton Records]: #singleton-records
|
||||
[Define Record Requests]: #define-record-requests
|
||||
[Compose Records]: #compose-records
|
||||
[How to Design Database Managers]: #how-to-design-database-managers
|
||||
[Observe the Database and Refetch when Needed]: #observe-the-database-and-refetch-when-needed
|
||||
[query interface]: ../README.md#the-query-interface
|
||||
[observe database changes]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
|
||||
[data protection]: ../README.md#data-protection
|
||||
[Embrace Errors]: #embrace-errors
|
||||
[Thread-Safety is also an Application Concern]: #thread-safety-is-also-an-application-concern
|
||||
[recommended convention]: AssociationsBasics.md#associations-and-the-database-schema
|
||||
[Association Aggregates]: AssociationsBasics.md#association-aggregates
|
||||
[Codable Record]: ../README.md#codable-records
|
||||
[CodingKeys]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
|
||||
[Combine Support]: Combine.md
|
||||
[Value]: ../README.md#values
|
||||
[Identifiable]: https://developer.apple.com/documentation/swift/identifiable
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
|
||||
@@ -195,7 +195,7 @@ protocol DerivableRequest<RowDecoder>: AggregatingRequest, FilteredRequest,
|
||||
- `SelectionRequest` provides selection methods such as `select(selection)` or `annotated(with: selection)`
|
||||
- `TableRequest` provides table targeting methods such as `aliased(tableAlias)`
|
||||
|
||||
DerivableRequest makes it possible to build reusable code snippets that apply to both requests and associations. You'll read more about it in the [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md) and [Associations](AssociationsBasics.md).
|
||||
DerivableRequest makes it possible to build reusable code snippets that apply to both requests and associations. You'll read more about it in the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) and [Associations](AssociationsBasics.md).
|
||||
|
||||
### FetchRequest
|
||||
|
||||
|
||||
@@ -21,7 +21,6 @@ To release a new GRDB version:
|
||||
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
|
||||
- Push to the master & development branch
|
||||
- `pod trunk push --allow-warnings GRDB.swift.podspec`
|
||||
- Update https://github.com/groue/WWDCCompanion
|
||||
- Update [performance comparison](https://github.com/groue/GRDB.swift/wiki/Performance):
|
||||
|
||||
`make test_performance | Tests/parsePerformanceTests.rb | Tests/generatePerformanceReport.rb`
|
||||
@@ -90,7 +90,7 @@ For your convenience, those record protocols can be derived from the [Decodable
|
||||
|
||||
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.
|
||||
|
||||
See [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md) for some practical advice.
|
||||
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
|
||||
@@ -190,7 +190,7 @@ Finally, raw FMDatabase, SQLite.swift, and Core Data are the hardest tools, and
|
||||
|
||||
For detailed information about GRDB concurrency, check the [Concurrency Guide].
|
||||
|
||||
For practical advice on designing the database access layer of your application, see the [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md).
|
||||
For practical advice on designing the database access layer of your application, see the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
|
||||
|
||||
|
||||
### Never pay for using raw SQL
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '6.7.0'
|
||||
s.version = '6.15.1'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -71,6 +71,7 @@
|
||||
56256ED025D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; };
|
||||
56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; };
|
||||
562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
|
||||
562B58CB2A29BBEF00E8C75D /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */; };
|
||||
562EA8261F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
|
||||
562EA82F1F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
|
||||
56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; };
|
||||
@@ -281,6 +282,7 @@
|
||||
56D110D828AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */; };
|
||||
56D110DD28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */; };
|
||||
56D110FA28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */; };
|
||||
56D3332029C38D6700430680 /* WALSnapshotTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */; };
|
||||
56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */; };
|
||||
56D496551D812F83008276D7 /* FoundationDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */; };
|
||||
56D496571D81303E008276D7 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; };
|
||||
@@ -457,6 +459,7 @@
|
||||
56256ECF25D1ACD0008C2BDD /* Table.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = "<group>"; };
|
||||
56256ED825D1B316008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = "<group>"; };
|
||||
562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = "<group>"; };
|
||||
562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = "<group>"; };
|
||||
562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = "<group>"; };
|
||||
562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = "<group>"; };
|
||||
56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = "<group>"; };
|
||||
@@ -511,7 +514,6 @@
|
||||
56419A6C24A51601004967E1 /* Support.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Support.swift; sourceTree = "<group>"; };
|
||||
56419A6D24A51601004967E1 /* DatabaseRegionObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationPublisherTests.swift; sourceTree = "<group>"; };
|
||||
56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationPublisherTests.swift; sourceTree = "<group>"; };
|
||||
5643676D272EDF2400C718C7 /* Scripts */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Scripts; sourceTree = "<group>"; };
|
||||
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
|
||||
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
|
||||
564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueConcurrentObserver.swift; sourceTree = "<group>"; };
|
||||
@@ -753,6 +755,7 @@
|
||||
56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Insert.swift"; sourceTree = "<group>"; };
|
||||
56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Save.swift"; sourceTree = "<group>"; };
|
||||
56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+DAO.swift"; sourceTree = "<group>"; };
|
||||
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshotTransaction.swift; sourceTree = "<group>"; };
|
||||
56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = "<group>"; };
|
||||
56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = "<group>"; };
|
||||
56D91AA12205E03700770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = "<group>"; };
|
||||
@@ -1055,6 +1058,7 @@
|
||||
563B06BF2185CD1700B38F35 /* ValueObservation */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */,
|
||||
560233C82724338800529DF3 /* SharedValueObservationTests.swift */,
|
||||
563B06F621861D8300B38F35 /* ValueObservationCountTests.swift */,
|
||||
563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */,
|
||||
@@ -1111,13 +1115,6 @@
|
||||
path = GRDBCombineTests;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
564390D42414FC2C00BA61E6 /* Frameworks */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
);
|
||||
name = Frameworks;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
5653EABF20944B1300F46237 /* Association */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -1466,6 +1463,7 @@
|
||||
566B9C1F25C6CC24004542CF /* RowDecodingError.swift */,
|
||||
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
|
||||
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
|
||||
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */,
|
||||
56E9FAD7221053DC00C703A8 /* SQL.swift */,
|
||||
569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */,
|
||||
56FBFED82210731A00945324 /* SQLRequest.swift */,
|
||||
@@ -1585,8 +1583,6 @@
|
||||
DC37742D19C8CC90004FCF85 /* GRDB */,
|
||||
DC10500F19C904DD00D8CA30 /* Tests */,
|
||||
DC3773F419C8CBB3004FCF85 /* Products */,
|
||||
564390D42414FC2C00BA61E6 /* Frameworks */,
|
||||
5643676D272EDF2400C718C7 /* Scripts */,
|
||||
);
|
||||
indentWidth = 4;
|
||||
sourceTree = "<group>";
|
||||
@@ -1740,6 +1736,7 @@
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
562B58CB2A29BBEF00E8C75D /* Issue1383.sqlite in Resources */,
|
||||
569BBA4622906A8200478429 /* InflectionsTests.json in Resources */,
|
||||
56D496C21D81374C008276D7 /* Betty.jpeg in Resources */,
|
||||
);
|
||||
@@ -2157,6 +2154,7 @@
|
||||
5653EC122098738B00F46237 /* SQLGenerationContext.swift in Sources */,
|
||||
560D92471C672C4B00F4F92B /* MutablePersistableRecord.swift in Sources */,
|
||||
5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
|
||||
56D3332029C38D6700430680 /* WALSnapshotTransaction.swift in Sources */,
|
||||
5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
|
||||
5657AAB91D107001006283EF /* NSData.swift in Sources */,
|
||||
560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */,
|
||||
|
||||
@@ -174,7 +174,7 @@ public struct Configuration {
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// The default clock is ``DefaultTransactionClock`` (which returns the
|
||||
/// current date with `Date()`).
|
||||
/// start date of the current transaction).
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -182,7 +182,7 @@ public struct Configuration {
|
||||
/// var config = Configuration()
|
||||
/// config.transactionClock = .custom { db in /* return some Date */ }
|
||||
/// ```
|
||||
public var transactionClock: TransactionClock = .default
|
||||
public var transactionClock: any TransactionClock = .default
|
||||
|
||||
// MARK: - Managing SQLite Connections
|
||||
|
||||
@@ -301,13 +301,15 @@ public struct Configuration {
|
||||
/// If nil, GRDB picks a default one.
|
||||
var readonlyBusyMode: Database.BusyMode? = nil
|
||||
|
||||
/// The maximum number of concurrent readers.
|
||||
/// The maximum number of concurrent reader connections.
|
||||
///
|
||||
/// This configuration applies to ``DatabasePool`` only. The default value
|
||||
/// is 5.
|
||||
/// This configuration has 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
|
||||
/// for concurrent reads of any ``DatabaseReader``. For example:
|
||||
/// for concurrent reads of any ``DatabaseReader``. In this context,
|
||||
/// ``DatabaseQueue`` and ``DatabaseSnapshot`` have a capacity of 1,
|
||||
/// because they can't perform two concurrent reads. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
@@ -321,6 +323,7 @@ public struct Configuration {
|
||||
/// print(dbQueue.configuration.maximumReaderCount) // 1
|
||||
/// print(dbPool.configuration.maximumReaderCount) // 5
|
||||
/// print(dbSnapshot.configuration.maximumReaderCount) // 1
|
||||
/// ```
|
||||
public var maximumReaderCount: Int = 5
|
||||
|
||||
/// The quality of service of database accesses.
|
||||
@@ -372,7 +375,22 @@ public struct Configuration {
|
||||
/// The default is true.
|
||||
public var automaticMemoryManagement = true
|
||||
#endif
|
||||
|
||||
|
||||
/// A boolean value indicating whether read-only connections should be
|
||||
/// kept open.
|
||||
///
|
||||
/// This configuration flag applies to ``DatabasePool`` only. The
|
||||
/// default value is false.
|
||||
///
|
||||
/// When the flag is false, a `DatabasePool` closes read-only
|
||||
/// connections when requested to dispose non-essential memory with
|
||||
/// ``DatabasePool/releaseMemory()``. When true, those connections are
|
||||
/// kept open.
|
||||
///
|
||||
/// Consider setting this flag to true when profiling your application
|
||||
/// reveals that a lot of time is spent opening new SQLite connections.
|
||||
public var persistentReadOnlyConnections = false
|
||||
|
||||
// MARK: - Factory Configuration
|
||||
|
||||
/// Creates a factory configuration.
|
||||
|
||||
+188
-77
@@ -14,9 +14,14 @@
|
||||
extension RangeReplaceableCollection {
|
||||
/// Creates a collection containing the elements of a cursor.
|
||||
///
|
||||
/// // [String]
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Array(cursor)
|
||||
/// For example, you can turn a cursor of strings into an array
|
||||
/// of strings:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a [String]
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Array(cursor)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter cursor: The cursor whose elements feed the collection.
|
||||
public init(_ cursor: some Cursor<Element>) throws {
|
||||
@@ -26,9 +31,14 @@ extension RangeReplaceableCollection {
|
||||
|
||||
/// Creates a collection containing the elements of a cursor.
|
||||
///
|
||||
/// // [String]
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Array(cursor, minimumCapacity: 100)
|
||||
/// For example, you can turn a cursor of strings into an array
|
||||
/// of strings:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a [String]
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Array(cursor, minimumCapacity: 100)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter cursor: The cursor whose elements feed the collection.
|
||||
/// - parameter minimumCapacity: Prepares the returned collection to store
|
||||
@@ -41,8 +51,8 @@ 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
|
||||
/// the collection.
|
||||
/// - Important: If an error is thrown, an unspecified amount of
|
||||
/// elements have been added to the collection.
|
||||
///
|
||||
/// - parameter newElements: The elements to append to the collection.
|
||||
public mutating func append(contentsOf newElements: some Cursor<Element>) throws {
|
||||
@@ -58,9 +68,13 @@ extension Dictionary {
|
||||
/// given closure and whose values are arrays of the elements that returned
|
||||
/// each key.
|
||||
///
|
||||
/// // [Int64: [Player]]
|
||||
/// let cursor = try Player.fetchCursor(db)
|
||||
/// let dictionary = try Dictionary(grouping: cursor, by: { $0.teamID })
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a [Int64: [Player]]
|
||||
/// let cursor = try Player.fetchCursor(db)
|
||||
/// let dictionary = try Dictionary(grouping: cursor, by: { $0.teamID })
|
||||
/// ```
|
||||
///
|
||||
/// - parameter cursor: A cursor of values to group into a dictionary.
|
||||
/// - parameter keyForValue: A closure that returns a key for each element
|
||||
@@ -81,12 +95,16 @@ extension Dictionary {
|
||||
/// given closure and whose values are arrays of the elements that returned
|
||||
/// each key.
|
||||
///
|
||||
/// // [Int64: [Player]]
|
||||
/// let cursor = try Player.fetchCursor(db)
|
||||
/// let dictionary = try Dictionary(
|
||||
/// minimumCapacity: 100,
|
||||
/// grouping: cursor,
|
||||
/// by: { $0.teamID })
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a [Int64: [Player]]
|
||||
/// let cursor = try Player.fetchCursor(db)
|
||||
/// let dictionary = try Dictionary(
|
||||
/// minimumCapacity: 100,
|
||||
/// grouping: cursor,
|
||||
/// by: { $0.teamID })
|
||||
/// ```
|
||||
///
|
||||
/// - parameter minimumCapacity: The minimum number of key-value pairs that
|
||||
/// the newly created dictionary should be able to store without
|
||||
@@ -112,9 +130,13 @@ extension Dictionary {
|
||||
/// of key-value tuples with unique keys. Passing a cursor with duplicate
|
||||
/// keys to this initializer results in a fatal error.
|
||||
///
|
||||
/// // [Int64: Player]
|
||||
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
|
||||
/// let playerByID = try Dictionary(uniqueKeysWithValues: cursor)
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a [Int64: [Player]]
|
||||
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
|
||||
/// let playerByID = try Dictionary(uniqueKeysWithValues: cursor)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter keysAndValues: A cursor of key-value pairs to use for the
|
||||
/// new dictionary. Every key in `keysAndValues` must be unique.
|
||||
@@ -137,11 +159,15 @@ extension Dictionary {
|
||||
/// of key-value tuples with unique keys. Passing a cursor with duplicate
|
||||
/// keys to this initializer results in a fatal error.
|
||||
///
|
||||
/// // [Int64: Player]
|
||||
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
|
||||
/// let playerByID = try Dictionary(
|
||||
/// minimumCapacity: 100,
|
||||
/// uniqueKeysWithValues: cursor)
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a [Int64: [Player]]
|
||||
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
|
||||
/// let playerByID = try Dictionary(
|
||||
/// minimumCapacity: 100,
|
||||
/// uniqueKeysWithValues: cursor)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter minimumCapacity: The minimum number of key-value pairs that
|
||||
/// the newly created dictionary should be able to store without
|
||||
@@ -165,9 +191,13 @@ extension Dictionary {
|
||||
extension Set {
|
||||
/// Creates a set containing the elements of a cursor.
|
||||
///
|
||||
/// // Set<String>
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Set(cursor)
|
||||
/// For example, you can turn a cursor of strings into a set of strings:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a Set<String>
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Set(cursor)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter cursor: A cursor of values to gather into a set.
|
||||
public init(_ cursor: some Cursor<Element>) throws {
|
||||
@@ -180,9 +210,13 @@ extension Set {
|
||||
|
||||
/// Creates a set containing the elements of a cursor.
|
||||
///
|
||||
/// // Set<String>
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Set(cursor, minimumCapacity: 100)
|
||||
/// For example, you can turn a cursor of strings into a set of strings:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a Set<String>
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Set(cursor, minimumCapacity: 100)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter cursor: A cursor of values to gather into a set.
|
||||
/// - parameter minimumCapacity: The minimum number of elements that the
|
||||
@@ -240,6 +274,75 @@ extension Sequence {
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Iterating Over a Cursor’s Elements
|
||||
///
|
||||
/// - ``next()``
|
||||
/// - ``forEach(_:)-4ib2m``
|
||||
/// - ``enumerated()``
|
||||
/// - ``isEmpty``
|
||||
///
|
||||
/// ### Finding Elements
|
||||
///
|
||||
/// - ``contains(_:)``
|
||||
/// - ``contains(where:)``
|
||||
/// - ``first(where:)``
|
||||
/// - ``min()``
|
||||
/// - ``min(by:)``
|
||||
/// - ``max()``
|
||||
/// - ``max(by:)``
|
||||
///
|
||||
/// ### Selecting Elements
|
||||
///
|
||||
/// - ``prefix(_:)``
|
||||
/// - ``prefix(while:)``
|
||||
/// - ``suffix(_:)``
|
||||
///
|
||||
/// ### Excluding Elements
|
||||
///
|
||||
/// - ``dropFirst()``
|
||||
/// - ``dropFirst(_:)``
|
||||
/// - ``dropLast()``
|
||||
/// - ``dropLast(_:)``
|
||||
/// - ``drop(while:)``
|
||||
/// - ``filter(_:)``
|
||||
///
|
||||
/// ### Transforming a Cursor
|
||||
///
|
||||
/// - ``map(_:)``
|
||||
/// - ``compactMap(_:)``
|
||||
/// - ``flatMap(_:)-5ci2v``
|
||||
/// - ``flatMap(_:)-8jxlj``
|
||||
/// - ``reduce(_:_:)``
|
||||
/// - ``reduce(into:_:)``
|
||||
///
|
||||
/// ### Transforming a Sequence into a Cursor
|
||||
///
|
||||
/// - ``Swift/Sequence/flatMap(_:)``
|
||||
///
|
||||
/// ### Joining Elements
|
||||
///
|
||||
/// - ``joined()-5r5ja``
|
||||
/// - ``joined()-7bnrx``
|
||||
/// - ``joined(separator:)``
|
||||
///
|
||||
/// ### Filling RangeReplaceableCollection with the contents of a Cursor
|
||||
///
|
||||
/// - ``Swift/RangeReplaceableCollection/init(_:)``
|
||||
/// - ``Swift/RangeReplaceableCollection/init(_:minimumCapacity:)``
|
||||
/// - ``Swift/RangeReplaceableCollection/append(contentsOf:)``
|
||||
///
|
||||
/// ### Creating a Dictionary from the contents of a Cursor
|
||||
///
|
||||
/// - ``Swift/Dictionary/init(grouping:by:)``
|
||||
/// - ``Swift/Dictionary/init(minimumCapacity:grouping:by:)``
|
||||
/// - ``Swift/Dictionary/init(uniqueKeysWithValues:)``
|
||||
/// - ``Swift/Dictionary/init(minimumCapacity:uniqueKeysWithValues:)``
|
||||
///
|
||||
/// ### Creating a Set from the contents of a Cursor
|
||||
///
|
||||
/// - ``Swift/Set/init(_:)``
|
||||
/// - ``Swift/Set/init(_:minimumCapacity:)``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``AnyCursor``
|
||||
@@ -269,7 +372,7 @@ extension Cursor {
|
||||
/// Returns a Boolean value indicating whether the cursor does not contain
|
||||
/// any element.
|
||||
///
|
||||
/// - important: This property may consume elements.
|
||||
/// - important: This property consumes an element.
|
||||
public var isEmpty: Bool {
|
||||
get throws { try next() == nil }
|
||||
}
|
||||
@@ -294,13 +397,17 @@ extension Cursor {
|
||||
/// Returns a cursor of pairs (n, x), where n represents a consecutive
|
||||
/// integer starting at zero, and x represents an element of the cursor.
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
|
||||
/// let c = cursor.enumerated()
|
||||
/// while let (n, x) = c.next() {
|
||||
/// print("\(n): \(x)")
|
||||
/// }
|
||||
/// // Prints: "0: foo"
|
||||
/// // Prints: "1: bar"
|
||||
/// ```swift
|
||||
/// let cursor = try String.fetchCursor(db, sql: """
|
||||
/// SELECT 'foo' UNION ALL SELECT 'bar'
|
||||
/// """)
|
||||
/// let c = cursor.enumerated()
|
||||
/// while let (n, x) = c.next() {
|
||||
/// print("\(n): \(x)")
|
||||
/// }
|
||||
/// // Prints: "0: foo"
|
||||
/// // Prints: "1: bar"
|
||||
/// ```
|
||||
public func enumerated() -> EnumeratedCursor<Self> {
|
||||
EnumeratedCursor(self)
|
||||
}
|
||||
@@ -346,11 +453,13 @@ 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))
|
||||
/// // Prints "[3, 4, 5]"
|
||||
/// try print(numbers.dropFirst(10))
|
||||
/// // Prints "[]"
|
||||
/// ```swift
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropFirst(2))
|
||||
/// // Prints "[3, 4, 5]"
|
||||
/// try print(numbers.dropFirst(10))
|
||||
/// // Prints "[]"
|
||||
/// ```
|
||||
///
|
||||
/// - Parameter n: The number of elements to drop from the beginning of
|
||||
/// the cursor. `n` must be greater than or equal to zero.
|
||||
@@ -364,9 +473,11 @@ 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())
|
||||
/// // Prints "[2, 3, 4, 5]"
|
||||
/// ```swift
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropFirst())
|
||||
/// // Prints "[2, 3, 4, 5]"
|
||||
/// ```
|
||||
///
|
||||
/// If the cursor has no elements, the result is an empty cursor.
|
||||
///
|
||||
@@ -381,11 +492,13 @@ 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))
|
||||
/// // Prints "[1, 2, 3]"
|
||||
/// try print(numbers.dropLast(10))
|
||||
/// // Prints "[]"
|
||||
/// ```swift
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropLast(2))
|
||||
/// // Prints "[1, 2, 3]"
|
||||
/// try print(numbers.dropLast(10))
|
||||
/// // Prints "[]"
|
||||
/// ```
|
||||
///
|
||||
/// - Parameter n: The number of elements to drop off the end of the
|
||||
/// cursor. `n` must be greater than or equal to zero.
|
||||
@@ -414,9 +527,11 @@ extension Cursor {
|
||||
///
|
||||
/// The following example drops the last element from a cursor of integers.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropLast())
|
||||
/// // Prints "[1, 2, 3, 4]"
|
||||
/// ```swift
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropLast())
|
||||
/// // Prints "[1, 2, 3, 4]"
|
||||
/// ```
|
||||
///
|
||||
/// If the cursor has no elements, the result is an empty cursor.
|
||||
///
|
||||
@@ -502,11 +617,13 @@ 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))
|
||||
/// // Prints "[1, 2]"
|
||||
/// try print(numbers.prefix(10))
|
||||
/// // Prints "[1, 2, 3, 4, 5]"
|
||||
/// ```swift
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.prefix(2))
|
||||
/// // Prints "[1, 2]"
|
||||
/// try print(numbers.prefix(10))
|
||||
/// // Prints "[1, 2, 3, 4, 5]"
|
||||
/// ```
|
||||
///
|
||||
/// - Parameter maxLength: The maximum number of elements to return. The
|
||||
/// value of `maxLength` must be greater than or equal to zero.
|
||||
@@ -562,11 +679,13 @@ 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))
|
||||
/// // Prints "[4, 5]"
|
||||
/// try print(numbers.suffix(10))
|
||||
/// // Prints "[1, 2, 3, 4, 5]"
|
||||
/// ```swift
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.suffix(2))
|
||||
/// // Prints "[4, 5]"
|
||||
/// try print(numbers.suffix(10))
|
||||
/// // Prints "[1, 2, 3, 4, 5]"
|
||||
/// ```
|
||||
///
|
||||
/// - Parameter maxLength: The maximum number of elements to return. The
|
||||
/// value of `maxLength` must be greater than or equal to zero.
|
||||
@@ -620,24 +739,16 @@ extension Cursor where Element: Equatable {
|
||||
extension Cursor where Element: Comparable {
|
||||
/// Returns the maximum element in the cursor.
|
||||
///
|
||||
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
|
||||
/// if its first argument should be ordered before its second
|
||||
/// argument; otherwise, `false`.
|
||||
/// - Returns: The cursor's maximum element, according to
|
||||
/// `areInIncreasingOrder`. If the cursor has no elements, returns
|
||||
/// `nil`.
|
||||
/// - Returns: The cursor's maximum element. If the cursor has no
|
||||
/// elements, returns `nil`.
|
||||
public func max() throws -> Element? {
|
||||
try max(by: <)
|
||||
}
|
||||
|
||||
/// Returns the minimum element in the cursor.
|
||||
///
|
||||
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
|
||||
/// if its first argument should be ordered before its second
|
||||
/// argument; otherwise, `false`.
|
||||
/// - Returns: The cursor's minimum element, according to
|
||||
/// `areInIncreasingOrder`. If the cursor has no elements, returns
|
||||
/// `nil`.
|
||||
/// - Returns: The cursor's minimum element. If the cursor has no
|
||||
/// elements, returns `nil`.
|
||||
public func min() throws -> Element? {
|
||||
try min(by: <)
|
||||
}
|
||||
|
||||
@@ -1313,11 +1313,33 @@ struct TableInfo: FetchableRecord {
|
||||
}
|
||||
}
|
||||
|
||||
enum SchemaObjectType: String {
|
||||
case index
|
||||
case table
|
||||
case trigger
|
||||
case view
|
||||
/// A value in the `type` column of `sqlite_master`.
|
||||
struct SchemaObjectType: Hashable, RawRepresentable, DatabaseValueConvertible {
|
||||
var rawValue: String
|
||||
init(rawValue: String) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
static let index = SchemaObjectType(rawValue: "index")
|
||||
static let table = SchemaObjectType(rawValue: "table")
|
||||
static let trigger = SchemaObjectType(rawValue: "trigger")
|
||||
static let view = SchemaObjectType(rawValue: "view")
|
||||
}
|
||||
|
||||
/// A row in `sqlite_master`.
|
||||
struct SchemaObject: Hashable, FetchableRecord {
|
||||
var type: SchemaObjectType
|
||||
var name: String
|
||||
var tbl_name: String?
|
||||
var sql: String?
|
||||
|
||||
init(row: Row) throws {
|
||||
// "rootpage" column is not always there: avoid using numerical indexes
|
||||
type = row["type"]
|
||||
name = row["name"]
|
||||
tbl_name = row["tbl_name"]
|
||||
sql = row["sql"]
|
||||
}
|
||||
}
|
||||
|
||||
/// All objects in a database schema (tables, views, indexes, triggers).
|
||||
@@ -1328,7 +1350,6 @@ struct SchemaInfo: Equatable {
|
||||
/// (case-insensitive).
|
||||
func containsObjectNamed(_ name: String, ofType type: SchemaObjectType) -> Bool {
|
||||
let name = name.lowercased()
|
||||
let type = type.rawValue
|
||||
return objects.contains {
|
||||
$0.type == type && $0.name.lowercased() == name
|
||||
}
|
||||
@@ -1341,15 +1362,12 @@ struct SchemaInfo: Equatable {
|
||||
func canonicalName(_ name: String, ofType type: SchemaObjectType) -> String? {
|
||||
let name = name.lowercased()
|
||||
return objects
|
||||
.first { $0.type == type.rawValue && $0.name.lowercased() == name }?
|
||||
.first { $0.type == type && $0.name.lowercased() == name }?
|
||||
.name
|
||||
}
|
||||
|
||||
private struct SchemaObject: Codable, Hashable, FetchableRecord {
|
||||
var type: String
|
||||
var name: String
|
||||
var tbl_name: String?
|
||||
var sql: String?
|
||||
func filter(_ isIncluded: (SchemaObject) -> Bool) -> Self {
|
||||
SchemaInfo(objects: objects.filter(isIncluded))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -94,6 +94,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
///
|
||||
/// ### Other Database Operations
|
||||
///
|
||||
/// - ``add(tokenizer:)``
|
||||
/// - ``backup(to:pagesPerStep:progress:)``
|
||||
/// - ``checkpoint(_:on:)``
|
||||
/// - ``clearSchemaCache()``
|
||||
@@ -312,8 +313,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
///
|
||||
/// See <doc:RecordTimestamps> for an example of usage.
|
||||
///
|
||||
/// Transaction dates, by default, are built from a new `Date()` instance.
|
||||
/// You can override this default behavior by configuring
|
||||
/// The transaction date, by default, is the start date of the current
|
||||
/// transaction. You can override this default behavior by configuring
|
||||
/// ``Configuration/transactionClock``.
|
||||
public var transactionDate: Date {
|
||||
get throws {
|
||||
|
||||
@@ -216,10 +216,12 @@ extension ResultCode: Sendable { }
|
||||
/// do {
|
||||
/// try player.insert(db)
|
||||
/// } catch let error as DatabaseError {
|
||||
/// switch error.resultCode {
|
||||
/// case ResultCode.SQLITE_CONSTRAINT_FOREIGNKEY:
|
||||
/// print(error) // prints debugging information
|
||||
///
|
||||
/// switch error {
|
||||
/// case DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY:
|
||||
/// // foreign key constraint error
|
||||
/// case ResultCode.SQLITE_CONSTRAINT:
|
||||
/// case DatabaseError.SQLITE_CONSTRAINT:
|
||||
/// // any other constraint error
|
||||
/// default:
|
||||
/// // any other database error
|
||||
|
||||
+109
-32
@@ -84,12 +84,20 @@ public final class DatabasePool {
|
||||
// > Many applications choose NORMAL when in WAL mode
|
||||
try db.execute(sql: "PRAGMA synchronous = NORMAL")
|
||||
|
||||
if !FileManager.default.fileExists(atPath: path + "-wal") {
|
||||
// Create the -wal file if it does not exist yet. This
|
||||
// avoids an SQLITE_CANTOPEN (14) error whenever a user
|
||||
// opens a pool to an existing non-WAL database, and
|
||||
// attempts to read from it.
|
||||
// See https://github.com/groue/GRDB.swift/issues/102
|
||||
// Make sure a non-empty wal file exists.
|
||||
//
|
||||
// The presence of the wal file avoids an SQLITE_CANTOPEN (14)
|
||||
// error when the user opens a pool and reads from it.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/102>.
|
||||
//
|
||||
// The non-empty wal file avoids an SQLITE_ERROR (1) error
|
||||
// when the user opens a pool and creates a wal snapshot
|
||||
// (which happens when starting a ValueObservation).
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1383>.
|
||||
let walPath = path + "-wal"
|
||||
if try FileManager.default.fileExists(atPath: walPath) == false
|
||||
|| (URL(fileURLWithPath: walPath).resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0) == 0
|
||||
{
|
||||
try db.inSavepoint {
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY);
|
||||
@@ -168,12 +176,15 @@ extension DatabasePool {
|
||||
|
||||
// MARK: - Memory management
|
||||
|
||||
/// Frees as much memory as possible, by disposing non-essential memory from
|
||||
/// the writer connection, and closing all reader connections.
|
||||
/// Frees as much memory as possible, by disposing non-essential memory.
|
||||
///
|
||||
/// This method is synchronous, and blocks the current thread until all
|
||||
/// database accesses are completed.
|
||||
///
|
||||
/// This method closes all read-only connections, unless the
|
||||
/// ``Configuration/persistentReadOnlyConnections`` configuration flag
|
||||
/// is set.
|
||||
///
|
||||
/// - warning: This method can prevent concurrent reads from executing,
|
||||
/// until it returns. Prefer ``releaseMemoryEventually()`` if you intend
|
||||
/// to keep on using the database while releasing memory.
|
||||
@@ -181,34 +192,50 @@ extension DatabasePool {
|
||||
// Release writer memory
|
||||
writer.sync { $0.releaseMemory() }
|
||||
|
||||
// Release readers memory by closing all connections.
|
||||
//
|
||||
// We must use a barrier in order to guarantee that memory has been
|
||||
// freed (reader connections closed) when the method exits, as
|
||||
// documented.
|
||||
//
|
||||
// Without the barrier, connections would only close _eventually_ (after
|
||||
// their eventual concurrent jobs have completed).
|
||||
readerPool?.barrier {
|
||||
readerPool?.removeAll()
|
||||
if configuration.persistentReadOnlyConnections {
|
||||
// Keep existing readers
|
||||
readerPool?.forEach { reader in
|
||||
reader.sync { $0.releaseMemory() }
|
||||
}
|
||||
} else {
|
||||
// Release readers memory by closing all connections.
|
||||
//
|
||||
// We must use a barrier in order to guarantee that memory has been
|
||||
// freed (reader connections closed) when the method exits, as
|
||||
// documented.
|
||||
//
|
||||
// Without the barrier, connections would only close _eventually_ (after
|
||||
// their eventual concurrent jobs have completed).
|
||||
readerPool?.barrier {
|
||||
readerPool?.removeAll()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Eventually frees as much memory as possible, by disposing non-essential
|
||||
/// memory from the writer connection, and closing all reader connections.
|
||||
/// Eventually frees as much memory as possible, by disposing
|
||||
/// non-essential memory.
|
||||
///
|
||||
/// This method eventually closes all read-only connections, unless the
|
||||
/// ``Configuration/persistentReadOnlyConnections`` configuration flag
|
||||
/// is set.
|
||||
///
|
||||
/// Unlike ``releaseMemory()``, this method does not prevent concurrent
|
||||
/// database accesses when it is executing. But it does not notify when
|
||||
/// non-essential memory has been freed.
|
||||
public func releaseMemoryEventually() {
|
||||
// Release readers memory by eventually closing all reader connections
|
||||
// (they will close after their current jobs have completed).
|
||||
readerPool?.removeAll()
|
||||
if configuration.persistentReadOnlyConnections {
|
||||
// Keep existing readers
|
||||
readerPool?.forEach { reader in
|
||||
reader.async { $0.releaseMemory() }
|
||||
}
|
||||
} else {
|
||||
// Release readers memory by eventually closing all reader connections
|
||||
// (they will close after their current jobs have completed).
|
||||
readerPool?.removeAll()
|
||||
}
|
||||
|
||||
// Release writer memory eventually.
|
||||
writer.async { db in
|
||||
db.releaseMemory()
|
||||
}
|
||||
writer.async { $0.releaseMemory() }
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
@@ -361,7 +388,7 @@ extension DatabasePool: DatabaseReader {
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")))
|
||||
value(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -405,7 +432,7 @@ extension DatabasePool: DatabaseReader {
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")))
|
||||
value(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -608,8 +635,12 @@ 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 invalidated: they will
|
||||
/// Eventual concurrent read-only accesses are not interrupted, and
|
||||
/// proceed until completion.
|
||||
///
|
||||
/// - This method closes all read-only connections, even if the
|
||||
/// ``Configuration/persistentReadOnlyConnections`` configuration flag
|
||||
/// is set.
|
||||
public func invalidateReadOnlyConnections() {
|
||||
readerPool?.removeAll()
|
||||
}
|
||||
@@ -640,6 +671,50 @@ extension DatabasePool: DatabaseReader {
|
||||
return readers.first { $0.onValidQueue }
|
||||
}
|
||||
|
||||
// MARK: - WAL Snapshot Transactions
|
||||
|
||||
// swiftlint:disable:next line_length
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
/// Returns a long-lived WAL snapshot transaction on a reader connection.
|
||||
func walSnapshotTransaction() throws -> WALSnapshotTransaction {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
return try WALSnapshotTransaction(onReader: reader, release: { isInsideTransaction in
|
||||
// Discard the connection if the transaction could not be
|
||||
// properly ended. If we'd reuse it, the next read would
|
||||
// fail because we'd fail starting a read transaction.
|
||||
releaseReader(isInsideTransaction ? .discard : .reuse)
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns a long-lived WAL snapshot transaction on a reader connection.
|
||||
///
|
||||
/// - important: The `completion` argument is executed in a serial
|
||||
/// dispatch queue, so make sure you use the transaction asynchronously.
|
||||
func asyncWALSnapshotTransaction(_ completion: @escaping (Result<WALSnapshotTransaction, Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
completion(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
}
|
||||
|
||||
readerPool.asyncGet { result in
|
||||
completion(result.flatMap { reader, releaseReader in
|
||||
Result {
|
||||
try WALSnapshotTransaction(onReader: reader, release: { isInsideTransaction in
|
||||
// Discard the connection if the transaction could not be
|
||||
// properly ended. If we'd reuse it, the next read would
|
||||
// fail because we'd fail starting a read transaction.
|
||||
releaseReader(isInsideTransaction ? .discard : .reuse)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
@@ -833,9 +908,11 @@ extension DatabasePool {
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// A ``DatabaseError`` of code `SQLITE_ERROR` is thrown if the SQLite
|
||||
/// database is not in the [WAL mode](https://www.sqlite.org/wal.html), or
|
||||
/// if this method is called from a database access where a write
|
||||
/// transaction is open.
|
||||
/// database is not in the [WAL mode](https://www.sqlite.org/wal.html),
|
||||
/// or if this method is called from a write transaction, or if the
|
||||
/// wal file is missing or truncated (size zero).
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/snapshot_get.html>
|
||||
public func makeSnapshotPool() throws -> DatabaseSnapshotPool {
|
||||
try unsafeReentrantRead { db in
|
||||
try DatabaseSnapshotPool(db)
|
||||
|
||||
@@ -225,21 +225,22 @@ extension DatabaseQueue: DatabaseReader {
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
writer.async { db in
|
||||
do {
|
||||
// The transaction guarantees snapshot isolation against eventual
|
||||
// external connection.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.beginReadOnly()
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
return
|
||||
defer {
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.commit()
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
|
||||
value(.success(db))
|
||||
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.endReadOnly()
|
||||
try? db.commit()
|
||||
do {
|
||||
// Enter read-only mode before starting a transaction, so that the
|
||||
// transaction commit does not trigger database observation.
|
||||
// See <https://github.com/groue/GRDB.swift/pull/1213>.
|
||||
try db.beginReadOnly()
|
||||
try db.beginTransaction(.deferred)
|
||||
value(.success(db))
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -273,20 +274,23 @@ extension DatabaseQueue: DatabaseReader {
|
||||
writer.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
|
||||
|
||||
do {
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.beginReadOnly()
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
return
|
||||
|
||||
defer {
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.commit()
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
|
||||
value(.success(db))
|
||||
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.endReadOnly()
|
||||
try? db.commit()
|
||||
do {
|
||||
// Enter read-only mode before starting a transaction, so that the
|
||||
// transaction commit does not trigger database observation.
|
||||
// See <https://github.com/groue/GRDB.swift/pull/1213>.
|
||||
try db.beginReadOnly()
|
||||
try db.beginTransaction(.deferred)
|
||||
value(.success(db))
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,109 +3,6 @@ import Combine
|
||||
#endif
|
||||
import Foundation
|
||||
|
||||
/// `DatabaseRegionObservation` tracks transactions that modify a
|
||||
/// database region.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// Tracked changes are 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).
|
||||
///
|
||||
/// Changes to internal system tables (such as `sqlite_master`) and changes to
|
||||
/// [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables are
|
||||
/// not notified.
|
||||
///
|
||||
/// `DatabaseRegionObservation` calls your application right after changes have
|
||||
/// been committed in the database, and before any other thread had any
|
||||
/// opportunity to perform further changes. *This is a pretty strong guarantee,
|
||||
/// that most applications do not really need.* Instead, most applications
|
||||
/// prefer to be notified with fresh values: make sure you check
|
||||
/// ``ValueObservation`` before using `DatabaseRegionObservation`.
|
||||
///
|
||||
/// ## DatabaseRegionObservation Usage
|
||||
///
|
||||
/// Create a `DatabaseRegionObservation` with one or several requests to track:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Tracks the full player table
|
||||
/// 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
|
||||
/// // Handle error
|
||||
/// } onChange: { (db: Database) in
|
||||
/// print("Players were changed")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Enjoy the changes notifications:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// try Player(name: "Arthur").insert(db)
|
||||
/// }
|
||||
/// // Prints "Players were changed"
|
||||
/// ```
|
||||
///
|
||||
/// You stop the observation by calling the ``DatabaseCancellable/cancel()``
|
||||
/// method on the object returned by the `start` method. Cancellation is
|
||||
/// automatic when the cancellable is deallocated:
|
||||
///
|
||||
/// ```swift
|
||||
/// cancellable.cancel()
|
||||
/// ```
|
||||
///
|
||||
/// `DatabaseRegionObservation` can also be turned into a Combine publisher, or
|
||||
/// an RxSwift observable (see the companion library
|
||||
/// [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB)):
|
||||
///
|
||||
/// ```swift
|
||||
/// let cancellable = observation.publisher(in: dbQueue).sink { completion in
|
||||
/// // Handle completion
|
||||
/// } receiveValue: { (db: Database) in
|
||||
/// print("Players were changed")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// You can feed `DatabaseRegionObservation` with any type that conforms to
|
||||
/// the ``DatabaseRegionConvertible`` protocol: ``FetchRequest``,
|
||||
/// ``DatabaseRegion``, ``Table``, etc. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Observe the score column of the 'player' table
|
||||
/// let observation = DatabaseRegionObservation(
|
||||
/// tracking: Player.select(Column("score")))
|
||||
///
|
||||
/// // Observe the 'score' column of the 'player' table
|
||||
/// let observation = DatabaseRegionObservation(
|
||||
/// tracking: SQLRequest("SELECT score FROM player"))
|
||||
///
|
||||
/// // Observe both the 'player' and 'team' tables
|
||||
/// let observation = DatabaseRegionObservation(
|
||||
/// tracking: Table("player"), Table("team"))
|
||||
///
|
||||
/// // Observe the full database
|
||||
/// let observation = DatabaseRegionObservation(
|
||||
/// tracking: .fullDatabase)
|
||||
/// ```
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating DatabaseRegionObservation
|
||||
///
|
||||
/// - ``init(tracking:)-5ldbe``
|
||||
/// - ``init(tracking:)-2nqjd``
|
||||
///
|
||||
/// ### Observing Database Transactions
|
||||
///
|
||||
/// - ``publisher(in:)``
|
||||
/// - ``start(in:onError:onChange:)``
|
||||
public struct DatabaseRegionObservation {
|
||||
/// A closure that is evaluated when the observation starts, and returns
|
||||
/// the observed database region.
|
||||
|
||||
@@ -108,12 +108,10 @@ public final class DatabaseSnapshotPool {
|
||||
/// assert(count == 0)
|
||||
/// ```
|
||||
///
|
||||
/// If any of the following statements are false when the snapshot is
|
||||
/// created, a ``DatabaseError`` of code `SQLITE_ERROR` is thrown:
|
||||
///
|
||||
/// - The database connection must be in the
|
||||
/// [WAL mode](https://www.sqlite.org/wal.html).
|
||||
/// - There must not be a write transaction open.
|
||||
/// A ``DatabaseError`` of code `SQLITE_ERROR` is thrown if the SQLite
|
||||
/// database is not in the [WAL mode](https://www.sqlite.org/wal.html),
|
||||
/// or if this method is called from a write transaction, or if the
|
||||
/// wal file is missing or truncated (size zero).
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/snapshot_get.html>
|
||||
///
|
||||
@@ -175,9 +173,9 @@ public final class DatabaseSnapshotPool {
|
||||
/// let snapshot = try DatabaseSnapshotPool(path: "/path/to/database.sqlite")
|
||||
/// ```
|
||||
///
|
||||
/// If the database at `path` is not in the
|
||||
/// [WAL mode](https://www.sqlite.org/wal.html), a ``DatabaseError`` of code
|
||||
/// `SQLITE_ERROR` is thrown.
|
||||
/// A ``DatabaseError`` of code `SQLITE_ERROR` is thrown if the SQLite
|
||||
/// database is not in the [WAL mode](https://www.sqlite.org/wal.html),
|
||||
/// or if the wal file is missing or truncated (size zero).
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/snapshot_get.html>
|
||||
///
|
||||
@@ -294,7 +292,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")))
|
||||
value(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -188,6 +188,34 @@ extension DatabaseValue: StatementBinding {
|
||||
return data.bind(to: sqliteStatement, at: index)
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls the given closure after binding a statement argument.
|
||||
///
|
||||
/// The binding is valid only during the execution of this method.
|
||||
///
|
||||
/// - 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 {
|
||||
switch storage {
|
||||
case .null:
|
||||
let code = sqlite3_bind_null(sqliteStatement, index)
|
||||
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
|
||||
return try body()
|
||||
case .int64(let int64):
|
||||
let code = int64.bind(to: sqliteStatement, at: index)
|
||||
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
|
||||
return try body()
|
||||
case .double(let double):
|
||||
let code = double.bind(to: sqliteStatement, at: index)
|
||||
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
|
||||
return try body()
|
||||
case .string(let 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValue: Sendable { }
|
||||
|
||||
@@ -1,49 +1,38 @@
|
||||
/// A type that can convert itself into and out of a database value.
|
||||
///
|
||||
/// `DatabaseValueConvertible` is adopted by `Bool`, `Int`, `String`,
|
||||
/// `Date`, etc.
|
||||
///
|
||||
/// To conform to `DatabaseValueConvertible`, provide custom implementations
|
||||
/// for ``fromDatabaseValue(_:)-21zzv`` and ``databaseValue-1ob9k``. These
|
||||
/// implementations are ready-made for `RawRepresentable` types whose
|
||||
/// `RawValue` is `StatementColumnConvertible`, and for `Codable` types.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a Value
|
||||
///
|
||||
/// - ``fromDatabaseValue(_:)-21zzv``
|
||||
/// - ``fromMissingColumn()-7iamp``
|
||||
///
|
||||
/// ### Accessing the DatabaseValue
|
||||
///
|
||||
/// - ``databaseValue-1ob9k``
|
||||
///
|
||||
/// ### Fetching Values from Raw SQL
|
||||
///
|
||||
/// - ``fetchCursor(_:sql:arguments:adapter:)-6elcz``
|
||||
/// - ``fetchAll(_:sql:arguments:adapter:)-1cqyb``
|
||||
/// - ``fetchSet(_:sql:arguments:adapter:)-5jene``
|
||||
/// - ``fetchOne(_:sql:arguments:adapter:)-qvqp``
|
||||
///
|
||||
/// ### Fetching Values from a Prepared Statement
|
||||
///
|
||||
/// - ``fetchCursor(_:arguments:adapter:)-4l6af``
|
||||
/// - ``fetchAll(_:arguments:adapter:)-3abuc``
|
||||
/// - ``fetchSet(_:arguments:adapter:)-6y54n``
|
||||
/// - ``fetchOne(_:arguments:adapter:)-3d7ax``
|
||||
///
|
||||
/// ### Fetching Values from a Request
|
||||
///
|
||||
/// - ``fetchCursor(_:_:)-8q4r6``
|
||||
/// - ``fetchAll(_:_:)-9hkqs``
|
||||
/// - ``fetchSet(_:_:)-1foke``
|
||||
/// - ``fetchOne(_:_:)-o6yj``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``DatabaseValueCursor``
|
||||
/// - ``StatementBinding``
|
||||
// Standard collections `Array`, `Set`, and `Dictionary` do not conform to
|
||||
// `DatabaseValueConvertible`, on purpose.
|
||||
//
|
||||
// Adding `DatabaseValueConvertible` conformance to those collection types
|
||||
// would litter JSON values in unexpected places, and foster misuse. For
|
||||
// example, it is better when the code below *does not compile*:
|
||||
//
|
||||
// ```swift
|
||||
// // MISUSE: if Array would conform to DatabaseValueConvertible, this
|
||||
// // code would compile, and run the incorrect SQLite query
|
||||
// // `SELECT ... WHERE id IN ('[1,2,3]')`, instead of the expected
|
||||
// // `SELECT ... WHERE id IN (1, 2, 3)`.
|
||||
// let ids = [1, 2, 3]
|
||||
// let players = try Player.fetchAll(db, sql: """
|
||||
// SELECT * FROM player WHERE id IN (?)
|
||||
// """, arguments: [ids])
|
||||
// ```
|
||||
//
|
||||
// Correct and fostered versions of the code above are:
|
||||
//
|
||||
// ```swift
|
||||
// // CORRECT (explicit SQLite arguments):
|
||||
// let ids = [1, 2, 3]
|
||||
// let questionMarks = databaseQuestionMarks(count: ids.count) // "?,?,?"
|
||||
// let players = try Player.fetchAll(db, sql: """
|
||||
// SELECT * FROM player WHERE id IN (\(questionMarks))
|
||||
// """, arguments: StatementArguments(ids))
|
||||
//
|
||||
// // CORRECT (SQL interpolation):
|
||||
// let ids = [1, 2, 3]
|
||||
// let request: SQLRequest<Player> = """
|
||||
// SELECT * FROM player WHERE id IN \(ids)
|
||||
// """
|
||||
// let players = try request.fetchAll(db)
|
||||
// ```
|
||||
public protocol DatabaseValueConvertible: SQLExpressible, StatementBinding {
|
||||
/// A database value.
|
||||
var databaseValue: DatabaseValue { get }
|
||||
@@ -167,7 +156,7 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
|
||||
}
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
try statement.reset(withArguments: arguments)
|
||||
try statement.prepareExecution(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
|
||||
@@ -289,14 +289,13 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// ```
|
||||
///
|
||||
/// - note: Usage of this method is discouraged, because waiting on the
|
||||
/// returned ``DatabaseFuture`` blocks a thread. You may prefer the
|
||||
/// asynchronous version of this method: ``spawnConcurrentRead(_:)``.
|
||||
/// returned ``DatabaseFuture`` blocks a thread. You may prefer
|
||||
/// ``spawnConcurrentRead(_:)`` instead.
|
||||
/// - parameter value: A closure which accesses the database.
|
||||
func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T>
|
||||
|
||||
// Exposed for RxGRDB and GRBCombine. Naming is not stabilized.
|
||||
/// Schedules read-only database operations for execution, and
|
||||
/// returns immediately.
|
||||
/// Schedules read-only database operations for execution.
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
@@ -311,7 +310,7 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// by the database writer.
|
||||
///
|
||||
/// In the example below, the number of players is fetched concurrently with
|
||||
/// the player insertion. Yet the future is guaranteed to return zero:
|
||||
/// the player insertion. Yet it is guaranteed to return zero:
|
||||
///
|
||||
/// ```swift
|
||||
/// try writer.writeWithoutTransaction { db in
|
||||
@@ -334,6 +333,10 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - important: The database operations are executed immediately,
|
||||
/// or asynchronously, depending on the actual class
|
||||
/// of `DatabaseWriter`.
|
||||
///
|
||||
/// - parameter value: A closure which accesses the database. Its argument
|
||||
/// is a `Result` that provides the database connection, or the failure
|
||||
/// that would prevent establishing the read access to the database.
|
||||
@@ -465,7 +468,7 @@ extension DatabaseWriter {
|
||||
|
||||
// MARK: - Erasing the content of the database
|
||||
|
||||
/// Erases the content of the database.
|
||||
/// Erase the database: delete all content, drop all tables, etc.
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func erase() throws {
|
||||
try barrierWriteWithoutTransaction { try $0.erase() }
|
||||
@@ -684,7 +687,7 @@ extension DatabaseWriter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Erases the content of the database.
|
||||
/// Erase the database: delete all content, drop all tables, etc.
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
|
||||
@@ -58,10 +58,6 @@
|
||||
/// - ``makePreparedRequest(_:forSingleResult:)``
|
||||
/// - ``PreparedRequest``
|
||||
///
|
||||
/// ### Database Observation Support
|
||||
///
|
||||
/// - ``databaseRegion(_:)``
|
||||
///
|
||||
/// ### Adapting the Fetched Rows
|
||||
///
|
||||
/// - ``adapted(_:)``
|
||||
@@ -141,7 +137,9 @@ extension FetchRequest {
|
||||
/// Returns an adapted request.
|
||||
///
|
||||
/// The returned request performs an identical database query, but adapts
|
||||
/// the fetched rows. See ``RowAdapter``.
|
||||
/// the fetched rows. See ``RowAdapter``, and
|
||||
/// ``splittingRowAdapters(columnCounts:)`` for a sample code that uses
|
||||
/// `adapted(_:)`.
|
||||
///
|
||||
/// - parameter adapter: A closure that accepts a database connection and
|
||||
/// returns a row adapter.
|
||||
@@ -215,8 +213,8 @@ public struct AnyFetchRequest<RowDecoder> {
|
||||
///
|
||||
/// // AnyFetchRequest<Row>
|
||||
/// let rowRequest = playerRequest.asRequest(of: Row.self)
|
||||
public func asRequest<RowDecoder>(of type: RowDecoder.Type) -> AnyFetchRequest<RowDecoder> {
|
||||
AnyFetchRequest<RowDecoder>(request: request)
|
||||
public func asRequest<T>(of type: T.Type) -> AnyFetchRequest<T> {
|
||||
AnyFetchRequest<T>(request: request)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-5
@@ -1152,8 +1152,7 @@ extension Row {
|
||||
/// Nil is returned if the scope is not available, or contains only
|
||||
/// null values.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support>
|
||||
/// for more information.
|
||||
/// See ``splittingRowAdapters(columnCounts:)`` for a sample code.
|
||||
func decodeIfPresent<Record: FetchableRecord>(
|
||||
_ type: Record.Type = Record.self,
|
||||
forKey scope: String)
|
||||
@@ -1194,8 +1193,7 @@ extension Row {
|
||||
/// A fatal error is raised if the scope is not available, or contains only
|
||||
/// null values.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support>
|
||||
/// for more information.
|
||||
/// See ``splittingRowAdapters(columnCounts:)`` for a sample code.
|
||||
func decode<Record: FetchableRecord>(
|
||||
_ type: Record.Type = Record.self,
|
||||
forKey scope: String)
|
||||
@@ -1366,7 +1364,7 @@ public final class RowCursor: DatabaseCursor {
|
||||
self._row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
try statement.reset(withArguments: arguments)
|
||||
try statement.prepareExecution(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
|
||||
+295
-68
@@ -1,27 +1,137 @@
|
||||
import Foundation
|
||||
|
||||
/// Returns an array of row adapters that split a row according to the input
|
||||
/// number of columns.
|
||||
/// Returns an array of row adapters that split a row according to the
|
||||
/// provided numbers of columns.
|
||||
///
|
||||
/// For example:
|
||||
/// This method is useful for splitting a row into chunks.
|
||||
///
|
||||
/// For example, let's consider the following SQL query:
|
||||
///
|
||||
/// ```swift
|
||||
/// let sql = "SELECT 1, 2,3,4, 5,6, 7,8"
|
||||
/// // <.><. . .><. .><. .>
|
||||
/// let adapters = splittingRowAdapters([1, 3, 2])
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "a": adapters[0],
|
||||
/// "b": adapters[1],
|
||||
/// "c": adapters[2],
|
||||
/// "d": adapters[3]])
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// row.scopes["a"] // [1]
|
||||
/// row.scopes["b"] // [2, 3, 4]
|
||||
/// row.scopes["c"] // [5, 6]
|
||||
/// row.scopes["d"] // [7, 8]
|
||||
/// let sql = """
|
||||
/// SELECT player.*, team.*
|
||||
/// FROM player
|
||||
/// LEFT JOIN team ON team.id = player.teamId
|
||||
/// WHERE player.id = ?
|
||||
/// """
|
||||
/// ```
|
||||
///
|
||||
/// The resulting rows contains columns from both player and team tables:
|
||||
///
|
||||
/// ```swift
|
||||
/// // [id: 1, name: "Arthur", teamId: 42, id: 42, name: "Reds"]
|
||||
/// // <---------------------------------><-------------------->
|
||||
/// // player columns team columns
|
||||
/// let row = try Row.fetchOne(db, sql: sql, arguments: [1])
|
||||
/// ```
|
||||
///
|
||||
/// Because some columns have the same name (`id` and `name`), it is
|
||||
/// difficult to access the team columns.
|
||||
///
|
||||
/// `splittingRowAdapters` and ``ScopeAdapter`` make it possible to
|
||||
/// access player and team columns independently, with row ``Row/scopes``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let adapters = try splittingRowAdapters([
|
||||
/// db.columns(in: "player").count,
|
||||
/// db.columns(in: "team").count,
|
||||
/// ])
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "player": adapters[0],
|
||||
/// "team": adapters[1],
|
||||
/// ])
|
||||
/// if let row = try Row.fetchOne(db, sql: sql, arguments: [1], adapter: adapter) {
|
||||
/// // A Row that only contains player columns
|
||||
/// // [id: 1, name: "Arthur", teamId: 42]
|
||||
/// row.scopes["player"]
|
||||
///
|
||||
/// // A Row that only contains team columns
|
||||
/// // [id: 42, name: "Reds"]
|
||||
/// row.scopes["team"]
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Decoding ``FetchableRecord`` types is easy:
|
||||
///
|
||||
/// ```swift
|
||||
/// if let row = try Row.fetchOne(db, sql: sql, arguments: [1], adapter: adapter) {
|
||||
/// // Player(id: 1, name: "Arthur", teamId: 42)
|
||||
/// let player: Player = row["player"]
|
||||
///
|
||||
/// // Team(id: 42, name: "Reds")
|
||||
/// // nil if the LEFT JOIN has fetched NULL team columns
|
||||
/// if 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:
|
||||
///
|
||||
/// - Support for record types that customize their fetched columns
|
||||
/// with ``TableRecord/databaseSelection-7iphs``.
|
||||
/// - ``SQLRequest`` and its support for [SQL Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md).
|
||||
/// - ``FetchRequest/adapted(_:)`` for building a request that embeds the
|
||||
/// row adapters.
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord, FetchableRecord { ... }
|
||||
/// struct Team: TableRecord, FetchableRecord { ... }
|
||||
///
|
||||
/// struct PlayerInfo {
|
||||
/// var player: Player
|
||||
/// var team: Team?
|
||||
/// }
|
||||
///
|
||||
/// extension PlayerInfo: FetchableRecord {
|
||||
/// init(row: Row) {
|
||||
/// player = row["player"]
|
||||
/// team = row["team"]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// extension PlayerInfo {
|
||||
/// /// The request for the player info, given a player id
|
||||
/// static func filter(playerId: Int64) -> some FetchRequest<PlayerInfo> {
|
||||
/// // Build SQL request with SQL interpolation
|
||||
/// let request: SQLRequest<PlayerInfo> = """
|
||||
/// SELECT
|
||||
/// \(columnsOf: Player.self), -- Instead of player.*
|
||||
/// \(columnsOf: Team.self), -- Instead of team.*
|
||||
/// FROM player
|
||||
/// LEFT JOIN team ON team.id = player.teamId
|
||||
/// WHERE player.id = \(playerId)
|
||||
/// """
|
||||
///
|
||||
/// // Returns an adapted request that defines the player and team
|
||||
/// // scopes in the fetched row
|
||||
/// return request.adapted { db in
|
||||
/// let adapters = try splittingRowAdapters(columnCounts: [
|
||||
/// Player.numberOfSelectedColumns(db),
|
||||
/// Team.numberOfSelectedColumns(db),
|
||||
/// ])
|
||||
/// return ScopeAdapter([
|
||||
/// "player": adapters[0],
|
||||
/// "team": adapters[1],
|
||||
/// ])
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Usage
|
||||
/// try dbQueue.read { db in
|
||||
/// if let playerInfo = try PlayerInfo.filter(playerId: 1).fetchOne(db) {
|
||||
/// print(playerInfo.player) // Player(id: 1, name: "Arthur", teamId: 42)
|
||||
/// print(playerInfo.team) // Team(id: 42, name: "Reds")
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter columnCounts: An array of row chunk lengths.
|
||||
/// - returns: An array of row adapters that split a row into as many chunks
|
||||
/// as the number of elements in `columnCounts`, plus one (the row adapter
|
||||
/// for all columns that remain on the right of the last chunk).
|
||||
public func splittingRowAdapters(columnCounts: [Int]) -> [any RowAdapter] {
|
||||
guard !columnCounts.isEmpty else {
|
||||
if columnCounts.isEmpty {
|
||||
// Identity adapter
|
||||
return [SuffixRowAdapter(fromIndex: 0)]
|
||||
}
|
||||
@@ -149,25 +259,57 @@ extension Statement: _RowLayout {
|
||||
|
||||
/// A type that helps two incompatible row interfaces working together.
|
||||
///
|
||||
/// You provide row adapters to methods that fetch. For example:
|
||||
/// Row adapters present database rows in the way expected by the
|
||||
/// row consumers.
|
||||
///
|
||||
/// For example, when a row consumer expects a column named "consumed", but
|
||||
/// the raw row has a column named "produced", the ``ColumnMapping`` row
|
||||
/// adapter comes in handy:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read {
|
||||
/// // An adapter that ignores the first two columns
|
||||
/// let adapter = SuffixRowAdapter(fromIndex: 2)
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
|
||||
/// // Feeds the "consumed" column from "produced":
|
||||
/// let adapter = ColumnMapping(["consumed": "produced"])
|
||||
/// let sql = "SELECT 'Hello' AS produced"
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
///
|
||||
/// // [baz:3]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// }
|
||||
/// // [consumed:"Hello"]
|
||||
/// print(row)
|
||||
///
|
||||
/// // "Hello"
|
||||
/// print(row["consumed"])
|
||||
/// ```
|
||||
///
|
||||
/// The raw fetched columns are not lost (see ``Row/unadapted``):
|
||||
///
|
||||
/// ```swift
|
||||
/// // ▿ [consumed:"Hello"]
|
||||
/// // unadapted: [produced:"Hello"]
|
||||
/// print(row.debugDescription)
|
||||
///
|
||||
/// // [produced:"Hello"]
|
||||
/// print(row.unadapted)
|
||||
/// ```
|
||||
///
|
||||
/// There are several situations where row adapters are useful. Among them:
|
||||
///
|
||||
/// - Adapters help disambiguate columns with identical names, which may
|
||||
/// happen when you select columns from several tables.
|
||||
/// See ``splittingRowAdapters(columnCounts:)`` for some sample code.
|
||||
///
|
||||
/// - Adapters help when SQLite outputs unexpected column names, which may
|
||||
/// happen with some subqueries. See ``RenameColumnAdapter`` for
|
||||
/// an example.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Splitting a Row
|
||||
/// ### Splitting a Row into Chunks
|
||||
///
|
||||
/// - ``splittingRowAdapters(columnCounts:)``
|
||||
///
|
||||
/// ### Adding Scopes to an Adapter
|
||||
///
|
||||
/// - ``addingScopes(_:)``
|
||||
///
|
||||
/// ### Built-in Adapters
|
||||
///
|
||||
/// - ``ColumnMapping``
|
||||
@@ -222,9 +364,22 @@ extension RowAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/// EmptyRowAdapter is a row adapter that hides all columns.
|
||||
/// `EmptyRowAdapter` is a row adapter that hides all columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let adapter = EmptyRowAdapter()
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c"
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
/// row.isEmpty // true
|
||||
/// ```
|
||||
///
|
||||
/// This limit adapter may turn out useful in some narrow use cases. You'll
|
||||
/// be happy to find it when you need it.
|
||||
public struct EmptyRowAdapter: RowAdapter {
|
||||
/// Creates an EmptyRowAdapter
|
||||
/// Creates an `EmptyRowAdapter`.
|
||||
public init() { }
|
||||
|
||||
public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter {
|
||||
@@ -232,19 +387,28 @@ public struct EmptyRowAdapter: RowAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/// ColumnMapping is a row adapter that maps column names.
|
||||
/// `ColumnMapping` is a row adapter that maps column names.
|
||||
///
|
||||
/// let adapter = ColumnMapping(["foo": "bar"])
|
||||
/// let sql = "SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz"
|
||||
/// Build a `ColumnMapping` with a dictionary whose keys
|
||||
/// are adapted column names, and values the column names in the base row:
|
||||
///
|
||||
/// // [foo:"bar"]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// ```swift
|
||||
/// // Feeds "newA" from "a", and "newB" from "b":
|
||||
/// let adapter = ColumnMapping(["newA": "a", "newB": "b"])
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c"
|
||||
///
|
||||
/// // [newA:0, newB:1]
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
/// ```
|
||||
///
|
||||
/// Note that columns that are not present in the dictionary are not present
|
||||
/// in the resulting adapted row.
|
||||
public struct ColumnMapping: RowAdapter {
|
||||
/// A dictionary from mapped column names to column names in a base row.
|
||||
let mapping: [String: String]
|
||||
|
||||
/// Creates a ColumnMapping with a dictionary from mapped column names to
|
||||
/// column names in a base row.
|
||||
/// Creates a `ColumnMapping` with a dictionary from mapped column names
|
||||
/// to column names in a base row.
|
||||
public init(_ mapping: [String: String]) {
|
||||
self.mapping = mapping
|
||||
}
|
||||
@@ -269,13 +433,17 @@ public struct ColumnMapping: RowAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/// SuffixRowAdapter is a row adapter that hides the first columns in a row.
|
||||
/// `SuffixRowAdapter` hides the leftmost columns in a row.
|
||||
///
|
||||
/// let adapter = SuffixRowAdapter(fromIndex: 2)
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
|
||||
/// For example:
|
||||
///
|
||||
/// // [baz:3]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// ```swift
|
||||
/// let adapter = SuffixRowAdapter(fromIndex: 2)
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d"
|
||||
///
|
||||
/// // [c:2, d: 3]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
/// ```
|
||||
public struct SuffixRowAdapter: RowAdapter {
|
||||
/// The suffix index
|
||||
let index: Int
|
||||
@@ -294,13 +462,17 @@ public struct SuffixRowAdapter: RowAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/// RangeRowAdapter is a row adapter that only exposes a range of columns.
|
||||
/// `RangeRowAdapter` is a row adapter that only exposes a range of columns.
|
||||
///
|
||||
/// let adapter = RangeRowAdapter(1..<3)
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz, 4 as qux"
|
||||
/// For example:
|
||||
///
|
||||
/// // [bar:2 baz:3]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// ```swift
|
||||
/// let adapter = RangeRowAdapter(1..<3)
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d"
|
||||
///
|
||||
/// // [b:1 c:2]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// ```
|
||||
public struct RangeRowAdapter: RowAdapter {
|
||||
/// The range
|
||||
let range: CountableRange<Int>
|
||||
@@ -322,28 +494,65 @@ public struct RangeRowAdapter: RowAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/// `ScopeAdapter` is a row adapter that lets you define scopes on rows.
|
||||
/// `ScopeAdapter` is a row adapter that defines row scopes.
|
||||
///
|
||||
/// // Two adapters
|
||||
/// let fooAdapter = ColumnMapping(["value": "foo"])
|
||||
/// let barAdapter = ColumnMapping(["value": "bar"])
|
||||
/// `ScopeAdapter` does not change the columns and values of the fetched
|
||||
/// row. Instead, it defines *scopes* based on other adapter, which you
|
||||
/// access through the ``Row/scopes`` property of the fetched rows.
|
||||
///
|
||||
/// // Define scopes
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "foo": fooAdapter,
|
||||
/// "bar": barAdapter])
|
||||
/// For example:
|
||||
///
|
||||
/// // Fetch
|
||||
/// let sql = "SELECT 'foo' AS foo, 'bar' AS bar"
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
/// ```swift
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "left": RangeRowAdapter(0..<2),
|
||||
/// "right": RangeRowAdapter(2..<4)])
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d"
|
||||
///
|
||||
/// // Scoped rows:
|
||||
/// if let fooRow = row.scopes["foo"] {
|
||||
/// fooRow["value"] // "foo"
|
||||
/// }
|
||||
/// if let barRow = row.scopes["bar"] {
|
||||
/// barRow["value"] // "bar"
|
||||
/// }
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
///
|
||||
/// row // [a:0 b:1 c:2 d:3]
|
||||
/// row.scopes["left"] // [a:0 b:1]
|
||||
/// row.scopes["right"] // [c:2 d:3]
|
||||
/// row.scopes["missing"] // nil
|
||||
/// ```
|
||||
///
|
||||
/// Scopes can be nested:
|
||||
///
|
||||
/// ```swift
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "left": ScopeAdapter([
|
||||
/// "left": RangeRowAdapter(0..<1),
|
||||
/// "right": RangeRowAdapter(1..<2)]),
|
||||
/// "right": ScopeAdapter([
|
||||
/// "left": RangeRowAdapter(2..<3),
|
||||
/// "right": RangeRowAdapter(3..<4)])
|
||||
/// ])
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d"
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
///
|
||||
/// let leftRow = row.scopes["left"]!
|
||||
/// leftRow.scopes["left"] // [a:0]
|
||||
/// leftRow.scopes["right"] // [b:1]
|
||||
///
|
||||
/// let rightRow = row.scopes["right"]!
|
||||
/// rightRow.scopes["left"] // [c:2]
|
||||
/// rightRow.scopes["right"] // [d:3]
|
||||
/// ```
|
||||
///
|
||||
/// Any adapter can be extended with scopes, with
|
||||
/// ``RowAdapter/addingScopes(_:)``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let baseAdapter = RangeRowAdapter(0..<2)
|
||||
/// let adapter = baseAdapter.addingScopes([
|
||||
/// "remainder": SuffixRowAdapter(fromIndex: 2)
|
||||
/// ])
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d"
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
///
|
||||
/// row // [a:0 b:1]
|
||||
/// row.scopes["remainder"] // [c:2 d:3]
|
||||
/// ```
|
||||
public struct ScopeAdapter: RowAdapter {
|
||||
|
||||
/// The base adapter
|
||||
@@ -363,7 +572,7 @@ public struct ScopeAdapter: RowAdapter {
|
||||
///
|
||||
/// - parameter scopes: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
public init(_ scopes: [String: RowAdapter]) {
|
||||
public init(_ scopes: [String: any RowAdapter]) {
|
||||
// Use SuffixRowAdapter(fromIndex: 0) as the identity adapter
|
||||
self.init(base: SuffixRowAdapter(fromIndex: 0), scopes: scopes)
|
||||
}
|
||||
@@ -423,11 +632,29 @@ struct ChainedAdapter: RowAdapter {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let adapter = RenameColumnAdapter { $0 + "rrr" }
|
||||
/// let sql = "SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz"
|
||||
/// ```swift
|
||||
/// let adapter = RenameColumnAdapter { column in column + "rrr" }
|
||||
/// let sql = "SELECT 0 AS a, 1 AS b, 2 AS c"
|
||||
///
|
||||
/// // [foorrr:"foo", barrrr:"bar", bazrrr:"baz"]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// // [arrr:0, brrr:1, crrr:2]
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
/// ```
|
||||
///
|
||||
/// This adapter is useful when subqueries contain duplicated column names:
|
||||
///
|
||||
/// ```swift
|
||||
/// let sql = "SELECT * FROM (SELECT 1 AS id, 2 AS id)"
|
||||
///
|
||||
/// // Prints ["id", "id:1"]
|
||||
/// // Note the "id:1" column, generated by SQLite.
|
||||
/// let row = try Row.fetchOne(db, sql: sql)!
|
||||
/// print(Array(row.columnNames))
|
||||
///
|
||||
/// // Drop the `:...` suffix, and prints ["id", "id"]
|
||||
/// let adapter = RenameColumnAdapter { String($0.prefix(while: { $0 != ":" })) }
|
||||
/// let adaptedRow = try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
/// print(Array(adaptedRow.columnNames))
|
||||
/// ```
|
||||
public struct RenameColumnAdapter: RowAdapter {
|
||||
let transform: (String) -> String
|
||||
|
||||
|
||||
+5
-3
@@ -39,6 +39,8 @@
|
||||
///
|
||||
/// - ``append(literal:)``
|
||||
/// - ``append(sql:arguments:)``
|
||||
/// - ``Swift/Collection/joined(separator:)``
|
||||
/// - ``Swift/Sequence/joined(separator:)``
|
||||
public struct SQL {
|
||||
/// `SQL.Element` is a component of an `SQL` literal.
|
||||
///
|
||||
@@ -316,12 +318,12 @@ extension SQL: SQLOrderingTerm {
|
||||
}
|
||||
|
||||
extension Sequence where Element == SQL {
|
||||
/// Returns the concatenated `SQL` literal of this sequence of literals,
|
||||
/// Concatenates the sequence elements into a new `SQL` literal,
|
||||
/// inserting the given raw SQL separator between each element.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```
|
||||
/// ```swift
|
||||
/// let components: [SQL] = [
|
||||
/// "UPDATE player",
|
||||
/// "SET name = \(name)",
|
||||
@@ -341,7 +343,7 @@ extension Sequence where Element == SQL {
|
||||
}
|
||||
|
||||
extension Collection where Element == SQL {
|
||||
/// Returns the concatenated `SQL` literal of this collection of literals,
|
||||
/// Concatenates the collection elements into a new `SQL` literal,
|
||||
/// inserting the given raw SQL separator between each element.
|
||||
///
|
||||
/// For example:
|
||||
|
||||
@@ -14,6 +14,9 @@ final class SerializedDatabase {
|
||||
/// The dispatch queue
|
||||
private let queue: DispatchQueue
|
||||
|
||||
/// If true, overrides `configuration.allowsUnsafeTransactions`.
|
||||
private var allowsUnsafeTransactions = false
|
||||
|
||||
init(
|
||||
path: String,
|
||||
configuration: Configuration = Configuration(),
|
||||
@@ -76,10 +79,25 @@ final class SerializedDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a block the serialized dispatch queue, and
|
||||
/// returns its result.
|
||||
/// Executes database operations, returns their result after they have
|
||||
/// finished executing, and allows or forbids long-lived transactions.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
/// This method is not reentrant.
|
||||
///
|
||||
/// - parameter allowingLongLivedTransaction: When true, the
|
||||
/// ``Configuration/allowsUnsafeTransactions`` configuration flag is
|
||||
/// ignored until this method is called again with false.
|
||||
func sync<T>(allowingLongLivedTransaction: Bool, _ body: (Database) throws -> T) rethrows -> T {
|
||||
try sync { db in
|
||||
self.allowsUnsafeTransactions = allowingLongLivedTransaction
|
||||
return try body(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes database operations, and returns their result after they
|
||||
/// have finished executing.
|
||||
///
|
||||
/// This method is not reentrant.
|
||||
func sync<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
// Three different cases:
|
||||
//
|
||||
@@ -122,8 +140,23 @@ final class SerializedDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a block the serialized dispatch queue, and
|
||||
/// returns its result.
|
||||
/// Executes database operations, returns their result after they have
|
||||
/// finished executing, and allows or forbids long-lived transactions.
|
||||
///
|
||||
/// This method is reentrant.
|
||||
///
|
||||
/// - parameter allowingLongLivedTransaction: When true, the
|
||||
/// ``Configuration/allowsUnsafeTransactions`` configuration flag is
|
||||
/// ignored until this method is called again with false.
|
||||
func reentrantSync<T>(allowingLongLivedTransaction: Bool, _ body: (Database) throws -> T) rethrows -> T {
|
||||
try reentrantSync { db in
|
||||
self.allowsUnsafeTransactions = allowingLongLivedTransaction
|
||||
return try body(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes database operations, and returns their result after they
|
||||
/// have finished executing.
|
||||
///
|
||||
/// This method is reentrant.
|
||||
func reentrantSync<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
@@ -189,7 +222,7 @@ final class SerializedDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Asynchronously executes a block in the serialized dispatch queue.
|
||||
/// Schedules database operations for execution, and returns immediately.
|
||||
func async(_ block: @escaping (Database) -> Void) {
|
||||
queue.async {
|
||||
block(self.db)
|
||||
@@ -242,7 +275,7 @@ final class SerializedDatabase {
|
||||
line: UInt = #line)
|
||||
{
|
||||
GRDBPrecondition(
|
||||
configuration.allowsUnsafeTransactions || !db.isInsideTransaction,
|
||||
allowsUnsafeTransactions || configuration.allowsUnsafeTransactions || !db.isInsideTransaction,
|
||||
message(),
|
||||
file: file,
|
||||
line: line)
|
||||
|
||||
+301
-108
@@ -25,59 +25,6 @@ extension String {
|
||||
}
|
||||
}
|
||||
|
||||
/// A prepared statement.
|
||||
///
|
||||
/// You create prepared statements from a ``Database`` instance. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// DELETE FROM player WHERE id = ?
|
||||
/// """)
|
||||
/// try statement.execute(arguments: [1])!
|
||||
/// try statement.execute(arguments: [12])!
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// To fetch rows and values from a prepared statement, use a fetching method of
|
||||
///``Row``, ``DatabaseValueConvertible``, or ``FetchableRecord``:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// SELECT name FROM player WHERE id = ?
|
||||
/// """)
|
||||
/// let name1 = try String.fetchOne(statement, arguments: [1])!
|
||||
/// let name2 = try String.fetchOne(statement, arguments: [12])!
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/stmt.html>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Executing a Prepared Statement
|
||||
///
|
||||
/// - ``execute(arguments:)``
|
||||
///
|
||||
/// ### Arguments
|
||||
///
|
||||
/// - ``arguments``
|
||||
/// - ``setArguments(_:)``
|
||||
/// - ``setUncheckedArguments(_:)``
|
||||
/// - ``validateArguments(_:)``
|
||||
/// - ``StatementArguments``
|
||||
///
|
||||
/// ### Statement Informations
|
||||
///
|
||||
/// - ``columnCount``
|
||||
/// - ``columnNames``
|
||||
/// - ``databaseRegion``
|
||||
/// - ``index(ofColumn:)``
|
||||
/// - ``isReadonly``
|
||||
/// - ``sql``
|
||||
/// - ``sqliteStatement``
|
||||
/// - ``SQLiteStatement``
|
||||
public final class Statement {
|
||||
enum TransactionEffect {
|
||||
case beginTransaction
|
||||
@@ -109,6 +56,20 @@ public final class Statement {
|
||||
// refined in `SQLQueryGenerator.makeStatement(_:)` when we have enough
|
||||
// information about the statement.
|
||||
/// The database region that the statement looks into.
|
||||
///
|
||||
/// The returned region describes the tables and columns read by
|
||||
/// the statement. It does not describe the columns that the statement
|
||||
/// writes into. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Reads score, writes bonus
|
||||
/// let statement = db.makeStatement(sql: """
|
||||
/// UPDATE player SET bonus = 0 WHERE score = 0
|
||||
/// """)
|
||||
///
|
||||
/// // Prints "player(score)"
|
||||
/// print(statement.databaseRegion)
|
||||
/// ```
|
||||
public internal(set) var databaseRegion = DatabaseRegion()
|
||||
|
||||
/// If true, the database schema cache gets invalidated after this statement
|
||||
@@ -209,25 +170,100 @@ public final class Statement {
|
||||
|
||||
// MARK: Arguments
|
||||
|
||||
private var argumentsNeedValidation = true
|
||||
/// Whether arguments are valid and bound inside the SQLite statement.
|
||||
///
|
||||
/// If true, arguments are considered valid, and they are bound in
|
||||
/// the SQLite statement:
|
||||
///
|
||||
/// - **Valid**: Arguments match the statement expectations, or the user has
|
||||
/// called ``setUncheckedArguments(_:)``.
|
||||
/// - **Bound**: The SQLite bindings are set. String and blob arguments
|
||||
/// are bound with SQLITE_TRANSIENT (copied and managed by SQLite).
|
||||
///
|
||||
/// When false, arguments have not been validated yet, or they are
|
||||
/// not bound.
|
||||
///
|
||||
/// - Not validated yet: this is the initial default (non-validated
|
||||
/// empty arguments)
|
||||
///
|
||||
/// ```swift
|
||||
/// // Default arguments are empty, argumentsAreValidAndBound is
|
||||
/// // false. The statement needs one argument.
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// INSERT INTO t VALUES (?)
|
||||
/// """)
|
||||
///
|
||||
/// // Because argumentsAreValidAndBound is false, we validate the
|
||||
/// // empty arguments, and throw SQLITE_MISUSE: wrong number
|
||||
/// // of statement arguments.
|
||||
/// try statement.execute()
|
||||
/// ```
|
||||
///
|
||||
/// - Not bound: this is the case after we have performed an optimized
|
||||
/// execution with temporary bindings that avoid copying strings
|
||||
/// and blobs:
|
||||
///
|
||||
/// ```swift
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// INSERT INTO t VALUES (?)
|
||||
/// """)
|
||||
/// // Arguments are set, and execution is performed with
|
||||
/// // temporary bindings.
|
||||
/// try statement.execute(arguments: ["Hello"])
|
||||
/// // <- Here statement.arguments is ["Hello"]
|
||||
/// // <- Here statement.argumentsAreValidAndBound is false
|
||||
/// ```
|
||||
///
|
||||
/// See `withArguments(_:do:)`.
|
||||
private var argumentsAreValidAndBound = false
|
||||
|
||||
/// The statement arguments. They may be bound, or not, in the SQLite
|
||||
/// statement. See `argumentsAreValidAndBound`.
|
||||
private var _arguments = StatementArguments()
|
||||
|
||||
lazy var sqliteArgumentCount: Int = {
|
||||
Int(sqlite3_bind_parameter_count(self.sqliteStatement))
|
||||
}()
|
||||
|
||||
// Returns ["id", nil", "name"] for "INSERT INTO table VALUES (:id, ?, :name)"
|
||||
// Returns ["id", nil, "name"] for "INSERT INTO table VALUES (:id, ?, :name)"
|
||||
fileprivate lazy var sqliteArgumentNames: [String?] = {
|
||||
(0..<CInt(self.sqliteArgumentCount)).map {
|
||||
guard let cString = sqlite3_bind_parameter_name(self.sqliteStatement, $0 + 1) else {
|
||||
(1..<CInt(sqliteArgumentCount + 1)).map {
|
||||
guard let cString = sqlite3_bind_parameter_name(sqliteStatement, $0) else {
|
||||
return nil
|
||||
}
|
||||
return String(String(cString: cString).dropFirst()) // Drop initial ":", "@", "$"
|
||||
return String(cString: cString + 1) // Drop initial ":", "@", "$"
|
||||
}
|
||||
}()
|
||||
|
||||
/// The statement arguments.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // This statement expects two arguments
|
||||
/// let statement = try db.makeUpdateArgument(sql: """
|
||||
/// INSERT INTO player (id, name) VALUES (?, ?)
|
||||
/// """)
|
||||
///
|
||||
/// // Set arguments
|
||||
/// statement.arguments = [1, "Arthur"]
|
||||
///
|
||||
/// // Prints [1, "Arthur"]
|
||||
/// print(statement.arguments)
|
||||
/// ```
|
||||
///
|
||||
/// If is a programmer error to set arguments that do not provide all
|
||||
/// values expected by the statement:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Fatal error
|
||||
/// statement.arguments = [1]
|
||||
/// statement.arguments = [1, "Arthur", Date()]
|
||||
/// ```
|
||||
///
|
||||
/// Prefer ``setArguments(_:)`` when you are not sure that
|
||||
/// arguments match, because it throws an error instead of raising a
|
||||
/// fatal error.
|
||||
public var arguments: StatementArguments {
|
||||
get { _arguments }
|
||||
set {
|
||||
@@ -237,12 +273,13 @@ public final class Statement {
|
||||
}
|
||||
}
|
||||
|
||||
/// Throws a ``DatabaseError`` of code `SQLITE_ERROR` if arguments don't
|
||||
/// fill all statement arguments.
|
||||
/// Throws a ``DatabaseError`` of code `SQLITE_ERROR` 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: """
|
||||
/// INSERT INTO player (id, name) VALUES (?, ?)
|
||||
/// """)
|
||||
@@ -251,7 +288,8 @@ public final class Statement {
|
||||
/// statement.validateArguments([1, "Arthur"])
|
||||
///
|
||||
/// // Throws
|
||||
/// statement.validateArguments([1])
|
||||
/// try statement.setArguments([1])
|
||||
/// try statement.setArguments([1, "Arthur", Date()])
|
||||
/// ```
|
||||
///
|
||||
/// See also ``setArguments(_:)``.
|
||||
@@ -264,12 +302,13 @@ public final class Statement {
|
||||
|
||||
/// Set arguments without any validation. Trades safety for performance.
|
||||
///
|
||||
/// Only call this method if you are sure input arguments match all expected
|
||||
/// arguments of the statement.
|
||||
/// Only call this method if you are sure input arguments provide all
|
||||
/// values expected by the statement.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // This statement expects two arguments
|
||||
/// let statement = try db.makeUpdateArgument(sql: """
|
||||
/// INSERT INTO player (id, name) VALUES (?, ?)
|
||||
/// """)
|
||||
@@ -278,18 +317,19 @@ public final class Statement {
|
||||
/// statement.setUncheckedArguments([1, "Arthur"])
|
||||
///
|
||||
/// // OK
|
||||
/// let arguments: StatementArguments = ... // some untrusted arguments
|
||||
/// let arguments = ... // some untrusted arguments
|
||||
/// try statement.validateArguments(arguments)
|
||||
/// statement.setUncheckedArguments(arguments)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// statement.setUncheckedArguments([1])
|
||||
/// statement.setUncheckedArguments([1, "Arthur", Date()])
|
||||
/// ```
|
||||
public func setUncheckedArguments(_ arguments: StatementArguments) {
|
||||
_arguments = arguments
|
||||
argumentsNeedValidation = false
|
||||
|
||||
// Reset and bind arguments
|
||||
try! reset()
|
||||
_arguments = arguments
|
||||
argumentsAreValidAndBound = true
|
||||
clearBindings()
|
||||
|
||||
var valuesIterator = arguments.values.makeIterator()
|
||||
@@ -302,14 +342,16 @@ public final class Statement {
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the statement arguments.
|
||||
/// Validates and sets the statement arguments.
|
||||
///
|
||||
/// This method throws a ``DatabaseError`` of code `SQLITE_ERROR` if
|
||||
/// arguments don't fill all statement arguments.
|
||||
/// This method 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: """
|
||||
/// INSERT INTO player (id, name) VALUES (?, ?)
|
||||
/// """)
|
||||
@@ -319,6 +361,7 @@ public final class Statement {
|
||||
///
|
||||
/// // Throws
|
||||
/// try statement.setArguments([1])
|
||||
/// try statement.setArguments([1, "Arthur", Date()])
|
||||
/// ```
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` if `arguments` don't fit the expected ones.
|
||||
@@ -327,16 +370,43 @@ public final class Statement {
|
||||
var consumedArguments = arguments
|
||||
let bindings = try consumedArguments.extractBindings(forStatement: self, allowingRemainingValues: false)
|
||||
|
||||
// Apply
|
||||
_arguments = arguments
|
||||
argumentsNeedValidation = false
|
||||
// Reset and bind arguments
|
||||
try reset()
|
||||
_arguments = arguments
|
||||
argumentsAreValidAndBound = true
|
||||
clearBindings()
|
||||
|
||||
for (index, dbValue) in zip(CInt(1)..., bindings) {
|
||||
bind(dbValue, at: index)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets, sets arguments, and calls the given closure after performing
|
||||
/// temporary bindings that avoid copying strings and blobs.
|
||||
///
|
||||
/// The bindings are valid only during the execution of this method.
|
||||
/// After it returns, the SQLite statement bindings are cleared (but the
|
||||
/// statement arguments are set).
|
||||
func withArguments<T>(_ arguments: StatementArguments, do body: () throws -> T) throws -> T {
|
||||
// Validate
|
||||
var consumedArguments = arguments
|
||||
let bindings = try consumedArguments.extractBindings(forStatement: self, allowingRemainingValues: false)
|
||||
|
||||
// Reset and bind arguments (temporarily)
|
||||
try reset()
|
||||
_arguments = arguments
|
||||
argumentsAreValidAndBound = false
|
||||
clearBindings()
|
||||
|
||||
defer {
|
||||
// Don't leave the SQLite statement in an invalid state
|
||||
// (temporary bindings that point to undefined memory).
|
||||
clearBindings()
|
||||
}
|
||||
|
||||
return try withBindings(bindings, to: sqliteStatement, do: body)
|
||||
}
|
||||
|
||||
// 1-based index
|
||||
func bind(_ value: some StatementBinding, at index: CInt) {
|
||||
let code = value.bind(to: sqliteStatement, at: index)
|
||||
@@ -369,14 +439,44 @@ public final class Statement {
|
||||
}
|
||||
}
|
||||
|
||||
func reset(withArguments arguments: StatementArguments?) throws {
|
||||
// Force arguments validity: it is a programmer error to provide
|
||||
// arguments that do not match the statement.
|
||||
if let arguments {
|
||||
try setArguments(arguments)
|
||||
} else if argumentsNeedValidation {
|
||||
/// Convenience method that resets, sets arguments if needed, and checks
|
||||
/// arguments validity.
|
||||
///
|
||||
/// - parameter newArguments: if not nil, this method sets arguments.
|
||||
func prepareExecution(withArguments newArguments: StatementArguments? = nil) throws {
|
||||
if let newArguments {
|
||||
try setArguments(newArguments) // calls reset()
|
||||
return
|
||||
}
|
||||
|
||||
if argumentsAreValidAndBound {
|
||||
try reset()
|
||||
try validateArguments(self.arguments)
|
||||
} else {
|
||||
// Arguments needs to be validated, or bound.
|
||||
if arguments.isEmpty {
|
||||
// Only reset and perform validation.
|
||||
try reset()
|
||||
try validateArguments(arguments)
|
||||
} else {
|
||||
// The `setArguments` method binds and validates, and that's
|
||||
// exactly what we want to do.
|
||||
//
|
||||
// To get there, perform statement.execute() after
|
||||
// statement.execute(arguments:):
|
||||
//
|
||||
// // Step 1
|
||||
// // Optimized execution with temporary bindings in order
|
||||
// // to avoid copying strings and blobs: after execution,
|
||||
// // arguments are set, but bindings have been cleared,
|
||||
// // and argumentsAreValidAndBound is false.
|
||||
// try statement.execute(arguments: StatementArguments(person)!)
|
||||
//
|
||||
// // Step 2 (we are here). Stop using temporary
|
||||
// // bindings because user explicitly opt ins for
|
||||
// // permanent ones.
|
||||
// try statement.execute()
|
||||
try setArguments(arguments) // calls reset()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -385,35 +485,83 @@ public final class Statement {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// try dbQueue.write { db in
|
||||
/// // Statement without argument
|
||||
/// let createTableStatement = try db.makeStatement(sql: """
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// CREATE TABLE player (
|
||||
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
/// name TEXT NOT NULL
|
||||
/// )
|
||||
/// """)
|
||||
/// try createTableStatement.execute()
|
||||
/// try statement.execute()
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// // Statement with argument
|
||||
/// let insertStatement = try db.makeStatement(sql: """
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?)
|
||||
/// """)
|
||||
///
|
||||
/// // Set argument and execute
|
||||
/// try insertStatement.setArguments(["Arthur"])
|
||||
/// try insertStatement.execute()
|
||||
/// try statement.setArguments(["Arthur"])
|
||||
/// try statement.execute()
|
||||
///
|
||||
/// // Set argument and execute in one shot
|
||||
/// try insertStatement.execute(arguments: ["Barbara"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When arguments are set at the moment of execution, with an 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.
|
||||
///
|
||||
/// For more information, see [`SQLITE_STATIC` and `SQLITE_TRANSIENT`](https://www.sqlite.org/c3ref/c_static.html).
|
||||
/// Compare:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Uses SQLITE_STATIC if there are few arguments,
|
||||
/// // SQLITE_TRANSIENT otherwise.
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// // Always uses SQLITE_TRANSIENT
|
||||
/// try statement.setArguments(["Arthur"])
|
||||
/// try statement.execute()
|
||||
/// ```
|
||||
///
|
||||
/// Both techniques have the same results, but when you care about
|
||||
/// performances, monitor your application in order to make the
|
||||
/// best choice.
|
||||
///
|
||||
/// - parameter arguments: Optional statement arguments.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func execute(arguments: StatementArguments? = nil) throws {
|
||||
try reset(withArguments: arguments)
|
||||
if let arguments {
|
||||
// Assume that the statement won't be reused with the same arguments.
|
||||
//
|
||||
// Avoid a stack overflow, and don't perform an unbounded nesting
|
||||
// of `withBinding(to:at:do:)` methods: only use temporary bindings
|
||||
// for less than 20 arguments. This number 20 is completely
|
||||
// arbitrary!
|
||||
// See <https://forums.swift.org/t/avoiding-stack-overflow-when-nesting-string-withcstring-how-to-handle-an-arbitrary-number-of-temp-values-in-general/63663>
|
||||
if sqliteArgumentCount <= 20 {
|
||||
// Perform an optimized execution with temporary bindings
|
||||
// in order to avoid copying strings and blobs.
|
||||
try withArguments(arguments) {
|
||||
try executeAllSteps()
|
||||
}
|
||||
} else {
|
||||
try setArguments(arguments)
|
||||
try executeAllSteps()
|
||||
}
|
||||
} else {
|
||||
try prepareExecution()
|
||||
try executeAllSteps()
|
||||
}
|
||||
}
|
||||
|
||||
private func executeAllSteps() throws {
|
||||
try database.statementWillExecute(self)
|
||||
|
||||
// Iterate all rows, since they may execute side effects.
|
||||
@@ -634,7 +782,7 @@ final class StatementCursor: DatabaseCursor {
|
||||
self._statement = statement
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
try statement.reset(withArguments: arguments)
|
||||
try statement.prepareExecution(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -679,11 +827,50 @@ public protocol StatementBinding {
|
||||
/// Binds a statement argument.
|
||||
///
|
||||
/// - parameter sqliteStatement: An SQLite statement.
|
||||
/// - parameter index: 1-based index to statement arguments
|
||||
/// - parameter index: 1-based index to statement arguments.
|
||||
/// - returns: the code returned by the `sqlite3_bind_xxx` function.
|
||||
func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt
|
||||
}
|
||||
|
||||
/// Helper function for `withBinding(to:at:do:)` methods.
|
||||
func checkBindingSuccess(code: CInt, sqliteStatement: SQLiteStatement) throws {
|
||||
if code == SQLITE_OK { return }
|
||||
let message = String(cString: sqlite3_errmsg(sqlite3_db_handle(sqliteStatement)))
|
||||
let sql = String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
|
||||
throw DatabaseError(resultCode: code, message: message, sql: sql)
|
||||
}
|
||||
|
||||
/// Calls the given closure after performing temporary bindings that avoid
|
||||
/// copying strings and blobs.
|
||||
///
|
||||
/// The bindings are valid only during the execution of this method.
|
||||
///
|
||||
/// - parameter bindings: The bindings
|
||||
/// - parameter sqliteStatement: The SQLite statement
|
||||
/// - parameter index: The index of the first binding.
|
||||
/// - parameter body: The closure to execute when arguments are bound.
|
||||
@usableFromInline
|
||||
func withBindings<C, T>(
|
||||
_ bindings: C,
|
||||
to sqliteStatement: SQLiteStatement,
|
||||
from index: CInt = 1,
|
||||
do body: () throws -> T)
|
||||
throws -> T
|
||||
where C: Collection, C.Element == DatabaseValue
|
||||
{
|
||||
guard let binding = bindings.first else {
|
||||
return try body()
|
||||
}
|
||||
|
||||
return try binding.withBinding(to: sqliteStatement, at: index) {
|
||||
try withBindings(
|
||||
bindings.dropFirst(),
|
||||
to: sqliteStatement,
|
||||
from: index + 1,
|
||||
do: body)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - StatementArguments
|
||||
|
||||
/// An instance of `StatementArguments` provides the values for argument
|
||||
@@ -699,9 +886,9 @@ public protocol StatementBinding {
|
||||
/// - `@AAAA` (e.g. `@name`): named argument
|
||||
/// - `$AAAA` (e.g. `$name`): named argument
|
||||
///
|
||||
/// GRDB does not allow to distinguish between the `:AAAA`, `@AAAA`, and `$AAAA`
|
||||
/// syntaxes. You are encouraged to write named arguments with a
|
||||
/// colon prefix: `:name`.
|
||||
/// All forms are supported, but GRDB does not allow to distinguish between
|
||||
/// the `:AAAA`, `@AAAA`, and `$AAAA` syntaxes. You are encouraged to write
|
||||
/// named arguments with a colon prefix: `:name`.
|
||||
///
|
||||
/// ## Positional Arguments
|
||||
///
|
||||
@@ -843,7 +1030,7 @@ public struct StatementArguments: Hashable {
|
||||
/// The result is nil unless all array elements conform to the
|
||||
/// ``DatabaseValueConvertible`` protocol.
|
||||
public init?(_ array: [Any]) {
|
||||
var values = [DatabaseValueConvertible?]()
|
||||
var values = [(any DatabaseValueConvertible)?]()
|
||||
for value in array {
|
||||
guard let dbValue = DatabaseValue(value: value) else {
|
||||
return nil
|
||||
@@ -1120,36 +1307,42 @@ public struct StatementArguments: Hashable {
|
||||
allowingRemainingValues: Bool)
|
||||
throws -> [DatabaseValue]
|
||||
{
|
||||
let initialValuesCount = values.count
|
||||
var iterator = values.makeIterator()
|
||||
var consumedValuesCount = 0
|
||||
let bindings = try statement.sqliteArgumentNames.map { argumentName -> DatabaseValue in
|
||||
if let argumentName {
|
||||
if let dbValue = namedValues[argumentName] {
|
||||
return dbValue
|
||||
} else if values.isEmpty {
|
||||
} else if let value = iterator.next() {
|
||||
consumedValuesCount += 1
|
||||
return value
|
||||
} else {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: "missing statement argument: \(argumentName)",
|
||||
sql: statement.sql)
|
||||
} else {
|
||||
return values.removeFirst()
|
||||
}
|
||||
} else if let value = iterator.next() {
|
||||
consumedValuesCount += 1
|
||||
return value
|
||||
} else {
|
||||
if values.isEmpty {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: "wrong number of statement arguments: \(initialValuesCount)",
|
||||
sql: statement.sql)
|
||||
} else {
|
||||
return values.removeFirst()
|
||||
}
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: "wrong number of statement arguments: \(values.count)",
|
||||
sql: statement.sql)
|
||||
}
|
||||
}
|
||||
if !allowingRemainingValues && !values.isEmpty {
|
||||
if !allowingRemainingValues && iterator.next() != nil {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: "wrong number of statement arguments: \(initialValuesCount)",
|
||||
message: "wrong number of statement arguments: \(values.count)",
|
||||
sql: statement.sql)
|
||||
}
|
||||
if consumedValuesCount == values.count {
|
||||
values.removeAll()
|
||||
} else {
|
||||
values = Array(values[consumedValuesCount...])
|
||||
}
|
||||
return bindings
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
/// // Optimized
|
||||
/// let scores = Int.fetchAll(db, sql: "SELECT score FROM player")
|
||||
///
|
||||
/// let rows = Row.fetchCursor(db, sql: "SELECT * FROM player")
|
||||
/// let rows = try Row.fetchCursor(db, sql: "SELECT * FROM player")
|
||||
/// while let row = try rows.next() {
|
||||
/// // Optimized
|
||||
/// let int: Int = row[0]
|
||||
@@ -89,7 +89,7 @@ public protocol StatementColumnConvertible {
|
||||
///
|
||||
/// Do not check for `NULL` in your implementation of this method. Null
|
||||
/// database values are handled
|
||||
/// in ``fromStatement(_:atUncheckedIndex:)-2i8y6``.
|
||||
/// in ``StatementColumnConvertible/fromStatement(_:atUncheckedIndex:)-2i8y6``.
|
||||
///
|
||||
/// For example, here is the how Int64 adopts StatementColumnConvertible:
|
||||
///
|
||||
@@ -223,7 +223,7 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
}
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
try statement.reset(withArguments: arguments)
|
||||
try statement.prepareExecution(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#if canImport(CoreGraphics)
|
||||
import CoreGraphics
|
||||
|
||||
/// CGFloat adopts DatabaseValueConvertible
|
||||
/// `CGFloat` is a database value.
|
||||
extension CGFloat: DatabaseValueConvertible {
|
||||
/// Returns a REAL database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import Foundation
|
||||
|
||||
/// Data is convertible to and from DatabaseValue.
|
||||
/// `Data` is a database value.
|
||||
extension Data: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
if let bytes = sqlite3_column_blob(sqliteStatement, index) {
|
||||
@@ -42,6 +42,23 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
sqlite3_bind_blob(sqliteStatement, index, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls the given closure after binding a statement argument.
|
||||
///
|
||||
/// The binding is valid only during the execution of this method.
|
||||
///
|
||||
/// - 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 withUnsafeBytes {
|
||||
let code = sqlite3_bind_blob(
|
||||
sqliteStatement, index,
|
||||
$0.baseAddress, CInt($0.count), nil /* SQLITE_STATIC */)
|
||||
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
|
||||
return try body()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Conversions
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
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.
|
||||
/// `NSDate` is a database value.
|
||||
extension NSDate: DatabaseValueConvertible {
|
||||
/// Returns a TEXT database value that contains the date encoded as
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
@@ -31,8 +30,6 @@ extension NSDate: DatabaseValueConvertible {
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Date is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
extension Date: DatabaseValueConvertible {
|
||||
/// Returns a TEXT database value that contains the date encoded as
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
@@ -115,6 +112,7 @@ extension Date: DatabaseValueConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// `Date` is a database value.
|
||||
extension Date: StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// Decimal adopts DatabaseValueConvertible
|
||||
/// `Decimal` is a database value.
|
||||
extension Decimal: DatabaseValueConvertible {
|
||||
/// Returns a TEXT decimal value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// NSData is convertible to and from DatabaseValue.
|
||||
/// `NSData` is a database value.
|
||||
extension NSData: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a BLOB database value.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import Foundation
|
||||
|
||||
/// NSNull adopts DatabaseValueConvertible
|
||||
/// `NSDate` is a database value.
|
||||
extension NSNull: DatabaseValueConvertible {
|
||||
|
||||
/// Returns the NULL database value.
|
||||
|
||||
@@ -9,7 +9,7 @@ private let integerRoundingBehavior = NSDecimalNumberHandler(
|
||||
raiseOnUnderflow: false,
|
||||
raiseOnDivideByZero: false)
|
||||
|
||||
/// NSNumber adopts DatabaseValueConvertible
|
||||
/// `NSNumber` is a database value.
|
||||
extension NSNumber: DatabaseValueConvertible {
|
||||
|
||||
/// A database value.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// NSString adopts DatabaseValueConvertible
|
||||
/// `NSString` is a database value.
|
||||
extension NSString: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a TEXT database value.
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux)
|
||||
/// NSURL stores its absoluteString in the database.
|
||||
/// `NSURL` is a database value.
|
||||
///
|
||||
/// `NSURL` stores its `absoluteString` in the database.
|
||||
extension NSURL: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a TEXT database value containing the absolute URL.
|
||||
@@ -18,5 +20,7 @@ extension NSURL: DatabaseValueConvertible {
|
||||
}
|
||||
#endif
|
||||
|
||||
/// URL stores its absoluteString in the database.
|
||||
/// `URL` is a database value.
|
||||
///
|
||||
/// `URL` stores its `absoluteString` in the database.
|
||||
extension URL: DatabaseValueConvertible { }
|
||||
@@ -1,7 +1,7 @@
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux)
|
||||
/// NSUUID adopts DatabaseValueConvertible
|
||||
/// `NSUUID` is a database value.
|
||||
extension NSUUID: DatabaseValueConvertible {
|
||||
/// Returns a BLOB database value containing the uuid bytes.
|
||||
public var databaseValue: DatabaseValue {
|
||||
@@ -35,7 +35,7 @@ extension NSUUID: DatabaseValueConvertible {
|
||||
}
|
||||
#endif
|
||||
|
||||
/// UUID adopts DatabaseValueConvertible
|
||||
/// `UUID` is a database value.
|
||||
extension UUID: DatabaseValueConvertible {
|
||||
/// Returns a BLOB database value containing the uuid bytes.
|
||||
public var databaseValue: DatabaseValue {
|
||||
|
||||
@@ -136,7 +136,7 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer {
|
||||
/// cannot be converted to the requested type.
|
||||
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
|
||||
func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
|
||||
if let type = T.self as? DatabaseValueConvertible.Type {
|
||||
if let type = T.self as? any DatabaseValueConvertible.Type {
|
||||
// Prefer DatabaseValueConvertible decoding over Decodable.
|
||||
// This allows custom database decoding, such as decoding Date from
|
||||
// String, for example.
|
||||
|
||||
@@ -44,6 +44,7 @@ extension Optional: SQLSelectable where Wrapped: SQLSelectable {
|
||||
|
||||
extension Optional: SQLSpecificExpressible where Wrapped: SQLSpecificExpressible { }
|
||||
|
||||
/// `Optional` is a database value when it wrapped type is.
|
||||
extension Optional: DatabaseValueConvertible where Wrapped: DatabaseValueConvertible {
|
||||
public var databaseValue: DatabaseValue {
|
||||
switch self {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// MARK: - Value Types
|
||||
|
||||
/// Bool adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Bool` is a database value.
|
||||
extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -95,7 +95,7 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Int adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Int` is a database value.
|
||||
extension Int: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -134,7 +134,7 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Int8 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Int8` is a database value.
|
||||
extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -173,7 +173,7 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Int16 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Int16` is a database value.
|
||||
extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -212,7 +212,7 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Int32 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Int32` is a database value.
|
||||
extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -251,7 +251,7 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Int64 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Int64` is a database value.
|
||||
extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -294,7 +294,7 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `UInt` is a database value.
|
||||
extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -333,7 +333,7 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt8 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `UInt8` is a database value.
|
||||
extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -372,7 +372,7 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt16 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `UInt16` is a database value.
|
||||
extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -411,7 +411,7 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt32 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `UInt32` is a database value.
|
||||
extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -450,7 +450,7 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt64 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `UInt64` is a database value.
|
||||
extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -489,7 +489,7 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Double adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Double` is a database value.
|
||||
extension Double: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -529,7 +529,7 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Float adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Float` is a database value.
|
||||
extension Float: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -569,7 +569,7 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// String adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `String` is a database value.
|
||||
extension String: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -610,6 +610,21 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_text(sqliteStatement, index, self, -1, SQLITE_TRANSIENT)
|
||||
}
|
||||
|
||||
/// Calls the given closure after binding a statement argument.
|
||||
///
|
||||
/// The binding is valid only during the execution of this method.
|
||||
///
|
||||
/// - 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 */)
|
||||
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
|
||||
return try body()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -41,8 +41,9 @@ extension TransactionClock where Self == CustomTransactionClock {
|
||||
}
|
||||
}
|
||||
|
||||
/// The default clock.
|
||||
/// The default transaction clock.
|
||||
public struct DefaultTransactionClock: TransactionClock {
|
||||
/// Returns the start date of the current transaction.
|
||||
public func now(_ db: Database) throws -> Date {
|
||||
// An opportunity to fetch transaction time from the database when
|
||||
// SQLite supports the feature.
|
||||
|
||||
@@ -454,7 +454,7 @@ class DatabaseObservationBroker {
|
||||
|
||||
if savepointStack.isEmpty {
|
||||
// Notify now
|
||||
for statementObservation in statementObservations where statementObservation.predicate.evaluate(event) {
|
||||
for statementObservation in statementObservations where statementObservation.tracksEvent(event) {
|
||||
statementObservation.transactionObservation.databaseWillChange(with: event)
|
||||
}
|
||||
} else {
|
||||
@@ -479,7 +479,7 @@ class DatabaseObservationBroker {
|
||||
|
||||
if savepointStack.isEmpty {
|
||||
// Notify now
|
||||
for statementObservation in statementObservations where statementObservation.predicate.evaluate(event) {
|
||||
for statementObservation in statementObservations where statementObservation.tracksEvent(event) {
|
||||
statementObservation.transactionObservation.databaseDidChange(with: event)
|
||||
}
|
||||
} else {
|
||||
@@ -639,7 +639,7 @@ class DatabaseObservationBroker {
|
||||
|
||||
for (event, statementObservations) in eventsBuffer {
|
||||
assert(statementObservations.isEmpty || !database.isReadOnly, "Read-only transactions are not notified")
|
||||
for statementObservation in statementObservations where statementObservation.predicate.evaluate(event) {
|
||||
for statementObservation in statementObservations where statementObservation.tracksEvent(event) {
|
||||
event.send(to: statementObservation.transactionObservation)
|
||||
}
|
||||
}
|
||||
@@ -739,311 +739,6 @@ class DatabaseObservationBroker {
|
||||
|
||||
// MARK: - TransactionObserver
|
||||
|
||||
/// A type that tracks database changes and transactions performed in
|
||||
/// a database.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// `TransactionObserver` is the low-level protocol that supports all
|
||||
/// <doc:DatabaseObservation> features.
|
||||
///
|
||||
/// A transaction observer is notified of individual changes (inserts, updates
|
||||
/// and deletes), before they are committed to disk, as well as transaction
|
||||
/// commits and rollbacks.
|
||||
///
|
||||
/// ## Activate a Transaction Observer
|
||||
///
|
||||
/// An observer starts receiving change notifications after it has been added to
|
||||
/// a database connection with the
|
||||
/// ``DatabaseWriter/add(transactionObserver:extent:)`` `DatabaseWriter` method,
|
||||
/// or the ``Database/add(transactionObserver:extent:)`` `Database` method:
|
||||
///
|
||||
/// ```swift
|
||||
/// 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.
|
||||
///
|
||||
/// ## 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).
|
||||
///
|
||||
/// Transaction completions are notified to the ``databaseWillCommit()-7mksu``,
|
||||
/// ``databaseDidCommit(_:)`` and ``databaseDidRollback(_:)`` callbacks.
|
||||
///
|
||||
/// Read-only transactions, changes and transactions performed by external
|
||||
/// database connections, changes to internal system tables (such as
|
||||
/// `sqlite_master`), changes to
|
||||
/// [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables, and 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) are
|
||||
/// not notified.
|
||||
///
|
||||
/// 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:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// try db.execute(sql: "INSERT ...") // 1. didChange
|
||||
/// try db.execute(sql: "UPDATE ...") // 2. didChange
|
||||
/// } // 3. willCommit, 4. didCommit
|
||||
///
|
||||
/// try dbQueue.inTransaction { db in
|
||||
/// try db.execute(sql: "INSERT ...") // 1. didChange
|
||||
/// try db.execute(sql: "UPDATE ...") // 2. didChange
|
||||
/// return .rollback // 3. didRollback
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// try db.execute(sql: "INSERT ...") // 1. didChange
|
||||
/// throw SomeError()
|
||||
/// } // 2. didRollback
|
||||
/// ```
|
||||
///
|
||||
/// Database statements that are executed outside of any explicit transaction
|
||||
/// do not drop off the radar:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.writeWithoutTransaction { db in
|
||||
/// try db.execute(sql: "INSERT ...") // 1. didChange, 2. willCommit, 3. didCommit
|
||||
/// try db.execute(sql: "UPDATE ...") // 4. didChange, 5. willCommit, 6. didCommit
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Changes that are on hold because of a
|
||||
/// [savepoint](https://www.sqlite.org/lang_savepoint.html) are only notified
|
||||
/// after the savepoint has been released. This makes sure that notified events
|
||||
/// are only those that have an opportunity to be committed:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.inTransaction { db in
|
||||
/// try db.execute(sql: "INSERT ...") // 1. didChange
|
||||
///
|
||||
/// try db.execute(sql: "SAVEPOINT foo")
|
||||
/// try db.execute(sql: "UPDATE ...") // delayed
|
||||
/// try db.execute(sql: "UPDATE ...") // delayed
|
||||
/// try db.execute(sql: "RELEASE SAVEPOINT foo") // 2. didChange, 3. didChange
|
||||
///
|
||||
/// try db.execute(sql: "SAVEPOINT bar")
|
||||
/// try db.execute(sql: "UPDATE ...") // not notified
|
||||
/// try db.execute(sql: "ROLLBACK TO SAVEPOINT bar")
|
||||
/// try db.execute(sql: "RELEASE SAVEPOINT bar")
|
||||
///
|
||||
/// return .commit // 4. willCommit, 5. didCommit
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Eventual errors thrown from `databaseWillCommit` are exposed to the
|
||||
/// application code:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// try dbQueue.inTransaction { db in
|
||||
/// ...
|
||||
/// return .commit // 1. willCommit (throws), 2. didRollback
|
||||
/// }
|
||||
/// } catch {
|
||||
/// // 3. The error thrown by the transaction observer.
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - Note: All callbacks are called in the writer dispatch queue, and
|
||||
/// serialized with all database updates.
|
||||
///
|
||||
/// - Note: The `databaseDidChange` and `databaseWillCommit` callbacks must not
|
||||
/// touch the SQLite database. This limitation does not apply to
|
||||
/// `databaseDidCommit` and `databaseDidRollback` which can use their
|
||||
/// database argument.
|
||||
///
|
||||
/// ## Filtering Database Events
|
||||
///
|
||||
/// **Transaction observers can choose the database changes they are
|
||||
/// interested in.**
|
||||
///
|
||||
/// The filtering happens in the ``observes(eventsOfKind:)`` method, which tells
|
||||
/// whether the observer wants notifications of specific kinds of changes,
|
||||
/// or not.
|
||||
///
|
||||
/// The ``DatabaseEventKind`` argument of `observes(eventsOfKind:)` can
|
||||
/// distinguish insertions from deletions and updates, and is also able to
|
||||
/// tell the columns that are about to be changed.
|
||||
///
|
||||
/// For example, an observer can focus on the changes that happen on the
|
||||
/// "player" database table only:
|
||||
///
|
||||
/// ```swift
|
||||
/// class PlayerObserver: TransactionObserver {
|
||||
/// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
/// // Only observe changes to the "player" table.
|
||||
/// eventKind.tableName == "player"
|
||||
/// }
|
||||
///
|
||||
/// func databaseDidChange(with event: DatabaseEvent) {
|
||||
/// // This method is only called for changes that happen to
|
||||
/// // the "player" table.
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When the `observes(eventsOfKind:)` method returns false for all event kinds,
|
||||
/// the observer is still notified of transactions.
|
||||
///
|
||||
/// ## Observation Extent
|
||||
///
|
||||
/// **You can specify how long an observer is notified of database changes
|
||||
/// and transactions.**
|
||||
///
|
||||
/// The `remove(transactionObserver:)` method explicitly stops notifications,
|
||||
/// at any time:
|
||||
///
|
||||
/// ```swift
|
||||
/// // From a database queue or pool:
|
||||
/// dbQueue.remove(transactionObserver: observer)
|
||||
///
|
||||
/// // From a database connection:
|
||||
/// dbQueue.inDatabase { db in
|
||||
/// db.remove(transactionObserver: observer)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Alternatively, use the `extent` parameter of the
|
||||
/// `add(transactionObserver:extent:)` method:
|
||||
///
|
||||
/// ```swift
|
||||
/// let observer = MyObserver()
|
||||
///
|
||||
/// // On a database queue or pool:
|
||||
/// dbQueue.add(transactionObserver: observer) // default extent
|
||||
/// dbQueue.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
/// dbQueue.add(transactionObserver: observer, extent: .nextTransaction)
|
||||
/// dbQueue.add(transactionObserver: observer, extent: .databaseLifetime)
|
||||
///
|
||||
/// // On a database connection:
|
||||
/// dbQueue.inDatabase { db in
|
||||
/// db.add(transactionObserver: ...)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - 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.
|
||||
///
|
||||
/// - `.databaseLifetime` has the database retain and notify the observer until
|
||||
/// the database connection is closed.
|
||||
///
|
||||
/// Finally, an observer can avoid processing database changes until the end
|
||||
/// of the current transaction. After
|
||||
/// ``stopObservingDatabaseChangesUntilNextTransaction()``, the
|
||||
/// `databaseDidChange` callback will not be called until the current
|
||||
/// transaction completes:
|
||||
///
|
||||
/// ```swift
|
||||
/// class PlayerObserver: TransactionObserver {
|
||||
/// var playerTableWasModified = false
|
||||
///
|
||||
/// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
/// eventKind.tableName == "player"
|
||||
/// }
|
||||
///
|
||||
/// func databaseDidChange(with event: DatabaseEvent) {
|
||||
/// playerTableWasModified = true
|
||||
///
|
||||
/// // It is pointless to keep on tracking further changes:
|
||||
/// stopObservingDatabaseChangesUntilNextTransaction()
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ### Support for SQLite Pre-Update Hooks
|
||||
///
|
||||
/// When SQLite is built with the `SQLITE_ENABLE_PREUPDATE_HOOK` option,
|
||||
/// `TransactionObserver` gets an extra callback which lets you observe
|
||||
/// individual column values in the rows modified by a transaction:
|
||||
///
|
||||
/// ```swift
|
||||
/// protocol TransactionObserver: AnyObject {
|
||||
/// #if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
/// /// Notifies before a database change (insert, update, or delete)
|
||||
/// /// with change information (initial / final values for the row's
|
||||
/// /// columns).
|
||||
/// ///
|
||||
/// /// The event is only valid for the duration of this method call. If you
|
||||
/// /// need to keep it longer, store a copy: event.copy().
|
||||
/// func databaseWillChange(with event: DatabasePreUpdateEvent)
|
||||
/// #endif
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This extra API can be activated in two ways:
|
||||
///
|
||||
/// 1. Use the GRDB.swift CocoaPod with a custom compilation option, as below.
|
||||
/// It uses the system SQLite, which is compiled with
|
||||
/// `SQLITE_ENABLE_PREUPDATE_HOOK` support, but only on iOS 11.0+ (we don't
|
||||
/// know the minimum version of macOS, tvOS, watchOS):
|
||||
///
|
||||
/// ```ruby
|
||||
/// pod 'GRDB.swift'
|
||||
/// platform :ios, '11.0' # or above
|
||||
///
|
||||
/// post_install do |installer|
|
||||
/// installer.pods_project.targets.select { |target| target.name == "GRDB.swift" }.each do |target|
|
||||
/// target.build_configurations.each do |config|
|
||||
/// # Enable extra GRDB APIs
|
||||
/// config.build_settings['OTHER_SWIFT_FLAGS'] = "$(inherited) -D SQLITE_ENABLE_PREUPDATE_HOOK"
|
||||
/// # Enable extra SQLite APIs
|
||||
/// config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = "$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1"
|
||||
/// end
|
||||
/// end
|
||||
/// end
|
||||
/// ```
|
||||
///
|
||||
/// **Warning**: make sure you use the right platform version! You will get
|
||||
/// runtime errors on devices with a lower version.
|
||||
///
|
||||
/// **Note**: the `GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1` option in
|
||||
/// `GCC_PREPROCESSOR_DEFINITIONS` defines some C function prototypes that
|
||||
/// are lacking from the system `<sqlite3.h>` header. When Xcode eventually
|
||||
/// ships with an SDK that includes a complete header, you may get a
|
||||
/// compiler error about duplicate function definitions. When this happens,
|
||||
/// just remove this `GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1` option.
|
||||
///
|
||||
/// 2. Use a [custom SQLite build](http://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md)
|
||||
/// and activate the `SQLITE_ENABLE_PREUPDATE_HOOK` compilation option.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Filtering Database Changes
|
||||
///
|
||||
/// - ``observes(eventsOfKind:)``
|
||||
/// - ``DatabaseEventKind``
|
||||
///
|
||||
/// ### Handling Database Changes
|
||||
///
|
||||
/// - ``databaseDidChange(with:)``
|
||||
/// - ``stopObservingDatabaseChangesUntilNextTransaction()``
|
||||
/// - ``DatabaseEvent``
|
||||
///
|
||||
/// ### Handling Transactions
|
||||
///
|
||||
/// - ``databaseWillCommit()-7mksu``
|
||||
/// - ``databaseDidCommit(_:)``
|
||||
/// - ``databaseDidRollback(_:)``
|
||||
public protocol TransactionObserver: AnyObject {
|
||||
|
||||
/// Returns whether specific kinds of database changes should be notified
|
||||
@@ -1066,7 +761,7 @@ public protocol TransactionObserver: AnyObject {
|
||||
/// When this method returns true for deletion events, the observer
|
||||
/// prevents the
|
||||
/// [truncate optimization](https://www.sqlite.org/lang_delete.html#the_truncate_optimization)
|
||||
/// from being applied.
|
||||
/// from being applied on the observed tables.
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
|
||||
|
||||
/// Called when the database is changed by an insert, update, or
|
||||
@@ -1274,12 +969,18 @@ final class TransactionObservation {
|
||||
struct StatementObservation {
|
||||
var transactionObservation: TransactionObservation
|
||||
|
||||
/// Filters database events that should be notified.
|
||||
var predicate: DatabaseEventPredicate
|
||||
/// A predicate that filters database events that should be notified.
|
||||
///
|
||||
/// Call this predicate as a method:
|
||||
///
|
||||
/// ```
|
||||
/// if observation.tracksEvent(event) { ... }
|
||||
/// ```
|
||||
var tracksEvent: DatabaseEventPredicate
|
||||
|
||||
init(transactionObservation: TransactionObservation, trackingEvents predicate: DatabaseEventPredicate) {
|
||||
self.transactionObservation = transactionObservation
|
||||
self.predicate = predicate
|
||||
self.tracksEvent = predicate
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1752,7 +1453,7 @@ enum DatabaseEventPredicate {
|
||||
/// statement authorizer.
|
||||
case matching(observedEventKinds: [DatabaseEventKind], authorizerEventKinds: [DatabaseEventKind])
|
||||
|
||||
func evaluate(_ event: some DatabaseEventProtocol) -> Bool {
|
||||
func callAsFunction(_ event: some DatabaseEventProtocol) -> Bool {
|
||||
switch self {
|
||||
case .all:
|
||||
return true
|
||||
|
||||
+30
-19
@@ -1,3 +1,5 @@
|
||||
// swiftlint:disable:next line_length
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
/// An instance of WALSnapshot records the state of a WAL mode database for some
|
||||
/// specific point in history.
|
||||
///
|
||||
@@ -20,13 +22,6 @@
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/snapshot.html>.
|
||||
final class WALSnapshot: Sendable {
|
||||
// Xcode 14 (Swift 5.7) ships with a macOS SDK that misses snapshot support.
|
||||
// Xcode 14.1 (Swift 5.7.1) ships with a macOS SDK that has snapshot support.
|
||||
// This is the meaning of (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))
|
||||
// swiftlint:disable:next line_length
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
static let available = true
|
||||
|
||||
let sqliteSnapshot: UnsafeMutablePointer<sqlite3_snapshot>
|
||||
|
||||
init(_ db: Database) throws {
|
||||
@@ -35,11 +30,30 @@ final class WALSnapshot: Sendable {
|
||||
return sqlite3_snapshot_get(db.sqliteConnection, "main", $0)
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
// <https://www.sqlite.org/c3ref/snapshot_get.html>
|
||||
//
|
||||
// > The following must be true for sqlite3_snapshot_get() to succeed. [...]
|
||||
// >
|
||||
// > 1. The database handle must not be in autocommit mode.
|
||||
// > 2. Schema S of database connection D must be a WAL
|
||||
// > mode database.
|
||||
// > 3. There must not be a write transaction open on schema S
|
||||
// > of database connection D.
|
||||
// > 4. One or more transactions must have been written to the
|
||||
// > current wal file since it was created on disk (by any
|
||||
// > connection). This means that a snapshot cannot be taken
|
||||
// > on a wal mode database with no wal file immediately
|
||||
// > after it is first opened. At least one transaction must
|
||||
// > be written to it first.
|
||||
|
||||
// Test condition 1:
|
||||
if sqlite3_get_autocommit(db.sqliteConnection) != 0 {
|
||||
throw DatabaseError(resultCode: code, message: """
|
||||
Can't create snapshot because database is in autocommit mode.
|
||||
""")
|
||||
}
|
||||
|
||||
// Test condition 2:
|
||||
if let journalMode = try? String.fetchOne(db, sql: "PRAGMA journal_mode"),
|
||||
journalMode != "wal"
|
||||
{
|
||||
@@ -47,7 +61,14 @@ final class WALSnapshot: Sendable {
|
||||
Can't create snapshot because database is not in WAL mode.
|
||||
""")
|
||||
}
|
||||
throw DatabaseError(resultCode: code)
|
||||
|
||||
// Condition 3 can't happen because GRDB only calls this
|
||||
// initializer from read transactions.
|
||||
//
|
||||
// Hence it is condition 4 that is false:
|
||||
throw DatabaseError(resultCode: code, message: """
|
||||
Can't create snapshot from a missing or empty wal file.
|
||||
""")
|
||||
}
|
||||
guard let sqliteSnapshot else {
|
||||
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
|
||||
@@ -67,15 +88,5 @@ final class WALSnapshot: Sendable {
|
||||
func compare(_ other: WALSnapshot) -> CInt {
|
||||
sqlite3_snapshot_cmp(sqliteSnapshot, other.sqliteSnapshot)
|
||||
}
|
||||
#else
|
||||
static let available = false
|
||||
|
||||
init(_ db: Database) throws {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "snapshots are not available")
|
||||
}
|
||||
|
||||
func compare(_ other: WALSnapshot) -> CInt {
|
||||
preconditionFailure("snapshots are not available")
|
||||
}
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,92 @@
|
||||
// swiftlint:disable:next line_length
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
/// A long-live read-only WAL transaction.
|
||||
///
|
||||
/// `WALSnapshotTransaction` **takes ownership** of its reader
|
||||
/// `SerializedDatabase` (TODO: make it a move-only type eventually).
|
||||
class WALSnapshotTransaction {
|
||||
private let reader: SerializedDatabase
|
||||
private let release: (_ isInsideTransaction: Bool) -> Void
|
||||
|
||||
/// 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.
|
||||
///
|
||||
/// The `release` closure is always called. It is called when the
|
||||
/// `WALSnapshotTransaction` is deallocated, or if the initializer
|
||||
/// throws.
|
||||
///
|
||||
/// In normal operations, the argument to `release` is always false,
|
||||
/// meaning that the connection is no longer in a transaction. If true,
|
||||
/// the connection has been left inside a transaction, due to
|
||||
/// some error.
|
||||
///
|
||||
/// Usage:
|
||||
///
|
||||
/// ```swift
|
||||
/// let transaction = WALSnapshotTransaction(
|
||||
/// reader: reader,
|
||||
/// release: { isInsideTransaction in
|
||||
/// ...
|
||||
/// })
|
||||
/// ```
|
||||
///
|
||||
/// - parameter reader: A read-only database connection.
|
||||
/// - parameter release: A closure to call when the read-only connection
|
||||
/// is no longer used.
|
||||
init(
|
||||
onReader reader: SerializedDatabase,
|
||||
release: @escaping (_ isInsideTransaction: Bool) -> Void)
|
||||
throws
|
||||
{
|
||||
assert(reader.configuration.readonly)
|
||||
|
||||
do {
|
||||
// Open a long-lived transaction, and enter snapshot isolation
|
||||
self.walSnapshot = try reader.sync(allowingLongLivedTransaction: true) { db in
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
|
||||
return try WALSnapshot(db)
|
||||
}
|
||||
self.reader = reader
|
||||
self.release = release
|
||||
} catch {
|
||||
// self is not initialized, so deinit will not run.
|
||||
Self.commitAndRelease(reader: reader, release: release)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
Self.commitAndRelease(reader: reader, release: release)
|
||||
}
|
||||
|
||||
/// Executes database operations in the snapshot transaction, and
|
||||
/// returns their result after they have finished executing.
|
||||
func read<T>(_ value: (Database) throws -> T) rethrows -> T {
|
||||
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
|
||||
try reader.sync(value)
|
||||
}
|
||||
|
||||
/// Schedules database operations for execution, and
|
||||
/// returns immediately.
|
||||
func asyncRead(_ value: @escaping (Database) -> Void) {
|
||||
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
|
||||
reader.async(value)
|
||||
}
|
||||
|
||||
private static func commitAndRelease(
|
||||
reader: SerializedDatabase,
|
||||
release: (_ isInsideTransaction: Bool) -> Void)
|
||||
{
|
||||
// WALSnapshotTransaction may be deinitialized in the dispatch
|
||||
// queue of its reader: allow reentrancy.
|
||||
let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in
|
||||
try? db.commit()
|
||||
return db.isInsideTransaction
|
||||
}
|
||||
release(isInsideTransaction)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -14,7 +14,7 @@ The other chapters cover, with more details, the fundamentals of SQLite concurre
|
||||
|
||||
**The two concurrency rules are strongly recommended practices.** They are all about SQLite, a robust and reliable database that takes great care of your data: don't miss an opportunity to put it on your side!
|
||||
|
||||
### Rule 1: Connect to any database file only once
|
||||
#### Rule 1: Connect to any database file only once
|
||||
|
||||
Open one single ``DatabaseQueue`` or ``DatabasePool`` per database file, for the whole duration of your use of the database. Not for the duration of _each_ database access, but really for the duration of _all_ database accesses to this file.
|
||||
|
||||
@@ -27,7 +27,7 @@ Open one single ``DatabaseQueue`` or ``DatabasePool`` per database file, for the
|
||||
- You will not be able to use the <doc:DatabaseObservation> features.
|
||||
- You will see SQLite errors ([`SQLITE_BUSY`]).
|
||||
|
||||
### Rule 2: Mind your transactions
|
||||
#### 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.
|
||||
|
||||
@@ -150,31 +150,31 @@ This prevents the database operations from various concurrent accesses from bein
|
||||
|
||||
**You will generally use the safe database access methods `read` and `write`.** In this context, "safe" means that a database access is concurrency-friendly, because GRDB provides the following guarantees:
|
||||
|
||||
### Serialized Writes
|
||||
#### Serialized Writes
|
||||
|
||||
**All writes performed by one ``DatabaseQueue`` or ``DatabasePool`` instance are serialized.**
|
||||
|
||||
This guarantee prevents [`SQLITE_BUSY`] errors during concurrent writes.
|
||||
|
||||
### Write Transactions
|
||||
#### Write Transactions
|
||||
|
||||
**All writes are wrapped in a transaction.**
|
||||
|
||||
Concurrent reads can not see partial database updates (even reads performed by other processes).
|
||||
|
||||
### Isolated Reads
|
||||
#### 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.
|
||||
|
||||
### Forbidden Writes
|
||||
#### Forbidden Writes
|
||||
|
||||
**Inside a read access, all attempts to write raise an error.**
|
||||
|
||||
This enforces the immutability of the database during a read.
|
||||
|
||||
### Non-Reentrancy
|
||||
#### Non-Reentrancy
|
||||
|
||||
**Database accesses methods are not reentrant.**
|
||||
|
||||
|
||||
@@ -22,6 +22,73 @@ The differences are:
|
||||
|
||||
**If you are not sure, choose `DatabaseQueue`.** You will always be able to switch to `DatabasePool` later.
|
||||
|
||||
## Opening a Connection
|
||||
|
||||
You need a path to a database file in order to open a database connection.
|
||||
|
||||
**When the SQLite file is ready-made, and you do not intend to modify its content**, then add the database file as a [resource of your Xcode project or Swift package](https://developer.apple.com/documentation/xcode), and open a read-only database connection:
|
||||
|
||||
```swift
|
||||
// HOW TO open a read-only connection to a database resource
|
||||
|
||||
// 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")
|
||||
|
||||
if let dbPath {
|
||||
// If the resource exists, open a read-only connection.
|
||||
// Writes are disallowed because resources can not be modified.
|
||||
var config = Configuration()
|
||||
config.readonly = true
|
||||
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
|
||||
} else {
|
||||
// The database resource can not 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.
|
||||
|
||||
> 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.
|
||||
>
|
||||
> 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".
|
||||
|
||||
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:
|
||||
|
||||
```swift
|
||||
// HOW TO create an empty database, or open an existing database file
|
||||
|
||||
// Create the "Application Support/MyDatabase" directory if needed
|
||||
let fileManager = FileManager.default
|
||||
let appSupportURL = try fileManager.url(
|
||||
for: .applicationSupportDirectory, in: .userDomainMask,
|
||||
appropriateFor: nil, create: true)
|
||||
let directoryURL = appSupportURL.appendingPathComponent("MyDatabase", isDirectory: true)
|
||||
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
|
||||
|
||||
// Open or create the database
|
||||
let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
|
||||
let dbQueue = try DatabaseQueue(path: databaseURL.path)
|
||||
```
|
||||
|
||||
## Closing Connections
|
||||
|
||||
Database connections are automatically closed when ``DatabaseQueue`` or ``DatabasePool`` instances are deinitialized.
|
||||
|
||||
If the correct execution of your program depends on precise database closing, perform an explicit call to ``DatabaseReader/close()``. This method may fail and create zombie connections, so please check its detailed documentation.
|
||||
|
||||
|
||||
## Next Steps
|
||||
|
||||
Once connected to the database, your next steps are probably:
|
||||
|
||||
- Define the structure of newly created databases: see <doc:Migrations>.
|
||||
- If you intend to write SQL, see <doc:SQLSupport>. Otherwise, see <doc:QueryInterface>.
|
||||
|
||||
Even if you plan to keep your project mundane and simple, take the time to read the <doc:Concurrency> guide eventually.
|
||||
|
||||
## Topics
|
||||
|
||||
### Configuring database connections
|
||||
|
||||
@@ -140,29 +140,13 @@ try db.create(table: "membership") { t in
|
||||
}
|
||||
t.column("role", .text).notNull()
|
||||
}
|
||||
|
||||
// REQUIRES EXTRA CONFIGURATION
|
||||
try db.create(table: "player") { t in
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
|
||||
try db.create(table: "team") { t in
|
||||
t.column("id", .text).notNull().unique()
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
|
||||
try db.create(table: "membership") { t in
|
||||
t.column("playerId", .integer).notNull()
|
||||
t.column("teamId", .text).notNull()
|
||||
t.column("role", .text).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
Primary keys support record fetching methods such as ``FetchableRecord/fetchOne(_:id:)``, and persistence methods such as ``MutablePersistableRecord/update(_:onConflict:)`` or ``MutablePersistableRecord/delete(_:)``.
|
||||
|
||||
See <doc:SingleRowTables> when you need to define a table that contains a single row.
|
||||
|
||||
☝️ **If the database table does not define any explicit primary key**, the record type for this table needs explicit support for the [hidden `rowid` column](https://www.sqlite.org/rowidtable.html):
|
||||
☝️ **If the database table does not define any explicit primary key**, identifying specific rows in this table needs explicit support for the [hidden `rowid` column](https://www.sqlite.org/rowidtable.html) in the matching record types:
|
||||
|
||||
```swift
|
||||
// A table without any explicit primary key
|
||||
@@ -265,8 +249,8 @@ try db.create(table: "player") { t in
|
||||
|
||||
// One single player at any given position in a team
|
||||
try db.create(
|
||||
index: "playerTeamPosition",
|
||||
on: "player", columns: ["teamId", "position"],
|
||||
indexOn: "player",
|
||||
columns: ["teamId", "position"],
|
||||
options: .unique)
|
||||
```
|
||||
|
||||
@@ -284,10 +268,7 @@ try db.create(
|
||||
> try db.create(table: "team") { t in
|
||||
> t.column("name", .text)
|
||||
> }
|
||||
> try db.create(
|
||||
> index: "teamName",
|
||||
> on: "team", columns: ["name"],
|
||||
> options: .unique)
|
||||
> try db.create(indexOn: "team", columns: ["name"], options: .unique)
|
||||
> ```
|
||||
>
|
||||
> 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.
|
||||
@@ -381,6 +362,7 @@ extension Team: TableRecord {
|
||||
- ``Database/create(virtualTable:ifNotExists:using:_:)``
|
||||
- ``Database/drop(table:)``
|
||||
- ``Database/dropFTS4SynchronizationTriggers(forTable:)``
|
||||
- ``Database/dropFTS5SynchronizationTriggers(forTable:)``
|
||||
- ``Database/rename(table:to:)``
|
||||
- ``Database/ColumnType``
|
||||
- ``Database/ConflictResolution``
|
||||
@@ -392,7 +374,9 @@ extension Team: TableRecord {
|
||||
|
||||
### Database Indexes
|
||||
|
||||
- ``Database/create(indexOn:columns:options:condition:)``
|
||||
- ``Database/create(index:on:columns:options:condition:)``
|
||||
- ``Database/drop(indexOn:columns:)``
|
||||
- ``Database/drop(index:)``
|
||||
- ``IndexOptions``
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Sharing a Database
|
||||
|
||||
How to share an SQLite Database between several processes.
|
||||
How to share an SQLite database between multiple processes • Recommendations for App Group containers, App Extensions, App Sandbox, and file coordination.
|
||||
|
||||
## Overview
|
||||
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
# ``GRDB``
|
||||
|
||||
A toolkit for SQLite databases, with a focus on application development
|
||||
|
||||
## Overview
|
||||
|
||||
Use GRDB to save your application’s permanent data into SQLite databases.
|
||||
|
||||
The library provides raw access to SQL and advanced SQLite features, because one sometimes enjoys a sharp tool.
|
||||
|
||||
It has robust concurrency primitives, so that multi-threaded applications can efficiently use their databases.
|
||||
|
||||
It grants your application models with persistence and fetching methods, so that you don't have to deal with SQL and raw database rows when you don't want to.
|
||||
|
||||
Compared to [SQLite.swift](https://github.com/stephencelis/SQLite.swift) or [FMDB](https://github.com/ccgus/fmdb), GRDB can spare you a lot of glue code. Compared to [Core Data](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/) or [Realm](http://realm.io), it can simplify your multi-threaded applications.
|
||||
|
||||
## Topics
|
||||
|
||||
### Fundamentals
|
||||
|
||||
- <doc:DatabaseConnections>
|
||||
- <doc:SQLSupport>
|
||||
- <doc:Concurrency>
|
||||
- <doc:Transactions>
|
||||
|
||||
### Migrations and The Database Schema
|
||||
|
||||
- <doc:DatabaseSchema>
|
||||
- <doc:Migrations>
|
||||
- <doc:SingleRowTables>
|
||||
|
||||
### Records and the Query Interface
|
||||
|
||||
- <doc:QueryInterface>
|
||||
- <doc:RecordTimestamps>
|
||||
|
||||
### Responding to Database Changes
|
||||
|
||||
- <doc:DatabaseObservation>
|
||||
|
||||
### Full-Text Search
|
||||
|
||||
- <doc:FullTextSearch>
|
||||
|
||||
### Combine Publishers
|
||||
|
||||
- ``DatabasePublishers``
|
||||
@@ -92,6 +92,7 @@ do {
|
||||
- ``label``
|
||||
- ``maximumReaderCount``
|
||||
- ``observesSuspensionNotifications``
|
||||
- ``persistentReadOnlyConnections``
|
||||
- ``prepareDatabase(_:)``
|
||||
- ``publicStatementArguments``
|
||||
- ``transactionClock``
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
# ``GRDB/DatabaseRegionObservation``
|
||||
|
||||
`DatabaseRegionObservation` tracks changes in a database region, and notifies impactful transactions.
|
||||
|
||||
## 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).
|
||||
|
||||
The only changes that are not notified are:
|
||||
|
||||
- Changes performed by external database connections.
|
||||
- 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.
|
||||
|
||||
`DatabaseRegionObservation` calls your application right after changes have been committed in the database, and before any other thread had any opportunity to perform further changes. *This is a pretty strong guarantee, that most applications do not really need.* Instead, most applications prefer to be notified with fresh values: make sure you check ``ValueObservation`` before using `DatabaseRegionObservation`.
|
||||
|
||||
## DatabaseRegionObservation Usage
|
||||
|
||||
Create a `DatabaseRegionObservation` with one or several requests to track:
|
||||
|
||||
```swift
|
||||
// Tracks the full player table
|
||||
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
|
||||
// Handle error
|
||||
} onChange: { (db: Database) in
|
||||
print("Players were changed")
|
||||
}
|
||||
```
|
||||
|
||||
Enjoy the changes notifications:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
try Player(name: "Arthur").insert(db)
|
||||
}
|
||||
// Prints "Players were changed"
|
||||
```
|
||||
|
||||
You stop the observation by calling the ``DatabaseCancellable/cancel()`` method on the object returned by the `start` method. Cancellation is automatic when the cancellable is deallocated:
|
||||
|
||||
```swift
|
||||
cancellable.cancel()
|
||||
```
|
||||
|
||||
`DatabaseRegionObservation` can also be turned into a Combine publisher, or an RxSwift observable (see the companion library [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB)):
|
||||
|
||||
```swift
|
||||
let cancellable = observation.publisher(in: dbQueue).sink { completion in
|
||||
// Handle completion
|
||||
} receiveValue: { (db: Database) in
|
||||
print("Players were changed")
|
||||
}
|
||||
```
|
||||
|
||||
You can feed `DatabaseRegionObservation` with any type that conforms to the ``DatabaseRegionConvertible`` protocol: ``FetchRequest``, ``DatabaseRegion``, ``Table``, etc. For example:
|
||||
|
||||
```swift
|
||||
// Observe the score column of the 'player' table
|
||||
let observation = DatabaseRegionObservation(
|
||||
tracking: Player.select(Column("score")))
|
||||
|
||||
// Observe the 'score' column of the 'player' table
|
||||
let observation = DatabaseRegionObservation(
|
||||
tracking: SQLRequest("SELECT score FROM player"))
|
||||
|
||||
// Observe both the 'player' and 'team' tables
|
||||
let observation = DatabaseRegionObservation(
|
||||
tracking: Table("player"), Table("team"))
|
||||
|
||||
// Observe the full database
|
||||
let observation = DatabaseRegionObservation(
|
||||
tracking: .fullDatabase)
|
||||
```
|
||||
|
||||
## Topics
|
||||
|
||||
### Creating DatabaseRegionObservation
|
||||
|
||||
- ``init(tracking:)-5ldbe``
|
||||
- ``init(tracking:)-2nqjd``
|
||||
|
||||
### Observing Database Transactions
|
||||
|
||||
- ``publisher(in:)``
|
||||
- ``start(in:onError:onChange:)``
|
||||
@@ -0,0 +1,203 @@
|
||||
# ``GRDB/DatabaseValueConvertible``
|
||||
|
||||
A type that can convert itself into and out of a database value.
|
||||
|
||||
## Overview
|
||||
|
||||
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: 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>.
|
||||
|
||||
## Conforming to the DatabaseValueConvertible Protocol
|
||||
|
||||
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.
|
||||
|
||||
For example:
|
||||
|
||||
```swift
|
||||
struct EvenInteger {
|
||||
let value: Int // Guaranteed even
|
||||
|
||||
init?(_ value: Int) {
|
||||
guard value.isMultiple(of: 2) else {
|
||||
return nil // Not an even number
|
||||
}
|
||||
self.value = value
|
||||
}
|
||||
}
|
||||
|
||||
extension EvenInteger: DatabaseValueConvertible {
|
||||
var databaseValue: DatabaseValue {
|
||||
value.databaseValue
|
||||
}
|
||||
|
||||
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
guard let value = Int.fromDatabaseValue(dbValue) else {
|
||||
return nil // Not an integer
|
||||
}
|
||||
return EvenInteger(value) // Nil if not even
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Built-in RawRepresentable support
|
||||
|
||||
`DatabaseValueConvertible` implementation is ready-made for `RawRepresentable` types whose raw value is itself `DatabaseValueConvertible`, such as enums:
|
||||
|
||||
```swift
|
||||
enum Grape: String {
|
||||
case chardonnay, merlot, riesling
|
||||
}
|
||||
|
||||
// Encodes and decodes `Grape` as a string in the database:
|
||||
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:
|
||||
|
||||
```swift
|
||||
struct Color: Codable {
|
||||
var red: Double
|
||||
var green: Double
|
||||
var blue: Double
|
||||
}
|
||||
|
||||
// Encodes and decodes `Color` as a JSON object in the database:
|
||||
extension Color: DatabaseValueConvertible { }
|
||||
```
|
||||
|
||||
By default, such codable value types are encoded and decoded with the standard [JSONEncoder](https://developer.apple.com/documentation/foundation/jsonencoder) and [JSONDecoder](https://developer.apple.com/documentation/foundation/jsondecoder). `Data` values are handled with the `.base64` strategy, `Date` with the `.millisecondsSince1970` strategy, and non conforming floats with the `.throw` strategy.
|
||||
|
||||
To customize the JSON format, provide an explicit implementation for the `DatabaseValueConvertible` requirements.
|
||||
|
||||
### Adding support for the Tagged library
|
||||
|
||||
[Tagged](https://github.com/pointfreeco/swift-tagged) is a popular library that makes it possible to enhance the type-safety of our programs with dedicated wrappers around basic types. For example:
|
||||
|
||||
```swift
|
||||
import Tagged
|
||||
|
||||
struct Player: Identifiable {
|
||||
// Thanks to Tagged, Player.ID can not be mismatched with Team.ID or
|
||||
// Award.ID, even though they all wrap strings.
|
||||
typealias ID = Tagged<Player, String>
|
||||
var id: ID
|
||||
var name: String
|
||||
var score: Int
|
||||
}
|
||||
```
|
||||
|
||||
Applications that use both Tagged and GRDB will want to add those lines somewhere:
|
||||
|
||||
```swift
|
||||
import GRDB
|
||||
import Tagged
|
||||
|
||||
// Add database support to Tagged values
|
||||
extension Tagged: SQLExpressible where RawValue: SQLExpressible { }
|
||||
extension Tagged: StatementBinding where RawValue: StatementBinding { }
|
||||
extension Tagged: StatementColumnConvertible where RawValue: StatementColumnConvertible { }
|
||||
extension Tagged: DatabaseValueConvertible where RawValue: DatabaseValueConvertible { }
|
||||
```
|
||||
|
||||
This makes it possible to use `Tagged` values in all the expected places:
|
||||
|
||||
```swift
|
||||
let id: Player.ID = ...
|
||||
let player = try Player.find(db, id: id)
|
||||
```
|
||||
|
||||
## Optimized Values
|
||||
|
||||
For extra performance, custom value types can conform to both `DatabaseValueConvertible` and ``StatementColumnConvertible``. This extra protocol grants raw access to the [low-level C SQLite interface](https://www.sqlite.org/c3ref/column_blob.html) when decoding values.
|
||||
|
||||
For example:
|
||||
|
||||
```swift
|
||||
extension EvenInteger: StatementColumnConvertible {
|
||||
init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
guard let value = Int(exactly: int64) else {
|
||||
return nil // Does not fit Int (probably a 32-bit architecture)
|
||||
}
|
||||
self.init(value) // Nil if not even
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This extra conformance is not required: only aim at the low-level C interface if you have identified a performance issue after profiling your application!
|
||||
|
||||
## Topics
|
||||
|
||||
### Creating a Value
|
||||
|
||||
- ``fromDatabaseValue(_:)-21zzv``
|
||||
- ``fromMissingColumn()-7iamp``
|
||||
|
||||
### Accessing the DatabaseValue
|
||||
|
||||
- ``databaseValue-1ob9k``
|
||||
|
||||
### Fetching Values from Raw SQL
|
||||
|
||||
- ``fetchCursor(_:sql:arguments:adapter:)-6elcz``
|
||||
- ``fetchAll(_:sql:arguments:adapter:)-1cqyb``
|
||||
- ``fetchSet(_:sql:arguments:adapter:)-5jene``
|
||||
- ``fetchOne(_:sql:arguments:adapter:)-qvqp``
|
||||
|
||||
### Fetching Values from a Prepared Statement
|
||||
|
||||
- ``fetchCursor(_:arguments:adapter:)-4l6af``
|
||||
- ``fetchAll(_:arguments:adapter:)-3abuc``
|
||||
- ``fetchSet(_:arguments:adapter:)-6y54n``
|
||||
- ``fetchOne(_:arguments:adapter:)-3d7ax``
|
||||
|
||||
### Fetching Values from a Request
|
||||
|
||||
- ``fetchCursor(_:_:)-8q4r6``
|
||||
- ``fetchAll(_:_:)-9hkqs``
|
||||
- ``fetchSet(_:_:)-1foke``
|
||||
- ``fetchOne(_:_:)-o6yj``
|
||||
|
||||
### Supported Value Types
|
||||
|
||||
- ``Swift/Bool``
|
||||
- ``CoreFoundation/CGFloat``
|
||||
- ``Foundation/Data``
|
||||
- ``DatabaseDateComponents``
|
||||
- ``Foundation/Date``
|
||||
- ``Swift/Double``
|
||||
- ``Foundation/Decimal``
|
||||
- ``Swift/Float``
|
||||
- ``Swift/Int``
|
||||
- ``Swift/Int8``
|
||||
- ``Swift/Int16``
|
||||
- ``Swift/Int32``
|
||||
- ``Swift/Int64``
|
||||
- ``Foundation/NSData``
|
||||
- ``Foundation/NSDate``
|
||||
- ``Foundation/NSNull``
|
||||
- ``Foundation/NSNumber``
|
||||
- ``Foundation/NSString``
|
||||
- ``Foundation/NSURL``
|
||||
- ``Foundation/NSUUID``
|
||||
- ``Swift/Optional``
|
||||
- ``Swift/UInt``
|
||||
- ``Swift/UInt8``
|
||||
- ``Swift/UInt16``
|
||||
- ``Swift/UInt32``
|
||||
- ``Swift/UInt64``
|
||||
- ``Swift/String``
|
||||
- ``Foundation/URL``
|
||||
- ``Foundation/UUID``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``DatabaseValueCursor``
|
||||
- ``StatementBinding``
|
||||
@@ -0,0 +1,205 @@
|
||||
# ``GRDB/Statement``
|
||||
|
||||
A prepared statement.
|
||||
|
||||
## Overview
|
||||
|
||||
Prepared statements let you execute an SQL query several times, with different arguments if needed.
|
||||
|
||||
Reusing prepared statements is a performance optimization technique because SQLite parses and analyses the SQL query only once, when the prepared statement is created.
|
||||
|
||||
## Building Prepared Statements
|
||||
|
||||
Build a prepared statement with the ``Database/makeStatement(sql:)`` method:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
let insertStatement = try db.makeStatement(sql: """
|
||||
INSERT INTO player (name, score) VALUES (:name, :score)
|
||||
""")
|
||||
|
||||
let selectStatement = try db.makeStatement(sql: """
|
||||
SELECT * FROM player WHERE name = ?
|
||||
""")
|
||||
}
|
||||
```
|
||||
|
||||
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. Set the values for those arguments with arrays or dictionaries of database values, or ``StatementArguments`` instances:
|
||||
|
||||
```swift
|
||||
insertStatement.arguments = ["name": "Arthur", "score": 1000]
|
||||
selectStatement.arguments = ["Arthur"]
|
||||
```
|
||||
|
||||
Alternatively, the ``Database/makeStatement(literal:)`` method creates prepared statements with support for [SQL Interpolation]:
|
||||
|
||||
```swift
|
||||
let insertStatement = try db.makeStatement(literal: "INSERT ...")
|
||||
let selectStatement = try db.makeStatement(literal: "SELECT ...")
|
||||
// ~~~~~~~
|
||||
```
|
||||
|
||||
The `makeStatement` methods throw an error of code `SQLITE_MISUSE` (21) if the SQL query contains multiple statements joined with a semicolon. See <doc:GRDB/Statement#Parsing-Multiple-Prepared-Statements-from-a-Single-SQL-String> below.
|
||||
|
||||
## Executing Prepared Statements and Fetching Values
|
||||
|
||||
Prepared statements can be executed:
|
||||
|
||||
```swift
|
||||
try insertStatement.execute()
|
||||
```
|
||||
|
||||
To fetch rows and values from a prepared statement, use a fetching method of ``Row``, ``DatabaseValueConvertible``, or ``FetchableRecord``:
|
||||
|
||||
```swift
|
||||
let players = try Player.fetchCursor(selectStatement) // A Cursor of Player
|
||||
let players = try Player.fetchAll(selectStatement) // [Player]
|
||||
let players = try Player.fetchSet(selectStatement) // Set<Player>
|
||||
let player = try Player.fetchOne(selectStatement) // Player?
|
||||
// ~~~~~~ or Row, Int, String, Date, etc.
|
||||
```
|
||||
|
||||
Arguments can be set at the moment of the statement execution:
|
||||
|
||||
```swift
|
||||
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.
|
||||
|
||||
> 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:
|
||||
>
|
||||
> ```swift
|
||||
> // First option
|
||||
> try statement.setArguments(...)
|
||||
> try statement.execute()
|
||||
>
|
||||
> // Second option
|
||||
> try statement.execute(arguments: ...)
|
||||
> ```
|
||||
>
|
||||
> 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.
|
||||
>
|
||||
> Don't make a blind choice, and monitor your app performance if it really matters!
|
||||
|
||||
## Caching Prepared Statements
|
||||
|
||||
When the same query will be used several times in the lifetime of an application, one may feel a natural desire to cache prepared statements.
|
||||
|
||||
Don't cache statements yourself.
|
||||
|
||||
> Note: This is because an application lacks the necessary tools. Statements are tied to specific SQLite connections and dispatch queues which are not managed by the application, especially with a ``DatabasePool`` connection. A change in the database schema [may, or may not](https://www.sqlite.org/compile.html#max_schema_retry) invalidate a statement.
|
||||
|
||||
Instead, use the ``Database/cachedStatement(sql:)`` method. GRDB does all the hard caching and memory management:
|
||||
|
||||
```swift
|
||||
let statement = try db.cachedStatement(sql: "INSERT ...")
|
||||
```
|
||||
|
||||
The variant ``Database/cachedStatement(literal:)`` supports [SQL Interpolation]:
|
||||
|
||||
```swift
|
||||
let statement = try db.cachedStatement(literal: "INSERT ...")
|
||||
```
|
||||
|
||||
Should a cached prepared statement throw an error, don't reuse it. Instead, reload one from the cache.
|
||||
|
||||
## Parsing Multiple Prepared Statements from a Single SQL String
|
||||
|
||||
To build multiple statements joined with a semicolon, use ``Database/allStatements(sql:arguments:)``:
|
||||
|
||||
```swift
|
||||
let statements = try db.allStatements(sql: """
|
||||
INSERT INTO player (name, score) VALUES (?, ?);
|
||||
INSERT INTO player (name, score) VALUES (?, ?);
|
||||
""", arguments: ["Arthur", 100, "O'Brien", 1000])
|
||||
while let statement = try statements.next() {
|
||||
try statement.execute()
|
||||
}
|
||||
```
|
||||
|
||||
The variant ``Database/allStatements(literal:)`` supports [SQL Interpolation]:
|
||||
|
||||
```swift
|
||||
let statements = try db.allStatements(literal: """
|
||||
INSERT INTO player (name, score) VALUES (\("Arthur"), \(100));
|
||||
INSERT INTO player (name, score) VALUES (\("O'Brien"), \(1000));
|
||||
""")
|
||||
// An alternative way to iterate all statements
|
||||
try statements.forEach { statement in
|
||||
try statement.execute()
|
||||
}
|
||||
```
|
||||
|
||||
> Tip: When you intend to run all statements in an SQL string but don't care about individual ones, don't bother iterating individual statement instances! Skip this documentation section and just use ``Database/execute(sql:arguments:)``:
|
||||
>
|
||||
> ```swift
|
||||
> try db.execute(sql: """
|
||||
> CREATE TABLE player ...;
|
||||
> INSERT INTO player ...;
|
||||
> """)
|
||||
> ```
|
||||
|
||||
The results of multiple `SELECT` statements can be joined into a single ``Cursor``. This is the GRDB version of the [`sqlite3_exec()`](https://www.sqlite.org/c3ref/exec.html) function:
|
||||
|
||||
```swift
|
||||
let statements = try db.allStatements(sql: """
|
||||
SELECT ...;
|
||||
SELECT ...;
|
||||
""")
|
||||
let players = try statements.flatMap { statement in
|
||||
try Player.fetchCursor(statement)
|
||||
}
|
||||
for let player = try players.next() {
|
||||
print(player.name)
|
||||
}
|
||||
```
|
||||
|
||||
The ``SQLStatementCursor`` returned from `allStatements` can be turned into a regular Swift array, but in this case make sure all individual statements can compile even if the previous ones were not executed:
|
||||
|
||||
```swift
|
||||
// OK: Array of statements
|
||||
let statements = try Array(db.allStatements(sql: """
|
||||
INSERT ...;
|
||||
UPDATE ...;
|
||||
"""))
|
||||
|
||||
// FAILURE: Can't build an array of statements since the INSERT won't
|
||||
// compile until CREATE TABLE is executed.
|
||||
let statements = try Array(db.allStatements(sql: """
|
||||
CREATE TABLE player ...;
|
||||
INSERT INTO player ...;
|
||||
"""))
|
||||
```
|
||||
|
||||
## Topics
|
||||
|
||||
### Executing a Prepared Statement
|
||||
|
||||
- ``execute(arguments:)``
|
||||
|
||||
### Arguments
|
||||
|
||||
- ``arguments``
|
||||
- ``setArguments(_:)``
|
||||
- ``setUncheckedArguments(_:)``
|
||||
- ``validateArguments(_:)``
|
||||
- ``StatementArguments``
|
||||
|
||||
### Statement Informations
|
||||
|
||||
- ``columnCount``
|
||||
- ``columnNames``
|
||||
- ``databaseRegion``
|
||||
- ``index(ofColumn:)``
|
||||
- ``isReadonly``
|
||||
- ``sql``
|
||||
- ``sqliteStatement``
|
||||
- ``SQLiteStatement``
|
||||
|
||||
|
||||
[SQL Interpolation]: https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md
|
||||
@@ -0,0 +1,255 @@
|
||||
# ``GRDB/TransactionObserver``
|
||||
|
||||
A type that tracks database changes and transactions performed in a database.
|
||||
|
||||
## Overview
|
||||
|
||||
`TransactionObserver` is the low-level protocol that supports all <doc:DatabaseObservation> features.
|
||||
|
||||
A transaction observer is notified of individual changes (inserts, updates and deletes), before they are committed to disk, as well as transaction commits and rollbacks.
|
||||
|
||||
## Activate a Transaction Observer
|
||||
|
||||
An observer starts receiving change notifications after it has been added to a database connection with the ``DatabaseWriter/add(transactionObserver:extent:)`` `DatabaseWriter` method, or the ``Database/add(transactionObserver:extent:)`` `Database` method:
|
||||
|
||||
```swift
|
||||
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.
|
||||
|
||||
## 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).
|
||||
|
||||
Transaction completions are notified to the ``databaseWillCommit()-7mksu``, ``databaseDidCommit(_:)`` and ``databaseDidRollback(_:)`` callbacks.
|
||||
|
||||
The only changes and transactions that are not notified are:
|
||||
|
||||
- Read-only transactions.
|
||||
- Changes and transactions performed by external database connections.
|
||||
- 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).
|
||||
|
||||
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:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
try db.execute(sql: "INSERT ...") // 1. didChange
|
||||
try db.execute(sql: "UPDATE ...") // 2. didChange
|
||||
} // 3. willCommit, 4. didCommit
|
||||
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute(sql: "INSERT ...") // 1. didChange
|
||||
try db.execute(sql: "UPDATE ...") // 2. didChange
|
||||
return .rollback // 3. didRollback
|
||||
}
|
||||
|
||||
try dbQueue.write { db in
|
||||
try db.execute(sql: "INSERT ...") // 1. didChange
|
||||
throw SomeError()
|
||||
} // 2. didRollback
|
||||
```
|
||||
|
||||
Database statements that are executed outside of any explicit transaction do not drop off the radar:
|
||||
|
||||
```swift
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
try db.execute(sql: "INSERT ...") // 1. didChange, 2. willCommit, 3. didCommit
|
||||
try db.execute(sql: "UPDATE ...") // 4. didChange, 5. willCommit, 6. didCommit
|
||||
}
|
||||
```
|
||||
|
||||
Changes that are on hold because of a [savepoint](https://www.sqlite.org/lang_savepoint.html) are only notified after the savepoint has been released. This makes sure that notified events are only those that have an opportunity to be committed:
|
||||
|
||||
```swift
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute(sql: "INSERT ...") // 1. didChange
|
||||
|
||||
try db.execute(sql: "SAVEPOINT foo")
|
||||
try db.execute(sql: "UPDATE ...") // delayed
|
||||
try db.execute(sql: "UPDATE ...") // delayed
|
||||
try db.execute(sql: "RELEASE SAVEPOINT foo") // 2. didChange, 3. didChange
|
||||
|
||||
try db.execute(sql: "SAVEPOINT bar")
|
||||
try db.execute(sql: "UPDATE ...") // not notified
|
||||
try db.execute(sql: "ROLLBACK TO SAVEPOINT bar")
|
||||
try db.execute(sql: "RELEASE SAVEPOINT bar")
|
||||
|
||||
return .commit // 4. willCommit, 5. didCommit
|
||||
}
|
||||
```
|
||||
|
||||
Eventual errors thrown from `databaseWillCommit` are exposed to the application code:
|
||||
|
||||
```swift
|
||||
do {
|
||||
try dbQueue.inTransaction { db in
|
||||
...
|
||||
return .commit // 1. willCommit (throws), 2. didRollback
|
||||
}
|
||||
} catch {
|
||||
// 3. The error thrown by the transaction observer.
|
||||
}
|
||||
```
|
||||
|
||||
- Note: All callbacks are called in the writer dispatch queue, and serialized with all database updates.
|
||||
|
||||
- Note: The `databaseDidChange` and `databaseWillCommit` callbacks must not touch the SQLite database. This limitation does not apply to `databaseDidCommit` and `databaseDidRollback` which can use their database argument.
|
||||
|
||||
## Filtering Database Events
|
||||
|
||||
**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:
|
||||
|
||||
```swift
|
||||
// Calls `observes(eventsOfKind:)` once.
|
||||
// Calls `databaseDidChange(with:)` for every updated row, or not at all.
|
||||
try db.execute(sql: "UPDATE player SET score = score + 1")
|
||||
```
|
||||
|
||||
The ``DatabaseEventKind`` argument of `observes(eventsOfKind:)` can distinguish insertions from deletions and updates, and is also able to tell the columns that are about to be changed.
|
||||
|
||||
For example, an observer can focus on the changes that happen on the "player" database table only:
|
||||
|
||||
```swift
|
||||
class PlayerObserver: TransactionObserver {
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
// Only observe changes to the "player" table.
|
||||
eventKind.tableName == "player"
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
// This method is only called for changes that happen to
|
||||
// the "player" table.
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
When the `observes(eventsOfKind:)` method returns false for all event kinds, the observer is still notified of transactions.
|
||||
|
||||
## Observation Extent
|
||||
|
||||
**You can specify how long an observer is notified of database changes and transactions.**
|
||||
|
||||
The `remove(transactionObserver:)` method explicitly stops notifications, at any time:
|
||||
|
||||
```swift
|
||||
// From a database queue or pool:
|
||||
dbQueue.remove(transactionObserver: observer)
|
||||
|
||||
// From a database connection:
|
||||
dbQueue.inDatabase { db in
|
||||
db.remove(transactionObserver: observer)
|
||||
}
|
||||
```
|
||||
|
||||
Alternatively, use the `extent` parameter of the `add(transactionObserver:extent:)` method:
|
||||
|
||||
```swift
|
||||
let observer = MyObserver()
|
||||
|
||||
// On a database queue or pool:
|
||||
dbQueue.add(transactionObserver: observer) // default extent
|
||||
dbQueue.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
dbQueue.add(transactionObserver: observer, extent: .nextTransaction)
|
||||
dbQueue.add(transactionObserver: observer, extent: .databaseLifetime)
|
||||
|
||||
// On a database connection:
|
||||
dbQueue.inDatabase { db in
|
||||
db.add(transactionObserver: ...)
|
||||
}
|
||||
```
|
||||
|
||||
- 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.
|
||||
|
||||
- `.databaseLifetime` has the database retain and notify the observer until the database connection is closed.
|
||||
|
||||
Finally, an observer can avoid processing database changes until the end of the current transaction. After ``stopObservingDatabaseChangesUntilNextTransaction()``, the `databaseDidChange` callback will not be called until the current transaction completes:
|
||||
|
||||
```swift
|
||||
class PlayerObserver: TransactionObserver {
|
||||
var playerTableWasModified = false
|
||||
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
eventKind.tableName == "player"
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
playerTableWasModified = true
|
||||
|
||||
// It is pointless to keep on tracking further changes:
|
||||
stopObservingDatabaseChangesUntilNextTransaction()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Support for SQLite Pre-Update Hooks
|
||||
|
||||
When SQLite is built with the `SQLITE_ENABLE_PREUPDATE_HOOK` option, `TransactionObserver` gets an extra callback which lets you observe individual column values in the rows modified by a transaction:
|
||||
|
||||
```swift
|
||||
protocol TransactionObserver: AnyObject {
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
/// Notifies before a database change (insert, update, or delete)
|
||||
/// with change information (initial / final values for the row's
|
||||
/// columns).
|
||||
///
|
||||
/// The event is only valid for the duration of this method call. If you
|
||||
/// need to keep it longer, store a copy: event.copy().
|
||||
func databaseWillChange(with event: DatabasePreUpdateEvent)
|
||||
#endif
|
||||
}
|
||||
```
|
||||
|
||||
This extra API can be activated in two ways:
|
||||
|
||||
1. Use the GRDB.swift CocoaPod with a custom compilation option, as below.
|
||||
|
||||
It uses the system SQLite, which is compiled with `SQLITE_ENABLE_PREUPDATE_HOOK` support, but only on iOS 11.0+ (we don't know the minimum version of macOS, tvOS, watchOS):
|
||||
|
||||
```ruby
|
||||
pod 'GRDB.swift'
|
||||
platform :ios, '11.0' # or above
|
||||
|
||||
post_install do |installer|
|
||||
installer.pods_project.targets.select { |target| target.name == "GRDB.swift" }.each do |target|
|
||||
target.build_configurations.each do |config|
|
||||
# Enable extra GRDB APIs
|
||||
config.build_settings['OTHER_SWIFT_FLAGS'] = "$(inherited) -D SQLITE_ENABLE_PREUPDATE_HOOK"
|
||||
# Enable extra SQLite APIs
|
||||
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = "$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1"
|
||||
end
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
**Warning**: make sure you use the right platform version! You will get runtime errors on devices with a lower version.
|
||||
|
||||
**Note**: the `GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1` option in `GCC_PREPROCESSOR_DEFINITIONS` defines some C function prototypes that are lacking from the system `<sqlite3.h>` header. When Xcode eventually ships with an SDK that includes a complete header, you may get a compiler error about duplicate function definitions. When this happens, just remove this `GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1` option.
|
||||
|
||||
2. Use a [custom SQLite build](http://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md) and activate the `SQLITE_ENABLE_PREUPDATE_HOOK` compilation option.
|
||||
|
||||
## Topics
|
||||
|
||||
### Filtering Database Changes
|
||||
|
||||
- ``observes(eventsOfKind:)``
|
||||
- ``DatabaseEventKind``
|
||||
|
||||
### Handling Database Changes
|
||||
|
||||
- ``databaseDidChange(with:)``
|
||||
- ``stopObservingDatabaseChangesUntilNextTransaction()``
|
||||
- ``DatabaseEvent``
|
||||
|
||||
### Handling Transactions
|
||||
|
||||
- ``databaseWillCommit()-7mksu``
|
||||
- ``databaseDidCommit(_:)``
|
||||
- ``databaseDidRollback(_:)``
|
||||
@@ -0,0 +1,267 @@
|
||||
# ``GRDB/ValueObservation``
|
||||
|
||||
`ValueObservation` tracks changes in the results of database requests, and notifies fresh values whenever the database changes.
|
||||
|
||||
## 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).
|
||||
|
||||
The only changes that are not notified are:
|
||||
|
||||
- Changes performed by external database connections. See <doc:DatabaseSharing#How-to-perform-cross-process-database-observation> for more information.
|
||||
- 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.
|
||||
|
||||
## ValueObservation Usage
|
||||
|
||||
1. Make sure that a unique 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:
|
||||
|
||||
```swift
|
||||
let observation = ValueObservation.tracking { db in
|
||||
// Fetch and return the observed value
|
||||
}
|
||||
|
||||
// For example, an observation of [Player], which tracks all players:
|
||||
let observation = ValueObservation.tracking { db in
|
||||
try Player.fetchAll(db)
|
||||
}
|
||||
|
||||
// The same observation, using shorthand notation:
|
||||
let observation = ValueObservation.tracking(Player.fetchAll)
|
||||
```
|
||||
|
||||
There is no limit on the values that can be observed. An observation can perform multiple requests, from multiple database tables, and use raw SQL. See ``tracking(_:)`` for some examples.
|
||||
|
||||
3. Start the observation in order to be notified of changes:
|
||||
|
||||
```swift
|
||||
let cancellable = observation.start(in: dbQueue) { error in
|
||||
// Handle error
|
||||
} onChange: { (players: [Player]) in
|
||||
print("Fresh players", players)
|
||||
}
|
||||
```
|
||||
|
||||
4. Stop the observation by calling the ``DatabaseCancellable/cancel()`` method on the object returned by the `start` method. Cancellation is automatic when the cancellable is deallocated:
|
||||
|
||||
```swift
|
||||
cancellable.cancel()
|
||||
```
|
||||
|
||||
`ValueObservation` can also be turned into an async sequence, a Combine publisher, or an RxSwift observable (see the companion library [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB)):
|
||||
|
||||
- Async sequence:
|
||||
|
||||
```swift
|
||||
do {
|
||||
for try await players in observation.values(in: dbQueue) {
|
||||
print("Fresh players", players)
|
||||
}
|
||||
} catch {
|
||||
// Handle error
|
||||
}
|
||||
```
|
||||
|
||||
- Combine Publisher:
|
||||
|
||||
```swift
|
||||
let cancellable = observation.publisher(in: dbQueue).sink { completion in
|
||||
// Handle completion
|
||||
} receiveValue: { (players: [Player]) in
|
||||
print("Fresh players", players)
|
||||
}
|
||||
```
|
||||
|
||||
## ValueObservation Behavior
|
||||
|
||||
`ValueObservation` notifies an initial value before the eventual 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 dispatch queue, asynchronously. This can be configured: see <doc:ValueObservation#ValueObservation-Scheduling>.
|
||||
|
||||
`ValueObservation` may coalesce subsequent changes into a single notification.
|
||||
|
||||
`ValueObservation` may notify consecutive identical values. You can filter out the undesired duplicates with the ``removeDuplicates()`` method.
|
||||
|
||||
Starting an observation retains the database connection, until it is stopped. As long as the observation is active, the database connection won't be deallocated.
|
||||
|
||||
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.
|
||||
>
|
||||
> 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``.
|
||||
>
|
||||
> If you need to process changes before they are committed to disk, use ``TransactionObserver``.
|
||||
|
||||
## ValueObservation Scheduling
|
||||
|
||||
By default, `ValueObservation` notifies the initial value, as well as eventual changes and errors, on the main dispatch queue, asynchronously:
|
||||
|
||||
```swift
|
||||
// The default scheduling
|
||||
let cancellable = observation.start(in: dbQueue) { error in
|
||||
// Called asynchronously on the main dispatch queue
|
||||
} onChange: { value in
|
||||
// Called asynchronously on the main dispatch queue
|
||||
print("Fresh value", value)
|
||||
}
|
||||
```
|
||||
|
||||
You can change this behavior by adding a `scheduling` argument to the `start()` method.
|
||||
|
||||
For example, the ``ValueObservationScheduler/immediate`` scheduler notifies all values on the main dispatch queue, 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!
|
||||
|
||||
The `immediate` scheduling requires that the observation starts from the main dispatch queue (a fatal error is raised otherwise):
|
||||
|
||||
```swift
|
||||
let cancellable = observation.start(in: dbQueue, scheduling: .immediate) { error in
|
||||
// Called on the main dispatch queue
|
||||
} onChange: { value in
|
||||
// Called on the main dispatch queue
|
||||
print("Fresh value", value)
|
||||
}
|
||||
// <- Here "Fresh value" has already been printed.
|
||||
```
|
||||
|
||||
The other built-in scheduler ``ValueObservationScheduler/async(onQueue:)`` asynchronously schedules values and errors on the dispatch queue of your choice.
|
||||
|
||||
## 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.
|
||||
|
||||
You build a shared observation with ``shared(in:scheduling:extent:)``:
|
||||
|
||||
```swift
|
||||
// SharedValueObservation<[Player]>
|
||||
let sharedObservation = ValueObservation
|
||||
.tracking { db in try Player.fetchAll(db) }
|
||||
.shared(in: dbQueue)
|
||||
```
|
||||
|
||||
`ValueObservation` and `SharedValueObservation` are nearly identical, but the latter has no operator such as `map`. As a replacement, you may for example use Combine apis:
|
||||
|
||||
```swift
|
||||
let cancellable = try sharedObservation
|
||||
.publisher() // Turn shared observation into a Combine Publisher
|
||||
.map { ... } // The map operator from Combine
|
||||
.sink(...)
|
||||
```
|
||||
|
||||
|
||||
## Specifying the Tracked Region
|
||||
|
||||
While the standard ``tracking(_:)`` method lets you track changes to a fetched value and receive any changes to it, sometimes your use case might require more granular control.
|
||||
|
||||
Consider a scenario where you'd like to get a specific Player's row, but only when their `score` column changes. You can use ``tracking(region:_:fetch:)`` to do just that:
|
||||
|
||||
```swift
|
||||
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),
|
||||
// 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) }
|
||||
)
|
||||
```
|
||||
|
||||
This ``tracking(region:_:fetch:)`` method lets you entirely separate the **observed region(s)** from the **fetched value** itself, for maximum flexibility. See ``DatabaseRegionConvertible`` for more information about the regions that can be tracked.
|
||||
|
||||
## ValueObservation Performance
|
||||
|
||||
This section further describes runtime aspects of `ValueObservation`, and provides some optimization tips for demanding applications.
|
||||
|
||||
**`ValueObservation` is triggered by database transactions that may modify the tracked value.**
|
||||
|
||||
Precisely speaking, `ValueObservation` tracks changes in a ``DatabaseRegion``, not changes in values.
|
||||
|
||||
For example, if you track the maximum score of players, all transactions that impact the `score` column of the `player` database table (any update, insertion, or deletion) trigger the observation, even if the maximum score itself is not changed.
|
||||
|
||||
You can filter out undesired duplicate notifications with the ``removeDuplicates()`` method.
|
||||
|
||||
**ValueObservation can create database contention.** In other words, active observations take a toll on the constrained database resources. When triggered by impactful transactions, observations fetch fresh values, and can delay read and write database accesses of other application components.
|
||||
|
||||
When needed, you can help GRDB optimize observations and reduce database contention:
|
||||
|
||||
> 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.
|
||||
|
||||
> 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:)``.
|
||||
|
||||
> Tip: When the observation processes some raw fetched values, use the ``map(_:)`` operator:
|
||||
>
|
||||
> ```swift
|
||||
> // Plain observation
|
||||
> let observation = ValueObservation.tracking { db -> MyValue in
|
||||
> let players = try Player.fetchAll(db)
|
||||
> return computeMyValue(players)
|
||||
> }
|
||||
>
|
||||
> // Optimized observation
|
||||
> let observation = ValueObservation
|
||||
> .tracking { db try Player.fetchAll(db) }
|
||||
> .map { players in computeMyValue(players) }
|
||||
> ```
|
||||
>
|
||||
> The `map` operator performs its job without blocking database accesses, and without blocking the main thread.
|
||||
|
||||
> Tip: When the observation tracks a constant database region, create an optimized observation with the ``trackingConstantRegion(_:)`` method. See the documentation of this method for more information about what constitutes a "constant region", and the nature of the optimization.
|
||||
|
||||
**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).
|
||||
|
||||
|
||||
## Topics
|
||||
|
||||
### Creating a ValueObservation
|
||||
|
||||
- ``tracking(_:)``
|
||||
- ``trackingConstantRegion(_:)``
|
||||
- ``tracking(region:_:fetch:)``
|
||||
- ``tracking(regions:fetch:)``
|
||||
|
||||
### Creating a Shared Observation
|
||||
|
||||
- ``shared(in:scheduling:extent:)``
|
||||
- ``SharedValueObservationExtent``
|
||||
|
||||
### Accessing Observed Values
|
||||
|
||||
- ``publisher(in:scheduling:)``
|
||||
- ``start(in:scheduling:onError:onChange:)``
|
||||
- ``values(in:scheduling:bufferingPolicy:)``
|
||||
- ``DatabaseCancellable``
|
||||
- ``ValueObservationScheduler``
|
||||
|
||||
### Mapping Values
|
||||
|
||||
- ``map(_:)``
|
||||
|
||||
### Filtering Values
|
||||
|
||||
- ``removeDuplicates()``
|
||||
- ``removeDuplicates(by:)``
|
||||
|
||||
### Requiring Write Access
|
||||
|
||||
- ``requiresWriteAccess``
|
||||
|
||||
### Debugging
|
||||
|
||||
- ``handleEvents(willStart:willFetch:willTrackRegion:databaseDidChange:didReceiveValue:didFail:didCancel:)``
|
||||
- ``print(_:to:)``
|
||||
|
||||
### Support
|
||||
|
||||
- ``ValueReducer``
|
||||
@@ -0,0 +1,106 @@
|
||||
# ``GRDB``
|
||||
|
||||
A toolkit for SQLite databases, with a focus on application development
|
||||
|
||||
##
|
||||
|
||||

|
||||
|
||||
- [GitHub Repository](http://github.com/groue/GRDB.swift)
|
||||
- [Installation Instructions, encryption with SQLCipher, custom SQLite builds](https://github.com/groue/GRDB.swift#installation)
|
||||
- [GRDBQuery](https://github.com/groue/GRDBQuery), the SwiftUI companion for GRDB
|
||||
|
||||
## Overview
|
||||
|
||||
Use this library to save your application’s permanent data into SQLite databases. It comes with built-in tools that address common needs:
|
||||
|
||||
- **SQL Generation**
|
||||
|
||||
Enhance your application models with persistence and fetching methods, so that you don't have to deal with SQL and raw database rows when you don't want to.
|
||||
|
||||
- **Database Observation**
|
||||
|
||||
Get notifications when database values are modified.
|
||||
|
||||
- **Robust Concurrency**
|
||||
|
||||
Multi-threaded applications can efficiently use their databases, including WAL databases that support concurrent reads and writes.
|
||||
|
||||
- **Migrations**
|
||||
|
||||
Evolve the schema of your database as you ship new versions of your application.
|
||||
|
||||
- **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!
|
||||
|
||||
## Usage
|
||||
|
||||
Start using the database in four steps:
|
||||
|
||||
```swift
|
||||
import GRDB
|
||||
|
||||
// 1. Open a database connection
|
||||
let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
|
||||
|
||||
// 2. Define the database schema
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.primaryKey("id", .text)
|
||||
t.column("name", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Define a record type
|
||||
struct Player: Codable, FetchableRecord, PersistableRecord {
|
||||
var id: String
|
||||
var name: String
|
||||
var score: Int
|
||||
}
|
||||
|
||||
// 4. Write and read in the database
|
||||
try dbQueue.write { db in
|
||||
try Player(id: "1", name: "Arthur", score: 100).insert(db)
|
||||
try Player(id: "2", name: "Barbara", score: 1000).insert(db)
|
||||
}
|
||||
|
||||
let players: [Player] = try dbQueue.read { db in
|
||||
try Player.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Topics
|
||||
|
||||
### Fundamentals
|
||||
|
||||
- <doc:DatabaseConnections>
|
||||
- <doc:SQLSupport>
|
||||
- <doc:Concurrency>
|
||||
- <doc:Transactions>
|
||||
|
||||
### Migrations and The Database Schema
|
||||
|
||||
- <doc:DatabaseSchema>
|
||||
- <doc:Migrations>
|
||||
|
||||
### Records and the Query Interface
|
||||
|
||||
- <doc:QueryInterface>
|
||||
- <doc:RecordRecommendedPractices>
|
||||
- <doc:RecordTimestamps>
|
||||
- <doc:SingleRowTables>
|
||||
|
||||
### Responding to Database Changes
|
||||
|
||||
- <doc:DatabaseObservation>
|
||||
|
||||
### Full-Text Search
|
||||
|
||||
- <doc:FullTextSearch>
|
||||
|
||||
### Combine Publishers
|
||||
|
||||
- ``DatabasePublishers``
|
||||
@@ -33,7 +33,7 @@ migrator.registerMigration("Add books and author.birthYear") { db in
|
||||
t.column("title", .text).notNull()
|
||||
}
|
||||
|
||||
try db.alter(table: "author") { t
|
||||
try db.alter(table: "author") { t in
|
||||
t.add(column: "birthYear", .integer)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
|
||||
Record types and the query interface build SQL queries for you.
|
||||
|
||||
## Overview
|
||||
|
||||
For an overview, see [Records](https://github.com/groue/GRDB.swift/blob/master/README.md#records), and [The Query Interface](https://github.com/groue/GRDB.swift/blob/master/README.md#the-query-interface).
|
||||
|
||||
## Topics
|
||||
|
||||
### Records
|
||||
|
||||
@@ -0,0 +1,581 @@
|
||||
# Recommended Practices for Designing Record Types
|
||||
|
||||
Leverage the best of record types and associations.
|
||||
|
||||
## Overview
|
||||
|
||||
GRDB sits right between low-level SQLite wrappers, and high-level ORMs like [Core Data], so you may face questions when designing the model layer of your application.
|
||||
|
||||
This is the topic of this article. Examples will be illustrated with a simple library database made of books and their authors.
|
||||
|
||||
## Trust SQLite More Than Yourself
|
||||
|
||||
Let's put things in the right order. An SQLite database stored on a user's device is more important than the Swift code that accesses it. When a user installs a new version of an application, only the database stored on the user's device remains the same. But all the Swift code may have changed.
|
||||
|
||||
This is why it is recommended to define a **robust database schema** even before playing with record types.
|
||||
|
||||
This is important because SQLite is very robust, whereas we developers write bugs. The more responsibility we give to SQLite, the less code we have to write, and the fewer defects we will ship on our users' devices, affecting their precious data.
|
||||
|
||||
For example, if we were to define <doc:Migrations> that configure a database made of books and their authors, we could write:
|
||||
|
||||
```swift
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
migrator.registerMigration("createLibrary") { db in
|
||||
try db.create(table: "author") { t in // (1)
|
||||
t.autoIncrementedPrimaryKey("id") // (2)
|
||||
t.column("name", .text).notNull() // (3)
|
||||
t.column("countryCode", .text) // (4)
|
||||
}
|
||||
|
||||
try db.create(table: "book") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("title", .text).notNull() // (5)
|
||||
t.column("authorId", .integer) // (6)
|
||||
.notNull() // (7)
|
||||
.indexed() // (8)
|
||||
.references("author", onDelete: .cascade) // (9)
|
||||
}
|
||||
}
|
||||
|
||||
try migrator.migrate(dbQueue)
|
||||
```
|
||||
|
||||
1. Our database tables follow the <doc:DatabaseSchema#Database-Schema-Recommendations>: table names are English, singular, and camelCased. They look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`.
|
||||
2. Each author has a unique id.
|
||||
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.
|
||||
7. The `book.authorId` column is not null so that SQLite guarantees that all books have an author.
|
||||
8. The `book.authorId` column is indexed in order to ease the selection of an author's books.
|
||||
9. We define a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book can refer to a missing author. On top of that, 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.
|
||||
|
||||
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.
|
||||
|
||||
> Tip: **Plan early for future versions of your application**: use <doc:Migrations>.
|
||||
|
||||
## Record Types
|
||||
|
||||
### Persistable Record Types are Responsible for Their Tables
|
||||
|
||||
**Define one record type per database table.** This record type will be responsible for writing in this table.
|
||||
|
||||
**Let's start from regular structs** whose properties match the columns in their database table. Those structs conform to the standard [`Identifiable`] protocol because they have an identifier (the primary key). They conform to the standard [`Codable`] protocol so that we don't have to write the methods that convert to and from raw database rows.
|
||||
|
||||
```swift
|
||||
struct Author: Codable, Identifiable {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
var countryCode: String?
|
||||
}
|
||||
|
||||
struct Book: Codable, Identifiable {
|
||||
var id: Int64?
|
||||
var authorId: Int64
|
||||
var title: String
|
||||
}
|
||||
```
|
||||
|
||||
**We add database powers to our types with record protocols.**
|
||||
|
||||
The `author` and `book` tables have an auto-incremented id. We want inserted records to learn about their id after a successful insertion. That's why we have them conform to the ``MutablePersistableRecord`` protocol, and implement ``MutablePersistableRecord/didInsert(_:)-109jm``. Other kinds of record types would just use ``PersistableRecord``, and ignore `didInsert`.
|
||||
|
||||
On the reading side, we use ``FetchableRecord``, the protocol that can decode database rows.
|
||||
|
||||
This gives:
|
||||
|
||||
```swift
|
||||
// Add Database access
|
||||
extension Author: FetchableRecord, MutablePersistableRecord {
|
||||
// Update auto-incremented id upon successful insertion
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
extension Book: FetchableRecord, MutablePersistableRecord {
|
||||
// Update auto-incremented id upon successful insertion
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
That's it. The `Author` type can read and write in the `author` database table. `Book` as well, in `book`:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// Insert and set author's id
|
||||
var author = Author(name: "Herman Melville", countryCode: "US")
|
||||
try author.insert(db)
|
||||
|
||||
// Insert and set book's id
|
||||
var book = Book(authorId: author.id!, title: "Moby-Dick")
|
||||
try book.insert(db)
|
||||
}
|
||||
|
||||
let books = try dbQueue.read { db in
|
||||
try Book.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
> 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:
|
||||
>
|
||||
> ```swift
|
||||
> try db.create(table: "author") { t in
|
||||
> t.autoIncrementedPrimaryKey("id")
|
||||
> t.column("name", .text).notNull() // Can't be NULL
|
||||
> t.column("countryCode", .text) // Can be NULL
|
||||
> }
|
||||
>
|
||||
> struct Author: Codable, Identifiable {
|
||||
> var id: Int64?
|
||||
> var name: String // Not optional
|
||||
> var countryCode: String? // Optional
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> 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!
|
||||
>
|
||||
> 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.
|
||||
|
||||
> Tip: When the database table has a single-column primary key, have the record type adopt the standard [`Identifiable`] protocol. This allows GRDB to define extra methods based on record ids:
|
||||
>
|
||||
> ```swift
|
||||
> let authorID: Int64 = 42
|
||||
> let author: Author = try dbQueue.read { db in
|
||||
> try Author.find(db, id: authorID)
|
||||
> }
|
||||
> ```
|
||||
|
||||
### 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.)
|
||||
|
||||
But it happens that 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.
|
||||
|
||||
Let's look at three examples.
|
||||
|
||||
#### First Example: Enums
|
||||
|
||||
Authors write books, and more specifically novels, poems, essays, or theatre plays. Let's add a `kind` column in the database. We decide that a book kind is represented as a string ("novel", "essay", etc.) in the database:
|
||||
|
||||
```swift
|
||||
try db.create(table: "book") { t in
|
||||
...
|
||||
t.column("kind", .text).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
In Swift, it is not a good practice to use `String` for the type of the `kind` property. We prefer an enum instead:
|
||||
|
||||
```swift
|
||||
struct Book: Codable {
|
||||
enum Kind: String, Codable {
|
||||
case essay, novel, poetry, theater
|
||||
}
|
||||
var id: Int64?
|
||||
var authorId: Int64
|
||||
var title: String
|
||||
var kind: Kind
|
||||
}
|
||||
```
|
||||
|
||||
Thanks to its enum property, the `Book` record prevents invalid book kinds from being stored into the database.
|
||||
|
||||
In order to use `Book.Kind` in database requests for books (see <doc:RecordRecommendedPractices#Record-Requests> below), we add the ``DatabaseValueConvertible`` conformance to `Book.Kind`:
|
||||
|
||||
```swift
|
||||
extension Book.Kind: DatabaseValueConvertible { }
|
||||
|
||||
// Fetch all novels
|
||||
let novels = try dbQueue.read { db in
|
||||
try Book.filter(Column("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.
|
||||
|
||||
When this happens, keep column properties private, and provide sensible accessors instead:
|
||||
|
||||
```swift
|
||||
try db.create(table: "place") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
t.column("latitude", .double).notNull()
|
||||
t.column("longitude", .double).notNull()
|
||||
}
|
||||
|
||||
struct Place: Codable {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
private var latitude: CLLocationDegrees
|
||||
private var longitude: CLLocationDegrees
|
||||
|
||||
var coordinate: CLLocationCoordinate2D {
|
||||
get {
|
||||
CLLocationCoordinate2D(
|
||||
latitude: latitude,
|
||||
longitude: longitude)
|
||||
}
|
||||
set {
|
||||
latitude = newValue.latitude
|
||||
longitude = newValue.longitude
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Generally speaking, private properties make it possible to hide raw columns from the rest of the application. The next example shows another application of this technique.
|
||||
|
||||
#### 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).
|
||||
|
||||
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.
|
||||
|
||||
That's why the `Product` record type has a `price: Decimal` property, backed by a `priceCents` integer column:
|
||||
|
||||
```swift
|
||||
try db.create(table: "product") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
t.column("priceCents", .integer).notNull()
|
||||
}
|
||||
|
||||
struct Product: Codable {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
private var priceCents: Int
|
||||
|
||||
var price: Decimal {
|
||||
get {
|
||||
Decimal(priceCents) / 100
|
||||
}
|
||||
set {
|
||||
priceCents = Self.cents(for: newValue)
|
||||
}
|
||||
}
|
||||
|
||||
private static func cents(for value: Decimal) -> Int {
|
||||
Int(Double(truncating: NSDecimalNumber(decimal: value * 100)))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Record Requests
|
||||
|
||||
Once we have record types that are able to read and write in the database, we'd like to perform database requests of such records.
|
||||
|
||||
### 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:
|
||||
|
||||
```swift
|
||||
// HOW TO define columns for a Codable record
|
||||
extension Author {
|
||||
enum Columns {
|
||||
static let id = Column(CodingKeys.id)
|
||||
static let name = Column(CodingKeys.name)
|
||||
static let countryCode = Column(CodingKeys.countryCode)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
For other record types, declare a plain `String` enum that conforms to the ``ColumnExpression`` protocol:
|
||||
|
||||
```swift
|
||||
// HOW TO define columns for a non-Codable record
|
||||
extension Author {
|
||||
enum Columns: String, ColumnExpression {
|
||||
case id, name, countryCode
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
From those columns it is possible to define requests of type ``QueryInterfaceRequest``:
|
||||
|
||||
```swift
|
||||
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))
|
||||
.fetchAll(db)
|
||||
|
||||
// Count French authors
|
||||
let frenchAuthorCount: Int = try Author.all()
|
||||
.filter(Author.Columns.countryCode == "FR")
|
||||
.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
### Turn Commonly-Used Requests into Methods
|
||||
|
||||
An application can define reusable request methods that extend the built-in GRDB apis. Those methods avoid code repetition, ease refactoring, and foster testability.
|
||||
|
||||
Define those methods in extensions of the ``DerivableRequest`` protocol, as below:
|
||||
|
||||
```swift
|
||||
// Author requests
|
||||
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))
|
||||
}
|
||||
|
||||
/// Filters authors from a country
|
||||
func filter(countryCode: String) -> Self {
|
||||
filter(Author.Columns.countryCode == countryCode)
|
||||
}
|
||||
}
|
||||
|
||||
// Book requests
|
||||
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))
|
||||
}
|
||||
|
||||
/// Filters books by kind
|
||||
func filter(kind: Book.Kind) -> Self {
|
||||
filter(Book.Columns.kind == kind)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Those methods define a fluent and legible api that encapsulates intimate database details:
|
||||
|
||||
```swift
|
||||
try dbQueue.read { db in
|
||||
let sortedSpanishAuthors: [Author] = try Author.all()
|
||||
.filter(countryCode: "ES")
|
||||
.orderByName()
|
||||
.fetchAll(db)
|
||||
|
||||
let novelCount: Int = try Book.all()
|
||||
.filter(kind: .novel)
|
||||
.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
```swift
|
||||
extension QueryInterfaceRequest<Author> {
|
||||
// Selects author ids
|
||||
func selectId() -> QueryInterfaceRequest<Int64> {
|
||||
selectPrimaryKey(as: Int64.self)
|
||||
}
|
||||
}
|
||||
|
||||
// The ids of Japanese authors
|
||||
let ids: Set<Int64> = try Author.all()
|
||||
.filter(countryCode: "JP")
|
||||
.selectId()
|
||||
.fetchSet(db)
|
||||
```
|
||||
|
||||
## 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:
|
||||
|
||||
```swift
|
||||
extension Book {
|
||||
static let author = belongsTo(Author.self)
|
||||
}
|
||||
|
||||
extension Author {
|
||||
static let books = hasMany(Book.self)
|
||||
}
|
||||
```
|
||||
|
||||
With associations, you can fetch a book's author, or an author's books:
|
||||
|
||||
```swift
|
||||
// Fetch all novels from an author
|
||||
try dbQueue.read { db in
|
||||
let author: Author = ...
|
||||
let novels: [Book] = try author.request(for: Author.books)
|
||||
.filter(kind: .novel)
|
||||
.orderByTitle()
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
Associations also make it possible to define more convenience request methods:
|
||||
|
||||
```swift
|
||||
extension DerivableRequest<Book> {
|
||||
/// Filters books from a country
|
||||
func filter(authorCountryCode countryCode: String) -> Self {
|
||||
// Books do not have any country column. But their author has one!
|
||||
// Return books that can be joined to an author from this country:
|
||||
joining(required: Book.author.filter(countryCode: countryCode))
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch all Italian novels
|
||||
try dbQueue.read { db in
|
||||
let italianNovels: [Book] = try Book.all()
|
||||
.filter(kind: .novel)
|
||||
.filter(authorCountryCode: "IT")
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
With associations, you can also process graphs of authors and books, as described in the next section.
|
||||
|
||||
### How to Model Graphs of Objects
|
||||
|
||||
Since the beginning of this article, the `Book` and `Author` are independent structs that don't know each other. The only "meeting point" is the `Book.authorId` property.
|
||||
|
||||
Record types don't know each other on purpose: one does not need to know the author of a book when it's time to update the title of a book, for example.
|
||||
|
||||
When an application wants to process authors and books together, it defines dedicated types that model the desired view on the graph of related objects. For example:
|
||||
|
||||
```swift
|
||||
// Fetch all authors along with their number of books
|
||||
struct AuthorInfo: Decodable, FetchableRecord {
|
||||
var author: Author
|
||||
var bookCount: Int
|
||||
}
|
||||
let authorInfos: [AuthorInfo] = try dbQueue.read { db in
|
||||
try Author
|
||||
.annotated(with: Author.books.count)
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
```swift
|
||||
// Fetch the literary careers of German authors, sorted by name
|
||||
struct LiteraryCareer: Codable, FetchableRecord {
|
||||
var author: Author
|
||||
var books: [Book]
|
||||
}
|
||||
let careers: [LiteraryCareer] = try dbQueue.read { db in
|
||||
try Author
|
||||
.filter(countryCode: "DE")
|
||||
.orderByName()
|
||||
.including(all: Author.books)
|
||||
.asRequest(of: LiteraryCareer.self)
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
```swift
|
||||
// Fetch all Colombian books and their authors
|
||||
struct Authorship: Decodable, FetchableRecord {
|
||||
var book: Book
|
||||
var author: Author
|
||||
}
|
||||
let authorships: [Authorship] = try dbQueue.read { db in
|
||||
try Book.all()
|
||||
.including(required: Book.author.filter(countryCode: "CO"))
|
||||
.asRequest(of: Authorship.self)
|
||||
.fetchAll(db)
|
||||
|
||||
// Equivalent alternative
|
||||
try Book.all()
|
||||
.filter(authorCountryCode: "CO")
|
||||
.including(required: Book.author)
|
||||
.asRequest(of: Authorship.self)
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
In the above sample codes, 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`).
|
||||
|
||||
For more information about associations, see the [Associations] guide.
|
||||
|
||||
### Lazy and Eager Loading: Comparison with Other Database Libraries
|
||||
|
||||
The additional record types described in the previous section may look superfluous. Some other database libraries are able to navigate in graphs of records without additional types.
|
||||
|
||||
For example, [Core Data] and Ruby's [Active Record] use **lazy loading**. This means that relationships are lazily fetched on demand:
|
||||
|
||||
```ruby
|
||||
# Lazy loading with Active Record
|
||||
author = Author.first # Fetch first author
|
||||
puts author.name
|
||||
author.books.each do |book| # Lazily fetch books on demand
|
||||
puts book.title
|
||||
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.
|
||||
|
||||
Vapor [Fluent] uses **eager loading**, which means that relationships are only fetched if explicitly requested:
|
||||
|
||||
```swift
|
||||
// Eager loading with Fluent
|
||||
let query = Author.query(on: db)
|
||||
.with(\.$books) // <- Explicit request for books
|
||||
.first()
|
||||
|
||||
// Fetch first author and its books in one stroke
|
||||
if let author = query.get() {
|
||||
print(author.name)
|
||||
for book in author.books { print(book.title) }
|
||||
}
|
||||
```
|
||||
|
||||
One must take care of fetching relationships, though, or Fluent raises a fatal error:
|
||||
|
||||
```swift
|
||||
// Oops, the books relation is not explicitly requested
|
||||
let query = Author.query(on: db).first()
|
||||
if let author = query.get() {
|
||||
// fatal error: Children relation not eager loaded.
|
||||
for book in author.books { print(book.title) }
|
||||
}
|
||||
```
|
||||
|
||||
**GRDB supports eager loading**. The difference with Fluent is that the relationships are modelled in a dedicated record type that provides runtime safety:
|
||||
|
||||
```swift
|
||||
// Eager loading with GRDB
|
||||
struct LiteraryCareer: Codable, FetchableRecord {
|
||||
var author: Author
|
||||
var books: [Book]
|
||||
}
|
||||
|
||||
let request = Author.all()
|
||||
.including(all: Author.books) // <- Explicit request for books
|
||||
.asRequest(of: LiteraryCareer.self)
|
||||
|
||||
// Fetch first author and its books in one stroke
|
||||
if let career = try request.fetchOne(db) {
|
||||
print(career.author.name)
|
||||
for book in career.books { print(book.title) }
|
||||
}
|
||||
```
|
||||
|
||||
[Active Record]: http://guides.rubyonrails.org/active_record_basics.html
|
||||
[`Codable`]: https://developer.apple.com/documentation/swift/Codable
|
||||
[Core Data]: https://developer.apple.com/documentation/coredata
|
||||
[`Decimal`]: https://developer.apple.com/documentation/foundation/decimal
|
||||
[`Decodable`]: https://developer.apple.com/documentation/swift/Decodable
|
||||
[Django]: https://docs.djangoproject.com/en/4.2/topics/db/
|
||||
[Fluent]: https://docs.vapor.codes/fluent/overview/
|
||||
[`Identifiable`]: https://developer.apple.com/documentation/swift/identifiable
|
||||
[isolated]: https://en.wikipedia.org/wiki/Isolation_(database_systems)
|
||||
[Associations]: https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md
|
||||
@@ -4,15 +4,15 @@ Learn how applications can save creation and modification dates of records.
|
||||
|
||||
## Overview
|
||||
|
||||
Record timestamps are the responsibility of your application. This article provides some sample code that you can adapt for your specific needs.
|
||||
Some applications want to record creation and modification dates of database records. This article provides some advice and sample code that you can adapt for your specific needs.
|
||||
|
||||
> Note: Creation and modification timestamps can be automatically handled by [SQLite triggers](https://www.sqlite.org/lang_createtrigger.html). We'll explore a different technique.
|
||||
> Note: Creation and modification dates can be automatically handled by [SQLite triggers](https://www.sqlite.org/lang_createtrigger.html). We'll explore a different technique, though.
|
||||
>
|
||||
> This is not an advice against triggers, and you won't feel hindered in any way if you prefer to use triggers. Still, consider:
|
||||
>
|
||||
> - A trigger does not suffer any exception, when some applications eventually want to fine-tune timestamps, or to perform migrations without touching timestamps.
|
||||
> - The "current time" according to SQLite can't be controlled in tests and previews.
|
||||
> - The "current time" according to SQLite is not guaranteed to be constant in a given transaction, and this may create undesired timestamp variations.
|
||||
> - The current time, according to SQLite, is not guaranteed to be constant in a given transaction. This may create undesired timestamp variations. We'll see below how GRDB provides a date that is constant at any point during a transaction.
|
||||
> - The current time, according to SQLite, can't be controlled in tests and previews.
|
||||
|
||||
We'll start from this table and record type:
|
||||
|
||||
@@ -34,7 +34,7 @@ struct Player: Identifiable {
|
||||
}
|
||||
```
|
||||
|
||||
Note that the table has non-null dates, while the record has optional dates.
|
||||
See how the table has non-null dates, while the record has optional dates.
|
||||
|
||||
This is because we intend, in this article, to timestamp actual database operations. The `creationDate` property is the date of database insertion, and `modificationDate` is the date of last modification in the database. A new `Player` instance has no meaningful timestamp until it is saved, and this absence of information is represented with `nil`:
|
||||
|
||||
@@ -54,28 +54,46 @@ player.creationDate // not nil
|
||||
player.modificationDate // not nil
|
||||
```
|
||||
|
||||
In the rest of the article, we'll address insertion first, then updates, and finally we'll see a way to avoid those optional timestamps.
|
||||
In the rest of the article, we'll address insertion first, then updates, and see a way to avoid those optional timestamps. The article ends with a sample protocol that your app may adapt and reuse.
|
||||
|
||||
- <doc:RecordTimestamps#Insertion-Timestamp>
|
||||
- <doc:RecordTimestamps#Modification-Timestamp>
|
||||
- <doc:RecordTimestamps#Dealing-with-Optional-Timestamps>
|
||||
- <doc:RecordTimestamps#Sample-code-TimestampedRecord>
|
||||
|
||||
## Insertion Timestamp
|
||||
|
||||
On insertion, the record should get fresh `creationDate` and `modificationDate`. The ``MutablePersistableRecord`` protocol provides the necessary tooling:
|
||||
On insertion, the `Player` record should get fresh `creationDate` and `modificationDate`. The ``MutablePersistableRecord`` protocol provides the necessary tooling, with the ``MutablePersistableRecord/willInsert(_:)-1xfwo`` persistence callback. Before insertion, the record sets both its `creationDate` and `modificationDate`:
|
||||
|
||||
```swift
|
||||
extension Player: Encodable, MutablePersistableRecord {
|
||||
// Update auto-incremented id upon successful insertion
|
||||
/// Sets both `creationDate` and `modificationDate` to the
|
||||
/// transaction date, if they are not set yet.
|
||||
mutating func willInsert(_ db: Database) throws {
|
||||
if creationDate == nil {
|
||||
creationDate = try db.transactionDate
|
||||
}
|
||||
if modificationDate == nil {
|
||||
modificationDate = try db.transactionDate
|
||||
}
|
||||
}
|
||||
|
||||
/// Update auto-incremented id upon successful insertion
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
|
||||
// Update timestamps before insertion
|
||||
mutating func willInsert(_ db: Database) throws {
|
||||
creationDate = try db.transactionDate
|
||||
modificationDate = try db.transactionDate
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.write { db in
|
||||
// An inserted record has both a creation and a modification date.
|
||||
var player = Player(name: "Arthur", score: 1000)
|
||||
try player.insert(db)
|
||||
player.creationDate // not nil
|
||||
player.modificationDate // not nil
|
||||
}
|
||||
```
|
||||
|
||||
Note that we are using the ``Database/transactionDate`` instead of `Date()`. This has two advantages:
|
||||
The `willInsert` callback uses the ``Database/transactionDate`` instead of `Date()`. This has two advantages:
|
||||
|
||||
- Within a write transaction, all inserted players get the same timestamp:
|
||||
|
||||
@@ -95,9 +113,16 @@ Note that we are using the ``Database/transactionDate`` instead of `Date()`. Thi
|
||||
Let's now deal with updates. The `update` persistence method won't automatically bump the timestamp as the `insert` method does. We have to explicitly deal with the modification date:
|
||||
|
||||
```swift
|
||||
// Increment the player score.
|
||||
// Increment the player score (two different ways).
|
||||
try dbQueue.write { db in
|
||||
var player: Player
|
||||
|
||||
// Update all columns
|
||||
player.score += 1
|
||||
player.modificationDate = try db.transactionDate
|
||||
try player.update(db)
|
||||
|
||||
// Alternatively, update only the modified columns
|
||||
try player.updateChanges(db) {
|
||||
$0.score += 1
|
||||
$0.modificationDate = try db.transactionDate
|
||||
@@ -107,6 +132,24 @@ try dbQueue.write { db in
|
||||
|
||||
Again, we use ``Database/transactionDate``, so that all modified players get the same timestamp within a given write transaction.
|
||||
|
||||
> Note: The insertion case could profit from automatic initialization of the creation date with the ``MutablePersistableRecord/willInsert(_:)-1xfwo`` persistence callback, but the modification date is not handled with ``MutablePersistableRecord/willUpdate(_:columns:)-3oko4``. Instead, the above sample code explicitly modifies the modification date.
|
||||
>
|
||||
> This may look like an inconvenience, but there are several reasons for this:
|
||||
>
|
||||
> 1. The persistence methods that update are not mutating methods. `willUpdate` can not modify the modification date.
|
||||
>
|
||||
> 2. Automatic changes to the modification date from the general `update` method create problems.
|
||||
>
|
||||
> Developers are seduced by this convenient-looking feature, but they also eventually want to disable automatic timestamp updates in specific circumstances. That's because application requirements happen to change, and developers happen to overlook some corner cases.
|
||||
>
|
||||
> This need is well acknowledged by existing database libraries: to disable automatic timestamp updates, [ActiveRecord](https://stackoverflow.com/questions/861448/is-there-a-way-to-avoid-automatically-updating-rails-timestamp-fields) uses globals (not thread-safe in a Swift application), [Django ORM](https://stackoverflow.com/questions/7499767/temporarily-disable-auto-now-auto-now-add) does not make it easy, and [Fluent](https://github.com/vapor/fluent-kit/issues/355) simply does not allow it.
|
||||
>
|
||||
> None of those solutions or lack thereof are seducing.
|
||||
>
|
||||
> 3. Not all applications need one modification timestamp. For example, some need one timestamp per property, or per group of properties.
|
||||
>
|
||||
> By not providing automatic timestamp updates, all GRDB-powered applications are treated equally: they explicitly bump their modification timestamps when needed. Apps can help themselves by introducing protocols dedicated to their particular handling of updates. For an example of such a protocol, see <doc:RecordTimestamps#Sample-code-TimestampedRecord> below.
|
||||
|
||||
## Dealing with Optional Timestamps
|
||||
|
||||
When you fetch timestamped records from the database, it may be inconvenient to deal with optional dates, even though the database columns are guaranteed to be not null:
|
||||
@@ -119,46 +162,47 @@ player.creationDate // optional 😕
|
||||
player.modificationDate // optional 😕
|
||||
```
|
||||
|
||||
A possible technique is to define two record types.
|
||||
|
||||
One record can deal with unsaved players:
|
||||
A possible technique is to define two record types: one that deals with players in general (optional timestamps), and one that only deals with persisted players (non-optional dates):
|
||||
|
||||
```swift
|
||||
/// `Player` deals with unsaved players
|
||||
struct Player: Identifiable {
|
||||
var id: Int64?
|
||||
var creationDate: Date?
|
||||
var modificationDate: Date?
|
||||
var id: Int64? // optional
|
||||
var creationDate: Date? // optional
|
||||
var modificationDate: Date? // optional
|
||||
var name: String
|
||||
var score: Int
|
||||
}
|
||||
|
||||
extension Player: Encodable, MutablePersistableRecord {
|
||||
// Update auto-incremented id upon successful insertion
|
||||
/// Updates auto-incremented id upon successful insertion
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
|
||||
// Update timestamps before insertion
|
||||
/// Sets both `creationDate` and `modificationDate` to the
|
||||
/// transaction date, if they are not set yet.
|
||||
mutating func willInsert(_ db: Database) throws {
|
||||
creationDate = try db.transactionDate
|
||||
modificationDate = try db.transactionDate
|
||||
if creationDate == nil {
|
||||
creationDate = try db.transactionDate
|
||||
}
|
||||
if modificationDate == nil {
|
||||
modificationDate = try db.transactionDate
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The other record only deals with saved players:
|
||||
|
||||
```swift
|
||||
struct TimestampedPlayer: Identifiable {
|
||||
let id: Int64
|
||||
let creationDate: Date
|
||||
var modificationDate: Date
|
||||
/// `PersistedPlayer` deals with persisted players
|
||||
struct PersistedPlayer: Identifiable {
|
||||
let id: Int64 // not optional
|
||||
let creationDate: Date // not optional
|
||||
var modificationDate: Date // not optional
|
||||
var name: String
|
||||
var score: Int
|
||||
}
|
||||
|
||||
extension TimestampedPlayer: Codable, FetchableRecord, PersistableRecord {
|
||||
static var databaseTableName: String { Player.databaseTableName }
|
||||
extension PersistedPlayer: Codable, FetchableRecord, PersistableRecord {
|
||||
static var databaseTableName: String { "player" }
|
||||
}
|
||||
```
|
||||
|
||||
@@ -166,22 +210,231 @@ Usage:
|
||||
|
||||
```swift
|
||||
// Fetch
|
||||
let timestampedPlayer = try dbQueue.read { db
|
||||
try TimestampedPlayer.find(db, id: 1)
|
||||
try dbQueue.read { db
|
||||
let persistedPlayer = try PersistedPlayer.find(db, id: 1)
|
||||
persistedPlayer.creationDate // not optional
|
||||
persistedPlayer.modificationDate // not optional
|
||||
}
|
||||
timestampedPlayer.creationDate // not optional
|
||||
timestampedPlayer.modificationDate // not optional
|
||||
|
||||
// Insert
|
||||
try dbQueue.write { db in
|
||||
var player = Player(id: nil, name: "Arthur", score: 1000)
|
||||
player.id // nil
|
||||
player.creationDate // nil
|
||||
player.modificationDate // nil
|
||||
|
||||
let timestampedPlayer = try player.insertAndFetch(db, as: TimestampedPlayer.self)
|
||||
|
||||
timestampedPlayer.id // not optional
|
||||
timestampedPlayer.creationDate // not optional
|
||||
timestampedPlayer.modificationDate // not optional
|
||||
let persistedPlayer = try player.insertAndFetch(db, as: PersistedPlayer.self)
|
||||
persistedPlayer.id // not optional
|
||||
persistedPlayer.creationDate // not optional
|
||||
persistedPlayer.modificationDate // not optional
|
||||
}
|
||||
```
|
||||
|
||||
See ``MutablePersistableRecord/insertAndFetch(_:onConflict:as:)`` and related methods for more information.
|
||||
|
||||
## Sample code: TimestampedRecord
|
||||
|
||||
This section provides a sample protocol for records that track their creation and modification dates.
|
||||
|
||||
You can copy it in your application, or use it as an inspiration. Not all apps have the same needs regarding timestamps!
|
||||
|
||||
`TimestampedRecord` provides the following features and methods:
|
||||
|
||||
- Use it as a replacement for `MutablePersistableRecord` (even if your record does not use an auto-incremented primary key):
|
||||
|
||||
```swift
|
||||
// The base Player type
|
||||
struct Player: Identifiable {
|
||||
var id: Int64?
|
||||
var creationDate: Date?
|
||||
var modificationDate: Date?
|
||||
var name: String
|
||||
var score: Int
|
||||
}
|
||||
|
||||
// Add database powers (read, write, timestamps)
|
||||
extension Player: Codable, TimestampedRecord, FetchableRecord {
|
||||
/// Update auto-incremented id upon successful insertion
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- Timestamps are set on insertion:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// An inserted record has both a creation and a modification date.
|
||||
var player = Player(name: "Arthur", score: 1000)
|
||||
try player.insert(db)
|
||||
player.creationDate // not nil
|
||||
player.modificationDate // not nil
|
||||
}
|
||||
```
|
||||
|
||||
- `updateWithTimestamp()` behaves like ``MutablePersistableRecord/update(_:onConflict:)``, but it also bumps the modification date.
|
||||
|
||||
```swift
|
||||
// Bump the modification date and update all columns in the database.
|
||||
player.score += 1
|
||||
try player.updateWithTimestamp(db)
|
||||
```
|
||||
|
||||
- `updateChangesWithTimestamp()` behaves like ``MutablePersistableRecord/updateChanges(_:onConflict:modify:)``, but it also bumps the modification date if the record is modified.
|
||||
|
||||
```swift
|
||||
// Only bump the modification date if record is changed, and only
|
||||
// update the changed columns.
|
||||
try player.updateChangesWithTimestamp(db) {
|
||||
$0.score = 1000
|
||||
}
|
||||
|
||||
// Prefer updateChanges() if the modification date should always be
|
||||
// updated, even if other columns are not changed.
|
||||
try player.updateChanges(db) {
|
||||
$0.score = 1000
|
||||
$0.modificationDate = try db.transactionDate
|
||||
}
|
||||
```
|
||||
|
||||
- `touch()` only updates the modification date in the database, just like the `touch` unix command.
|
||||
|
||||
```swift
|
||||
// Only update the modification date in the database.
|
||||
try player.touch(db)
|
||||
```
|
||||
|
||||
- There is no `TimestampedRecord.saveWithTimestamp()` method that would insert or update, like ``MutablePersistableRecord/save(_:onConflict:)``. You are encouraged to write instead (and maybe extend your version of `TimestampedRecord` so that it supports this pattern):
|
||||
|
||||
```swift
|
||||
extension Player {
|
||||
/// If the player has a non-nil primary key and a matching row in
|
||||
/// the database, the player is updated. Otherwise, it is inserted.
|
||||
mutating func saveWithTimestamp(_ db: Database) throws {
|
||||
// Test the presence of id first, so that we don't perform an
|
||||
// update that would surely throw RecordError.recordNotFound.
|
||||
if id == nil {
|
||||
try insert(db)
|
||||
} else {
|
||||
do {
|
||||
try updateWithTimestamp(db)
|
||||
} catch RecordError.recordNotFound {
|
||||
// Primary key is set, but no row was updated.
|
||||
try insert(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The full implementation of `TimestampedRecord` follows:
|
||||
|
||||
```swift
|
||||
/// A record type that tracks its creation and modification dates. See
|
||||
/// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordtimestamps>
|
||||
protocol TimestampedRecord: MutablePersistableRecord {
|
||||
var creationDate: Date? { get set }
|
||||
var modificationDate: Date? { get set }
|
||||
}
|
||||
|
||||
extension TimestampedRecord {
|
||||
/// By default, `TimestampedRecord` types set `creationDate` and
|
||||
/// `modificationDate` to the transaction date, if they are nil,
|
||||
/// before insertion.
|
||||
///
|
||||
/// `TimestampedRecord` types that customize the `willInsert`
|
||||
/// persistence callback should call `initializeTimestamps` from
|
||||
/// their implementation.
|
||||
mutating func willInsert(_ db: Database) throws {
|
||||
try initializeTimestamps(db)
|
||||
}
|
||||
|
||||
/// Sets `creationDate` and `modificationDate` to the transaction date,
|
||||
/// if they are nil.
|
||||
///
|
||||
/// It is called automatically before insertion, if your type does not
|
||||
/// customize the `willInsert` persistence callback. If you customize
|
||||
/// this callback, call `initializeTimestamps` from your implementation.
|
||||
mutating func initializeTimestamps(_ db: Database) throws {
|
||||
if creationDate == nil {
|
||||
creationDate = try db.transactionDate
|
||||
}
|
||||
if modificationDate == nil {
|
||||
modificationDate = try db.transactionDate
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets `modificationDate`, and executes an `UPDATE` statement
|
||||
/// on all columns.
|
||||
///
|
||||
/// - parameter modificationDate: The modification date. If nil, the
|
||||
/// transaction date is used.
|
||||
mutating func updateWithTimestamp(_ db: Database, modificationDate: Date? = nil) throws {
|
||||
self.modificationDate = try modificationDate ?? db.transactionDate
|
||||
try update(db)
|
||||
}
|
||||
|
||||
/// Modifies the record according to the provided `modify` closure, and,
|
||||
/// if and only if the record was modified, sets `modificationDate` and
|
||||
/// executes an `UPDATE` statement that updates the modified columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// var player = Player.find(db, id: 1)
|
||||
/// let modified = try player.updateChangesWithTimestamp(db) {
|
||||
/// $0.score = 1000
|
||||
/// }
|
||||
/// if modified {
|
||||
/// print("player was modified")
|
||||
/// } else {
|
||||
/// print("player was not modified")
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - modificationDate: The modification date. If nil, the
|
||||
/// transaction date is used.
|
||||
/// - modify: A closure that modifies the record.
|
||||
/// - returns: Whether the record was changed and updated.
|
||||
@discardableResult
|
||||
mutating func updateChangesWithTimestamp(
|
||||
_ db: Database,
|
||||
modificationDate: Date? = nil,
|
||||
modify: (inout Self) -> Void)
|
||||
throws -> Bool
|
||||
{
|
||||
// Grab the changes performed by `modify`
|
||||
let initialChanges = try databaseChanges(modify: modify)
|
||||
if initialChanges.isEmpty {
|
||||
return false
|
||||
}
|
||||
|
||||
// Update modification date and grab its column name
|
||||
let dateChanges = try databaseChanges(modify: {
|
||||
$0.modificationDate = try modificationDate ?? db.transactionDate
|
||||
})
|
||||
|
||||
// Update the modified columns
|
||||
let modifiedColumns = Set(initialChanges.keys).union(dateChanges.keys)
|
||||
try update(db, columns: modifiedColumns)
|
||||
return true
|
||||
}
|
||||
|
||||
/// Sets `modificationDate`, and executes an `UPDATE` statement that
|
||||
/// updates the `modificationDate` column, if and only if the record
|
||||
/// was modified.
|
||||
///
|
||||
/// - parameter modificationDate: The modification date. If nil, the
|
||||
/// transaction date is used.
|
||||
mutating func touch(_ db: Database, modificationDate: Date? = nil) throws {
|
||||
try updateChanges(db) {
|
||||
$0.modificationDate = try modificationDate ?? db.transactionDate
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 19 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 56 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 104 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 21 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 70 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 134 KiB |
@@ -62,6 +62,8 @@ try dbQueue.read { db in
|
||||
}
|
||||
```
|
||||
|
||||
For a more detailed overview, see [SQLite API](https://github.com/groue/GRDB.swift/blob/master/README.md#sqlite-api).
|
||||
|
||||
## Topics
|
||||
|
||||
### Fundamental Database Types
|
||||
@@ -79,7 +81,6 @@ try dbQueue.read { db in
|
||||
|
||||
### Database Values
|
||||
|
||||
- ``DatabaseDateComponents``
|
||||
- ``DatabaseValueConvertible``
|
||||
- ``StatementColumnConvertible``
|
||||
|
||||
|
||||
+8
-1
@@ -35,6 +35,10 @@ import Foundation
|
||||
/// - ``FTS5WrapperTokenizer``
|
||||
/// - ``FTS5TokenFlags``
|
||||
/// - ``FTS5Tokenization``
|
||||
///
|
||||
/// ### Low-Level FTS5 Customization
|
||||
///
|
||||
/// - ``api(_:)``
|
||||
public struct FTS5 {
|
||||
/// Options for Latin script characters. Matches the raw "remove_diacritics"
|
||||
/// tokenizer argument.
|
||||
@@ -100,7 +104,10 @@ public struct FTS5 {
|
||||
}
|
||||
}
|
||||
|
||||
static func api(_ db: Database) -> UnsafePointer<fts5_api> {
|
||||
/// Returns a pointer to the `fts5_api` structure.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#extending_fts5>
|
||||
public static func api(_ db: Database) -> UnsafePointer<fts5_api> {
|
||||
// Access to FTS5 is one of the rare SQLite api which was broken in
|
||||
// SQLite 3.20.0+, for security reasons:
|
||||
//
|
||||
|
||||
@@ -61,7 +61,7 @@ extension Database {
|
||||
///
|
||||
/// class MyTokenizer : FTS5CustomTokenizer { ... }
|
||||
/// db.add(tokenizer: MyTokenizer.self)
|
||||
public func add<Tokenizer: FTS5CustomTokenizer>(tokenizer: Tokenizer.Type) {
|
||||
public func add(tokenizer: (some FTS5CustomTokenizer).Type) {
|
||||
let api = FTS5.api(self)
|
||||
|
||||
// Swift won't let the @convention(c) xCreate() function below create
|
||||
@@ -76,7 +76,7 @@ extension Database {
|
||||
return SQLITE_ERROR
|
||||
}
|
||||
do {
|
||||
let tokenizer = try Tokenizer(db: db, arguments: arguments)
|
||||
let tokenizer = try tokenizer.init(db: db, arguments: arguments)
|
||||
|
||||
// Tokenizer must remain alive until xDeleteTokenizer()
|
||||
// is called, as the xDelete member of xTokenizer
|
||||
@@ -158,7 +158,7 @@ extension Database {
|
||||
let code = withUnsafeMutablePointer(to: &xTokenizer) { xTokenizerPointer in
|
||||
api.pointee.xCreateTokenizer(
|
||||
UnsafeMutablePointer(mutating: api),
|
||||
Tokenizer.name,
|
||||
tokenizer.name,
|
||||
constructorPointer,
|
||||
xTokenizerPointer,
|
||||
deleteConstructor)
|
||||
|
||||
+3
-1
@@ -57,7 +57,7 @@ extension DatabaseCursor {
|
||||
extension DatabaseMigrator {
|
||||
@available(*, unavailable, message: "The completion function now accepts one Result<Database, Error> argument")
|
||||
public func asyncMigrate(
|
||||
_ writer: DatabaseWriter,
|
||||
_ writer: any DatabaseWriter,
|
||||
completion: @escaping (Database, Error?) -> Void)
|
||||
{ preconditionFailure() }
|
||||
}
|
||||
@@ -167,3 +167,5 @@ extension ValueObservation {
|
||||
where Reducer == ValueReducers.Fetch<Value>
|
||||
{ preconditionFailure() }
|
||||
}
|
||||
|
||||
// swiftlint:enable all
|
||||
@@ -457,7 +457,13 @@ public struct DatabaseMigrator {
|
||||
}
|
||||
}()
|
||||
|
||||
if try db.schema(.main) != tmpSchema {
|
||||
// Only compare user objects
|
||||
func isUserObject(_ object: SchemaObject) -> Bool {
|
||||
!Database.isSQLiteInternalTable(object.name) && !Database.isGRDBInternalTable(object.name)
|
||||
}
|
||||
let tmpUserSchema = tmpSchema.filter(isUserObject)
|
||||
let userSchema = try db.schema(.main).filter(isUserObject)
|
||||
if userSchema != tmpUserSchema {
|
||||
needsErase = true
|
||||
return .commit
|
||||
}
|
||||
|
||||
Loaded 100 of 186 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user