mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-06 05:28:44 +00:00
Compare commits
156
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9318693fe4 | ||
|
|
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 | ||
|
|
e76cda27dc | ||
|
|
2618c9fa1e | ||
|
|
522e4be817 | ||
|
|
ff8b9e5cb8 | ||
|
|
38c9ec29f5 | ||
|
|
3b0cf1fb0b | ||
|
|
dc4f10ecb0 | ||
|
|
012ed8133f | ||
|
|
d0314e0db8 | ||
|
|
850db8f2e9 | ||
|
|
44ec63dbe2 | ||
|
|
e9afb04b1e | ||
|
|
72216beacb | ||
|
|
6500a97f88 | ||
|
|
3c71a6deea | ||
|
|
e4421c509c | ||
|
|
c8339db68b | ||
|
|
961b3a9cad | ||
|
|
efa8f0e69d | ||
|
|
93928a791a | ||
|
|
f649d9e19e | ||
|
|
31350672c7 | ||
|
|
17906dc505 | ||
|
|
f8f586a98c | ||
|
|
302fc69f3a | ||
|
|
0045592891 | ||
|
|
69105e6f80 | ||
|
|
aff924a72b | ||
|
|
abaa14db83 | ||
|
|
9b113fb548 | ||
|
|
ac214e6760 | ||
|
|
d3c289a320 | ||
|
|
c64e9f947b | ||
|
|
7a790c1f23 | ||
|
|
bc9190a1dc | ||
|
|
a9feac1339 | ||
|
|
846939d632 | ||
|
|
ba68e3b02d | ||
|
|
59f98ae1fd | ||
|
|
590158ca3e | ||
|
|
7d7724c3aa | ||
|
|
76a065af6d | ||
|
|
2976e81a95 | ||
|
|
fb547c1a15 | ||
|
|
38ce06d263 | ||
|
|
3794e7e801 | ||
|
|
557ad3d3d3 | ||
|
|
70a35afad8 | ||
|
|
4a5713502f | ||
|
|
c3cc998fc1 | ||
|
|
0f0f33d0d1 | ||
|
|
0b92c856ae | ||
|
|
6e2e1f4889 | ||
|
|
0dd17a9a16 | ||
|
|
4100b0627f | ||
|
|
c50cfd937e | ||
|
|
3d7170f1bc | ||
|
|
2c5a86479a | ||
|
|
119f226610 | ||
|
|
d2db26d570 | ||
|
|
82ed41b700 | ||
|
|
639eadbad2 | ||
|
|
4ff3221feb | ||
|
|
a61a769da9 | ||
|
|
04bdafd448 | ||
|
|
5fa5e62d0e | ||
|
|
1d5f05351a | ||
|
|
05da03ab1a |
No files matched your search
+49
-35
@@ -1,3 +1,5 @@
|
||||
# https://github.com/actions/runner-images/blob/main/images/macos/macos-12-Readme.md
|
||||
|
||||
name: "GRDB CI"
|
||||
|
||||
on:
|
||||
@@ -9,12 +11,14 @@ on:
|
||||
- 'GRDB/**'
|
||||
- 'Tests/**'
|
||||
- '.github/workflows/**'
|
||||
- 'Makefile'
|
||||
- 'Package.swift'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'GRDB/**'
|
||||
- 'Tests/**'
|
||||
- '.github/workflows/**'
|
||||
- 'Makefile'
|
||||
- 'Package.swift'
|
||||
|
||||
concurrency:
|
||||
@@ -24,50 +28,56 @@ permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
macOS:
|
||||
name: macOS
|
||||
Framework:
|
||||
name: Framework
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
env:
|
||||
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-12
|
||||
destination: "platform=macOS"
|
||||
name: "macOS"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
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
|
||||
name: "macOS 12, Xcode 14.0.1, Swift 5.7"
|
||||
shell: "/bin/zsh {0}"
|
||||
destination: "platform=macOS"
|
||||
name: "macOS"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
destination: "OS=16.0,name=iPhone 14"
|
||||
name: "iOS"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_GRDBOSX_maxSwift
|
||||
iOS:
|
||||
name: iOS
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 14.0.1, Swift 5.7"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project GRDB.xcodeproj -scheme GRDB -destination "${{ matrix.destination }}" OTHER_SWIFT_FLAGS='$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' GCC_PREPROCESSOR_DEFINITIONS='$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' clean test
|
||||
SPM:
|
||||
name: SPM
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
env:
|
||||
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.1"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 14.0.1, Swift 5.7"
|
||||
shell: "/bin/zsh {0}"
|
||||
name: "Xcode 14.0.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
@@ -75,15 +85,16 @@ jobs:
|
||||
SQLCipher3:
|
||||
name: SQLCipher3
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
env:
|
||||
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 14.0.1, Swift 5.7"
|
||||
shell: "/bin/zsh {0}"
|
||||
name: "Xcode 14.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
@@ -91,15 +102,16 @@ jobs:
|
||||
SQLCipher4:
|
||||
name: SQLCipher4
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
env:
|
||||
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 14.0.1, Swift 5.7"
|
||||
shell: "/bin/zsh {0}"
|
||||
name: "Xcode 14.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
@@ -107,15 +119,16 @@ jobs:
|
||||
CustomSQLite:
|
||||
name: CustomSQLite
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
env:
|
||||
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 14.0.1, Swift 5.7"
|
||||
shell: "/bin/zsh {0}"
|
||||
name: "Xcode 14.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
@@ -123,15 +136,16 @@ jobs:
|
||||
XCFramework:
|
||||
name: XCFramework
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
env:
|
||||
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 14.0.1, Swift 5.7"
|
||||
shell: "/bin/zsh {0}"
|
||||
name: "Xcode 14.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
## https://github.com/github/gitignore/blob/master/Global/OSX.gitignore
|
||||
## https://github.com/github/gitignore/blob/master/Global/macOS.gitignore
|
||||
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
|
||||
@@ -4,6 +4,46 @@ Here is a list of people who were happy to meet GRDB :-)
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/DamienPetrilli/status/1623922310976786433
|
||||
|
||||
> I can't overstate how much more productive I am since I ditched the obsolete Core Data framework and started to use GRDB instead.
|
||||
>
|
||||
> The hard stuff is doable, and the simple stuff is even simpler, as it should be.
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/fullqueuedev/status/1603350969357684736
|
||||
|
||||
> Yes, I much prefer GRDB. I’ve tested many SQLite wrappers over the years 💜
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/cassiuspacheco/status/1574948903857770497
|
||||
|
||||
> SQLite using @groue’s GRDB, no brainer! Awesome documentation, support and beautifully designed.
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/simrandotdev/status/1552004471122587649
|
||||
|
||||
> We get Core Data from Apple which is the worst library to deal with.
|
||||
> Then there is Realm which is nice but again you do not get the RAW SQL power as it is its own type of Db.
|
||||
> Then comes the most beautiful library every written which is very close to Room called GRDB.
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/bellebcooper/status/1534070340850094080
|
||||
|
||||
> When I first started using GRDB I didn't know SQL or much at all about databases 😬 So I've always really liked the query API. But these days I really appreciate that you support raw SQL too, because it gives me more control and freedom when I need it. 👍👍👍
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/mikeash/status/1504810545429499909
|
||||
|
||||
> Another cool library using SQL interpolation!
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/swiftkarim/status/1354753451377483781
|
||||
|
||||
> I cannot recommend GRDB enough. It works well with Swift and eliminates whole classes of potential programming errors that can be made with Core Data. Also being able to use raw SQL queries if needed can be extremely useful!
|
||||
|
||||
+95
-26
@@ -7,21 +7,26 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 6.x Releases
|
||||
|
||||
- `6.10.x` Releases - [6.10.0](#6100)
|
||||
- `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)
|
||||
- `6.4.x` Releases - [6.4.0](#640)
|
||||
- `6.3.x` Releases - [6.3.0](#630) - [6.3.1](#631)
|
||||
- `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)
|
||||
@@ -36,41 +41,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)
|
||||
@@ -82,18 +87,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)
|
||||
|
||||
@@ -103,6 +108,70 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 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)
|
||||
|
||||
- **Fixed**: [#1316](https://github.com/groue/GRDB.swift/pull/1316) and [#1320](https://github.com/groue/GRDB.swift/pull/1320) by [@baekteun](https://github.com/baekteun): Replace "OSX" with "macOS".
|
||||
- **Fixed**: [#1328](https://github.com/groue/GRDB.swift/pull/1328) by [@ytti](https://github.com/ytti): Fix documentation about Data passphrases.
|
||||
- **Fixed**: [#1327](https://github.com/groue/GRDB.swift/pull/1327) by [@groue](https://github.com/groue): Remove dependency on any specific SwiftLint version.
|
||||
- **New**: [#1331](https://github.com/groue/GRDB.swift/pull/1331) by [@groue](https://github.com/groue): Transaction Date
|
||||
- **New**: [#1336](https://github.com/groue/GRDB.swift/pull/1336) by [@groue](https://github.com/groue): Enable FTS5 by default
|
||||
- **Documentation Update**: The new [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordtimestamps) article explains how applications can save the creation and modification date of records.
|
||||
- Added support for `Table` in SQL interpolation.
|
||||
|
||||
## 6.6.1
|
||||
|
||||
Released January 15, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.6.0...v6.6.1)
|
||||
|
||||
- **Fixed**: [#1317](https://github.com/groue/GRDB.swift/pull/1317) by [@groue](https://github.com/groue): Fix handling of multiple deep prefetched associations
|
||||
|
||||
## 6.6.0
|
||||
|
||||
Released December 29, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.5.0...v6.6.0)
|
||||
|
||||
- **New**: [#1304](https://github.com/groue/GRDB.swift/pull/1304) by [@groue](https://github.com/groue): Expose generated columns with availability checks
|
||||
|
||||
## 6.5.0
|
||||
|
||||
Released December 5, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.4.0...v6.5.0)
|
||||
@@ -3647,7 +3716,7 @@ It comes with breaking changes, but the good news is that they are the last (unt
|
||||
|
||||
As a matter of fact, GRDB 1.0 still supports Xcode 8.1 and Swift 3.0. But future versions are free to use Swift 3.1 features, and will require Xcode 8.3+.
|
||||
|
||||
The targetted operating systems are unchanged: iOS 8.0+ / OSX 10.9+ / watchOS 2.0+
|
||||
The targetted operating systems are unchanged: iOS 8.0+ / macOS 10.9+ / watchOS 2.0+
|
||||
|
||||
- **[Record types](https://github.com/groue/GRDB.swift#records) have their `persistentDictionary` property replaced with the `encode(to:)` method:**
|
||||
|
||||
@@ -5455,11 +5524,11 @@ Released May 17, 2016
|
||||
|
||||
**Fixed**
|
||||
|
||||
- Restored support for iOS before 8.2 and OS X before 10.10. Fixes [#51](https://github.com/groue/GRDB.swift/issues/51).
|
||||
- Restored support for iOS before 8.2 and macOS before 10.10. Fixes [#51](https://github.com/groue/GRDB.swift/issues/51).
|
||||
|
||||
**Breaking Changes**
|
||||
|
||||
- Support for advanced migrations is not available until iOS 8.2 and OS X 10.10:
|
||||
- Support for advanced migrations is not available until iOS 8.2 and macOS 10.10:
|
||||
|
||||
```diff
|
||||
struct DatabaseMigrator {
|
||||
@@ -5515,7 +5584,7 @@ Released May 10, 2016
|
||||
|
||||
**New**
|
||||
|
||||
- `FetchedRecordsController` is now exposed in OSX CocoaPods framework ([documentation](https://github.com/groue/GRDB.swift#fetchedrecordscontroller))
|
||||
- `FetchedRecordsController` is now exposed in macOS CocoaPods framework ([documentation](https://github.com/groue/GRDB.swift#fetchedrecordscontroller))
|
||||
|
||||
**Fixed**
|
||||
|
||||
@@ -5648,7 +5717,7 @@ Released April 5, 2016
|
||||
|
||||
**Fixed**
|
||||
|
||||
- Restored CocoaPods support for iOS 8+ and OS X 10.9+
|
||||
- Restored CocoaPods support for iOS 8+ and macOS 10.9+
|
||||
|
||||
|
||||
## 0.56.0
|
||||
@@ -5691,7 +5760,7 @@ Released March 31, 2016
|
||||
|
||||
Released March 29, 2016
|
||||
|
||||
This release restores CocoaPods support for iOS 9.0+ and OSX 10.11+. We'll try to bring back CocoaPods support for iOS 8.0+ or OSX 10.9+ in a further release.
|
||||
This release restores CocoaPods support for iOS 9.0+ and macOS 10.11+. We'll try to bring back CocoaPods support for iOS 8.0+ or macOS 10.9+ in a further release.
|
||||
|
||||
|
||||
## 0.54.0
|
||||
@@ -6590,7 +6659,7 @@ Released August 25, 2015
|
||||
|
||||
**Fixed**
|
||||
|
||||
- Reduced iOS Deployment Target to 8.0, and OSX Deployment Target to 10.9.
|
||||
- Reduced iOS Deployment Target to 8.0, and macOS Deployment Target to 10.9.
|
||||
- `DatabaseQueue.inTransaction()` is now declared as `rethrows`.
|
||||
|
||||
**Breaking changes**
|
||||
|
||||
@@ -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
|
||||
@@ -2907,8 +2907,6 @@ See [Good Practices for Designing Record Types] for more information.
|
||||
.including(required: Passport.citizen))
|
||||
```
|
||||
|
||||
Come [discuss](http://twitter.com/groue) for more information, or if you wish to help turning those missing features into reality.
|
||||
|
||||
---
|
||||
|
||||
This documentation owns a lot to the [Active Record Associations](http://guides.rubyonrails.org/association_basics.html) guide, which is an immensely well-written introduction to database relations. Many thanks to the Rails team and contributors.
|
||||
@@ -2919,7 +2917,7 @@ This documentation owns a lot to the [Active Record Associations](http://guides.
|
||||
|
||||
**GRDB**
|
||||
|
||||
Copyright (C) 2015-2020 Gwendal Roué
|
||||
Copyright (C) 2015-2023 Gwendal Roué
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
@@ -2998,7 +2996,7 @@ 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
|
||||
|
||||
@@ -398,7 +398,7 @@ let cancellable = hallOfFamePublisher.sink(
|
||||
[`writePublisher(receiveOn:updates:thenRead:)`]: #databasewriterwritepublisherreceiveonupdatesthenread
|
||||
[`migratePublisher(_:receiveOn:)`]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasemigrator/migratepublisher(_:receiveon:)
|
||||
[configured]: ../README.md#databasepool-configuration
|
||||
[database pool]: ../README.md#database-pools
|
||||
[database queue]: ../README.md#database-queues
|
||||
[database pool]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool
|
||||
[database queue]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue
|
||||
[database snapshot]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesnapshot
|
||||
[scheduler]: https://developer.apple.com/documentation/combine/scheduler
|
||||
@@ -21,7 +21,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
|
||||
2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5`, `SQLITE_ENABLE_PREUPDATE_HOOK`.
|
||||
|
||||
It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) when you use a [Database Pool](../README.md#database-pools).
|
||||
It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) when you use a [Database Pool](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool).
|
||||
|
||||
3. Create a folder named `GRDBCustomSQLite` somewhere in your project directory.
|
||||
|
||||
|
||||
@@ -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 */
|
||||
|
||||
+11
-13
@@ -1,16 +1,14 @@
|
||||
{
|
||||
"object": {
|
||||
"pins": [
|
||||
{
|
||||
"package": "GRDBQuery",
|
||||
"repositoryURL": "https://github.com/groue/GRDBQuery",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "4301166cd2aee9ce37b4057c9a58f5cc3bbeae06",
|
||||
"version": "0.1.0"
|
||||
}
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "grdbquery",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/groue/GRDBQuery",
|
||||
"state" : {
|
||||
"revision" : "aefc0d7e7a64e841da33e1c8be7429da1bd9b5d6",
|
||||
"version" : "0.6.0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 1
|
||||
}
|
||||
],
|
||||
"version" : 2
|
||||
}
|
||||
@@ -17,7 +17,7 @@ struct AppDatabase {
|
||||
/// Application can use a `DatabasePool`, while SwiftUI previews and tests
|
||||
/// can use a fast in-memory `DatabaseQueue`.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections>
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
|
||||
private let dbWriter: any DatabaseWriter
|
||||
|
||||
/// The DatabaseMigrator that defines the database schema.
|
||||
@@ -162,7 +162,7 @@ extension AppDatabase {
|
||||
// reading methods.
|
||||
extension AppDatabase {
|
||||
/// Provides a read-only access to the database
|
||||
var databaseReader: DatabaseReader {
|
||||
var reader: DatabaseReader {
|
||||
dbWriter
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@ extension AppDatabase {
|
||||
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
|
||||
|
||||
// Connect to a database on disk
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
|
||||
let dbURL = folderURL.appendingPathComponent("db.sqlite")
|
||||
let dbPool = try DatabasePool(path: dbURL.path)
|
||||
|
||||
@@ -58,7 +58,7 @@ extension AppDatabase {
|
||||
/// Creates an empty database for SwiftUI previews
|
||||
static func empty() -> AppDatabase {
|
||||
// Connect to an in-memory database
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
|
||||
let dbQueue = try! DatabaseQueue()
|
||||
return try! AppDatabase(dbQueue)
|
||||
}
|
||||
|
||||
@@ -29,12 +29,12 @@ struct PlayerRequest: Queryable {
|
||||
|
||||
func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> {
|
||||
// Build the publisher from the general-purpose read-only access
|
||||
// granted by `appDatabase.databaseReader`.
|
||||
// granted by `appDatabase.reader`.
|
||||
// Some apps will prefer to call a dedicated method of `appDatabase`.
|
||||
ValueObservation
|
||||
.tracking(fetchValue(_:))
|
||||
.publisher(
|
||||
in: appDatabase.databaseReader,
|
||||
in: appDatabase.reader,
|
||||
// The `.immediate` scheduling feeds the view right on
|
||||
// subscription, and avoids an undesired animation when the
|
||||
// application starts.
|
||||
|
||||
@@ -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 */
|
||||
|
||||
+11
-13
@@ -1,16 +1,14 @@
|
||||
{
|
||||
"object": {
|
||||
"pins": [
|
||||
{
|
||||
"package": "GRDBQuery",
|
||||
"repositoryURL": "https://github.com/groue/GRDBQuery",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "4301166cd2aee9ce37b4057c9a58f5cc3bbeae06",
|
||||
"version": "0.1.0"
|
||||
}
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "grdbquery",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/groue/GRDBQuery",
|
||||
"state" : {
|
||||
"revision" : "aefc0d7e7a64e841da33e1c8be7429da1bd9b5d6",
|
||||
"version" : "0.6.0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 1
|
||||
}
|
||||
],
|
||||
"version" : 2
|
||||
}
|
||||
@@ -18,7 +18,7 @@ struct AppDatabase {
|
||||
/// Application can use a `DatabasePool`, while SwiftUI previews and tests
|
||||
/// can use a fast in-memory `DatabaseQueue`.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections>
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
|
||||
private let dbWriter: any DatabaseWriter
|
||||
|
||||
/// The DatabaseMigrator that defines the database schema.
|
||||
@@ -163,7 +163,7 @@ extension AppDatabase {
|
||||
// reading methods.
|
||||
extension AppDatabase {
|
||||
/// Provides a read-only access to the database
|
||||
var databaseReader: DatabaseReader {
|
||||
var reader: DatabaseReader {
|
||||
dbWriter
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@ extension AppDatabase {
|
||||
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
|
||||
|
||||
// Connect to a database on disk
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
|
||||
let dbURL = folderURL.appendingPathComponent("db.sqlite")
|
||||
let dbPool = try DatabasePool(path: dbURL.path)
|
||||
|
||||
@@ -58,7 +58,7 @@ extension AppDatabase {
|
||||
/// Creates an empty database for SwiftUI previews
|
||||
static func empty() -> AppDatabase {
|
||||
// Connect to an in-memory database
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
|
||||
let dbQueue = try! DatabaseQueue()
|
||||
return try! AppDatabase(dbQueue)
|
||||
}
|
||||
|
||||
@@ -29,12 +29,12 @@ struct PlayerRequest: Queryable {
|
||||
|
||||
func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> {
|
||||
// Build the publisher from the general-purpose read-only access
|
||||
// granted by `appDatabase.databaseReader`.
|
||||
// granted by `appDatabase.reader`.
|
||||
// Some apps will prefer to call a dedicated method of `appDatabase`.
|
||||
ValueObservation
|
||||
.tracking(fetchValue(_:))
|
||||
.publisher(
|
||||
in: appDatabase.databaseReader,
|
||||
in: appDatabase.reader,
|
||||
// The `.immediate` scheduling feeds the view right on
|
||||
// subscription, and avoids an undesired animation when the
|
||||
// application starts.
|
||||
|
||||
@@ -40,6 +40,20 @@
|
||||
remoteGlobalIDString = 56B036021E8D9EBE003B6DA4;
|
||||
remoteInfo = GRDBDemoiOS;
|
||||
};
|
||||
5642252F29A2390800D714BF /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = DC3773F219C8CBB3004FCF85;
|
||||
remoteInfo = GRDB;
|
||||
};
|
||||
5642253329A2391900D714BF /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = DC3773F219C8CBB3004FCF85;
|
||||
remoteInfo = GRDB;
|
||||
};
|
||||
56606D092355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
@@ -328,6 +342,7 @@
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
5642253429A2391900D714BF /* PBXTargetDependency */,
|
||||
);
|
||||
name = "GRDBDemoWatchOS Extension";
|
||||
productName = "GRDBDemoWatchOS Extension";
|
||||
@@ -347,6 +362,7 @@
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
5642253029A2390800D714BF /* PBXTargetDependency */,
|
||||
568E5FD81E926430002582E0 /* PBXTargetDependency */,
|
||||
);
|
||||
name = GRDBDemoiOS;
|
||||
@@ -511,6 +527,16 @@
|
||||
target = 56B036021E8D9EBE003B6DA4 /* GRDBDemoiOS */;
|
||||
targetProxy = 56185BF525B80B8900B9C30F /* PBXContainerItemProxy */;
|
||||
};
|
||||
5642253029A2390800D714BF /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = GRDB;
|
||||
targetProxy = 5642252F29A2390800D714BF /* PBXContainerItemProxy */;
|
||||
};
|
||||
5642253429A2391900D714BF /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = GRDB;
|
||||
targetProxy = 5642253329A2391900D714BF /* PBXContainerItemProxy */;
|
||||
};
|
||||
568E5FCE1E926430002582E0 /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
target = 568E5FCA1E926430002582E0 /* GRDBDemoWatchOS Extension */;
|
||||
|
||||
@@ -16,7 +16,7 @@ final class AppDatabase {
|
||||
/// Application can use a `DatabasePool`, and tests can use a fast
|
||||
/// in-memory `DatabaseQueue`.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections>
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
|
||||
private let dbWriter: any DatabaseWriter
|
||||
|
||||
/// The DatabaseMigrator that defines the database schema.
|
||||
@@ -127,7 +127,7 @@ extension AppDatabase {
|
||||
// reading methods.
|
||||
extension AppDatabase {
|
||||
/// Provides a read-only access to the database
|
||||
var databaseReader: DatabaseReader {
|
||||
var reader: DatabaseReader {
|
||||
dbWriter
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@ extension AppDatabase {
|
||||
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
|
||||
|
||||
// Connect to a database on disk
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
|
||||
let dbURL = folderURL.appendingPathComponent("db.sqlite")
|
||||
let dbPool = try DatabasePool(path: dbURL.path)
|
||||
|
||||
|
||||
+1
-1
@@ -138,7 +138,7 @@ class PlayerListViewController: UITableViewController {
|
||||
playersCancellable = ValueObservation
|
||||
.tracking(request.fetchAll(_:))
|
||||
.start(
|
||||
in: AppDatabase.shared.databaseReader,
|
||||
in: AppDatabase.shared.reader,
|
||||
// Immediate scheduling feeds the data source right on subscription,
|
||||
// and avoids an undesired animation when the application starts.
|
||||
scheduling: .immediate,
|
||||
|
||||
@@ -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.**
|
||||
|
||||
@@ -197,7 +197,7 @@ The changes can quite impact your application. We'll describe them below, as wel
|
||||
scheduling: .immediate,
|
||||
onError: { error in ... },
|
||||
onChange: { [weak self] (players: [Player]) in
|
||||
guard let self = self else { return }
|
||||
guard let self else { return }
|
||||
self.updateView(players)
|
||||
})
|
||||
// <- Here the view has already been updated.
|
||||
|
||||
@@ -103,7 +103,7 @@ let authorInfo: AuthorInfo? = try dbQueue.read { db in
|
||||
let books = try author.books.fetchAll(db)
|
||||
return AuthorInfo(author: author, books: books)
|
||||
}
|
||||
if let authorInfo = authorInfo {
|
||||
if let authorInfo {
|
||||
print("\(authorInfo.author.name) has written:")
|
||||
for book in authorInfo.books {
|
||||
print("- \(book.title)")
|
||||
@@ -126,7 +126,7 @@ let bookInfo: BookInfo? = try dbQueue.read { db in
|
||||
.including(required: Book.author)
|
||||
return try BookInfo.fetchOne(db, request)
|
||||
}
|
||||
if let bookInfo = bookInfo {
|
||||
if let bookInfo {
|
||||
print("\(bookInfo.book.title) was written by \(bookInfo.author.name)")
|
||||
}
|
||||
|
||||
|
||||
@@ -363,7 +363,7 @@ Let's extend Player with database methods.
|
||||
|
||||
This chapter lists all kinds of supported interpolations.
|
||||
|
||||
- Types adopting the [TableRecord] protocol:
|
||||
- Types adopting the [TableRecord] protocol and [Table](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/table) instances:
|
||||
|
||||
```swift
|
||||
struct Player: TableRecord { ... }
|
||||
@@ -371,9 +371,13 @@ This chapter lists all kinds of supported interpolations.
|
||||
// SELECT * FROM player
|
||||
"SELECT * FROM \(Player.self)"
|
||||
|
||||
// INSERT INTO player ...
|
||||
// SELECT * FROM player
|
||||
let player: Player = ...
|
||||
"INSERT INTO \(tableOf: player) ..."
|
||||
"SELECT * FROM \(tableOf: player) ..."
|
||||
|
||||
// SELECT * FROM player
|
||||
let playerTable = Table("player")
|
||||
"SELECT * FROM \(playerTable)"
|
||||
```
|
||||
|
||||
- Columns selected by [TableRecord]:
|
||||
|
||||
@@ -154,11 +154,11 @@ See [Database Observation](https://swiftpackageindex.com/groue/grdb.swift/docume
|
||||
|
||||
### Non-blocking database reads
|
||||
|
||||
GRDB ships with two ways to access databases, [database queues](../README.md#database-queues) and [pools](../README.md#database-pools).
|
||||
GRDB ships with two ways to access databases, [database queues](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue) and [pools](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool).
|
||||
|
||||
Database queues look a lot like FMDB's [FMDatabaseQueue](https://github.com/ccgus/fmdb#using-fmdatabasequeue-and-thread-safety): they serialize database accesses in a serial dispatch queue. There is never more than one thread that is accessing the database. This means that a long running database transaction that happens in a background thread, such as the synchronization of your local database from a remote server, can block your UI. As long as the queue is busy, the main thread can't fetch the values it wants to display on screen.
|
||||
|
||||
[Database pools](../README.md#database-pools) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured).
|
||||
[Database pools](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured).
|
||||
|
||||
|
||||
### Strong and clear multi-threading guarantees
|
||||
@@ -287,7 +287,7 @@ Happy GRDB! :gift:
|
||||
|
||||
[Concurrency Guide]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency
|
||||
[Core Data]: https://developer.apple.com/documentation/coredata
|
||||
[DatabasePool]: ../README.md#database-pools
|
||||
[DatabasePool]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool
|
||||
[Diesel]: http://diesel.rs
|
||||
[FCModel]: https://github.com/marcoarment/FCModel
|
||||
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
|
||||
|
||||
+4
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '6.5.0'
|
||||
s.version = '6.10.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
@@ -20,6 +20,9 @@ Pod::Spec.new do |s|
|
||||
ss.source_files = 'GRDB/**/*.swift', 'Support/grdb_config.h'
|
||||
ss.framework = 'Foundation'
|
||||
ss.library = 'sqlite3'
|
||||
ss.xcconfig = {
|
||||
'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_ENABLE_FTS5',
|
||||
}
|
||||
end
|
||||
|
||||
s.subspec 'SQLCipher' do |ss|
|
||||
|
||||
@@ -250,6 +250,8 @@
|
||||
56AACAA822ACED7100A40F2A /* Fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AACAA722ACED7100A40F2A /* Fetch.swift */; };
|
||||
56AE64122229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */; };
|
||||
56AE6424222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE6423222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift */; };
|
||||
56AFEF2F29969F6E00CA1E51 /* TransactionClock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */; };
|
||||
56AFEF372996B9DC00CA1E51 /* TransactionDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF362996B9DC00CA1E51 /* TransactionDateTests.swift */; };
|
||||
56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; };
|
||||
56B6EF56208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */; };
|
||||
56B7EE832863781300C0525F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7EE822863781300C0525F /* WALSnapshot.swift */; };
|
||||
@@ -279,6 +281,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 */; };
|
||||
@@ -371,6 +374,7 @@
|
||||
56E9FACB221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FACA221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift */; };
|
||||
56E9FADA221053DD00C703A8 /* SQL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAD7221053DC00C703A8 /* SQL.swift */; };
|
||||
56EA63C5209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */; };
|
||||
56F0383B28C21814000DEBFB /* Database+Cache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0383A28C21814000DEBFB /* Database+Cache.swift */; };
|
||||
56F34FBA24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */; };
|
||||
56F34FC224B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */; };
|
||||
56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
|
||||
@@ -711,6 +715,8 @@
|
||||
56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HasOneThroughAssociation.swift; sourceTree = "<group>"; };
|
||||
56AE6423222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLTests.swift; sourceTree = "<group>"; };
|
||||
56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEscapingTests.swift; sourceTree = "<group>"; };
|
||||
56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionClock.swift; sourceTree = "<group>"; };
|
||||
56AFEF362996B9DC00CA1E51 /* TransactionDateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionDateTests.swift; sourceTree = "<group>"; };
|
||||
56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = "<group>"; };
|
||||
56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = "<group>"; };
|
||||
56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = "<group>"; };
|
||||
@@ -749,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>"; };
|
||||
@@ -771,6 +778,7 @@
|
||||
56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReadOnlyTests.swift; sourceTree = "<group>"; };
|
||||
56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataMemoryTests.swift; sourceTree = "<group>"; };
|
||||
56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizerTests.swift; sourceTree = "<group>"; };
|
||||
56F0383A28C21814000DEBFB /* Database+Cache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Cache.swift"; sourceTree = "<group>"; };
|
||||
56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = "<group>"; };
|
||||
56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLExpressionIsConstantTests.swift; sourceTree = "<group>"; };
|
||||
56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLIdentifyingColumnsTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1368,6 +1376,7 @@
|
||||
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */,
|
||||
56A238201B9C74A90082EB20 /* Statement */,
|
||||
56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */,
|
||||
56AFEF362996B9DC00CA1E51 /* TransactionDateTests.swift */,
|
||||
5607EFD11BB8253300605DE3 /* TransactionObserver */,
|
||||
);
|
||||
name = Core;
|
||||
@@ -1437,6 +1446,7 @@
|
||||
56A238701B9C75030082EB20 /* Configuration.swift */,
|
||||
56DAA2DA1DE9C827006E10C8 /* Cursor.swift */,
|
||||
56A238711B9C75030082EB20 /* Database.swift */,
|
||||
56F0383A28C21814000DEBFB /* Database+Cache.swift */,
|
||||
566B91221FA4CF810012D5B0 /* Database+Schema.swift */,
|
||||
566B91081FA4C3960012D5B0 /* Database+Statements.swift */,
|
||||
4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */,
|
||||
@@ -1461,12 +1471,14 @@
|
||||
566B9C1F25C6CC24004542CF /* RowDecodingError.swift */,
|
||||
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
|
||||
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
|
||||
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */,
|
||||
56E9FAD7221053DC00C703A8 /* SQL.swift */,
|
||||
569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */,
|
||||
56FBFED82210731A00945324 /* SQLRequest.swift */,
|
||||
56A238781B9C75030082EB20 /* Statement.swift */,
|
||||
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
|
||||
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
|
||||
56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */,
|
||||
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
|
||||
56B7EE822863781300C0525F /* WALSnapshot.swift */,
|
||||
5605F1471C672E4000235C62 /* Support */,
|
||||
@@ -1950,6 +1962,7 @@
|
||||
56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */,
|
||||
56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
|
||||
564CE5BE21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */,
|
||||
56AFEF372996B9DC00CA1E51 /* TransactionDateTests.swift in Sources */,
|
||||
564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */,
|
||||
D263F40A26C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift in Sources */,
|
||||
5653EAEE20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */,
|
||||
@@ -2013,6 +2026,7 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */,
|
||||
56F0383B28C21814000DEBFB /* Database+Cache.swift in Sources */,
|
||||
56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
56158780288D875E00A67323 /* Optional.swift in Sources */,
|
||||
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */,
|
||||
@@ -2098,6 +2112,7 @@
|
||||
5657AB0F1D10899D006283EF /* URL.swift in Sources */,
|
||||
560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */,
|
||||
56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */,
|
||||
56AFEF2F29969F6E00CA1E51 /* TransactionClock.swift in Sources */,
|
||||
5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */,
|
||||
56D91AA92205F2F100770D8D /* DatabasePromise.swift in Sources */,
|
||||
56959629222C462D002CB7C9 /* HasManyThroughAssociation.swift in Sources */,
|
||||
@@ -2149,6 +2164,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 */,
|
||||
|
||||
+3
@@ -17,6 +17,9 @@
|
||||
location = "group:MyPlayground.playground">
|
||||
</FileRef>
|
||||
</Group>
|
||||
<FileRef
|
||||
location = "group:BRAG.md">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:CHANGELOG.md">
|
||||
</FileRef>
|
||||
|
||||
@@ -1,55 +1,6 @@
|
||||
import Dispatch
|
||||
import Foundation
|
||||
|
||||
/// The configuration of a database connection.
|
||||
///
|
||||
/// You create a `Configuration` before opening a database connection:
|
||||
///
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.readonly = true
|
||||
/// config.maximumReaderCount = 2 // (DatabasePool only) The default is 5
|
||||
/// config.prepareDatabase { db in // A function to run on connection
|
||||
/// db.trace { print("SQL >", $0) }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = try DatabaseQueue( // or DatabasePool
|
||||
/// path: "/path/to/database.sqlite",
|
||||
/// configuration: config)
|
||||
/// ```
|
||||
///
|
||||
/// See <doc:DatabaseConnections>.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a Configuration
|
||||
///
|
||||
/// - ``init()``
|
||||
///
|
||||
/// ### Configuring SQLite Connections
|
||||
///
|
||||
/// - ``acceptsDoubleQuotedStringLiterals``
|
||||
/// - ``busyMode``
|
||||
/// - ``foreignKeysEnabled``
|
||||
/// - ``readonly``
|
||||
///
|
||||
/// ### Configuring GRDB Connections
|
||||
///
|
||||
/// - ``allowsUnsafeTransactions``
|
||||
/// - ``defaultTransactionKind``
|
||||
/// - ``label``
|
||||
/// - ``maximumReaderCount``
|
||||
/// - ``observesSuspensionNotifications``
|
||||
/// - ``prepareDatabase(_:)``
|
||||
/// - ``publicStatementArguments``
|
||||
///
|
||||
/// ### Configuring the Quality of Service
|
||||
///
|
||||
/// - ``qos``
|
||||
/// - ``readQoS``
|
||||
/// - ``writeQoS``
|
||||
/// - ``targetQueue``
|
||||
/// - ``writeTargetQueue``
|
||||
public struct Configuration {
|
||||
|
||||
// MARK: - Misc options
|
||||
@@ -64,6 +15,15 @@ public struct Configuration {
|
||||
/// A boolean value indicating whether an SQLite connection is read-only.
|
||||
///
|
||||
/// The default is false.
|
||||
///
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.readonly = true
|
||||
///
|
||||
/// let dbQueue = try DatabaseQueue( // or DatabasePool
|
||||
/// path: "/path/to/database.sqlite",
|
||||
/// configuration: config)
|
||||
/// ```
|
||||
public var readonly = false
|
||||
|
||||
/// A label that describes a database connection.
|
||||
@@ -209,6 +169,21 @@ public struct Configuration {
|
||||
/// ```
|
||||
public var publicStatementArguments = false
|
||||
|
||||
/// The clock that feeds ``Database/transactionDate``.
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// The default clock is ``DefaultTransactionClock`` (which returns the
|
||||
/// start date of the current transaction).
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.transactionClock = .custom { db in /* return some Date */ }
|
||||
/// ```
|
||||
public var transactionClock: TransactionClock = .default
|
||||
|
||||
// MARK: - Managing SQLite Connections
|
||||
|
||||
private var setups: [(Database) throws -> Void] = []
|
||||
@@ -326,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()
|
||||
@@ -346,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.
|
||||
@@ -397,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.
|
||||
@@ -446,7 +439,7 @@ public struct Configuration {
|
||||
/// Creates a DispatchQueue which has the quality of service and target
|
||||
/// queue of read accesses.
|
||||
func makeReaderDispatchQueue(label: String) -> DispatchQueue {
|
||||
if let targetQueue = targetQueue {
|
||||
if let targetQueue {
|
||||
return DispatchQueue(label: label, target: targetQueue)
|
||||
} else {
|
||||
return DispatchQueue(label: label, qos: qos)
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
extension Database {
|
||||
func withCache<T>(atPath path: String, execute: () throws -> T) throws -> T {
|
||||
GRDBPrecondition(attachedCache == nil, "Database is already cached.")
|
||||
|
||||
return try throwingFirstError {
|
||||
attachedCache = AttachedCache(
|
||||
schema: .attached("cache"),
|
||||
statementCache: StatementCache(database: self))
|
||||
try self.execute(literal: "ATTACH DATABASE \(path) AS cache")
|
||||
return try execute()
|
||||
} finally: {
|
||||
attachedCache = nil
|
||||
try self.execute(sql: "DETACH DATABASE cache")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Statement {
|
||||
/// Returns a statement ready for iterating the results of this statement
|
||||
/// with a DatabaseCursor.
|
||||
///
|
||||
/// The result is not the same statement as the receiver if we cache the
|
||||
/// statement's results.
|
||||
func databaseCursorStatement(with arguments: StatementArguments?) throws -> Statement {
|
||||
// Should we cache statement results and return a new statement on the cached values?
|
||||
guard
|
||||
// Don't cache until we were instructed to.
|
||||
let attachedCache = database.attachedCache,
|
||||
|
||||
// Only cache read-only statements.
|
||||
isReadonly,
|
||||
|
||||
// Only cache statements that access user tables.
|
||||
databaseRegion
|
||||
.filteringTables({ !Database.isSQLiteInternalTable($0) && !Database.isGRDBInternalTable($0) })
|
||||
.isEmpty == false,
|
||||
|
||||
// Only cache statements that can build a name for the cache table.
|
||||
let cacheTableName,
|
||||
|
||||
// Only cache statements for which we can guarantee rowid ordering
|
||||
// without ambiguity.
|
||||
case let statementColumns = columnNames.map({ $0.lowercased() }),
|
||||
let rowid = ["rowid", "_rowid_", "oid"].first(where: { !statementColumns.contains($0) })
|
||||
else {
|
||||
// Don't cache: return self.
|
||||
// Reset before cursor iteration: the statement may be reused.
|
||||
try prepareExecution(withArguments: arguments)
|
||||
return self
|
||||
}
|
||||
|
||||
// Cache the results if not done yet
|
||||
let cacheTable = Database.TableIdentifier(schemaID: attachedCache.schema, name: cacheTableName)
|
||||
try database.execute(sql: """
|
||||
CREATE TABLE IF NOT EXISTS \(cacheTable.quotedDatabaseIdentifier) AS \(sql)
|
||||
""", arguments: arguments ?? self.arguments)
|
||||
|
||||
// Return a statement on the cached values, preserving the order of the
|
||||
// original rows.
|
||||
//
|
||||
// Quoting <https://sqlite.org/lang_createtable.html#create_table_as_select_statements>:
|
||||
//
|
||||
// > Tables created using CREATE TABLE AS are initially populated with
|
||||
// > the rows of data returned by the SELECT statement. Rows are
|
||||
// > assigned contiguously ascending rowid values, starting with 1, in
|
||||
// > the order that they are returned by the SELECT statement.
|
||||
let statement = try attachedCache.statementCache.statement("""
|
||||
SELECT * FROM \(cacheTable.quotedDatabaseIdentifier) ORDER BY \(rowid)
|
||||
""")
|
||||
// Reset before cursor iteration: the statement may be reused.
|
||||
try statement.reset()
|
||||
return statement
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,10 @@ extension Database {
|
||||
case let .attached(name): return "\(name).sqlite_master"
|
||||
}
|
||||
}
|
||||
|
||||
func table(_ name: String) -> TableIdentifier {
|
||||
TableIdentifier(schemaID: self, name: name)
|
||||
}
|
||||
}
|
||||
|
||||
/// The identifier of a database table or view.
|
||||
@@ -210,7 +214,7 @@ extension Database {
|
||||
}
|
||||
}
|
||||
|
||||
private func tableExists(_ table: TableIdentifier) throws -> Bool {
|
||||
func tableExists(_ table: TableIdentifier) throws -> Bool {
|
||||
try exists(type: .table, name: table.name, in: table.schemaID)
|
||||
}
|
||||
|
||||
@@ -387,7 +391,7 @@ extension Database {
|
||||
return try self.table(for: table)!.hasRowID
|
||||
}
|
||||
#else
|
||||
if #available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) {
|
||||
if #available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) { // SQLite 3.37+
|
||||
return try self.table(for: table)!.hasRowID
|
||||
}
|
||||
#endif
|
||||
@@ -912,7 +916,7 @@ public struct ColumnInfo: FetchableRecord {
|
||||
|
||||
/// Information about an index.
|
||||
///
|
||||
/// You get `ForeignKeyInfo` instances with the ``Database/indexes(on:)``
|
||||
/// You get `IndexInfo` instances with the ``Database/indexes(on:)``
|
||||
/// `Database` method.
|
||||
///
|
||||
/// Related SQLite documentation:
|
||||
@@ -1032,7 +1036,7 @@ public struct ForeignKeyViolation {
|
||||
})
|
||||
|
||||
var description: String
|
||||
if let foreignKey = foreignKey {
|
||||
if let foreignKey {
|
||||
description = """
|
||||
FOREIGN KEY constraint violation - \
|
||||
from \(originTable)(\(foreignKey.originColumns.joined(separator: ", "))) \
|
||||
@@ -1042,9 +1046,9 @@ public struct ForeignKeyViolation {
|
||||
description = "FOREIGN KEY constraint violation - from \(originTable) to \(destinationTable)"
|
||||
}
|
||||
|
||||
if let originRow = originRow {
|
||||
if let originRow {
|
||||
description += ", in \(String(describing: originRow))"
|
||||
} else if let originRowID = originRowID {
|
||||
} else if let originRowID {
|
||||
description += ", in rowid \(originRowID)"
|
||||
}
|
||||
|
||||
@@ -1084,7 +1088,7 @@ extension ForeignKeyViolation: CustomStringConvertible {
|
||||
///
|
||||
/// See also ``failureDescription(_:)``.
|
||||
public var description: String {
|
||||
if let originRowID = originRowID {
|
||||
if let originRowID {
|
||||
return """
|
||||
FOREIGN KEY constraint violation - from \(originTable) to \(destinationTable), \
|
||||
in rowid \(originRowID)
|
||||
|
||||
@@ -406,8 +406,8 @@ extension SQLStatementCursor: Cursor {
|
||||
/// Check that all arguments were consumed: it is a programmer error to
|
||||
/// provide arguments that do not match the statements.
|
||||
private func checkArgumentsAreEmpty() throws {
|
||||
if let arguments = arguments,
|
||||
let initialArgumentCount = initialArgumentCount,
|
||||
if let arguments,
|
||||
let initialArgumentCount,
|
||||
arguments.values.isEmpty == false
|
||||
{
|
||||
throw DatabaseError(
|
||||
@@ -445,6 +445,8 @@ extension Database {
|
||||
clearSchemaCache()
|
||||
}
|
||||
|
||||
checkForAutocommitTransition()
|
||||
|
||||
// Database observation: cleanup
|
||||
try observationBroker?.statementDidExecute(statement)
|
||||
}
|
||||
@@ -460,6 +462,8 @@ extension Database {
|
||||
internalStatementCache.remove(statement)
|
||||
publicStatementCache.remove(statement)
|
||||
|
||||
checkForAutocommitTransition()
|
||||
|
||||
// Extract values that may be modified by the user in their
|
||||
// `TransactionObserver.databaseDidRollback(_:)` implementation
|
||||
// (see below).
|
||||
@@ -481,6 +485,25 @@ extension Database {
|
||||
arguments: arguments,
|
||||
publicStatementArguments: configuration.publicStatementArguments)
|
||||
}
|
||||
|
||||
private func checkForAutocommitTransition() {
|
||||
if sqlite3_get_autocommit(sqliteConnection) == 0 {
|
||||
if autocommitState == .on {
|
||||
// Record transaction date as soon as the connection leaves
|
||||
// auto-commit mode.
|
||||
// We grab a result, so that this failure is later reported
|
||||
// whenever the user calls `Database.transactionDate`.
|
||||
transactionDateResult = Result { try configuration.transactionClock.now(self) }
|
||||
}
|
||||
autocommitState = .off
|
||||
} else {
|
||||
if autocommitState == .off {
|
||||
// Reset transaction date
|
||||
transactionDateResult = nil
|
||||
}
|
||||
autocommitState = .on
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A thread-unsafe statement cache
|
||||
@@ -510,7 +533,7 @@ struct StatementCache {
|
||||
let statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT))
|
||||
#else
|
||||
let statement: Statement
|
||||
if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) {
|
||||
if #available(iOS 12, macOS 10.14, watchOS 5, *) { // SQLite 3.20+
|
||||
statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT))
|
||||
} else {
|
||||
statement = try db.makeStatement(sql: sql)
|
||||
|
||||
+79
-10
@@ -61,6 +61,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// - ``inTransaction(_:_:)``
|
||||
/// - ``isInsideTransaction``
|
||||
/// - ``rollback()``
|
||||
/// - ``transactionDate``
|
||||
/// - ``TransactionCompletion``
|
||||
/// - ``TransactionKind``
|
||||
///
|
||||
@@ -276,6 +277,74 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// This cache is never cleared: we assume journal mode never changes.
|
||||
var journalModeCache: String?
|
||||
|
||||
// MARK: - Transaction Date
|
||||
|
||||
enum AutocommitState {
|
||||
case off
|
||||
case on
|
||||
}
|
||||
|
||||
/// The state of the auto-commit mode, as left by the last
|
||||
/// executed statement.
|
||||
///
|
||||
/// The goal of this property is to detect changes in the auto-commit mode.
|
||||
/// When you need to know if the database is currently in the auto-commit
|
||||
/// mode, always prefer ``isInsideTransaction``.
|
||||
var autocommitState = AutocommitState.on
|
||||
|
||||
/// The date of the current transaction, wrapped in a result that is an
|
||||
/// error if there was an error grabbing this date when the transaction has
|
||||
/// started.
|
||||
///
|
||||
/// Invariant: `transactionDateResult` is nil iff connection is not
|
||||
/// inside a transaction.
|
||||
var transactionDateResult: Result<Date, Error>?
|
||||
|
||||
/// The date of the current transaction.
|
||||
///
|
||||
/// The returned date is constant at any point during a transaction. It is
|
||||
/// set when the database leaves the
|
||||
/// [autocommit mode](https://www.sqlite.org/c3ref/get_autocommit.html) with
|
||||
/// a `BEGIN` statement.
|
||||
///
|
||||
/// When the database is not currently in a transaction, a new date is
|
||||
/// returned on each call.
|
||||
///
|
||||
/// See <doc:RecordTimestamps> for an example of usage.
|
||||
///
|
||||
/// 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 {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
|
||||
// Check invariant: `transactionDateResult` is nil iff connection
|
||||
// is not inside a transaction.
|
||||
assert(isInsideTransaction || transactionDateResult == nil)
|
||||
|
||||
if let transactionDateResult {
|
||||
return try transactionDateResult.get()
|
||||
} else {
|
||||
return try configuration.transactionClock.now(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class AttachedCache {
|
||||
var schema: SchemaIdentifier
|
||||
var statementCache: StatementCache
|
||||
|
||||
init(schema: Database.SchemaIdentifier, statementCache: StatementCache) {
|
||||
self.schema = schema
|
||||
self.statementCache = statementCache
|
||||
}
|
||||
}
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The attached database that caches the results of requests.
|
||||
var attachedCache: AttachedCache?
|
||||
|
||||
// MARK: - Private properties
|
||||
|
||||
/// Support for ``Configuration/busyMode``.
|
||||
@@ -335,10 +404,10 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
_ = sqlite3_close(sqliteConnection) // ignore result code
|
||||
throw DatabaseError(resultCode: code)
|
||||
}
|
||||
if let sqliteConnection = sqliteConnection {
|
||||
return sqliteConnection
|
||||
guard let sqliteConnection else {
|
||||
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
|
||||
}
|
||||
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
|
||||
return sqliteConnection
|
||||
}
|
||||
|
||||
// MARK: - Database Setup
|
||||
@@ -1163,7 +1232,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
if let firstError = firstError {
|
||||
if let firstError {
|
||||
throw firstError
|
||||
}
|
||||
}
|
||||
@@ -1312,7 +1381,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
if let firstError = firstError {
|
||||
if let firstError {
|
||||
throw firstError
|
||||
}
|
||||
}
|
||||
@@ -1861,10 +1930,10 @@ extension Database {
|
||||
enum Impl {
|
||||
case trace_v1(String)
|
||||
case trace_v2(
|
||||
sqliteStatement: SQLiteStatement,
|
||||
unexpandedSQL: UnsafePointer<CChar>?,
|
||||
sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?,
|
||||
publicStatementArguments: Bool) // See Configuration.publicStatementArguments
|
||||
sqliteStatement: SQLiteStatement,
|
||||
unexpandedSQL: UnsafePointer<CChar>?,
|
||||
sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?,
|
||||
publicStatementArguments: Bool) // See Configuration.publicStatementArguments
|
||||
}
|
||||
var impl: Impl
|
||||
|
||||
@@ -1886,7 +1955,7 @@ extension Database {
|
||||
fatalError("Unavailable statement SQL")
|
||||
|
||||
case let .trace_v2(sqliteStatement, unexpandedSQL, _, _):
|
||||
if let unexpandedSQL = unexpandedSQL {
|
||||
if let unexpandedSQL {
|
||||
return String(cString: unexpandedSQL).trimmedSQLStatement
|
||||
} else {
|
||||
return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
|
||||
|
||||
@@ -198,7 +198,7 @@ extension ResultCode: CustomStringConvertible {
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
if let errorString = errorString {
|
||||
if let errorString {
|
||||
return "\(rawValue) (\(errorString))"
|
||||
} else {
|
||||
return "\(rawValue)"
|
||||
@@ -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
|
||||
@@ -543,13 +545,13 @@ extension DatabaseError: CustomStringConvertible {
|
||||
/// without notice: don't have your application rely on any specific format.
|
||||
public var description: String {
|
||||
var description = "SQLite error \(resultCode.rawValue)"
|
||||
if let message = message {
|
||||
if let message {
|
||||
description += ": \(message)"
|
||||
}
|
||||
if let sql = sql {
|
||||
if let sql {
|
||||
description += " - while executing `\(sql)`"
|
||||
}
|
||||
if publicStatementArguments, let arguments = arguments, !arguments.isEmpty {
|
||||
if publicStatementArguments, let arguments, !arguments.isEmpty {
|
||||
description += " with arguments \(arguments)"
|
||||
}
|
||||
return description
|
||||
@@ -571,13 +573,13 @@ extension DatabaseError: CustomStringConvertible {
|
||||
/// property with care.
|
||||
public var expandedDescription: String {
|
||||
var description = "SQLite error \(resultCode.rawValue)"
|
||||
if let message = message {
|
||||
if let message {
|
||||
description += ": \(message)"
|
||||
}
|
||||
if let sql = sql {
|
||||
if let sql {
|
||||
description += " - while executing `\(sql)`"
|
||||
}
|
||||
if let arguments = arguments, !arguments.isEmpty {
|
||||
if let arguments, !arguments.isEmpty {
|
||||
description += " with arguments \(arguments)"
|
||||
}
|
||||
return description
|
||||
@@ -598,7 +600,7 @@ extension DatabaseError: CustomNSError {
|
||||
/// Part of the `CustomNSError` conformance.
|
||||
public var errorUserInfo: [String: Any] {
|
||||
var userInfo = [NSLocalizedDescriptionKey: description]
|
||||
if let message = message {
|
||||
if let message {
|
||||
userInfo[NSLocalizedFailureReasonErrorKey] = message
|
||||
}
|
||||
return userInfo
|
||||
|
||||
@@ -4,66 +4,6 @@ import Foundation
|
||||
import UIKit
|
||||
#endif
|
||||
|
||||
/// A database connection that allows concurrent accesses to an SQLite database.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// Unless ``Configuration/readonly``, a `DatabasePool` opens an SQLite database
|
||||
/// in the [WAL mode](https://sqlite.org/wal.html).
|
||||
///
|
||||
/// It creates one writer SQLite connection, and a pool of up to
|
||||
/// ``Configuration/maximumReaderCount`` read-only SQLite connections. All
|
||||
/// write accesses are executed in a serial **writer dispatch queue**. All
|
||||
/// read accesses are executed in **reader dispatch queues** (one per read-only
|
||||
/// SQLite connection). SQLite connections are closed when the `DatabasePool`
|
||||
/// is deallocated.
|
||||
///
|
||||
/// See <doc:Concurrency> for more information about concurrent
|
||||
/// database accesses.
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// ```swift
|
||||
/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
///
|
||||
/// let playerCount = try dbPool.read { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// let newPlayerCount = try dbPool.write { db -> Int in
|
||||
/// try Player(name: "Arthur").insert(db)
|
||||
/// return try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// `DatabasePool` inherits most of its database access methods from the
|
||||
/// ``DatabaseReader`` and ``DatabaseWriter`` protocols. It defines a few
|
||||
/// specific database access methods as well.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a DatabasePool
|
||||
///
|
||||
/// - ``init(path:configuration:)``
|
||||
///
|
||||
/// ### Accessing the Database
|
||||
///
|
||||
/// See ``DatabaseReader`` and ``DatabaseWriter`` for more database
|
||||
/// access methods.
|
||||
///
|
||||
/// - ``asyncConcurrentRead(_:)``
|
||||
/// - ``writeInTransaction(_:_:)``
|
||||
///
|
||||
/// ### Creating Database Snapshots
|
||||
///
|
||||
/// - ``makeSnapshot()``
|
||||
/// - ``makeSnapshotPool()``
|
||||
///
|
||||
/// ### Managing SQLite Connections
|
||||
///
|
||||
/// - ``invalidateReadOnlyConnections()``
|
||||
/// - ``releaseMemory()``
|
||||
/// - ``releaseMemoryEventually()``
|
||||
public final class DatabasePool {
|
||||
private let writer: SerializedDatabase
|
||||
|
||||
@@ -176,7 +116,7 @@ public final class DatabasePool {
|
||||
// Undo job done in setupMemoryManagement()
|
||||
//
|
||||
// https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error
|
||||
// Explicit unregistration is required before OS X 10.11.
|
||||
// Explicit unregistration is required before macOS 10.11.
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
|
||||
// Close reader connections before the writer connection.
|
||||
@@ -228,12 +168,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.
|
||||
@@ -241,34 +184,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)
|
||||
@@ -421,7 +380,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
|
||||
}
|
||||
|
||||
@@ -465,7 +424,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
|
||||
}
|
||||
|
||||
@@ -668,8 +627,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()
|
||||
}
|
||||
@@ -700,11 +663,55 @@ 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>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
@@ -735,7 +742,7 @@ extension DatabasePool: DatabaseReader {
|
||||
/// the writer.
|
||||
private func _addConcurrent<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#if canImport(Combine)
|
||||
/// A namespace for database Combine publishers.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public enum DatabasePublishers { }
|
||||
#endif
|
||||
@@ -4,51 +4,6 @@ import Foundation
|
||||
import UIKit
|
||||
#endif
|
||||
|
||||
/// A database connection that serializes accesses to an SQLite database.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// A `DatabaseQueue` creates one single SQLite connection. All database
|
||||
/// accesses are executed in a serial **writer dispatch queue**. The SQLite
|
||||
/// connection is closed when the `DatabaseQueue` is deallocated.
|
||||
///
|
||||
/// ```swift
|
||||
/// let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
|
||||
///
|
||||
/// let playerCount = try dbQueue.read { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// let newPlayerCount = try dbQueue.write { db -> Int in
|
||||
/// try Player(name: "Arthur").insert(db)
|
||||
/// return try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// `DatabaseQueue` inherits most of its database access methods from the
|
||||
/// ``DatabaseReader`` and ``DatabaseWriter`` protocols. It defines a few
|
||||
/// specific database access methods as well.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a DatabaseQueue
|
||||
///
|
||||
/// - ``init(named:configuration:)``
|
||||
/// - ``init(path:configuration:)``
|
||||
///
|
||||
/// ### Accessing the Database
|
||||
///
|
||||
/// See ``DatabaseReader`` and ``DatabaseWriter`` for more database
|
||||
/// access methods.
|
||||
///
|
||||
/// - ``inDatabase(_:)``
|
||||
/// - ``inTransaction(_:_:)``
|
||||
///
|
||||
/// ### Managing the SQLite Connection
|
||||
///
|
||||
/// - ``releaseMemory()``
|
||||
public final class DatabaseQueue {
|
||||
private let writer: SerializedDatabase
|
||||
|
||||
@@ -148,7 +103,7 @@ public final class DatabaseQueue {
|
||||
// Undo job done in setupMemoryManagement()
|
||||
//
|
||||
// https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error
|
||||
// Explicit unregistration is required before OS X 10.11.
|
||||
// Explicit unregistration is required before macOS 10.11.
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
}
|
||||
@@ -339,7 +294,7 @@ extension DatabaseQueue: DatabaseReader {
|
||||
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
|
||||
@@ -325,7 +325,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// - returns: A DatabaseCancellable that can stop the observation.
|
||||
func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
}
|
||||
@@ -441,7 +441,7 @@ extension DatabaseReader {
|
||||
/// - parameter value: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
|
||||
/// would happen while establishing the database access.
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func read<T>(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
asyncRead { result in
|
||||
@@ -487,7 +487,7 @@ extension DatabaseReader {
|
||||
/// - parameter value: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
|
||||
/// would happen while establishing the database access.
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func unsafeRead<T>(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
asyncUnsafeRead { result in
|
||||
@@ -532,7 +532,7 @@ extension DatabaseReader {
|
||||
///
|
||||
/// - parameter scheduler: A Combine Scheduler.
|
||||
/// - parameter value: A closure which accesses the database.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func readPublisher<Output>(
|
||||
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
|
||||
value: @escaping (Database) throws -> Output)
|
||||
@@ -550,7 +550,7 @@ extension DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
extension DatabasePublishers {
|
||||
/// A publisher that reads from the database.
|
||||
///
|
||||
@@ -569,7 +569,7 @@ extension DatabasePublishers {
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
extension Publisher where Failure == Error {
|
||||
fileprivate func eraseToReadPublisher() -> DatabasePublishers.Read<Output> {
|
||||
.init(upstream: eraseToAnyPublisher())
|
||||
@@ -584,7 +584,7 @@ extension DatabaseReader {
|
||||
/// initial value.
|
||||
func _addReadOnly<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
@@ -676,7 +676,7 @@ extension AnyDatabaseReader: DatabaseReader {
|
||||
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
|
||||
@@ -168,9 +168,14 @@ public struct DatabaseRegion {
|
||||
// TransactionObserver protocol. By removing internal SQLite tables from
|
||||
// the observed region, we optimize database observation.
|
||||
//
|
||||
// We also remove GRDB internal tables (cache tables).
|
||||
//
|
||||
// And by canonicalizing table names, we remove views, and help the
|
||||
// `isModified` methods.
|
||||
try ignoringInternalSQLiteTables().canonicalTables(db)
|
||||
let notInternalTables = filteringTables {
|
||||
!Database.isSQLiteInternalTable($0) && !Database.isGRDBInternalTable($0)
|
||||
}
|
||||
return try notInternalTables.canonicalTables(db)
|
||||
}
|
||||
|
||||
/// Returns a region only made of actual tables with their canonical names.
|
||||
@@ -190,11 +195,11 @@ public struct DatabaseRegion {
|
||||
return region
|
||||
}
|
||||
|
||||
/// Returns a region which doesn't contain any SQLite internal table.
|
||||
private func ignoringInternalSQLiteTables() -> DatabaseRegion {
|
||||
/// Returns a region which only contains the filtered tables
|
||||
func filteringTables(_ predicate: (String) -> Bool) -> DatabaseRegion {
|
||||
guard let tableRegions else { return .fullDatabase }
|
||||
let filteredRegions = tableRegions.filter {
|
||||
!Database.isSQLiteInternalTable($0.key.rawValue)
|
||||
predicate($0.key.rawValue)
|
||||
}
|
||||
return DatabaseRegion(tableRegions: filteredRegions)
|
||||
}
|
||||
@@ -287,8 +292,8 @@ private struct TableRegion: Equatable {
|
||||
var rowIds: Set<Int64>? // nil means "all rowids"
|
||||
|
||||
var isEmpty: Bool {
|
||||
if let columns = columns, columns.isEmpty { return true }
|
||||
if let rowIds = rowIds, rowIds.isEmpty { return true }
|
||||
if let columns, columns.isEmpty { return true }
|
||||
if let rowIds, rowIds.isEmpty { return true }
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -231,7 +128,7 @@ extension DatabaseRegionObservation {
|
||||
}
|
||||
|
||||
#if canImport(Combine)
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
extension DatabaseRegionObservation {
|
||||
// MARK: - Publishing Impactful Transactions
|
||||
|
||||
@@ -243,7 +140,7 @@ extension DatabaseRegionObservation {
|
||||
///
|
||||
/// Do not reschedule the publisher with `receive(on:options:)` or any
|
||||
/// `Publisher` method that schedules publisher elements.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func publisher(in writer: some DatabaseWriter) -> DatabasePublishers.DatabaseRegion {
|
||||
DatabasePublishers.DatabaseRegion(self, in: writer)
|
||||
}
|
||||
@@ -284,7 +181,7 @@ private class DatabaseRegionObserver: TransactionObserver {
|
||||
}
|
||||
|
||||
#if canImport(Combine)
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
extension DatabasePublishers {
|
||||
/// A publisher that tracks transactions that modify a database region.
|
||||
///
|
||||
|
||||
@@ -170,7 +170,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
|
||||
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
|
||||
@@ -294,7 +294,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
|
||||
}
|
||||
|
||||
@@ -322,14 +322,14 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
return result
|
||||
}
|
||||
} else {
|
||||
/// There is no unsafe access to a snapshot.
|
||||
// There is no unsafe access to a snapshot.
|
||||
return try read(value)
|
||||
}
|
||||
}
|
||||
|
||||
public func _add<Reducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable where Reducer: ValueReducer
|
||||
{
|
||||
|
||||
@@ -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 { }
|
||||
@@ -314,6 +342,25 @@ extension DatabaseValue: CustomStringConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValue {
|
||||
/// A string that represented the value in a lossless and
|
||||
/// unambiguous way.
|
||||
var losslessDescription: String {
|
||||
switch storage {
|
||||
case .null:
|
||||
return "NULL"
|
||||
case let .string(string):
|
||||
return String(reflecting: string)
|
||||
case let .double(double):
|
||||
return double.description
|
||||
case let .int64(int64):
|
||||
return int64.description
|
||||
case let .blob(data):
|
||||
return "X'" + data.map { String(format: "%02X", $0) }.joined() + "'"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Compares DatabaseValue like SQLite.
|
||||
///
|
||||
/// See RxGRDB for tests.
|
||||
|
||||
@@ -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 }
|
||||
@@ -158,16 +147,14 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
|
||||
private let columnIndex: CInt
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
|
||||
let statement = try statement.databaseCursorStatement(with: arguments)
|
||||
self._statement = statement
|
||||
if let adapter = adapter {
|
||||
if let adapter {
|
||||
// adapter may redefine the index of the leftmost column
|
||||
columnIndex = try CInt(adapter.baseColumnIndex(atIndex: 0, layout: statement))
|
||||
} else {
|
||||
columnIndex = 0
|
||||
}
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
try statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
|
||||
@@ -516,7 +516,7 @@ extension DatabaseWriter {
|
||||
///
|
||||
/// - Parameter filePath: file path for new database
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
@available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *)
|
||||
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *)
|
||||
public func vacuum(into filePath: String) throws {
|
||||
try writeWithoutTransaction {
|
||||
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
|
||||
@@ -531,7 +531,7 @@ extension DatabaseWriter {
|
||||
/// was modified.
|
||||
func _addWriteOnly<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
@@ -582,7 +582,7 @@ extension DatabaseWriter {
|
||||
/// - throws: The error thrown by `updates`, or any ``DatabaseError`` that
|
||||
/// would happen while establishing the database access or committing
|
||||
/// the transaction.
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func write<T>(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
asyncWrite(updates, completion: { _, result in
|
||||
@@ -620,7 +620,7 @@ extension DatabaseWriter {
|
||||
///
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `updates`.
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func writeWithoutTransaction<T>(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
asyncWriteWithoutTransaction { db in
|
||||
@@ -672,7 +672,7 @@ extension DatabaseWriter {
|
||||
///
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `updates`.
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func barrierWriteWithoutTransaction<T>(
|
||||
_ updates: @Sendable @escaping (Database) throws -> T)
|
||||
async throws -> T
|
||||
@@ -687,7 +687,7 @@ extension DatabaseWriter {
|
||||
/// Erases the content of the database.
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func erase() async throws {
|
||||
try await writeWithoutTransaction { try $0.erase() }
|
||||
}
|
||||
@@ -698,7 +698,7 @@ extension DatabaseWriter {
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_vacuum.html>
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func vacuum() async throws {
|
||||
try await writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
|
||||
}
|
||||
@@ -715,7 +715,7 @@ extension DatabaseWriter {
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_vacuum.html#vacuuminto>
|
||||
///
|
||||
/// - Parameter filePath: file path for new database
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func vacuum(into filePath: String) async throws {
|
||||
try await writeWithoutTransaction {
|
||||
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
|
||||
@@ -730,7 +730,7 @@ extension DatabaseWriter {
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_vacuum.html#vacuuminto>
|
||||
///
|
||||
/// - Parameter filePath: file path for new database
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func vacuum(into filePath: String) async throws {
|
||||
try await writeWithoutTransaction {
|
||||
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
|
||||
@@ -775,7 +775,7 @@ extension DatabaseWriter {
|
||||
///
|
||||
/// - parameter scheduler: A Combine Scheduler.
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func writePublisher<Output>(
|
||||
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
|
||||
updates: @escaping (Database) throws -> Output)
|
||||
@@ -840,7 +840,7 @@ extension DatabaseWriter {
|
||||
/// - parameter scheduler: A Combine Scheduler.
|
||||
/// - parameter updates: A closure which writes in the database.
|
||||
/// - parameter value: A closure which reads from the database.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func writePublisher<S, T, Output>(
|
||||
receiveOn scheduler: S = DispatchQueue.main,
|
||||
updates: @escaping (Database) throws -> T,
|
||||
@@ -872,7 +872,7 @@ extension DatabaseWriter {
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
extension DatabasePublishers {
|
||||
/// A publisher that writes into the database.
|
||||
///
|
||||
@@ -891,7 +891,7 @@ extension DatabasePublishers {
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
extension Publisher where Failure == Error {
|
||||
fileprivate func eraseToWritePublisher() -> DatabasePublishers.Write<Output> {
|
||||
.init(upstream: self.eraseToAnyPublisher())
|
||||
@@ -993,7 +993,7 @@ extension AnyDatabaseWriter: DatabaseReader {
|
||||
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
|
||||
@@ -141,7 +141,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.
|
||||
|
||||
+6
-10
@@ -682,7 +682,7 @@ extension Row {
|
||||
/// ``JoinableRequest/including(optional:)`` request methods define scopes
|
||||
/// named after the key of included associations between record types.
|
||||
///
|
||||
/// A depth-first search is performed in all available scopes in the row,
|
||||
/// A breadth-first search is performed in all available scopes in the row,
|
||||
/// recursively.
|
||||
///
|
||||
/// A fatal error is raised if the scope is not available, or contains only
|
||||
@@ -726,7 +726,7 @@ extension Row {
|
||||
/// ``JoinableRequest/including(optional:)`` request methods define scopes
|
||||
/// named after the key of included associations between record types.
|
||||
///
|
||||
/// A depth-first search is performed in all available scopes in the row,
|
||||
/// A breadth-first search is performed in all available scopes in the row,
|
||||
/// recursively.
|
||||
///
|
||||
/// The result is nil if the scope is not available, or contains only
|
||||
@@ -879,7 +879,7 @@ extension Row {
|
||||
/// A view on the scopes tree defined by row adapters.
|
||||
///
|
||||
/// The returned object provides an access to all available scopes in
|
||||
/// the row, recursively. For any given scope identifier, a depth-first
|
||||
/// the row, recursively. For any given scope identifier, a breadth-first
|
||||
/// search is performed.
|
||||
///
|
||||
/// Row scopes can be defined manually, with ``ScopeAdapter``.
|
||||
@@ -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)
|
||||
@@ -1362,11 +1360,9 @@ public final class RowCursor: DatabaseCursor {
|
||||
@usableFromInline let _row: Row // Reused for performance
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
|
||||
let statement = try statement.databaseCursorStatement(with: arguments)
|
||||
self._statement = statement
|
||||
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)
|
||||
}
|
||||
|
||||
deinit {
|
||||
|
||||
+294
-67
@@ -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
|
||||
@@ -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
|
||||
|
||||
|
||||
+2
-2
@@ -121,8 +121,8 @@ public struct SQL {
|
||||
fileprivate func qualified(with alias: TableAlias) -> Element {
|
||||
switch self {
|
||||
case .sql:
|
||||
/// A raw SQL string can't be qualified with a table alias,
|
||||
/// because we can't parse it.
|
||||
// A raw SQL string can't be qualified with a table alias,
|
||||
// because we can't parse it.
|
||||
return self
|
||||
case .subquery:
|
||||
// Subqueries don't need table alias
|
||||
|
||||
@@ -206,9 +206,9 @@ extension SQLRequest: FetchRequest {
|
||||
switch cache {
|
||||
case .none:
|
||||
statement = try db.makeStatement(sql: sql)
|
||||
case .public?:
|
||||
case .public:
|
||||
statement = try db.cachedStatement(sql: sql)
|
||||
case .internal?:
|
||||
case .internal:
|
||||
statement = try db.internalCachedStatement(sql: sql)
|
||||
}
|
||||
try statement.setArguments(context.arguments)
|
||||
|
||||
@@ -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)
|
||||
|
||||
+373
-140
@@ -1,3 +1,4 @@
|
||||
import CryptoKit
|
||||
import Foundation
|
||||
|
||||
/// A raw SQLite statement, suitable for the SQLite C API.
|
||||
@@ -25,59 +26,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 +57,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
|
||||
@@ -134,6 +96,23 @@ public final class Statement {
|
||||
authorizerEventKinds.contains(where: \.isDelete)
|
||||
}
|
||||
|
||||
/// A string that represented the statement in a lossless and
|
||||
/// unambiguous way.
|
||||
lazy var losslessDescription: String = {
|
||||
"\(sql); -- \(arguments.losslessDescription)"
|
||||
}()
|
||||
|
||||
/// A table name for caching the results of this statement
|
||||
lazy var cacheTableName: String? = {
|
||||
guard #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *),
|
||||
let losslessDescription = losslessDescription.data(using: .utf8)
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
let digest = Insecure.SHA1.hash(data: losslessDescription)
|
||||
return "grdb_cache_" + digest.map { String(format: "%02X", $0) }.joined()
|
||||
}()
|
||||
|
||||
@usableFromInline
|
||||
unowned let database: Database
|
||||
|
||||
@@ -175,7 +154,7 @@ public final class Statement {
|
||||
database.sqliteConnection, statementStart, -1, prepFlags,
|
||||
&sqliteStatement, statementEnd)
|
||||
#else
|
||||
if #available(iOS 12.0, OSX 10.14, tvOS 12.0, watchOS 5.0, *) {
|
||||
if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { // SQLite 3.20+
|
||||
code = sqlite3_prepare_v3(
|
||||
database.sqliteConnection, statementStart, -1, prepFlags,
|
||||
&sqliteStatement, statementEnd)
|
||||
@@ -209,25 +188,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 +291,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 +306,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 +320,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,23 +335,24 @@ 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()
|
||||
for (index, argumentName) in zip(CInt(1)..., sqliteArgumentNames) {
|
||||
if let argumentName = argumentName, let value = arguments.namedValues[argumentName] {
|
||||
if let argumentName, let value = arguments.namedValues[argumentName] {
|
||||
bind(value, at: index)
|
||||
} else if let value = valuesIterator.next() {
|
||||
bind(value, at: index)
|
||||
@@ -302,14 +360,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 +379,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 +388,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 +457,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 = 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 +503,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.
|
||||
@@ -507,37 +673,47 @@ extension Statement {
|
||||
|
||||
/// A cursor that lazily iterates the results of a prepared ``Statement``.
|
||||
///
|
||||
/// To get a `DatabaseCursor` instance, use a fetching method of
|
||||
/// ``Row``, ``DatabaseValueConvertible``, ``FetchableRecord``,
|
||||
/// or ``FetchRequest``. For example:
|
||||
/// ## Overview
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// // A cursor of database rows,
|
||||
/// // built from a prepared statement
|
||||
/// let statement = try db.makeStatement(sql: "SELECT * FROM player")
|
||||
/// let rows = try Row.fetchCursor(statement)
|
||||
/// while let row = try rows.next() {
|
||||
/// let id: Int64 = row["id"]
|
||||
/// let name: String = row["name"]
|
||||
/// }
|
||||
/// To get a `DatabaseCursor` instance, use one of the `fetchCursor` methods.
|
||||
/// For example:
|
||||
///
|
||||
/// // A cursor of values,
|
||||
/// // built from an SQL string
|
||||
/// let scores = try Int.fetchCursor(db, sql: "SELECT score FROM player")
|
||||
/// while let score = try scores.next() {
|
||||
/// print(score)
|
||||
/// }
|
||||
/// - A cursor of ``Row`` built from a prepared ``Statement``:
|
||||
///
|
||||
/// // A cursor of players,
|
||||
/// // built from a QueryInterfaceRequest:
|
||||
/// let request = Player.all()
|
||||
/// let players = try request.fetchCursor(db)
|
||||
/// while let player = try players.next() {
|
||||
/// print(player.name, player.score)
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let statement = try db.makeStatement(sql: "SELECT * FROM player")
|
||||
/// let rows = try Row.fetchCursor(statement)
|
||||
/// while let row = try rows.next() {
|
||||
/// let id: Int64 = row["id"]
|
||||
/// let name: String = row["name"]
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
/// ```
|
||||
///
|
||||
/// - A cursor of `Int` built from an SQL string (see ``DatabaseValueConvertible``):
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let sql = "SELECT score FROM player"
|
||||
/// let scores = try Int.fetchCursor(db, sql: sql)
|
||||
/// while let score = try scores.next() {
|
||||
/// print(score)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - A cursor of `Player` records built from a request (see ``FetchableRecord`` and ``FetchRequest``):
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let request = Player.all()
|
||||
/// let players = try request.fetchCursor(db)
|
||||
/// while let player = try players.next() {
|
||||
/// print(player.name, player.score)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// A database cursor is valid only during the current database access (read or
|
||||
/// write). Do not store or escape a cursor for later use.
|
||||
@@ -621,10 +797,7 @@ final class StatementCursor: DatabaseCursor {
|
||||
|
||||
// Use Statement.makeCursor() instead
|
||||
init(statement: Statement, arguments: StatementArguments? = nil) throws {
|
||||
self._statement = statement
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
try statement.reset(withArguments: arguments)
|
||||
_statement = try statement.databaseCursorStatement(with: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -669,11 +842,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
|
||||
@@ -689,9 +901,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
|
||||
///
|
||||
@@ -1110,36 +1322,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 = argumentName {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -1186,4 +1404,19 @@ extension StatementArguments: CustomStringConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
extension StatementArguments {
|
||||
/// A string that represented the value in a lossless and
|
||||
/// unambiguous way.
|
||||
var losslessDescription: String {
|
||||
var chunks: [String] = []
|
||||
for value in values {
|
||||
chunks.append(value.losslessDescription)
|
||||
}
|
||||
for (key, value) in namedValues.sorted(by: { $0.key < $1.key }) {
|
||||
chunks.append("\(key): \(value.losslessDescription)")
|
||||
}
|
||||
return chunks.joined(separator: ",")
|
||||
}
|
||||
}
|
||||
|
||||
extension StatementArguments: Sendable { }
|
||||
@@ -107,7 +107,7 @@ final class StatementAuthorizer {
|
||||
|
||||
case SQLITE_DELETE:
|
||||
if isDropStatement { return SQLITE_OK }
|
||||
guard let cString1 = cString1 else { return SQLITE_OK }
|
||||
guard let cString1 else { return SQLITE_OK }
|
||||
|
||||
// Deletions from sqlite_master and sqlite_temp_master are not like
|
||||
// other deletions: `sqlite3_update_hook` does not notify them, and
|
||||
@@ -137,7 +137,7 @@ final class StatementAuthorizer {
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_TRANSACTION:
|
||||
guard let cString1 = cString1 else { return SQLITE_OK }
|
||||
guard let cString1 else { return SQLITE_OK }
|
||||
if strcmp(cString1, "BEGIN") == 0 {
|
||||
transactionEffect = .beginTransaction
|
||||
} else if strcmp(cString1, "COMMIT") == 0 {
|
||||
@@ -148,7 +148,7 @@ final class StatementAuthorizer {
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_SAVEPOINT:
|
||||
guard let cString1 = cString1 else { return SQLITE_OK }
|
||||
guard let cString1 else { return SQLITE_OK }
|
||||
guard let name = cString2.map(String.init) else { return SQLITE_OK }
|
||||
if strcmp(cString1, "BEGIN") == 0 {
|
||||
transactionEffect = .beginSavepoint(name)
|
||||
|
||||
@@ -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]
|
||||
@@ -214,16 +214,14 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
@usableFromInline let columnIndex: CInt
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
|
||||
let statement = try statement.databaseCursorStatement(with: arguments)
|
||||
self._statement = statement
|
||||
if let adapter = adapter {
|
||||
if let adapter {
|
||||
// adapter may redefine the index of the leftmost column
|
||||
columnIndex = try CInt(adapter.baseColumnIndex(atIndex: 0, layout: statement))
|
||||
} else {
|
||||
columnIndex = 0
|
||||
}
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
try statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import Foundation
|
||||
|
||||
/// A type that provides the moment of a transaction.
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Built-in Clocks
|
||||
///
|
||||
/// - ``DefaultTransactionClock``
|
||||
/// - ``CustomTransactionClock``
|
||||
public protocol TransactionClock {
|
||||
/// Returns the date of the current transaction.
|
||||
///
|
||||
/// This function is called whenever a transaction starts - precisely
|
||||
/// speaking, whenever the database connection leaves the auto-commit mode.
|
||||
///
|
||||
/// It is also called when the ``Database/transactionDate`` property is
|
||||
/// called, and the database connection is not in a transaction.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/get_autocommit.html>
|
||||
func now(_ db: Database) throws -> Date
|
||||
}
|
||||
|
||||
extension TransactionClock where Self == DefaultTransactionClock {
|
||||
/// Returns the default clock.
|
||||
public static var `default`: Self { DefaultTransactionClock() }
|
||||
}
|
||||
|
||||
extension TransactionClock where Self == CustomTransactionClock {
|
||||
/// Returns a custom clock.
|
||||
///
|
||||
/// The provided closure is called whenever a transaction starts - precisely
|
||||
/// speaking, whenever the database connection leaves the auto-commit mode.
|
||||
///
|
||||
/// It is also called when the ``Database/transactionDate`` property is
|
||||
/// called, and the database connection is not in a transaction.
|
||||
public static func custom(_ now: @escaping (Database) throws -> Date) -> Self {
|
||||
CustomTransactionClock(now)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
Date()
|
||||
}
|
||||
}
|
||||
|
||||
/// A custom transaction clock.
|
||||
public struct CustomTransactionClock: TransactionClock {
|
||||
let _now: (Database) throws -> Date
|
||||
|
||||
public init(_ now: @escaping (Database) throws -> Date) {
|
||||
self._now = now
|
||||
}
|
||||
|
||||
public func now(_ db: Database) throws -> Date {
|
||||
try _now(db)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -1125,7 +820,7 @@ public protocol TransactionObserver: AnyObject {
|
||||
///
|
||||
/// Requires SQLite compiled with option SQLITE_ENABLE_PREUPDATE_HOOK.
|
||||
///
|
||||
/// As of OSX 10.11.5, and iOS 9.3.2, the built-in SQLite library
|
||||
/// As of macOS 10.11.5, and iOS 9.3.2, the built-in SQLite library
|
||||
/// does not have this enabled, so you'll need to compile your own
|
||||
/// version of SQLite:
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md>
|
||||
@@ -1482,7 +1177,7 @@ public struct DatabasePreUpdateEvent {
|
||||
/// The triggering depth of the row update
|
||||
/// Returns:
|
||||
/// 0 if the preupdate callback was invoked as a result of a direct insert,
|
||||
// update, or delete operation;
|
||||
/// update, or delete operation;
|
||||
/// 1 for inserts, updates, or deletes invoked by top-level triggers;
|
||||
/// 2 for changes resulting from triggers called by top-level triggers;
|
||||
/// ... and so forth
|
||||
@@ -1699,7 +1394,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
|
||||
{
|
||||
var value: SQLiteValue? = nil
|
||||
guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil }
|
||||
if let value = value {
|
||||
if let value {
|
||||
return DatabaseValue(sqliteValue: value)
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -65,7 +65,7 @@ final class WALSnapshot: Sendable {
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/snapshot_cmp.html>.
|
||||
func compare(_ other: WALSnapshot) -> CInt {
|
||||
return sqlite3_snapshot_cmp(sqliteSnapshot, other.sqliteSnapshot)
|
||||
sqlite3_snapshot_cmp(sqliteSnapshot, other.sqliteSnapshot)
|
||||
}
|
||||
#else
|
||||
static let available = false
|
||||
|
||||
@@ -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
|
||||
@@ -45,7 +45,7 @@ try dbQueue.read { db
|
||||
}
|
||||
```
|
||||
|
||||
Alternatively, you can open an explicit transaction or savepoint with ``Database/inTransaction(_:_:)`` and ``Database/inSavepoint(_:)``.
|
||||
Alternatively, you can open an explicit transaction or savepoint: see <doc:Transactions>.
|
||||
|
||||
- *Why does this rule exist?* - Because GRDB and SQLite can not guess where to insert the transaction boundaries that protect the invariants of your database. This is your task. Transactions also avoid concurrency problems, as described in the <doc:Concurrency#Safe-and-Unsafe-Database-Accesses> section below.
|
||||
|
||||
|
||||
@@ -17,25 +17,95 @@ let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
The differences are:
|
||||
|
||||
- `DatabasePool` allows concurrent database accesses (this can improve the performance of multithreaded applications).
|
||||
- `DatabasePool` opens your SQLite database in the [WAL mode](https://www.sqlite.org/wal.html) (unless read-only).
|
||||
- `DatabaseQueue` supports [in-memory databases](https://www.sqlite.org/inmemorydb.html).
|
||||
- `DatabasePool` opens your SQLite database in the [WAL mode](https://www.sqlite.org/wal.html).
|
||||
- `DatabaseQueue` supports <doc:DatabaseQueue#In-Memory-Databases>.
|
||||
|
||||
**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
|
||||
### Configuring database connections
|
||||
|
||||
- ``Configuration``
|
||||
|
||||
### Database Connections
|
||||
### Connections for read and write accesses
|
||||
|
||||
- ``DatabaseQueue``
|
||||
- ``DatabasePool``
|
||||
|
||||
### Read-only connections on an unchanging database content
|
||||
|
||||
- ``DatabaseSnapshot``
|
||||
- ``DatabaseSnapshotPool``
|
||||
|
||||
### Using Database Connections
|
||||
### Using database connections
|
||||
|
||||
- ``Database``
|
||||
- ``DatabaseError``
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ Compared to [SQLite.swift](https://github.com/stephencelis/SQLite.swift) or [FMD
|
||||
- <doc:DatabaseConnections>
|
||||
- <doc:SQLSupport>
|
||||
- <doc:Concurrency>
|
||||
- <doc:Transactions>
|
||||
|
||||
### Migrations and The Database Schema
|
||||
|
||||
@@ -31,6 +32,7 @@ Compared to [SQLite.swift](https://github.com/stephencelis/SQLite.swift) or [FMD
|
||||
### Records and the Query Interface
|
||||
|
||||
- <doc:QueryInterface>
|
||||
- <doc:RecordTimestamps>
|
||||
|
||||
### Responding to Database Changes
|
||||
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
# ``GRDB/Configuration``
|
||||
|
||||
The configuration of a database connection.
|
||||
|
||||
## Overview
|
||||
|
||||
You create a `Configuration` before opening a database connection:
|
||||
|
||||
```swift
|
||||
var config = Configuration()
|
||||
config.readonly = true
|
||||
config.maximumReaderCount = 2 // (DatabasePool only) The default is 5
|
||||
|
||||
let dbQueue = try DatabaseQueue( // or DatabasePool
|
||||
path: "/path/to/database.sqlite",
|
||||
configuration: config)
|
||||
```
|
||||
|
||||
See <doc:DatabaseConnections>.
|
||||
|
||||
## Frequent Use Cases
|
||||
|
||||
#### Tracing SQL Statements
|
||||
|
||||
You can setup a tracing function that prints out all executed SQL requests with ``prepareDatabase(_:)`` and ``Database/trace(options:_:)``:
|
||||
|
||||
```swift
|
||||
var config = Configuration()
|
||||
config.prepareDatabase { db in
|
||||
db.trace { print("SQL> \($0)") }
|
||||
}
|
||||
|
||||
let dbQueue = try DatabaseQueue(
|
||||
path: "/path/to/database.sqlite",
|
||||
configuration: config)
|
||||
|
||||
// Prints "SQL> SELECT COUNT(*) FROM player"
|
||||
let playerCount = dbQueue.read { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
#### Public Statement Arguments
|
||||
|
||||
Debugging is easier when database errors and tracing functions expose the values sent to the database. Since those values may contain sensitive information, verbose logging is disabled by default. You turn it on with ``publicStatementArguments``:
|
||||
|
||||
```swift
|
||||
var config = Configuration()
|
||||
#if DEBUG
|
||||
// Protect sensitive information by enabling
|
||||
// verbose debugging in DEBUG builds only.
|
||||
config.publicStatementArguments = true
|
||||
#endif
|
||||
|
||||
let dbQueue = try DatabaseQueue(
|
||||
path: "/path/to/database.sqlite",
|
||||
configuration: config)
|
||||
|
||||
do {
|
||||
try dbQueue.write { db in
|
||||
user.name = ...
|
||||
user.location = ...
|
||||
user.address = ...
|
||||
user.phoneNumber = ...
|
||||
try user.save(db)
|
||||
}
|
||||
} catch {
|
||||
// Prints sensitive information in debug builds only
|
||||
print(error)
|
||||
}
|
||||
```
|
||||
|
||||
> Warning: It is your responsibility to prevent sensitive information from leaking in unexpected locations, so you should not set the `publicStatementArguments` flag in release builds (think about GDPR and other privacy-related rules).
|
||||
|
||||
## Topics
|
||||
|
||||
### Creating a Configuration
|
||||
|
||||
- ``init()``
|
||||
|
||||
### Configuring SQLite Connections
|
||||
|
||||
- ``acceptsDoubleQuotedStringLiterals``
|
||||
- ``busyMode``
|
||||
- ``foreignKeysEnabled``
|
||||
- ``readonly``
|
||||
|
||||
### Configuring GRDB Connections
|
||||
|
||||
- ``allowsUnsafeTransactions``
|
||||
- ``defaultTransactionKind``
|
||||
- ``label``
|
||||
- ``maximumReaderCount``
|
||||
- ``observesSuspensionNotifications``
|
||||
- ``persistentReadOnlyConnections``
|
||||
- ``prepareDatabase(_:)``
|
||||
- ``publicStatementArguments``
|
||||
- ``transactionClock``
|
||||
- ``TransactionClock``
|
||||
|
||||
### Configuring the Quality of Service
|
||||
|
||||
- ``qos``
|
||||
- ``readQoS``
|
||||
- ``writeQoS``
|
||||
- ``targetQueue``
|
||||
- ``writeTargetQueue``
|
||||
@@ -0,0 +1,96 @@
|
||||
# ``GRDB/DatabasePool``
|
||||
|
||||
A database connection that allows concurrent accesses to an SQLite database.
|
||||
|
||||
## Usage
|
||||
|
||||
Open a `DatabasePool` with the path to a database file:
|
||||
|
||||
```swift
|
||||
import GRDB
|
||||
|
||||
let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
```
|
||||
|
||||
SQLite creates the database file if it does not already exist. The connection is closed when the database queue gets deallocated.
|
||||
|
||||
**A `DatabasePool` can be used from any thread.** The ``DatabaseWriter/write(_:)-76inz`` and ``DatabaseReader/read(_:)-3806d`` methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue:
|
||||
|
||||
```swift
|
||||
// Modify the database:
|
||||
try dbPool.write { db in
|
||||
try Player(name: "Arthur").insert(db)
|
||||
}
|
||||
|
||||
// Read values:
|
||||
try dbPool.read { db in
|
||||
let players = try Player.fetchAll(db)
|
||||
let playerCount = try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
Database access methods can return values:
|
||||
|
||||
```swift
|
||||
let playerCount = try dbPool.read { db in
|
||||
try Place.fetchCount(db)
|
||||
}
|
||||
|
||||
let newPlayerCount = try dbPool.write { db -> Int in
|
||||
try Player(name: "Arthur").insert(db)
|
||||
return try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
The ``DatabaseWriter/write(_:)-76inz`` method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rollbacked, and the error is rethrown.
|
||||
|
||||
When you don't need to modify the database, prefer the ``DatabaseReader/read(_:)-3806d`` method, because several threads can perform reads in parallel.
|
||||
|
||||
When precise transaction handling is required, see <doc:Transactions>.
|
||||
|
||||
Asynchronous database accesses are described in <doc:Concurrency>.
|
||||
|
||||
`DatabasePool` can take snapshots of the database: see ``DatabaseSnapshot`` and ``DatabaseSnapshotPool``.
|
||||
|
||||
`DatabasePool` can be configured with ``Configuration``.
|
||||
|
||||
## Concurrency
|
||||
|
||||
A `DatabasePool` creates one writer SQLite connection, and a pool of read-only SQLite connections.
|
||||
|
||||
Unless ``Configuration/readonly``, the database is set to the [WAL mode](https://sqlite.org/wal.html). The WAL mode makes it possible for reads and writes to proceed concurrently.
|
||||
|
||||
All write accesses are executed in a serial **writer dispatch queue**, which means that there is never more than one thread that writes in the database.
|
||||
|
||||
All read accesses are executed in **reader dispatch queues** (one per read-only SQLite connection). Reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be configured with ``Configuration/maximumReaderCount``.
|
||||
|
||||
SQLite connections are closed when the `DatabasePool` is deallocated.
|
||||
|
||||
`DatabasePool` inherits most of its database access methods from the ``DatabaseReader`` and ``DatabaseWriter`` protocols. It defines a few specific database access methods as well, listed below.
|
||||
|
||||
A `DatabasePool` needs your application to follow rules in order to deliver its safety guarantees. See <doc:Concurrency> for more information.
|
||||
|
||||
## Topics
|
||||
|
||||
### Creating a DatabasePool
|
||||
|
||||
- ``init(path:configuration:)``
|
||||
|
||||
### Accessing the Database
|
||||
|
||||
See ``DatabaseReader`` and ``DatabaseWriter`` for more database
|
||||
access methods.
|
||||
|
||||
- ``asyncConcurrentRead(_:)``
|
||||
- ``writeInTransaction(_:_:)``
|
||||
|
||||
### Creating Database Snapshots
|
||||
|
||||
- ``makeSnapshot()``
|
||||
- ``makeSnapshotPool()``
|
||||
|
||||
### Managing SQLite Connections
|
||||
|
||||
- ``invalidateReadOnlyConnections()``
|
||||
- ``releaseMemory()``
|
||||
- ``releaseMemoryEventually()``
|
||||
@@ -0,0 +1,102 @@
|
||||
# ``GRDB/DatabaseQueue``
|
||||
|
||||
A database connection that serializes accesses to an SQLite database.
|
||||
|
||||
## Usage
|
||||
|
||||
Open a `DatabaseQueue` with the path to a database file:
|
||||
|
||||
```swift
|
||||
import GRDB
|
||||
|
||||
let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
|
||||
```
|
||||
|
||||
SQLite creates the database file if it does not already exist. The connection is closed when the database queue gets deallocated.
|
||||
|
||||
**A `DatabaseQueue` can be used from any thread.** The ``DatabaseWriter/write(_:)-76inz`` and ``DatabaseReader/read(_:)-3806d`` methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue:
|
||||
|
||||
```swift
|
||||
// Modify the database:
|
||||
try dbQueue.write { db in
|
||||
try Player(name: "Arthur").insert(db)
|
||||
}
|
||||
|
||||
// Read values:
|
||||
try dbQueue.read { db in
|
||||
let players = try Player.fetchAll(db)
|
||||
let playerCount = try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
Database access methods can return values:
|
||||
|
||||
```swift
|
||||
let playerCount = try dbQueue.read { db in
|
||||
try Place.fetchCount(db)
|
||||
}
|
||||
|
||||
let newPlayerCount = try dbQueue.write { db -> Int in
|
||||
try Player(name: "Arthur").insert(db)
|
||||
return try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
The ``DatabaseWriter/write(_:)-76inz`` method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rollbacked, and the error is rethrown.
|
||||
|
||||
When you don't need to modify the database, prefer the ``DatabaseReader/read(_:)-3806d`` method: it prevents any modification to the database.
|
||||
|
||||
When precise transaction handling is required, see <doc:Transactions>.
|
||||
|
||||
Asynchronous database accesses are described in <doc:Concurrency>.
|
||||
|
||||
`DatabaseQueue` can be configured with ``Configuration``.
|
||||
|
||||
## In-Memory Databases
|
||||
|
||||
`DatabaseQueue` can open a connection to an [in-memory SQLite database](https://www.sqlite.org/inmemorydb.html).
|
||||
|
||||
Such connections are quite handy for tests and SwiftUI previews, since you do not have to perform any cleanup of the file system.
|
||||
|
||||
```swift
|
||||
let dbQueue = try DatabaseQueue()
|
||||
```
|
||||
|
||||
In order to create several connections to the same in-memory database, give this database a name:
|
||||
|
||||
```swift
|
||||
// A shared in-memory database
|
||||
let dbQueue1 = try DatabaseQueue(named: "myDatabase")
|
||||
|
||||
// Another connection to the same database
|
||||
let dbQueue2 = try DatabaseQueue(named: "myDatabase")
|
||||
```
|
||||
|
||||
See ``init(named:configuration:)``.
|
||||
|
||||
## Concurrency
|
||||
|
||||
A `DatabaseQueue` creates one single SQLite connection. All database accesses are executed in a serial **writer dispatch queue**, which means that there is never more than one thread that uses the database. The SQLite connection is closed when the `DatabaseQueue` is deallocated.
|
||||
|
||||
`DatabaseQueue` inherits most of its database access methods from the ``DatabaseReader`` and ``DatabaseWriter`` protocols. It defines a few specific database access methods as well, listed below.
|
||||
|
||||
A `DatabaseQueue` needs your application to follow rules in order to deliver its safety guarantees. See <doc:Concurrency> for more information.
|
||||
|
||||
## Topics
|
||||
|
||||
### Creating a DatabaseQueue
|
||||
|
||||
- ``init(named:configuration:)``
|
||||
- ``init(path:configuration:)``
|
||||
|
||||
### Accessing the Database
|
||||
|
||||
See ``DatabaseReader`` and ``DatabaseWriter`` for more database
|
||||
access methods.
|
||||
|
||||
- ``inDatabase(_:)``
|
||||
- ``inTransaction(_:_:)``
|
||||
|
||||
### Managing the SQLite Connection
|
||||
|
||||
- ``releaseMemory()``
|
||||
@@ -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,171 @@
|
||||
# ``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``
|
||||
|
||||
### 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,264 @@
|
||||
# ``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** 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.
|
||||
|
||||
## 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``
|
||||
@@ -12,3 +12,4 @@ Please refer to the [Full-Text Search](https://github.com/groue/GRDB.swift/blob/
|
||||
|
||||
- ``FTS3``
|
||||
- ``FTS4``
|
||||
- ``FTS5``
|
||||
@@ -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,440 @@
|
||||
# Record Timestamps and Transaction Date
|
||||
|
||||
Learn how applications can save creation and modification dates of records.
|
||||
|
||||
## Overview
|
||||
|
||||
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 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, 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:
|
||||
|
||||
```swift
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("creationDate", .datetime).notNull()
|
||||
t.column("modificationDate", .datetime).notNull()
|
||||
t.column("name", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
|
||||
struct Player: Identifiable {
|
||||
var id: Int64?
|
||||
var creationDate: Date?
|
||||
var modificationDate: Date?
|
||||
var name: String
|
||||
var score: Int
|
||||
}
|
||||
```
|
||||
|
||||
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`:
|
||||
|
||||
```swift
|
||||
// A new player has no timestamps.
|
||||
var player = Player(id: nil, name: "Arthur", score: 1000)
|
||||
player.id // nil, because never saved
|
||||
player.creationDate // nil, because never saved
|
||||
player.modificationDate // nil, because never saved
|
||||
|
||||
// After insertion, the player has timestamps.
|
||||
try dbQueue.write { db in
|
||||
try player.insert(db)
|
||||
}
|
||||
player.id // not nil
|
||||
player.creationDate // not nil
|
||||
player.modificationDate // not nil
|
||||
```
|
||||
|
||||
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 `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 {
|
||||
/// 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
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
```swift
|
||||
// All players have the same timestamp.
|
||||
try dbQueue.write { db in
|
||||
for var player in players {
|
||||
try player.insert(db)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- The transaction date can be configured with ``Configuration/transactionClock``, so that your tests and previews can control the date.
|
||||
|
||||
## Modification Timestamp
|
||||
|
||||
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 (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
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
```swift
|
||||
let player = try dbQueue.read { db
|
||||
try Player.find(db, id: 1)
|
||||
}
|
||||
player.creationDate // optional 😕
|
||||
player.modificationDate // optional 😕
|
||||
```
|
||||
|
||||
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? // optional
|
||||
var creationDate: Date? // optional
|
||||
var modificationDate: Date? // optional
|
||||
var name: String
|
||||
var score: Int
|
||||
}
|
||||
|
||||
extension Player: Encodable, MutablePersistableRecord {
|
||||
/// Updates auto-incremented id upon successful insertion
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `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 PersistedPlayer: Codable, FetchableRecord, PersistableRecord {
|
||||
static var databaseTableName: String { "player" }
|
||||
}
|
||||
```
|
||||
|
||||
Usage:
|
||||
|
||||
```swift
|
||||
// Fetch
|
||||
try dbQueue.read { db
|
||||
let persistedPlayer = try PersistedPlayer.find(db, id: 1)
|
||||
persistedPlayer.creationDate // not optional
|
||||
persistedPlayer.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 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
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -23,7 +23,7 @@ try dbQueue.write { db in
|
||||
}
|
||||
```
|
||||
|
||||
Build prepared ``Statement`` and lazily iterate fetched rows with an efficient and fast ``DatabaseCursor``:
|
||||
Build a prepared ``Statement`` and lazily iterate a ``DatabaseCursor`` of ``Row``:
|
||||
|
||||
```swift
|
||||
try dbQueue.read { db in
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
# Transactions and Savepoints
|
||||
|
||||
## Transactions and Safety
|
||||
|
||||
**A transaction is a fundamental tool of SQLite** that guarantees [data consistency](https://www.sqlite.org/transactional.html) as well as [proper isolation](https://sqlite.org/isolation.html) between application threads and database connections. It is at the core of GRDB <doc:Concurrency> guarantees.
|
||||
|
||||
To profit from database transactions, all you have to do is group related database statements in a single database access method such as ``DatabaseWriter/write(_:)-76inz`` or ``DatabaseReader/read(_:)-3806d``:
|
||||
|
||||
```swift
|
||||
// BEGIN TRANSACTION
|
||||
// INSERT INTO credit ...
|
||||
// INSERT INTO debit ...
|
||||
// COMMIT
|
||||
try dbQueue.write { db in
|
||||
try Credit(destinationAccount, amount).insert(db)
|
||||
try Debit(sourceAccount, amount).insert(db)
|
||||
}
|
||||
|
||||
// BEGIN TRANSACTION
|
||||
// SELECT * FROM credit
|
||||
// SELECT * FROM debit
|
||||
// COMMIT
|
||||
let (credits, debits) = try dbQueue.read { db in
|
||||
let credits = try Credit.fetchAll(db)
|
||||
let debits = try Debit.fetchAll(db)
|
||||
return (credits, debits)
|
||||
}
|
||||
```
|
||||
|
||||
In the following sections we'll explore how you can avoid transactions, and how to perform explicit transactions and savepoints.
|
||||
|
||||
## Database Accesses without Transactions
|
||||
|
||||
When needed, you can write outside of any transaction with ``DatabaseWriter/writeWithoutTransaction(_:)-4qh1w`` (also named `inDatabase(_:)`, for `DatabaseQueue`):
|
||||
|
||||
```swift
|
||||
// INSERT INTO credit ...
|
||||
// INSERT INTO debit ...
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
try Credit(destinationAccount, amount).insert(db)
|
||||
try Debit(sourceAccount, amount).insert(db)
|
||||
}
|
||||
```
|
||||
|
||||
For reads, use ``DatabaseReader/unsafeRead(_:)-5i7tf``:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM credit
|
||||
// SELECT * FROM debit
|
||||
let (credits, debits) = try dbPool.unsafeRead { db in
|
||||
let credits = try Credit.fetchAll(db)
|
||||
let debits = try Debit.fetchAll(db)
|
||||
return (credits, debits)
|
||||
}
|
||||
```
|
||||
|
||||
Those method names, `writeWithoutTransaction` and `unsafeRead`, are longer and "scarier" than the regular `write` and `read` in order to draw your attention to the dangers of those unisolated accesses.
|
||||
|
||||
In our credit/debit example, a credit may be successfully inserted, but the debit insertion may fail, ending up with unbalanced accounts (oops).
|
||||
|
||||
```swift
|
||||
// UNSAFE DATABASE INTEGRITY
|
||||
try dbQueue.writeWithoutTransaction { db in // or dbPool.writeWithoutTransaction
|
||||
try Credit(destinationAccount, amount).insert(db)
|
||||
// 😬 May fail after credit was successfully written to disk:
|
||||
try Debit(sourceAccount, amount).insert(db)
|
||||
}
|
||||
```
|
||||
|
||||
Transactions avoid this kind of bug.
|
||||
|
||||
``DatabasePool`` concurrent reads can see an inconsistent state of the database:
|
||||
|
||||
```swift
|
||||
// UNSAFE CONCURRENCY
|
||||
try dbPool.writeWithoutTransaction { db in
|
||||
try Credit(destinationAccount, amount).insert(db)
|
||||
// <- 😬 Here a concurrent read sees a partial db update (unbalanced accounts)
|
||||
try Debit(sourceAccount, amount).insert(db)
|
||||
}
|
||||
```
|
||||
|
||||
Transactions avoid this kind of bug, too.
|
||||
|
||||
Finally, reads performed outside of any transaction are not isolated from concurrent writes. It is possible to see unbalanced accounts, even though the invariant is never broken on disk:
|
||||
|
||||
```swift
|
||||
// UNSAFE CONCURRENCY
|
||||
let (credits, debits) = try dbPool.unsafeRead { db in
|
||||
let credits = try Credit.fetchAll(db)
|
||||
// <- 😬 Here a concurrent write can modify the balance before debits are fetched
|
||||
let debits = try Debit.fetchAll(db)
|
||||
return (credits, debits)
|
||||
}
|
||||
```
|
||||
|
||||
Yes, transactions also avoid this kind of bug.
|
||||
|
||||
## Explicit Transactions
|
||||
|
||||
To open explicit transactions, use `inTransaction()` or `writeInTransaction()`:
|
||||
|
||||
```swift
|
||||
// BEGIN TRANSACTION
|
||||
// INSERT INTO credit ...
|
||||
// INSERT INTO debit ...
|
||||
// COMMIT
|
||||
try dbQueue.inTransaction { db in // or dbPool.writeInTransaction
|
||||
try Credit(destinationAccount, amount).insert(db)
|
||||
try Debit(sourceAccount, amount).insert(db)
|
||||
return .commit
|
||||
}
|
||||
|
||||
// BEGIN TRANSACTION
|
||||
// INSERT INTO credit ...
|
||||
// INSERT INTO debit ...
|
||||
// COMMIT
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
try db.inTransaction {
|
||||
try Credit(destinationAccount, amount).insert(db)
|
||||
try Debit(sourceAccount, amount).insert(db)
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If an error is thrown from the transaction block, the transaction is rollbacked and the error is rethrown by the transaction method. If the transaction closure returns `.rollback` instead of `.commit`, the transaction is also rollbacked, but no error is thrown.
|
||||
|
||||
Full manual transaction management is also possible:
|
||||
|
||||
```swift
|
||||
try dbQueue.writeWithoutTransaction { db
|
||||
try db.beginTransaction()
|
||||
...
|
||||
try db.commit()
|
||||
|
||||
try db.execute(sql: "BEGIN TRANSACTION")
|
||||
...
|
||||
try db.execute(sql: "ROLLBACK")
|
||||
}
|
||||
```
|
||||
|
||||
Transactions can't be left opened unless the ``Configuration/allowsUnsafeTransactions`` configuration flag is set:
|
||||
|
||||
```swift
|
||||
// fatal error: A transaction has been left opened at the end of a database access
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
try db.execute(sql: "BEGIN TRANSACTION")
|
||||
// <- no commit or rollback
|
||||
}
|
||||
```
|
||||
|
||||
It is possible to ask if a transaction is currently opened:
|
||||
|
||||
```swift
|
||||
func myCriticalMethod(_ db: Database) throws {
|
||||
precondition(db.isInsideTransaction, "This method requires a transaction")
|
||||
try ...
|
||||
}
|
||||
```
|
||||
|
||||
Yet, there is a better option than checking for transactions. Critical database sections should use savepoints, described below:
|
||||
|
||||
```swift
|
||||
func myCriticalMethod(_ db: Database) throws {
|
||||
try db.inSavepoint {
|
||||
// Here the database is guaranteed to be inside a transaction.
|
||||
try ...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Savepoints
|
||||
|
||||
**Statements grouped in a savepoint can be rollbacked without invalidating a whole transaction:**
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// Makes sure both inserts succeed, or none:
|
||||
try db.inSavepoint {
|
||||
try Credit(destinationAccount, amount).insert(db)
|
||||
try Debit(sourceAccount, amount).insert(db)
|
||||
return .commit
|
||||
}
|
||||
|
||||
// Other savepoints, etc...
|
||||
}
|
||||
```
|
||||
|
||||
If an error is thrown from the savepoint block, the savepoint is rollbacked and the error is rethrown by the `inSavepoint` method. If the savepoint closure returns `.rollback` instead of `.commit`, the savepoint is also rollbacked, but no error is thrown.
|
||||
|
||||
**Unlike transactions, savepoints can be nested.** They implicitly open a transaction if no one was opened when the savepoint begins. As such, they behave just like nested transactions. Yet the database changes are only written to disk when the outermost transaction is committed:
|
||||
|
||||
```swift
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
try db.inSavepoint {
|
||||
...
|
||||
try db.inSavepoint {
|
||||
...
|
||||
return .commit
|
||||
}
|
||||
...
|
||||
return .commit // Writes changes to disk
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
SQLite savepoints are more than nested transactions, though. For advanced uses, use [SQLite savepoint documentation](https://www.sqlite.org/lang_savepoint.html).
|
||||
|
||||
|
||||
## Transaction Kinds
|
||||
|
||||
SQLite supports [three kinds of transactions](https://www.sqlite.org/lang_transaction.html): deferred (the default), immediate, and exclusive.
|
||||
|
||||
The transaction kind can be chosen for individual transaction:
|
||||
|
||||
```swift
|
||||
let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
|
||||
|
||||
// BEGIN EXCLUSIVE TRANSACTION ...
|
||||
try dbQueue.inTransaction(.exclusive) { db in ... }
|
||||
```
|
||||
|
||||
It is also possible to configure the ``Configuration/defaultTransactionKind``:
|
||||
|
||||
```swift
|
||||
var config = Configuration()
|
||||
config.defaultTransactionKind = .immediate
|
||||
|
||||
let dbQueue = try DatabaseQueue(
|
||||
path: "/path/to/database.sqlite",
|
||||
configuration: config)
|
||||
|
||||
// BEGIN IMMEDIATE TRANSACTION ...
|
||||
try dbQueue.write { db in ... }
|
||||
|
||||
// BEGIN IMMEDIATE TRANSACTION ...
|
||||
try dbQueue.inTransaction { db in ... }
|
||||
```
|
||||
+18
-13
@@ -1,7 +1,14 @@
|
||||
/// The virtual table module for the FTS3 full-text engine.
|
||||
///
|
||||
/// To create FTS3 tables, use the ``Database`` method
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)``.
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE VIRTUAL TABLE document USING fts3(content)
|
||||
/// try db.create(virtualTable: "document", using: FTS3()) { t in
|
||||
/// t.column("content")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts3.html>
|
||||
///
|
||||
@@ -23,26 +30,24 @@
|
||||
public struct FTS3 {
|
||||
/// Options for Latin script characters.
|
||||
public enum Diacritics {
|
||||
/// Do not remove diacritics from Latin script characters.
|
||||
/// Do not remove diacritics from Latin script characters. This option
|
||||
/// matches the `remove_diacritics=0` tokenizer argument.
|
||||
///
|
||||
/// This option matches the `remove_diacritics=0` tokenizer argument.
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts3.html#tokenizer>
|
||||
case keep
|
||||
|
||||
/// Remove diacritics from Latin script characters.
|
||||
///
|
||||
/// This option matches the `remove_diacritics=1` tokenizer argument.
|
||||
/// Remove diacritics from Latin script characters. This option matches
|
||||
/// the `remove_diacritics=1` tokenizer argument.
|
||||
case removeLegacy
|
||||
|
||||
#if GRDBCUSTOMSQLITE
|
||||
/// Remove diacritics from Latin script characters.
|
||||
///
|
||||
/// This option matches the `remove_diacritics=2` tokenizer argument.
|
||||
/// Remove diacritics from Latin script characters. This option matches
|
||||
/// the `remove_diacritics=2` tokenizer argument.
|
||||
case remove
|
||||
#elseif !GRDBCIPHER
|
||||
/// Remove diacritics from Latin script characters.
|
||||
///
|
||||
/// This option matches the `remove_diacritics=2` tokenizer argument.
|
||||
@available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) // SQLite 3.27+
|
||||
/// Remove diacritics from Latin script characters. This option matches
|
||||
/// the `remove_diacritics=2` tokenizer argument.
|
||||
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.27+
|
||||
case remove
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
/// An ``FTS3`` tokenizer.
|
||||
/// The descriptor for an ``FTS3`` tokenizer.
|
||||
///
|
||||
/// `FTS3TokenizerDescriptor` can be used in both ``FTS3`` and ``FTS4`` tables.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// db.create(virtualTable: "book", using: FTS4()) { t in
|
||||
/// try db.create(virtualTable: "book", using: FTS4()) { t in
|
||||
/// t.tokenizer = .simple // FTS3TokenizerDescriptor
|
||||
/// }
|
||||
/// ```
|
||||
@@ -14,7 +14,7 @@
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating Tokenizers
|
||||
/// ### Creating Tokenizer Descriptors
|
||||
///
|
||||
/// - ``porter``
|
||||
/// - ``simple``
|
||||
@@ -34,7 +34,7 @@ public struct FTS3TokenizerDescriptor {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// db.create(virtualTable: "book", using: FTS4()) { t in
|
||||
/// try db.create(virtualTable: "book", using: FTS4()) { t in
|
||||
/// t.tokenizer = .simple
|
||||
/// }
|
||||
/// ```
|
||||
@@ -47,7 +47,7 @@ public struct FTS3TokenizerDescriptor {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// db.create(virtualTable: "book", using: FTS4()) { t in
|
||||
/// try db.create(virtualTable: "book", using: FTS4()) { t in
|
||||
/// t.tokenizer = .porter
|
||||
/// }
|
||||
/// ```
|
||||
@@ -60,7 +60,7 @@ public struct FTS3TokenizerDescriptor {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// db.create(virtualTable: "book", using: FTS4()) { t in
|
||||
/// try db.create(virtualTable: "book", using: FTS4()) { t in
|
||||
/// t.tokenizer = .unicode61()
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
+11
-4
@@ -1,7 +1,14 @@
|
||||
/// The virtual table module for the FTS4 full-text engine.
|
||||
///
|
||||
/// To create FTS4 tables, use the ``Database`` method
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)``.
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE VIRTUAL TABLE document USING fts4(content)
|
||||
/// try db.create(virtualTable: "document", using: FTS4()) { t in
|
||||
/// t.column("content")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts3.html>
|
||||
///
|
||||
@@ -62,7 +69,7 @@ extension FTS4: VirtualTableModule {
|
||||
|
||||
switch definition.contentMode {
|
||||
case .raw(let content):
|
||||
if let content = content {
|
||||
if let content {
|
||||
arguments.append("content=\"\(content)\"")
|
||||
}
|
||||
case .synchronized(let contentTable):
|
||||
@@ -234,7 +241,7 @@ public final class FTS4TableDefinition {
|
||||
/// The FTS4 `prefix` option.
|
||||
///
|
||||
/// // CREATE VIRTUAL TABLE document USING FTS4(content, prefix='2 4');
|
||||
/// db.create(virtualTable: "document", using:FTS4()) { t in
|
||||
/// try db.create(virtualTable: "document", using:FTS4()) { t in
|
||||
/// t.prefixes = [2, 4]
|
||||
/// t.column("content")
|
||||
/// }
|
||||
@@ -300,7 +307,7 @@ public final class FTS4TableDefinition {
|
||||
/// try db.dropFTS4SynchronizationTriggers(forTable: "book_ft")
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://sqlite.org/fts5.html#external_content_tables>
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts3.html#_external_content_fts4_tables_>
|
||||
public func synchronize(withTable tableName: String) {
|
||||
contentMode = .synchronized(contentTable: tableName)
|
||||
}
|
||||
|
||||
+225
-129
@@ -1,19 +1,49 @@
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
import Foundation
|
||||
|
||||
/// FTS5 lets you define "fts5" virtual tables.
|
||||
/// The virtual table module for the FTS5 full-text engine.
|
||||
///
|
||||
/// // CREATE VIRTUAL TABLE document USING fts5(content)
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
/// t.column("content")
|
||||
/// }
|
||||
/// To create FTS5 tables, use the ``Database`` method
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
|
||||
///
|
||||
/// See <https://www.sqlite.org/fts5.html>
|
||||
public struct FTS5: VirtualTableModule {
|
||||
/// ```swift
|
||||
/// // CREATE VIRTUAL TABLE document USING fts5(content)
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
/// t.column("content")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### The FTS5 Module
|
||||
///
|
||||
/// - ``init()``
|
||||
/// - ``FTS5TableDefinition``
|
||||
/// - ``FTS5ColumnDefinition``
|
||||
/// - ``FTS5TokenizerDescriptor``
|
||||
///
|
||||
/// ### Full-Text Search Pattern
|
||||
///
|
||||
/// - ``FTS5Pattern``
|
||||
///
|
||||
/// ### FTS5 Tokenizers
|
||||
///
|
||||
/// - ``FTS5Tokenizer``
|
||||
/// - ``FTS5CustomTokenizer``
|
||||
/// - ``FTS5WrapperTokenizer``
|
||||
/// - ``FTS5TokenFlags``
|
||||
/// - ``FTS5Tokenization``
|
||||
///
|
||||
/// ### Low-Level FTS5 Customization
|
||||
///
|
||||
/// - ``api(_:)``
|
||||
public struct FTS5 {
|
||||
/// Options for Latin script characters. Matches the raw "remove_diacritics"
|
||||
/// tokenizer argument.
|
||||
///
|
||||
/// See <https://www.sqlite.org/fts5.html>
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#unicode61_tokenizer>
|
||||
public enum Diacritics {
|
||||
/// Do not remove diacritics from Latin script characters. This
|
||||
/// option matches the raw "remove_diacritics=0" tokenizer argument.
|
||||
@@ -30,20 +60,23 @@ public struct FTS5: VirtualTableModule {
|
||||
/// Remove diacritics from Latin script characters. This
|
||||
/// option matches the raw "remove_diacritics=2" tokenizer argument,
|
||||
/// available from SQLite 3.27.0
|
||||
@available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *)
|
||||
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.27+
|
||||
case remove
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Creates a FTS5 module suitable for the Database
|
||||
/// `create(virtualTable:using:)` method.
|
||||
/// Creates an FTS5 module.
|
||||
///
|
||||
/// // CREATE VIRTUAL TABLE document USING fts5(content)
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
/// t.column("content")
|
||||
/// }
|
||||
/// For example:
|
||||
///
|
||||
/// See <https://www.sqlite.org/fts5.html>
|
||||
/// ```swift
|
||||
/// // CREATE VIRTUAL TABLE document USING fts5(content)
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
/// t.column("content")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See ``Database/create(virtualTable:ifNotExists:using:_:)``
|
||||
public init() { }
|
||||
|
||||
// Support for FTS5Pattern initializers. Don't make public. Users tokenize
|
||||
@@ -71,10 +104,73 @@ public struct FTS5: VirtualTableModule {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - VirtualTableModule Adoption
|
||||
/// 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:
|
||||
//
|
||||
// Starting SQLite 3.20.0+, we need to use the new sqlite3_bind_pointer api.
|
||||
// The previous way to access FTS5 does not work any longer.
|
||||
//
|
||||
// So let's see which SQLite version we are linked against:
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
// GRDB is linked against SQLCipher or a custom SQLite build: SQLite 3.20.0 or more.
|
||||
return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer)
|
||||
#else
|
||||
// GRDB is linked against the system SQLite.
|
||||
if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { // SQLite 3.20+
|
||||
return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer)
|
||||
} else {
|
||||
return api_v1(db)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
private static func api_v1(_ db: Database) -> UnsafePointer<fts5_api> {
|
||||
guard let data = try! Data.fetchOne(db, sql: "SELECT fts5()") else {
|
||||
fatalError("FTS5 is not available")
|
||||
}
|
||||
return data.withUnsafeBytes {
|
||||
$0.bindMemory(to: UnsafePointer<fts5_api>.self).first!
|
||||
}
|
||||
}
|
||||
|
||||
// Technique given by Jordan Rose:
|
||||
// https://forums.swift.org/t/c-interoperability-combinations-of-library-and-os-versions/14029/4
|
||||
private static func api_v2(
|
||||
_ db: Database,
|
||||
// swiftlint:disable:next line_length
|
||||
_ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer<Int8>?, CInt, CUnsignedInt, UnsafeMutablePointer<OpaquePointer?>?, UnsafeMutablePointer<UnsafePointer<Int8>?>?) -> CInt,
|
||||
// swiftlint:disable:next line_length
|
||||
_ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, CInt, UnsafeMutableRawPointer?, UnsafePointer<Int8>?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> CInt)
|
||||
-> UnsafePointer<fts5_api>
|
||||
{
|
||||
var statement: SQLiteStatement? = nil
|
||||
var api: UnsafePointer<fts5_api>? = nil
|
||||
let type: StaticString = "fts5_api_ptr"
|
||||
|
||||
let code = sqlite3_prepare_v3(db.sqliteConnection, "SELECT fts5(?)", -1, 0, &statement, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
fatalError("FTS5 is not available")
|
||||
}
|
||||
defer { sqlite3_finalize(statement) }
|
||||
type.utf8Start.withMemoryRebound(to: Int8.self, capacity: type.utf8CodeUnitCount) { typePointer in
|
||||
_ = sqlite3_bind_pointer(statement, 1, &api, typePointer, nil)
|
||||
}
|
||||
sqlite3_step(statement)
|
||||
guard let api else {
|
||||
fatalError("FTS5 is not available")
|
||||
}
|
||||
return api
|
||||
}
|
||||
}
|
||||
|
||||
extension FTS5: VirtualTableModule {
|
||||
/// The virtual table module name
|
||||
public let moduleName = "fts5"
|
||||
public var moduleName: String { "fts5" }
|
||||
|
||||
/// Reserved; part of the VirtualTableModule protocol.
|
||||
///
|
||||
@@ -114,11 +210,11 @@ public struct FTS5: VirtualTableModule {
|
||||
|
||||
switch definition.contentMode {
|
||||
case let .raw(content, contentRowID):
|
||||
if let content = content {
|
||||
if let content {
|
||||
let quotedContent = try content.sqlExpression.quotedSQL(db)
|
||||
arguments.append("content=\(quotedContent)")
|
||||
}
|
||||
if let contentRowID = contentRowID {
|
||||
if let contentRowID {
|
||||
let quotedContentRowID = try contentRowID.sqlExpression.quotedSQL(db)
|
||||
arguments.append("content_rowid=\(quotedContentRowID)")
|
||||
}
|
||||
@@ -203,82 +299,38 @@ public struct FTS5: VirtualTableModule {
|
||||
try db.execute(sql: "INSERT INTO \(ftsTable)(\(ftsTable)) VALUES('rebuild')")
|
||||
}
|
||||
}
|
||||
|
||||
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:
|
||||
//
|
||||
// Starting SQLite 3.20.0+, we need to use the new sqlite3_bind_pointer api.
|
||||
// The previous way to access FTS5 does not work any longer.
|
||||
//
|
||||
// So let's see which SQLite version we are linked against:
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
// GRDB is linked against SQLCipher or a custom SQLite build: SQLite 3.20.0 or more.
|
||||
return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer)
|
||||
#else
|
||||
// GRDB is linked against the system SQLite.
|
||||
//
|
||||
// Do we use SQLite 3.19.3 (iOS 11.4), or SQLite 3.24.0 (iOS 12.0)?
|
||||
if #available(iOS 12.0, OSX 10.14, tvOS 12.0, watchOS 5.0, *) {
|
||||
// SQLite 3.24.0 or more
|
||||
return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer)
|
||||
} else {
|
||||
// SQLite 3.19.3 or less
|
||||
return api_v1(db)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
private static func api_v1(_ db: Database) -> UnsafePointer<fts5_api> {
|
||||
guard let data = try! Data.fetchOne(db, sql: "SELECT fts5()") else {
|
||||
fatalError("FTS5 is not available")
|
||||
}
|
||||
return data.withUnsafeBytes {
|
||||
$0.bindMemory(to: UnsafePointer<fts5_api>.self).first!
|
||||
}
|
||||
}
|
||||
|
||||
// Technique given by Jordan Rose:
|
||||
// https://forums.swift.org/t/c-interoperability-combinations-of-library-and-os-versions/14029/4
|
||||
private static func api_v2(
|
||||
_ db: Database,
|
||||
// swiftlint:disable:next line_length
|
||||
_ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer<Int8>?, CInt, CUnsignedInt, UnsafeMutablePointer<OpaquePointer?>?, UnsafeMutablePointer<UnsafePointer<Int8>?>?) -> CInt,
|
||||
// swiftlint:disable:next line_length
|
||||
_ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, CInt, UnsafeMutableRawPointer?, UnsafePointer<Int8>?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> CInt)
|
||||
-> UnsafePointer<fts5_api>
|
||||
{
|
||||
var statement: SQLiteStatement? = nil
|
||||
var api: UnsafePointer<fts5_api>? = nil
|
||||
let type: StaticString = "fts5_api_ptr"
|
||||
|
||||
let code = sqlite3_prepare_v3(db.sqliteConnection, "SELECT fts5(?)", -1, 0, &statement, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
fatalError("FTS5 is not available")
|
||||
}
|
||||
defer { sqlite3_finalize(statement) }
|
||||
type.utf8Start.withMemoryRebound(to: Int8.self, capacity: type.utf8CodeUnitCount) { typePointer in
|
||||
_ = sqlite3_bind_pointer(statement, 1, &api, typePointer, nil)
|
||||
}
|
||||
sqlite3_step(statement)
|
||||
guard let api else {
|
||||
fatalError("FTS5 is not available")
|
||||
}
|
||||
return api
|
||||
}
|
||||
}
|
||||
|
||||
/// The FTS5TableDefinition class lets you define columns of a FTS5 virtual table.
|
||||
/// A `FTS5TableDefinition` lets you define the components of an FTS5
|
||||
/// virtual table.
|
||||
///
|
||||
/// You don't create instances of this class. Instead, you use the Database
|
||||
/// `create(virtualTable:using:)` method:
|
||||
/// You don't create instances of this class. Instead, you use the `Database`
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` method:
|
||||
///
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition
|
||||
/// t.column("content")
|
||||
/// }
|
||||
/// ```swift
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition
|
||||
/// t.column("content")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See <https://www.sqlite.org/fts5.html>
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Define Columns
|
||||
///
|
||||
/// - ``column(_:)``
|
||||
///
|
||||
/// ### External Content Tables
|
||||
///
|
||||
/// - ``synchronize(withTable:)``
|
||||
///
|
||||
/// ### FTS5 Options
|
||||
///
|
||||
/// - ``columnSize``
|
||||
/// - ``content``
|
||||
/// - ``contentRowID``
|
||||
/// - ``detail``
|
||||
/// - ``prefixes``
|
||||
/// - ``tokenizer``
|
||||
public final class FTS5TableDefinition {
|
||||
enum ContentMode {
|
||||
case raw(content: String?, contentRowID: String?)
|
||||
@@ -289,25 +341,30 @@ public final class FTS5TableDefinition {
|
||||
fileprivate var columns: [FTS5ColumnDefinition] = []
|
||||
fileprivate var contentMode: ContentMode = .raw(content: nil, contentRowID: nil)
|
||||
|
||||
/// The virtual table tokenizer
|
||||
/// The virtual table tokenizer.
|
||||
///
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
/// t.tokenizer = .porter()
|
||||
/// }
|
||||
/// For example:
|
||||
///
|
||||
/// See <https://www.sqlite.org/fts5.html#fts5_table_creation_and_initialization>
|
||||
/// ```swift
|
||||
/// // CREATE VIRTUAL TABLE "documents" USING fts5(tokenize=porter)
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
/// t.tokenizer = .porter()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#fts5_table_creation_and_initialization>
|
||||
public var tokenizer: FTS5TokenizerDescriptor?
|
||||
|
||||
/// The FTS5 `content` option
|
||||
/// The FTS5 `content` option.
|
||||
///
|
||||
/// When you want the full-text table to be synchronized with the
|
||||
/// content of an external table, prefer the `synchronize(withTable:)`
|
||||
/// method.
|
||||
/// content of an external table, prefer the
|
||||
/// ``synchronize(withTable:)`` method.
|
||||
///
|
||||
/// Setting this property invalidates any synchronization previously
|
||||
/// established with the `synchronize(withTable:)` method.
|
||||
/// established with the ``synchronize(withTable:)`` method.
|
||||
///
|
||||
/// See <https://www.sqlite.org/fts5.html#external_content_and_contentless_tables>
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#external_content_and_contentless_tables>
|
||||
public var content: String? {
|
||||
get {
|
||||
switch contentMode {
|
||||
@@ -330,13 +387,13 @@ public final class FTS5TableDefinition {
|
||||
/// The FTS5 `content_rowid` option
|
||||
///
|
||||
/// When you want the full-text table to be synchronized with the
|
||||
/// content of an external table, prefer the `synchronize(withTable:)`
|
||||
/// method.
|
||||
/// content of an external table, prefer the
|
||||
/// ``synchronize(withTable:)`` method.
|
||||
///
|
||||
/// Setting this property invalidates any synchronization previously
|
||||
/// established with the `synchronize(withTable:)` method.
|
||||
/// established with the ``synchronize(withTable:)`` method.
|
||||
///
|
||||
/// See <https://sqlite.org/fts5.html#external_content_tables>
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#external_content_tables>
|
||||
public var contentRowID: String? {
|
||||
get {
|
||||
switch contentMode {
|
||||
@@ -356,19 +413,19 @@ public final class FTS5TableDefinition {
|
||||
}
|
||||
}
|
||||
|
||||
/// Support for the FTS5 `prefix` option
|
||||
/// The FTS5 `prefix` option.
|
||||
///
|
||||
/// See <https://www.sqlite.org/fts5.html#prefix_indexes>
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#prefix_indexes>
|
||||
public var prefixes: Set<Int>?
|
||||
|
||||
/// Support for the FTS5 `columnsize` option
|
||||
/// The FTS5 `columnsize` option.
|
||||
///
|
||||
/// <https://www.sqlite.org/fts5.html#the_columnsize_option>
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#the_columnsize_option>
|
||||
public var columnSize: Int?
|
||||
|
||||
/// Support for the FTS5 `detail` option
|
||||
/// The FTS5 `detail` option.
|
||||
///
|
||||
/// <https://www.sqlite.org/fts5.html#the_detail_option>
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#the_detail_option>
|
||||
public var detail: String?
|
||||
|
||||
init(configuration: VirtualTableConfiguration) {
|
||||
@@ -377,11 +434,18 @@ public final class FTS5TableDefinition {
|
||||
|
||||
/// Appends a table column.
|
||||
///
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
/// t.column("content")
|
||||
/// }
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE VIRTUAL TABLE document USING fts5(content)
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
/// t.column("content")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter name: the column name.
|
||||
/// - returns: A ``FTS5ColumnDefinition`` that allows you to refine the
|
||||
/// column definition.
|
||||
@discardableResult
|
||||
public func column(_ name: String) -> FTS5ColumnDefinition {
|
||||
let column = FTS5ColumnDefinition(name: name)
|
||||
@@ -396,22 +460,50 @@ public final class FTS5TableDefinition {
|
||||
/// content in the external table. SQL triggers make sure that the
|
||||
/// full-text table is kept up to date with the external table.
|
||||
///
|
||||
/// See <https://sqlite.org/fts5.html#external_content_tables>
|
||||
/// SQLite automatically deletes those triggers when the content
|
||||
/// (not full-text) table is dropped.
|
||||
///
|
||||
/// However, those triggers remain after the full-text table has been
|
||||
/// dropped. Unless they are dropped too, they will prevent future
|
||||
/// insertion, updates, and deletions in the content table, and the creation
|
||||
/// of a new full-text table.
|
||||
///
|
||||
/// To drop those triggers, call the `Database`
|
||||
/// ``Database/dropFTS5SynchronizationTriggers(forTable:)`` method:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create tables
|
||||
/// try db.create(table: "book") { t in
|
||||
/// ...
|
||||
/// }
|
||||
/// try db.create(virtualTable: "book_ft", using: FTS5()) { t in
|
||||
/// t.synchronize(withTable: "book")
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// // Drop full-text table
|
||||
/// try db.drop(table: "book_ft")
|
||||
/// try db.dropFTS5SynchronizationTriggers(forTable: "book_ft")
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://sqlite.org/fts5.html#external_content_tables>
|
||||
public func synchronize(withTable tableName: String) {
|
||||
contentMode = .synchronized(contentTable: tableName)
|
||||
}
|
||||
}
|
||||
|
||||
/// The FTS5ColumnDefinition class lets you refine a column of an FTS5
|
||||
/// virtual table.
|
||||
/// Describes a column in an ``FTS5`` virtual table.
|
||||
///
|
||||
/// You get instances of this class when you create an FTS5 table:
|
||||
/// You get instances of `FTS5ColumnDefinition` when you create an ``FTS5``
|
||||
/// virtual table. For example:
|
||||
///
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
/// t.column("content") // FTS5ColumnDefinition
|
||||
/// }
|
||||
/// ```swift
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
/// t.column("content") // FTS5ColumnDefinition
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See <https://www.sqlite.org/fts5.html>
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html>
|
||||
public final class FTS5ColumnDefinition {
|
||||
fileprivate let name: String
|
||||
fileprivate var isIndexed: Bool
|
||||
@@ -423,14 +515,18 @@ public final class FTS5ColumnDefinition {
|
||||
|
||||
/// Excludes the column from the full-text index.
|
||||
///
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
/// t.column("a")
|
||||
/// t.column("b").notIndexed()
|
||||
/// }
|
||||
/// For example:
|
||||
///
|
||||
/// See <https://www.sqlite.org/fts5.html#the_unindexed_column_option>
|
||||
/// ```swift
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
/// t.column("a")
|
||||
/// t.column("b").notIndexed()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#the_unindexed_column_option>
|
||||
///
|
||||
/// - returns: `self` so that you can further refine the column definition.
|
||||
@discardableResult
|
||||
public func notIndexed() -> Self {
|
||||
self.isIndexed = false
|
||||
@@ -439,7 +535,7 @@ public final class FTS5ColumnDefinition {
|
||||
}
|
||||
|
||||
extension Column {
|
||||
/// The FTS5 rank column
|
||||
/// The ``FTS5`` rank column.
|
||||
public static let rank = Column("rank")
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
|
||||
/// The protocol for custom FTS5 tokenizers.
|
||||
/// A type that implements a custom tokenizer for the ``FTS5`` full-text engine.
|
||||
///
|
||||
/// See [FTS5 Tokenizers](https://github.com/groue/GRDB.swift/blob/master/Documentation/FTS5Tokenizers.md)
|
||||
/// for more information.
|
||||
public protocol FTS5CustomTokenizer: FTS5Tokenizer {
|
||||
/// The name of the tokenizer; should uniquely identify your custom
|
||||
/// tokenizer.
|
||||
/// The name of the tokenizer.
|
||||
///
|
||||
/// The name should uniquely identify the tokenizer: don't use a built-in
|
||||
/// name such as `ascii`, `porter` or `unicode61`.
|
||||
static var name: String { get }
|
||||
|
||||
/// Creates a custom tokenizer.
|
||||
@@ -27,7 +31,7 @@ extension FTS5CustomTokenizer {
|
||||
///
|
||||
/// class MyTokenizer : FTS5CustomTokenizer { ... }
|
||||
///
|
||||
/// db.create(virtualTable: "book", using: FTS5()) { t in
|
||||
/// try db.create(virtualTable: "book", using: FTS5()) { t in
|
||||
/// let tokenizer = MyTokenizer.tokenizerDescriptor(arguments: ["unicode61", "remove_diacritics", "0"])
|
||||
/// t.tokenizer = tokenizer
|
||||
/// }
|
||||
@@ -108,7 +112,7 @@ extension Database {
|
||||
}
|
||||
let constructor = Unmanaged<FTS5TokenizerConstructor>.fromOpaque(constructorPointer).takeUnretainedValue()
|
||||
var arguments: [String] = []
|
||||
if let azArg = azArg {
|
||||
if let azArg {
|
||||
for i in 0..<Int(nArg) {
|
||||
if let cstr = azArg[i] {
|
||||
arguments.append(String(cString: cstr))
|
||||
|
||||
+90
-32
@@ -1,17 +1,40 @@
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
/// A full text pattern for querying FTS5 virtual tables.
|
||||
/// A full text pattern for querying ``FTS5`` virtual tables.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#full_text_query_syntax>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating Raw FTS5 Patterns
|
||||
///
|
||||
/// - ``Database/makeFTS5Pattern(rawPattern:forTable:)``
|
||||
///
|
||||
/// ### Creating FTS5 Patterns from User Input
|
||||
///
|
||||
/// - ``init(matchingAllPrefixesIn:)``
|
||||
/// - ``init(matchingAllTokensIn:)``
|
||||
/// - ``init(matchingAnyTokenIn:)``
|
||||
/// - ``init(matchingPhrase:)``
|
||||
/// - ``init(matchingPrefixPhrase:)``
|
||||
public struct FTS5Pattern {
|
||||
|
||||
/// The raw pattern string. Guaranteed to be a valid FTS5 pattern.
|
||||
/// The raw pattern string.
|
||||
///
|
||||
/// It is guaranteed to be a valid FTS5 pattern.
|
||||
public let rawPattern: String
|
||||
|
||||
/// Creates a pattern that matches any token found in the input string;
|
||||
/// returns nil if no pattern could be built.
|
||||
/// Creates a pattern that matches any token found in the input string.
|
||||
///
|
||||
/// FTS5Pattern(matchingAnyTokenIn: "") // nil
|
||||
/// FTS5Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar
|
||||
/// The result is nil if no pattern could be built.
|
||||
///
|
||||
/// - parameter string: The string to turn into an FTS5 pattern
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// FTS5Pattern(matchingAnyTokenIn: "") // nil
|
||||
/// FTS5Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar
|
||||
/// ```
|
||||
///
|
||||
/// - parameter string: The string to turn into an FTS5 pattern.
|
||||
public init?(matchingAnyTokenIn string: String) {
|
||||
guard let tokens = try? FTS5.tokenize(query: string), !tokens.isEmpty else {
|
||||
return nil
|
||||
@@ -19,13 +42,18 @@ public struct FTS5Pattern {
|
||||
try? self.init(rawPattern: tokens.joined(separator: " OR "))
|
||||
}
|
||||
|
||||
/// Creates a pattern that matches all tokens found in the input string;
|
||||
/// returns nil if no pattern could be built.
|
||||
/// Creates a pattern that matches all tokens found in the input string.
|
||||
///
|
||||
/// FTS5Pattern(matchingAllTokensIn: "") // nil
|
||||
/// FTS5Pattern(matchingAllTokensIn: "foo bar") // foo bar
|
||||
/// The result is nil if no pattern could be built.
|
||||
///
|
||||
/// - parameter string: The string to turn into an FTS5 pattern
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// FTS5Pattern(matchingAllTokensIn: "") // nil
|
||||
/// FTS5Pattern(matchingAllTokensIn: "foo bar") // foo bar
|
||||
/// ```
|
||||
///
|
||||
/// - parameter string: The string to turn into an FTS5 pattern.
|
||||
public init?(matchingAllTokensIn string: String) {
|
||||
guard let tokens = try? FTS5.tokenize(query: string), !tokens.isEmpty else {
|
||||
return nil
|
||||
@@ -34,12 +62,18 @@ public struct FTS5Pattern {
|
||||
}
|
||||
|
||||
/// Creates a pattern that matches all token prefixes found in the input
|
||||
/// string; returns nil if no pattern could be built.
|
||||
/// string.
|
||||
///
|
||||
/// FTS3Pattern(matchingAllTokensIn: "") // nil
|
||||
/// FTS3Pattern(matchingAllTokensIn: "foo bar") // foo* bar*
|
||||
/// The result is nil if no pattern could be built.
|
||||
///
|
||||
/// - parameter string: The string to turn into an FTS3 pattern
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// FTS5Pattern(matchingAllTokensIn: "") // nil
|
||||
/// FTS5Pattern(matchingAllTokensIn: "foo bar") // foo* bar*
|
||||
/// ```
|
||||
///
|
||||
/// - parameter string: The string to turn into an FTS5 pattern.
|
||||
public init?(matchingAllPrefixesIn string: String) {
|
||||
guard let tokens = try? FTS5.tokenize(query: string), !tokens.isEmpty else {
|
||||
return nil
|
||||
@@ -47,13 +81,18 @@ public struct FTS5Pattern {
|
||||
try? self.init(rawPattern: tokens.map { "\($0)*" }.joined(separator: " "))
|
||||
}
|
||||
|
||||
/// Creates a pattern that matches a contiguous string; returns nil if no
|
||||
/// pattern could be built.
|
||||
/// Creates a pattern that matches a contiguous string.
|
||||
///
|
||||
/// FTS5Pattern(matchingPhrase: "") // nil
|
||||
/// FTS5Pattern(matchingPhrase: "foo bar") // "foo bar"
|
||||
/// The result is nil if no pattern could be built.
|
||||
///
|
||||
/// - parameter string: The string to turn into an FTS5 pattern
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// FTS5Pattern(matchingPhrase: "") // nil
|
||||
/// FTS5Pattern(matchingPhrase: "foo bar") // "foo bar"
|
||||
/// ```
|
||||
///
|
||||
/// - parameter string: The string to turn into an FTS5 pattern.
|
||||
public init?(matchingPhrase string: String) {
|
||||
guard let tokens = try? FTS5.tokenize(query: string), !tokens.isEmpty else {
|
||||
return nil
|
||||
@@ -61,14 +100,20 @@ public struct FTS5Pattern {
|
||||
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
|
||||
}
|
||||
|
||||
/// Creates a pattern that matches the prefix of an indexed document;
|
||||
/// returns nil if no pattern could be built.
|
||||
/// Creates a pattern that matches the prefix of an indexed document.
|
||||
///
|
||||
/// FTS5Pattern(matchingPrefixPhrase: "") // nil
|
||||
/// FTS5Pattern(matchingPrefixPhrase: "the word") // ^"the word"
|
||||
/// The result is nil if no pattern could be built.
|
||||
///
|
||||
/// This pattern matches a prefix made of full tokens: "the bat" matches
|
||||
/// "the bat is happy", but not "mind the bat", or "the batcave is dark".
|
||||
/// The returned pattern matches a prefix made of full tokens: "the bat"
|
||||
/// matches "the bat is happy", but not "mind the bat", or "the batcave
|
||||
/// is dark".
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// FTS5Pattern(matchingPrefixPhrase: "") // nil
|
||||
/// FTS5Pattern(matchingPrefixPhrase: "the word") // ^"the word"
|
||||
/// ```
|
||||
///
|
||||
/// - parameter string: The string to turn into an FTS5 pattern
|
||||
public init?(matchingPrefixPhrase string: String) {
|
||||
@@ -113,13 +158,26 @@ extension Database {
|
||||
|
||||
// MARK: - FTS5
|
||||
|
||||
/// Creates a pattern from a raw pattern string; throws DatabaseError on
|
||||
/// invalid syntax.
|
||||
/// Creates an FTS5 pattern from a raw pattern string.
|
||||
///
|
||||
/// The pattern syntax is documented at <https://www.sqlite.org/fts5.html#full_text_query_syntax>
|
||||
/// For example:
|
||||
///
|
||||
/// try db.makeFTS5Pattern(rawPattern: "and", forTable: "document") // OK
|
||||
/// try db.makeFTS5Pattern(rawPattern: "AND", forTable: "document") // malformed MATCH expression: [AND]
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// // OK
|
||||
/// let pattern = try db.makeFTS5Pattern(rawPattern: "and", forTable: "document")
|
||||
///
|
||||
/// // Throws error: malformed MATCH expression: [AND]
|
||||
/// let pattern = try db.makeFTS5Pattern(rawPattern: "AND", forTable: "document")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter rawPattern: A pattern that follows the
|
||||
/// [Full-text Query Syntax](https://www.sqlite.org/fts5.html#full_text_query_syntax).
|
||||
/// - parameter table: The full-text table that the pattern is intended to
|
||||
/// match against.
|
||||
/// - returns: A valid FTS5 pattern.
|
||||
/// - throws: A ``DatabaseError`` if the raw pattern is invalid.
|
||||
public func makeFTS5Pattern(rawPattern: String, forTable table: String) throws -> FTS5Pattern {
|
||||
try FTS5Pattern(rawPattern: rawPattern, allowedColumns: columns(in: table).map(\.name))
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import Foundation
|
||||
|
||||
/// A low-level SQLite function that lets FTS5Tokenizer notify tokens.
|
||||
///
|
||||
/// See FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:)
|
||||
/// See ``FTS5Tokenizer/tokenize(context:tokenization:pText:nText:tokenCallback:)``.
|
||||
public typealias FTS5TokenCallback = @convention(c) (
|
||||
_ context: UnsafeMutableRawPointer?,
|
||||
_ flags: CInt,
|
||||
@@ -15,7 +15,7 @@ public typealias FTS5TokenCallback = @convention(c) (
|
||||
|
||||
/// The reason why FTS5 is requesting tokenization.
|
||||
///
|
||||
/// See <https://www.sqlite.org/fts5.html#custom_tokenizers>
|
||||
/// See the `FTS5_TOKENIZE_*` constants in <https://www.sqlite.org/fts5.html#custom_tokenizers>.
|
||||
public struct FTS5Tokenization: OptionSet {
|
||||
public let rawValue: CInt
|
||||
|
||||
@@ -23,20 +23,42 @@ public struct FTS5Tokenization: OptionSet {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
/// FTS5_TOKENIZE_QUERY
|
||||
/// `FTS5_TOKENIZE_QUERY`
|
||||
public static let query = FTS5Tokenization(rawValue: FTS5_TOKENIZE_QUERY)
|
||||
|
||||
/// FTS5_TOKENIZE_PREFIX
|
||||
/// `FTS5_TOKENIZE_PREFIX`
|
||||
public static let prefix = FTS5Tokenization(rawValue: FTS5_TOKENIZE_PREFIX)
|
||||
|
||||
/// FTS5_TOKENIZE_DOCUMENT
|
||||
/// `FTS5_TOKENIZE_DOCUMENT`
|
||||
public static let document = FTS5Tokenization(rawValue: FTS5_TOKENIZE_DOCUMENT)
|
||||
|
||||
/// FTS5_TOKENIZE_AUX
|
||||
/// `FTS5_TOKENIZE_AUX`
|
||||
public static let aux = FTS5Tokenization(rawValue: FTS5_TOKENIZE_AUX)
|
||||
}
|
||||
|
||||
/// The protocol for FTS5 tokenizers
|
||||
/// A type that implements a tokenizer for the ``FTS5`` full-text engine.
|
||||
///
|
||||
/// You can instantiate tokenizers, including
|
||||
/// [built-in tokenizers](https://www.sqlite.org/fts5.html#tokenizers),
|
||||
/// with the ``Database/makeTokenizer(_:)`` method:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let unicode61 = try db.makeTokenizer(.unicode61()) // FTS5Tokenizer
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See [FTS5 Tokenizers](https://github.com/groue/GRDB.swift/blob/master/Documentation/FTS5Tokenizers.md)
|
||||
/// for more information.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Tokenizing Text
|
||||
///
|
||||
/// - ``tokenize(document:)``
|
||||
/// - ``tokenize(query:)``
|
||||
/// - ``tokenize(context:tokenization:pText:nText:tokenCallback:)``
|
||||
/// - ``FTS5TokenCallback``
|
||||
public protocol FTS5Tokenizer: AnyObject {
|
||||
/// Tokenizes the text described by `pText` and `nText`, and
|
||||
/// notifies found tokens to the `tokenCallback` function.
|
||||
@@ -72,8 +94,10 @@ extension FTS5Tokenizer {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let tokenizer = try db.makeTokenizer(.ascii())
|
||||
/// try tokenizer.tokenize(document: "foo bar") // [("foo", flags), ("bar", flags)]
|
||||
/// ```swift
|
||||
/// let tokenizer = try db.makeTokenizer(.ascii())
|
||||
/// try tokenizer.tokenize(document: "foo bar") // [("foo", flags), ("bar", flags)]
|
||||
/// ```
|
||||
///
|
||||
/// See also `tokenize(query:)`.
|
||||
///
|
||||
@@ -88,8 +112,10 @@ extension FTS5Tokenizer {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let tokenizer = try db.makeTokenizer(.ascii())
|
||||
/// try tokenizer.tokenize(query: "foo bar") // [("foo", flags), ("bar", flags)]
|
||||
/// ```swift
|
||||
/// let tokenizer = try db.makeTokenizer(.ascii())
|
||||
/// try tokenizer.tokenize(query: "foo bar") // [("foo", flags), ("bar", flags)]
|
||||
/// ```
|
||||
///
|
||||
/// See also `tokenize(document:)`.
|
||||
///
|
||||
@@ -210,7 +236,7 @@ extension Database {
|
||||
throw DatabaseError(resultCode: code, message: "failed fts5_tokenizer.xCreate")
|
||||
}
|
||||
|
||||
if let tokenizerPointer = tokenizerPointer {
|
||||
if let tokenizerPointer {
|
||||
self.tokenizerPointer = tokenizerPointer
|
||||
} else {
|
||||
throw DatabaseError(resultCode: code, message: "nil tokenizer")
|
||||
@@ -240,20 +266,27 @@ extension Database {
|
||||
|
||||
/// Creates an FTS5 tokenizer, given its descriptor.
|
||||
///
|
||||
/// let unicode61 = try db.makeTokenizer(.unicode61())
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let unicode61 = try db.makeTokenizer(.unicode61())
|
||||
/// ```
|
||||
///
|
||||
/// You can use this method when you implement a custom wrapper tokenizer
|
||||
/// with ``FTS5WrapperTokenizer``:
|
||||
///
|
||||
/// ```swift
|
||||
/// final class MyTokenizer : FTS5WrapperTokenizer {
|
||||
/// var wrappedTokenizer: FTS5Tokenizer
|
||||
///
|
||||
/// init(db: Database, arguments: [String]) throws {
|
||||
/// wrappedTokenizer = try db.makeTokenizer(.unicode61())
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// It is a programmer error to use the tokenizer outside of a protected
|
||||
/// database queue, or after the database has been closed.
|
||||
///
|
||||
/// Use this method when you implement a custom wrapper tokenizer:
|
||||
///
|
||||
/// final class MyTokenizer : FTS5WrapperTokenizer {
|
||||
/// var wrappedTokenizer: FTS5Tokenizer
|
||||
///
|
||||
/// init(db: Database, arguments: [String]) throws {
|
||||
/// wrappedTokenizer = try db.makeTokenizer(.unicode61())
|
||||
/// }
|
||||
/// }
|
||||
public func makeTokenizer(_ descriptor: FTS5TokenizerDescriptor) throws -> any FTS5Tokenizer {
|
||||
let api = FTS5.api(self)
|
||||
|
||||
|
||||
@@ -1,61 +1,109 @@
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
/// An FTS5 tokenizer, suitable for FTS5 table definitions:
|
||||
/// The descriptor for an ``FTS5`` tokenizer.
|
||||
///
|
||||
/// db.create(virtualTable: "book", using: FTS5()) { t in
|
||||
/// t.tokenizer = .unicode61() // FTS5TokenizerDescriptor
|
||||
/// }
|
||||
/// For example:
|
||||
///
|
||||
/// See <https://www.sqlite.org/fts5.html#tokenizers>
|
||||
/// ```swift
|
||||
/// try db.create(virtualTable: "book", using: FTS5()) { t in
|
||||
/// t.tokenizer = .unicode61() // FTS5TokenizerDescriptor
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#tokenizers>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating Tokenizer Descriptors
|
||||
///
|
||||
/// - ``init(components:)``
|
||||
/// - ``ascii(separators:tokenCharacters:)``
|
||||
/// - ``porter(wrapping:)``
|
||||
/// - ``unicode61(diacritics:categories:separators:tokenCharacters:)``
|
||||
/// - ``FTS5/Diacritics``
|
||||
///
|
||||
/// ### Instantiating Tokenizers
|
||||
///
|
||||
/// - ``Database/makeTokenizer(_:)``
|
||||
public struct FTS5TokenizerDescriptor {
|
||||
/// The tokenizer components
|
||||
/// The tokenizer components.
|
||||
///
|
||||
/// // ["unicode61"]
|
||||
/// FTS5TokenizerDescriptor.unicode61().components
|
||||
/// For example:
|
||||
///
|
||||
/// // ["unicode61", "remove_diacritics", "0"]
|
||||
/// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).components
|
||||
/// ```swift
|
||||
/// // ["unicode61"]
|
||||
/// FTS5TokenizerDescriptor.unicode61().components
|
||||
///
|
||||
/// // ["unicode61", "remove_diacritics", "0"]
|
||||
/// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).components
|
||||
/// ```
|
||||
public let components: [String]
|
||||
|
||||
/// The tokenizer name
|
||||
/// The tokenizer name.
|
||||
///
|
||||
/// // "unicode61"
|
||||
/// FTS5TokenizerDescriptor.unicode61().name
|
||||
/// For example:
|
||||
///
|
||||
/// // "unicode61"
|
||||
/// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).name
|
||||
/// ```swift
|
||||
/// // "unicode61"
|
||||
/// FTS5TokenizerDescriptor.unicode61().name
|
||||
///
|
||||
/// // "unicode61"
|
||||
/// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).name
|
||||
/// ```
|
||||
var name: String { components[0] }
|
||||
|
||||
/// The tokenizer arguments.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // []
|
||||
/// FTS5TokenizerDescriptor.unicode61().components
|
||||
///
|
||||
/// // ["remove_diacritics", "0"]
|
||||
/// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).components
|
||||
/// ```
|
||||
var arguments: [String] {
|
||||
Array(components.suffix(from: 1))
|
||||
}
|
||||
|
||||
/// Creates an FTS5 tokenizer descriptor.
|
||||
///
|
||||
/// db.create(virtualTable: "book", using: FTS5()) { t in
|
||||
/// let tokenizer = FTS5TokenizerDescriptor(components: ["porter", "unicode61", "remove_diacritics", "0"])
|
||||
/// t.tokenizer = tokenizer
|
||||
/// }
|
||||
/// For example:
|
||||
///
|
||||
/// - precondition: Components is not empty
|
||||
/// ```swift
|
||||
/// try db.create(virtualTable: "book", using: FTS5()) { t in
|
||||
/// t.tokenizer = FTS5TokenizerDescriptor(components: [
|
||||
/// "porter",
|
||||
/// "unicode61",
|
||||
/// "remove_diacritics",
|
||||
/// "0"])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - precondition: Components is not empty.
|
||||
public init(components: [String]) {
|
||||
GRDBPrecondition(!components.isEmpty, "FTS5TokenizerDescriptor requires at least one component")
|
||||
assert(!components.isEmpty)
|
||||
self.components = components
|
||||
}
|
||||
|
||||
/// The "ascii" tokenizer
|
||||
/// The "ascii" tokenizer.
|
||||
///
|
||||
/// db.create(virtualTable: "book", using: FTS5()) { t in
|
||||
/// t.tokenizer = .ascii()
|
||||
/// }
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try db.create(virtualTable: "book", using: FTS5()) { t in
|
||||
/// t.tokenizer = .ascii()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#ascii_tokenizer>
|
||||
///
|
||||
/// - parameters:
|
||||
/// - separators: Unless empty (the default), SQLite will consider
|
||||
/// these characters as token separators.
|
||||
/// - tokenCharacters: Unless empty (the default), SQLite will
|
||||
/// consider these characters as token characters.
|
||||
///
|
||||
/// See <https://www.sqlite.org/fts5.html#ascii_tokenizer>
|
||||
public static func ascii(
|
||||
separators: Set<Character> = [],
|
||||
tokenCharacters: Set<Character> = [])
|
||||
@@ -78,30 +126,39 @@ public struct FTS5TokenizerDescriptor {
|
||||
return FTS5TokenizerDescriptor(components: components)
|
||||
}
|
||||
|
||||
/// The "porter" tokenizer
|
||||
/// The "porter" tokenizer.
|
||||
///
|
||||
/// db.create(virtualTable: "book", using: FTS5()) { t in
|
||||
/// t.tokenizer = .porter()
|
||||
/// }
|
||||
/// For example:
|
||||
///
|
||||
/// - parameters:
|
||||
/// - base: An eventual wrapping tokenizer which replaces the
|
||||
// default unicode61() base tokenizer.
|
||||
/// ```swift
|
||||
/// try db.create(virtualTable: "book", using: FTS5()) { t in
|
||||
/// t.tokenizer = .porter()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See <https://www.sqlite.org/fts5.html#porter_tokenizer>
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#porter_tokenizer>
|
||||
///
|
||||
/// - parameter base: An eventual wrapping tokenizer which replaces the
|
||||
/// default unicode61() base tokenizer.
|
||||
public static func porter(wrapping base: FTS5TokenizerDescriptor? = nil) -> FTS5TokenizerDescriptor {
|
||||
if let base = base {
|
||||
if let base {
|
||||
return FTS5TokenizerDescriptor(components: ["porter"] + base.components)
|
||||
} else {
|
||||
return FTS5TokenizerDescriptor(components: ["porter"])
|
||||
}
|
||||
}
|
||||
|
||||
/// An "unicode61" tokenizer
|
||||
/// The "unicode61" tokenizer.
|
||||
///
|
||||
/// db.create(virtualTable: "book", using: FTS5()) { t in
|
||||
/// t.tokenizer = .unicode61()
|
||||
/// }
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try db.create(virtualTable: "book", using: FTS5()) { t in
|
||||
/// t.tokenizer = .unicode61()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#unicode61_tokenizer>
|
||||
///
|
||||
/// - parameters:
|
||||
/// - diacritics: By default SQLite will strip diacritics from
|
||||
@@ -112,8 +169,6 @@ public struct FTS5TokenizerDescriptor {
|
||||
/// these characters as token separators.
|
||||
/// - tokenCharacters: Unless empty (the default), SQLite will
|
||||
/// consider these characters as token characters.
|
||||
///
|
||||
/// See <https://www.sqlite.org/fts5.html#unicode61_tokenizer>
|
||||
public static func unicode61(
|
||||
diacritics: FTS5.Diacritics = .removeLegacy,
|
||||
categories: String = "",
|
||||
|
||||
@@ -3,7 +3,7 @@ import Foundation
|
||||
|
||||
/// Flags that tell SQLite how to register a token.
|
||||
///
|
||||
/// See the `FTS5_TOKEN_*` flags in <https://www.sqlite.org/fts5.html#custom_tokenizers>.
|
||||
/// See the `FTS5_TOKEN_*` constants in <https://www.sqlite.org/fts5.html#custom_tokenizers>.
|
||||
public struct FTS5TokenFlags: OptionSet {
|
||||
public let rawValue: CInt
|
||||
|
||||
@@ -11,7 +11,7 @@ public struct FTS5TokenFlags: OptionSet {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
/// FTS5_TOKEN_COLOCATED
|
||||
/// `FTS5_TOKEN_COLOCATED`
|
||||
public static let colocated = FTS5TokenFlags(rawValue: FTS5_TOKEN_COLOCATED)
|
||||
}
|
||||
|
||||
@@ -20,34 +20,18 @@ public struct FTS5TokenFlags: OptionSet {
|
||||
/// See FTS5WrapperTokenizer.accept(token:flags:tokenCallback:)
|
||||
public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5TokenFlags) throws -> Void
|
||||
|
||||
/// The protocol for custom FTS5 tokenizers that wrap another tokenizer.
|
||||
/// A type that implements a custom tokenizer for the ``FTS5`` full-text engine
|
||||
/// by wrapping another tokenizer.
|
||||
///
|
||||
/// Types that adopt FTS5WrapperTokenizer don't have to implement the
|
||||
/// low-level FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:).
|
||||
/// See [FTS5 Tokenizers](https://github.com/groue/GRDB.swift/blob/master/Documentation/FTS5Tokenizers.md)
|
||||
/// for more information.
|
||||
///
|
||||
/// Instead, they process regular Swift strings.
|
||||
/// ## Topics
|
||||
///
|
||||
/// Here is the implementation for a trivial tokenizer that wraps the
|
||||
/// built-in ascii tokenizer without any custom processing:
|
||||
/// ### Tokenizing Text
|
||||
///
|
||||
/// class TrivialAsciiTokenizer : FTS5WrapperTokenizer {
|
||||
/// static let name = "trivial"
|
||||
/// let wrappedTokenizer: FTS5Tokenizer
|
||||
///
|
||||
/// init(db: Database, arguments: [String]) throws {
|
||||
/// wrappedTokenizer = try db.makeTokenizer(.ascii())
|
||||
/// }
|
||||
///
|
||||
/// func accept(
|
||||
/// token: String,
|
||||
/// flags: FTS5TokenFlags,
|
||||
/// for tokenization: FTS5Tokenization,
|
||||
/// tokenCallback: FTS5WrapperTokenCallback)
|
||||
/// throws
|
||||
/// {
|
||||
/// try tokenCallback(token, flags)
|
||||
/// }
|
||||
/// }
|
||||
/// - ``accept(token:flags:for:tokenCallback:)``
|
||||
/// - ``FTS5WrapperTokenCallback``
|
||||
public protocol FTS5WrapperTokenizer: FTS5CustomTokenizer {
|
||||
/// The wrapped tokenizer
|
||||
var wrappedTokenizer: any FTS5Tokenizer { get }
|
||||
@@ -57,16 +41,17 @@ public protocol FTS5WrapperTokenizer: FTS5CustomTokenizer {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// func accept(
|
||||
/// token: String,
|
||||
/// flags: FTS5TokenFlags,
|
||||
/// for tokenization: FTS5Tokenization,
|
||||
/// tokenCallback: FTS5WrapperTokenCallback)
|
||||
/// throws
|
||||
/// {
|
||||
/// // pass through:
|
||||
/// try tokenCallback(token, flags)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// func accept(
|
||||
/// token: String,
|
||||
/// flags: FTS5TokenFlags,
|
||||
/// for tokenization: FTS5Tokenization,
|
||||
/// tokenCallback: FTS5WrapperTokenCallback
|
||||
/// ) throws {
|
||||
/// // pass through:
|
||||
/// try tokenCallback(token, flags)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When implementing the accept method, there are a two rules
|
||||
/// to observe:
|
||||
@@ -74,8 +59,8 @@ public protocol FTS5WrapperTokenizer: FTS5CustomTokenizer {
|
||||
/// 1. Errors thrown by the tokenCallback function must not be caught.
|
||||
///
|
||||
/// 2. The input `flags` should be given unmodified to the tokenCallback
|
||||
/// function, unless you union it with the .colocated flag when the
|
||||
/// tokenizer produces synonyms (see
|
||||
/// function, unless you union it with the ``FTS5TokenFlags/colocated`` flag
|
||||
/// when the tokenizer produces synonyms (see
|
||||
/// <https://www.sqlite.org/fts5.html#synonym_support>).
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -99,7 +84,6 @@ private struct FTS5WrapperContext {
|
||||
}
|
||||
|
||||
extension FTS5WrapperTokenizer {
|
||||
/// Default implementation
|
||||
public func tokenize(
|
||||
context: UnsafeMutableRawPointer?,
|
||||
tokenization: FTS5Tokenization,
|
||||
|
||||
+3
-3
@@ -119,7 +119,7 @@ extension PersistableRecord {
|
||||
public func performSave(_ db: Database) throws { preconditionFailure() }
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
extension QueryInterfaceRequest where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible {
|
||||
@available(*, unavailable, message: "selectID() has been removed. You may use selectPrimaryKey(as:) instead.")
|
||||
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID> { preconditionFailure() }
|
||||
@@ -144,13 +144,13 @@ extension SelectionRequest {
|
||||
@available(*, unavailable, renamed: "SQLExpression.AssociativeBinaryOperator")
|
||||
public typealias SQLAssociativeBinaryOperator = SQLExpression.AssociativeBinaryOperator
|
||||
|
||||
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible {
|
||||
@available(*, unavailable, message: "selectID() has been removed. You may use selectPrimaryKey(as:) instead.")
|
||||
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID> { preconditionFailure() }
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
|
||||
@available(*, unavailable, message: "selectID() has been removed. You may use selectPrimaryKey(as:) instead.")
|
||||
public static func selectID() -> QueryInterfaceRequest<ID> { preconditionFailure() }
|
||||
|
||||
@@ -490,7 +490,7 @@ extension DatabaseMigrator {
|
||||
/// - parameter writer: A DatabaseWriter.
|
||||
/// where migrations should apply.
|
||||
/// - parameter scheduler: A Combine Scheduler.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func migratePublisher(
|
||||
_ writer: some DatabaseWriter,
|
||||
receiveOn scheduler: some Scheduler = DispatchQueue.main)
|
||||
@@ -508,7 +508,7 @@ extension DatabaseMigrator {
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
extension DatabasePublishers {
|
||||
/// A publisher that migrates a database.
|
||||
///
|
||||
|
||||
@@ -77,7 +77,7 @@ public struct BelongsToAssociation<Origin, Destination> {
|
||||
originIsLeft: true)
|
||||
|
||||
let associationKey: SQLAssociationKey
|
||||
if let key = key {
|
||||
if let key {
|
||||
associationKey = .fixedSingular(key)
|
||||
} else {
|
||||
associationKey = .inflected(destinationTable)
|
||||
|
||||
@@ -77,7 +77,7 @@ public struct HasManyAssociation<Origin, Destination> {
|
||||
originIsLeft: false)
|
||||
|
||||
let associationKey: SQLAssociationKey
|
||||
if let key = key {
|
||||
if let key {
|
||||
associationKey = .fixedPlural(key)
|
||||
} else {
|
||||
associationKey = .inflected(destinationTable)
|
||||
|
||||
@@ -80,7 +80,7 @@ public struct HasOneAssociation<Origin, Destination> {
|
||||
originIsLeft: false)
|
||||
|
||||
let associationKey: SQLAssociationKey
|
||||
if let key = key {
|
||||
if let key {
|
||||
associationKey = .fixedSingular(key)
|
||||
} else {
|
||||
associationKey = .inflected(destinationTable)
|
||||
|
||||
@@ -334,7 +334,7 @@ struct SQLCTE {
|
||||
|
||||
/// The number of columns in the common table expression.
|
||||
func columnCount(_ db: Database) throws -> Int {
|
||||
if let columns = columns {
|
||||
if let columns {
|
||||
// No need to hit the database
|
||||
return columns.count
|
||||
}
|
||||
|
||||
@@ -533,7 +533,7 @@ extension QueryInterfaceRequest {
|
||||
return try SQLQueryGenerator(relation: relation).makeDeleteStatement(db, selection: selection)
|
||||
}
|
||||
|
||||
/// Returns a cursor over the record deleted by a
|
||||
/// Returns a cursor over the records deleted by a
|
||||
/// `DELETE RETURNING` statement.
|
||||
///
|
||||
/// For example:
|
||||
@@ -553,7 +553,7 @@ extension QueryInterfaceRequest {
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A ``RecordCursor`` over deleted records.
|
||||
/// - returns: A ``RecordCursor`` over the deleted records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func deleteAndFetchCursor(_ db: Database)
|
||||
throws -> RecordCursor<RowDecoder>
|
||||
@@ -636,7 +636,7 @@ extension QueryInterfaceRequest {
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
/// - precondition: `selection` is not empty.
|
||||
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
|
||||
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
|
||||
public func deleteAndFetchStatement(
|
||||
_ db: Database,
|
||||
selection: [any SQLSelectable])
|
||||
@@ -646,7 +646,7 @@ extension QueryInterfaceRequest {
|
||||
return try SQLQueryGenerator(relation: relation).makeDeleteStatement(db, selection: selection)
|
||||
}
|
||||
|
||||
/// Returns a cursor over the record deleted by a
|
||||
/// Returns a cursor over the records deleted by a
|
||||
/// `DELETE RETURNING` statement.
|
||||
///
|
||||
/// For example:
|
||||
@@ -666,9 +666,9 @@ extension QueryInterfaceRequest {
|
||||
/// <https://www.sqlite.org/lang_returning.html>.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A ``RecordCursor`` over deleted records.
|
||||
/// - returns: A ``RecordCursor`` over the deleted records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
|
||||
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
|
||||
public func deleteAndFetchCursor(_ db: Database)
|
||||
throws -> RecordCursor<RowDecoder>
|
||||
where RowDecoder: FetchableRecord & TableRecord
|
||||
@@ -696,7 +696,7 @@ extension QueryInterfaceRequest {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of deleted records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
|
||||
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
|
||||
public func deleteAndFetchAll(_ db: Database)
|
||||
throws -> [RowDecoder]
|
||||
where RowDecoder: FetchableRecord & TableRecord
|
||||
@@ -723,7 +723,7 @@ extension QueryInterfaceRequest {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A set of deleted records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
|
||||
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
|
||||
public func deleteAndFetchSet(_ db: Database)
|
||||
throws -> Set<RowDecoder>
|
||||
where RowDecoder: FetchableRecord & TableRecord & Hashable
|
||||
@@ -865,7 +865,7 @@ extension QueryInterfaceRequest {
|
||||
return updateStatement
|
||||
}
|
||||
|
||||
/// Returns a cursor over the record updated by an
|
||||
/// Returns a cursor over the records updated by an
|
||||
/// `UPDATE RETURNING` statement.
|
||||
///
|
||||
/// For example:
|
||||
@@ -995,7 +995,7 @@ extension QueryInterfaceRequest {
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
/// - precondition: `selection` and `assignments` are not empty.
|
||||
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
|
||||
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
|
||||
public func updateAndFetchStatement(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
@@ -1018,7 +1018,7 @@ extension QueryInterfaceRequest {
|
||||
return updateStatement
|
||||
}
|
||||
|
||||
/// Returns a cursor over the record updated by an
|
||||
/// Returns a cursor over the records updated by an
|
||||
/// `UPDATE RETURNING` statement.
|
||||
///
|
||||
/// For example:
|
||||
@@ -1043,7 +1043,7 @@ extension QueryInterfaceRequest {
|
||||
/// - returns: A cursor over the updated records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
/// - precondition: `assignments` is not empty.
|
||||
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
|
||||
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
|
||||
public func updateAndFetchCursor(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
@@ -1081,7 +1081,7 @@ extension QueryInterfaceRequest {
|
||||
/// - returns: An array of updated records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
/// - precondition: `assignments` is not empty.
|
||||
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
|
||||
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
|
||||
public func updateAndFetchAll(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
@@ -1114,7 +1114,7 @@ extension QueryInterfaceRequest {
|
||||
/// - returns: A set of updated records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
/// - precondition: `assignments` is not empty.
|
||||
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
|
||||
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
|
||||
public func updateAndFetchSet(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
@@ -1355,7 +1355,7 @@ private func prefetch(
|
||||
// useless, and we only need to select pivot columns:
|
||||
let originRelation = originRelation
|
||||
.unorderedUnlessLimited() // only preserve ordering in the CTE if limited
|
||||
.removingChildrenForPrefetchedAssociations()
|
||||
.removingPrefetchedAssociations()
|
||||
.selectOnly(leftColumns.map { SQLExpression.column($0).sqlSelection })
|
||||
let originCTE = CommonTableExpression(
|
||||
named: "grdb_base",
|
||||
|
||||
@@ -316,7 +316,8 @@ extension FilteredRequest {
|
||||
/// - ``filter(key:)-2te6v``
|
||||
/// - ``filter(keys:)-6ggt1``
|
||||
/// - ``filter(keys:)-8fbn9``
|
||||
/// - ``matching(_:)``
|
||||
/// - ``matching(_:)-3s3zr``
|
||||
/// - ``matching(_:)-7c1e8``
|
||||
///
|
||||
/// ### The GROUP BY and HAVING Clauses
|
||||
///
|
||||
@@ -570,7 +571,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
extension TableRequest
|
||||
where Self: FilteredRequest,
|
||||
Self: TypedRequest,
|
||||
@@ -1337,7 +1338,8 @@ extension JoinableRequest where Self: SelectionRequest {
|
||||
/// - ``FilteredRequest/filter(literal:)``
|
||||
/// - ``FilteredRequest/filter(sql:arguments:)``
|
||||
/// - ``FilteredRequest/filterWhenConnected(_:)``
|
||||
/// - ``TableRequest/matching(_:)``
|
||||
/// - ``TableRequest/matching(_:)-3s3zr``
|
||||
/// - ``TableRequest/matching(_:)-7c1e8``
|
||||
/// - ``FilteredRequest/none()``
|
||||
///
|
||||
/// ### The GROUP BY and HAVING Clauses
|
||||
|
||||
@@ -9,7 +9,8 @@
|
||||
/// ### Deriving SQL Expressions
|
||||
///
|
||||
/// - ``detached``
|
||||
/// - ``match(_:)``
|
||||
/// - ``match(_:)-727nk``
|
||||
/// - ``match(_:)-1vvo8``
|
||||
///
|
||||
/// ### Creating Column Assignments
|
||||
///
|
||||
|
||||
@@ -42,3 +42,9 @@ struct DatabasePromise<T> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabasePromise: CustomStringConvertible {
|
||||
var description: String {
|
||||
"DatabasePromise<\(T.self)>"
|
||||
}
|
||||
}
|
||||
@@ -120,10 +120,10 @@ public struct _SQLAssociation {
|
||||
let reversedSteps = zip(steps, steps.dropFirst())
|
||||
.map { (step, nextStep) in
|
||||
// Intermediate steps are not selected, and including(all:)
|
||||
// children are useless:
|
||||
// children can't impact the destination relation:
|
||||
let relation = step.relation
|
||||
.selectOnly([])
|
||||
.removingChildrenForPrefetchedAssociations()
|
||||
.removingPrefetchedAssociations()
|
||||
|
||||
// Don't interfere with user-defined keys that could be added later
|
||||
let key = step.key.with {
|
||||
|
||||
Loaded 100 of 213 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user