mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-06 05:28:44 +00:00
Compare commits
303
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 | ||
|
|
7b63ddf542 | ||
|
|
13860219be | ||
|
|
4cbf442cc8 | ||
|
|
2bde3e11bc | ||
|
|
5ab7bfb229 | ||
|
|
520766a74e | ||
|
|
6c16a9a4e5 | ||
|
|
726022d5a5 | ||
|
|
4a4ff9950c | ||
|
|
afc578db7f | ||
|
|
df3bd46346 | ||
|
|
08ec50f44b | ||
|
|
156ed53588 | ||
|
|
f9cfadce78 | ||
|
|
2269a82479 | ||
|
|
8330469ac3 | ||
|
|
72f56a1b03 | ||
|
|
cbd05c9037 | ||
|
|
a27c34e635 | ||
|
|
35019f7a36 | ||
|
|
69e4706549 | ||
|
|
65bd4d90c2 | ||
|
|
7343912ac3 | ||
|
|
409bd3bb26 | ||
|
|
fed4833764 | ||
|
|
e3cc15707a | ||
|
|
5302b98a15 | ||
|
|
ef019bb9da | ||
|
|
35e60f2b97 | ||
|
|
2e2b79a3a9 | ||
|
|
7bd1992e61 | ||
|
|
f8728bbed8 | ||
|
|
f774aa7c07 | ||
|
|
7a9b8093ed | ||
|
|
c7df15faf5 | ||
|
|
f5ebf0de4d | ||
|
|
cd16e921fe | ||
|
|
8b8e480391 | ||
|
|
3074b61cb7 | ||
|
|
d91e6c2db6 | ||
|
|
a0bfbafd9c | ||
|
|
4e4699ebed | ||
|
|
6295f4609e | ||
|
|
e430b4ebd7 | ||
|
|
4ff8928dc4 | ||
|
|
10596e17bf | ||
|
|
392e9e447d | ||
|
|
e8f1e76958 | ||
|
|
131f414a75 | ||
|
|
d4cefc984f | ||
|
|
2dce8d533e | ||
|
|
dc43607921 | ||
|
|
0ba3dff901 | ||
|
|
fcf8ac43b7 | ||
|
|
9b4d76ca37 | ||
|
|
9b663e3bcc | ||
|
|
847386860f | ||
|
|
8a42c11624 | ||
|
|
e4c5cc3451 | ||
|
|
79d4db7827 | ||
|
|
b1770e89b7 | ||
|
|
12d656d3a1 | ||
|
|
0bc49460d7 | ||
|
|
2743ded335 | ||
|
|
e129df15db | ||
|
|
c4c0b1ce90 | ||
|
|
9ac8c0703d | ||
|
|
433ed36a4b | ||
|
|
c23b93d71b | ||
|
|
b8bc8273a9 | ||
|
|
bcb70855d5 | ||
|
|
eaf8dc239a | ||
|
|
6864e6b2fb | ||
|
|
4b21704258 | ||
|
|
a71eb3d662 | ||
|
|
dffe56f8a9 | ||
|
|
4871304c60 | ||
|
|
a6f9b1c4b7 | ||
|
|
cbac0e7286 | ||
|
|
997d6cb677 | ||
|
|
51230834c8 | ||
|
|
638e586dbc | ||
|
|
6dc4d50e00 | ||
|
|
5d50e396c1 | ||
|
|
981d42aed6 | ||
|
|
8ffceb49c8 | ||
|
|
b14ef2112c | ||
|
|
2d31ed4618 | ||
|
|
5e7b604ecd | ||
|
|
90ec3c188b | ||
|
|
1625bc83f8 | ||
|
|
be9740b5f6 | ||
|
|
f914fe73ff | ||
|
|
57b07515c7 | ||
|
|
9d03c1ae61 | ||
|
|
3014ddb00a | ||
|
|
85b2e113b2 | ||
|
|
c5a0598cea | ||
|
|
5242fe10f6 | ||
|
|
71880a9b8e | ||
|
|
14fb1945be | ||
|
|
33cdf6f270 | ||
|
|
ca079cab17 | ||
|
|
0873474a17 | ||
|
|
bfe2450da5 | ||
|
|
19b0b6af3e | ||
|
|
cdf480ef1f | ||
|
|
da3059f0a8 | ||
|
|
754ced7b5e | ||
|
|
fb81ec6792 | ||
|
|
1be868c4b0 | ||
|
|
4dda8d7650 | ||
|
|
16fe4331f2 | ||
|
|
5ff2ad9e71 | ||
|
|
f5259af512 | ||
|
|
2dd2d2db35 | ||
|
|
9fd3e822e5 | ||
|
|
edbfc7749c | ||
|
|
2aa7e3c79f | ||
|
|
3592db997a | ||
|
|
4307f6a680 | ||
|
|
b7b83a965b | ||
|
|
fcfecc5a73 | ||
|
|
39a76ff929 | ||
|
|
aef2d087ae | ||
|
|
0b12e89e62 | ||
|
|
0379947ab1 | ||
|
|
2e5cf546c6 | ||
|
|
0c011b970b | ||
|
|
a08a86cc76 | ||
|
|
29a21302a2 | ||
|
|
13c804d1cc | ||
|
|
811d287bd9 | ||
|
|
1818534513 | ||
|
|
8d316dc969 | ||
|
|
38e7e649c7 | ||
|
|
3df9e8e5c1 | ||
|
|
c98d918bf6 | ||
|
|
c197e2f520 | ||
|
|
13b3f1d741 | ||
|
|
ad011a0974 | ||
|
|
a89dad2554 | ||
|
|
4f4553f4f0 | ||
|
|
9b505bb34b | ||
|
|
6c841bf96e | ||
|
|
76b05369ff | ||
|
|
e79b6a5622 |
No files matched your search
+51
-69
@@ -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,74 +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_13.3.1.app"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_13.2.1.app"
|
||||
runsOn: macOS-11
|
||||
name: "macOS 11, Xcode 13.2.1, Swift 5.5.2"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_13.1.app"
|
||||
runsOn: macOS-11
|
||||
name: "macOS 11, Xcode 13.1, Swift 5.5.1"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_13.0.app"
|
||||
runsOn: macOS-11
|
||||
name: "macOS 11, Xcode 13.0, Swift 5.5.0"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.5.1.app"
|
||||
runsOn: macOS-11
|
||||
name: "macOS 11, Xcode 12.5.1, Swift 5.4"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.4.app"
|
||||
runsOn: macOS-10.15
|
||||
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
|
||||
shell: "/bin/zsh {0}"
|
||||
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
|
||||
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_13.3.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.4.app"
|
||||
runsOn: macOS-10.15
|
||||
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
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_13.3.1.app"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
name: "Xcode 14.1"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.0.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
@@ -99,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_13.3.1.app"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
name: "Xcode 14.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
@@ -115,19 +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_13.3.1.app"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.4.app"
|
||||
runsOn: macOS-10.15
|
||||
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
|
||||
shell: "/bin/zsh {0}"
|
||||
name: "Xcode 14.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
@@ -135,19 +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_13.3.1.app"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.4.app"
|
||||
runsOn: macOS-10.15
|
||||
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
|
||||
shell: "/bin/zsh {0}"
|
||||
name: "Xcode 14.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
@@ -155,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_13.3.1.app"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
name: "Xcode 14.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
|
||||
+1
-2
@@ -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
|
||||
@@ -106,7 +106,6 @@ Podfile.lock
|
||||
|
||||
# SPM
|
||||
.build
|
||||
.swiftpm/
|
||||
GRDB.xcworkspace/xcshareddata/swiftpm
|
||||
#Package.resolved
|
||||
Tests/SPM/Packages
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
version: 1
|
||||
external_links:
|
||||
documentation: "https://github.com/groue/GRDB.swift/blob/master/README.md"
|
||||
builder:
|
||||
configs:
|
||||
- documentation_targets: [GRDB]
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
<FileRef
|
||||
location = "self:">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
@@ -0,0 +1,134 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1410"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "GRDB_GRDBTests"
|
||||
BuildableName = "GRDB_GRDBTests"
|
||||
BlueprintName = "GRDB_GRDBTests"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "GRDB"
|
||||
BuildableName = "GRDB"
|
||||
BlueprintName = "GRDB"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "GRDB-dynamic"
|
||||
BuildableName = "GRDB-dynamic"
|
||||
BlueprintName = "GRDB-dynamic"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "GRDBTests"
|
||||
BuildableName = "GRDBTests"
|
||||
BlueprintName = "GRDBTests"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "CSQLite"
|
||||
BuildableName = "CSQLite"
|
||||
BlueprintName = "CSQLite"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO"
|
||||
parallelizable = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "GRDBTests"
|
||||
BuildableName = "GRDBTests"
|
||||
BlueprintName = "GRDBTests"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "GRDB_GRDBTests"
|
||||
BuildableName = "GRDB_GRDBTests"
|
||||
BlueprintName = "GRDB_GRDBTests"
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -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!
|
||||
|
||||
+141
-26
@@ -7,17 +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)
|
||||
@@ -32,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)
|
||||
@@ -78,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)
|
||||
|
||||
@@ -99,6 +108,112 @@ 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)
|
||||
|
||||
- **New**: [#1299](https://github.com/groue/GRDB.swift/pull/1299) by [@groue](https://github.com/groue): Record.find() convenience methods
|
||||
|
||||
## 6.4.0
|
||||
|
||||
Released November 28, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.3.1...v6.4.0)
|
||||
|
||||
- **New**: [#1293](https://github.com/groue/GRDB.swift/pull/1293) by [@groue](https://github.com/groue): Enable concurrent reads from a WAL snapshot.
|
||||
- **New**: [#1297](https://github.com/groue/GRDB.swift/pull/1297) by [@groue](https://github.com/groue): SPM: expose the CSQLite product.
|
||||
- **New**: `DatabaseReader.configuration.readQoS` and `writeQoS` return the effective quality of service of read-only and write database accesses. This helps application code avoid priority inversion and similar scheduling misuses when needed.
|
||||
- **New**: `DatabaseReader.configuration.maximumReaderCount` returns the effective capacity for concurrent reads, so that application code can adapt when needed.
|
||||
- **New**: `DatabasePool.makeSnapshot()` no longer throws an error when the database is not in the WAL mode. In such case, the returned snapshot prevents all database modifications during its lifetime.
|
||||
- **New**: A new [`DatabaseSnapshotReader`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesnapshotreader) protocol was introduced for types that see an unchanging database content (`DatabaseSnapshot` and the new `DatabaseSnapshotPool`).
|
||||
- **New**: [`Database.registerAccess(to:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/registeraccess(to:)) has `ValueObservation` track a region. This helps building optimized observations of a constant database region with [`ValueObservation.trackingConstantRegion(_:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/trackingconstantregion(_:)).
|
||||
- **New**: Open several connections to the same in-memory database with [`DatabaseQueue(named:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue/init(named:configuration:)).
|
||||
- **New**: [`TableDefinition`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tabledefinition) has new methods for defining primary keys, with automatic NOT NULL constraints. They workaround [an SQLite bug](https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls). Previous techniques for defining primary keys are preserved for backwards compatibility, but their use is not recommended.
|
||||
- **New**: The [Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) documentation article has a brand new "Database Schema Recommendations" section.
|
||||
- **New**: Multiple improvements to the DocC documentation.
|
||||
|
||||
## 6.3.1
|
||||
|
||||
Released November 11, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.3.0...v6.3.1)
|
||||
|
||||
- **New**: DocC documentation is hosted at https://swiftpackageindex.com/groue/GRDB.swift/documentation
|
||||
|
||||
## 6.3.0
|
||||
|
||||
Released November 6, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.2.0...v6.3.0)
|
||||
|
||||
- **New**: [#1291](https://github.com/groue/GRDB.swift/pull/1291) by [@groue](https://github.com/groue): DocC inline documentation
|
||||
- **New**: The `Row.dataNoCopy` methods are deprecated. Use `Row.withUnsafeData` instead.
|
||||
|
||||
## 6.2.0
|
||||
|
||||
Released October 28, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.1.0...v6.2.0)
|
||||
|
||||
- **New**: [#1289](https://github.com/groue/GRDB.swift/pull/1289) by [@arkie](https://github.com/arkie): Add support for passing in categories to the FTS5 unicode61 tokenizer (SQLite 3.25+)
|
||||
- **Fixed**: The `FTS5Tokenizer.tokenize(query:)` method no longer returns incorrect results for certain tokenizer arguments.
|
||||
|
||||
## 6.1.0
|
||||
|
||||
Released October 20, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.0.0...v6.1.0)
|
||||
@@ -3601,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:**
|
||||
|
||||
@@ -5409,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 {
|
||||
@@ -5469,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**
|
||||
|
||||
@@ -5602,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
|
||||
@@ -5645,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
|
||||
@@ -6544,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**
|
||||
|
||||
+3
-3
@@ -15,8 +15,6 @@ How you can Contribute
|
||||
- [xcpretty](https://github.com/xcpretty/xcpretty) (gem)
|
||||
- For contributing code:
|
||||
- [Swiftlint](https://github.com/realm/SwiftLint) (present in the `$PATH` or in `/opt/homebrew/bin/`)
|
||||
- For generating documentation:
|
||||
- [Jazzy](https://github.com/realm/jazzy) (gem)
|
||||
|
||||
2. **Clone the `development` branch on your machine.**
|
||||
|
||||
@@ -69,7 +67,9 @@ How you can Contribute
|
||||
|
||||
7. **Please provide documentation for your changes**
|
||||
|
||||
GRDB documentation is provided as reference (inline doc comments starting with `///`, see [Documentation Comment Syntax](https://github.com/apple/swift/blob/main/docs/DocumentationComments.md)), and guides ([README.md](README.md) and the [Documentation](Documentation) folder).
|
||||
GRDB documentation is provided as a DocC reference, and guides ([README.md](README.md) and the [Documentation](Documentation) folder).
|
||||
|
||||
Please keep the reference and the guides up-to-date. Use Xcode > Product > Build Documentation in order to control the quality of your reference documentation.
|
||||
|
||||
GRDB is "documentation-driven", which means that nothing ships until it is supported by documentation that makes sense. Documentation makes sense when someone who is not you is able to figure out what is the purpose of your contribution, how to use it, and what are its eventual caveats and corner cases. When the documentation is hard to write, or reveals too many caveats, it is the sign that the api needs to be fixed.
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Sharing a Database in an App Group Container
|
||||
============================================
|
||||
|
||||
This guide [has moved](SharingADatabase.md).
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing).
|
||||
@@ -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
|
||||
@@ -511,7 +511,7 @@ When using class names composed of two or more words, the table name should use
|
||||
| Mouse | mouse | `mouse`, `mice`, `maxMouseSize` |
|
||||
| Person | person | `person`, `people`, `personCount` |
|
||||
|
||||
If your application relies on non-English names, GRDB may generate unexpected identifiers. If this happens, please [open an issue](http://github.com/groue/GRDB.swift/issues).
|
||||
If your application relies on non-English names, GRDB may generate unexpected identifiers. If this happens, please [open an issue](https://github.com/groue/GRDB.swift/issues).
|
||||
|
||||
See [The Structure of a Joined Request] for more information.
|
||||
|
||||
@@ -649,7 +649,7 @@ Here is the recommended [migration] for the **[HasOne]** association:
|
||||
```swift
|
||||
migrator.registerMigration("Countries") { db in
|
||||
try db.create(table: "country") { t in
|
||||
t.column("code", .text).primaryKey() // (1)
|
||||
t.primaryKey("code", .text) // (1)
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "demographics") { t in
|
||||
@@ -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:
|
||||
|
||||
@@ -2963,7 +2961,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
[Further Refinements to Associations]: #further-refinements-to-associations
|
||||
[The Types of Associations]: #the-types-of-associations
|
||||
[FetchableRecord]: ../README.md#fetchablerecord-protocols
|
||||
[migration]: Migrations.md
|
||||
[migration]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations
|
||||
[Record]: ../README.md#records
|
||||
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
|
||||
[Associations and the Database Schema]: #associations-and-the-database-schema
|
||||
@@ -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
|
||||
@@ -3008,8 +3006,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
[PersistableRecord]: ../README.md#persistablerecord-protocol
|
||||
[Codable Records]: ../README.md#codable-records
|
||||
[persistence methods]: ../README.md#persistence-methods
|
||||
[database observation tools]: ../README.md#database-changes-observation
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[database observation tools]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
|
||||
[FAQ]: ../README.md#faq-associations
|
||||
[common table expressions]: CommonTableExpressions.md
|
||||
[Common Table Expressions]: CommonTableExpressions.md
|
||||
|
||||
+11
-13
@@ -191,7 +191,7 @@ let newPlayerCount = dbQueue.writePublisher { db -> Int in
|
||||
|
||||
The difference is that the last fetches are performed in the `thenRead` function. This function accepts two arguments: a readonly database connection, and the result of the `updates` function. This allows you to pass information from a function to the other (it is ignored in the sample code above).
|
||||
|
||||
When you use a [database pool], this method applies a scheduling optimization: the `thenRead` function sees the database in the state left by the `updates` function, and yet does not block any concurrent writes. This can reduce database write contention. See [Advanced DatabasePool](Concurrency.md#advanced-databasepool) for more information.
|
||||
When you use a [database pool], this method applies a scheduling optimization: the `thenRead` function sees the database in the state left by the `updates` function, and yet does not block any concurrent writes. This can reduce database write contention.
|
||||
|
||||
When you use a [database queue], the results are guaranteed to be identical, but no scheduling optimization is applied.
|
||||
|
||||
@@ -226,11 +226,11 @@ This publisher has the same behavior as ValueObservation:
|
||||
|
||||
- It notifies an initial value before the eventual changes.
|
||||
- It may coalesce subsequent changes into a single notification.
|
||||
- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](../README.md#valueobservationremoveduplicates) GRDB operator also.
|
||||
- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/removeduplicates()) GRDB operator also.
|
||||
- It only completes when it is cancelled.
|
||||
- By default, it notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously.
|
||||
|
||||
This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservation scheduler](../README.md#valueobservation-scheduling).
|
||||
This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservationScheduler](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservationscheduler).
|
||||
|
||||
For example, the `.immediate` scheduler makes sure the initial value is notified immediately when the publisher is subscribed. It can help your application update the user interface without having to wait for any asynchronous notifications:
|
||||
|
||||
@@ -248,8 +248,6 @@ This publisher has the same behavior as ValueObservation:
|
||||
|
||||
Note that the `.immediate` scheduler requires that the publisher is subscribed from the main thread. It raises a fatal error otherwise.
|
||||
|
||||
See [ValueObservation Scheduling](../README.md#valueobservation-scheduling) for more information.
|
||||
|
||||
|
||||
#### `SharedValueObservation.publisher()`
|
||||
|
||||
@@ -384,23 +382,23 @@ let cancellable = hallOfFamePublisher.sink(
|
||||
[Usage]: #usage
|
||||
[Asynchronous Database Access]: #asynchronous-database-access
|
||||
[Combine]: https://developer.apple.com/documentation/combine
|
||||
[Database Changes Observation]: ../README.md#database-changes-observation
|
||||
[Database Changes Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
|
||||
[Database Observation]: #database-observation
|
||||
[Combine and Data Consistency]: #combine-and-data-consistency
|
||||
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
|
||||
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation
|
||||
[Demo Application]: DemoApps/GRDBCombineDemo/README.md
|
||||
[SQLite]: http://sqlite.org
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[SharedValueObservation]: ../README.md#valueobservation-sharing
|
||||
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
|
||||
[SharedValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/sharedvalueobservation
|
||||
[`DatabaseRegionObservation.publisher(in:)`]: #databaseregionobservationpublisherin
|
||||
[`ValueObservation.publisher(in:scheduling:)`]: #valueobservationpublisherinscheduling
|
||||
[`SharedValueObservation.publisher()`]: #sharedvalueobservationpublisher
|
||||
[`readPublisher(receiveOn:value:)`]: #databasereaderreadpublisherreceiveonvalue
|
||||
[`writePublisher(receiveOn:updates:)`]: #databasewriterwritepublisherreceiveonupdates
|
||||
[`writePublisher(receiveOn:updates:thenRead:)`]: #databasewriterwritepublisherreceiveonupdatesthenread
|
||||
[`migratePublisher(_:receiveOn:)`]: Migrations.md#asynchronous-migrations
|
||||
[`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 snapshot]: Concurrency.md#database-snapshots
|
||||
[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
|
||||
@@ -1,537 +1,4 @@
|
||||
:twisted_rightwards_arrows: Concurrency
|
||||
=======================================
|
||||
|
||||
**GRDB helps your app deal with SQLite concurrency.**
|
||||
|
||||
If your app moves slow database jobs off the main thread, so that the user interface remains responsive, then this guide is for you. In the case of apps that share a database with other processes, such as an iOS app and its extensions, don't miss the dedicated [Sharing a Database] guide after this one.
|
||||
|
||||
**In all cases, and first and foremost, follow the [Concurrency Rules] right from the start.**
|
||||
|
||||
The other chapters cover, with more details, the fundamentals of SQLite concurrency, and how GRDB makes it manageable from your Swift code.
|
||||
|
||||
- [Concurrency Rules]
|
||||
- [Synchronous and Asynchronous Database Accesses]
|
||||
- [Safe and Unsafe Database Accesses]
|
||||
- [Differences between Database Queues and Pools]
|
||||
- [Concurrent Thinking]
|
||||
- [Advanced DatabasePool]
|
||||
- [Database Snapshots]
|
||||
- [Sharing a Database]
|
||||
|
||||
|
||||
## Concurrency Rules
|
||||
|
||||
**The two concurrency rules are strongly recommended practices.** They are all about SQLite, a robust and reliable database that takes great care of your data: don't miss an opportunity to put it on your side!
|
||||
|
||||
<a id="rule-1"></a>:point_up: **[Rule 1](#rule-1): Connect to any database file only once**
|
||||
|
||||
Open one single [DatabaseQueue] or [DatabasePool] per database file, for the whole duration of your use of the database. Not for the duration of _each_ database access, but really for the duration of _all_ database accesses to this file.
|
||||
|
||||
> *Why does this rule exist?* - Since SQLite does not support parallel writes, each [DatabaseQueue] and [DatabasePool] makes sure application threads perform writes one by one, without overlap.
|
||||
>
|
||||
> *Practical advice* - An app that uses a single database will connect only once. A document-based app will connect each time a document is opened, and disconnect when the document is closed. See the [demo apps] in order to see how to setup a UIKit or SwiftUI application for a single database.
|
||||
>
|
||||
> *What if you do not follow this rule?*
|
||||
>
|
||||
> - You will not be able to use the [Database Observation] features.
|
||||
> - You will see SQLite errors with code 5 ([SQLITE_BUSY]).
|
||||
|
||||
<a id="rule-2"></a>:point_up: **[Rule 2](#rule-2): Mind your transactions**
|
||||
|
||||
Database operations that are grouped in an SQLite transaction are guaranteed to be either fully saved on disk, or not at all. Read-only transactions have an interesting property as well: they guarantee a stable and immutable view of the database[^1], and do not see changes performed by eventual concurrent writes. In other words, transactions are the one and single tool that helps you enforce and rely on the important invariants of your database (such as "all credits have a matching debit", or "all books have an author").
|
||||
|
||||
**You are responsible**, in your Swift code, for delimiting transactions. You do so by grouping database accesses inside a pair of `{ db in ... }` brackets:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in /* Inside a transaction */ }
|
||||
try dbQueue.read { db in /* Inside a transaction */ }
|
||||
let observation = ValueObservation.tracking { db in /* Inside a transaction */ }`
|
||||
```
|
||||
|
||||
> *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.
|
||||
>
|
||||
> *Practical advice* - See below a correct example, as well as frequent mistakes you should avoid:
|
||||
>
|
||||
> <details><summary>Sample code</summary>
|
||||
>
|
||||
> In order to insert a money transfer in the database, in a way that enforces the "all credits have a matching debit" invariant, you can write:
|
||||
>
|
||||
> ```swift
|
||||
> // CORRECT: the "all credits have a matching debit" invariant is preserved.
|
||||
> do {
|
||||
> try dbQueue.write { db in
|
||||
> try credit.insert(db)
|
||||
> try debit.insert(db)
|
||||
> }
|
||||
> } catch {
|
||||
> print("An error occurred: \(error)")
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> A frequent mistake is to forget about grouping inside a pair of `{ db in ... }` brackets:
|
||||
>
|
||||
> ```swift
|
||||
> // INCORRECT. Related database operations are not grouped inside
|
||||
> // one transaction. The invariant is not enforced.
|
||||
> do {
|
||||
> try dbQueue.write { db in try credit.insert(db) }
|
||||
> try dbQueue.write { db in try debit.insert(db) }
|
||||
> } catch {
|
||||
> print("An error occurred: \(error)")
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> Another frequent mistake is to catch database errors at the wrong place:
|
||||
>
|
||||
> ```swift
|
||||
> // INCORRECT. Related database operations are not grouped inside
|
||||
> // one transaction, and a failed operation does not prevent
|
||||
> // subsequent operations from being performed. The invariant is
|
||||
> // not enforced.
|
||||
> do {
|
||||
> try dbQueue.write { db in try credit.insert(db) }
|
||||
> } catch {
|
||||
> print("An error occurred: \(error)")
|
||||
> }
|
||||
>
|
||||
> do {
|
||||
> try dbQueue.write { db in try debit.insert(db) }
|
||||
> } catch {
|
||||
> print("An error occurred: \(error)")
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> </details>
|
||||
>
|
||||
> *What if you do not follow this rule?* - You will see broken database invariants, at runtime, and when your apps wakes up after a crash. You may have a hard time fixing this mess.
|
||||
|
||||
|
||||
## Synchronous and Asynchronous Database Accesses
|
||||
|
||||
**You can access the database from any thread, in a synchronous or asynchronous way.**
|
||||
|
||||
:arrow_right: **A sync access blocks the current thread** until the database operations are completed:
|
||||
|
||||
```swift
|
||||
let playerCount = try dbQueue.read { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
|
||||
let newPlayerCount = try dbQueue.write { db -> Int in
|
||||
try Player(id: 12, name: "Arthur").insert(db)
|
||||
return try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
It is a programmer error to perform a sync access from any other database access (this restriction can be lifted: see [Safe and Unsafe Database Accesses]):
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// Fatal Error: Database methods are not reentrant.
|
||||
try dbQueue.write { db in ... }
|
||||
}
|
||||
```
|
||||
|
||||
:twisted_rightwards_arrows: **An async access does not block the current thread.** Instead, it notifies you when the database operations are completed. There are four ways to access the database asynchronously:
|
||||
|
||||
<details>
|
||||
<summary><b>Swift concurrency</b> (async/await)</summary>
|
||||
|
||||
[**:fire: EXPERIMENTAL**](../README.md#what-are-experimental-features)
|
||||
|
||||
```swift
|
||||
let playerCount = try await dbQueue.read { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
|
||||
let newPlayerCount = try await dbQueue.write { db -> Int in
|
||||
try Player(id: 12, name: "Arthur").insert(db)
|
||||
return try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
Note the identical method names: `read`, `write`. The async version is only available in async Swift functions.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Combine publishers</b></summary>
|
||||
|
||||
```swift
|
||||
let playerCountPublisher = dbQueue.readPublisher { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
|
||||
let newPlayerCountPublisher = dbQueue.writePublisher { db -> Int in
|
||||
try Player(id: 12, name: "Arthur").insert(db)
|
||||
return try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
Those publishers do not access the database until they are subscribed. They complete on the main dispatch queue by default. See [GRDB ❤️ Combine].
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>RxSwift observables</b></summary>
|
||||
|
||||
```swift
|
||||
let playerCountObservable = dbQueue.rx.read { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
|
||||
let newPlayerCountObservable = dbQueue.rx.write { db -> Int in
|
||||
try Player(id: 12, name: "Arthur").insert(db)
|
||||
return try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
Those observables do not access the database until they are subscribed. They complete on the main dispatch queue by default. See the companion library [RxGRDB].
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Completion blocks</b></summary>
|
||||
|
||||
```swift
|
||||
dbQueue.asyncRead { (dbResult: Result<Database, Error>) in
|
||||
do {
|
||||
// Maybe read access could not be established
|
||||
let db = try dbResult.get()
|
||||
let playerCount = try Player.fetchCount(db)
|
||||
... // Handle playerCount
|
||||
} catch {
|
||||
... // Handle error
|
||||
}
|
||||
}
|
||||
|
||||
dbQueue.asyncWrite({ (db: Database) -> Int in
|
||||
try Player(id: 12, name: "Arthur").insert(db)
|
||||
return try Player.fetchCount(db)
|
||||
}, completion: { (db: Database, result: Result<Int, Error>) in
|
||||
// Handle write transaction result:
|
||||
switch result {
|
||||
case let .success(newPlayerCount):
|
||||
... // Handle newPlayerCount
|
||||
case let .failure(error):
|
||||
... // Handle error
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
During one async access, all individual database operations grouped inside (fetch, insert, etc.) are synchronous:
|
||||
|
||||
```swift
|
||||
// One asynchronous access...
|
||||
try await dbQueue.write { db in
|
||||
// ... always performs synchronous database operations:
|
||||
try Player(...).insert(db)
|
||||
try Player(...).insert(db)
|
||||
let players = try Player.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
This is true for all async techniques.
|
||||
|
||||
This prevents the database operations from various concurrent accesses from being interleaved, with disastrous consequences. For example, one access must not be able to issue a `COMMIT` statement in the middle of an unfinished concurrent write!
|
||||
|
||||
|
||||
## Safe and Unsafe Database Accesses
|
||||
|
||||
**You will generally use the safe database access methods `read` and `write`.** In this context, "safe" means that a database access is concurrency-friendly, because GRDB provides the following guarantees:
|
||||
|
||||
- <a id="guarantee-serialized-writes"></a>**[Serialized Writes]** - All writes performed by one [DatabaseQueue] or [DatabasePool] instance are serialized. *Why is it important?* - this guarantee prevents [SQLITE_BUSY] errors during concurrent writes.
|
||||
- <a id="guarantee-write-transactions"></a>**[Write Transactions]** - All writes are wrapped in a transaction. *Why is it important?* - concurrent reads can not see partial database updates (even reads performed by other processes).
|
||||
- <a id="guarantee-isolated-reads"></a>**[Isolated Reads]** - All reads are wrapped in a transaction. *Why is it important?* - an isolated read sees a stable and immutable state of the database[^1], and does not see changes performed by eventual concurrent writes (even writes performed by other processes).
|
||||
- <a id="guarantee-forbidden-writes"></a>**[Forbidden Writes]** - Inside a read access, all attempts to write raise an error. *Why is it important?* - this enforces the immutability of the database during a read.
|
||||
- <a id="guarantee-non-reentrancy"></a>**[Non-Reentrancy]** - Database accesses are not reentrant. *Why is it important?* - this reduces the opportunities for deadlocks, and fosters the clear transaction boundaries of the [second concurrency rule](#rule-2).
|
||||
|
||||
Some applications need to relax this safety net, in order to achieve specific SQLite operations. In this case, replace `read` and `write` with one of the methods below:
|
||||
|
||||
- **Write outside of any transaction**
|
||||
(Lifted guarantee: [Write Transactions])
|
||||
|
||||
```swift
|
||||
try dbQueue.writeWithoutTransaction { db in ... }
|
||||
```
|
||||
|
||||
`writeWithoutTransaction` is also available as an `async` function. You can also use `asyncWriteWithoutTransaction`.
|
||||
|
||||
- **Write outside of any transaction, and prevents concurrent reads**
|
||||
(Lifted guarantee: [Write Transactions])
|
||||
|
||||
```swift
|
||||
try dbQueue.barrierWriteWithoutTransaction { db in ... }
|
||||
```
|
||||
|
||||
The barrier write guarantees an exclusive access to the database: the method blocks until all concurrent database accesses are completed, reads and writes, and postpones all other accesses until it completes.
|
||||
|
||||
There is a known limitation: database accesses performed by other processes, and reads performed by [DatabaseSnapshot] are out of scope of this barrier, and can run concurrently with the barrier.
|
||||
|
||||
You will use this method, for example, when you [change the password](../README.md#changing-the-passphrase-of-an-encrypted-database) of an encrypted database.
|
||||
|
||||
`barrierWriteWithoutTransaction` is also available as an `async` function. You can also use `asyncBarrierWriteWithoutTransaction`.
|
||||
|
||||
- **Reentrant write outside of any transaction**
|
||||
(Lifted guarantees: [Write Transactions], [Non-Reentrancy])
|
||||
|
||||
```swift
|
||||
try dbQueue.unsafeReentrantWrite { db in ... }
|
||||
```
|
||||
|
||||
Reentrant writes can be performed from any other database access:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// No fatal error
|
||||
try dbQueue.unsafeReentrantWrite { db in ... }
|
||||
}
|
||||
```
|
||||
|
||||
`unsafeReentrantWrite` has no async version.
|
||||
|
||||
- **Read outside of any transaction**
|
||||
(Lifted guarantees: [Isolated Reads], [Forbidden Writes])
|
||||
|
||||
```swift
|
||||
try dbQueue.unsafeRead { db in ... }
|
||||
```
|
||||
|
||||
`unsafeRead` is also available as an `async` function.
|
||||
|
||||
- **Reentrant read, outside of any transaction**
|
||||
(Lifted guarantees: [Isolated Reads], [Forbidden Writes], [Non-Reentrancy])
|
||||
|
||||
```swift
|
||||
try dbQueue.unsafeReentrantRead { db in ... }
|
||||
```
|
||||
|
||||
Reentrant reads can be performed from any other database access:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// No fatal error
|
||||
try dbQueue.unsafeReentrantRead { db in ... }
|
||||
}
|
||||
```
|
||||
|
||||
`unsafeReentrantRead` has no async version.
|
||||
|
||||
:point_up: **By using one of the methods above, you become responsible of the thread-safety of your application.** Please understand the consequences of lifting each concurrency guarantee. Some guarantees can also be restored at your convenience:
|
||||
|
||||
- The [Write Transactions] and [Isolated Reads] guarantees can be restored at any point, by opening an [explicit transaction](../README.md#transactions-and-savepoints). For example:
|
||||
|
||||
```swift
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
try db.inTransaction {
|
||||
...
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- The [Forbidden Writes] guarantee can only be lifted with [DatabaseQueue]. It can be restored with [`PRAGMA query_only`](https://www.sqlite.org/pragma.html#pragma_query_only).
|
||||
|
||||
|
||||
## Differences between Database Queues and Pools
|
||||
|
||||
Despite the common [guarantees](#safe-and-unsafe-database-accesses) and [rules](#concurrency-rules) shared by database queues and pools, those two database accessors don't have the same behavior.
|
||||
|
||||
[DatabaseQueue] opens a single database connection, and serializes all database accesses, reads, and writes. There is never more than one thread that uses the database. In the image below, we see how three threads can see the database as time passes:
|
||||
|
||||

|
||||
|
||||
[DatabasePool] manages a pool of several database connections, and allows concurrent reads and writes thanks to the [WAL mode](https://www.sqlite.org/wal.html). A database pool serializes all writes (the [Serialized Writes] guarantee). Reads are isolated so that they don't see changes performed by other threads (the [Isolated Reads] guarantee). This gives a very different picture:
|
||||
|
||||

|
||||
|
||||
See how, with database pools, two reads can see different database states at the same time. This may look scary! Please see the next [Concurrent Thinking] chapter below for a relief.
|
||||
|
||||
|
||||
## Concurrent Thinking
|
||||
|
||||
Despite their [differences](#differences-between-database-queues-and-pools), you can write robust code that works equally well with both database queues and pools.
|
||||
|
||||
This allows your app to switch between queues and pools, at your convenience:
|
||||
|
||||
- The [demo applications] share the same database code for the on-disk pool that feeds the app, and the in-memory queue that feeds tests and SwiftUI previews. This makes sure tests and previews run fast, without any temporary file, with the same behavior as the app.
|
||||
- Applications that perform slow write transactions (when saving a lot of data from a remote server, for example) may want to replace their queue with a pool so that the reads that feed their user interface can run in parallel.
|
||||
|
||||
All you need is a little "concurrent thinking", based on those two basic facts:
|
||||
|
||||
- You are sure, when you perform a write access, that you deal with the latest database state on disk. This is enforced by SQLite, which simply can't perform parallel writes, and by GRDB database queues and pools, which make sure [only one thread can write](#guarantee-serialized-writes). As for writes performed by other processes, they can only trigger [SQLITE_BUSY] errors [that you can handle](SharingADatabase.md).
|
||||
|
||||
- Whenever you extract some data from a database access, immediately consider it as _stale_. It is stale, whether you use a database queue or a database pool. It is stale because nothing prevents other application threads or processes from overwriting the value you have just fetched:
|
||||
|
||||
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/Images/TwoCookiesLeft.jpg" width="50%">
|
||||
|
||||
```swift
|
||||
// or dbQueue.write, for that matter
|
||||
let cookieCount = dbPool.read { db in
|
||||
try Cookie.fetchCount(db)
|
||||
}
|
||||
|
||||
// At this point, the number of cookies on disk
|
||||
// may have already changed.
|
||||
print("We have \(cookieCount) cookies left")
|
||||
```
|
||||
|
||||
Does this mean you can't rely on anything? Of course not:
|
||||
|
||||
- If you intend to display the database content on screen, use [ValueObservation]: it always eventually notifies the latest state of the database. You won't display stale values for a long time [^2].
|
||||
|
||||
- As said above, the moment of truth is the next write access!
|
||||
|
||||
|
||||
## Advanced DatabasePool
|
||||
|
||||
[DatabasePool] is very concurrent, since all reads can run in parallel, and can even run during write operations. But writes are still serialized: at any given point in time, there is no more than a single thread that is writing into the database.
|
||||
|
||||
When your application modifies the database, and then reads some value that depends on those modifications, you may want to avoid blocking concurrent writes longer than necessary:
|
||||
|
||||
```swift
|
||||
try dbPool.write { db in
|
||||
// Increment the number of players
|
||||
try Player(...).insert(db)
|
||||
try Player(...).insert(db)
|
||||
|
||||
// Read the number of players. Concurrent writes are blocked :-(
|
||||
let newPlayerCount = try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
:arrow_right: The solution is the `concurrentRead` method. It must be called from within a write access, outside of any transaction. It returns a *future value* which you consume any time later, with the `wait()` method.
|
||||
|
||||
```swift
|
||||
let future: DatabaseFuture<Int> = try dbPool.writeWithoutTransaction { db in
|
||||
// Increment the number of players
|
||||
try db.inTransaction {
|
||||
try Player(...).insert(db)
|
||||
try Player(...).insert(db)
|
||||
return .commit
|
||||
}
|
||||
|
||||
// <- Not in a transaction here
|
||||
let future = dbPool.concurrentRead { db
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
return future
|
||||
}
|
||||
// <- Concurrent writes can be performed :-)
|
||||
|
||||
// Wait and handle newPlayerCount
|
||||
let newPlayerCount = try future.wait()
|
||||
```
|
||||
|
||||
:twisted_rightwards_arrows: The async version of `concurrentRead` is `asyncConcurrentRead`:
|
||||
|
||||
```swift
|
||||
try dbPool.writeWithoutTransaction { db in
|
||||
// Increment the number of players
|
||||
try db.inTransaction {
|
||||
try Player(...).insert(db)
|
||||
try Player(...).insert(db)
|
||||
return .commit
|
||||
}
|
||||
|
||||
// <- Not in a transaction here
|
||||
dbPool.asyncConcurrentRead { dbResult in
|
||||
do {
|
||||
// Maybe read access could not be established
|
||||
let db = try dbResult.get()
|
||||
let newPlayerCount = try Player.fetchCount(db)
|
||||
// Handle newPlayerCount
|
||||
} catch {
|
||||
// Handle error
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`concurrentRead` and `asyncConcurrentRead` block until they can guarantee their closure argument an isolated access to the database, in the exact state left by the last transaction. It then asynchronously executes this closure.
|
||||
|
||||
In the illustration below, the striped band shows the delay needed for the reading thread to acquire isolation. Until then, no other thread can write:
|
||||
|
||||

|
||||
|
||||
[Transaction Observers](../README.md#transactionobserver-protocol) can also use those methods in their `databaseDidCommit` method, in order to process database changes without blocking other threads that want to write into the database.
|
||||
|
||||
|
||||
## Database Snapshots
|
||||
|
||||
**[DatabasePool] can take snapshots.** A database snapshot sees an unchanging database content, as it existed at the moment it was created.
|
||||
|
||||
"Unchanging" means that a snapshot never sees any database modifications during all its lifetime. And yet it doesn't prevent database updates. This "magic" is made possible by SQLite's WAL mode (see [Isolation In SQLite](https://sqlite.org/isolation.html)).
|
||||
|
||||
```swift
|
||||
let snapshot = try dbPool.makeSnapshot()
|
||||
```
|
||||
|
||||
You can create as many snapshots as you need, regardless of the [maximum number of readers](../README.md#database-configuration) in the pool. A snapshot database connection is closed when the snapshot is deinitialized.
|
||||
|
||||
**A snapshot can be used from any thread.** It has the same [synchronous and asynchronous reading methods](#synchronous-and-asynchronous-database-accesses) as database queues and pools:
|
||||
|
||||
```swift
|
||||
let playerCount = try snapshot.read { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
When you want to control the latest committed changes seen by a snapshot, create the snapshot from within a write, outside of any transaction:
|
||||
|
||||
```swift
|
||||
let snapshot1 = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshot in
|
||||
try db.inTransaction {
|
||||
// delete all players
|
||||
try Player.deleteAll()
|
||||
return .commit
|
||||
}
|
||||
|
||||
// <- not in a transaction here
|
||||
return dbPool.makeSnapshot()
|
||||
}
|
||||
// <- Other threads may modify the database here
|
||||
let snapshot2 = try dbPool.makeSnapshot()
|
||||
|
||||
try snapshot1.read { db in
|
||||
// Guaranteed to be zero
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
|
||||
try snapshot2.read { db in
|
||||
// Could be anything
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
> **Note**: snapshots currently serialize all database accesses. In the future, snapshots may allow concurrent reads.
|
||||
|
||||
[^1]: This immutable view of the database is called [snapshot isolation](https://www.sqlite.org/isolation.html).
|
||||
|
||||
[^2]: After the database has been changed on disk, GRDB has to fetch the fresh value, and then hop to the main thread. Only then your screen can be updated.
|
||||
|
||||
[Concurrency Rules]: #concurrency-rules
|
||||
[Synchronous and Asynchronous Database Accesses]: #synchronous-and-asynchronous-database-accesses
|
||||
[Safe and Unsafe Database Accesses]: #safe-and-unsafe-database-accesses
|
||||
[Differences between Database Queues and Pools]: #differences-between-database-queues-and-pools
|
||||
[Concurrent Thinking]: #concurrent-thinking
|
||||
[Advanced DatabasePool]: #advanced-databasepool
|
||||
[Database Snapshots]: #database-snapshots
|
||||
[DatabaseQueue]: ../README.md#database-queues
|
||||
[DatabasePool]: ../README.md#database-pools
|
||||
[DatabaseSnapshot]: #database-snapshots
|
||||
[demo apps]: DemoApps
|
||||
[Database Observation]: ../README.md#database-changes-observation
|
||||
[SQLITE_BUSY]: https://www.sqlite.org/rescode.html#busy
|
||||
[Sharing a Database]: SharingADatabase.md
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[GRDB ❤️ Combine]: Combine.md
|
||||
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
|
||||
[Serialized Writes]: #guarantee-serialized-writes
|
||||
[Write Transactions]: #guarantee-write-transactions
|
||||
[Isolated Reads]: #guarantee-isolated-reads
|
||||
[Forbidden Writes]: #guarantee-forbidden-writes
|
||||
[Non-Reentrancy]: #guarantee-non-reentrancy
|
||||
[demo applications]: DemoApps
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
|
||||
@@ -5,7 +5,7 @@ By default, GRDB uses the version of SQLite that ships with the target operating
|
||||
|
||||
**You can build GRDB with a custom build of [SQLite 3.39.3](https://www.sqlite.org/changes.html).**
|
||||
|
||||
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](../../../#support-for-sqlite-pre-update-hooks).
|
||||
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver).
|
||||
|
||||
GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfalling/SQLiteLib), which uses the same SQLite configuration as the one used by Apple in its operating systems, and lets you add extra compilation options that leverage the features you need.
|
||||
|
||||
@@ -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](../README.md#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,24 +17,24 @@ 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.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md>
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
|
||||
private var migrator: DatabaseMigrator {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
#if DEBUG
|
||||
// Speed up development by nuking the database when migrations change
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md#the-erasedatabaseonschemachange-option
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
#endif
|
||||
|
||||
migrator.registerMigration("createPlayer") { db in
|
||||
// Create a table
|
||||
// See https://github.com/groue/GRDB.swift#create-tables
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema>
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
@@ -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.
|
||||
|
||||
@@ -13,7 +13,7 @@ The topics covered in this demo are:
|
||||
|
||||
- How to setup a database in an iOS app.
|
||||
- How to define a simple [Codable Record](../../../README.md#codable-records).
|
||||
- How to track database changes and animate a SwiftUI List with an async sequence built from [ValueObservation](../../../README.md#valueobservation).
|
||||
- How to track database changes and animate a SwiftUI List with an async sequence built from [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation).
|
||||
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
|
||||
- How to feed SwiftUI previews with a transient database.
|
||||
|
||||
@@ -25,7 +25,7 @@ The topics covered in this demo are:
|
||||
|
||||
- [AppDatabase.swift](GRDBAsyncDemo/AppDatabase.swift)
|
||||
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema.
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasemigrator) in order to setup the database schema.
|
||||
|
||||
- [Persistence.swift](GRDBAsyncDemo/Persistence.swift)
|
||||
|
||||
|
||||
@@ -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,24 +18,24 @@ 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.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md>
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
|
||||
private var migrator: DatabaseMigrator {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
#if DEBUG
|
||||
// Speed up development by nuking the database when migrations change
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md#the-erasedatabaseonschemachange-option
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
#endif
|
||||
|
||||
migrator.registerMigration("createPlayer") { db in
|
||||
// Create a table
|
||||
// See https://github.com/groue/GRDB.swift#create-tables
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema>
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
@@ -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.
|
||||
|
||||
@@ -13,7 +13,7 @@ The topics covered in this demo are:
|
||||
|
||||
- How to setup a database in an iOS app.
|
||||
- How to define a simple [Codable Record](../../../README.md#codable-records).
|
||||
- How to track database changes and animate a SwiftUI List with [ValueObservation](../../../README.md#valueobservation) Combine publishers.
|
||||
- How to track database changes and animate a SwiftUI List with [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) Combine publishers.
|
||||
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
|
||||
- How to feed SwiftUI previews with a transient database.
|
||||
|
||||
@@ -25,7 +25,7 @@ The topics covered in this demo are:
|
||||
|
||||
- [AppDatabase.swift](GRDBCombineDemo/AppDatabase.swift)
|
||||
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema.
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasemigrator) in order to setup the database schema.
|
||||
|
||||
- [Persistence.swift](GRDBCombineDemo/Persistence.swift)
|
||||
|
||||
|
||||
@@ -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,24 +16,24 @@ 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.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md>
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
|
||||
private var migrator: DatabaseMigrator {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
#if DEBUG
|
||||
// Speed up development by nuking the database when migrations change
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md#the-erasedatabaseonschemachange-option
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
#endif
|
||||
|
||||
migrator.registerMigration("createPlayer") { db in
|
||||
// Create a table
|
||||
// See https://github.com/groue/GRDB.swift#create-tables
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema>
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
@@ -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,
|
||||
|
||||
@@ -13,14 +13,14 @@ The topics covered in this demo are:
|
||||
|
||||
- How to setup a database in an iOS app.
|
||||
- How to define a simple [Codable Record](../../../README.md#codable-records).
|
||||
- How to track database changes and animate a table view with [ValueObservation](../../../README.md#valueobservation).
|
||||
- How to track database changes and animate a table view with [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation).
|
||||
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
|
||||
|
||||
**Files of interest:**
|
||||
|
||||
- [AppDatabase.swift](GRDBDemoiOS/AppDatabase.swift)
|
||||
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema, and [ValueObservation](../../../README.md#valueobservation) in order to let the application observe database changes.
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasemigrator) in order to setup the database schema, and [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) in order to let the application observe database changes.
|
||||
|
||||
- [Persistence.swift](GRDBDemoiOS/Persistence.swift)
|
||||
|
||||
|
||||
@@ -2,4 +2,4 @@
|
||||
|
||||
FetchedRecordsController has been removed in GRDB 5.
|
||||
|
||||
The [Database Observation](../README.md#database-changes-observation) chapter describes the other ways to observe the database.
|
||||
See [Database Observation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation) for other ways to observe the database.
|
||||
@@ -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).
|
||||
@@ -304,7 +301,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/6.1/Structs/StatementArguments.html):
|
||||
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statementarguments):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -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.**
|
||||
@@ -587,7 +550,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/6.1/Structs/StatementArguments.html):
|
||||
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statementarguments):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -726,10 +689,7 @@ let books = Book.fetchAll(db, sql: sql, arguments: [pattern])
|
||||
|
||||
**You can define [record](../README.md#records) types around the full-text virtual tables.**
|
||||
|
||||
However these tables don't have any explicit primary key. Instead, they use the [implicit rowid primary key](../README.md#the-implicit-rowid-primary-key): a special hidden column named `rowid`.
|
||||
|
||||
You will have to [expose this hidden column](../README.md#exposing-the-rowid-column) in order to fetch, delete, and update full-text records by primary key.
|
||||
|
||||
The primary key of those tables is the hidden `rowid` column. If you need to fetch, delete, and update full-text records by primary key, you will have to expose this column to the record type. See [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) for more information.
|
||||
|
||||
## Unicode Full-Text Gotchas
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -499,10 +499,10 @@ let publisher = observation
|
||||
This change is innocuous for database boolean values that are `0`, `1`, or `NULL`. However, it is a breaking change for all other database values.
|
||||
|
||||
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
|
||||
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
|
||||
[removeDuplicates]: ../README.md#valueobservationremoveduplicates
|
||||
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
|
||||
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation
|
||||
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
|
||||
[removeDuplicates]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/removeduplicates()
|
||||
[Custom SQL functions]: ../README.md#custom-sql-functions
|
||||
[Batch updates]: ../README.md#update-requests
|
||||
[SQL Interpolation]: SQLInterpolation.md
|
||||
@@ -510,4 +510,4 @@ let publisher = observation
|
||||
[SQLRequest]: ../README.md#custom-requests
|
||||
[QueryInterfaceRequest]: ../README.md#requests
|
||||
[Combine publishers]: Combine.md
|
||||
[Database Observation]: ../README.md#database-changes-observation
|
||||
[Database Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
|
||||
@@ -195,7 +195,7 @@ The record protocols have been refactored. We tried to keep the amount of modifi
|
||||
|
||||
To help you update your applications with persistence callbacks, let's look at two examples.
|
||||
|
||||
First, check the updated [Single-Row Tables](SingleRowTables.md) guide, if your application defines a "singleton record".
|
||||
First, check the updated [Single-Row Tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables) guide, if your application defines a "singleton record".
|
||||
|
||||
Next, let's consider a record that performs some validation before insertion and updates. In GRDB 5, this would look like:
|
||||
|
||||
|
||||
@@ -245,7 +245,7 @@ Let's look at three examples:
|
||||
|
||||
**Singleton Records** are records that store configuration values, user preferences, and generally some global application state. They are backed by a database table that contains a single row.
|
||||
|
||||
The recommended setup for such records is described in the [Single-Row Tables](SingleRowTables.md) guide. Go check it, and come back when you're done!
|
||||
The recommended setup for such records is described in the [Single-Row Tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables) guide. Go check it, and come back when you're done!
|
||||
|
||||
|
||||
## Define Record Requests
|
||||
@@ -804,16 +804,16 @@ Instead, have a look at [Database Observation]:
|
||||
[Divide and Conquer]: https://en.wikipedia.org/wiki/Divide_and_rule
|
||||
[Why Adopt GRDB?]: WhyAdoptGRDB.md
|
||||
[isolation]: https://en.wikipedia.org/wiki/Isolation_(database_systems)
|
||||
[migrations]: Migrations.md
|
||||
[migration]: Migrations.md
|
||||
[migrations]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations
|
||||
[migration]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations
|
||||
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
|
||||
[Concurrency Guide]: Concurrency.md
|
||||
[GRDB concurrency rules]: Concurrency.md#concurrency-rules
|
||||
[Concurrency Guide]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency
|
||||
[GRDB concurrency rules]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency
|
||||
[PersistableRecord]: ../README.md#persistablerecord-protocol
|
||||
[Database Observation]: ../README.md#database-changes-observation
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
|
||||
[TransactionObserver]: ../README.md#transactionobserver-protocol
|
||||
[Database Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
|
||||
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
|
||||
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
|
||||
[TransactionObserver]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver
|
||||
[Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself
|
||||
[Persistable Record Types are Responsible for Their Tables]: #persistable-record-types-are-responsible-for-their-tables
|
||||
[Record Types Hide Intimate Database Details]: #record-types-hide-intimate-database-details
|
||||
@@ -823,7 +823,7 @@ Instead, have a look at [Database Observation]:
|
||||
[How to Design Database Managers]: #how-to-design-database-managers
|
||||
[Observe the Database and Refetch when Needed]: #observe-the-database-and-refetch-when-needed
|
||||
[query interface]: ../README.md#the-query-interface
|
||||
[observe database changes]: ../README.md#database-changes-observation
|
||||
[observe database changes]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
|
||||
[data protection]: ../README.md#data-protection
|
||||
[Embrace Errors]: #embrace-errors
|
||||
[Thread-Safety is also an Application Concern]: #thread-safety-is-also-an-application-concern
|
||||
|
||||
+1
-300
@@ -1,302 +1,3 @@
|
||||
# Migrations
|
||||
|
||||
**Migrations** are a convenient way to alter your database schema over time in a consistent and easy way.
|
||||
|
||||
- [Migrations Overview]
|
||||
- [The `eraseDatabaseOnSchemaChange` Option]
|
||||
- [Advanced Database Schema Changes]
|
||||
- [Foreign Key Checks]
|
||||
- [Asynchronous Migrations]
|
||||
|
||||
|
||||
## Migrations Overview
|
||||
|
||||
Migrations run in order, once and only once. When a user upgrades your application, only non-applied migrations are run.
|
||||
|
||||
Inside each migration, you typically [define and update your database tables](../README.md#database-schema) according to your evolving application needs:
|
||||
|
||||
```swift
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
// 1st migration
|
||||
migrator.registerMigration("v1") { db in
|
||||
try db.create(table: "author") { t in ... }
|
||||
try db.create(table: "book") { t in ... }
|
||||
try db.create(index: ...)
|
||||
}
|
||||
|
||||
// 2nd migration
|
||||
migrator.registerMigration("v2") { db in
|
||||
try db.alter(table: "author") { t in ... }
|
||||
}
|
||||
|
||||
// Migrations for future versions will be inserted here:
|
||||
//
|
||||
// // 3rd migration
|
||||
// migrator.registerMigration("...") { db in
|
||||
// ...
|
||||
// }
|
||||
```
|
||||
|
||||
**Each migration runs in a separate transaction.** Should one throw an error, its transaction is rollbacked, subsequent migrations do not run, and the error is eventually thrown by `migrator.migrate(dbQueue)`.
|
||||
|
||||
**Migrations run with deferred foreign key checks.** This means that eventual foreign key violations are only checked at the end of the migration (and they make the migration fail). See [Foreign Key Checks] below for more information.
|
||||
|
||||
**The memory of applied migrations is stored in the database itself** (in a reserved table).
|
||||
|
||||
You migrate the database up to the latest version with the `migrate(_:)` method:
|
||||
|
||||
```swift
|
||||
try migrator.migrate(dbQueue) // or migrator.migrate(dbPool)
|
||||
```
|
||||
|
||||
Migrate a database up to a specific version (useful for testing):
|
||||
|
||||
```swift
|
||||
try migrator.migrate(dbQueue, upTo: "v2")
|
||||
|
||||
// Migrations can only run forward:
|
||||
try migrator.migrate(dbQueue, upTo: "v2")
|
||||
try migrator.migrate(dbQueue, upTo: "v1")
|
||||
// ^ fatal error: database is already migrated beyond migration "v1"
|
||||
```
|
||||
|
||||
When several versions of your app are deployed in the wild, you may want to perform extra checks:
|
||||
|
||||
```swift
|
||||
try dbQueue.read { db in
|
||||
// Readonly apps may want to check if database lacks expected migrations:
|
||||
if try migrator.hasCompletedMigrations(db) == false {
|
||||
// database too old
|
||||
}
|
||||
|
||||
// All apps may want to check if database contains unknown (future) migrations:
|
||||
if try migrator.hasBeenSuperseded(db) {
|
||||
// database too new
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/6.1/Structs/DatabaseMigrator.html) for more migrator methods.
|
||||
|
||||
|
||||
## The `eraseDatabaseOnSchemaChange` Option
|
||||
|
||||
A DatabaseMigrator can automatically wipe out the full database content, and recreate the whole database from scratch, if it detects that migrations have changed their definition:
|
||||
|
||||
```swift
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
```
|
||||
|
||||
> **Warning**: This option can destroy your precious users' data!
|
||||
|
||||
Setting `eraseDatabaseOnSchemaChange` is useful during application development, as you are still designing migrations, and the schema changes often.
|
||||
|
||||
It is recommended that this option does not ship in the released application:
|
||||
|
||||
```swift
|
||||
var migrator = DatabaseMigrator()
|
||||
#if DEBUG
|
||||
// Speed up development by nuking the database when migrations change
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
#endif
|
||||
```
|
||||
|
||||
The `eraseDatabaseOnSchemaChange` option triggers a recreation of the database if and only if:
|
||||
|
||||
- A migration has been removed, or renamed.
|
||||
- A *schema change* is detected. A schema change is any difference in the `sqlite_master` table, which contains the SQL used to create database tables, indexes, triggers, and views.
|
||||
|
||||
|
||||
## Advanced Database Schema Changes
|
||||
|
||||
If SQLite does not directly support all kinds of schema alterations, you can make arbitrary changes to the schema design of any table using a sequence of operations, as in the example below:
|
||||
|
||||
```swift
|
||||
migrator.registerMigration("Add NOT NULL check on player.name") { db in
|
||||
try db.create(table: "new_player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
try db.execute(sql: "INSERT INTO new_player SELECT * FROM player")
|
||||
try db.drop(table: "player")
|
||||
try db.rename(table: "new_player", to: "player")
|
||||
}
|
||||
```
|
||||
|
||||
This technique is described in SQLite documentation: [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes).
|
||||
|
||||
The detailed sequence of operations is described below, some of them are performed by GRDB, and others by your code:
|
||||
|
||||
1. GRDB: If foreign key constraints are enabled, disable them using PRAGMA foreign_keys=OFF.
|
||||
|
||||
2. GRDB: Start a transaction.
|
||||
|
||||
3. **Your code**: Remember the format of all indexes, triggers, and views associated with table X. This information will be needed in step 8 below. One way to do this is to run a query like the following: `SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'`.
|
||||
|
||||
4. **Your code**: Use `CREATE TABLE` to construct a new table "new_X" that is in the desired revised format of table X. Make sure that the name "new_X" does not collide with any existing table name, of course.
|
||||
|
||||
5. **Your code**: Transfer content from X into new_X using a statement like: `INSERT INTO new_X SELECT ... FROM X`.
|
||||
|
||||
6. **Your code**: Drop the old table X: `DROP TABLE X`.
|
||||
|
||||
7. **Your code**: Change the name of new_X to X using: `ALTER TABLE new_X RENAME TO X`.
|
||||
|
||||
8. **Your code**: Use `CREATE INDEX`, `CREATE TRIGGER`, and `CREATE VIEW` to reconstruct indexes, triggers, and views associated with table X. Perhaps use the old format of the triggers, indexes, and views saved from step 3 above as a guide, making changes as appropriate for the alteration.
|
||||
|
||||
9. **Your code**: If any views refer to table X in a way that is affected by the schema change, then drop those views using `DROP VIEW` and recreate them with whatever changes are necessary to accommodate the schema change using `CREATE VIEW`.
|
||||
|
||||
10. GRDB: If foreign key constraints were originally enabled then run [`PRAGMA foreign_key_check`](https://www.sqlite.org/pragma.html#pragma_foreign_key_check) to verify that the schema change did not break any foreign key constraints.
|
||||
|
||||
11. GRDB: Commit the transaction started in step 2.
|
||||
|
||||
12. GRDB: If foreign keys constraints were originally enabled, reenable them now.
|
||||
|
||||
> **Note**: Take care to follow the procedure above precisely, in the same order, or you might corrupt triggers, views, and foreign key constraints. Have a second look at [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes) if necessary.
|
||||
>
|
||||
> **Note**: By default, all migrations perform, at step 10, a full check of all foreign keys in your database. When your database is big, those checks may have a noticeable impact on migration performances. See [Foreign Key Checks] for a discussion of your ways to avoid this toll.
|
||||
|
||||
|
||||
## Foreign Key Checks
|
||||
|
||||
SQLite makes it [difficult](https://www.sqlite.org/lang_altertable.html) to perform some schema changes, and this creates very undesired churn w.r.t. foreign keys. GRDB makes its best to hide those problems to you, but you might have to deal with them one day, especially if your database becomes *very big*:
|
||||
|
||||
You'll need to read this chapter if you are looking for a mitigation to the time spent by migrations performing foreign key checks. You'll know this by instrumenting your migrations, and looking for the time spent in the `checkForeignKeys` method. See [Advanced Database Schema Changes] right above to know what are those foreign key checks.
|
||||
|
||||
**Your first mitigation technique is immediate foreign key checks.**
|
||||
|
||||
If you register a migration with `.immediate` foreign key checks, the migration will not temporarily disable foreign keys, and won't need to perform a deferred full check of all foreign keys in your database:
|
||||
|
||||
```swift
|
||||
migrator.registerMigration("make it faster please", foreignKeyChecks: .immediate) { db in
|
||||
try db.create(table: ...) // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Such a migration is much faster, and it still guarantees that no foreign key constraint is broken. But it can not run the kind of migrations covered by [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes). In this case, you'll need to use the second mitigation technique:
|
||||
|
||||
**Your second mitigation technique is to disable deferred foreign key checks.**
|
||||
|
||||
You can ask the migrator to stop performing foreign key checks for all newly registered migrations.
|
||||
|
||||
:warning: If you use this technique, your app becomes responsible for preventing foreign key violations from being committed to disk!
|
||||
|
||||
```swift
|
||||
migrator = migrator.disablingDeferredForeignKeyChecks()
|
||||
|
||||
// From now on, migrations are unchecked!
|
||||
migrator.registerMigration("fast but unchecked") { db in ... }
|
||||
```
|
||||
|
||||
In order to prevent foreign key violations from being committed to disk, you can:
|
||||
|
||||
- Run migrations with immediate foreign key check, as long as they do not require the technique described by [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes):
|
||||
|
||||
```swift
|
||||
migrator = migrator.disablingDeferredForeignKeyChecks()
|
||||
migrator.registerMigration("unchecked") { db in ... }
|
||||
migrator.registerMigration("checked", foreignKeyChecks: .immediate) { db in ... }
|
||||
```
|
||||
|
||||
- Perform foreign key checks on some tables only:
|
||||
|
||||
```swift
|
||||
migrator = migrator.disablingDeferredForeignKeyChecks()
|
||||
migrator.registerMigration("partially checked") { db in
|
||||
...
|
||||
|
||||
// Throws an error and stops migrations if there exists a
|
||||
// foreign key violation in the 'player' table.
|
||||
try db.checkForeignKeys(in: "player")
|
||||
}
|
||||
```
|
||||
|
||||
- Perform a full check of foreign keys, eventually:
|
||||
|
||||
```swift
|
||||
try migrator.migrate(dbQueue)
|
||||
|
||||
// Throws an error if there exists any foreign key violation.
|
||||
try dbQueue.read { db in
|
||||
try db.checkForeignKeys()
|
||||
}
|
||||
```
|
||||
|
||||
In order to check for foreign key violations, the `checkForeignKeys()` and `checkForeignKeys(in:)` methods are recommended over the raw use of the [`PRAGMA foreign_key_check`](https://www.sqlite.org/pragma.html#pragma_foreign_key_check). Those methods throw a nicely detailed DatabaseError that contains a lot of debugging information:
|
||||
|
||||
```swift
|
||||
// SQLite error 19: FOREIGN KEY constraint violation - from player(teamId) to team(id),
|
||||
// in [id:1 teamId:2 name:"O'Brien" score:1000]
|
||||
try db.checkForeignKeys()
|
||||
```
|
||||
|
||||
You can also iterate a lazy [cursor](../README.md#cursors) of all individual foreign key violations found in the database:
|
||||
|
||||
```swift
|
||||
let violations = try db.foreignKeyViolations()
|
||||
while let violation = try violations.next() {
|
||||
// The name of the table that contains the `REFERENCES` clause
|
||||
violation.originTable
|
||||
|
||||
// The rowid of the row that contains the invalid `REFERENCES` clause, or
|
||||
// nil if the origin table is a `WITHOUT ROWID` table.
|
||||
violation.originRowID
|
||||
|
||||
// The name of the table that is referred to.
|
||||
violation.destinationTable
|
||||
|
||||
// The id of the specific foreign key constraint that failed. This id
|
||||
// matches `ForeignKeyInfo.id`. See `Database.foreignKeys(on:)` for more
|
||||
// information.
|
||||
violation.foreignKeyId
|
||||
|
||||
// Plain description:
|
||||
// "FOREIGN KEY constraint violation - from player to team, in rowid 1"
|
||||
String(describing: violation)
|
||||
|
||||
// Rich description:
|
||||
// "FOREIGN KEY constraint violation - from player(teamId) to team(id),
|
||||
// in [id:1 teamId:2 name:"O'Brien" score:1000]"
|
||||
try violation.failureDescription(db)
|
||||
|
||||
// Turn violation into a DatabaseError
|
||||
throw violation.databaseError(db)
|
||||
}
|
||||
```
|
||||
|
||||
## Asynchronous Migrations
|
||||
|
||||
`DatabaseMigrator` provides the following ways to migrate a database in an asynchronous way.
|
||||
|
||||
The `asyncMigrate(_:completion:)` method:
|
||||
|
||||
```swift
|
||||
// Completes in a protected dispatch queue that can write in the database
|
||||
migrator.asyncMigrate(dbQueue, completion: { result in
|
||||
switch result {
|
||||
case .failure:
|
||||
// Some error occurred during migrations
|
||||
case let .success(db):
|
||||
// Migrations succeeded
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
The `migratePublisher(_:receiveOn:)` [Combine](https://developer.apple.com/documentation/combine) publisher:
|
||||
|
||||
```swift
|
||||
// DatabasePublishers.Migrate
|
||||
let publisher = migrator.migratePublisher(dbQueue)
|
||||
```
|
||||
|
||||
This publisher completes on the main queue, unless you provide a specific [scheduler](https://developer.apple.com/documentation/combine/scheduler) to the `receiveOn` argument.
|
||||
|
||||
|
||||
|
||||
[Migrations Overview]: #migrations-overview
|
||||
[The `eraseDatabaseOnSchemaChange` Option]: #the-erasedatabaseonschemachange-option
|
||||
[Advanced Database Schema Changes]: #advanced-database-schema-changes
|
||||
[Foreign Key Checks]: #foreign-key-checks
|
||||
[Asynchronous Migrations]: #asynchronous-migrations
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations).
|
||||
@@ -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)")
|
||||
}
|
||||
|
||||
|
||||
@@ -607,8 +607,8 @@ myRequest(Player.select(...).filter(...))
|
||||
[association aggregates]: AssociationsBasics.md#association-aggregates
|
||||
[Column]: #column
|
||||
[ColumnExpression]: #columnexpression
|
||||
[DatabaseRegionConvertible]: #databaseregionconvertible
|
||||
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
|
||||
[DatabaseRegionConvertible]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionconvertible
|
||||
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation
|
||||
[DatabaseValue]: #databasevalue
|
||||
[DatabaseValueConvertible]: #databasevalueconvertible
|
||||
[DerivableRequest]: #derivablerequest
|
||||
|
||||
@@ -13,19 +13,15 @@ To release a new GRDB version:
|
||||
- On https://github.com/groue/sqlcipher.git upgrade, update SQLCipher version in README.md
|
||||
- On https://github.com/swiftlyfalling/SQLiteLib upgrade, update SQLite version in Documentation/CustomSQLiteBuilds.md
|
||||
- Update GRDB version number and release date in:
|
||||
- Makefile
|
||||
- CHANGELOG.md
|
||||
- GRDB.swift.podspec
|
||||
- README.md
|
||||
- Documentation/FullTextSearch.md
|
||||
- Documentation/Migrations.md
|
||||
- Support/Info.plist
|
||||
- Commit and tag
|
||||
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
|
||||
- Push to the master & development branch
|
||||
- `pod trunk push --allow-warnings GRDB.swift.podspec`
|
||||
- `make doc`, and update index.html in the `gh-pages` branch
|
||||
- Update http://github.com/groue/WWDCCompanion
|
||||
- Update https://github.com/groue/WWDCCompanion
|
||||
- Update [performance comparison](https://github.com/groue/GRDB.swift/wiki/Performance):
|
||||
|
||||
`make test_performance | Tests/parsePerformanceTests.rb | Tests/generatePerformanceReport.rb`
|
||||
@@ -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]:
|
||||
|
||||
@@ -1,294 +1,4 @@
|
||||
Sharing a Database
|
||||
==================
|
||||
|
||||
**This guide describes a recommended setup that applies as soon as several processes want to access the same SQLite database.** It complements the [Concurrency](Concurrency.md) guide, that you should read first.
|
||||
|
||||
On iOS for example, you can share database files between multiple processes by storing them in an [App Group Container](https://developer.apple.com/documentation/foundation/nsfilemanager/1412643-containerurlforsecurityapplicati). On macOS as well, several processes may want to open the same database, according to their particular sandboxing contexts.
|
||||
|
||||
Accessing a shared database from several SQLite connections, from several processes, creates challenges at various levels:
|
||||
|
||||
1. **Database setup** may be attempted by multiple processes, concurrently.
|
||||
2. **SQLite** may throw `SQLITE_BUSY` errors, code 5, "database is locked".
|
||||
3. **iOS** may kill your application with a `0xDEAD10CC` exception.
|
||||
4. **GRDB** database observation misses changes performed by external processes.
|
||||
|
||||
We'll address all of those challenges below.
|
||||
|
||||
- [Use a Database Pool]
|
||||
- [How to limit the `SQLITE_BUSY` error]
|
||||
- [How to limit the `0xDEAD10CC` exception]
|
||||
- [How to perform cross-process database observation]
|
||||
|
||||
|
||||
## Use a Database Pool
|
||||
|
||||
In order to access a shared database, use a [Database Pool]. It opens the database in the [WAL mode](https://www.sqlite.org/wal.html), which helps sharing a database.
|
||||
|
||||
Since several processes may open the database at the same time, protect the creation of the database pool with an [NSFileCoordinator].
|
||||
|
||||
- In a process that can create and write in the database, use this sample code:
|
||||
|
||||
```swift
|
||||
/// Returns an initialized database pool at the shared location databaseURL
|
||||
func openSharedDatabase(at databaseURL: URL) throws -> DatabasePool {
|
||||
let coordinator = NSFileCoordinator(filePresenter: nil)
|
||||
var coordinatorError: NSError?
|
||||
var dbPool: DatabasePool?
|
||||
var dbError: Error?
|
||||
coordinator.coordinate(writingItemAt: databaseURL, options: .forMerging, error: &coordinatorError, byAccessor: { url in
|
||||
do {
|
||||
dbPool = try openDatabase(at: url)
|
||||
} catch {
|
||||
dbError = error
|
||||
}
|
||||
})
|
||||
if let error = dbError ?? coordinatorError {
|
||||
throw error
|
||||
}
|
||||
return dbPool!
|
||||
}
|
||||
|
||||
private func openDatabase(at databaseURL: URL) throws -> DatabasePool {
|
||||
var configuration = Configuration()
|
||||
configuration.prepareDatabase { db in
|
||||
// Activate the persistent WAL mode so that
|
||||
// readonly processes can access the database.
|
||||
//
|
||||
// See https://www.sqlite.org/walformat.html#operations_that_require_locks_and_which_locks_those_operations_use
|
||||
// and https://www.sqlite.org/c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntlpersistwal
|
||||
if db.configuration.readonly == false {
|
||||
var flag: CInt = 1
|
||||
let code = withUnsafeMutablePointer(to: &flag) { flagP in
|
||||
sqlite3_file_control(db.sqliteConnection, nil, SQLITE_FCNTL_PERSIST_WAL, flagP)
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: ResultCode(rawValue: code))
|
||||
}
|
||||
}
|
||||
}
|
||||
let dbPool = try DatabasePool(path: databaseURL.path, configuration: configuration)
|
||||
|
||||
// Perform here other database setups, such as defining
|
||||
// the database schema with a DatabaseMigrator, and
|
||||
// checking if the application can open the file:
|
||||
try migrator.migrate(dbPool)
|
||||
if try dbPool.read(migrator.hasBeenSuperseded) {
|
||||
// Database is too recent
|
||||
throw /* some error */
|
||||
}
|
||||
|
||||
return dbPool
|
||||
}
|
||||
```
|
||||
|
||||
- In a process that only reads in the database, use this sample code:
|
||||
|
||||
```swift
|
||||
/// Returns an initialized database pool at the shared location databaseURL,
|
||||
/// or nil if the database is not created yet, or does not have the required
|
||||
/// schema version.
|
||||
func openSharedReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
|
||||
let coordinator = NSFileCoordinator(filePresenter: nil)
|
||||
var coordinatorError: NSError?
|
||||
var dbPool: DatabasePool?
|
||||
var dbError: Error?
|
||||
coordinator.coordinate(readingItemAt: databaseURL, options: .withoutChanges, error: &coordinatorError, byAccessor: { url in
|
||||
do {
|
||||
dbPool = try openReadOnlyDatabase(at: url)
|
||||
} catch {
|
||||
dbError = error
|
||||
}
|
||||
})
|
||||
if let error = dbError ?? coordinatorError {
|
||||
throw error
|
||||
}
|
||||
return dbPool
|
||||
}
|
||||
|
||||
private func openReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
|
||||
do {
|
||||
var configuration = Configuration()
|
||||
configuration.readonly = true
|
||||
let dbPool = try DatabasePool(path: databaseURL.path, configuration: configuration)
|
||||
|
||||
// Check here if the database schema is the expected one,
|
||||
// for example with a DatabaseMigrator:
|
||||
return try dbPool.read { db in
|
||||
if try migrator.hasBeenSuperseded(db) {
|
||||
// Database is too recent
|
||||
return nil
|
||||
} else if try migrator.hasCompletedMigrations(db) == false {
|
||||
// Database is too old
|
||||
return nil
|
||||
}
|
||||
return dbPool
|
||||
}
|
||||
} catch {
|
||||
if FileManager.default.fileExists(atPath: databaseURL.path) {
|
||||
throw error
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
#### The specific case of readonly connections
|
||||
|
||||
Readonly connections will fail unless two extra files ending in `-shm` and `-wal` are present next to the database file ([source](https://www.sqlite.org/walformat.html#operations_that_require_locks_and_which_locks_those_operations_use)). Those files are regular companions of databases in the [WAL mode]. But they are deleted, under regular operations, when database connections are closed. Precisely speaking, they *may* be deleted: it depends on the SQLite and the operating system versions ([source](https://github.com/groue/GRDB.swift/issues/739#issuecomment-604363998)). And when they are deleted, readonly connections fail.
|
||||
|
||||
The solution is to enable the "persistent WAL mode", as shown in the sample code above, by setting the [SQLITE_FCNTL_PERSIST_WAL](https://www.sqlite.org/c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntlpersistwal) flag. This mode makes sure the `-shm` and `-wal` files are never deleted, and guarantees a database access to readonly connections.
|
||||
|
||||
|
||||
## How to limit the `SQLITE_BUSY` error
|
||||
|
||||
> The SQLITE_BUSY result code indicates that the database file could not be written (or in some cases read) because of concurrent activity by some other database connection, usually a database connection in a separate process.
|
||||
|
||||
See https://www.sqlite.org/rescode.html#busy for more information about this error.
|
||||
|
||||
If several processes want to write in the database, configure the database pool of each process that wants to write:
|
||||
|
||||
```swift
|
||||
var configuration = Configuration()
|
||||
configuration.busyMode = .timeout(/* a TimeInterval */)
|
||||
let dbPool = try DatabasePool(path: ..., configuration: configuration)
|
||||
```
|
||||
|
||||
With such a setup, you may still get `SQLITE_BUSY` (5, "database is locked") errors from all write operations. They will occur if the database remains locked by another process for longer than the specified timeout.
|
||||
|
||||
```swift
|
||||
do {
|
||||
try dbPool.write { db in ... }
|
||||
} catch DatabaseError.SQLITE_BUSY {
|
||||
// Another process won't let you write. Deal with it.
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: **Tip**: In order to be nice to other processes, measure the duration of your longest writes, and attempt at optimizing the ones that last for too long. See the [How do I monitor the duration of database statements execution?] FAQ.
|
||||
|
||||
|
||||
## How to limit the `0xDEAD10CC` exception
|
||||
|
||||
> The exception code 0xDEAD10CC indicates that an application has been terminated by the OS because it held on to a file lock or sqlite database lock during suspension.
|
||||
|
||||
See https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report for more information about this exception.
|
||||
|
||||
1. If you use SQLCipher, use SQLCipher 4+, and call the [`cipher_plaintext_header_size` pragma](https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_plaintext_header_size) from your database preparation function:
|
||||
|
||||
```swift
|
||||
var configuration = Configuration()
|
||||
configuration.prepareDatabase { (db: Database) in
|
||||
try db.usePassphrase("secret")
|
||||
try db.execute(sql: "PRAGMA cipher_plaintext_header_size = 32")
|
||||
}
|
||||
let dbPool = try DatabasePool(path: ..., configuration: configuration)
|
||||
```
|
||||
|
||||
This will avoid this issue: https://github.com/sqlcipher/sqlcipher/issues/255.
|
||||
|
||||
This will also disable a SQLCipher security feature: the salt. As described by https://www.zetetic.net/sqlcipher/design/:
|
||||
|
||||
> The salt is used for key derivation and it ensures that even if two databases are created using the same password, they will not have the same encryption key.
|
||||
|
||||
Applications are responsible for managing the salt themselves and providing it to SQLCipher. See https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_plaintext_header_size for instructions.
|
||||
|
||||
2. [**:fire: EXPERIMENTAL**](../README.md#what-are-experimental-features) In each process that wants to write in the database:
|
||||
|
||||
Set the `observesSuspensionNotifications` configuration flag:
|
||||
|
||||
```swift
|
||||
var configuration = Configuration()
|
||||
configuration.observesSuspensionNotifications = true
|
||||
let dbPool = try DatabasePool(path: ..., configuration: configuration)
|
||||
```
|
||||
|
||||
Post `Database.suspendNotification` when the application is about to be [suspended](https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle). You can for example post this notification from `UIApplicationDelegate.applicationDidEnterBackground(_:)`, or in the expiration handler of a [background task](https://forums.developer.apple.com/thread/85066).
|
||||
|
||||
```swift
|
||||
@UIApplicationMain
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
func applicationDidEnterBackground(_ application: UIApplication) {
|
||||
// Suspend databases
|
||||
NotificationCenter.default.post(name: Database.suspendNotification, object: self)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Post `Database.resumeNotification` from `UIApplicationDelegate.applicationWillEnterForeground(_:)` (or `SceneDelegate.sceneWillEnterForeground(_:)` for scene-based applications):
|
||||
|
||||
```swift
|
||||
@UIApplicationMain
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
func applicationWillEnterForeground(_ application: UIApplication) {
|
||||
// Resume databases
|
||||
NotificationCenter.default.post(name: Database.resumeNotification, object: self)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If the application uses the background modes supported by iOS, post `Database.resumeNotification` method from each and every background mode callback that may use the database. For example, if your application supports background fetches:
|
||||
|
||||
```swift
|
||||
@UIApplicationMain
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
|
||||
// Resume databases
|
||||
NotificationCenter.default.post(name: Database.resumeNotification, object: self)
|
||||
// Proceed with background fetch
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Suspended databases greatly reduce the odds of `0xDEAD10CC` exception occurring. If you see one in your crash logs, please open an issue!
|
||||
|
||||
In exchange, you will get `SQLITE_INTERRUPT` (9) or `SQLITE_ABORT` (4) errors, with messages "Database is suspended", "Transaction was aborted", or "interrupted", for any attempt at writing in the database when it is suspended.
|
||||
|
||||
You can catch those errors:
|
||||
|
||||
```swift
|
||||
do {
|
||||
try dbPool.write { db in ... }
|
||||
} catch DatabaseError.SQLITE_INTERRUPT, DatabaseError.SQLITE_ABORT {
|
||||
// Oops, the database is suspended.
|
||||
// Maybe try again after database is resumed?
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## How to perform cross-process database observation
|
||||
|
||||
GRDB [Database Observation] features, as well as its [Combine publishers] and [RxGRDB], are not able to notify database changes performed by other processes.
|
||||
|
||||
Whenever you need to notify other processes that the database has been changed, you will have to use a cross-process notification mechanism such as [NSFileCoordinator] or [CFNotificationCenterGetDarwinNotifyCenter].
|
||||
|
||||
You can trigger those notifications automatically with [DatabaseRegionObservation]:
|
||||
|
||||
```swift
|
||||
// Notify all changes made to the "player" and "team" database tables
|
||||
let observation = DatabaseRegionObservation(tracking: Player.all(), Team.all())
|
||||
let observer = try observation.start(in: dbPool) { (db: Database) in
|
||||
// Notify other processes
|
||||
}
|
||||
|
||||
// Notify all changes made to the database
|
||||
let observation = DatabaseRegionObservation(tracking: DatabaseRegion.fullDatabase)
|
||||
let observer = try observation.start(in: dbPool) { (db: Database) in
|
||||
// Notify other processes
|
||||
}
|
||||
```
|
||||
|
||||
[Use a Database Pool]: #use-a-database-pool
|
||||
[How to limit the `SQLITE_BUSY` error]: #how-to-limit-the-sqlite_busy-error
|
||||
[How to limit the `0xDEAD10CC` exception]: #how-to-limit-the-0xdead10cc-exception
|
||||
[How to perform cross-process database observation]: #how-to-perform-cross-process-database-observation
|
||||
[Database Pool]: ../README.md#database-pools
|
||||
[Database Observation]: ../README.md#database-changes-observation
|
||||
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
|
||||
[NSFileCoordinator]: https://developer.apple.com/documentation/foundation/nsfilecoordinator
|
||||
[CFNotificationCenterGetDarwinNotifyCenter]: https://developer.apple.com/documentation/corefoundation/1542572-cfnotificationcentergetdarwinnot
|
||||
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
|
||||
[WAL mode]: https://www.sqlite.org/wal.html
|
||||
[How do I monitor the duration of database statements execution?]: ../README.md#how-do-i-monitor-the-duration-of-database-statements-execution
|
||||
[Combine publishers]: Combine.md
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing).
|
||||
@@ -1,240 +1,4 @@
|
||||
Single-Row Tables
|
||||
=================
|
||||
|
||||
Let's talk about database tables that should contain a single row.
|
||||
|
||||
Such tables can store configuration values, user preferences, and generally some global application state. They are a suitable alternative to `UserDefaults` in some applications, especially when configuration refers to values found in other database tables, and database integrity is a concern.
|
||||
|
||||
An alternative way to store such configuration is a table of key-value pairs: two columns, and one row for each configuration value. This technique works, but it has a few drawbacks: you will have to deal with the various types of configuration values (strings, integers, dates, etc), and you won't be able to define foreign keys. This is why we won't explore key-value tables.
|
||||
|
||||
This guide helps you implementing a single-row table with GRDB, with recommendations on the database schema, migrations, and the design of a matching [record] type.
|
||||
|
||||
- [The Single-Row Table]
|
||||
- [The Single-Row Record]
|
||||
- [Wrap-Up]
|
||||
|
||||
|
||||
## The Single-Row Table
|
||||
|
||||
As always with GRDB, everything starts at the level of the database schema. Putting the robust SQLite on our side is always a good idea, because we have to write less code, and this helps shipping less bugs.
|
||||
|
||||
We want to instruct SQLite that our table must never contain more than one row. We will never have to wonder what to do if we were unlucky enough to find two rows with conflicting values in this table.
|
||||
|
||||
SQLite is not able to guarantee that the table is never empty, so we have to deal with two cases: either the table is empty, or it contains one row.
|
||||
|
||||
Those two cases can create a nagging question for the application. By default, inserts fail when the row already exists, and updates fail when the table is empty. In order to avoid those errors, we will have the app perform an insert in case of a failed update (in the [The Single-Row Record] chapter). And we instruct SQLite to just replace the eventual existing row in case of conflicting inserts:
|
||||
|
||||
```swift
|
||||
// CREATE TABLE appConfiguration (
|
||||
// id INTEGER PRIMARY KEY ON CONFLICT REPLACE CHECK (id = 1),
|
||||
// flag BOOLEAN NOT NULL,
|
||||
// ...)
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// Single row guarantee
|
||||
t.column("id", .integer)
|
||||
// Have inserts replace the existing row
|
||||
.primaryKey(onConflict: .replace)
|
||||
// Make sure the id column is always 1
|
||||
.check { $0 == 1 }
|
||||
|
||||
// The configuration columns
|
||||
t.column("flag", .boolean).notNull()
|
||||
// ... other columns
|
||||
}
|
||||
```
|
||||
|
||||
When you use [migrations], you may wonder if it is a good idea or not to perform an initial insert just after the table is created. Well, this is not recommended:
|
||||
|
||||
```swift
|
||||
// NOT RECOMMENDED
|
||||
migrator.registerMigration("appConfiguration") { db in
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// Single row guarantee
|
||||
t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 }
|
||||
|
||||
// Define sensible defaults for each column
|
||||
t.column("flag", .boolean).notNull()
|
||||
.defaults(to: false)
|
||||
// ... other columns
|
||||
}
|
||||
|
||||
// Populate the table
|
||||
try db.execute(sql: "INSERT INTO appConfiguration DEFAULT VALUES")
|
||||
}
|
||||
```
|
||||
|
||||
It is not a good idea to populate the table in a migration, for two reasons:
|
||||
|
||||
1. This is not a hard guarantee that the table will never be empty. As a consequence, this won't prevent your Swift code from dealing with the possibility of a missing row. On top of that, the Swift code that deals with the missing row may not use the same default values as the SQLite schema (a [DRY] violation), with unclear consequences.
|
||||
|
||||
2. Migrations that are shipped in the wild should *never* change, because you want to control the state of the databases installed on your users' devices, regardless of the application version they install first, regardless of how many application versions are skipped when they download an upgrade, etc. By inserting an initial row in a migration, you make it difficult for your application to adjust the sensible default values in the future, while keeping a clear idea of the various installation and upgrade scenarios.
|
||||
|
||||
The recommended migration creates the table, nothing more:
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
migrator.registerMigration("appConfiguration") { db in
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// Single row guarantee
|
||||
t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 }
|
||||
|
||||
// The configuration columns
|
||||
t.column("flag", .boolean).notNull()
|
||||
// ... other columns
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## The Single-Row Record
|
||||
|
||||
Now that the database schema has been defined, we can define the [record] type that will help the application access the single row:
|
||||
|
||||
```swift
|
||||
struct AppConfiguration: Codable {
|
||||
// Support for the single row guarantee
|
||||
private var id = 1
|
||||
|
||||
// The configuration properties
|
||||
var flag: Bool
|
||||
// ... other properties
|
||||
}
|
||||
```
|
||||
|
||||
In case the database table would be empty, we need a default configuration:
|
||||
|
||||
```swift
|
||||
extension AppConfiguration {
|
||||
/// The default configuration
|
||||
static let `default` = AppConfiguration(flag: false, ...)
|
||||
}
|
||||
```
|
||||
|
||||
We make our record able to access the database:
|
||||
|
||||
```swift
|
||||
extension AppConfiguration: FetchableRecord, PersistableRecord {
|
||||
```
|
||||
|
||||
We have seen in the [The Single-Row Table] chapter that by default, updates throw an error if the database table is empty. To avoid this error, we instruct GRDB to insert the missing default configuration before attempting to update (see [Persistence Callbacks] for more information about the `willSave` method):
|
||||
|
||||
```swift
|
||||
// Customize the default PersistableRecord behavior
|
||||
func willUpdate(_ db: Database, columns: Set<String>) throws {
|
||||
// Insert the default configuration if it does not exist yet.
|
||||
if try !exists(db) {
|
||||
try AppConfiguration.default.insert(db)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The standard GRDB method `fetchOne` returns an optional which is nil when the database table is empty. As a convenience, let's define a method that returns a non-optional (replacing the missing row with `default`):
|
||||
|
||||
```swift
|
||||
/// Returns the persisted configuration, or the default one if the
|
||||
/// database table is empty.
|
||||
static func fetch(_ db: Database) throws -> AppConfiguration {
|
||||
try fetchOne(db) ?? .default
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And that's it! Now we can use our singleton record:
|
||||
|
||||
```swift
|
||||
// READ
|
||||
let config = try dbQueue.read { db in
|
||||
try AppConfiguration.fetch(db)
|
||||
}
|
||||
if config.flag {
|
||||
// ...
|
||||
}
|
||||
|
||||
// WRITE
|
||||
try dbQueue.write { db in
|
||||
var config = try AppConfiguration.fetch(db)
|
||||
|
||||
// Update some config values
|
||||
try config.updateChanges(db) {
|
||||
$0.flag = true
|
||||
}
|
||||
|
||||
// Other possible ways to write config:
|
||||
try config.update(db)
|
||||
try config.save(db)
|
||||
try config.insert(db)
|
||||
try config.upsert(db)
|
||||
}
|
||||
```
|
||||
|
||||
The four `update`, `save`, `insert` and `upsert` methods can be used interchangeably. They all make sure the configuration is stored in the database.
|
||||
|
||||
The `updateChanges` method only updates the values changed by its closure argument (and performs an initial insert of default configuration if the database table is empty).
|
||||
|
||||
See [Persistence Methods] for more information.
|
||||
|
||||
|
||||
## Wrap-Up
|
||||
|
||||
We all love to copy and paste, don't we? Just customize the template code below:
|
||||
|
||||
```swift
|
||||
// Table creation
|
||||
try db.create(table: "appConfiguration") { t in
|
||||
// Single row guarantee
|
||||
t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 }
|
||||
|
||||
// The configuration columns
|
||||
t.column("flag", .boolean).notNull()
|
||||
// ... other columns
|
||||
}
|
||||
```
|
||||
|
||||
```swift
|
||||
//
|
||||
// AppConfiguration.swift
|
||||
//
|
||||
|
||||
import GRDB
|
||||
|
||||
struct AppConfiguration: Codable {
|
||||
// Support for the single row guarantee
|
||||
private var id = 1
|
||||
|
||||
// The configuration properties
|
||||
var flag: Bool
|
||||
// ... other properties
|
||||
}
|
||||
|
||||
extension AppConfiguration {
|
||||
/// The default configuration
|
||||
static let `default` = AppConfiguration(flag: false, ...)
|
||||
}
|
||||
|
||||
// Database Access
|
||||
extension AppConfiguration: FetchableRecord, PersistableRecord {
|
||||
// Customize the default PersistableRecord behavior
|
||||
func willUpdate(_ db: Database, columns: Set<String>) throws {
|
||||
// Insert the default configuration if it does not exist yet.
|
||||
if try !exists(db) {
|
||||
try AppConfiguration.default.insert(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the persisted configuration, or the default one if the
|
||||
/// database table is empty.
|
||||
static func fetch(_ db: Database) throws -> AppConfiguration {
|
||||
try fetchOne(db) ?? .default
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
[migrations]: Migrations.md
|
||||
[record]: ../README.md#records
|
||||
[The Single-Row Table]: #the-single-row-table
|
||||
[The Single-Row Record]: #the-single-row-record
|
||||
[Wrap-Up]: #wrap-up
|
||||
[DRY]: https://en.wikipedia.org/wiki/Don%27t_repeat_yourself
|
||||
[Persistence Callbacks]: ../README.md#persistence-callbacks
|
||||
[Persistence Methods]: ../README.md#persistence-methods
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables).
|
||||
@@ -149,16 +149,16 @@ Next, you choose the dispatch queue on which notifications happen (generally the
|
||||
|
||||
Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, or SQL triggers. GRDB roots its notification system in the rock-solid SQLite itself, so that high-level requests and raw SQL queries are equally supported.
|
||||
|
||||
See [Database Observation](../README.md#database-changes-observation) for further information.
|
||||
See [Database Observation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation) for further information.
|
||||
|
||||
|
||||
### 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
|
||||
@@ -285,23 +285,22 @@ If this little tour of GRDB has convinced you, the real trip starts here: [GRDB]
|
||||
|
||||
Happy GRDB! :gift:
|
||||
|
||||
[Concurrency Guide]: Concurrency.md
|
||||
[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]: ../README.md#valueobservation
|
||||
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
|
||||
[Fluent]: https://github.com/vapor/fluent
|
||||
[FMDB]: http://github.com/ccgus/fmdb
|
||||
[GRDB]: http://github.com/groue/GRDB.swift
|
||||
[FMDB]: https://github.com/ccgus/fmdb
|
||||
[GRDB]: https://github.com/groue/GRDB.swift
|
||||
[PersistableRecord]: ../README.md#records
|
||||
[Realm]: http://realm.io
|
||||
[FetchableRecord]: ../README.md#records
|
||||
[SQLite.swift]: http://github.com/stephencelis/SQLite.swift
|
||||
[SQLite.swift]: https://github.com/stephencelis/SQLite.swift
|
||||
[StORM]: https://www.perfect.org/docs/StORM.html
|
||||
[Swift-Kuery]: http://github.com/IBM-Swift/Swift-Kuery
|
||||
[Swift-Kuery]: https://github.com/IBM-Swift/Swift-Kuery
|
||||
[TableRecord]: ../README.md#records
|
||||
[TransactionObserver]: ../README.md#transactionobserver-protocol
|
||||
[query interface]: ../README.md#the-query-interface
|
||||
[associations]: AssociationsBasics.md
|
||||
[Codable records]: ../README.md#codable-records
|
||||
|
||||
+4
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '6.1.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|
|
||||
|
||||
@@ -202,6 +202,8 @@
|
||||
56894F752606576600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F742606576600268F4D /* FoundationDecimalTests.swift */; };
|
||||
56894FB72606589700268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F94260657D600268F4D /* Decimal.swift */; };
|
||||
568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLQueryGenerator.swift */; };
|
||||
568EB71929211E0800E59445 /* DatabaseSnapshotPool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */; };
|
||||
568EB71E2921234800E59445 /* DatabaseSnapshotPoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */; };
|
||||
568ECA8A25D7013000B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA8925D7013000B71526 /* SQLSelection.swift */; };
|
||||
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */; };
|
||||
568ECB1825D9161600B71526 /* SQLSubquery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB1725D9161500B71526 /* SQLSubquery.swift */; };
|
||||
@@ -248,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 */; };
|
||||
@@ -277,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 */; };
|
||||
@@ -369,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 */; };
|
||||
@@ -616,6 +622,8 @@
|
||||
56894F742606576600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = "<group>"; };
|
||||
56894F94260657D600268F4D /* Decimal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = "<group>"; };
|
||||
568D13182207213E00674B58 /* SQLQueryGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQueryGenerator.swift; sourceTree = "<group>"; };
|
||||
568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPool.swift; sourceTree = "<group>"; };
|
||||
568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPoolTests.swift; sourceTree = "<group>"; };
|
||||
568ECA8925D7013000B71526 /* SQLSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelection.swift; sourceTree = "<group>"; };
|
||||
568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOrdering.swift; sourceTree = "<group>"; };
|
||||
568ECB1725D9161500B71526 /* SQLSubquery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSubquery.swift; sourceTree = "<group>"; };
|
||||
@@ -707,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>"; };
|
||||
@@ -745,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>"; };
|
||||
@@ -767,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>"; };
|
||||
@@ -906,11 +918,10 @@
|
||||
children = (
|
||||
563082E32430B6BE00C14A05 /* DatabaseCancellable.swift */,
|
||||
560233C32724234F00529DF3 /* SharedValueObservation.swift */,
|
||||
564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */,
|
||||
563B06AA217EF0CC00B38F35 /* ValueObservation.swift */,
|
||||
56848972242DE36F002F9702 /* ValueObservationScheduler.swift */,
|
||||
5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */,
|
||||
56AACAA022ACEC9700A40F2A /* ValueReducer */,
|
||||
566BD72F2927AFC300595649 /* Observers */,
|
||||
56AACAA022ACEC9700A40F2A /* Reducers */,
|
||||
);
|
||||
path = ValueObservation;
|
||||
sourceTree = "<group>";
|
||||
@@ -1232,6 +1243,15 @@
|
||||
path = Utils;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
566BD72F2927AFC300595649 /* Observers */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */,
|
||||
5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */,
|
||||
);
|
||||
path = Observers;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
5674A7251F30A8EF0095F066 /* FetchableRecord */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -1334,6 +1354,7 @@
|
||||
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */,
|
||||
564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */,
|
||||
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */,
|
||||
568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */,
|
||||
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */,
|
||||
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */,
|
||||
56A238131B9C74A90082EB20 /* DatabaseTests.swift */,
|
||||
@@ -1355,6 +1376,7 @@
|
||||
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */,
|
||||
56A238201B9C74A90082EB20 /* Statement */,
|
||||
56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */,
|
||||
56AFEF362996B9DC00CA1E51 /* TransactionDateTests.swift */,
|
||||
5607EFD11BB8253300605DE3 /* TransactionObserver */,
|
||||
);
|
||||
name = Core;
|
||||
@@ -1424,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 */,
|
||||
@@ -1438,6 +1461,7 @@
|
||||
564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */,
|
||||
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
|
||||
566A84192041146100E50BFD /* DatabaseSnapshot.swift */,
|
||||
568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */,
|
||||
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
|
||||
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
|
||||
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
|
||||
@@ -1447,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 */,
|
||||
@@ -1494,7 +1520,7 @@
|
||||
path = Record;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56AACAA022ACEC9700A40F2A /* ValueReducer */ = {
|
||||
56AACAA022ACEC9700A40F2A /* Reducers */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56AACAA722ACED7100A40F2A /* Fetch.swift */,
|
||||
@@ -1503,7 +1529,7 @@
|
||||
563B8F91249E6171007A48C9 /* Trace.swift */,
|
||||
5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */,
|
||||
);
|
||||
path = ValueReducer;
|
||||
path = Reducers;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56DAA2C41DE99D8D006E10C8 /* Cursor */ = {
|
||||
@@ -1785,6 +1811,7 @@
|
||||
56D496B01D813385008276D7 /* DatabaseErrorTests.swift in Sources */,
|
||||
56176C5C1EACCCC7000F3F2B /* FTS5TableBuilderTests.swift in Sources */,
|
||||
562206061E420EA4005860AC /* DatabasePoolBackupTests.swift in Sources */,
|
||||
568EB71E2921234800E59445 /* DatabaseSnapshotPoolTests.swift in Sources */,
|
||||
56D496B51D813413008276D7 /* DatabaseCollationTests.swift in Sources */,
|
||||
563DE4F3231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */,
|
||||
56BF2282241781C5003D86EB /* UtilsTests.swift in Sources */,
|
||||
@@ -1935,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 */,
|
||||
@@ -1998,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 */,
|
||||
@@ -2035,6 +2064,7 @@
|
||||
566B91131FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
|
||||
5605F1591C672E4000235C62 /* CGFloat.swift in Sources */,
|
||||
5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
|
||||
568EB71929211E0800E59445 /* DatabaseSnapshotPool.swift in Sources */,
|
||||
5605F1631C672E4000235C62 /* Date.swift in Sources */,
|
||||
5605F1711C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
|
||||
56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */,
|
||||
@@ -2082,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 */,
|
||||
@@ -2133,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>
|
||||
|
||||
+253
-140
@@ -1,37 +1,48 @@
|
||||
import Dispatch
|
||||
import Foundation
|
||||
|
||||
/// Configuration for a DatabaseQueue or DatabasePool.
|
||||
public struct Configuration {
|
||||
|
||||
// MARK: - Misc options
|
||||
|
||||
/// If true (the default), support for foreign keys is enabled.
|
||||
/// See <https://www.sqlite.org/foreignkeys.html> for more information.
|
||||
/// A boolean value indicating whether foreign key support is enabled.
|
||||
///
|
||||
/// Default: true
|
||||
/// The default is true.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/foreignkeys.html>.
|
||||
public var foreignKeysEnabled = true
|
||||
|
||||
/// If true, database modifications are disallowed.
|
||||
/// A boolean value indicating whether an SQLite connection is read-only.
|
||||
///
|
||||
/// Default: false
|
||||
/// 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
|
||||
|
||||
/// The configuration label.
|
||||
/// A label that describes a database connection.
|
||||
///
|
||||
/// You can query this label at runtime:
|
||||
///
|
||||
/// var configuration = Configuration()
|
||||
/// configuration.label = "MyDatabase"
|
||||
/// let dbQueue = try DatabaseQueue(path: ..., configuration: configuration)
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.label = "MyDatabase"
|
||||
/// let dbQueue = try DatabaseQueue(configuration: config)
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// print(db.configuration.label) // Prints "MyDatabase"
|
||||
/// }
|
||||
/// try dbQueue.read { db in
|
||||
/// print(db.configuration.label) // Prints "MyDatabase"
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The configuration label is also used to name Database connections (the
|
||||
/// `Database.description` property), and the various dispatch queues
|
||||
/// created by GRDB, visible in debugging sessions and crash logs.
|
||||
/// The configuration label is also used to name ``Database`` connections
|
||||
/// (their ``Database/description`` property), and the various dispatch
|
||||
/// queues created by GRDB, visible in debugging sessions and crash logs.
|
||||
///
|
||||
/// Those connection names and dispatch queue labels are intended for
|
||||
/// debugging only. Their format may change between GRDB releases.
|
||||
@@ -66,62 +77,68 @@ public struct Configuration {
|
||||
/// The default configuration label is nil.
|
||||
public var label: String? = nil
|
||||
|
||||
/// If false, SQLite from version 3.29.0 will not interpret a double-quoted
|
||||
/// string as a string literal if it does not match any valid identifier.
|
||||
/// A boolean value indicating whether SQLite 3.29+ interprets
|
||||
/// double-quoted strings as string literals when they does not match any
|
||||
/// valid identifier.
|
||||
///
|
||||
/// For example:
|
||||
/// The default and recommended value is false:
|
||||
///
|
||||
/// // Error: no such column: foo
|
||||
/// let name = try String.fetchOne(db, sql: """
|
||||
/// SELECT "foo" FROM "player"
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// // Error: no such column: missingColumn
|
||||
/// let name = try String.fetchOne(db, sql: """
|
||||
/// SELECT "missingColumn" FROM "player"
|
||||
/// """)
|
||||
/// ```
|
||||
///
|
||||
/// When true, or before version 3.29.0, such strings are interpreted as
|
||||
/// string literals, as in the example below. This is a well known SQLite
|
||||
/// [misfeature](https://sqlite.org/quirks.html#dblquote).
|
||||
/// When true, or before SQLite version 3.29.0, double-quoted strings that
|
||||
/// do not match any valid identifier are interpreted as string literals,
|
||||
/// as in the example below. This is an SQLite
|
||||
/// [misfeature](https://sqlite.org/quirks.html#double_quoted_string_literals_are_accepted):
|
||||
///
|
||||
/// // Success: "foo"
|
||||
/// let name = try String.fetchOne(db, sql: """
|
||||
/// SELECT "foo" FROM "player"
|
||||
/// """)
|
||||
///
|
||||
/// - Recommended value: false
|
||||
/// - Default value: false
|
||||
/// ```swift
|
||||
/// // MISFEATURE: This query succeeds with result "missingColumn"
|
||||
/// let name = try String.fetchOne(db, sql: """
|
||||
/// SELECT "missingColumn" FROM "player"
|
||||
/// """)
|
||||
/// ```
|
||||
public var acceptsDoubleQuotedStringLiterals = false
|
||||
|
||||
/// When true, the `Database.suspendNotification` and
|
||||
/// `Database.resumeNotification` suspend and resume the database. Database
|
||||
/// suspension helps avoiding the [`0xdead10cc`
|
||||
/// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report).
|
||||
/// A boolean value indicating whether the database connection listens to
|
||||
/// the ``Database/suspendNotification`` and ``Database/resumeNotification``
|
||||
/// notifications.
|
||||
///
|
||||
/// During suspension, all database accesses but reads in WAL mode may throw
|
||||
/// a DatabaseError of code `SQLITE_INTERRUPT`, or `SQLITE_ABORT`. You can
|
||||
/// check for those error codes with the
|
||||
/// `DatabaseError.isInterruptionError` property.
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// Set this flag to true when you apply the technique described in
|
||||
/// <doc:DatabaseSharing#How-to-limit-the-0xDEAD10CC-exception>. See
|
||||
/// ``Database/suspendNotification`` for more informations about
|
||||
/// suspended databases.
|
||||
public var observesSuspensionNotifications = false
|
||||
|
||||
/// If false (the default), statement arguments are not visible in the
|
||||
/// description of database errors and trace events, preventing sensitive
|
||||
/// information from leaking in unexpected places.
|
||||
/// A boolean value indicating whether statement arguments are visible in
|
||||
/// the description of database errors and trace events.
|
||||
///
|
||||
/// For example:
|
||||
/// The default and recommended value is false: statement arguments are not
|
||||
/// visible in database errors and trace events, preventing sensitive
|
||||
/// information from leaking in unexpected places. For example:
|
||||
///
|
||||
/// // Error: sensitive information is not printed when an error occurs:
|
||||
/// do {
|
||||
/// let email = "..." // sensitive information
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// print(error)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// db.trace { event in
|
||||
/// // By default, sensitive information is NOT printed
|
||||
/// // when a statement is traced:
|
||||
/// print(event)
|
||||
/// }
|
||||
///
|
||||
/// // Trace: sensitive information is not printed when a statement is traced:
|
||||
/// db.trace { event in
|
||||
/// print(event)
|
||||
/// }
|
||||
/// let email = "..." // sensitive information
|
||||
/// do {
|
||||
/// // The sensitive information to protect
|
||||
/// let email = "..."
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// // By default, sensitive information is NOT printed
|
||||
/// // when an error occurs:
|
||||
/// print(error)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// For debugging purpose, you can set this flag to true, and get more
|
||||
/// precise database reports. It is your responsibility to prevent sensitive
|
||||
@@ -129,169 +146,265 @@ public struct Configuration {
|
||||
/// this flag in release builds (think about GDPR and other
|
||||
/// privacy-related rules):
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// #if DEBUG
|
||||
/// // Protect sensitive information by enabling verbose debugging in DEBUG builds only
|
||||
/// config.publicStatementArguments = true
|
||||
/// #endif
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// #if DEBUG
|
||||
/// // Enable verbose debugging in DEBUG builds only
|
||||
/// config.publicStatementArguments = true
|
||||
/// #endif
|
||||
///
|
||||
/// // The descriptions of trace events and errors now contain the
|
||||
/// // sensitive information:
|
||||
/// db.trace { event in
|
||||
/// print(event)
|
||||
/// }
|
||||
/// do {
|
||||
/// let email = "..."
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// print(error)
|
||||
/// }
|
||||
/// db.trace { event in
|
||||
/// // Sensitive information is printed in DEBUG builds:
|
||||
/// print(event)
|
||||
/// }
|
||||
///
|
||||
/// do {
|
||||
/// // The sensitive information to protect
|
||||
/// let email = "..."
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// // Sensitive information is printed in DEBUG builds:
|
||||
/// print(error)
|
||||
/// }
|
||||
/// ```
|
||||
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] = []
|
||||
|
||||
/// The function argument is run when an SQLite connection is opened,
|
||||
/// before the connection is made available for database access methods.
|
||||
/// Defines a function to run whenever an SQLite connection is opened.
|
||||
///
|
||||
/// The preparation function is run before the connection is made available
|
||||
/// for database access methods.
|
||||
///
|
||||
/// This method can be called several times. The preparation functions are
|
||||
/// run in the same order.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// try db.execute(sql: "PRAGMA kdf_iter = 10000")
|
||||
/// }
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// // Prints all SQL statements
|
||||
/// db.trace { print("SQL >", $0) }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When you use a `DatabasePool`, preparation functions are called for
|
||||
/// When you use a ``DatabasePool``, preparation functions are called for
|
||||
/// the writer connection and all reader connections. You can distinguish
|
||||
/// them by querying `db.configuration.readonly`:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// if db.configuration.readonly {
|
||||
/// // reader connection
|
||||
/// } else {
|
||||
/// // writer connection
|
||||
/// }
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// if db.configuration.readonly {
|
||||
/// // reader connection
|
||||
/// } else {
|
||||
/// // writer connection
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// On newly created databases, `DatabasePool` the WAL mode is activated
|
||||
/// after the preparation functions have run.
|
||||
/// On newly created databases files, ``DatabasePool`` activates the WAL
|
||||
/// mode after the preparation functions have run.
|
||||
public mutating func prepareDatabase(_ setup: @escaping (Database) throws -> Void) {
|
||||
setups.append(setup)
|
||||
}
|
||||
|
||||
// MARK: - Transactions
|
||||
|
||||
/// The default kind of transaction.
|
||||
/// The default kind of write transactions.
|
||||
///
|
||||
/// Default: deferred
|
||||
/// The default is ``Database/TransactionKind/deferred``.
|
||||
///
|
||||
/// You can change the default transaction kind. For example, you can force
|
||||
/// all write transactions to be `IMMEDIATE`:
|
||||
///
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.defaultTransactionKind = .immediate
|
||||
/// let dbQueue = try DatabaseQueue(configuration: config)
|
||||
///
|
||||
/// // BEGIN IMMEDIATE TRANSACTION; ...; COMMIT TRANSACTION;
|
||||
/// try dbQueue.write { db in ... }
|
||||
/// ```
|
||||
///
|
||||
/// This property is ignored for read-only transactions. Those always open
|
||||
/// `DEFERRED` SQLite transactions.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>
|
||||
public var defaultTransactionKind: Database.TransactionKind = .deferred
|
||||
|
||||
/// If false, it is a programmer error to leave a transaction opened at the
|
||||
/// end of a database access block.
|
||||
/// A boolean value indicating whether it is valid to leave a transaction
|
||||
/// opened at the end of a database access method.
|
||||
///
|
||||
/// For example:
|
||||
/// The default value is false: not completing a transaction is a
|
||||
/// programmer error:
|
||||
///
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// ```swift
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
///
|
||||
/// // fatal error: A transaction has been left opened at the end of a database access
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.beginTransaction()
|
||||
/// }
|
||||
/// // fatal error: A transaction has been left opened at the end of a database access
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.beginTransaction()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// If true, one can leave opened transaction at the end of database access
|
||||
/// blocks:
|
||||
/// When true, one can leave opened transaction at the end of database
|
||||
/// access method:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.allowsUnsafeTransactions = true
|
||||
/// let dbQueue = try DatabaseQueue(configuration: config)
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.allowsUnsafeTransactions = true
|
||||
/// let dbQueue = try DatabaseQueue(configuration: config)
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.beginTransaction()
|
||||
/// }
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.beginTransaction()
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.commit()
|
||||
/// }
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.commit()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This configuration flag has no effect on DatabasePool readers: those
|
||||
/// never allow leaving a transaction opened at the end of a read access.
|
||||
///
|
||||
/// Default: false
|
||||
/// This configuration flag has no effect on ``DatabasePool`` reader
|
||||
/// connections: those never allow leaving a transaction opened at the end
|
||||
/// of a read access.
|
||||
public var allowsUnsafeTransactions = false
|
||||
|
||||
// MARK: - Concurrency
|
||||
|
||||
/// The behavior in case of SQLITE_BUSY error. See <https://www.sqlite.org/rescode.html#busy>
|
||||
/// Defines the how `SQLITE_BUSY` errors are handled.
|
||||
///
|
||||
/// Default: immediateError
|
||||
/// The default is ``Database/BusyMode/immediateError``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/rescode.html#busy>
|
||||
public var busyMode: Database.BusyMode = .immediateError
|
||||
|
||||
/// The behavior in case of SQLITE_BUSY error, for read-only connections.
|
||||
/// If nil, GRDB picks a default one.
|
||||
var readonlyBusyMode: Database.BusyMode? = nil
|
||||
|
||||
/// The maximum number of concurrent readers (applies to database
|
||||
/// pools only).
|
||||
/// The maximum number of concurrent reader connections.
|
||||
///
|
||||
/// Default: 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``. 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()
|
||||
/// config.maximumReaderCount = 5
|
||||
///
|
||||
/// let path = "/path/to/database.sqlite"
|
||||
/// let dbQueue = try DatabaseQueue(path: path, configuration: config)
|
||||
/// let dbPool = try DatabasePool(path: path, configuration: config)
|
||||
/// let dbSnapshot = try dbPool.makeSnapshot()
|
||||
///
|
||||
/// print(dbQueue.configuration.maximumReaderCount) // 1
|
||||
/// print(dbPool.configuration.maximumReaderCount) // 5
|
||||
/// print(dbSnapshot.configuration.maximumReaderCount) // 1
|
||||
/// ```
|
||||
public var maximumReaderCount: Int = 5
|
||||
|
||||
/// The quality of service class for the work performed by the database.
|
||||
/// The quality of service of database accesses.
|
||||
///
|
||||
/// The quality of service is ignored if you supply a target queue.
|
||||
/// The quality of service is ignored if you supply a ``targetQueue``.
|
||||
///
|
||||
/// Default: .userInitiated
|
||||
/// The default is `userInitiated`.
|
||||
public var qos: DispatchQoS = .userInitiated
|
||||
|
||||
/// The quality of service of read accesses
|
||||
var readQoS: DispatchQoS {
|
||||
/// The effective quality of service of read-only database accesses.
|
||||
public var readQoS: DispatchQoS {
|
||||
targetQueue?.qos ?? self.qos
|
||||
}
|
||||
|
||||
/// A target queue for database accesses.
|
||||
/// The effective quality of service of write database accesses.
|
||||
public var writeQoS: DispatchQoS {
|
||||
writeTargetQueue?.qos ?? targetQueue?.qos ?? self.qos
|
||||
}
|
||||
|
||||
/// The target dispatch queue for database accesses.
|
||||
///
|
||||
/// Database connections which are not read-only will prefer
|
||||
/// `writeTargetQueue` instead, if it is not nil.
|
||||
/// ``writeTargetQueue`` instead, if it is not nil.
|
||||
///
|
||||
/// When you use a database pool, make sure this queue is concurrent. This
|
||||
/// When you use ``DatabasePool``, make sure this queue is concurrent. This
|
||||
/// is because in a serial dispatch queue, no concurrent database access can
|
||||
/// happen, and you may experience deadlocks.
|
||||
///
|
||||
/// If the queue is nil, all database accesses happen in unspecified
|
||||
/// dispatch queues whose quality of service is determined by the
|
||||
/// `qos` property.
|
||||
/// ``qos`` property.
|
||||
///
|
||||
/// Default: nil
|
||||
/// The default is nil.
|
||||
public var targetQueue: DispatchQueue? = nil
|
||||
|
||||
/// The target queue for database connections which are not read-only.
|
||||
/// The target dispatch queue for write database accesses.
|
||||
///
|
||||
/// If this queue is nil, writer connections are controlled by `targetQueue`.
|
||||
/// If this queue is nil, writer connections are controlled
|
||||
/// by ``targetQueue``.
|
||||
///
|
||||
/// Default: nil
|
||||
/// The default is nil.
|
||||
public var writeTargetQueue: DispatchQueue? = nil
|
||||
|
||||
#if os(iOS)
|
||||
/// Sets whether GRDB will release memory when entering the background or
|
||||
/// upon receiving a memory warning in iOS.
|
||||
/// A boolean value indicating whether the database connection releases
|
||||
/// memory when entering the background or upon receiving a memory warning
|
||||
/// in iOS.
|
||||
///
|
||||
/// Default: true
|
||||
/// 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
|
||||
/// Creates a factory configuration.
|
||||
public init() { }
|
||||
|
||||
// MARK: - Not Public
|
||||
|
||||
var threadingMode: Database.ThreadingMode = .`default`
|
||||
/// The SQLite [threading mode](https://www.sqlite.org/threadsafe.html).
|
||||
///
|
||||
/// - Note: Only the multi-thread mode (`SQLITE_OPEN_NOMUTEX`) is currently
|
||||
/// supported, since all <doc:DatabaseConnections> access SQLite connections
|
||||
/// through a `SerializedDatabase`.
|
||||
var threadingMode = Database.ThreadingMode.default
|
||||
|
||||
var SQLiteConnectionDidOpen: (() -> Void)?
|
||||
var SQLiteConnectionWillClose: ((SQLiteConnection) -> Void)?
|
||||
var SQLiteConnectionDidClose: (() -> Void)?
|
||||
@@ -326,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)
|
||||
|
||||
+92
-73
@@ -214,13 +214,13 @@ extension Sequence {
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// The most common way to iterate over the elements of a cursor is to use a
|
||||
/// `while` loop:
|
||||
/// To iterate over the elements of a cursor, use a `while` loop:
|
||||
///
|
||||
/// let cursor = ...
|
||||
/// while let element = try cursor.next() {
|
||||
/// ...
|
||||
/// }
|
||||
/// ```swift
|
||||
/// while let element = try cursor.next() {
|
||||
/// print(element)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ## Relationship with standard Sequence and IteratorProtocol
|
||||
///
|
||||
@@ -237,12 +237,28 @@ extension Sequence {
|
||||
/// `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`,
|
||||
/// `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`,
|
||||
/// `suffix`.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``AnyCursor``
|
||||
/// - ``DropFirstCursor``
|
||||
/// - ``DropWhileCursor``
|
||||
/// - ``EnumeratedCursor``
|
||||
/// - ``FilterCursor``
|
||||
/// - ``FlattenCursor``
|
||||
/// - ``MapCursor``
|
||||
/// - ``PrefixCursor``
|
||||
/// - ``PrefixWhileCursor``
|
||||
public protocol Cursor<Element>: AnyObject {
|
||||
/// The type of element traversed by the cursor.
|
||||
associatedtype Element
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next element
|
||||
/// exists. Once nil has been returned, all subsequent calls return nil.
|
||||
/// exists.
|
||||
///
|
||||
/// Once nil has been returned, all subsequent calls return nil.
|
||||
func next() throws -> Element?
|
||||
|
||||
/// Calls the given closure on each element in the cursor.
|
||||
@@ -672,24 +688,22 @@ extension Cursor where Element: StringProtocol {
|
||||
|
||||
// MARK: Specialized Cursors
|
||||
|
||||
/// A type-erased cursor of Element.
|
||||
/// A type-erased cursor.
|
||||
///
|
||||
/// This cursor forwards its next() method to an arbitrary underlying cursor
|
||||
/// having the same Element type, hiding the specifics of the underlying
|
||||
/// cursor.
|
||||
/// An instance of `AnyCursor` forwards its operations to an underlying base
|
||||
/// cursor having the same `Element` type, hiding the specifics of the
|
||||
/// underlying cursor.
|
||||
public final class AnyCursor<Element>: Cursor {
|
||||
private let _next: () throws -> Element?
|
||||
private let _forEach: ((Element) throws -> Void) throws -> Void
|
||||
|
||||
/// Creates a cursor that wraps a base cursor but whose type depends only on
|
||||
/// the base cursor’s element type
|
||||
/// Creates a new cursor that wraps and forwards operations to `base`.
|
||||
public init<C: Cursor>(_ base: C) where C.Element == Element {
|
||||
_next = base.next
|
||||
_forEach = base.forEach
|
||||
}
|
||||
|
||||
/// Creates a cursor that wraps a base iterator but whose type depends only
|
||||
/// on the base iterator’s element type
|
||||
/// Creates a new cursor whose elements are elements of `iterator`.
|
||||
public convenience init<I>(iterator: I)
|
||||
where I: IteratorProtocol, I.Element == Element
|
||||
{
|
||||
@@ -697,15 +711,14 @@ public final class AnyCursor<Element>: Cursor {
|
||||
self.init { iterator.next() }
|
||||
}
|
||||
|
||||
/// Creates a cursor that wraps a base sequence but whose type depends only
|
||||
/// on the base sequence’s element type
|
||||
public convenience init<S>(_ s: S)
|
||||
/// Creates a new cursor whose elements are elements of `sequence`.
|
||||
public convenience init<S>(_ sequence: S)
|
||||
where S: Sequence, S.Element == Element
|
||||
{
|
||||
self.init(iterator: s.makeIterator())
|
||||
self.init(iterator: sequence.makeIterator())
|
||||
}
|
||||
|
||||
/// Creates a cursor that wraps the given closure in its next() method
|
||||
/// Creates a cursor that wraps the given closure in its ``next()`` method.
|
||||
public init(_ next: @escaping () throws -> Element?) {
|
||||
_next = next
|
||||
_forEach = {
|
||||
@@ -720,8 +733,9 @@ public final class AnyCursor<Element>: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public final class DropFirstCursor<Base: Cursor>: Cursor {
|
||||
/// A `Cursor` that consumes and drops n elements from an underlying `Base`
|
||||
/// cursor before possibly returning the first available element.
|
||||
public final class DropFirstCursor<Base: Cursor> {
|
||||
private let base: Base
|
||||
private let limit: Int
|
||||
private var dropped: Int = 0
|
||||
@@ -731,7 +745,9 @@ public final class DropFirstCursor<Base: Cursor>: Cursor {
|
||||
self.base = base
|
||||
self.limit = limit
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension DropFirstCursor: Cursor {
|
||||
public func next() throws -> Base.Element? {
|
||||
while dropped < limit {
|
||||
if try base.next() == nil {
|
||||
@@ -744,11 +760,9 @@ public final class DropFirstCursor<Base: Cursor>: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor whose elements consist of the elements that follow the initial
|
||||
/// consecutive elements of some base cursor that satisfy a given predicate.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class DropWhileCursor<Base: Cursor>: Cursor {
|
||||
/// A `Cursor` whose elements consist of the elements that follow the initial
|
||||
/// consecutive elements of some `Base` cursor that satisfy a given predicate.
|
||||
public final class DropWhileCursor<Base: Cursor> {
|
||||
private let base: Base
|
||||
private let predicate: (Base.Element) throws -> Bool
|
||||
private var predicateHasFailed = false
|
||||
@@ -757,7 +771,9 @@ public final class DropWhileCursor<Base: Cursor>: Cursor {
|
||||
self.base = base
|
||||
self.predicate = predicate
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension DropWhileCursor: Cursor {
|
||||
public func next() throws -> Base.Element? {
|
||||
if predicateHasFailed {
|
||||
return try base.next()
|
||||
@@ -775,19 +791,24 @@ public final class DropWhileCursor<Base: Cursor>: Cursor {
|
||||
|
||||
/// An enumeration of the elements of a cursor.
|
||||
///
|
||||
/// To create an instance of `EnumeratedCursor`, call the `enumerated()` method
|
||||
/// on a cursor:
|
||||
/// `EnumeratedCursor` is a cursor of pairs _(n, x)_, where _ns_ are consecutive
|
||||
/// `Int` values starting at zero, and _xs_ are the elements of a `Base` cursor.
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
|
||||
/// let c = cursor.enumerated()
|
||||
/// while let (n, x) = c.next() {
|
||||
/// print("\(n): \(x)")
|
||||
/// }
|
||||
/// // Prints: "0: foo"
|
||||
/// // Prints: "1: bar"
|
||||
/// To create an instance of `EnumeratedCursor`, call `enumerated()` on a
|
||||
/// cursor. For example:
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class EnumeratedCursor<Base: Cursor>: Cursor {
|
||||
/// ```swift
|
||||
/// let base = try String.fetchCursor(db, sql: """
|
||||
/// SELECT 'foo' UNION ALL SELECT 'bar'
|
||||
/// """)
|
||||
/// let cursor = base.enumerated()
|
||||
/// while let (n, x) = cursor.next() {
|
||||
/// print("\(n): \(x)")
|
||||
/// }
|
||||
/// // Prints: "0: foo"
|
||||
/// // Prints: "1: bar"
|
||||
/// ```
|
||||
public final class EnumeratedCursor<Base: Cursor> {
|
||||
private let base: Base
|
||||
private var index: Int
|
||||
|
||||
@@ -795,7 +816,9 @@ public final class EnumeratedCursor<Base: Cursor>: Cursor {
|
||||
self.base = base
|
||||
self.index = 0
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension EnumeratedCursor: Cursor {
|
||||
public func next() throws -> (Int, Base.Element)? {
|
||||
guard let element = try base.next() else { return nil }
|
||||
defer { index += 1 }
|
||||
@@ -810,11 +833,9 @@ public final class EnumeratedCursor<Base: Cursor>: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor whose elements consist of the elements of some base cursor that
|
||||
/// A `Cursor` whose elements consist of the elements of some `Base` cursor that
|
||||
/// also satisfy a given predicate.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class FilterCursor<Base: Cursor>: Cursor {
|
||||
public final class FilterCursor<Base: Cursor> {
|
||||
private let base: Base
|
||||
private let isIncluded: (Base.Element) throws -> Bool
|
||||
|
||||
@@ -822,7 +843,9 @@ public final class FilterCursor<Base: Cursor>: Cursor {
|
||||
self.base = base
|
||||
self.isIncluded = isIncluded
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension FilterCursor: Cursor {
|
||||
public func next() throws -> Base.Element? {
|
||||
while let element = try base.next() {
|
||||
if try isIncluded(element) {
|
||||
@@ -841,20 +864,18 @@ public final class FilterCursor<Base: Cursor>: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor consisting of all the elements contained in each segment contained
|
||||
/// in some Base cursor.
|
||||
///
|
||||
/// See Cursor.joined(), Cursor.flatMap(_:), Sequence.flatMap(_:)
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class FlattenCursor<Base: Cursor>: Cursor where Base.Element: Cursor {
|
||||
/// A `Cursor` consisting of all the elements contained in each segment
|
||||
/// contained in some `Base` cursor.
|
||||
public final class FlattenCursor<Base: Cursor> where Base.Element: Cursor {
|
||||
private let base: Base
|
||||
private var inner: Base.Element?
|
||||
|
||||
init(_ base: Base) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension FlattenCursor: Cursor {
|
||||
public func next() throws -> Base.Element.Element? {
|
||||
while true {
|
||||
if let element = try inner?.next() {
|
||||
@@ -868,13 +889,9 @@ public final class FlattenCursor<Base: Cursor>: Cursor where Base.Element: Curso
|
||||
}
|
||||
}
|
||||
|
||||
/// A Cursor whose elements consist of those in a Base Cursor passed through a
|
||||
/// transform function returning Element.
|
||||
///
|
||||
/// See Cursor.map(_:)
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class MapCursor<Base: Cursor, Element>: Cursor {
|
||||
/// A `Cursor` whose elements consist of those in a `Base` cursor passed through
|
||||
/// a transform function returning Element.
|
||||
public final class MapCursor<Base: Cursor, Element> {
|
||||
private let base: Base
|
||||
private let transform: (Base.Element) throws -> Element
|
||||
|
||||
@@ -882,7 +899,9 @@ public final class MapCursor<Base: Cursor, Element>: Cursor {
|
||||
self.base = base
|
||||
self.transform = transform
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension MapCursor: Cursor {
|
||||
public func next() throws -> Element? {
|
||||
guard let element = try base.next() else { return nil }
|
||||
return try transform(element)
|
||||
@@ -895,11 +914,9 @@ public final class MapCursor<Base: Cursor, Element>: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor that only consumes up to `n` elements from an underlying
|
||||
/// A `Cursor` that only consumes up to `n` elements from an underlying
|
||||
/// `Base` cursor.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class PrefixCursor<Base: Cursor>: Cursor {
|
||||
public final class PrefixCursor<Base: Cursor> {
|
||||
private let base: Base
|
||||
private let maxLength: Int
|
||||
private var taken = 0
|
||||
@@ -908,7 +925,9 @@ public final class PrefixCursor<Base: Cursor>: Cursor {
|
||||
self.base = base
|
||||
self.maxLength = maxLength
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension PrefixCursor: Cursor {
|
||||
public func next() throws -> Base.Element? {
|
||||
if taken >= maxLength { return nil }
|
||||
taken += 1
|
||||
@@ -922,11 +941,9 @@ public final class PrefixCursor<Base: Cursor>: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor whose elements consist of the initial consecutive elements of
|
||||
/// some base cursor that satisfy a given predicate.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class PrefixWhileCursor<Base: Cursor>: Cursor {
|
||||
/// A `Cursor` whose elements consist of the initial consecutive elements of
|
||||
/// some `Base` cursor that satisfy a given predicate.
|
||||
public final class PrefixWhileCursor<Base: Cursor> {
|
||||
private let base: Base
|
||||
private let predicate: (Base.Element) throws -> Bool
|
||||
private var predicateHasFailed = false
|
||||
@@ -935,7 +952,9 @@ public final class PrefixWhileCursor<Base: Cursor>: Cursor {
|
||||
self.base = base
|
||||
self.predicate = predicate
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension PrefixWhileCursor: Cursor {
|
||||
public func next() throws -> Base.Element? {
|
||||
if !predicateHasFailed, let nextElement = try base.next() {
|
||||
if try predicate(nextElement) {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
+285
-165
@@ -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.
|
||||
@@ -79,11 +83,22 @@ extension Database {
|
||||
|
||||
// MARK: - Database Schema
|
||||
|
||||
/// Returns the current schema version.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_schema_version>
|
||||
public func schemaVersion() throws -> Int32 {
|
||||
try Int32.fetchOne(internalCachedStatement(sql: "PRAGMA schema_version"))!
|
||||
}
|
||||
|
||||
/// Clears the database schema cache.
|
||||
///
|
||||
/// You may need to clear the cache manually if the database schema is
|
||||
/// modified by another connection.
|
||||
/// If the database schema is modified by another SQLite connection to the
|
||||
/// same database file, your application may need to call this method in
|
||||
/// order to avoid undesired consequences.
|
||||
public func clearSchemaCache() {
|
||||
// TODO: can't we automatically clear the cache for writer connection,
|
||||
// just as we do for DatabasePool reader connections?
|
||||
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
schemaCache.clear()
|
||||
|
||||
@@ -102,7 +117,7 @@ extension Database {
|
||||
// at offset 40 of the database header:
|
||||
// <https://sqlite.org/pragma.html#pragma_schema_version>
|
||||
// <https://sqlite.org/fileformat2.html#database_header>
|
||||
let schemaVersion = try Int32.fetchOne(internalCachedStatement(sql: "PRAGMA schema_version"))
|
||||
let schemaVersion = try self.schemaVersion()
|
||||
if lastSchemaVersion != schemaVersion {
|
||||
lastSchemaVersion = schemaVersion
|
||||
clearSchemaCache()
|
||||
@@ -199,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)
|
||||
}
|
||||
|
||||
@@ -220,7 +235,7 @@ extension Database {
|
||||
|
||||
/// Returns whether a table is an internal GRDB table.
|
||||
///
|
||||
/// Those are tables whose name begins with "grdb_".
|
||||
/// Those are tables whose name begins with `grdb_`.
|
||||
public static func isGRDBInternalTable(_ tableName: String) -> Bool {
|
||||
tableName.starts(with: "grdb_")
|
||||
}
|
||||
@@ -253,7 +268,9 @@ extension Database {
|
||||
/// table has no explicit primary key, the result is the hidden
|
||||
/// "rowid" column.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
|
||||
/// such table exists in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo {
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try primaryKey(TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
@@ -374,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
|
||||
@@ -413,7 +430,9 @@ extension Database {
|
||||
/// the columns contain the primary key or a unique index, use
|
||||
/// ``table(_:hasUniqueKey:)``.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
|
||||
/// such table exists in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func indexes(on tableName: String) throws -> [IndexInfo] {
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try indexes(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
@@ -473,18 +492,25 @@ extension Database {
|
||||
return indexes
|
||||
}
|
||||
|
||||
/// True if a sequence of columns uniquely identifies a row, that is to say
|
||||
/// if the columns contain the primary key, or a unique index.
|
||||
/// Returns whether a sequence of columns uniquely identifies a row.
|
||||
///
|
||||
/// The result is true if and only if the primary key, or a unique index, is
|
||||
/// included in the sequence.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c);
|
||||
/// // CREATE UNIQUE INDEX i ON t(a, b);
|
||||
/// try db.table("t", hasUniqueKey: ["id"]) // true
|
||||
/// try db.table("t", hasUniqueKey: ["a", "b"]) // true
|
||||
/// try db.table("t", hasUniqueKey: ["c"]) // false
|
||||
/// try db.table("t", hasUniqueKey: ["id", "a"]) // true
|
||||
/// try db.table("t", hasUniqueKey: ["id", "a", "b", "c"]) // true
|
||||
/// ```swift
|
||||
/// // One table with one primary key (id), and a unique index (a, b):
|
||||
/// //
|
||||
/// // > CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c);
|
||||
/// // > CREATE UNIQUE INDEX i ON t(a, b);
|
||||
/// try db.table("t", hasUniqueKey: ["id"]) // true
|
||||
/// try db.table("t", hasUniqueKey: ["a", "b"]) // true
|
||||
/// try db.table("t", hasUniqueKey: ["b", "a"]) // true
|
||||
/// try db.table("t", hasUniqueKey: ["c"]) // false
|
||||
/// try db.table("t", hasUniqueKey: ["id", "a"]) // true
|
||||
/// try db.table("t", hasUniqueKey: ["id", "a", "b", "c"]) // true
|
||||
/// ```
|
||||
public func table<Columns>(
|
||||
_ tableName: String,
|
||||
hasUniqueKey columns: Columns)
|
||||
@@ -494,9 +520,11 @@ extension Database {
|
||||
try columnsForUniqueKey(Array(columns), in: tableName) != nil
|
||||
}
|
||||
|
||||
/// The foreign keys defined on table named `tableName`.
|
||||
/// Returns the foreign keys defined on table named `tableName`.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
|
||||
/// such table exists in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo] {
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try foreignKeys(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
@@ -577,6 +605,10 @@ extension Database {
|
||||
}
|
||||
|
||||
/// Returns a cursor over foreign key violations in the table.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
|
||||
/// such table exists in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func foreignKeyViolations(in tableName: String) throws -> RecordCursor<ForeignKeyViolation> {
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if try exists(type: .table, name: tableName, in: schemaIdentifier) {
|
||||
@@ -592,14 +624,26 @@ extension Database {
|
||||
""")
|
||||
}
|
||||
|
||||
/// Throws a DatabaseError of extended code `SQLITE_CONSTRAINT_FOREIGNKEY`
|
||||
/// if there exists a foreign key violation in the database.
|
||||
/// Throws an error if there exists a foreign key violation in the database.
|
||||
///
|
||||
/// On the first foreign key violation found in the database, this method
|
||||
/// throws a ``DatabaseError`` with extended code
|
||||
/// `SQLITE_CONSTRAINT_FOREIGNKEY`.
|
||||
///
|
||||
/// If you are looking for the list of foreign key violations, prefer
|
||||
/// ``foreignKeyViolations()`` instead.
|
||||
public func checkForeignKeys() throws {
|
||||
try checkForeignKeys(from: foreignKeyViolations())
|
||||
}
|
||||
|
||||
/// Throws a DatabaseError of extended code `SQLITE_CONSTRAINT_FOREIGNKEY`
|
||||
/// if there exists a foreign key violation in the table.
|
||||
/// Throws an error if there exists a foreign key violation in the table.
|
||||
///
|
||||
/// On the first foreign key violation found in the table, this method
|
||||
/// throws a ``DatabaseError`` with extended code
|
||||
/// `SQLITE_CONSTRAINT_FOREIGNKEY`.
|
||||
///
|
||||
/// If you are looking for the list of foreign key violations, prefer
|
||||
/// ``foreignKeyViolations(in:)`` instead.
|
||||
public func checkForeignKeys(in tableName: String) throws {
|
||||
try checkForeignKeys(from: foreignKeyViolations(in: tableName))
|
||||
}
|
||||
@@ -613,7 +657,9 @@ extension Database {
|
||||
/// Returns the actual name of the database table, or nil if the table does
|
||||
/// not exist.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
|
||||
/// such table exists in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
func canonicalTableName(_ tableName: String) throws -> String? {
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try schema(schemaIdentifier).canonicalName(tableName, ofType: .table) {
|
||||
@@ -635,9 +681,11 @@ extension Database {
|
||||
|
||||
extension Database {
|
||||
|
||||
/// The columns in the table, or view, named `tableName`.
|
||||
/// Returns the columns in a table or a view.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
|
||||
/// such table or view with this name exists in the main or temp schema, or
|
||||
/// in an attached database.
|
||||
public func columns(in tableName: String) throws -> [ColumnInfo] {
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try columns(in: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
@@ -794,43 +842,29 @@ extension Database {
|
||||
}
|
||||
}
|
||||
|
||||
/// A column of a database table.
|
||||
/// Information about a column of a database table.
|
||||
///
|
||||
/// This type closely matches the information returned by the
|
||||
/// `table_info` and `table_xinfo` pragmas.
|
||||
/// You get `ColumnInfo` instances with the ``Database/columns(in:)``
|
||||
/// `Database` method.
|
||||
///
|
||||
/// sqlite> CREATE TABLE player (
|
||||
/// ...> id INTEGER PRIMARY KEY,
|
||||
/// ...> firstName TEXT,
|
||||
/// ...> lastName TEXT);
|
||||
/// sqlite> PRAGMA table_info(player);
|
||||
/// cid name type notnull dflt_value pk
|
||||
/// ------ ---------- ---------- ---------- ---------- -----
|
||||
/// 0 id INTEGER 0 1
|
||||
/// 1 firstName TEXT 0 0
|
||||
/// 2 lastName TEXT 0 0
|
||||
/// sqlite> PRAGMA table_xinfo(player);
|
||||
/// cid name type notnull dflt_value pk hidden
|
||||
/// ------ ---------- ---------- ---------- ---------- ----- ----------
|
||||
/// 0 id INTEGER 0 1 0
|
||||
/// 1 firstName TEXT 0 0 0
|
||||
/// 2 lastName TEXT 0 0 0
|
||||
/// Related SQLite documentation:
|
||||
///
|
||||
/// See `Database.columns(in:)` and <https://www.sqlite.org/pragma.html#pragma_table_info>
|
||||
/// - [pragma `table_info`](https://www.sqlite.org/pragma.html#pragma_table_info)
|
||||
/// - [pragma `table_xinfo`](https://www.sqlite.org/pragma.html#pragma_table_xinfo)
|
||||
public struct ColumnInfo: FetchableRecord {
|
||||
let cid: Int
|
||||
let hidden: Int?
|
||||
|
||||
/// The column name
|
||||
/// The column name.
|
||||
public let name: String
|
||||
|
||||
/// The column data type
|
||||
/// The column data type.
|
||||
///
|
||||
/// The casing of this string depends on the SQLite version: make sure you
|
||||
/// process this string in a case-insensitive way.
|
||||
public let type: String
|
||||
|
||||
/// True if and only if the column is constrained to be not null.
|
||||
/// A boolean value indicating if the column is constrained to be not null.
|
||||
public let isNotNull: Bool
|
||||
|
||||
/// The SQL snippet that defines the default value, if any.
|
||||
@@ -841,31 +875,34 @@ public struct ColumnInfo: FetchableRecord {
|
||||
/// expression may be a literal, as `1`, or `'foo'`. It may also contain a
|
||||
/// non-constant expression such as `CURRENT_TIMESTAMP`.
|
||||
///
|
||||
/// For more information, see
|
||||
/// <https://www.sqlite.org/lang_createtable.html#the_default_clause>.
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#the_default_clause>.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try db.execute(sql: """
|
||||
/// CREATE TABLE player(
|
||||
/// id INTEGER PRIMARY KEY,
|
||||
/// name TEXT DEFAULT 'Anonymous',
|
||||
/// score INT DEFAULT 0,
|
||||
/// creationDate DATE DEFAULT CURRENT_TIMESTAMP
|
||||
/// )
|
||||
/// """)
|
||||
/// let columnInfos = try db.columns(in: "player")
|
||||
/// columnInfos[0].defaultValueSQL // nil
|
||||
/// columnInfos[1].defaultValueSQL // "'Anonymous'"
|
||||
/// columnInfos[2].defaultValueSQL // "0"
|
||||
/// columnInfos[3].defaultValueSQL // "CURRENT_TIMESTAMP"
|
||||
/// ```swift
|
||||
/// try db.execute(sql: """
|
||||
/// CREATE TABLE player(
|
||||
/// id INTEGER PRIMARY KEY,
|
||||
/// name TEXT DEFAULT 'Anonymous',
|
||||
/// score INT DEFAULT 0,
|
||||
/// creationDate DATE DEFAULT CURRENT_TIMESTAMP
|
||||
/// )
|
||||
/// """)
|
||||
/// let columnInfos = try db.columns(in: "player")
|
||||
/// columnInfos[0].defaultValueSQL // nil
|
||||
/// columnInfos[1].defaultValueSQL // "'Anonymous'"
|
||||
/// columnInfos[2].defaultValueSQL // "0"
|
||||
/// columnInfos[3].defaultValueSQL // "CURRENT_TIMESTAMP"
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#the_default_clause>.
|
||||
public let defaultValueSQL: String?
|
||||
|
||||
/// For columns that are part of the primary key, this is the one-based
|
||||
/// index of the column in the primary key. For other columns, it is zero.
|
||||
/// The one-based index of the column in the primary key.
|
||||
///
|
||||
/// For columns that are not part of the primary key, it is zero.
|
||||
public let primaryKeyIndex: Int
|
||||
|
||||
/// :nodoc:
|
||||
public init(row: Row) {
|
||||
cid = row["cid"]
|
||||
name = row["name"]
|
||||
@@ -877,13 +914,17 @@ public struct ColumnInfo: FetchableRecord {
|
||||
}
|
||||
}
|
||||
|
||||
/// An index on a database table.
|
||||
/// Information about an index.
|
||||
///
|
||||
/// See `Database.indexes(on:)`
|
||||
/// You get `IndexInfo` instances with the ``Database/indexes(on:)``
|
||||
/// `Database` method.
|
||||
///
|
||||
/// Related SQLite documentation:
|
||||
///
|
||||
/// - [pragma `index_list`](https://www.sqlite.org/pragma.html#pragma_index_list)
|
||||
/// - [pragma `index_info`](https://www.sqlite.org/pragma.html#pragma_index_info)
|
||||
public struct IndexInfo {
|
||||
/// The origin of an index.
|
||||
///
|
||||
/// See ``Database/indexes(on:)``.
|
||||
public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible {
|
||||
public var rawValue: String
|
||||
|
||||
@@ -891,72 +932,100 @@ public struct IndexInfo {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
/// An index created from a CREATE INDEX statement.
|
||||
/// An index created from a `CREATE INDEX` statement.
|
||||
public static let createIndex = Origin(rawValue: "c")
|
||||
|
||||
/// An index created by a UNIQUE constraint.
|
||||
/// An index created by a `UNIQUE` constraint.
|
||||
public static let uniqueConstraint = Origin(rawValue: "u")
|
||||
|
||||
/// An index created by a PRIMARY KEY constraint.
|
||||
/// An index created by a `PRIMARY KEY` constraint.
|
||||
public static let primaryKeyConstraint = Origin(rawValue: "pk")
|
||||
}
|
||||
|
||||
/// The name of the index
|
||||
/// The name of the index.
|
||||
public let name: String
|
||||
|
||||
/// The indexed columns
|
||||
/// The indexed columns.
|
||||
public let columns: [String]
|
||||
|
||||
/// True if the index is unique
|
||||
/// A boolean value indicating if the index is unique.
|
||||
public let isUnique: Bool
|
||||
|
||||
/// The origin of the index
|
||||
/// The origin of the index.
|
||||
public let origin: Origin
|
||||
}
|
||||
|
||||
/// A foreign key violation produced by PRAGMA foreign_key_check
|
||||
/// A foreign key violation.
|
||||
///
|
||||
/// See <https://www.sqlite.org/pragma.html#pragma_foreign_key_check>
|
||||
public struct ForeignKeyViolation: FetchableRecord, CustomStringConvertible {
|
||||
/// The name of the table that contains the `REFERENCES` clause
|
||||
/// You get instances of `ForeignKeyViolation` from the `Database` methods
|
||||
/// ``Database/foreignKeyViolations()`` and
|
||||
/// ``Database/foreignKeyViolations(in:)`` methods.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read {
|
||||
/// let violations = try db.foreignKeyViolations()
|
||||
/// while let violation = try violations.next() {
|
||||
/// // The name of the table that contains the `REFERENCES` clause
|
||||
/// violation.originTable
|
||||
///
|
||||
/// // The rowid of the row that contains the invalid `REFERENCES` clause, or
|
||||
/// // nil if the origin table is a `WITHOUT ROWID` table.
|
||||
/// violation.originRowID
|
||||
///
|
||||
/// // The name of the table that is referred to.
|
||||
/// violation.destinationTable
|
||||
///
|
||||
/// // The id of the specific foreign key constraint that failed. This id
|
||||
/// // matches `ForeignKeyInfo.id`. See `Database.foreignKeys(on:)` for more
|
||||
/// // information.
|
||||
/// violation.foreignKeyId
|
||||
///
|
||||
/// // Plain description:
|
||||
/// // "FOREIGN KEY constraint violation - from player to team, in rowid 1"
|
||||
/// String(describing: violation)
|
||||
///
|
||||
/// // Rich description:
|
||||
/// // "FOREIGN KEY constraint violation - from player(teamId) to team(id),
|
||||
/// // in [id:1 teamId:2 name:"O'Brien" score:1000]"
|
||||
/// try violation.failureDescription(db)
|
||||
///
|
||||
/// // Turn violation into a DatabaseError
|
||||
/// throw violation.databaseError(db)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_foreign_key_check>
|
||||
public struct ForeignKeyViolation {
|
||||
/// The name of the table that contains the foreign key.
|
||||
public var originTable: String
|
||||
|
||||
/// The rowid of the row that contains the invalid `REFERENCES` clause, or
|
||||
/// nil if the origin table is a `WITHOUT ROWID` table.
|
||||
/// The rowid of the row that contains the foreign key violation.
|
||||
///
|
||||
/// If it nil if the origin table is a `WITHOUT ROWID` table.
|
||||
public var originRowID: Int64?
|
||||
|
||||
/// The name of the table that is referred to.
|
||||
public var destinationTable: String
|
||||
|
||||
/// The id of the specific foreign key constraint that failed. This id
|
||||
/// matches `ForeignKeyInfo.id`. See `Database.foreignKeys(on:)` for more
|
||||
/// information.
|
||||
/// The id of the foreign key constraint that failed.
|
||||
///
|
||||
/// This id matches the ``ForeignKeyInfo/id`` property in
|
||||
/// ``ForeignKeyInfo``. See ``Database/foreignKeys(on:)``.
|
||||
public var foreignKeyId: Int
|
||||
|
||||
public init(row: Row) {
|
||||
originTable = row[0]
|
||||
originRowID = row[1]
|
||||
destinationTable = row[2]
|
||||
foreignKeyId = row[3]
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
if let originRowID = originRowID {
|
||||
return """
|
||||
FOREIGN KEY constraint violation - from \(originTable) to \(destinationTable), \
|
||||
in rowid \(originRowID)
|
||||
"""
|
||||
} else {
|
||||
return """
|
||||
FOREIGN KEY constraint violation - from \(originTable) to \(destinationTable)
|
||||
"""
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a precise description of the foreign key violation.
|
||||
/// A precise description of the foreign key violation.
|
||||
///
|
||||
/// For example: 'FOREIGN KEY constraint violation - from player(teamId) to team(id),
|
||||
/// in [id:1 teamId:2 name:"O'Brien" score: 1000]'
|
||||
/// For example:
|
||||
///
|
||||
/// ```
|
||||
/// FOREIGN KEY constraint violation - from player(teamId) to team(id),
|
||||
/// in [id:1 teamId:2 name:"O'Brien" score: 1000]
|
||||
/// ```
|
||||
///
|
||||
/// See also ``description``.
|
||||
public func failureDescription(_ db: Database) throws -> String {
|
||||
// Grab detailed information, if possible, for better error message
|
||||
let originRow = try originRowID.flatMap { rowid in
|
||||
@@ -967,7 +1036,7 @@ public struct ForeignKeyViolation: FetchableRecord, CustomStringConvertible {
|
||||
})
|
||||
|
||||
var description: String
|
||||
if let foreignKey = foreignKey {
|
||||
if let foreignKey {
|
||||
description = """
|
||||
FOREIGN KEY constraint violation - \
|
||||
from \(originTable)(\(foreignKey.originColumns.joined(separator: ", "))) \
|
||||
@@ -977,16 +1046,18 @@ public struct ForeignKeyViolation: FetchableRecord, CustomStringConvertible {
|
||||
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)"
|
||||
}
|
||||
|
||||
return description
|
||||
}
|
||||
|
||||
/// Returns a DatabaseError of extended code `SQLITE_CONSTRAINT_FOREIGNKEY`
|
||||
/// Converts the violation into a ``DatabaseError``.
|
||||
///
|
||||
/// The returned error has the extended code `SQLITE_CONSTRAINT_FOREIGNKEY`.
|
||||
public func databaseError(_ db: Database) -> DatabaseError {
|
||||
// Grab detailed information, if possible, for better error message.
|
||||
// If detailed information is not available, fallback to plain description.
|
||||
@@ -997,45 +1068,85 @@ public struct ForeignKeyViolation: FetchableRecord, CustomStringConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Primary keys are returned from the Database.primaryKey(_:) method.
|
||||
extension ForeignKeyViolation: FetchableRecord {
|
||||
public init(row: Row) {
|
||||
originTable = row[0]
|
||||
originRowID = row[1]
|
||||
destinationTable = row[2]
|
||||
foreignKeyId = row[3]
|
||||
}
|
||||
}
|
||||
|
||||
extension ForeignKeyViolation: CustomStringConvertible {
|
||||
/// A description of the foreign key violation.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```
|
||||
/// FOREIGN KEY constraint violation - from player to team, in rowid 1
|
||||
/// ```
|
||||
///
|
||||
/// See also ``failureDescription(_:)``.
|
||||
public var description: String {
|
||||
if let originRowID {
|
||||
return """
|
||||
FOREIGN KEY constraint violation - from \(originTable) to \(destinationTable), \
|
||||
in rowid \(originRowID)
|
||||
"""
|
||||
} else {
|
||||
return """
|
||||
FOREIGN KEY constraint violation - from \(originTable) to \(destinationTable)
|
||||
"""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Information about a primary key.
|
||||
///
|
||||
/// You get `PrimaryKeyInfo` instances with the ``Database/primaryKey(_:)``
|
||||
/// `Database` method.
|
||||
///
|
||||
/// When the table's primary key is the rowid:
|
||||
///
|
||||
/// // CREATE TABLE item (name TEXT)
|
||||
/// let pk = try db.primaryKey("item")
|
||||
/// pk.columns // ["rowid"]
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // true
|
||||
/// ```swift
|
||||
/// // CREATE TABLE item (name TEXT)
|
||||
/// let pk = try db.primaryKey("item")
|
||||
/// pk.columns // ["rowid"]
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // true
|
||||
///
|
||||
/// // CREATE TABLE citizen (
|
||||
/// // id INTEGER PRIMARY KEY,
|
||||
/// // name TEXT
|
||||
/// // )
|
||||
/// let pk = try db.primaryKey("citizen")!
|
||||
/// pk.columns // ["id"]
|
||||
/// pk.rowIDColumn // "id"
|
||||
/// pk.isRowID // true
|
||||
/// // CREATE TABLE citizen (
|
||||
/// // id INTEGER PRIMARY KEY,
|
||||
/// // name TEXT
|
||||
/// // )
|
||||
/// let pk = try db.primaryKey("citizen")!
|
||||
/// pk.columns // ["id"]
|
||||
/// pk.rowIDColumn // "id"
|
||||
/// pk.isRowID // true
|
||||
/// ```
|
||||
///
|
||||
/// When the table's primary key is not the rowid:
|
||||
///
|
||||
/// // CREATE TABLE country (
|
||||
/// // isoCode TEXT NOT NULL PRIMARY KEY
|
||||
/// // name TEXT
|
||||
/// // )
|
||||
/// let pk = db.primaryKey("country")!
|
||||
/// pk.columns // ["isoCode"]
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // false
|
||||
/// ```swift
|
||||
/// // CREATE TABLE country (
|
||||
/// // isoCode TEXT NOT NULL PRIMARY KEY
|
||||
/// // name TEXT
|
||||
/// // )
|
||||
/// let pk = try db.primaryKey("country")!
|
||||
/// pk.columns // ["isoCode"]
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // false
|
||||
///
|
||||
/// // CREATE TABLE citizenship (
|
||||
/// // citizenID INTEGER NOT NULL REFERENCES citizen(id)
|
||||
/// // countryIsoCode TEXT NOT NULL REFERENCES country(isoCode)
|
||||
/// // PRIMARY KEY (citizenID, countryIsoCode)
|
||||
/// // )
|
||||
/// let pk = db.primaryKey("citizenship")!
|
||||
/// pk.columns // ["citizenID", "countryIsoCode"]
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // false
|
||||
/// // CREATE TABLE citizenship (
|
||||
/// // citizenID INTEGER NOT NULL REFERENCES citizen(id)
|
||||
/// // countryIsoCode TEXT NOT NULL REFERENCES country(isoCode)
|
||||
/// // PRIMARY KEY (citizenID, countryIsoCode)
|
||||
/// // )
|
||||
/// let pk = try db.primaryKey("citizenship")!
|
||||
/// pk.columns // ["citizenID", "countryIsoCode"]
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // false
|
||||
/// ```
|
||||
public struct PrimaryKeyInfo {
|
||||
private enum Impl {
|
||||
/// The hidden rowID.
|
||||
@@ -1063,7 +1174,7 @@ public struct PrimaryKeyInfo {
|
||||
|
||||
static let hiddenRowID = PrimaryKeyInfo(impl: .hiddenRowID)
|
||||
|
||||
/// The columns in the primary key; this array is never empty.
|
||||
/// The columns in the primary key. This array is never empty.
|
||||
public var columns: [String] {
|
||||
switch impl {
|
||||
case .hiddenRowID:
|
||||
@@ -1075,7 +1186,8 @@ public struct PrimaryKeyInfo {
|
||||
}
|
||||
}
|
||||
|
||||
/// When not nil, the name of the column that contains the INTEGER PRIMARY KEY.
|
||||
/// When not nil, the name of the column that contains the
|
||||
/// `INTEGER PRIMARY KEY`.
|
||||
public var rowIDColumn: String? {
|
||||
switch impl {
|
||||
case .hiddenRowID:
|
||||
@@ -1087,7 +1199,7 @@ public struct PrimaryKeyInfo {
|
||||
}
|
||||
}
|
||||
|
||||
/// When true, the primary key is the rowid:
|
||||
/// A boolean value indicating if the primary key is the rowid.
|
||||
public var isRowID: Bool {
|
||||
switch impl {
|
||||
case .hiddenRowID:
|
||||
@@ -1099,7 +1211,9 @@ public struct PrimaryKeyInfo {
|
||||
}
|
||||
}
|
||||
|
||||
/// When false, the table is a WITHOUT ROWID table
|
||||
/// A boolean value indicating if the table has a rowid.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/withoutrowid.html>
|
||||
var tableHasRowID: Bool {
|
||||
switch impl {
|
||||
case .hiddenRowID:
|
||||
@@ -1111,7 +1225,7 @@ public struct PrimaryKeyInfo {
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of the fastest primary key column
|
||||
/// The name of the fastest primary key column.
|
||||
///
|
||||
/// Returns nil for WITHOUT ROWID tables with a multi-columns primary key
|
||||
var fastPrimaryKeyColumn: String? {
|
||||
@@ -1140,30 +1254,34 @@ public struct PrimaryKeyInfo {
|
||||
}
|
||||
}
|
||||
|
||||
/// You get foreign keys from table names, with the
|
||||
/// `foreignKeys(on:)` method.
|
||||
/// Information about a foreign key.
|
||||
///
|
||||
/// You get `ForeignKeyInfo` instances with the ``Database/foreignKeys(on:)``
|
||||
/// `Database` method.
|
||||
///
|
||||
/// Related SQLite documentation: [pragma `foreign_key_list`](https://www.sqlite.org/pragma.html#pragma_foreign_key_list).
|
||||
public struct ForeignKeyInfo {
|
||||
/// The first column in the output of the `foreign_key_list` pragma
|
||||
/// The first column in the output of the `foreign_key_list` pragma.
|
||||
public var id: Int
|
||||
|
||||
/// The name of the destination table
|
||||
/// The name of the destination table.
|
||||
public let destinationTable: String
|
||||
|
||||
/// The column to column mapping
|
||||
/// The column to column mapping.
|
||||
public let mapping: [(origin: String, destination: String)]
|
||||
|
||||
/// The origin columns
|
||||
/// The origin columns.
|
||||
public var originColumns: [String] {
|
||||
mapping.map(\.origin)
|
||||
}
|
||||
|
||||
/// The destination columns
|
||||
/// The destination columns.
|
||||
public var destinationColumns: [String] {
|
||||
mapping.map(\.destination)
|
||||
}
|
||||
}
|
||||
|
||||
/// See <https://www.sqlite.org/pragma.html#pragma_table_list>
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_table_list>
|
||||
struct TableInfo: FetchableRecord {
|
||||
struct Kind: RawRepresentable {
|
||||
var rawValue: String
|
||||
@@ -1210,13 +1328,6 @@ enum SchemaObjectType: String {
|
||||
struct SchemaInfo: Equatable {
|
||||
private var objects: Set<SchemaObject>
|
||||
|
||||
/// - parameter masterTable: "sqlite_master" or "sqlite_temp_master"
|
||||
init(_ db: Database, masterTableName: String) throws { // swiftlint:disable:this inclusive_language
|
||||
objects = try SchemaObject.fetchSet(db, sql: """
|
||||
SELECT type, name, tbl_name, sql FROM \(masterTableName)
|
||||
""")
|
||||
}
|
||||
|
||||
/// Returns whether there exists a object of given type with this name
|
||||
/// (case-insensitive).
|
||||
func containsObjectNamed(_ name: String, ofType type: SchemaObjectType) -> Bool {
|
||||
@@ -1245,3 +1356,12 @@ struct SchemaInfo: Equatable {
|
||||
var sql: String?
|
||||
}
|
||||
}
|
||||
|
||||
extension SchemaInfo {
|
||||
/// - parameter masterTable: "sqlite_master" or "sqlite_temp_master"
|
||||
init(_ db: Database, masterTableName: String) throws { // swiftlint:disable:this inclusive_language
|
||||
objects = try SchemaObject.fetchSet(db, sql: """
|
||||
SELECT type, name, tbl_name, sql FROM \(masterTableName)
|
||||
""")
|
||||
}
|
||||
}
|
||||
+213
-160
@@ -8,17 +8,19 @@ extension Database {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
/// ```swift
|
||||
/// let statement = try db.makeStatement(sql: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// let statement = try db.makeStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - parameter sql: An SQL string.
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func makeStatement(sql: String) throws -> Statement {
|
||||
try makeStatement(sql: sql, prepFlags: 0)
|
||||
}
|
||||
@@ -27,33 +29,38 @@ extension Database {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let statement = try db.makeStatement(literal: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
/// ```swift
|
||||
/// let statement = try db.makeStatement(literal: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// let statement = try db.makeStatement(literal: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// let statement = try db.makeStatement(literal: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
/// In the provided literal, no argument must be set, or all arguments must
|
||||
/// be set. An error is raised otherwise. For example:
|
||||
///
|
||||
/// // OK
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// // OK
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
/// // NOT OK (first argument is not set, but second is)
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter sqlLiteral: An ``SQL`` literal.
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func makeStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
let (sql, arguments) = try sqlLiteral.build(self)
|
||||
let statement = try makeStatement(sql: sql)
|
||||
@@ -72,11 +79,11 @@ extension Database {
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - parameter sql: An SQL string.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see <http://www.sqlite.org/c3ref/prepare.html>)
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
func makeStatement(sql: String, prepFlags: CUnsignedInt) throws -> Statement {
|
||||
let statements = SQLStatementCursor(database: self, sql: sql, arguments: nil, prepFlags: prepFlags)
|
||||
guard let statement = try statements.next() else {
|
||||
@@ -113,20 +120,22 @@ extension Database {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let statement = try db.cachedStatement(sql: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
/// ```swift
|
||||
/// let statement = try db.cachedStatement(sql: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// let statement = try db.cachedStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// let statement = try db.cachedStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```
|
||||
///
|
||||
/// The returned statement may have already been used: it may or may not
|
||||
/// contain values for its eventual arguments.
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - parameter sql: An SQL string.
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func cachedStatement(sql: String) throws -> Statement {
|
||||
try publicStatementCache.statement(sql)
|
||||
}
|
||||
@@ -135,33 +144,38 @@ extension Database {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let statement = try db.cachedStatement(literal: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
/// ```swift
|
||||
/// let statement = try db.cachedStatement(literal: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// let statement = try db.cachedStatement(literal: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// let statement = try db.cachedStatement(literal: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
/// In the provided literal, no argument must be set, or all arguments must
|
||||
/// be set. An error is raised otherwise. For example:
|
||||
///
|
||||
/// // OK
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// // OK
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
/// // NOT OK (first argument is not set, but second is)
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter sqlLiteral: An ``SQL`` literal.
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func cachedStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
let (sql, arguments) = try sqlLiteral.build(self)
|
||||
let statement = try cachedStatement(sql: sql)
|
||||
@@ -177,83 +191,95 @@ extension Database {
|
||||
try internalStatementCache.statement(sql)
|
||||
}
|
||||
|
||||
/// Returns a cursor of all SQL statements separated by semi-colons.
|
||||
/// Returns a cursor of prepared statements.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let statements = try db.allStatements(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// """, arguments: ["Arthur", "Barbara", "O'Brien"])
|
||||
/// while let statement = try statements.next() {
|
||||
/// try statement.execute()
|
||||
/// }
|
||||
/// ```swift
|
||||
/// let statements = try db.allStatements(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// """, arguments: ["Arthur", "Barbara", "O'Brien"])
|
||||
/// while let statement = try statements.next() {
|
||||
/// try statement.execute()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The `arguments` parameter must be nil, or all arguments must be set. The
|
||||
/// returned cursor will throw an error otherwise. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // OK
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
///
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """, arguments: [1000, 1000])
|
||||
///
|
||||
/// // NOT OK (first argument is set, but second is not)
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """, arguments: [1000])
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - sql: An SQL string.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - returns: A cursor of `Statement`
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
/// - precondition: Arguments must be nil, or all arguments must be set.
|
||||
/// The returned cursor will throw an error otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """, arguments: [1000, 1000])
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """, arguments: [1000])
|
||||
/// - returns: A cursor of prepared ``Statement``.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func allStatements(sql: String, arguments: StatementArguments? = nil)
|
||||
throws -> SQLStatementCursor
|
||||
{
|
||||
SQLStatementCursor(database: self, sql: sql, arguments: arguments)
|
||||
}
|
||||
|
||||
/// Returns a cursor of all SQL statements separated by semi-colons.
|
||||
/// Returns a cursor of prepared statements.
|
||||
///
|
||||
/// Literals allow you to safely embed raw values in your SQL, without any
|
||||
/// risk of syntax errors or SQL injection:
|
||||
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// let statements = try db.allStatements(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"));
|
||||
/// INSERT INTO player (name) VALUES (\("Barbara"));
|
||||
/// INSERT INTO player (name) VALUES (\("O'Brien"));
|
||||
/// """)
|
||||
/// while let statement = try statements.next() {
|
||||
/// try statement.execute()
|
||||
/// }
|
||||
/// ```swift
|
||||
/// let statements = try db.allStatements(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"));
|
||||
/// INSERT INTO player (name) VALUES (\("Barbara"));
|
||||
/// INSERT INTO player (name) VALUES (\("O'Brien"));
|
||||
/// """)
|
||||
/// while let statement = try statements.next() {
|
||||
/// try statement.execute()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A cursor of `Statement`
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// The returned cursor will throw an error otherwise.
|
||||
/// In the provided literal, no argument must be set, or all arguments must
|
||||
/// be set. The returned cursor will throw an error otherwise. For example:
|
||||
///
|
||||
/// // OK
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < \(1000);
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000);
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// // OK
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < \(1000);
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < \(1000);
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000);
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK (first argument is set, but second is not)
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < \(1000);
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter sqlLiteral: An ``SQL`` literal.
|
||||
/// - returns: A cursor of prepared ``Statement``.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func allStatements(literal sqlLiteral: SQL) throws -> SQLStatementCursor {
|
||||
let context = SQLGenerationContext(self)
|
||||
let sql = try sqlLiteral.sql(context)
|
||||
@@ -263,45 +289,49 @@ extension Database {
|
||||
return SQLStatementCursor(database: self, sql: sql, arguments: arguments)
|
||||
}
|
||||
|
||||
/// Executes one or several SQL statements, separated by semi-colons.
|
||||
/// Executes one or several SQL statements.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try db.execute(
|
||||
/// sql: "INSERT INTO player (name) VALUES (:name)",
|
||||
/// arguments: ["name": "Arthur"])
|
||||
/// ```swift
|
||||
/// try db.execute(
|
||||
/// sql: "INSERT INTO player (name) VALUES (:name)",
|
||||
/// arguments: ["name": "Arthur"])
|
||||
///
|
||||
/// try db.execute(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// """, arguments: ["Arthur", "Barbara", "O'Brien"])
|
||||
/// try db.execute(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// """, arguments: ["Arthur", "Barbara", "O'Brien"])
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - sql: An SQL string.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func execute(sql: String, arguments: StatementArguments = StatementArguments()) throws {
|
||||
try execute(literal: SQL(sql: sql, arguments: arguments))
|
||||
}
|
||||
|
||||
/// Executes one or several SQL statements, separated by semi-colons.
|
||||
/// Executes one or several SQL statements.
|
||||
///
|
||||
/// Literals allow you to safely embed raw values in your SQL, without any
|
||||
/// risk of syntax errors or SQL injection:
|
||||
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// try db.execute(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"))
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// try db.execute(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"))
|
||||
/// """)
|
||||
///
|
||||
/// try db.execute(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"));
|
||||
/// INSERT INTO player (name) VALUES (\("Barbara"));
|
||||
/// INSERT INTO player (name) VALUES (\("O'Brien"));
|
||||
/// """)
|
||||
/// try db.execute(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"));
|
||||
/// INSERT INTO player (name) VALUES (\("Barbara"));
|
||||
/// INSERT INTO player (name) VALUES (\("O'Brien"));
|
||||
/// """)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
/// - parameter sqlLiteral: An ``SQL`` literal.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func execute(literal sqlLiteral: SQL) throws {
|
||||
let statements = try allStatements(literal: sqlLiteral)
|
||||
while let statement = try statements.next() {
|
||||
@@ -310,8 +340,8 @@ extension Database {
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor over all statements in a SQL string.
|
||||
public class SQLStatementCursor: Cursor {
|
||||
/// A cursor over all statements in an SQL string.
|
||||
public class SQLStatementCursor {
|
||||
private let database: Database
|
||||
private let cString: ContiguousArray<CChar>
|
||||
private let prepFlags: CUnsignedInt
|
||||
@@ -329,7 +359,9 @@ public class SQLStatementCursor: Cursor {
|
||||
self.offset = 0
|
||||
self.arguments = arguments
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SQLStatementCursor: Cursor {
|
||||
public func next() throws -> Statement? {
|
||||
guard offset < cString.count - 1 /* trailing \0 */ else {
|
||||
// End of C string -> end of cursor.
|
||||
@@ -374,8 +406,8 @@ public class 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(
|
||||
@@ -399,9 +431,7 @@ extension Database {
|
||||
try checkForSuspensionViolation(from: statement)
|
||||
|
||||
// Record the database region selected by the statement execution.
|
||||
if isRecordingSelectedRegion {
|
||||
selectedRegion.formUnion(statement.databaseRegion)
|
||||
}
|
||||
try registerAccess(to: statement.databaseRegion)
|
||||
|
||||
// Database observation: prepare transaction observers.
|
||||
observationBroker?.statementWillExecute(statement)
|
||||
@@ -415,6 +445,8 @@ extension Database {
|
||||
clearSchemaCache()
|
||||
}
|
||||
|
||||
checkForAutocommitTransition()
|
||||
|
||||
// Database observation: cleanup
|
||||
try observationBroker?.statementDidExecute(statement)
|
||||
}
|
||||
@@ -430,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).
|
||||
@@ -451,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
|
||||
@@ -480,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)
|
||||
|
||||
+505
-233
File diff suppressed because it is too large.
Load diff
@@ -1,22 +1,27 @@
|
||||
/// An instance of `DatabaseBackupProgress` is passed to a callback of the
|
||||
/// `DatabaseReader.backup` or `Database.backup` methods to report
|
||||
/// database backup progress to the caller.
|
||||
/// Describe the progress of a database backup.
|
||||
///
|
||||
/// This is an advanced API for expert users. It is based directly on the SQLite
|
||||
/// [online backup API](https://www.sqlite.org/c3ref/backup_finish.html).
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/backup_finish.html>
|
||||
public struct DatabaseBackupProgress {
|
||||
/// Total page count is defined by the `sqlite3_backup_remaining` function
|
||||
/// The number of pages still to be backed up.
|
||||
///
|
||||
/// It is the result of the `sqlite3_backup_remaining` function.
|
||||
public let remainingPageCount: Int
|
||||
|
||||
/// Total page count is defined by the `sqlite3_backup_pagecount` function
|
||||
|
||||
/// The number of pages in the source database.
|
||||
///
|
||||
/// It is the result of the `sqlite3_backup_pagecount` function.
|
||||
public let totalPageCount: Int
|
||||
|
||||
/// Completed page count is defined as `sqlite3_backup_pagecount() - sqlite3_backup_remaining()`
|
||||
|
||||
/// The number of of backed up pages.
|
||||
///
|
||||
/// It is equal to `totalPageCount - remainingPageCount`.
|
||||
public var completedPageCount: Int {
|
||||
totalPageCount - remainingPageCount
|
||||
}
|
||||
|
||||
/// This property is true if and only if `sqlite3_backup_step()` returns
|
||||
/// `SQLITE_DONE`
|
||||
|
||||
/// A boolean value indicating whether the backup is complete.
|
||||
///
|
||||
/// It is true if and only if the last call the `sqlite3_backup_step` has
|
||||
/// returned `SQLITE_DONE`.
|
||||
public let isCompleted: Bool
|
||||
}
|
||||
@@ -1,21 +1,44 @@
|
||||
import Foundation
|
||||
|
||||
/// A Collation is a string comparison function used by SQLite.
|
||||
/// `DatabaseCollation` is a custom string comparison function used by SQLite.
|
||||
///
|
||||
/// See also ``Database/CollationName``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/datatype3.html#collating_sequences>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a Custom Collation
|
||||
///
|
||||
/// - ``init(_:function:)``
|
||||
/// - ``name``
|
||||
///
|
||||
/// ### Built-in Collations
|
||||
///
|
||||
/// - ``caseInsensitiveCompare``
|
||||
/// - ``localizedCaseInsensitiveCompare``
|
||||
/// - ``localizedCompare``
|
||||
/// - ``localizedStandardCompare``
|
||||
/// - ``unicodeCompare``
|
||||
public final class DatabaseCollation {
|
||||
/// The name of the collation
|
||||
/// The name of the collation.
|
||||
public let name: String
|
||||
let function: (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
|
||||
|
||||
/// Creates a collation.
|
||||
///
|
||||
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// db.add(collation: collation)
|
||||
/// try db.execute(sql: "CREATE TABLE file (name TEXT COLLATE localized_standard")
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// db.add(collation: collation)
|
||||
/// try db.execute(sql: "CREATE TABLE file (name TEXT COLLATE localized_standard")
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The function name.
|
||||
/// - name: The collation name.
|
||||
/// - function: A function that compares two strings.
|
||||
public init(_ name: String, function: @escaping (String, String) -> ComparisonResult) {
|
||||
self.name = name
|
||||
@@ -43,13 +66,11 @@ extension DatabaseCollation: Hashable {
|
||||
// implies hash equality) is thus non trivial. But it's not that
|
||||
// important, since this hashValue is only used when one adds
|
||||
// or removes a collation from a database connection.
|
||||
/// :nodoc:
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(0)
|
||||
}
|
||||
|
||||
/// Two collations are equal if they share the same name (case insensitive)
|
||||
/// :nodoc:
|
||||
public static func == (lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool {
|
||||
// See <https://www.sqlite.org/c3ref/create_collation.html>
|
||||
return sqlite3_stricmp(lhs.name, rhs.name) == 0
|
||||
|
||||
+165
-73
@@ -2,9 +2,9 @@ import Foundation
|
||||
|
||||
/// An SQLite result code.
|
||||
///
|
||||
/// See <https://www.sqlite.org/rescode.html>
|
||||
public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
|
||||
/// The raw SQLite result code
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/rescode.html>
|
||||
public struct ResultCode: RawRepresentable, Equatable {
|
||||
/// The raw SQLite result code.
|
||||
public let rawValue: CInt
|
||||
|
||||
/// Creates a `ResultCode` from a raw SQLite result code.
|
||||
@@ -12,11 +12,14 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
/// A result code limited to the least significant 8 bits of the receiver.
|
||||
/// See <https://www.sqlite.org/rescode.html> for more information.
|
||||
/// A primary result code limited to the least significant 8 bits.
|
||||
///
|
||||
/// let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY
|
||||
/// resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY
|
||||
/// resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true
|
||||
/// ```
|
||||
public var primaryResultCode: ResultCode {
|
||||
ResultCode(rawValue: rawValue & 0xFF)
|
||||
}
|
||||
@@ -28,11 +31,15 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
|
||||
/// Primary result codes match themselves and their extended result codes,
|
||||
/// while extended result codes match only themselves:
|
||||
///
|
||||
/// switch error.extendedResultCode {
|
||||
/// case .SQLITE_CONSTRAINT_FOREIGNKEY: // foreign key constraint error
|
||||
/// case .SQLITE_CONSTRAINT: // any other constraint error
|
||||
/// default: // any other database error
|
||||
/// }
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// switch error.extendedResultCode {
|
||||
/// case .SQLITE_CONSTRAINT_FOREIGNKEY: // foreign key constraint error
|
||||
/// case .SQLITE_CONSTRAINT: // any other constraint error
|
||||
/// default: // any other database error
|
||||
/// }
|
||||
/// ```
|
||||
public static func ~= (pattern: ResultCode, code: ResultCode) -> Bool {
|
||||
if pattern.isPrimary {
|
||||
return pattern == code.primaryResultCode
|
||||
@@ -166,30 +173,32 @@ extension ResultCode {
|
||||
/// Primary result codes match themselves and their extended result codes,
|
||||
/// while extended result codes match only themselves.
|
||||
///
|
||||
/// do {
|
||||
/// try ...
|
||||
/// } catch ResultCode.SQLITE_CONSTRAINT_FOREIGNKEY {
|
||||
/// // foreign key constraint error
|
||||
/// } catch ResultCode.SQLITE_CONSTRAINT {
|
||||
/// // any other constraint error
|
||||
/// } catch {
|
||||
/// // any other database error
|
||||
/// }
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// try ...
|
||||
/// } catch ResultCode.SQLITE_CONSTRAINT_FOREIGNKEY {
|
||||
/// // foreign key constraint error
|
||||
/// } catch ResultCode.SQLITE_CONSTRAINT {
|
||||
/// // any other constraint error
|
||||
/// } catch {
|
||||
/// // any other database error
|
||||
/// }
|
||||
/// ```
|
||||
public static func ~= (lhs: Self, rhs: Error) -> Bool {
|
||||
guard let error = rhs as? DatabaseError else { return false }
|
||||
return lhs ~= error.extendedResultCode
|
||||
}
|
||||
}
|
||||
|
||||
// CustomStringConvertible
|
||||
extension ResultCode {
|
||||
extension ResultCode: CustomStringConvertible {
|
||||
var errorString: String? {
|
||||
String(cString: sqlite3_errstr(rawValue))
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
if let errorString = errorString {
|
||||
if let errorString {
|
||||
return "\(rawValue) (\(errorString))"
|
||||
} else {
|
||||
return "\(rawValue)"
|
||||
@@ -199,61 +208,145 @@ extension ResultCode {
|
||||
|
||||
extension ResultCode: Sendable { }
|
||||
|
||||
/// DatabaseError wraps an SQLite error.
|
||||
public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
|
||||
/// The SQLite error code (see
|
||||
/// <https://www.sqlite.org/rescode.html#primary_result_code_list>).
|
||||
///
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch let error as DatabaseError where error.resultCode == .SQL_CONSTRAINT {
|
||||
/// // A constraint error
|
||||
/// }
|
||||
/// A `DatabaseError` describes an SQLite error.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// try player.insert(db)
|
||||
/// } catch let error as DatabaseError {
|
||||
/// print(error) // prints debugging information
|
||||
///
|
||||
/// switch error {
|
||||
/// case DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY:
|
||||
/// // foreign key constraint error
|
||||
/// case DatabaseError.SQLITE_CONSTRAINT:
|
||||
/// // any other constraint error
|
||||
/// default:
|
||||
/// // any other database error
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The above example can also be written in a shorter way:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// try player.insert(db)
|
||||
/// } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY {
|
||||
/// // foreign key constraint error
|
||||
/// } catch DatabaseError.SQLITE_CONSTRAINT {
|
||||
/// // any other constraint error
|
||||
/// } catch {
|
||||
/// // any other database error
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/rescode.html>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating DatabaseError
|
||||
///
|
||||
/// - ``init(resultCode:message:sql:arguments:publicStatementArguments:)``
|
||||
/// - ``ResultCode``
|
||||
///
|
||||
/// ### Error Information
|
||||
///
|
||||
/// - ``arguments``
|
||||
/// - ``extendedResultCode``
|
||||
/// - ``isInterruptionError``
|
||||
/// - ``message``
|
||||
/// - ``resultCode``
|
||||
/// - ``sql``
|
||||
///
|
||||
/// ### Converting DatabaseError to String
|
||||
///
|
||||
/// - ``description``
|
||||
/// - ``expandedDescription``
|
||||
public struct DatabaseError: Error {
|
||||
/// The SQLite primary result code.
|
||||
///
|
||||
/// This property returns a "primary result code", that is to say the least
|
||||
/// significant 8 bits of any SQLite result code. See
|
||||
/// <https://www.sqlite.org/rescode.html> for more information.
|
||||
/// significant 8 bits of any SQLite result code.
|
||||
///
|
||||
/// See also `extendedResultCode`.
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch let error as DatabaseError where error.resultCode == .SQL_CONSTRAINT {
|
||||
/// // A constraint error
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The above example can also be written in a shorter way:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch DatabaseError.SQL_CONSTRAINT {
|
||||
/// // A constraint error
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See also ``extendedResultCode``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/rescode.html>
|
||||
public var resultCode: ResultCode {
|
||||
extendedResultCode.primaryResultCode
|
||||
}
|
||||
|
||||
/// The SQLite extended error code (see
|
||||
/// <https://www.sqlite.org/rescode.html#extended_result_code_list>).
|
||||
/// The SQLite extended error code.
|
||||
///
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch let error as DatabaseError where error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY {
|
||||
/// // A foreign key constraint error
|
||||
/// }
|
||||
/// For example:
|
||||
///
|
||||
/// See also `resultCode`.
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch let error as DatabaseError where error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY {
|
||||
/// // A foreign key constraint error
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The above example can also be written in a shorter way:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY {
|
||||
/// // A foreign key constraint error
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See also ``resultCode``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/rescode.html>
|
||||
public let extendedResultCode: ResultCode
|
||||
|
||||
/// The SQLite error message.
|
||||
public let message: String?
|
||||
|
||||
/// The SQL query that yielded the error (if relevant).
|
||||
/// The SQL query that yielded the error.
|
||||
public let sql: String?
|
||||
|
||||
/// The query arguments that yielded the error (if relevant).
|
||||
/// The query arguments that yielded the error.
|
||||
public let arguments: StatementArguments?
|
||||
|
||||
/// See Configuration.publicStatementArguments
|
||||
var publicStatementArguments: Bool
|
||||
|
||||
/// Creates a DatabaseError.
|
||||
/// Creates a `DatabaseError`.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - resultCode: A ResultCode (defaults to .SQLITE_ERROR).
|
||||
/// - message: An eventual error message. If nil, the error message is
|
||||
/// derived from the result code.
|
||||
/// - sql: An eventual SQL string.
|
||||
/// - arguments: Eventual Statement arguments.
|
||||
/// - arguments: Eventual statement arguments.
|
||||
/// - publicStatementArguments: If false (the default), statement
|
||||
/// arguments are not visible in the error's `description` property.
|
||||
/// arguments are not visible in the error's ``description`` property.
|
||||
public init(
|
||||
resultCode: ResultCode = .SQLITE_ERROR,
|
||||
message: String? = nil,
|
||||
@@ -422,13 +515,14 @@ extension DatabaseError {
|
||||
}
|
||||
|
||||
extension DatabaseError {
|
||||
/// Returns true if the error has code `SQLITE_ABORT` or `SQLITE_INTERRUPT`.
|
||||
/// A boolean value indicating if the error has code
|
||||
/// `SQLITE_ABORT` or `SQLITE_INTERRUPT`.
|
||||
///
|
||||
/// Such an error can be thrown when a database has been interrupted, or
|
||||
/// when the database is suspended.
|
||||
///
|
||||
/// See `DatabaseReader.interrupt()` and `DatabaseReader.suspend()` for
|
||||
/// more information.
|
||||
/// See ``DatabaseReader/interrupt()`` and ``Database/suspendNotification``
|
||||
/// for more information.
|
||||
public var isInterruptionError: Bool {
|
||||
switch resultCode {
|
||||
case .SQLITE_ABORT, .SQLITE_INTERRUPT:
|
||||
@@ -439,8 +533,7 @@ extension DatabaseError {
|
||||
}
|
||||
}
|
||||
|
||||
// CustomStringConvertible
|
||||
extension DatabaseError {
|
||||
extension DatabaseError: CustomStringConvertible {
|
||||
/// The error description.
|
||||
///
|
||||
/// For example:
|
||||
@@ -452,13 +545,13 @@ extension DatabaseError {
|
||||
/// 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
|
||||
@@ -480,35 +573,34 @@ extension DatabaseError {
|
||||
/// 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
|
||||
}
|
||||
}
|
||||
|
||||
// CustomNSError
|
||||
extension DatabaseError {
|
||||
|
||||
/// NSError bridging: the domain of the error.
|
||||
/// :nodoc:
|
||||
extension DatabaseError: CustomNSError {
|
||||
/// Part of the `CustomNSError` conformance.
|
||||
///
|
||||
/// Returns `GRDB.DatabaseError`.
|
||||
public static var errorDomain: String { "GRDB.DatabaseError" }
|
||||
|
||||
/// NSError bridging: the error code within the given domain.
|
||||
/// :nodoc:
|
||||
/// Part of the `CustomNSError` conformance.
|
||||
///
|
||||
/// Returns the ``extendedResultCode``.
|
||||
public var errorCode: Int { Int(extendedResultCode.rawValue) }
|
||||
|
||||
/// NSError bridging: the user-info dictionary.
|
||||
/// :nodoc:
|
||||
/// 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
|
||||
|
||||
@@ -1,4 +1,25 @@
|
||||
/// An SQL function or aggregate.
|
||||
/// A custom SQL function or aggregate.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a Custom SQL Function or Aggregate
|
||||
///
|
||||
/// - ``init(_:argumentCount:pure:function:)``
|
||||
/// - ``init(_:argumentCount:pure:aggregate:)``
|
||||
/// - ``DatabaseAggregate``
|
||||
///
|
||||
/// ### Calling an SQL Function or Aggregate
|
||||
///
|
||||
/// - ``callAsFunction(_:)``
|
||||
///
|
||||
/// ### Built-in Functions
|
||||
///
|
||||
/// - ``capitalize``
|
||||
/// - ``localizedCapitalize``
|
||||
/// - ``localizedLowercase``
|
||||
/// - ``localizedUppercase``
|
||||
/// - ``lowercase``
|
||||
/// - ``uppercase``
|
||||
public final class DatabaseFunction: Hashable {
|
||||
// SQLite identifies functions by (name + argument count)
|
||||
private struct Identity: Hashable {
|
||||
@@ -17,14 +38,23 @@ public final class DatabaseFunction: Hashable {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int + 1
|
||||
/// ```swift
|
||||
/// let succ = DatabaseFunction("succ", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// db.add(function: fn)
|
||||
/// return int + 1
|
||||
/// }
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// try dbQueue.read { db in
|
||||
/// db.add(function: succ)
|
||||
/// try Int.fetchOne(db, sql: "SELECT succ(1)")! // 2
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ### Related APIs
|
||||
///
|
||||
/// - ``Database/add(function:)``
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The function name.
|
||||
@@ -34,10 +64,10 @@ public final class DatabaseFunction: Hashable {
|
||||
/// only depends on its inputs. When a function is pure, SQLite has
|
||||
/// the opportunity to perform additional optimizations. Default value
|
||||
/// is false.
|
||||
/// - function: A function that takes an array of DatabaseValue
|
||||
/// arguments, and returns an optional DatabaseValueConvertible such
|
||||
/// as Int, String, NSDate, etc. The array is guaranteed to have
|
||||
/// exactly *argumentCount* elements, provided *argumentCount* is
|
||||
/// - function: A function that takes an array of ``DatabaseValue``
|
||||
/// arguments, and returns an optional ``DatabaseValueConvertible``
|
||||
/// such as `Int`, `String`, `Date`, etc. The array is guaranteed to
|
||||
/// have exactly `argumentCount` elements, provided `argumentCount` is
|
||||
/// not nil.
|
||||
public init(
|
||||
_ name: String,
|
||||
@@ -59,29 +89,35 @@ public final class DatabaseFunction: Hashable {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct MySum: DatabaseAggregate {
|
||||
/// var sum: Int = 0
|
||||
/// ```swift
|
||||
/// struct MySum: DatabaseAggregate {
|
||||
/// var sum: Int = 0
|
||||
///
|
||||
/// mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
/// if let int = Int.fromDatabaseValue(dbValues[0]) {
|
||||
/// sum += int
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// func finalize() -> (any DatabaseValueConvertible)? {
|
||||
/// return sum
|
||||
/// mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
/// if let int = Int.fromDatabaseValue(dbValues[0]) {
|
||||
/// sum += int
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// try dbQueue.write { db in
|
||||
/// db.add(function: fn)
|
||||
/// try db.execute(sql: "CREATE TABLE test(i)")
|
||||
/// try db.execute(sql: "INSERT INTO test(i) VALUES (1)")
|
||||
/// try db.execute(sql: "INSERT INTO test(i) VALUES (2)")
|
||||
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
|
||||
/// func finalize() -> (any DatabaseValueConvertible)? {
|
||||
/// return sum
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// let mySum = DatabaseFunction("mySum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// try dbQueue.write { db in
|
||||
/// db.add(function: mySum)
|
||||
/// try db.execute(sql: "CREATE TABLE test(i)")
|
||||
/// try db.execute(sql: "INSERT INTO test(i) VALUES (1)")
|
||||
/// try db.execute(sql: "INSERT INTO test(i) VALUES (2)")
|
||||
/// try Int.fetchOne(db, sql: "SELECT mySum(i) FROM test")! // 3
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ### Related APIs
|
||||
///
|
||||
/// - ``Database/add(function:)``
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The function name.
|
||||
@@ -91,10 +127,11 @@ public final class DatabaseFunction: Hashable {
|
||||
/// results only depends on its inputs. When an aggregate is pure,
|
||||
/// SQLite has the opportunity to perform additional optimizations.
|
||||
/// Default value is false.
|
||||
/// - aggregate: A type that implements the DatabaseAggregate protocol.
|
||||
/// For each step of the aggregation, its `step` method is called with
|
||||
/// an array of DatabaseValue arguments. The array is guaranteed to
|
||||
/// have exactly *argumentCount* elements, provided *argumentCount* is
|
||||
/// - aggregate: A type that implements the ``DatabaseAggregate``
|
||||
/// protocol. For each step of the aggregation, its
|
||||
/// ``DatabaseAggregate/step(_:)`` method is called with an array of
|
||||
/// ``DatabaseValue`` arguments. The array is guaranteed to have
|
||||
/// exactly `argumentCount` elements, provided `argumentCount` is
|
||||
/// not nil.
|
||||
public init<Aggregate: DatabaseAggregate>(
|
||||
_ name: String,
|
||||
@@ -109,7 +146,29 @@ public final class DatabaseFunction: Hashable {
|
||||
|
||||
/// Returns an SQL expression that applies the function.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/#sql-functions>
|
||||
/// You can use a `DatabaseFunction` as a regular Swift function. It returns
|
||||
/// an SQL expression that you can use in the query interface.
|
||||
///
|
||||
/// In the example below, `square(Column("score"))` generates the
|
||||
/// `square(score)` SQL expression:
|
||||
///
|
||||
/// ```swift
|
||||
/// let square = DatabaseFunction("square", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int * int
|
||||
/// }
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// try dbQueue.read { db in
|
||||
/// db.add(function: square)
|
||||
///
|
||||
/// // SELECT square(score) FROM player
|
||||
/// let squaredScores = let Player
|
||||
/// .select(square(Column("score")), as: Int.self)
|
||||
/// .fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
public func callAsFunction(_ arguments: any SQLExpressible...) -> SQLExpression {
|
||||
switch kind {
|
||||
case .aggregate:
|
||||
@@ -346,13 +405,11 @@ public final class DatabaseFunction: Hashable {
|
||||
}
|
||||
|
||||
extension DatabaseFunction {
|
||||
/// :nodoc:
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(identity)
|
||||
}
|
||||
|
||||
/// Two functions are equal if they share the same name and arity.
|
||||
/// :nodoc:
|
||||
public static func == (lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool {
|
||||
lhs.identity == rhs.identity
|
||||
}
|
||||
@@ -362,47 +419,53 @@ extension DatabaseFunction {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct MySum : DatabaseAggregate {
|
||||
/// var sum: Int = 0
|
||||
/// ```swift
|
||||
/// struct MySum : DatabaseAggregate {
|
||||
/// var sum: Int = 0
|
||||
///
|
||||
/// mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
/// if let int = Int.fromDatabaseValue(dbValues[0]) {
|
||||
/// sum += int
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// func finalize() -> (any DatabaseValueConvertible)? {
|
||||
/// return sum
|
||||
/// mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
/// if let int = Int.fromDatabaseValue(dbValues[0]) {
|
||||
/// sum += int
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// try dbQueue.write { db in
|
||||
/// db.add(function: fn)
|
||||
/// try db.execute(sql: "CREATE TABLE test(i)")
|
||||
/// try db.execute(sql: "INSERT INTO test(i) VALUES (1)")
|
||||
/// try db.execute(sql: "INSERT INTO test(i) VALUES (2)")
|
||||
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
|
||||
/// func finalize() -> (any DatabaseValueConvertible)? {
|
||||
/// return sum
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// let mySum = DatabaseFunction("mySum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// try dbQueue.write { db in
|
||||
/// db.add(function: mySum)
|
||||
/// try db.execute(sql: "CREATE TABLE test(i)")
|
||||
/// try db.execute(sql: "INSERT INTO test(i) VALUES (1)")
|
||||
/// try db.execute(sql: "INSERT INTO test(i) VALUES (2)")
|
||||
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
|
||||
/// }
|
||||
/// ```
|
||||
public protocol DatabaseAggregate {
|
||||
/// Creates an aggregate.
|
||||
///
|
||||
/// A new instance is created for each aggregation.
|
||||
init()
|
||||
|
||||
/// This method is called at each step of the aggregation.
|
||||
/// Updates the aggregated value for one step of the aggregation.
|
||||
///
|
||||
/// The dbValues argument contains as many values as given to the SQL
|
||||
/// aggregate function.
|
||||
/// This method is called once for each step of the aggregation.
|
||||
///
|
||||
/// -- One value
|
||||
/// SELECT maxLength(name) FROM player
|
||||
/// The `dbValues` argument contains as many values as given to the SQL
|
||||
/// aggregate function:
|
||||
///
|
||||
/// -- Two values
|
||||
/// SELECT maxFullNameLength(firstName, lastName) FROM player
|
||||
/// ```sql
|
||||
/// -- One value
|
||||
/// SELECT maxLength(name) FROM player
|
||||
///
|
||||
/// This method is never called after the finalize() method has been called.
|
||||
/// -- Two values
|
||||
/// SELECT maxFullNameLength(firstName, lastName) FROM player
|
||||
/// ```
|
||||
mutating func step(_ dbValues: [DatabaseValue]) throws
|
||||
|
||||
/// Returns the final result
|
||||
/// Returns the aggregated value.
|
||||
func finalize() throws -> (any DatabaseValueConvertible)?
|
||||
}
|
||||
+245
-185
@@ -4,8 +4,7 @@ import Foundation
|
||||
import UIKit
|
||||
#endif
|
||||
|
||||
/// A DatabasePool grants concurrent accesses to an SQLite database.
|
||||
public final class DatabasePool: DatabaseWriter {
|
||||
public final class DatabasePool {
|
||||
private let writer: SerializedDatabase
|
||||
|
||||
/// The pool of reader connections.
|
||||
@@ -16,7 +15,6 @@ public final class DatabasePool: DatabaseWriter {
|
||||
|
||||
// MARK: - Database Information
|
||||
|
||||
/// The database configuration
|
||||
public var configuration: Configuration {
|
||||
writer.configuration
|
||||
}
|
||||
@@ -28,16 +26,21 @@ public final class DatabasePool: DatabaseWriter {
|
||||
|
||||
// MARK: - Initializer
|
||||
|
||||
/// Opens the SQLite database at path *path*.
|
||||
/// Opens or creates an SQLite database.
|
||||
///
|
||||
/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
/// For example:
|
||||
///
|
||||
/// Database connections get closed when the database pool gets deallocated.
|
||||
/// ```swift
|
||||
/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
/// ```
|
||||
///
|
||||
/// The SQLite connections are closed when the database pool
|
||||
/// gets deallocated.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - path: The path to the database file.
|
||||
/// - configuration: A configuration.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public init(path: String, configuration: Configuration = Configuration()) throws {
|
||||
GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1")
|
||||
|
||||
@@ -113,7 +116,7 @@ public final class DatabasePool: DatabaseWriter {
|
||||
// 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.
|
||||
@@ -123,7 +126,7 @@ public final class DatabasePool: DatabaseWriter {
|
||||
|
||||
/// Returns a Configuration suitable for readonly connections on a
|
||||
/// WAL database.
|
||||
static func readerConfiguration(_ configuration: Configuration) -> Configuration {
|
||||
private static func readerConfiguration(_ configuration: Configuration) -> Configuration {
|
||||
var configuration = configuration
|
||||
|
||||
configuration.readonly = true
|
||||
@@ -132,7 +135,7 @@ public final class DatabasePool: DatabaseWriter {
|
||||
// Other transaction kinds are forbidden by SQLite in read-only connections.
|
||||
configuration.defaultTransactionKind = .deferred
|
||||
|
||||
// https://www.sqlite.org/wal.html#sometimes_queries_return_sqlite_busy_in_wal_mode
|
||||
// <https://www.sqlite.org/wal.html#sometimes_queries_return_sqlite_busy_in_wal_mode>
|
||||
// > But there are some obscure cases where a query against a WAL-mode
|
||||
// > database can return SQLITE_BUSY, so applications should be prepared
|
||||
// > for that happenstance.
|
||||
@@ -165,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.
|
||||
@@ -178,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)
|
||||
@@ -358,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
|
||||
}
|
||||
|
||||
@@ -369,7 +391,7 @@ extension DatabasePool: DatabaseReader {
|
||||
reader.async { db in
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader()
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
do {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
@@ -402,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
|
||||
}
|
||||
|
||||
@@ -412,10 +434,9 @@ extension DatabasePool: DatabaseReader {
|
||||
// Second async jump because that's how `Pool.async` has to be used.
|
||||
reader.async { db in
|
||||
defer {
|
||||
releaseReader()
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
do {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
value(.success(db))
|
||||
} catch {
|
||||
@@ -431,6 +452,8 @@ extension DatabasePool: DatabaseReader {
|
||||
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
if let reader = currentReader {
|
||||
return try reader.reentrantSync(value)
|
||||
} else if writer.onValidQueue {
|
||||
return try writer.execute(value)
|
||||
} else {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
@@ -462,48 +485,46 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
/// Performs the same job as asyncConcurrentRead.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
asyncConcurrentRead(value)
|
||||
}
|
||||
|
||||
/// Asynchronously executes a read-only function in a protected
|
||||
/// dispatch queue.
|
||||
/// Performs an asynchronous read access.
|
||||
///
|
||||
/// This method must be called from a writing dispatch queue, outside of any
|
||||
/// transaction. You'll get a fatal error otherwise.
|
||||
/// This method must be called from the writer dispatch queue, outside of
|
||||
/// any transaction. You'll get a fatal error otherwise.
|
||||
///
|
||||
/// The `value` function is guaranteed to see the database in the last
|
||||
/// committed state at the moment this method is called. Eventual
|
||||
/// concurrent database updates are not visible from the function.
|
||||
///
|
||||
/// This method returns as soon as the isolation guarantees described above
|
||||
/// are established.
|
||||
/// This method returns as soon as the isolation guarantee described above
|
||||
/// has been established.
|
||||
///
|
||||
/// In the example below, the number of players is fetched concurrently with
|
||||
/// the player insertion. Yet the future is guaranteed to return zero:
|
||||
/// the player insertion. Yet it is guaranteed to be zero:
|
||||
///
|
||||
/// try writer.asyncWriteWithoutTransaction { db in
|
||||
/// // Delete all players
|
||||
/// try Player.deleteAll()
|
||||
/// ```swift
|
||||
/// try writer.asyncWriteWithoutTransaction { db in
|
||||
/// // Delete all players
|
||||
/// try Player.deleteAll()
|
||||
///
|
||||
/// // Count players concurrently
|
||||
/// writer.asyncConcurrentRead { dbResult in
|
||||
/// do {
|
||||
/// let db = try dbResult.get()
|
||||
/// // Guaranteed to be zero
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // Handle error
|
||||
/// }
|
||||
/// // Count players concurrently
|
||||
/// writer.asyncConcurrentRead { dbResult in
|
||||
/// do {
|
||||
/// let db = try dbResult.get()
|
||||
/// // Guaranteed to be zero
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // Handle error
|
||||
/// }
|
||||
///
|
||||
/// // Insert a player
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
///
|
||||
/// // Insert a player
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter value: A function that accesses the database.
|
||||
public func asyncConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
// Check that we're on the writer queue...
|
||||
@@ -529,7 +550,7 @@ extension DatabasePool: DatabaseReader {
|
||||
reader.async { db in
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader()
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
do {
|
||||
// https://www.sqlite.org/isolation.html
|
||||
@@ -606,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()
|
||||
}
|
||||
@@ -638,92 +663,55 @@ extension DatabasePool: DatabaseReader {
|
||||
return readers.first { $0.onValidQueue }
|
||||
}
|
||||
|
||||
// MARK: - Writing in Database
|
||||
// MARK: - WAL Snapshot Transactions
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
|
||||
// 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()
|
||||
}
|
||||
return try readerPool.barrier {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
|
||||
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)
|
||||
})
|
||||
}
|
||||
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
|
||||
/// 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 {
|
||||
updates(.failure(DatabaseError.connectionIsClosed()))
|
||||
completion(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
}
|
||||
readerPool.asyncBarrier {
|
||||
self.writer.sync { updates(.success($0)) }
|
||||
|
||||
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)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// wrapped inside a transaction, and returns the result.
|
||||
///
|
||||
/// If the updates throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If the updates return .rollback, the transaction is
|
||||
/// also rollbacked, but no error is thrown.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the transaction
|
||||
/// has completed.
|
||||
///
|
||||
/// Eventual concurrent reads are guaranteed to not see any partial updates
|
||||
/// of the database until the transaction has completed.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// try dbPool.writeInTransaction { db in
|
||||
/// db.execute(...)
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .deferred. See <https://www.sqlite.org/lang_transaction.html>
|
||||
/// for more information.
|
||||
/// - updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates, or by the
|
||||
/// wrapping transaction.
|
||||
public func writeInTransaction(
|
||||
_ kind: Database.TransactionKind? = nil,
|
||||
_ updates: (Database) throws -> Database.TransactionCompletion)
|
||||
throws
|
||||
{
|
||||
try writer.sync { db in
|
||||
try db.inTransaction(kind) {
|
||||
try updates(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.reentrantSync(updates)
|
||||
}
|
||||
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction.
|
||||
///
|
||||
/// Eventual concurrent reads may see partial updates unless you wrap them
|
||||
/// in a transaction.
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
writer.async(updates)
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// :nodoc:
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
@@ -754,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
|
||||
{
|
||||
@@ -771,68 +759,121 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabasePool: DatabaseWriter {
|
||||
// MARK: - Writing in Database
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
return try readerPool.barrier {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
updates(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
}
|
||||
readerPool.asyncBarrier {
|
||||
self.writer.sync { updates(.success($0)) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps database operations inside a database transaction.
|
||||
///
|
||||
/// The `updates` function runs in the writer dispatch queue, serialized
|
||||
/// with all database updates.
|
||||
///
|
||||
/// If `updates` throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If it returns
|
||||
/// ``Database/TransactionCompletion/rollback``, the transaction is also
|
||||
/// rollbacked, but no error is thrown.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbPool.writeInTransaction { db in
|
||||
/// try Player(name: "Arthur").insert(db)
|
||||
/// try Player(name: "Barbara").insert(db)
|
||||
/// return .commit
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - precondition: This method is not reentrant.
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is the ``Configuration/defaultTransactionKind`` of the
|
||||
/// the ``configuration``.
|
||||
/// - updates: A function that updates the database.
|
||||
/// - throws: The error thrown by `updates`, or by the wrapping transaction.
|
||||
public func writeInTransaction(
|
||||
_ kind: Database.TransactionKind? = nil,
|
||||
_ updates: (Database) throws -> Database.TransactionCompletion)
|
||||
throws
|
||||
{
|
||||
try writer.sync { db in
|
||||
try db.inTransaction(kind) {
|
||||
try updates(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.reentrantSync(updates)
|
||||
}
|
||||
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
writer.async(updates)
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
// MARK: - Snapshots
|
||||
|
||||
/// Creates a database snapshot.
|
||||
/// Creates a database snapshot that serializes accesses to an unchanging
|
||||
/// database content, as it exists at the moment the snapshot is created.
|
||||
///
|
||||
/// The snapshot sees an unchanging database content, as it existed at the
|
||||
/// moment it was created.
|
||||
/// It is a programmer error to create a snapshot from the writer dispatch
|
||||
/// queue when a transaction is opened:
|
||||
///
|
||||
/// When you want to control the latest committed changes seen by a
|
||||
/// snapshot, create it from the pool's writer protected dispatch queue:
|
||||
/// ```swift
|
||||
/// try dbPool.write { db in
|
||||
/// try Player.deleteAll()
|
||||
///
|
||||
/// let snapshot1 = try dbPool.write { db -> DatabaseSnapshot in
|
||||
/// // fatal error: makeSnapshot() must not be called from inside a transaction
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// To avoid this fatal error, create the snapshot *before* or *after*
|
||||
/// the transaction:
|
||||
///
|
||||
/// ```swift
|
||||
/// let snapshot = try dbPool.makeSnapshot() // OK
|
||||
///
|
||||
/// try dbPool.writeWithoutTransaction { db in
|
||||
/// let snapshot = try dbPool.makeSnapshot() // OK
|
||||
///
|
||||
/// try db.inTransaction {
|
||||
/// try Player.deleteAll()
|
||||
/// return try dbPool.makeSnapshot()
|
||||
/// }
|
||||
/// // <- Other threads may modify the database here
|
||||
/// let snapshot2 = try dbPool.makeSnapshot()
|
||||
///
|
||||
/// try snapshot1.read { db in
|
||||
/// // Guaranteed to be zero
|
||||
/// try Player.fetchCount(db)
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// try snapshot2.read { db in
|
||||
/// // Could be anything
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// // OK
|
||||
/// let snapshot = try dbPool.makeSnapshot() // OK
|
||||
/// }
|
||||
///
|
||||
/// It is forbidden to create a snapshot from the writer protected dispatch
|
||||
/// queue when a transaction is opened, though, because it is likely a
|
||||
/// programmer error:
|
||||
///
|
||||
/// try dbPool.write { db in
|
||||
/// try db.inTransaction {
|
||||
/// try Player.deleteAll()
|
||||
/// // fatal error: makeSnapshot() must not be called from inside a transaction
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
/// return .commit
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// To avoid this fatal error, create the snapshot *before* or *after* the
|
||||
/// transaction:
|
||||
///
|
||||
/// try dbPool.writeWithoutTransaction { db in
|
||||
/// // OK
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
///
|
||||
/// try db.inTransaction {
|
||||
/// try Player.deleteAll()
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// // OK
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
/// }
|
||||
///
|
||||
/// You can create as many snapshots as you need, regardless of the maximum
|
||||
/// number of reader connections in the pool.
|
||||
///
|
||||
/// For more information, read about "snapshot isolation" at <https://sqlite.org/isolation.html>
|
||||
/// let snapshot = try dbPool.makeSnapshot() // OK
|
||||
/// ```
|
||||
public func makeSnapshot() throws -> DatabaseSnapshot {
|
||||
// Sanity check
|
||||
if writer.onValidQueue {
|
||||
@@ -845,8 +886,27 @@ extension DatabasePool {
|
||||
|
||||
return try DatabaseSnapshot(
|
||||
path: path,
|
||||
configuration: writer.configuration,
|
||||
configuration: DatabasePool.readerConfiguration(writer.configuration),
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "snapshot.\($databaseSnapshotCount.increment())")
|
||||
}
|
||||
|
||||
// swiftlint:disable:next line_length
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
/// Creates a database snapshot that allows concurrent accesses to an
|
||||
/// unchanging database content, as it exists at the moment the snapshot
|
||||
/// is created.
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// A ``DatabaseError`` of code `SQLITE_ERROR` is thrown if the SQLite
|
||||
/// database is not in the [WAL mode](https://www.sqlite.org/wal.html), or
|
||||
/// if this method is called from a database access where a write
|
||||
/// transaction is open.
|
||||
public func makeSnapshotPool() throws -> DatabaseSnapshotPool {
|
||||
try unsafeReentrantRead { db in
|
||||
try DatabaseSnapshotPool(db)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -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
|
||||
+128
-73
@@ -4,35 +4,44 @@ import Foundation
|
||||
import UIKit
|
||||
#endif
|
||||
|
||||
/// A DatabaseQueue serializes access to an SQLite database.
|
||||
public final class DatabaseQueue: DatabaseWriter {
|
||||
public final class DatabaseQueue {
|
||||
private let writer: SerializedDatabase
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// The database configuration
|
||||
public var configuration: Configuration {
|
||||
writer.configuration
|
||||
}
|
||||
|
||||
/// The path to the database file; it is ":memory:" for in-memory databases.
|
||||
/// The path to the database file.
|
||||
///
|
||||
/// The path is `:memory:` for in-memory databases.
|
||||
public var path: String {
|
||||
writer.path
|
||||
}
|
||||
|
||||
// MARK: - Initializers
|
||||
|
||||
/// Opens the SQLite database at path *path*.
|
||||
/// Opens or creates an SQLite database.
|
||||
///
|
||||
/// let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
|
||||
/// For example:
|
||||
///
|
||||
/// Database connections get closed when the database queue gets deallocated.
|
||||
/// ```swift
|
||||
/// let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
|
||||
/// ```
|
||||
///
|
||||
/// The SQLite connection is closed when the database queue
|
||||
/// gets deallocated.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - path: The path to the database file.
|
||||
/// - configuration: A configuration.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public init(path: String, configuration: Configuration = Configuration()) throws {
|
||||
// DatabaseQueue can't perform parallel reads
|
||||
var configuration = configuration
|
||||
configuration.maximumReaderCount = 1
|
||||
|
||||
writer = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
@@ -51,14 +60,41 @@ public final class DatabaseQueue: DatabaseWriter {
|
||||
|
||||
/// Opens an in-memory SQLite database.
|
||||
///
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// To create an independent in-memory database, don't pass any name. The
|
||||
/// database memory is released when the database queue is deallocated:
|
||||
///
|
||||
/// Database memory is released when the database queue gets deallocated.
|
||||
/// ```swift
|
||||
/// // An independent in-memory database
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// ```
|
||||
///
|
||||
/// When you need to open several connections to the same in-memory
|
||||
/// database, give it a name:
|
||||
///
|
||||
/// ```swift
|
||||
/// // A shared in-memory database
|
||||
/// let dbQueue = try DatabaseQueue(named: "myDatabase")
|
||||
/// ```
|
||||
///
|
||||
/// In this case, the database is automatically deleted and memory is
|
||||
/// reclaimed when the last connection to the database of the given
|
||||
/// name closes.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/inmemorydb.html>
|
||||
///
|
||||
/// - parameter name: When nil, an independent in-memory database opens.
|
||||
/// Otherwise, the shared in-memory database of the given name opens.
|
||||
/// - parameter configuration: A configuration.
|
||||
public init(configuration: Configuration = Configuration()) throws {
|
||||
public init(named name: String? = nil, configuration: Configuration = Configuration()) throws {
|
||||
let path: String
|
||||
if let name {
|
||||
path = "file:\(name)?mode=memory&cache=shared"
|
||||
} else {
|
||||
path = ":memory:"
|
||||
}
|
||||
|
||||
writer = try SerializedDatabase(
|
||||
path: ":memory:",
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
defaultLabel: "GRDB.DatabaseQueue")
|
||||
}
|
||||
@@ -67,13 +103,9 @@ public final class DatabaseQueue: DatabaseWriter {
|
||||
// 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)
|
||||
}
|
||||
|
||||
public func close() throws {
|
||||
try writer.sync { try $0.close() }
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseQueue {
|
||||
@@ -133,7 +165,10 @@ extension DatabaseQueue {
|
||||
#endif
|
||||
}
|
||||
|
||||
extension DatabaseQueue {
|
||||
extension DatabaseQueue: DatabaseReader {
|
||||
public func close() throws {
|
||||
try writer.sync { try $0.close() }
|
||||
}
|
||||
|
||||
// MARK: - Interrupting Database Operations
|
||||
|
||||
@@ -233,9 +268,6 @@ extension DatabaseQueue {
|
||||
})
|
||||
}
|
||||
|
||||
/// Performs the same job as asyncConcurrentRead.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
// Check that we're on the writer queue...
|
||||
writer.execute { db in
|
||||
@@ -258,33 +290,59 @@ extension DatabaseQueue {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
// The easy case: the database does not change
|
||||
return _addReadOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
} else {
|
||||
// Observe from the writer database connection.
|
||||
return _addWriteOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseQueue: DatabaseWriter {
|
||||
// MARK: - Writing in Database
|
||||
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// wrapped inside a transaction, and returns the result.
|
||||
/// Wraps database operations inside a database transaction.
|
||||
///
|
||||
/// If the updates throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If the updates return .rollback, the transaction is
|
||||
/// also rollbacked, but no error is thrown.
|
||||
/// The `updates` function runs in the writer dispatch queue, serialized
|
||||
/// with all database updates.
|
||||
///
|
||||
/// If `updates` throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If it returns
|
||||
/// ``Database/TransactionCompletion/rollback``, the transaction is also
|
||||
/// rollbacked, but no error is thrown.
|
||||
///
|
||||
/// Eventual concurrent database accesses are postponed until the
|
||||
/// transaction has completed.
|
||||
/// For example:
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// try dbQueue.writeInTransaction { db in
|
||||
/// db.execute(...)
|
||||
/// return .commit
|
||||
/// }
|
||||
/// ```swift
|
||||
/// try dbQueue.inTransaction { db in
|
||||
/// try Player(name: "Arthur").insert(db)
|
||||
/// try Player(name: "Barbara").insert(db)
|
||||
/// return .commit
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .deferred. See <https://www.sqlite.org/lang_transaction.html>
|
||||
/// for more information.
|
||||
/// - updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates, or by the
|
||||
/// wrapping transaction.
|
||||
/// type is the ``Configuration/defaultTransactionKind`` of the
|
||||
/// the ``configuration``.
|
||||
/// - updates: A function that updates the database.
|
||||
/// - throws: The error thrown by `updates`, or by the wrapping transaction.
|
||||
public func inTransaction(
|
||||
_ kind: Database.TransactionKind? = nil,
|
||||
_ updates: (Database) throws -> Database.TransactionCompletion)
|
||||
@@ -311,19 +369,40 @@ extension DatabaseQueue {
|
||||
writer.async { updates(.success($0)) }
|
||||
}
|
||||
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, and returns the result.
|
||||
/// Executes database operations, and returns their result after they have
|
||||
/// finished executing.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the updates
|
||||
/// are completed.
|
||||
/// This method is identical to
|
||||
/// ``DatabaseWriter/writeWithoutTransaction(_:)-4qh1w``
|
||||
///
|
||||
/// Eventual concurrent reads may see partial updates unless you wrap them
|
||||
/// in a transaction.
|
||||
/// For example:
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
/// ```swift
|
||||
/// let newPlayerCount = try dbQueue.inDatabase { db in
|
||||
/// try Player(name: "Arthur").insert(db)
|
||||
/// return try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates.
|
||||
/// Database operations run in the writer dispatch queue, serialized
|
||||
/// with all database updates performed by this `DatabaseWriter`.
|
||||
///
|
||||
/// The ``Database`` argument to `updates` is valid only during the
|
||||
/// execution of the closure. Do not store or return the database connection
|
||||
/// for later use.
|
||||
///
|
||||
/// It is a programmer error to call this method from another database
|
||||
/// access method. Doing so raises a "Database methods are not reentrant"
|
||||
/// fatal error at runtime.
|
||||
///
|
||||
/// - warning: Database operations are not wrapped in a transaction. They
|
||||
/// can see changes performed by concurrent writes or writes performed by
|
||||
/// other processes: two identical requests performed by the `updates`
|
||||
/// closure may not return the same value. Concurrent database accesses
|
||||
/// can see partial updates performed by the `updates` closure.
|
||||
///
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `updates`.
|
||||
public func inDatabase<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
@@ -335,28 +414,4 @@ extension DatabaseQueue {
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
writer.async(updates)
|
||||
}
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// :nodoc:
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
// The easy case: the database does not change
|
||||
return _addReadOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
} else {
|
||||
// Observe from the writer database connection.
|
||||
return _addWriteOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
}
|
||||
}
|
||||
}
|
||||
+375
-291
@@ -3,273 +3,314 @@ import Combine
|
||||
#endif
|
||||
import Dispatch
|
||||
|
||||
/// `DatabaseReader` is the protocol for all types that can fetch values from
|
||||
/// an SQLite database.
|
||||
/// A type that reads from an SQLite database.
|
||||
///
|
||||
/// It is adopted by `DatabaseQueue`, `DatabasePool`, and `DatabaseSnapshot`.
|
||||
/// Do not declare new conformances to `DatabaseReader`. Only the built-in
|
||||
/// conforming types are valid.
|
||||
///
|
||||
/// The protocol comes with isolation guarantees that describe the behavior of
|
||||
/// adopting types in a multithreaded application.
|
||||
/// conforming types in a multithreaded application. See <doc:Concurrency> for
|
||||
/// more information.
|
||||
///
|
||||
/// Types that adopt the protocol can provide in practice stronger guarantees.
|
||||
/// For example, `DatabaseQueue` provides a stronger isolation level
|
||||
/// than `DatabasePool`.
|
||||
/// ## Topics
|
||||
///
|
||||
/// **Warning**: Isolation guarantees stand as long as there is no external
|
||||
/// connection to the database. Should you have to cope with external
|
||||
/// connections, protect yourself with transactions, and be ready to setup a
|
||||
/// [busy handler](https://www.sqlite.org/c3ref/busy_handler.html).
|
||||
/// ### Database Information
|
||||
///
|
||||
/// - ``configuration``
|
||||
///
|
||||
/// ### Reading from the Database
|
||||
///
|
||||
/// - ``read(_:)-3806d``
|
||||
/// - ``read(_:)-4w6gy``
|
||||
/// - ``readPublisher(receiveOn:value:)``
|
||||
/// - ``asyncRead(_:)``
|
||||
///
|
||||
/// ### Unsafe Methods
|
||||
///
|
||||
/// - ``unsafeRead(_:)-5i7tf``
|
||||
/// - ``unsafeRead(_:)-11mk0``
|
||||
/// - ``unsafeReentrantRead(_:)``
|
||||
/// - ``asyncUnsafeRead(_:)``
|
||||
///
|
||||
/// ### Other Database Operations
|
||||
///
|
||||
/// - ``backup(to:pagesPerStep:progress:)``
|
||||
/// - ``close()``
|
||||
/// - ``interrupt()``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``AnyDatabaseReader``
|
||||
public protocol DatabaseReader: AnyObject, Sendable {
|
||||
|
||||
/// The database configuration
|
||||
/// The database configuration.
|
||||
var configuration: Configuration { get }
|
||||
|
||||
/// Closes the database connection with the `sqlite3_close()` function.
|
||||
/// Closes the database connection.
|
||||
///
|
||||
/// **Note**: You DO NOT HAVE to call this method, and you SHOULD NOT call
|
||||
/// it unless the correct execution of your program depends on precise
|
||||
/// database closing. Database connections are automatically closed when
|
||||
/// they are deinitialized, and this is sufficient for most applications.
|
||||
/// - note: You do not have to call this method, and you should not call
|
||||
/// it unless the correct execution of your program depends on precise
|
||||
/// database closing. Database connections are automatically closed when
|
||||
/// they are deinitialized, and this is sufficient for most applications.
|
||||
///
|
||||
/// If this method does not throw, then the database is properly closed, and
|
||||
/// every future database access will throw a `DatabaseError` of
|
||||
/// every future database access will throw a ``DatabaseError`` of
|
||||
/// code `SQLITE_MISUSE`.
|
||||
///
|
||||
/// Otherwise, there exists concurrent database accesses or living prepared
|
||||
/// statements that prevent the database from closing, and this method
|
||||
/// throws a `DatabaseError` of code `SQLITE_BUSY`.
|
||||
/// throws a ``DatabaseError`` of code `SQLITE_BUSY`.
|
||||
/// See <https://www.sqlite.org/c3ref/close.html> for more information.
|
||||
///
|
||||
/// After an error has been thrown, the database may still be opened, and
|
||||
/// you can keep on accessing it. It may also remain in a "zombie" state,
|
||||
/// in which case it will throw `SQLITE_MISUSE` for all future
|
||||
/// database accesses.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
func close() throws
|
||||
|
||||
// MARK: - Interrupting Database Operations
|
||||
|
||||
/// This method causes any pending database operation to abort and return at
|
||||
/// its earliest opportunity.
|
||||
/// Causes any pending database operation to abort and return at its
|
||||
/// earliest opportunity.
|
||||
///
|
||||
/// It can be called from any thread.
|
||||
/// This method can be called from any thread.
|
||||
///
|
||||
/// A call to `interrupt()` that occurs when there are no running SQL
|
||||
/// statements is a no-op and has no effect on SQL statements that are
|
||||
/// started after `interrupt()` returns.
|
||||
///
|
||||
/// A database operation that is interrupted will throw a DatabaseError with
|
||||
/// code SQLITE_INTERRUPT. If the interrupted SQL operation is an INSERT,
|
||||
/// UPDATE, or DELETE that is inside an explicit transaction, then the
|
||||
/// entire transaction will be rolled back automatically. If the rolled back
|
||||
/// transaction was started by a transaction-wrapping method such as
|
||||
/// `DatabaseWriter.write` or `Database.inTransaction`, then all database
|
||||
/// accesses will throw a DatabaseError with code SQLITE_ABORT until the
|
||||
/// wrapping method returns.
|
||||
/// A database operation that is interrupted will throw a ``DatabaseError``
|
||||
/// with code `SQLITE_INTERRUPT`. If the interrupted SQL operation is an
|
||||
/// `INSERT`, `UPDATE`, or `DELETE` that is inside an explicit transaction,
|
||||
/// then the entire transaction will be rolled back automatically. If the
|
||||
/// rolled back transaction was started by a transaction-wrapping method
|
||||
/// such as ``DatabaseWriter/write(_:)-76inz`` or
|
||||
/// ``Database/inTransaction(_:_:)``, then all database accesses will throw
|
||||
/// a ``DatabaseError`` with code `SQLITE_ABORT` until the wrapping
|
||||
/// method returns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// // interrupted:
|
||||
/// try Player(...).insert(db) // throws SQLITE_INTERRUPT
|
||||
/// // not executed:
|
||||
/// try Player(...).insert(db)
|
||||
/// } // throws SQLITE_INTERRUPT
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// do {
|
||||
/// // interrupted:
|
||||
/// try Player(...).insert(db) // throws SQLITE_INTERRUPT
|
||||
/// // not executed:
|
||||
/// try Player(...).insert(db)
|
||||
/// } // throws SQLITE_INTERRUPT
|
||||
/// try Player(...).insert(db) // throws SQLITE_INTERRUPT
|
||||
/// } catch { }
|
||||
/// try Player(...).insert(db) // throws SQLITE_ABORT
|
||||
/// } // throws SQLITE_ABORT
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// do {
|
||||
/// // interrupted:
|
||||
/// try Player(...).insert(db) // throws SQLITE_INTERRUPT
|
||||
/// } catch { }
|
||||
/// try Player(...).insert(db) // throws SQLITE_ABORT
|
||||
/// } // throws SQLITE_ABORT
|
||||
/// try dbQueue.write { db in
|
||||
/// do {
|
||||
/// // interrupted:
|
||||
/// try Player(...).insert(db) // throws SQLITE_INTERRUPT
|
||||
/// } catch { }
|
||||
/// } // throws SQLITE_ABORT
|
||||
/// ```
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// do {
|
||||
/// // interrupted:
|
||||
/// try Player(...).insert(db) // throws SQLITE_INTERRUPT
|
||||
/// } catch { }
|
||||
/// } // throws SQLITE_ABORT
|
||||
/// Beware: when an application opens a transaction without a
|
||||
/// transaction-wrapping method, no `SQLITE_ABORT` error warns of
|
||||
/// aborted transactions:
|
||||
///
|
||||
/// When an application creates transaction without a transaction-wrapping
|
||||
/// method, no SQLITE_ABORT error warns of aborted transactions:
|
||||
/// ```swift
|
||||
/// try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction
|
||||
/// try db.beginTransaction()
|
||||
/// do {
|
||||
/// // interrupted:
|
||||
/// try Player(...).insert(db) // throws SQLITE_INTERRUPT
|
||||
/// } catch { }
|
||||
/// try Player(...).insert(db) // success
|
||||
/// try db.commit() // throws SQLITE_ERROR "cannot commit - no transaction is active"
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction
|
||||
/// try db.beginTransaction()
|
||||
/// do {
|
||||
/// // interrupted:
|
||||
/// try Player(...).insert(db) // throws SQLITE_INTERRUPT
|
||||
/// } catch { }
|
||||
/// try Player(...).insert(db) // success
|
||||
/// try db.commit() // throws SQLITE_ERROR "cannot commit - no transaction is active"
|
||||
/// }
|
||||
///
|
||||
/// Both SQLITE_ABORT and SQLITE_INTERRUPT errors can be checked with the
|
||||
/// `DatabaseError.isInterruptionError` property.
|
||||
/// Both `SQLITE_ABORT` and `SQLITE_INTERRUPT` errors can be checked with the
|
||||
/// ``DatabaseError/isInterruptionError`` property.
|
||||
func interrupt()
|
||||
|
||||
// MARK: - Read From Database
|
||||
|
||||
/// Synchronously executes a read-only function that accepts a database
|
||||
/// connection, and returns its result.
|
||||
/// Executes read-only database operations, and returns their result after
|
||||
/// they have finished executing.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let count = try reader.read { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// let count = try reader.read { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The `value` function runs in an isolated fashion: eventual concurrent
|
||||
/// database updates are not visible from the function:
|
||||
/// Database operations are isolated in a transaction: they do not see
|
||||
/// changes performed by eventual concurrent writes (even writes performed
|
||||
/// by other processes).
|
||||
///
|
||||
/// try reader.read { db in
|
||||
/// // Those two values are guaranteed to be equal, even if the
|
||||
/// // `player` table is modified, between the two requests, by
|
||||
/// // some other database connection or some other thread.
|
||||
/// let count1 = try Player.fetchCount(db)
|
||||
/// let count2 = try Player.fetchCount(db)
|
||||
/// }
|
||||
/// The database connection is read-only: attempts to write throw a
|
||||
/// ``DatabaseError`` with resultCode `SQLITE_READONLY`.
|
||||
///
|
||||
/// try reader.read { db in
|
||||
/// // Now this value may be different:
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// Attempts to write in the database throw a DatabaseError with
|
||||
/// resultCode `SQLITE_READONLY`.
|
||||
/// The ``Database`` argument to `value` is valid only during the execution
|
||||
/// of the closure. Do not store or return the database connection for
|
||||
/// later use.
|
||||
///
|
||||
/// It is a programmer error to call this method from another database
|
||||
/// access method:
|
||||
/// access method. Doing so raises a "Database methods are not reentrant"
|
||||
/// fatal error at runtime.
|
||||
///
|
||||
/// try reader.read { db in
|
||||
/// // Raises a fatal error
|
||||
/// try reader.read { ... )
|
||||
/// }
|
||||
///
|
||||
/// - parameter value: A function that accesses the database.
|
||||
/// - throws: The error thrown by `value`, or any `DatabaseError` that would
|
||||
/// happen while establishing the read access to the database.
|
||||
/// - 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.
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
func read<T>(_ value: (Database) throws -> T) throws -> T
|
||||
|
||||
/// Asynchronously executes a read-only function that accepts a
|
||||
/// database connection.
|
||||
/// Schedules read-only database operations for execution, and
|
||||
/// returns immediately.
|
||||
///
|
||||
/// The `value` function runs in an isolated fashion: eventual concurrent
|
||||
/// database updates are not visible from the function:
|
||||
/// For example:
|
||||
///
|
||||
/// reader.asyncRead { dbResult in
|
||||
/// do {
|
||||
/// let db = try dbResult.get()
|
||||
/// // Those two values are guaranteed to be equal, even if the
|
||||
/// // `player` table is modified, between the two requests, by
|
||||
/// // some other database connection or some other thread.
|
||||
/// let count1 = try Player.fetchCount(db)
|
||||
/// let count2 = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // handle error
|
||||
/// }
|
||||
/// ```swift
|
||||
/// try reader.asyncRead { dbResult in
|
||||
/// do {
|
||||
/// let db = try dbResult.get()
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // Handle error
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Attempts to write in the database throw a DatabaseError with
|
||||
/// resultCode `SQLITE_READONLY`.
|
||||
/// Database operations are isolated in a transaction: they do not see
|
||||
/// changes performed by eventual concurrent writes (even writes performed
|
||||
/// by other processes).
|
||||
///
|
||||
/// - parameter value: A function that accesses the database. Its argument
|
||||
/// The database connection is read-only: attempts to write throw a
|
||||
/// ``DatabaseError`` with resultCode `SQLITE_READONLY`.
|
||||
///
|
||||
/// - parameter value: A closure which accesses the database. Its argument
|
||||
/// is a `Result` that provides the database connection, or the failure
|
||||
/// that would prevent establishing the read access to the database.
|
||||
func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void)
|
||||
|
||||
/// Synchronously executes a function that accepts a database
|
||||
/// connection, and returns its result.
|
||||
/// Executes database operations, and returns their result after they have
|
||||
/// finished executing.
|
||||
///
|
||||
/// This method is "unsafe" because the database reader does nothing more
|
||||
/// than providing a database connection. When you use this method, you
|
||||
/// become responsible for the thread-safety of your application, and
|
||||
/// responsible for database accesses performed by other processes. See
|
||||
/// <doc:Concurrency#Safe-and-Unsafe-Database-Accesses> for
|
||||
/// more information.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let count = try reader.unsafeRead { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// let count = try reader.unsafeRead { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The guarantees of the `read` method are lifted:
|
||||
///
|
||||
/// the `value` function is not isolated: eventual concurrent database
|
||||
/// updates are visible from the function:
|
||||
///
|
||||
/// try reader.unsafeRead { db in
|
||||
/// // Those two values can be different, because some other
|
||||
/// // database connection or some other thread may modify the
|
||||
/// // database between the two requests.
|
||||
/// let count1 = try Player.fetchCount(db)
|
||||
/// let count2 = try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// The `value` function is not prevented from writing (DatabaseQueue, in
|
||||
/// particular, will accept database modifications in `unsafeRead`).
|
||||
/// The ``Database`` argument to `value` is valid only during the execution
|
||||
/// of the closure. Do not store or return the database connection for
|
||||
/// later use.
|
||||
///
|
||||
/// It is a programmer error to call this method from another database
|
||||
/// access method:
|
||||
/// access method. Doing so raises a "Database methods are not reentrant"
|
||||
/// fatal error at runtime.
|
||||
///
|
||||
/// try reader.read { db in
|
||||
/// // Raises a fatal error
|
||||
/// try reader.unsafeRead { ... )
|
||||
/// }
|
||||
/// - warning: Database operations may not be wrapped in a transaction. They
|
||||
/// may see changes performed by concurrent writes or writes performed by
|
||||
/// other processes: two identical requests performed by the `value`
|
||||
/// closure may not return the same value.
|
||||
/// - warning: Attempts to write in the database may succeed.
|
||||
///
|
||||
/// - parameter value: A function that accesses the database.
|
||||
/// - throws: The error thrown by `value`, or any `DatabaseError` that would
|
||||
/// happen while establishing the read access to the database.
|
||||
/// - 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.
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T
|
||||
|
||||
/// Asynchronously executes a function that accepts a database connection.
|
||||
/// Schedules database operations for execution, and returns immediately.
|
||||
///
|
||||
/// The guarantees of the `asyncRead` method are lifted:
|
||||
/// This method is "unsafe" because the database reader does nothing more
|
||||
/// than providing a database connection. When you use this method, you
|
||||
/// become responsible for the thread-safety of your application, and
|
||||
/// responsible for database accesses performed by other processes. See
|
||||
/// <doc:Concurrency#Safe-and-Unsafe-Database-Accesses> for
|
||||
/// more information.
|
||||
///
|
||||
/// the `value` function is not isolated: eventual concurrent database
|
||||
/// updates are visible from the function:
|
||||
/// For example:
|
||||
///
|
||||
/// reader.asyncUnsafeRead { dbResult in
|
||||
/// do {
|
||||
/// let db = try dbResult.get()
|
||||
/// // Those two values can be different, because some other
|
||||
/// // database connection or some other thread may modify the
|
||||
/// // database between the two requests.
|
||||
/// let count1 = try Player.fetchCount(db)
|
||||
/// let count2 = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // handle error
|
||||
/// }
|
||||
/// ```swift
|
||||
/// reader.asyncUnsafeRead { dbResult in
|
||||
/// do {
|
||||
/// let db = try dbResult.get()
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // handle error
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The `value` function is not prevented from writing (DatabaseQueue, in
|
||||
/// particular, will accept database modifications in `asyncUnsafeRead`).
|
||||
/// - warning: Database operations may not be wrapped in a transaction. They
|
||||
/// may see changes performed by concurrent writes or writes performed by
|
||||
/// other processes: two identical requests performed by the `value`
|
||||
/// closure may not return the same value.
|
||||
/// - warning: Attempts to write in the database may succeed.
|
||||
///
|
||||
/// - parameter value: A function that accesses the database. Its argument
|
||||
/// - parameter value: A closure which accesses the database. Its argument
|
||||
/// is a `Result` that provides the database connection, or the failure
|
||||
/// that would prevent establishing the read access to the database.
|
||||
func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void)
|
||||
|
||||
/// Synchronously executes a function that accepts a database
|
||||
/// connection, and returns its result.
|
||||
/// Executes database operations, and returns their result after they have
|
||||
/// finished executing.
|
||||
///
|
||||
/// The guarantees of the safe `read` method are lifted:
|
||||
/// This method is "unsafe" because the database reader does nothing more
|
||||
/// than providing a database connection. When you use this method, you
|
||||
/// become responsible for the thread-safety of your application, and
|
||||
/// responsible for database accesses performed by other processes. See
|
||||
/// <doc:Concurrency#Safe-and-Unsafe-Database-Accesses> for
|
||||
/// more information.
|
||||
///
|
||||
/// the `value` function is not isolated: eventual concurrent database
|
||||
/// updates are visible from the function:
|
||||
/// This method can be called from other database access methods. If called
|
||||
/// from the dispatch queue of a current database access (read or write),
|
||||
/// the `Database` argument to `value` is the same as the current
|
||||
/// database access.
|
||||
///
|
||||
/// try reader.unsafeReentrantRead { db in
|
||||
/// // Those two values can be different, because some other
|
||||
/// // database connection or some other thread may modify the
|
||||
/// // database between the two requests.
|
||||
/// let count1 = try Player.fetchCount(db)
|
||||
/// let count2 = try Player.fetchCount(db)
|
||||
/// }
|
||||
/// Reentrant database accesses are discouraged because they muddle
|
||||
/// transaction boundaries
|
||||
/// (see <doc:Concurrency#Rule-2:-Mind-your-transactions> for
|
||||
/// more information).
|
||||
///
|
||||
/// The `value` function is not prevented from writing (DatabaseQueue, in
|
||||
/// particular, will accept database modifications in `unsafeRead`).
|
||||
/// For example:
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
/// ```swift
|
||||
/// let count = try reader.unsafeReentrantRead { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter value: A function that accesses the database.
|
||||
/// - throws: The error thrown by `value`, or any `DatabaseError` that would
|
||||
/// happen while establishing the read access to the database.
|
||||
/// The ``Database`` argument to `value` is valid only during the execution
|
||||
/// of the closure. Do not store or return the database connection for
|
||||
/// later use.
|
||||
///
|
||||
/// - warning: Database operations may not be wrapped in a transaction. They
|
||||
/// may see changes performed by concurrent writes or writes performed by
|
||||
/// other processes: two identical requests performed by the `value`
|
||||
/// closure may not return the same value.
|
||||
/// - warning: Attempts to write in the database may succeed.
|
||||
///
|
||||
/// - 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.
|
||||
func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T
|
||||
|
||||
|
||||
@@ -277,16 +318,14 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
|
||||
/// Starts a value observation.
|
||||
///
|
||||
/// You should use the `ValueObservation.start(in:onError:onChange:)`
|
||||
/// Use the ``ValueObservation/start(in:scheduling:onError:onChange:)``
|
||||
/// method instead.
|
||||
///
|
||||
/// - parameter observation: the stared observation
|
||||
/// - returns: a cancellable
|
||||
///
|
||||
/// :nodoc:
|
||||
/// - parameter observation: a ValueObservation.
|
||||
/// - 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
|
||||
}
|
||||
@@ -306,31 +345,32 @@ extension DatabaseReader {
|
||||
///
|
||||
/// Usage:
|
||||
///
|
||||
/// let source: DatabaseQueue = ...
|
||||
/// let destination: DatabaseQueue = ...
|
||||
/// try source.backup(to: destination)
|
||||
/// ```swift
|
||||
/// let source: DatabaseQueue = ...
|
||||
/// let destination: DatabaseQueue = ...
|
||||
/// try source.backup(to: destination)
|
||||
/// ```
|
||||
///
|
||||
/// When you're after progress reporting during backup, you'll want to
|
||||
/// perform the backup in several steps. Each step copies the number of
|
||||
/// _database pages_ you specify. See <https://www.sqlite.org/c3ref/backup_finish.html>
|
||||
/// for more information:
|
||||
///
|
||||
/// // Backup with progress reporting
|
||||
/// try source.backup(
|
||||
/// to: destination,
|
||||
/// pagesPerStep: ...)
|
||||
/// { backupProgress in
|
||||
/// print("Database backup progress:", backupProgress)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// // Backup with progress reporting
|
||||
/// try source.backup(to: destination, pagesPerStep: ...) { progress in
|
||||
/// print("Database backup progress:", progress)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The `progress` callback will be called at least once—when
|
||||
/// `backupProgress.isCompleted == true`. If the callback throws
|
||||
/// when `backupProgress.isCompleted == false`, the backup is aborted
|
||||
/// and the error is rethrown. If the callback throws when
|
||||
/// and the error is rethrown. If the callback throws when
|
||||
/// `backupProgress.isCompleted == true`, backup completion is
|
||||
/// unaffected and the error is silently ignored.
|
||||
///
|
||||
/// See also `Database.backup()`.
|
||||
/// See also ``Database/backup(to:pagesPerStep:progress:)``
|
||||
///
|
||||
/// - parameters:
|
||||
/// - writer: The destination database.
|
||||
@@ -338,8 +378,8 @@ extension DatabaseReader {
|
||||
/// step. By default, all pages are copied in one single step.
|
||||
/// - progress: An optional function that is notified of the backup
|
||||
/// progress.
|
||||
/// - throws: The error thrown by `progress` if the backup is abandoned, or
|
||||
/// any `DatabaseError` that would happen while performing the backup.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or the
|
||||
/// error thrown by `progress`.
|
||||
public func backup(
|
||||
to writer: some DatabaseWriter,
|
||||
pagesPerStep: CInt = -1,
|
||||
@@ -374,40 +414,34 @@ extension DatabaseReader {
|
||||
extension DatabaseReader {
|
||||
// MARK: - Asynchronous Database Access
|
||||
|
||||
/// Asynchronously executes a read-only function that accepts a database
|
||||
/// connection, and returns its result.
|
||||
/// Executes read-only database operations, and returns their result after
|
||||
/// they have finished executing.
|
||||
///
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let count = try await reader.read { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// let count = try await reader.read { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The `value` function runs in an isolated fashion: eventual concurrent
|
||||
/// database updates are not visible from the function:
|
||||
/// Database operations are isolated in a transaction: they do not see
|
||||
/// changes performed by eventual concurrent writes (even writes performed
|
||||
/// by other processes).
|
||||
///
|
||||
/// try await reader.read { db in
|
||||
/// // Those two values are guaranteed to be equal, even if the
|
||||
/// // `player` table is modified, between the two requests, by
|
||||
/// // some other database connection or some other thread.
|
||||
/// let count1 = try Player.fetchCount(db)
|
||||
/// let count2 = try Player.fetchCount(db)
|
||||
/// }
|
||||
/// The database connection is read-only: attempts to write throw a
|
||||
/// ``DatabaseError`` with resultCode `SQLITE_READONLY`.
|
||||
///
|
||||
/// try await reader.read { db in
|
||||
/// // Now this value may be different:
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// }
|
||||
/// The ``Database`` argument to `value` is valid only during the execution
|
||||
/// of the closure. Do not store or return the database connection for
|
||||
/// later use.
|
||||
///
|
||||
/// Attempts to write in the database throw a DatabaseError with
|
||||
/// resultCode `SQLITE_READONLY`.
|
||||
///
|
||||
/// - parameter value: A function that accesses the database.
|
||||
/// - throws: The error thrown by `value`, or any `DatabaseError` that would
|
||||
/// happen while establishing the read access to the database.
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
/// - 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(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
|
||||
@@ -420,36 +454,40 @@ extension DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
/// Asynchronously executes a function that accepts a database connection.
|
||||
/// Executes database operations, and returns their result after they have
|
||||
/// finished executing.
|
||||
///
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// This method is "unsafe" because the database reader does nothing more
|
||||
/// than providing a database connection. When you use this method, you
|
||||
/// become responsible for the thread-safety of your application, and
|
||||
/// responsible for database accesses performed by other processes. See
|
||||
/// <doc:Concurrency#Safe-and-Unsafe-Database-Accesses> for
|
||||
/// more information.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let count = try await reader.unsafeRead { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// let count = try await reader.unsafeRead { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The guarantees of the `read` method are lifted:
|
||||
/// The ``Database`` argument to `value` is valid only during the execution
|
||||
/// of the closure. Do not store or return the database connection for
|
||||
/// later use.
|
||||
///
|
||||
/// the `value` function is not isolated: eventual concurrent database
|
||||
/// updates are visible from the function:
|
||||
/// - warning: Database operations may not be wrapped in a transaction. They
|
||||
/// may see changes performed by concurrent writes or writes performed by
|
||||
/// other processes: two identical requests performed by the `value`
|
||||
/// closure may not return the same value.
|
||||
/// - warning: Attempts to write in the database may succeed.
|
||||
///
|
||||
/// try await reader.asyncRead { db in
|
||||
/// // Those two values can be different, because some other
|
||||
/// // database connection or some other thread may modify the
|
||||
/// // database between the two requests.
|
||||
/// let count1 = try Player.fetchCount(db)
|
||||
/// let count2 = try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// The `value` function is not prevented from writing (DatabaseQueue, in
|
||||
/// particular, will accept database modifications in `asyncUnsafeRead`).
|
||||
///
|
||||
/// - parameter value: A function that accesses the database.
|
||||
/// - throws: The error thrown by `value`, or any `DatabaseError` that would
|
||||
/// happen while establishing the read access to the database.
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
/// - 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(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
|
||||
@@ -467,41 +505,38 @@ extension DatabaseReader {
|
||||
extension DatabaseReader {
|
||||
// MARK: - Publishing Database Values
|
||||
|
||||
/// Returns a Publisher that asynchronously completes with a fetched value.
|
||||
/// Returns a publisher that publishes one value and completes.
|
||||
///
|
||||
/// // DatabasePublishers.Read<[Player]>
|
||||
/// let players = dbQueue.readPublisher { db in
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
/// The database is not accessed until subscription. Value and completion
|
||||
/// are published on `scheduler` (the main dispatch queue by default).
|
||||
///
|
||||
/// Its value and completion are emitted on the main dispatch queue.
|
||||
/// For example:
|
||||
///
|
||||
/// - parameter value: A closure which accesses the database.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func readPublisher<Output>(
|
||||
value: @escaping (Database) throws -> Output)
|
||||
-> DatabasePublishers.Read<Output>
|
||||
{
|
||||
readPublisher(receiveOn: DispatchQueue.main, value: value)
|
||||
}
|
||||
|
||||
/// Returns a Publisher that asynchronously completes with a fetched value.
|
||||
/// ```swift
|
||||
/// // DatabasePublishers.Read<Int>
|
||||
/// let countPublisher = reader.readPublisher { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// // DatabasePublishers.Read<[Player]>
|
||||
/// let players = dbQueue.readPublisher(
|
||||
/// receiveOn: DispatchQueue.global(),
|
||||
/// value: { db in try Player.fetchAll(db) })
|
||||
/// Database operations are isolated in a transaction: they do not see
|
||||
/// changes performed by eventual concurrent writes (even writes performed
|
||||
/// by other processes).
|
||||
///
|
||||
/// Its value and completion are emitted on `scheduler`.
|
||||
/// The database connection is read-only: attempts to write throw a
|
||||
/// ``DatabaseError`` with resultCode `SQLITE_READONLY`.
|
||||
///
|
||||
/// The ``Database`` argument to `value` is valid only during the execution
|
||||
/// of the closure. Do not store or return the database connection for
|
||||
/// later use.
|
||||
///
|
||||
/// - parameter scheduler: A Combine Scheduler.
|
||||
/// - parameter value: A closure which accesses the database.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func readPublisher<S, Output>(
|
||||
receiveOn scheduler: S,
|
||||
@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)
|
||||
-> DatabasePublishers.Read<Output>
|
||||
where S: Scheduler
|
||||
{
|
||||
Deferred {
|
||||
Future { fulfill in
|
||||
@@ -515,15 +550,13 @@ 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 a value from the database. It publishes exactly
|
||||
/// one element, or an error.
|
||||
/// A publisher that reads from the database.
|
||||
///
|
||||
/// See:
|
||||
/// `Read` publishes exactly one element, or an error.
|
||||
///
|
||||
/// - `DatabaseReader.readPublisher(receiveOn:value:)`.
|
||||
/// - `DatabaseReader.readPublisher(value:)`.
|
||||
/// You build such a publisher from ``DatabaseReader``.
|
||||
public struct Read<Output>: Publisher {
|
||||
public typealias Output = Output
|
||||
public typealias Failure = Error
|
||||
@@ -536,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())
|
||||
@@ -551,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
|
||||
{
|
||||
@@ -592,18 +625,21 @@ extension DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
/// A type-erased DatabaseReader
|
||||
/// A type-erased database reader.
|
||||
///
|
||||
/// Instances of AnyDatabaseReader forward their methods to an arbitrary
|
||||
/// underlying database reader.
|
||||
public final class AnyDatabaseReader: DatabaseReader {
|
||||
/// An instance of `AnyDatabaseReader` forwards its operations to an underlying
|
||||
/// base database reader.
|
||||
public final class AnyDatabaseReader {
|
||||
private let base: any DatabaseReader
|
||||
|
||||
/// Creates a database reader that wraps a base database reader.
|
||||
/// Creates a new database reader that wraps and forwards operations
|
||||
/// to `base`.
|
||||
public init(_ base: some DatabaseReader) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension AnyDatabaseReader: DatabaseReader {
|
||||
public var configuration: Configuration {
|
||||
base.configuration
|
||||
}
|
||||
@@ -612,14 +648,10 @@ public final class AnyDatabaseReader: DatabaseReader {
|
||||
try base.close()
|
||||
}
|
||||
|
||||
// MARK: - Interrupting Database Operations
|
||||
|
||||
public func interrupt() {
|
||||
base.interrupt()
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func read<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try base.read(value)
|
||||
@@ -642,12 +674,9 @@ public final class AnyDatabaseReader: DatabaseReader {
|
||||
try base.unsafeReentrantRead(value)
|
||||
}
|
||||
|
||||
// MARK: - Value Observation
|
||||
|
||||
/// :nodoc:
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
@@ -657,3 +686,58 @@ public final class AnyDatabaseReader: DatabaseReader {
|
||||
onChange: onChange)
|
||||
}
|
||||
}
|
||||
|
||||
/// A type that sees an unchanging database content.
|
||||
///
|
||||
/// Do not declare new conformances to `DatabaseSnapshotReader`. Only the
|
||||
/// built-in conforming types are valid.
|
||||
///
|
||||
/// The protocol comes with the same features and guarantees as
|
||||
/// ``DatabaseReader``. On top of them, a `DatabaseSnapshotReader` always sees
|
||||
/// the same state of the database.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Reading from the Database
|
||||
///
|
||||
/// - ``reentrantRead(_:)``
|
||||
public protocol DatabaseSnapshotReader: DatabaseReader { }
|
||||
|
||||
extension DatabaseSnapshotReader {
|
||||
/// Executes database operations, and returns their result after they have
|
||||
/// finished executing.
|
||||
///
|
||||
/// This method can be called from other database access methods. If called
|
||||
/// from the dispatch queue of a current database access, the `Database`
|
||||
/// argument to `value` is the same as the current database access.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let count = try snapshot.reentrantRead { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The ``Database`` argument to `value` is valid only during the execution
|
||||
/// of the closure. Do not store or return the database connection for
|
||||
/// later use.
|
||||
///
|
||||
/// - 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.
|
||||
public func reentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
// Reentrant reads are safe in a snapshot
|
||||
try unsafeReentrantRead(value)
|
||||
}
|
||||
|
||||
// There is no such thing as an unsafe access to a snapshot.
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try read(value)
|
||||
}
|
||||
|
||||
// There is no such thing as an unsafe access to a snapshot.
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
asyncRead(value)
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
/// DatabaseRegion defines a region in the database. DatabaseRegion is dedicated
|
||||
/// to help transaction observers recognize impactful database changes in their
|
||||
/// `observes(eventsOfKind:)` and `databaseDidChange(with:)` methods.
|
||||
/// An observable region of the database.
|
||||
///
|
||||
/// A database region is the union of any number of "table regions", which can
|
||||
/// cover a full table, or the combination of columns and rows:
|
||||
/// A `DatabaseRegion` is the union of any number of "table regions", which can
|
||||
/// cover a full table, or the combination of columns and rows identified by
|
||||
/// their rowids:
|
||||
///
|
||||
/// |Table1 | |Table2 | |Table3 | |Table4 | |Table5 |
|
||||
/// |-------| |-------| |-------| |-------| |-------|
|
||||
@@ -12,24 +11,36 @@
|
||||
/// |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | |
|
||||
/// |x|x|x|x| |x| | | | | | | | | | | | | | | | | | |
|
||||
///
|
||||
/// To create a database region, you use one of those methods:
|
||||
/// It is dedicated to help ``TransactionObserver`` types detect impactful
|
||||
/// database changes.
|
||||
///
|
||||
/// - `DatabaseRegion.fullDatabase`: the region that covers all database tables.
|
||||
/// You get `DatabaseRegion` instances from a ``DatabaseRegionConvertible``
|
||||
/// value, a prepared ``Statement``, or from the initializers described below.
|
||||
///
|
||||
/// - `DatabaseRegion()`: the empty region.
|
||||
/// ## Topics
|
||||
///
|
||||
/// - `DatabaseRegion(table:)`: the region that covers one database table.
|
||||
/// ### Creating Regions
|
||||
///
|
||||
/// - `Statement.databaseRegion`:
|
||||
/// - ``fullDatabase-3ir3p``
|
||||
/// - ``init()``
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name, score FROM player")
|
||||
/// let region = statement.databaseRegion
|
||||
/// ### Instance Properties
|
||||
///
|
||||
/// - `FetchRequest.databaseRegion(_:)`
|
||||
/// - ``isEmpty``
|
||||
/// - ``isFullDatabase``
|
||||
///
|
||||
/// let request = Player.filter(key: 1)
|
||||
/// let region = try request.databaseRegion(db)
|
||||
public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
/// ### Combining Regions
|
||||
///
|
||||
/// - ``formUnion(_:)``
|
||||
/// - ``union(_:)``
|
||||
///
|
||||
/// ### Detecting Database Changes
|
||||
///
|
||||
/// Use those methods from ``TransactionObserver`` methods.
|
||||
///
|
||||
/// - ``isModified(byEventsOfKind:)``
|
||||
/// - ``isModified(by:)``
|
||||
public struct DatabaseRegion {
|
||||
private let tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
|
||||
|
||||
private init(tableRegions: [CaseInsensitiveIdentifier: TableRegion]?) {
|
||||
@@ -45,17 +56,15 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
return tableRegions.isEmpty
|
||||
}
|
||||
|
||||
/// Returns whether the region covers the full database: all columns and all
|
||||
/// rows from all tables.
|
||||
/// Returns whether the region covers the full database.
|
||||
public var isFullDatabase: Bool {
|
||||
tableRegions == nil
|
||||
}
|
||||
|
||||
/// The region that covers the full database: all columns and all rows
|
||||
/// from all tables.
|
||||
/// The region that covers the full database.
|
||||
public static let fullDatabase = DatabaseRegion(tableRegions: nil)
|
||||
|
||||
/// Creates an empty database region.
|
||||
/// The empty database region.
|
||||
public init() {
|
||||
self.init(tableRegions: [:])
|
||||
}
|
||||
@@ -159,9 +168,14 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
// 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.
|
||||
@@ -181,11 +195,11 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
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)
|
||||
}
|
||||
@@ -226,9 +240,7 @@ extension DatabaseRegion {
|
||||
}
|
||||
}
|
||||
|
||||
// Equatable
|
||||
extension DatabaseRegion {
|
||||
/// :nodoc:
|
||||
extension DatabaseRegion: Equatable {
|
||||
public static func == (lhs: DatabaseRegion, rhs: DatabaseRegion) -> Bool {
|
||||
switch (lhs.tableRegions, rhs.tableRegions) {
|
||||
case (nil, nil):
|
||||
@@ -249,9 +261,7 @@ extension DatabaseRegion {
|
||||
}
|
||||
}
|
||||
|
||||
// CustomStringConvertible
|
||||
extension DatabaseRegion {
|
||||
/// :nodoc:
|
||||
extension DatabaseRegion: CustomStringConvertible {
|
||||
public var description: String {
|
||||
guard let tableRegions else {
|
||||
return "full database"
|
||||
@@ -282,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
|
||||
}
|
||||
|
||||
@@ -337,10 +347,42 @@ private struct TableRegion: Equatable {
|
||||
|
||||
// MARK: - DatabaseRegionConvertible
|
||||
|
||||
/// `DatabaseRegionConvertible` is the protocol for values that can be turned
|
||||
/// into a `DatabaseRegion`.
|
||||
/// A type that operates on a specific ``DatabaseRegion``.
|
||||
///
|
||||
/// Such values specify the region observed by `DatabaseRegionObservation`.
|
||||
/// A `DatabaseRegionConvertible` instance feeds database observation tools such
|
||||
/// as ``DatabaseRegionObservation`` and ``ValueObservation``:
|
||||
///
|
||||
/// ```swift
|
||||
/// // An observation triggered by all changes to the database
|
||||
/// DatabaseRegionObservation(tracking: .fullDatabase)
|
||||
///
|
||||
/// // An observation triggered by all changes to the 'player' table
|
||||
/// DatabaseRegionObservation(tracking: Table("player"))
|
||||
///
|
||||
/// // An observation triggered by all changes to the row
|
||||
/// // with rowid 1 in the 'player' table
|
||||
/// DatabaseRegionObservation(tracking: Player.filter(id: 1))
|
||||
///
|
||||
/// // An observation triggered by all changes to the 'score' column
|
||||
/// // of the 'player' table
|
||||
/// DatabaseRegionObservation(tracking: SQLRequest("SELECT score FROM player"))
|
||||
/// ```
|
||||
///
|
||||
/// Specifying a region from a ``FetchRequest`` does not execute the request.
|
||||
/// In the above example, `Player.filter(id: 1)` and `SELECT score FROM player`
|
||||
/// are only compiled by SQLite, so that GRDB can understand the tables, rows,
|
||||
/// and columns that constitute the database region.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a DatabaseRegion
|
||||
///
|
||||
/// - ``fullDatabase``
|
||||
/// - ``databaseRegion(_:)``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``AnyDatabaseRegionConvertible``
|
||||
public protocol DatabaseRegionConvertible {
|
||||
/// Returns a database region.
|
||||
///
|
||||
@@ -355,7 +397,6 @@ extension DatabaseRegionConvertible where Self == DatabaseRegion {
|
||||
}
|
||||
|
||||
extension DatabaseRegion: DatabaseRegionConvertible {
|
||||
/// :nodoc:
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
self
|
||||
}
|
||||
@@ -373,7 +414,6 @@ public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
|
||||
_region = region.databaseRegion
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
try _region(db)
|
||||
}
|
||||
|
||||
@@ -3,19 +3,6 @@ import Combine
|
||||
#endif
|
||||
import Foundation
|
||||
|
||||
/// DatabaseRegionObservation tracks changes in the results of database
|
||||
/// requests, and notifies each database transaction whenever the
|
||||
/// database changes.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let observation = DatabaseRegionObservation(tracking: Player.all)
|
||||
/// let cancellable = try observation.start(
|
||||
/// in: dbQueue,
|
||||
/// onError: { error in ... },
|
||||
/// onChange: { (db: Database) in
|
||||
/// print("A modification of the player table has just been committed.")
|
||||
/// })
|
||||
public struct DatabaseRegionObservation {
|
||||
/// A closure that is evaluated when the observation starts, and returns
|
||||
/// the observed database region.
|
||||
@@ -23,51 +10,32 @@ public struct DatabaseRegionObservation {
|
||||
}
|
||||
|
||||
extension DatabaseRegionObservation {
|
||||
/// Creates a DatabaseRegionObservation which observes *regions*, and
|
||||
/// notifies whenever one of the observed regions is modified by a
|
||||
/// database transaction.
|
||||
/// Creates a `DatabaseRegionObservation` that notifies all transactions
|
||||
/// that modify one of the provided regions.
|
||||
///
|
||||
/// For example, this sample code counts the number of a times the player
|
||||
/// table is modified:
|
||||
/// For example:
|
||||
///
|
||||
/// let observation = DatabaseRegionObservation(tracking: Player.all())
|
||||
///
|
||||
/// var count = 0
|
||||
/// let cancellable = observation.start(
|
||||
/// in: dbQueue,
|
||||
/// onError: { error in ... },
|
||||
/// onChange: { _ in
|
||||
/// count += 1
|
||||
/// print("Players have been modified \(count) times.")
|
||||
/// }à
|
||||
///
|
||||
/// The observation lasts until the cancellable returned by `start` is
|
||||
/// cancelled or deallocated.
|
||||
/// ```swift
|
||||
/// // An observation that tracks the 'player' table
|
||||
/// let observation = DatabaseRegionObservation(tracking: Player.all())
|
||||
/// ```
|
||||
///
|
||||
/// - parameter regions: A list of observed regions.
|
||||
public init(tracking regions: any DatabaseRegionConvertible...) {
|
||||
self.init(tracking: regions)
|
||||
}
|
||||
|
||||
/// Creates a DatabaseRegionObservation which observes *regions*, and
|
||||
/// notifies whenever one of the observed regions is modified by a
|
||||
/// database transaction.
|
||||
/// Creates a `DatabaseRegionObservation` that notifies all transactions
|
||||
/// that modify one of the provided regions.
|
||||
///
|
||||
/// For example, this sample code counts the number of a times the player
|
||||
/// table is modified:
|
||||
/// For example:
|
||||
///
|
||||
/// let observation = DatabaseRegionObservation(tracking: [Player.all()])
|
||||
/// ```swift
|
||||
/// // An observation that tracks the 'player' table
|
||||
/// let observation = DatabaseRegionObservation(tracking: [Player.all()])
|
||||
/// ```
|
||||
///
|
||||
/// var count = 0
|
||||
/// let cancellable = observation.start(in: dbQueue) { _ in
|
||||
/// count += 1
|
||||
/// print("Players have been modified \(count) times.")
|
||||
/// }
|
||||
///
|
||||
/// The observation lasts until the cancellable returned by `start` is
|
||||
/// cancelled or deallocated.
|
||||
///
|
||||
/// - parameter regions: A list of observed regions.
|
||||
/// - parameter regions: An array of observed regions.
|
||||
public init(tracking regions: [any DatabaseRegionConvertible]) {
|
||||
self.init(observedRegion: DatabaseRegion.union(regions))
|
||||
}
|
||||
@@ -81,29 +49,40 @@ extension DatabaseRegionObservation {
|
||||
case started(DatabaseRegionObserver)
|
||||
}
|
||||
|
||||
/// Starts the observation in the provided database writer (such as
|
||||
/// a database queue or database pool), and returns a transaction observer.
|
||||
/// Starts observing the database.
|
||||
///
|
||||
/// The observation lasts until the returned cancellable is cancelled
|
||||
/// or deallocated.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let observation = DatabaseRegionObservation.tracking(Player.all())
|
||||
/// let cancellable = observation.start(
|
||||
/// in: dbQueue,
|
||||
/// onError: { error in ... },
|
||||
/// onChange: { (db: Database) in
|
||||
/// print("A modification of the player table has just been committed.")
|
||||
/// })
|
||||
/// ```swift
|
||||
/// let observation = DatabaseRegionObservation(tracking: Player.all())
|
||||
///
|
||||
/// If the `start` method is called from a writing database access method,
|
||||
/// the observation of impactful transactions starts immediately. Otherwise,
|
||||
/// it blocks the current thread until a write access can be established.
|
||||
/// let cancellable = try observation.start(in: dbQueue) { error in
|
||||
/// // handle error
|
||||
/// } onChange: { (db: Database) in
|
||||
/// print("A modification of the player table has just been committed.")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// If this method is called from the writer dispatch queue of `writer` (see
|
||||
/// ``DatabaseWriter``), the observation starts immediately. Otherwise, it
|
||||
/// blocks the current thread until a write access can be established.
|
||||
///
|
||||
/// Both `onError` and `onChange` closures are executed in the writer
|
||||
/// dispatch queue, serialized with all database updates performed
|
||||
/// by `writer`.
|
||||
///
|
||||
/// The ``Database`` argument to `onChange` is valid only during the
|
||||
/// execution of the closure. Do not store or return the database connection
|
||||
/// for later use.
|
||||
///
|
||||
/// - parameter writer: A DatabaseWriter.
|
||||
/// - parameter onError: A closure that is provided eventual errors that
|
||||
/// happen during observation
|
||||
/// - parameter onChange: A closure that is provided a database connection
|
||||
/// with write access each time the observed region has been modified.
|
||||
/// - returns: a cancellable.
|
||||
/// - parameter onError: The closure to execute when the observation fails.
|
||||
/// - parameter onChange: The closure to execute when a transaction has
|
||||
/// modified the observed region.
|
||||
/// - returns: A DatabaseCancellable that can stop the observation.
|
||||
public func start(
|
||||
in writer: some DatabaseWriter,
|
||||
onError: @escaping (Error) -> Void,
|
||||
@@ -149,17 +128,19 @@ 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
|
||||
|
||||
/// Returns a publisher that tracks changes in a database region.
|
||||
/// Returns a publisher that observes the database.
|
||||
///
|
||||
/// It emits database connections on a protected dispatch queue.
|
||||
/// The publisher publishes ``Database`` connections on the writer dispatch
|
||||
/// queue of `writer` (see ``DatabaseWriter``). Those connections are valid
|
||||
/// only when published. Do not store or return them for later use.
|
||||
///
|
||||
/// Error completion, if any, is only emitted, synchronously,
|
||||
/// on subscription.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
/// Do not reschedule the publisher with `receive(on:options:)` or any
|
||||
/// `Publisher` method that schedules publisher elements.
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func publisher(in writer: some DatabaseWriter) -> DatabasePublishers.DatabaseRegion {
|
||||
DatabasePublishers.DatabaseRegion(self, in: writer)
|
||||
}
|
||||
@@ -200,11 +181,11 @@ 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 changes in a database region.
|
||||
/// A publisher that tracks transactions that modify a database region.
|
||||
///
|
||||
/// See `DatabaseRegionObservation.publisher(in:)`.
|
||||
/// You build such a publisher from ``DatabaseRegionObservation``.
|
||||
public struct DatabaseRegion: Publisher {
|
||||
public typealias Output = Database
|
||||
public typealias Failure = Error
|
||||
@@ -217,7 +198,6 @@ extension DatabasePublishers {
|
||||
self.observation = observation
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
|
||||
let subscription = DatabaseRegionSubscription(
|
||||
writer: writer,
|
||||
|
||||
@@ -1,93 +1,176 @@
|
||||
import Dispatch
|
||||
|
||||
/// A DatabaseSnapshot sees an unchanging database content, as it existed at the
|
||||
/// moment it was created.
|
||||
/// A database connection that serializes accesses to an unchanging
|
||||
/// database content, as it existed at the moment the snapshot was created.
|
||||
///
|
||||
/// See DatabasePool.makeSnapshot()
|
||||
/// ## Overview
|
||||
///
|
||||
/// For more information, read about "snapshot isolation" at <https://sqlite.org/isolation.html>
|
||||
public final class DatabaseSnapshot: DatabaseReader {
|
||||
private let serializedDatabase: SerializedDatabase
|
||||
/// A `DatabaseSnapshot` never sees any database modification during all its
|
||||
/// lifetime. All database accesses performed from a snapshot always see the
|
||||
/// same identical database content.
|
||||
///
|
||||
/// A snapshot creates one single SQLite connection. All database
|
||||
/// accesses are executed in a serial **reader dispatch queue**. The SQLite
|
||||
/// connection is closed when the `DatabaseSnapshot` is deallocated.
|
||||
///
|
||||
/// A snapshot created on a [WAL](https://sqlite.org/wal.html) database doesn't
|
||||
/// prevent database modifications performed by other connections (but it won't
|
||||
/// see them). Refer to [Isolation In SQLite](https://sqlite.org/isolation.html)
|
||||
/// for more information.
|
||||
///
|
||||
/// On non-WAL databases, a snapshot prevents all database modifications as long
|
||||
/// as it exists, because of the
|
||||
/// [SHARED lock](https://www.sqlite.org/lockingv3.html) it holds.
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// You create instances of `DatabaseSnapshot` from a ``DatabasePool``,
|
||||
/// with ``DatabasePool/makeSnapshot()``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
/// let playerCount = try snapshot.read { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When you want to control the database state seen by a snapshot, create the
|
||||
/// snapshot from within a write access, outside of any transaction.
|
||||
///
|
||||
/// For example, compare the two snapshots below. The first one is guaranteed to
|
||||
/// see an empty table of players, because is is created after all players have
|
||||
/// been deleted, and from the serialized writer dispatch queue which prevents
|
||||
/// any concurrent write. The second is created without this concurrency
|
||||
/// protection, which means that some other threads may already have created
|
||||
/// some players:
|
||||
///
|
||||
/// ```swift
|
||||
/// let snapshot1 = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshot in
|
||||
/// try db.inTransaction {
|
||||
/// try Player.deleteAll()
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// return try dbPool.makeSnapshot()
|
||||
/// }
|
||||
///
|
||||
/// // <- Other threads may have created some players here
|
||||
/// let snapshot2 = try dbPool.makeSnapshot()
|
||||
///
|
||||
/// // Guaranteed to be zero
|
||||
/// let count1 = try snapshot1.read(Player.fetchCount)
|
||||
///
|
||||
/// // Could be anything
|
||||
/// let count2 = try snapshot2.read(Player.fetchCount)
|
||||
/// ```
|
||||
///
|
||||
/// `DatabaseSnapshot` inherits its database access methods from the
|
||||
/// ``DatabaseReader`` protocols.
|
||||
///
|
||||
/// `DatabaseSnapshot` serializes database accesses and can't perform concurrent
|
||||
/// reads. For concurrent reads, see ``DatabaseSnapshotPool``.
|
||||
public final class DatabaseSnapshot {
|
||||
private let reader: SerializedDatabase
|
||||
|
||||
/// The database configuration
|
||||
public var configuration: Configuration {
|
||||
serializedDatabase.configuration
|
||||
reader.configuration
|
||||
}
|
||||
|
||||
init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws {
|
||||
var configuration = DatabasePool.readerConfiguration(configuration)
|
||||
configuration.allowsUnsafeTransactions = true // Snaphost keeps a long-lived transaction
|
||||
/// The path to the database file.
|
||||
public var path: String {
|
||||
reader.path
|
||||
}
|
||||
|
||||
init(
|
||||
path: String,
|
||||
configuration: Configuration,
|
||||
defaultLabel: String = "GRDB.DatabaseSnapshot",
|
||||
purpose: String? = nil)
|
||||
throws
|
||||
{
|
||||
let configuration = Self.configure(configuration)
|
||||
|
||||
serializedDatabase = try SerializedDatabase(
|
||||
reader = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
defaultLabel: defaultLabel,
|
||||
purpose: purpose)
|
||||
|
||||
try serializedDatabase.sync { db in
|
||||
// Assert WAL mode
|
||||
let journalMode = try String.fetchOne(db, sql: "PRAGMA journal_mode")
|
||||
guard journalMode == "wal" else {
|
||||
throw DatabaseError(message: "WAL mode is not activated at path: \(path)")
|
||||
}
|
||||
|
||||
try reader.sync { db in
|
||||
// Open transaction
|
||||
try db.beginTransaction(.deferred)
|
||||
|
||||
// Acquire snapshot isolation
|
||||
try db.internalCachedStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next()
|
||||
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
// Leave snapshot isolation
|
||||
serializedDatabase.reentrantSync { db in
|
||||
reader.reentrantSync { db in
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
|
||||
public func close() throws {
|
||||
try serializedDatabase.sync { try $0.close() }
|
||||
private static func configure(_ configuration: Configuration) -> Configuration {
|
||||
var configuration = configuration
|
||||
|
||||
// DatabaseSnapshot can't perform parallel reads.
|
||||
configuration.maximumReaderCount = 1
|
||||
|
||||
// DatabaseSnapshot is read-only.
|
||||
configuration.readonly = true
|
||||
|
||||
// DatabaseSnapshot uses deferred transactions by default.
|
||||
// Other transaction kinds are forbidden by SQLite in read-only connections.
|
||||
configuration.defaultTransactionKind = .deferred
|
||||
|
||||
// DatabaseSnapshot keeps a long-lived transaction.
|
||||
configuration.allowsUnsafeTransactions = true
|
||||
|
||||
return configuration
|
||||
}
|
||||
}
|
||||
|
||||
// DatabaseReader
|
||||
extension DatabaseSnapshot {
|
||||
extension DatabaseSnapshot: DatabaseSnapshotReader {
|
||||
public func close() throws {
|
||||
try reader.sync { try $0.close() }
|
||||
}
|
||||
|
||||
// MARK: - Interrupting Database Operations
|
||||
|
||||
public func interrupt() {
|
||||
serializedDatabase.interrupt()
|
||||
reader.interrupt()
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
try serializedDatabase.sync(block)
|
||||
try reader.sync(block)
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
serializedDatabase.async { value(.success($0)) }
|
||||
reader.async { value(.success($0)) }
|
||||
}
|
||||
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) rethrows -> T {
|
||||
try serializedDatabase.sync(value)
|
||||
try reader.sync(value)
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
serializedDatabase.async { value(.success($0)) }
|
||||
reader.async { value(.success($0)) }
|
||||
}
|
||||
|
||||
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try serializedDatabase.reentrantSync(value)
|
||||
try reader.reentrantSync(value)
|
||||
}
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// :nodoc:
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
// swiftlint:disable:next line_length
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
/// A database connection that allows concurrent accesses to an unchanging
|
||||
/// database content, as it existed at the moment the snapshot was created.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// A `DatabaseSnapshotPool` never sees any database modification during all its
|
||||
/// lifetime. All database accesses performed from a snapshot always see the
|
||||
/// same identical database content.
|
||||
///
|
||||
/// It creates a pool of up to ``Configuration/maximumReaderCount`` read-only
|
||||
/// SQLite connections. All read accesses are executed in **reader dispatch
|
||||
/// queues** (one per read-only SQLite connection). SQLite connections are
|
||||
/// closed when the `DatabasePool` is deallocated.
|
||||
///
|
||||
/// An SQLite database in the [WAL mode](https://www.sqlite.org/wal.html) is
|
||||
/// required for creating a `DatabaseSnapshotPool`.
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// You create a `DatabaseSnapshotPool` from a
|
||||
/// [WAL mode](https://www.sqlite.org/wal.html) database, such as databases
|
||||
/// created from a ``DatabasePool``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
/// let snapshot = try dbPool.makeSnapshotPool()
|
||||
/// ```
|
||||
///
|
||||
/// When you want to control the database state seen by a snapshot, create the
|
||||
/// snapshot from a database connection, outside of a write transaction. You can
|
||||
/// for example take snapshots from a ``ValueObservation``:
|
||||
///
|
||||
/// ```swift
|
||||
/// // An observation of the 'player' table
|
||||
/// // that notifies fresh database snapshots:
|
||||
/// let observation = ValueObservation.tracking { db in
|
||||
/// // Don't fetch players now, and return a snapshot instead.
|
||||
/// // Register an access to the player table so that the
|
||||
/// // observation tracks changes to this table.
|
||||
/// try db.registerAccess(to: Player.all())
|
||||
/// return try DatabaseSnapshotPool(db)
|
||||
/// }
|
||||
///
|
||||
/// // Start observing the 'player' table
|
||||
/// let cancellable = try observation.start(in: dbPool) { error in
|
||||
/// // Handle error
|
||||
/// } onChange: { (snapshot: DatabaseSnapshotPool) in
|
||||
/// // Handle a fresh snapshot
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// `DatabaseSnapshotPool` inherits its database access methods from the
|
||||
/// ``DatabaseReader`` protocols.
|
||||
///
|
||||
/// Related SQLite documentation:
|
||||
///
|
||||
/// - <https://www.sqlite.org/c3ref/snapshot_get.html>
|
||||
/// - <https://www.sqlite.org/c3ref/snapshot_open.html>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a DatabaseSnapshotPool
|
||||
///
|
||||
/// See also ``DatabasePool/makeSnapshotPool()``.
|
||||
///
|
||||
/// - ``init(_:configuration:)``
|
||||
/// - ``init(path:configuration:)``
|
||||
public final class DatabaseSnapshotPool {
|
||||
public let configuration: Configuration
|
||||
|
||||
/// The path to the database file.
|
||||
public let path: String
|
||||
|
||||
/// The pool of reader connections.
|
||||
/// It is constant, until close() sets it to nil.
|
||||
private var readerPool: Pool<SerializedDatabase>?
|
||||
|
||||
/// The WAL snapshot
|
||||
private let walSnapshot: WALSnapshot
|
||||
|
||||
/// A connection that prevents checkpoints and keeps the WAL snapshot valid.
|
||||
/// It is never used.
|
||||
private let snapshotHolder: DatabaseQueue
|
||||
|
||||
/// Creates a snapshot of the database.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
/// let snapshot = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshotPool in
|
||||
/// try db.inTransaction {
|
||||
/// try Player.deleteAll()
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// // Create the snapshot after all players have been deleted.
|
||||
/// return DatabaseSnapshotPool(db)
|
||||
/// }
|
||||
///
|
||||
/// // Later... Maybe some players have been created.
|
||||
/// // The snapshot is guaranteed to see an empty table of players, though:
|
||||
/// let count = try snapshot.read(Player.fetchCount)
|
||||
/// assert(count == 0)
|
||||
/// ```
|
||||
///
|
||||
/// If any of the following statements are false when the snapshot is
|
||||
/// created, a ``DatabaseError`` of code `SQLITE_ERROR` is thrown:
|
||||
///
|
||||
/// - The database connection must be in the
|
||||
/// [WAL mode](https://www.sqlite.org/wal.html).
|
||||
/// - There must not be a write transaction open.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/snapshot_get.html>
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter configuration: A configuration. If nil, the configuration of
|
||||
/// `db` is used.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public init(_ db: Database, configuration: Configuration? = nil) throws {
|
||||
var configuration = Self.configure(configuration ?? db.configuration)
|
||||
|
||||
// Acquire and hold WAL snapshot
|
||||
let walSnapshot = try db.isolated(readOnly: true) {
|
||||
try WALSnapshot(db)
|
||||
}
|
||||
var holderConfig = Configuration()
|
||||
holderConfig.allowsUnsafeTransactions = true
|
||||
snapshotHolder = try DatabaseQueue(path: db.path, configuration: holderConfig)
|
||||
try snapshotHolder.inDatabase { db in
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
|
||||
let code = sqlite3_snapshot_open(db.sqliteConnection, "main", walSnapshot.sqliteSnapshot)
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code)
|
||||
}
|
||||
}
|
||||
|
||||
configuration.prepareDatabase { db in
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
|
||||
let code = sqlite3_snapshot_open(db.sqliteConnection, "main", walSnapshot.sqliteSnapshot)
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code)
|
||||
}
|
||||
}
|
||||
|
||||
self.configuration = configuration
|
||||
self.path = db.path
|
||||
self.walSnapshot = walSnapshot
|
||||
|
||||
var readerCount = 0
|
||||
readerPool = Pool(
|
||||
maximumCount: configuration.maximumReaderCount,
|
||||
qos: configuration.readQoS,
|
||||
makeElement: {
|
||||
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
|
||||
return try SerializedDatabase(
|
||||
path: db.path,
|
||||
configuration: configuration,
|
||||
defaultLabel: "GRDB.DatabaseSnapshotPool",
|
||||
purpose: "snapshot.\(readerCount)")
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates a snapshot of the database.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let snapshot = try DatabaseSnapshotPool(path: "/path/to/database.sqlite")
|
||||
/// ```
|
||||
///
|
||||
/// If the database at `path` is not in the
|
||||
/// [WAL mode](https://www.sqlite.org/wal.html), a ``DatabaseError`` of code
|
||||
/// `SQLITE_ERROR` is thrown.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/snapshot_get.html>
|
||||
///
|
||||
/// - parameters:
|
||||
/// - path: The path to the database file.
|
||||
/// - configuration: A configuration.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public init(path: String, configuration: Configuration = Configuration()) throws {
|
||||
var configuration = Self.configure(configuration)
|
||||
|
||||
// Acquire and hold WAL snapshot
|
||||
var holderConfig = Configuration()
|
||||
holderConfig.allowsUnsafeTransactions = true
|
||||
snapshotHolder = try DatabaseQueue(path: path, configuration: holderConfig)
|
||||
let walSnapshot = try snapshotHolder.inDatabase { db in
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
|
||||
return try WALSnapshot(db)
|
||||
}
|
||||
|
||||
configuration.prepareDatabase { db in
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
|
||||
let code = sqlite3_snapshot_open(db.sqliteConnection, "main", walSnapshot.sqliteSnapshot)
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code)
|
||||
}
|
||||
}
|
||||
|
||||
self.configuration = configuration
|
||||
self.path = path
|
||||
self.walSnapshot = walSnapshot
|
||||
|
||||
var readerCount = 0
|
||||
readerPool = Pool(
|
||||
maximumCount: configuration.maximumReaderCount,
|
||||
qos: configuration.readQoS,
|
||||
makeElement: {
|
||||
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
|
||||
return try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
defaultLabel: "GRDB.DatabaseSnapshotPool",
|
||||
purpose: "snapshot.\(readerCount)")
|
||||
})
|
||||
}
|
||||
|
||||
private static func configure(_ configuration: Configuration) -> Configuration {
|
||||
var configuration = configuration
|
||||
|
||||
// DatabaseSnapshotPool needs a non-empty pool of connections.
|
||||
GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1")
|
||||
|
||||
// DatabaseSnapshotPool is read-only.
|
||||
configuration.readonly = true
|
||||
|
||||
// DatabaseSnapshotPool uses deferred transactions by default.
|
||||
// Other transaction kinds are forbidden by SQLite in read-only connections.
|
||||
configuration.defaultTransactionKind = .deferred
|
||||
|
||||
// DatabaseSnapshotPool keeps a long-lived transaction.
|
||||
configuration.allowsUnsafeTransactions = true
|
||||
|
||||
// DatabaseSnapshotPool requires the WAL mode.
|
||||
// See <https://www.sqlite.org/wal.html#sometimes_queries_return_sqlite_busy_in_wal_mode>
|
||||
if configuration.readonlyBusyMode == nil {
|
||||
configuration.readonlyBusyMode = .timeout(10)
|
||||
}
|
||||
|
||||
return configuration
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseSnapshotPool: @unchecked Sendable { }
|
||||
|
||||
extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
public func close() throws {
|
||||
try readerPool?.barrier {
|
||||
defer { readerPool = nil }
|
||||
|
||||
try readerPool?.forEach { reader in
|
||||
try reader.sync { try $0.close() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func interrupt() {
|
||||
readerPool?.forEach { $0.interrupt() }
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func read<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
var completion: PoolCompletion!
|
||||
defer {
|
||||
releaseReader(completion)
|
||||
}
|
||||
return try reader.sync { db in
|
||||
do {
|
||||
let value = try value(db)
|
||||
completion = poolCompletion(db)
|
||||
return value
|
||||
} catch {
|
||||
completion = poolCompletion(db)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
}
|
||||
|
||||
readerPool.asyncGet { result in
|
||||
do {
|
||||
let (reader, releaseReader) = try result.get()
|
||||
// Second async jump because that's how `Pool.async` has to be used.
|
||||
reader.async { db in
|
||||
value(.success(db))
|
||||
releaseReader(self.poolCompletion(db))
|
||||
}
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
if let reader = currentReader {
|
||||
return try reader.reentrantSync { db in
|
||||
let result = try value(db)
|
||||
if snapshotIsLost(db) {
|
||||
throw DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.")
|
||||
}
|
||||
return result
|
||||
}
|
||||
} else {
|
||||
// There is no unsafe access to a snapshot.
|
||||
return try read(value)
|
||||
}
|
||||
}
|
||||
|
||||
public func _add<Reducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable where Reducer: ValueReducer
|
||||
{
|
||||
_addReadOnly(observation: observation, scheduling: scheduler, onChange: onChange)
|
||||
}
|
||||
|
||||
/// Returns a reader that can be used from the current dispatch queue,
|
||||
/// if any.
|
||||
private var currentReader: SerializedDatabase? {
|
||||
guard let readerPool else {
|
||||
return nil
|
||||
}
|
||||
|
||||
var readers: [SerializedDatabase] = []
|
||||
readerPool.forEach { reader in
|
||||
// We can't check for reader.onValidQueue here because
|
||||
// Pool.forEach() runs its closure argument in some arbitrary
|
||||
// dispatch queue. We thus extract the reader so that we can query
|
||||
// it below.
|
||||
readers.append(reader)
|
||||
}
|
||||
|
||||
// Now the readers array contains some readers. The pool readers may
|
||||
// already be different, because some other thread may have started
|
||||
// a new read, for example.
|
||||
//
|
||||
// This doesn't matter: the reader we are looking for is already on
|
||||
// its own dispatch queue. If it exists, is still in use, thus still
|
||||
// in the pool, and thus still relevant for our check:
|
||||
return readers.first { $0.onValidQueue }
|
||||
}
|
||||
|
||||
private func poolCompletion(_ db: Database) -> PoolCompletion {
|
||||
snapshotIsLost(db) ? .discard : .reuse
|
||||
}
|
||||
|
||||
private func snapshotIsLost(_ db: Database) -> Bool {
|
||||
do {
|
||||
let currentSnapshot = try WALSnapshot(db)
|
||||
if currentSnapshot.compare(walSnapshot) == 0 {
|
||||
return false
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
} catch {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
+163
-61
@@ -1,21 +1,69 @@
|
||||
// TODO: remove @preconcurrency when Data conformance to Sendable is exposed.
|
||||
@preconcurrency import Foundation
|
||||
import Foundation
|
||||
|
||||
// MARK: - DatabaseValue
|
||||
|
||||
/// DatabaseValue is the intermediate type between SQLite and your values.
|
||||
/// A value stored in a database table.
|
||||
///
|
||||
/// See <https://www.sqlite.org/datatype3.html>
|
||||
public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLSpecificExpressible {
|
||||
/// The SQLite storage
|
||||
/// To get `DatabaseValue` instances, you can:
|
||||
///
|
||||
/// - Fetch `DatabaseValue` from a ``Database`` instace:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let dbValue = try DatabaseValue.fetchOne(db, sql: """
|
||||
/// SELECT name FROM player
|
||||
/// """)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - Extract `DatabaseValue` from a database ``Row``:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// if let row = try Row.fetchOne(db, sql: """
|
||||
/// SELECT name FROM player
|
||||
/// """)
|
||||
/// {
|
||||
/// let dbValue = row[0] as DatabaseValue
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - Use the ``DatabaseValueConvertible/databaseValue-1ob9k`` property on a
|
||||
/// ``DatabaseValueConvertible`` value:
|
||||
///
|
||||
/// ```swift
|
||||
/// let dbValue = DatabaseValue.null
|
||||
/// let dbValue = 1.databaseValue
|
||||
/// let dbValue = "Arthur".databaseValue
|
||||
/// let dbValue = Date().databaseValue
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/datatype3.html>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a DatabaseValue
|
||||
///
|
||||
/// - ``init(value:)``
|
||||
/// - ``null``
|
||||
///
|
||||
/// ### Accessing the SQLite storage
|
||||
///
|
||||
/// - ``isNull``
|
||||
/// - ``storage-swift.property``
|
||||
/// - ``Storage-swift.enum``
|
||||
public struct DatabaseValue: Hashable {
|
||||
/// The SQLite storage.
|
||||
public let storage: Storage
|
||||
|
||||
/// The NULL DatabaseValue.
|
||||
public static let null = DatabaseValue(storage: .null)
|
||||
|
||||
/// An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB).
|
||||
/// A value stored in a database table, with its exact SQLite storage
|
||||
/// (NULL, INTEGER, REAL, TEXT, BLOB).
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/datatype3.html#storage_classes_and_datatypes>
|
||||
@frozen
|
||||
public enum Storage: Equatable {
|
||||
public enum Storage {
|
||||
/// The NULL storage class.
|
||||
case null
|
||||
|
||||
@@ -31,7 +79,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
|
||||
/// The BLOB storage class, wrapping Data.
|
||||
case blob(Data)
|
||||
|
||||
/// Returns Int64, Double, String, Data or nil.
|
||||
/// Returns `Int64`, `Double`, `String`, `Data` or nil.
|
||||
public var value: (any DatabaseValueConvertible)? {
|
||||
switch self {
|
||||
case .null:
|
||||
@@ -46,27 +94,11 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
/// Return true if the storages are identical.
|
||||
///
|
||||
/// Unlike DatabaseValue equality that considers the integer 1 to be
|
||||
/// equal to the 1.0 double (as SQLite does), int64 and double storages
|
||||
/// are never equal.
|
||||
public static func == (_ lhs: Storage, _ rhs: Storage) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case (.null, .null): return true
|
||||
case let (.int64(lhs), .int64(rhs)): return lhs == rhs
|
||||
case let (.double(lhs), .double(rhs)): return lhs == rhs
|
||||
case let (.string(lhs), .string(rhs)): return lhs == rhs
|
||||
case let (.blob(lhs), .blob(rhs)): return lhs == rhs
|
||||
default: return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a DatabaseValue from Any.
|
||||
/// Creates a `DatabaseValue` from any value.
|
||||
///
|
||||
/// The result is nil unless object adopts DatabaseValueConvertible.
|
||||
/// The result is nil unless `value` adopts ``DatabaseValueConvertible``.
|
||||
public init?(value: Any) {
|
||||
guard let convertible = value as? any DatabaseValueConvertible else {
|
||||
return nil
|
||||
@@ -76,7 +108,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
|
||||
|
||||
// MARK: - Extracting Value
|
||||
|
||||
/// Returns true if databaseValue is NULL.
|
||||
/// A boolean value indicating is the database value is `NULL`.
|
||||
public var isNull: Bool {
|
||||
switch storage {
|
||||
case .null:
|
||||
@@ -116,7 +148,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a DatabaseValue initialized from a raw SQLite statement pointer.
|
||||
/// Creates a `DatabaseValue` initialized from a raw SQLite statement pointer.
|
||||
init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_NULL:
|
||||
@@ -156,48 +188,85 @@ 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 { }
|
||||
extension DatabaseValue.Storage: Sendable { }
|
||||
|
||||
// @unchecked Sendable because Data is not Sendable in all target OS
|
||||
extension DatabaseValue.Storage: @unchecked Sendable { }
|
||||
|
||||
// MARK: - Hashable & Equatable
|
||||
|
||||
// Hashable
|
||||
extension DatabaseValue {
|
||||
|
||||
/// :nodoc:
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
switch storage {
|
||||
case .null:
|
||||
hasher.combine(0)
|
||||
case .int64(let int64):
|
||||
// 1 == 1.0, hence 1 and 1.0 must have the same hash:
|
||||
hasher.combine(Double(int64))
|
||||
case .double(let double):
|
||||
hasher.combine(double)
|
||||
case .string(let string):
|
||||
hasher.combine(string)
|
||||
case .blob(let data):
|
||||
hasher.combine(data)
|
||||
extension DatabaseValue.Storage: Equatable {
|
||||
/// Return true if the storages are identical.
|
||||
///
|
||||
/// Unlike ``DatabaseValue`` equality that considers the integer 1 as
|
||||
/// equal to the 1.0 double (as SQLite does), int64 and double storages
|
||||
/// are never equal.
|
||||
public static func == (_ lhs: Self, _ rhs: Self) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case (.null, .null): return true
|
||||
case let (.int64(lhs), .int64(rhs)): return lhs == rhs
|
||||
case let (.double(lhs), .double(rhs)): return lhs == rhs
|
||||
case let (.string(lhs), .string(rhs)): return lhs == rhs
|
||||
case let (.blob(lhs), .blob(rhs)): return lhs == rhs
|
||||
default: return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether two DatabaseValues are equal.
|
||||
}
|
||||
|
||||
extension DatabaseValue: Equatable {
|
||||
/// Returns whether two ``DatabaseValue`` are equal.
|
||||
///
|
||||
/// 1.databaseValue == "foo".databaseValue // false
|
||||
/// 1.databaseValue == 1.databaseValue // true
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// 1.databaseValue == "foo".databaseValue // false
|
||||
/// 1.databaseValue == 1.databaseValue // true
|
||||
/// ```
|
||||
///
|
||||
/// When comparing integers and doubles, the result is true if and only
|
||||
/// values are equal, and if converting one type to the other does
|
||||
/// not lose information:
|
||||
///
|
||||
/// 1.databaseValue == 1.0.databaseValue // true
|
||||
/// ```swift
|
||||
/// 1.databaseValue == 1.0.databaseValue // true
|
||||
/// ```
|
||||
///
|
||||
/// For a comparison that distinguishes integer and doubles, compare
|
||||
/// storages instead:
|
||||
///
|
||||
/// 1.databaseValue.storage == 1.0.databaseValue.storage // false
|
||||
/// ```swift
|
||||
/// 1.databaseValue.storage == 1.0.databaseValue.storage // false
|
||||
/// ```
|
||||
public static func == (lhs: DatabaseValue, rhs: DatabaseValue) -> Bool {
|
||||
switch (lhs.storage, rhs.storage) {
|
||||
case (.null, .null):
|
||||
@@ -220,8 +289,25 @@ extension DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
// DatabaseValueConvertible
|
||||
extension DatabaseValue {
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
switch storage {
|
||||
case .null:
|
||||
hasher.combine(0)
|
||||
case .int64(let int64):
|
||||
// 1 == 1.0, hence 1 and 1.0 must have the same hash:
|
||||
hasher.combine(Double(int64))
|
||||
case .double(let double):
|
||||
hasher.combine(double)
|
||||
case .string(let string):
|
||||
hasher.combine(string)
|
||||
case .blob(let data):
|
||||
hasher.combine(data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValue: DatabaseValueConvertible {
|
||||
/// Returns self
|
||||
public var databaseValue: DatabaseValue {
|
||||
self
|
||||
@@ -233,16 +319,13 @@ extension DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
// SQLExpressible
|
||||
extension DatabaseValue {
|
||||
extension DatabaseValue: SQLSpecificExpressible {
|
||||
public var sqlExpression: SQLExpression {
|
||||
.databaseValue(self)
|
||||
}
|
||||
}
|
||||
|
||||
// CustomStringConvertible
|
||||
extension DatabaseValue {
|
||||
/// :nodoc:
|
||||
extension DatabaseValue: CustomStringConvertible {
|
||||
public var description: String {
|
||||
switch storage {
|
||||
case .null:
|
||||
@@ -259,6 +342,25 @@ extension DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
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,30 +1,59 @@
|
||||
/// Types that adopt DatabaseValueConvertible can be initialized from
|
||||
/// database values.
|
||||
///
|
||||
/// The protocol comes with built-in methods that allow to fetch cursors,
|
||||
/// arrays, or single values:
|
||||
///
|
||||
/// try String.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String]
|
||||
/// try String.fetchOne(db, sql: "SELECT name FROM ...", arguments:...) // String?
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// try String.fetchCursor(statement, arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(statement, arguments:...) // [String]
|
||||
/// try String.fetchOne(statement, arguments:...) // String?
|
||||
///
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
// 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 {
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// A database value.
|
||||
var databaseValue: DatabaseValue { get }
|
||||
|
||||
/// Returns a value initialized from `dbValue`, if possible.
|
||||
/// Creates an instance with the specified database value.
|
||||
///
|
||||
/// If there is no value of the type that corresponds with the specified
|
||||
/// database value, this method returns nil. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let dbValue = "Arthur".databaseValue
|
||||
///
|
||||
/// String.fromDatabaseValue(dbValue) // "Arthur"
|
||||
/// Int.fromDatabaseValue(dbValue) // nil
|
||||
/// ```
|
||||
///
|
||||
/// - parameter dbValue: A DatabaseValue.
|
||||
/// - returns: A decoded value, or, if decoding is impossible, nil.
|
||||
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self?
|
||||
|
||||
/// Creates a value from a missing column, if possible.
|
||||
/// Creates an instance from a missing column, if possible.
|
||||
///
|
||||
/// - warning: Do not customize the default implementation.
|
||||
///
|
||||
@@ -94,34 +123,38 @@ extension DatabaseValueConvertible {
|
||||
|
||||
// MARK: - Cursors
|
||||
|
||||
/// A cursor of database values extracted from a single column.
|
||||
/// A cursor of database values.
|
||||
///
|
||||
/// A `DatabaseValueCursor` iterates all rows from a database request. Its
|
||||
/// elements are the database values decoded from the leftmost column.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let urls: DatabaseValueCursor<URL> = try URL.fetchCursor(db, sql: "SELECT url FROM link")
|
||||
/// while let url = urls.next() { // URL
|
||||
/// print(url)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let names: DatabaseValueCursor<String> = try String.fetchCursor(db, sql: """
|
||||
/// SELECT name FROM player
|
||||
/// """)
|
||||
/// while let name = names.next() { // String
|
||||
/// print(name)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: DatabaseCursor {
|
||||
public typealias Element = Value
|
||||
/// :nodoc:
|
||||
public let _statement: Statement
|
||||
/// :nodoc:
|
||||
public var _isDone = false
|
||||
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 {
|
||||
@@ -130,7 +163,6 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
|
||||
try? _statement.reset()
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _element(sqliteStatement: SQLiteStatement) throws -> Value {
|
||||
try Value.decode(
|
||||
fromStatement: sqliteStatement,
|
||||
@@ -158,23 +190,35 @@ extension DatabaseValueConvertible {
|
||||
|
||||
/// Returns a cursor over values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try String.fetchCursor(statement) // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
/// let sql = "SELECT score FROM player WHERE lastName = ?"
|
||||
/// let statement = try db.makeStatement(sql: sql)
|
||||
/// let scores = try Int.fetchCursor(statement, arguments: [lastName])
|
||||
/// while let score = try scores.next() {
|
||||
/// print(score)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column if the `adapter` argument
|
||||
/// is nil.
|
||||
///
|
||||
/// The returned cursor is valid only during the remaining execution of the
|
||||
/// database access. Do not store or return the cursor for later use.
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispatch queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - returns: A ``DatabaseValueCursor`` over fetched values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchCursor(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
@@ -186,15 +230,26 @@ extension DatabaseValueConvertible {
|
||||
|
||||
/// Returns an array of values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try String.fetchAll(statement) // [String]
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
/// let sql = "SELECT score FROM player WHERE lastName = ?"
|
||||
/// let statement = try db.makeStatement(sql: sql)
|
||||
/// let scores = try Int.fetchAll(statement, arguments: [lastName])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column if the `adapter` argument
|
||||
/// is nil.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
@@ -206,18 +261,29 @@ extension DatabaseValueConvertible {
|
||||
|
||||
/// Returns a single value fetched from a prepared statement.
|
||||
///
|
||||
/// The result is nil if the query returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
/// The value is decoded from the leftmost column if the `adapter` argument
|
||||
/// is nil.
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let name = try String.fetchOne(statement) // String?
|
||||
/// The result is nil if the request returns no row, or one row with a
|
||||
/// `NULL` value.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
/// let sql = "SELECT score FROM player WHERE lastName = ? LIMIT 1"
|
||||
/// let statement = try db.makeStatement(sql: sql)
|
||||
/// let score = try Int.fetchOne(statement, arguments: [lastName])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
@@ -233,15 +299,26 @@ extension DatabaseValueConvertible {
|
||||
extension DatabaseValueConvertible where Self: Hashable {
|
||||
/// Returns a set of values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try String.fetchSet(statement) // Set<String>
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
/// let sql = "SELECT score FROM player WHERE lastName = ?"
|
||||
/// let statement = try db.makeStatement(sql: sql)
|
||||
/// let scores = try Int.fetchSet(statement, arguments: [lastName])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column if the `adapter` argument
|
||||
/// is nil.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A set.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
@@ -258,23 +335,35 @@ extension DatabaseValueConvertible {
|
||||
|
||||
/// Returns a cursor over values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try String.fetchCursor(db, sql: "SELECT name FROM ...") // Cursor of String
|
||||
/// while let name = try name.next() { // String
|
||||
/// ...
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
/// let sql = "SELECT score FROM player WHERE lastName = ?"
|
||||
/// let scores = try Int.fetchCursor(db, sql: sql, arguments: [lastName])
|
||||
/// while let score = try scores.next() {
|
||||
/// print(score)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column if the `adapter` argument
|
||||
/// is nil.
|
||||
///
|
||||
/// The returned cursor is valid only during the remaining execution of the
|
||||
/// database access. Do not store or return the cursor for later use.
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispatch queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - sql: An SQL string.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - returns: A ``DatabaseValueCursor`` over fetched values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchCursor(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
@@ -287,15 +376,26 @@ extension DatabaseValueConvertible {
|
||||
|
||||
/// Returns an array of values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try String.fetchAll(db, sql: "SELECT name FROM ...") // [String]
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
/// let sql = "SELECT score FROM player WHERE lastName = ?"
|
||||
/// let scores = try Int.fetchAll(db, sql: sql, arguments: [lastName])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column if the `adapter` argument
|
||||
/// is nil.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - sql: An SQL string.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
@@ -308,18 +408,29 @@ extension DatabaseValueConvertible {
|
||||
|
||||
/// Returns a single value fetched from an SQL query.
|
||||
///
|
||||
/// The result is nil if the query returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
/// The value is decoded from the leftmost column if the `adapter` argument
|
||||
/// is nil.
|
||||
///
|
||||
/// let name = try String.fetchOne(db, sql: "SELECT name FROM ...") // String?
|
||||
/// The result is nil if the request returns no row, or one row with a
|
||||
/// `NULL` value.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
/// let sql = "SELECT score FROM player WHERE lastName = ?"
|
||||
/// let score = try Int.fetchOne(db, sql: sql, arguments: [lastName])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - sql: An SQL string.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
@@ -334,15 +445,26 @@ extension DatabaseValueConvertible {
|
||||
extension DatabaseValueConvertible where Self: Hashable {
|
||||
/// Returns a set of values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try String.fetchSet(db, sql: "SELECT name FROM ...") // Set<String>
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
/// let sql = "SELECT score FROM player WHERE lastName = ?"
|
||||
/// let scores = try Int.fetchSet(db, sql: sql, arguments: [lastName])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column if the `adapter` argument
|
||||
/// is nil.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - sql: An SQL string.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A set.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
@@ -360,56 +482,114 @@ extension DatabaseValueConvertible {
|
||||
|
||||
/// Returns a cursor over values fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try String.fetchCursor(db, request) // Cursor of String
|
||||
/// while let name = try name.next() { // String
|
||||
/// ...
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
/// SELECT score FROM player WHERE lastName = \(lastName)
|
||||
/// """
|
||||
///
|
||||
/// let scores = try Int.fetchCursor(db, request)
|
||||
/// while let score = try scores.next() {
|
||||
/// print(score)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column.
|
||||
///
|
||||
/// The returned cursor is valid only during the remaining execution of the
|
||||
/// database access. Do not store or return the cursor for later use.
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispatch queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> DatabaseValueCursor<Self> {
|
||||
/// - returns: A ``DatabaseValueCursor`` over fetched values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ request: some FetchRequest) throws -> DatabaseValueCursor<Self> {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchCursor(request.statement, adapter: request.adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try String.fetchAll(db, request) // [String]
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
/// SELECT score FROM player WHERE lastName = \(lastName)
|
||||
/// """
|
||||
///
|
||||
/// let scores = try Int.fetchAll(db, request)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An array.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [Self] {
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchAll(request.statement, adapter: request.adapter)
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from a fetch request.
|
||||
///
|
||||
/// The result is nil if the query returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
/// The value is decoded from the leftmost column.
|
||||
///
|
||||
/// let request = Player.filter(key: 1).select(Column("name"))
|
||||
/// let name = try String.fetchOne(db, request) // String?
|
||||
/// The result is nil if the request returns no row, or one row with a
|
||||
/// `NULL` value.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
/// SELECT score FROM player WHERE lastName = \(lastName) LIMIT 1
|
||||
/// """
|
||||
///
|
||||
/// let scores = try Int.fetchOne(db, request)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne<R: FetchRequest>(_ db: Database, _ request: R) throws -> Self? {
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: true)
|
||||
return try fetchOne(request.statement, adapter: request.adapter)
|
||||
}
|
||||
@@ -418,15 +598,34 @@ extension DatabaseValueConvertible {
|
||||
extension DatabaseValueConvertible where Self: Hashable {
|
||||
/// Returns a set of values fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try String.fetchSet(db, request) // Set<String>
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
/// SELECT score FROM player WHERE lastName = \(lastName)
|
||||
/// """
|
||||
///
|
||||
/// let scores = try Int.fetchAll(db, request)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: A set.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchSet<R: FetchRequest>(_ db: Database, _ request: R) throws -> Set<Self> {
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchSet(request.statement, adapter: request.adapter)
|
||||
}
|
||||
@@ -436,63 +635,140 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching Values
|
||||
|
||||
/// A cursor over fetched values.
|
||||
/// Returns a cursor over fetched values.
|
||||
///
|
||||
/// let request: some FetchRequest<String> = ...
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String
|
||||
/// while let string = try strings.next() { // String
|
||||
/// ...
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
/// SELECT score FROM player WHERE lastName = \(lastName)
|
||||
/// """
|
||||
///
|
||||
/// let scores = try request.fetchCursor(db)
|
||||
/// while let score = try scores.next() {
|
||||
/// print(score)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column.
|
||||
///
|
||||
/// The returned cursor is valid only during the remaining execution of the
|
||||
/// database access. Do not store or return the cursor for later use.
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispatch queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - returns: A ``DatabaseValueCursor`` over fetched values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder> {
|
||||
try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched values.
|
||||
/// Returns an array of fetched values.
|
||||
///
|
||||
/// let request: some FetchRequest<String> = ...
|
||||
/// let strings = try request.fetchAll(db) // [String]
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
/// SELECT score FROM player WHERE lastName = \(lastName)
|
||||
/// """
|
||||
///
|
||||
/// let scores = try request.fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched value.
|
||||
/// Returns a single fetched value.
|
||||
///
|
||||
/// The result is nil if the request returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
/// The value is decoded from the leftmost column.
|
||||
///
|
||||
/// let request: some FetchRequest<String> = ...
|
||||
/// let string = try request.fetchOne(db) // String?
|
||||
/// The result is nil if the request returns no row, or one row with a
|
||||
/// `NULL` value.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
/// SELECT score FROM player WHERE lastName = \(lastName) LIMIT 1
|
||||
/// """
|
||||
///
|
||||
/// let score = try request.fetchOne(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable {
|
||||
/// A set of fetched values.
|
||||
/// Returns a set of fetched values.
|
||||
///
|
||||
/// let request: some FetchRequest<String> = ...
|
||||
/// let strings = try request.fetchSet(db) // Set<String>
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
/// SELECT score FROM player WHERE lastName = \(lastName)
|
||||
/// """
|
||||
///
|
||||
/// let scores = try request.fetchSet(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
|
||||
try RowDecoder.fetchSet(db, self)
|
||||
}
|
||||
|
||||
+575
-330
File diff suppressed because it is too large.
Load diff
+128
-39
@@ -1,38 +1,102 @@
|
||||
// MARK: - FetchRequest
|
||||
|
||||
/// The protocol for all requests that fetch database rows, and tell how those
|
||||
/// rows should be interpreted.
|
||||
/// A type that fetches and decodes database rows.
|
||||
///
|
||||
/// struct Player: FetchableRecord { ... }
|
||||
/// let request: some FetchRequest<Player> = ...
|
||||
/// The main kinds of fetch requests are ``SQLRequest``
|
||||
/// and ``QueryInterfaceRequest``:
|
||||
///
|
||||
/// try request.fetchCursor(db) // Cursor of Player
|
||||
/// try request.fetchAll(db) // [Player]
|
||||
/// try request.fetchSet(db) // Set<Player>
|
||||
/// try request.fetchOne(db) // Player?
|
||||
/// try request.fetchCount(db) // Int
|
||||
/// ```swift
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // SQLRequest
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT * FROM player WHERE lastName = \(lastName)
|
||||
/// """
|
||||
///
|
||||
/// // QueryInterfaceRequest
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // Use the request
|
||||
/// try dbQueue.read { db in
|
||||
/// let players = try request.fetchAll(db) // [Player]
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Counting the Results
|
||||
///
|
||||
/// - ``fetchCount(_:)``
|
||||
///
|
||||
/// ### Fetching Database Rows
|
||||
///
|
||||
/// - ``fetchCursor(_:)-9283d``
|
||||
/// - ``fetchAll(_:)-7p809``
|
||||
/// - ``fetchOne(_:)-9fafl``
|
||||
/// - ``fetchSet(_:)-6bdrd``
|
||||
///
|
||||
/// ### Fetching Database Values
|
||||
///
|
||||
/// - ``fetchCursor(_:)-19f5g``
|
||||
/// - ``fetchCursor(_:)-66xoi``
|
||||
/// - ``fetchAll(_:)-1loau``
|
||||
/// - ``fetchAll(_:)-28pne``
|
||||
/// - ``fetchOne(_:)-44mvv``
|
||||
/// - ``fetchOne(_:)-5hlkf``
|
||||
/// - ``fetchSet(_:)-4hhtm``
|
||||
/// - ``fetchSet(_:)-9wshm``
|
||||
///
|
||||
/// ### Fetching Records
|
||||
///
|
||||
/// - ``fetchCursor(_:)-2ah3q``
|
||||
/// - ``fetchAll(_:)-vdos``
|
||||
/// - ``fetchOne(_:)-2bq0k``
|
||||
/// - ``fetchSet(_:)-4jdrq``
|
||||
///
|
||||
/// ### Preparing Database Requests
|
||||
///
|
||||
/// - ``makePreparedRequest(_:forSingleResult:)``
|
||||
/// - ``PreparedRequest``
|
||||
///
|
||||
/// ### Database Observation Support
|
||||
///
|
||||
/// - ``databaseRegion(_:)``
|
||||
///
|
||||
/// ### Adapting the Fetched Rows
|
||||
///
|
||||
/// - ``adapted(_:)``
|
||||
/// - ``AdaptedFetchRequest``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``AnyFetchRequest``
|
||||
public protocol FetchRequest<RowDecoder>: SQLSubqueryable, DatabaseRegionConvertible {
|
||||
/// The type that tells how fetched database rows should be interpreted.
|
||||
associatedtype RowDecoder
|
||||
|
||||
/// Returns a PreparedRequest that is ready to be executed.
|
||||
/// Returns a ``PreparedRequest``.
|
||||
///
|
||||
/// The `singleResult` argument is a hint that a single result row will be
|
||||
/// consumed. Implementations can optionally use it to optimize the
|
||||
/// prepared statement, for example by adding a `LIMIT 1` SQL clause:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Calls makePreparedRequest(db, forSingleResult: true)
|
||||
/// try request.fetchOne(db)
|
||||
///
|
||||
/// // Calls makePreparedRequest(db, forSingleResult: false)
|
||||
/// try request.fetchAll(db)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter singleResult: A hint that a single result row will be
|
||||
/// consumed. Implementations can optionally use it to optimize the
|
||||
/// prepared statement, for example by adding a `LIMIT 1` SQL clause.
|
||||
///
|
||||
/// // Calls makePreparedRequest(db, forSingleResult: true)
|
||||
/// try request.fetchOne(db)
|
||||
///
|
||||
/// // Calls makePreparedRequest(db, forSingleResult: false)
|
||||
/// try request.fetchAll(db)
|
||||
/// - returns: A prepared request.
|
||||
/// consumed.
|
||||
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
|
||||
|
||||
/// Returns the number of rows fetched by the request.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
func fetchCount(_ db: Database) throws -> Int
|
||||
}
|
||||
|
||||
@@ -47,12 +111,12 @@ extension FetchRequest {
|
||||
|
||||
// MARK: - PreparedRequest
|
||||
|
||||
/// A PreparedRequest is a request that is ready to be executed.
|
||||
/// A `PreparedRequest` is a request that is ready to be executed.
|
||||
public struct PreparedRequest {
|
||||
/// A prepared statement
|
||||
/// A prepared statement with bound parameters.
|
||||
public var statement: Statement
|
||||
|
||||
/// An eventual adapter for rows fetched by the select statement
|
||||
/// An eventual adapter for rows fetched by the select statement.
|
||||
public var adapter: (any RowAdapter)?
|
||||
|
||||
/// Support for eager loading of hasMany associations.
|
||||
@@ -75,15 +139,23 @@ extension PreparedRequest: Refinable { }
|
||||
|
||||
extension FetchRequest {
|
||||
/// Returns an adapted request.
|
||||
///
|
||||
/// The returned request performs an identical database query, but adapts
|
||||
/// 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.
|
||||
public func adapted(_ adapter: @escaping (Database) throws -> any RowAdapter) -> AdaptedFetchRequest<Self> {
|
||||
AdaptedFetchRequest(self, adapter)
|
||||
}
|
||||
}
|
||||
|
||||
/// An adapted request.
|
||||
public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
|
||||
public typealias RowDecoder = Base.RowDecoder
|
||||
|
||||
///
|
||||
/// See ``FetchRequest/adapted(_:)``.
|
||||
public struct AdaptedFetchRequest<Base: FetchRequest> {
|
||||
let base: Base
|
||||
let adapter: (Database) throws -> any RowAdapter
|
||||
|
||||
@@ -93,10 +165,16 @@ public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
|
||||
self.base = base
|
||||
self.adapter = adapter
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension AdaptedFetchRequest: SQLSubqueryable {
|
||||
public var sqlSubquery: SQLSubquery {
|
||||
base.sqlSubquery
|
||||
}
|
||||
}
|
||||
|
||||
extension AdaptedFetchRequest: FetchRequest {
|
||||
public typealias RowDecoder = Base.RowDecoder
|
||||
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
try base.fetchCount(db)
|
||||
@@ -125,21 +203,39 @@ public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
|
||||
///
|
||||
/// An `AnyFetchRequest` forwards its operations to an underlying request,
|
||||
/// hiding its specifics.
|
||||
public struct AnyFetchRequest<RowDecoder>: FetchRequest {
|
||||
public struct AnyFetchRequest<RowDecoder> {
|
||||
private let request: FetchRequestEraser
|
||||
|
||||
/// Creates a request bound to type RowDecoder.
|
||||
/// Returns a request that performs an identical database query, but decodes
|
||||
/// database rows with `type`.
|
||||
///
|
||||
/// - parameter type: The fetched type RowDecoder
|
||||
/// - returns: A request bound to type RowDecoder.
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // AnyFetchRequest<Player>
|
||||
/// let playerRequest = AnyFetchRequest(Player.all())
|
||||
///
|
||||
/// // AnyFetchRequest<Row>
|
||||
/// let rowRequest = playerRequest.asRequest(of: Row.self)
|
||||
public func asRequest<RowDecoder>(of type: RowDecoder.Type) -> AnyFetchRequest<RowDecoder> {
|
||||
AnyFetchRequest<RowDecoder>(request: request)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension AnyFetchRequest {
|
||||
/// Creates a request that wraps and forwards operations to `request`.
|
||||
public init(_ request: some FetchRequest<RowDecoder>) {
|
||||
self.init(request: ConcreteFetchRequestEraser(request: request))
|
||||
}
|
||||
}
|
||||
|
||||
extension AnyFetchRequest: SQLSubqueryable {
|
||||
public var sqlSubquery: SQLSubquery {
|
||||
request.sqlSubquery
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension AnyFetchRequest: FetchRequest {
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
try request.fetchCount(db)
|
||||
}
|
||||
@@ -153,13 +249,6 @@ public struct AnyFetchRequest<RowDecoder>: FetchRequest {
|
||||
}
|
||||
}
|
||||
|
||||
extension AnyFetchRequest {
|
||||
/// Creates a request that wraps and forwards operations to `request`.
|
||||
public init(_ request: some FetchRequest<RowDecoder>) {
|
||||
self.init(request: ConcreteFetchRequestEraser(request: request))
|
||||
}
|
||||
}
|
||||
|
||||
// Class-based type erasure, so that we preserve full type information.
|
||||
private class FetchRequestEraser: FetchRequest {
|
||||
typealias RowDecoder = Void
|
||||
|
||||
+967
-632
File diff suppressed because it is too large.
Load diff
+318
-105
@@ -1,25 +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.
|
||||
///
|
||||
/// 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]
|
||||
/// For example, let's consider the following SQL query:
|
||||
///
|
||||
/// ```swift
|
||||
/// 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)]
|
||||
}
|
||||
@@ -41,8 +153,6 @@ public func splittingRowAdapters(columnCounts: [Int]) -> [any RowAdapter] {
|
||||
}
|
||||
|
||||
/// _LayoutedColumnMapping is a type that supports the RowAdapter protocol.
|
||||
///
|
||||
/// :nodoc:
|
||||
public struct _LayoutedColumnMapping {
|
||||
/// An array of (baseIndex, mappedName) pairs, where baseIndex is the index
|
||||
/// of a column in a base row, and mappedName the mapped name of
|
||||
@@ -93,7 +203,6 @@ public struct _LayoutedColumnMapping {
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
extension _LayoutedColumnMapping: _LayoutedRowAdapter {
|
||||
/// Returns self.
|
||||
public var _mapping: _LayoutedColumnMapping { self }
|
||||
@@ -102,7 +211,6 @@ extension _LayoutedColumnMapping: _LayoutedRowAdapter {
|
||||
public var _scopes: [String: any _LayoutedRowAdapter] { [:] }
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
extension _LayoutedColumnMapping: _RowLayout {
|
||||
/// Returns the index of the leftmost column named `name`, in a
|
||||
/// case-insensitive way.
|
||||
@@ -118,8 +226,6 @@ extension _LayoutedColumnMapping: _RowLayout {
|
||||
///
|
||||
/// GRBD ships with a ready-made type that adopts this protocol:
|
||||
/// `_LayoutedColumnMapping`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol _LayoutedRowAdapter {
|
||||
/// A LayoutedColumnMapping that defines how to map a column name to a
|
||||
/// column in a base row.
|
||||
@@ -131,8 +237,6 @@ public protocol _LayoutedRowAdapter {
|
||||
|
||||
/// `_RowLayout` is a protocol that supports the `RowAdapter` protocol. It
|
||||
/// describes the layout of a base row.
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol _RowLayout {
|
||||
/// An array of (baseIndex, name) pairs, where baseIndex is the index
|
||||
/// of a column in a base row, and name the name of that column.
|
||||
@@ -144,21 +248,77 @@ public protocol _RowLayout {
|
||||
}
|
||||
|
||||
extension Statement: _RowLayout {
|
||||
/// :nodoc:
|
||||
public var _layoutColumns: [(Int, String)] {
|
||||
Array(columnNames.enumerated())
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _layoutIndex(ofColumn name: String) -> Int? {
|
||||
index(ofColumn: name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Implementation details of `RowAdapter`.
|
||||
/// A type that helps two incompatible row interfaces working together.
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol _RowAdapter {
|
||||
/// 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
|
||||
/// // 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)!
|
||||
///
|
||||
/// // [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 into Chunks
|
||||
///
|
||||
/// - ``splittingRowAdapters(columnCounts:)``
|
||||
///
|
||||
/// ### Adding Scopes to an Adapter
|
||||
///
|
||||
/// - ``addingScopes(_:)``
|
||||
///
|
||||
/// ### Built-in Adapters
|
||||
///
|
||||
/// - ``ColumnMapping``
|
||||
/// - ``EmptyRowAdapter``
|
||||
/// - ``RangeRowAdapter``
|
||||
/// - ``RenameColumnAdapter``
|
||||
/// - ``ScopeAdapter``
|
||||
/// - ``SuffixRowAdapter``
|
||||
public protocol RowAdapter {
|
||||
/// You never call this method directly. It is called for you whenever an
|
||||
/// adapter has to be applied.
|
||||
///
|
||||
@@ -181,27 +341,6 @@ public protocol _RowAdapter {
|
||||
func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter
|
||||
}
|
||||
|
||||
/// `RowAdapter` is a protocol that helps two incompatible row interfaces
|
||||
/// working together.
|
||||
///
|
||||
/// GRDB ships with four concrete types that adopt the RowAdapter protocol:
|
||||
///
|
||||
/// - `ColumnMapping`: renames row columns
|
||||
/// - `EmptyRowAdapter`: hides all columns
|
||||
/// - `RangeRowAdapter`: exposes a range of columns
|
||||
/// - `RenameColumnAdapter`: transforms column names with a function
|
||||
/// - `ScopeAdapter`: defines row scopes
|
||||
/// - `SuffixRowAdapter`: hides the first columns of a row
|
||||
///
|
||||
/// To use a row adapter, provide it to any method that fetches:
|
||||
///
|
||||
/// let adapter = SuffixRowAdapter(fromIndex: 2)
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
|
||||
///
|
||||
/// // [baz:3]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
public protocol RowAdapter: _RowAdapter { }
|
||||
|
||||
extension RowAdapter {
|
||||
/// Returns an adapter based on self, with added scopes.
|
||||
///
|
||||
@@ -225,35 +364,55 @@ 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() { }
|
||||
|
||||
/// :nodoc:
|
||||
public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter {
|
||||
_LayoutedColumnMapping(layoutColumns: [])
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter {
|
||||
let layoutColumns = try mapping
|
||||
.map { (mappedColumn, baseColumn) -> (Int, String) in
|
||||
@@ -274,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,19 +457,22 @@ public struct SuffixRowAdapter: RowAdapter {
|
||||
self.index = index
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter {
|
||||
_LayoutedColumnMapping(layoutColumns: layout._layoutColumns.suffix(from: index))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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>
|
||||
@@ -323,34 +489,70 @@ public struct RangeRowAdapter: RowAdapter {
|
||||
self.range = range.lowerBound..<(range.upperBound + 1)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter {
|
||||
_LayoutedColumnMapping(layoutColumns: layout._layoutColumns[range])
|
||||
}
|
||||
}
|
||||
|
||||
/// `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
|
||||
@@ -399,7 +601,6 @@ public struct ScopeAdapter: RowAdapter {
|
||||
self.scopes = scopes
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter {
|
||||
let layoutedAdapter = try base._layoutedAdapter(from: layout)
|
||||
var layoutedScopes = layoutedAdapter._scopes
|
||||
@@ -431,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
|
||||
|
||||
@@ -445,7 +664,6 @@ public struct RenameColumnAdapter: RowAdapter {
|
||||
self.transform = transform
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter {
|
||||
let layoutColumns = layout._layoutColumns.map { (index, column) in (index, transform(column)) }
|
||||
return _LayoutedColumnMapping(layoutColumns: layoutColumns)
|
||||
@@ -505,14 +723,9 @@ struct AdaptedRowImpl: RowImpl {
|
||||
return try Value.fastDecode(fromRow: base, atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data {
|
||||
func withUnsafeData<T>(atUncheckedIndex index: Int, _ body: (Data?) throws -> T) throws -> T {
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return try base.impl.fastDecodeDataNoCopy(atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? {
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return try base.impl.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: mappedIndex)
|
||||
return try base.impl.withUnsafeData(atUncheckedIndex: mappedIndex, body)
|
||||
}
|
||||
|
||||
func columnName(atUncheckedIndex index: Int) -> String {
|
||||
|
||||
+133
-67
@@ -1,14 +1,44 @@
|
||||
/// `SQL` helps you build SQL literal with
|
||||
/// [SQL Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md).
|
||||
/// An SQL literal.
|
||||
///
|
||||
/// For example:
|
||||
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
|
||||
/// without any risk of syntax errors or SQL injection. For example:
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// let name: String = ...
|
||||
/// let id: Int64 = ...
|
||||
/// let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
/// try db.execute(literal: query)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// let name: String = "O'Brien"
|
||||
/// let id: Int64 = 42
|
||||
/// let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
///
|
||||
/// // UPDATE player SET name = 'O''Brien' WHERE id = 42
|
||||
/// try db.execute(literal: query)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating an SQL Literal from a Literal Value
|
||||
///
|
||||
/// - ``init(stringLiteral:)``
|
||||
/// - ``init(unicodeScalarLiteral:)-7p0al``
|
||||
/// - ``init(extendedGraphemeClusterLiteral:)-1oham``
|
||||
///
|
||||
/// ### Creating an SQL Literal from an Interpolation
|
||||
///
|
||||
/// - ``init(stringInterpolation:)``
|
||||
/// - ``SQLInterpolation``
|
||||
///
|
||||
/// ### Creating an SQL Literal from an SQL String
|
||||
///
|
||||
/// - ``init(sql:arguments:)``
|
||||
///
|
||||
/// ### Creating an SQL Literal from an SQL Expression
|
||||
///
|
||||
/// - ``init(_:)``
|
||||
///
|
||||
/// ### Concatenating SQL Literals
|
||||
///
|
||||
/// - ``append(literal:)``
|
||||
/// - ``append(sql:arguments:)``
|
||||
public struct SQL {
|
||||
/// `SQL.Element` is a component of an `SQL` literal.
|
||||
///
|
||||
@@ -91,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
|
||||
@@ -118,9 +148,11 @@ public struct SQL {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let query = SQL(
|
||||
/// sql: "UPDATE player SET name = ? WHERE id = ?",
|
||||
/// arguments: [name, id])
|
||||
/// ```swift
|
||||
/// let query = SQL(
|
||||
/// sql: "UPDATE player SET name = ? WHERE id = ?",
|
||||
/// arguments: [name, id])
|
||||
/// ```
|
||||
public init(sql: String, arguments: StatementArguments = StatementArguments()) {
|
||||
self.init(elements: [.sql(sql, arguments)])
|
||||
}
|
||||
@@ -129,11 +161,13 @@ public struct SQL {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let columnLiteral = SQL(Column("username"))
|
||||
/// let suffixLiteral = SQL("@example.com".databaseValue)
|
||||
/// let emailLiteral = [columnLiteral, suffixLiteral].joined(separator: " || ")
|
||||
/// let request = User.select(emailLiteral.sqlExpression)
|
||||
/// let emails = try String.fetchAll(db, request)
|
||||
/// ```swift
|
||||
/// let columnLiteral = SQL(Column("username"))
|
||||
/// let suffixLiteral = SQL("@example.com".databaseValue)
|
||||
/// let emailLiteral = [columnLiteral, suffixLiteral].joined(separator: " || ")
|
||||
/// let request = User.select(emailLiteral.sqlExpression)
|
||||
/// let emails = try String.fetchAll(db, request)
|
||||
/// ```
|
||||
public init(_ expression: some SQLSpecificExpressible) {
|
||||
self.init(elements: [.expression(expression.sqlExpression)])
|
||||
}
|
||||
@@ -166,10 +200,14 @@ public struct SQL {
|
||||
extension SQL {
|
||||
/// Returns the `SQL` literal produced by the concatenation of two literals.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// let selection: SQL = "SELECT * FROM player "
|
||||
/// let condition: SQL = "WHERE name = \(name)"
|
||||
/// let query = selection + condition
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let name = "O'Brien"
|
||||
/// let selection: SQL = "SELECT * FROM player "
|
||||
/// let condition: SQL = "WHERE name = \(name)"
|
||||
/// let query = selection + condition
|
||||
/// ```
|
||||
public static func + (lhs: SQL, rhs: SQL) -> SQL {
|
||||
var result = lhs
|
||||
result += rhs
|
||||
@@ -178,27 +216,39 @@ extension SQL {
|
||||
|
||||
/// Appends an `SQL` literal to the receiver.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQL = "SELECT * FROM player "
|
||||
/// query += "WHERE name = \(name)"
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQL = "SELECT * FROM player "
|
||||
/// query += "WHERE name = \(name)"
|
||||
/// ```
|
||||
public static func += (lhs: inout SQL, rhs: SQL) {
|
||||
lhs.elements += rhs.elements
|
||||
}
|
||||
|
||||
/// Appends an `SQL` literal to the receiver.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQL = "SELECT * FROM player "
|
||||
/// query.append(literal: "WHERE name = \(name)")
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQL = "SELECT * FROM player "
|
||||
/// query.append(literal: "WHERE name = \(name)")
|
||||
/// ```
|
||||
public mutating func append(literal sqlLiteral: SQL) {
|
||||
self += sqlLiteral
|
||||
}
|
||||
|
||||
/// Appends a plain SQL string to the receiver, and eventual arguments.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQL = "SELECT * FROM player "
|
||||
/// query.append(sql: "WHERE name = ?", arguments: [name])
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQL = "SELECT * FROM player "
|
||||
/// query.append(sql: "WHERE name = ?", arguments: [name])
|
||||
/// ```
|
||||
public mutating func append(sql: String, arguments: StatementArguments = StatementArguments()) {
|
||||
self += SQL(sql: sql, arguments: arguments)
|
||||
}
|
||||
@@ -210,39 +260,56 @@ extension SQL: SQLSpecificExpressible {
|
||||
/// Use this property when you need an explicit `SQLExpression`.
|
||||
/// For example:
|
||||
///
|
||||
/// func date(_ value: some SQLExpressible) -> SQLExpression {
|
||||
/// SQL("DATE(\(value))").sqlExpression
|
||||
/// }
|
||||
/// ```swift
|
||||
/// func date(_ value: some SQLExpressible) -> SQLExpression {
|
||||
/// SQL("DATE(\(value))").sqlExpression
|
||||
/// }
|
||||
///
|
||||
/// // SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23'
|
||||
/// let createdAt = Column("createdAt")
|
||||
/// let request = Player.filter(date(createdAt) == "2020-01-23")
|
||||
/// // SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23'
|
||||
/// let createdAt = Column("createdAt")
|
||||
/// let request = Player.filter(date(createdAt) == "2020-01-23")
|
||||
/// ```
|
||||
public var sqlExpression: SQLExpression {
|
||||
.literal(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQL: SQLSelectable {
|
||||
/// Creates a literal SQL expression.
|
||||
/// Creates a literal SQL result column.
|
||||
///
|
||||
/// Use this property when you need an explicit `SQLSelection`. For example:
|
||||
///
|
||||
/// // SELECT firstName AS givenName, lastName AS familyName FROM player
|
||||
/// let selection = SQL("firstName AS givenName, lastName AS familyName").sqlSelection
|
||||
/// let request = Player.select(selection)
|
||||
/// ```swift
|
||||
/// // SELECT firstName AS givenName, lastName AS familyName FROM player
|
||||
/// let selection = SQL("firstName AS givenName, lastName AS familyName").sqlSelection
|
||||
/// let request = Player.select(selection)
|
||||
/// ```
|
||||
public var sqlSelection: SQLSelection {
|
||||
.literal(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQL: SQLOrderingTerm {
|
||||
/// Creates a literal SQL ordering.
|
||||
/// Creates a literal SQL ordering term.
|
||||
///
|
||||
/// Use this property when you need an explicit `SQLOrdering`. For example:
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY name DESC
|
||||
/// let ordering = SQL("name DESC").sqlOrdering
|
||||
/// let request = Player.order(ordering)
|
||||
/// ```swift
|
||||
/// // SELECT * FROM player ORDER BY name DESC
|
||||
/// let ordering = SQL("name DESC").sqlOrdering
|
||||
/// let request = Player.order(ordering)
|
||||
/// ```
|
||||
///
|
||||
/// An ordering term is only valid if it represent a single ordering terms.
|
||||
///
|
||||
/// ```swift
|
||||
/// // Valid
|
||||
/// SQL("score DESC").sqlOrdering
|
||||
/// SQL("name").sqlOrdering
|
||||
///
|
||||
/// // Invalid
|
||||
/// SQL("score DESC, name").sqlOrdering
|
||||
/// ```
|
||||
public var sqlOrdering: SQLOrdering {
|
||||
.literal(self)
|
||||
}
|
||||
@@ -254,15 +321,16 @@ extension Sequence where Element == SQL {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let components: [SQL] = [
|
||||
/// "UPDATE player",
|
||||
/// "SET name = \(name)",
|
||||
/// "WHERE id = \(id)"
|
||||
/// ]
|
||||
/// let query = components.joined(separator: " ")
|
||||
/// ```
|
||||
/// let components: [SQL] = [
|
||||
/// "UPDATE player",
|
||||
/// "SET name = \(name)",
|
||||
/// "WHERE id = \(id)"
|
||||
/// ]
|
||||
/// let query = components.joined(separator: " ")
|
||||
/// ```
|
||||
///
|
||||
/// - Note: The separator is a raw SQL string, not an SQL literal that
|
||||
/// supports [SQL Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md).
|
||||
/// - Note: The separator is a raw SQL string, not an ``SQL`` literal.
|
||||
public func joined(separator: String = "") -> SQL {
|
||||
if separator.isEmpty {
|
||||
return SQL(elements: flatMap(\.elements))
|
||||
@@ -278,15 +346,16 @@ extension Collection where Element == SQL {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let components: [SQL] = [
|
||||
/// "UPDATE player",
|
||||
/// "SET name = \(name)",
|
||||
/// "WHERE id = \(id)"
|
||||
/// ]
|
||||
/// let query = components.joined(separator: " ")
|
||||
/// ```swift
|
||||
/// let components: [SQL] = [
|
||||
/// "UPDATE player",
|
||||
/// "SET name = \(name)",
|
||||
/// "WHERE id = \(id)"
|
||||
/// ]
|
||||
/// let query = components.joined(separator: " ")
|
||||
/// ```
|
||||
///
|
||||
/// - Note: The separator is a raw SQL string, not an SQL literal that
|
||||
/// supports [SQL Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md).
|
||||
/// - Note: The separator is a raw SQL string, not an ``SQL`` literal.
|
||||
public func joined(separator: String = "") -> SQL {
|
||||
if separator.isEmpty {
|
||||
return SQL(elements: flatMap(\.elements))
|
||||
@@ -299,22 +368,19 @@ extension Collection where Element == SQL {
|
||||
// MARK: - ExpressibleByStringInterpolation
|
||||
|
||||
extension SQL: ExpressibleByStringInterpolation {
|
||||
/// :nodoc
|
||||
public init(unicodeScalarLiteral: String) {
|
||||
self.init(sql: unicodeScalarLiteral, arguments: [])
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(extendedGraphemeClusterLiteral: String) {
|
||||
self.init(sql: extendedGraphemeClusterLiteral, arguments: [])
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
|
||||
/// Creates an `SQL` literal from the given literal SQL string.
|
||||
public init(stringLiteral: String) {
|
||||
self.init(sql: stringLiteral, arguments: [])
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(stringInterpolation sqlInterpolation: SQLInterpolation) {
|
||||
self.init(elements: sqlInterpolation.elements)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
/// :nodoc:
|
||||
public struct SQLInterpolation: StringInterpolationProtocol {
|
||||
var elements: [SQL.Element]
|
||||
|
||||
|
||||
+85
-41
@@ -1,4 +1,49 @@
|
||||
/// A FetchRequest built from raw SQL.
|
||||
/// An SQL request that can decode database rows.
|
||||
///
|
||||
/// `SQLRequest` allows you to safely embed raw values in your SQL,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// ```swift
|
||||
/// extension Player: FetchableRecord {
|
||||
/// static func filter(name: String) -> SQLRequest<Player> {
|
||||
/// "SELECT * FROM player WHERE name = \(name)"
|
||||
/// }
|
||||
///
|
||||
/// static func maximumScore() -> SQLRequest<Int> {
|
||||
/// "SELECT MAX(score) FROM player"
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let players = try Player.filter(name: "O'Brien").fetchAll(db) // [Player]
|
||||
/// let maxScore = try Player.maximumScore().fetchOne(db) // Int?
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// An `SQLRequest` can be created from a string literal or interpolation, as in
|
||||
/// the above examples, and from the initializers documented below.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating an SQL Request from a Literal Value
|
||||
///
|
||||
/// - ``init(stringLiteral:)``
|
||||
/// - ``init(unicodeScalarLiteral:)-84mq8``
|
||||
/// - ``init(extendedGraphemeClusterLiteral:)-1sf75``
|
||||
///
|
||||
/// ### Creating an SQL Request from an Interpolation
|
||||
///
|
||||
/// - ``init(stringInterpolation:)``
|
||||
///
|
||||
/// ### Creating an SQL Request from an SQL Literal
|
||||
///
|
||||
/// - ``init(literal:adapter:cached:)-4vuxn``
|
||||
/// - ``init(literal:adapter:cached:)-82f97``
|
||||
///
|
||||
/// ### Creating an SQL Request from an SQL String
|
||||
///
|
||||
/// - ``init(sql:arguments:adapter:cached:)-3qq8t``
|
||||
/// - ``init(sql:arguments:adapter:cached:)-5ecx2``
|
||||
public struct SQLRequest<RowDecoder> {
|
||||
/// There are two statement caches: one "public" for statements generated by
|
||||
/// the user, and one "internal" for the statements generated by GRDB. Those
|
||||
@@ -12,7 +57,7 @@ public struct SQLRequest<RowDecoder> {
|
||||
case `internal`
|
||||
}
|
||||
|
||||
/// The request adapter
|
||||
/// The row adapter.
|
||||
public var adapter: (any RowAdapter)?
|
||||
|
||||
private(set) var sqlLiteral: SQL
|
||||
@@ -31,23 +76,23 @@ public struct SQLRequest<RowDecoder> {
|
||||
}
|
||||
|
||||
extension SQLRequest {
|
||||
/// Creates a request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
/// Creates a request from an SQL string.
|
||||
///
|
||||
/// let request = SQLRequest<String>(sql: """
|
||||
/// SELECT name FROM player
|
||||
/// """)
|
||||
/// let request = SQLRequest<Player>(sql: """
|
||||
/// SELECT * FROM player WHERE id = ?
|
||||
/// """, arguments: [1])
|
||||
/// ```swift
|
||||
/// let request = SQLRequest<String>(sql: """
|
||||
/// SELECT name FROM player
|
||||
/// """)
|
||||
/// let request = SQLRequest<Player>(sql: """
|
||||
/// SELECT * FROM player WHERE name = ?
|
||||
/// """, arguments: ["O'Brien"])
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - sql: An SQL string.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: A SQLRequest
|
||||
public init(
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
@@ -61,22 +106,23 @@ extension SQLRequest {
|
||||
type: RowDecoder.self)
|
||||
}
|
||||
|
||||
/// Creates a request from an `SQL` literal, and optional row adapter.
|
||||
/// Creates a request from an ``SQL`` literal.
|
||||
///
|
||||
/// Literals allow you to safely embed raw values in your SQL, without any
|
||||
/// risk of syntax errors or SQL injection:
|
||||
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// let name = "O'brien"
|
||||
/// let request = SQLRequest<Player>(literal: """
|
||||
/// SELECT * FROM player WHERE name = \(name)
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// let name = "O'Brien"
|
||||
/// let request = SQLRequest<Player>(literal: """
|
||||
/// SELECT * FROM player WHERE name = \(name)
|
||||
/// """)
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqlLiteral: An `SQL` literal.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: A SQLRequest
|
||||
public init(literal sqlLiteral: SQL, adapter: (any RowAdapter)? = nil, cached: Bool = false) {
|
||||
self.init(
|
||||
literal: sqlLiteral,
|
||||
@@ -87,20 +133,20 @@ extension SQLRequest {
|
||||
}
|
||||
|
||||
extension SQLRequest<Row> {
|
||||
/// Creates a request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
/// Creates a request of database rows, from an SQL string.
|
||||
///
|
||||
/// let request = SQLRequest(sql: """
|
||||
/// SELECT * FROM player WHERE id = ?
|
||||
/// """, arguments: [1])
|
||||
/// ```swift
|
||||
/// let request = SQLRequest(sql: """
|
||||
/// SELECT * FROM player WHERE name = ?
|
||||
/// """, arguments: ["O'Brien"])
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - sql: An SQL string.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: A SQLRequest
|
||||
public init(
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
@@ -114,22 +160,23 @@ extension SQLRequest<Row> {
|
||||
type: Row.self)
|
||||
}
|
||||
|
||||
/// Creates a request from an `SQL` literal, and optional row adapter.
|
||||
/// Creates a request of database rows, from an ``SQL`` literal.
|
||||
///
|
||||
/// Literals allow you to safely embed raw values in your SQL, without any
|
||||
/// risk of syntax errors or SQL injection:
|
||||
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// let name = "O'brien"
|
||||
/// let request = SQLRequest(literal: """
|
||||
/// SELECT * FROM player WHERE name = \(name)
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// let name = "O'Brien"
|
||||
/// let request = SQLRequest(literal: """
|
||||
/// SELECT * FROM player WHERE name = \(name)
|
||||
/// """)
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqlLiteral: An `SQL` literal.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: A SQLRequest
|
||||
public init(literal sqlLiteral: SQL, adapter: (any RowAdapter)? = nil, cached: Bool = false) {
|
||||
self.init(
|
||||
literal: sqlLiteral,
|
||||
@@ -159,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)
|
||||
@@ -170,22 +217,19 @@ extension SQLRequest: FetchRequest {
|
||||
}
|
||||
|
||||
extension SQLRequest: ExpressibleByStringInterpolation {
|
||||
/// :nodoc
|
||||
public init(unicodeScalarLiteral: String) {
|
||||
self.init(sql: unicodeScalarLiteral)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(extendedGraphemeClusterLiteral: String) {
|
||||
self.init(sql: extendedGraphemeClusterLiteral)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
/// Creates an `SQLRequest` from the given literal SQL string.
|
||||
public init(stringLiteral: String) {
|
||||
self.init(sql: stringLiteral)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(stringInterpolation sqlInterpolation: SQLInterpolation) {
|
||||
self.init(literal: SQL(stringInterpolation: sqlInterpolation))
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import Foundation
|
||||
|
||||
/// A class that serializes accesses to a database.
|
||||
/// A class that serializes accesses to an SQLite connection.
|
||||
final class SerializedDatabase {
|
||||
/// The database connection
|
||||
private let db: Database
|
||||
@@ -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)
|
||||
|
||||
+705
-269
File diff suppressed because it is too large.
Load diff
@@ -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)
|
||||
|
||||
@@ -1,25 +1,76 @@
|
||||
/// The `StatementColumnConvertible` protocol grants access to the low-level C
|
||||
/// interface that extracts values from query results:
|
||||
/// <https://www.sqlite.org/c3ref/column_blob.html>. It can bring performance
|
||||
/// improvements.
|
||||
/// A type that can decode itself from the low-level C interface to
|
||||
/// SQLite results.
|
||||
///
|
||||
/// To use it, have a value type adopt both `StatementColumnConvertible` and
|
||||
/// `DatabaseValueConvertible`. GRDB will then automatically apply the
|
||||
/// optimization whenever direct access to SQLite is possible:
|
||||
/// `StatementColumnConvertible` is adopted by `Bool`, `Int`, `String`,
|
||||
/// `Date`, and most common values.
|
||||
///
|
||||
/// let rows = Row.fetchCursor(db, sql: "SELECT ...")
|
||||
/// while let row = try rows.next() {
|
||||
/// let int: Int = row[0] // there
|
||||
/// }
|
||||
/// let ints = Int.fetchAll(db, sql: "SELECT ...") // there
|
||||
/// struct Player {
|
||||
/// init(row: Row) {
|
||||
/// name = row["name"] // there
|
||||
/// score = row["score"] // there
|
||||
/// }
|
||||
/// When a type conforms to both ``DatabaseValueConvertible`` and
|
||||
/// `StatementColumnConvertible`, GRDB can apply some optimization whenever
|
||||
/// direct access to SQLite is possible. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Optimized
|
||||
/// let scores = Int.fetchAll(db, sql: "SELECT score FROM player")
|
||||
///
|
||||
/// let rows = try Row.fetchCursor(db, sql: "SELECT * FROM player")
|
||||
/// while let row = try rows.next() {
|
||||
/// // Optimized
|
||||
/// let int: Int = row[0]
|
||||
/// let name: String = row[1]
|
||||
/// }
|
||||
///
|
||||
/// struct Player: FetchableRecord {
|
||||
/// var name: String
|
||||
/// var score: Int
|
||||
///
|
||||
/// init(row: Row) {
|
||||
/// // Optimized
|
||||
/// name = row["name"]
|
||||
/// score = row["score"]
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// To conform to `StatementColumnConvertible`, provide a custom implementation
|
||||
/// of ``init(sqliteStatement:index:)-354je``. This implementation is ready-made
|
||||
/// for `RawRepresentable` types whose `RawValue`
|
||||
/// is `StatementColumnConvertible`.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/column_blob.html>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a Value
|
||||
///
|
||||
/// - ``init(sqliteStatement:index:)-354je``
|
||||
/// - ``fromStatement(_:atUncheckedIndex:)-2i8y6``
|
||||
///
|
||||
/// ### Fetching Values from Raw SQL
|
||||
///
|
||||
/// - ``DatabaseValueConvertible/fetchCursor(_:sql:arguments:adapter:)-4xfxh``
|
||||
/// - ``DatabaseValueConvertible/fetchAll(_:sql:arguments:adapter:)-7bn2i``
|
||||
/// - ``DatabaseValueConvertible/fetchSet(_:sql:arguments:adapter:)-1ythd``
|
||||
/// - ``DatabaseValueConvertible/fetchOne(_:sql:arguments:adapter:)-563lc``
|
||||
///
|
||||
/// ### Fetching Values from a Prepared Statement
|
||||
///
|
||||
/// - ``DatabaseValueConvertible/fetchCursor(_:arguments:adapter:)-81f9d``
|
||||
/// - ``DatabaseValueConvertible/fetchAll(_:arguments:adapter:)-64gua``
|
||||
/// - ``DatabaseValueConvertible/fetchSet(_:arguments:adapter:)-9fh2b``
|
||||
/// - ``DatabaseValueConvertible/fetchOne(_:arguments:adapter:)-8cbzp``
|
||||
///
|
||||
/// ### Fetching Values from a Request
|
||||
///
|
||||
/// - ``DatabaseValueConvertible/fetchCursor(_:_:)-77a34``
|
||||
/// - ``DatabaseValueConvertible/fetchAll(_:_:)-7tnun``
|
||||
/// - ``DatabaseValueConvertible/fetchSet(_:_:)-4bc1m``
|
||||
/// - ``DatabaseValueConvertible/fetchOne(_:_:)-94q4e``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``FastDatabaseValueCursor``
|
||||
public protocol StatementColumnConvertible {
|
||||
/// Creates a value from a raw SQLite statement pointer, if possible.
|
||||
/// Creates an instance from a raw SQLite statement pointer, if possible.
|
||||
///
|
||||
/// This method can be called with a NULL database value.
|
||||
///
|
||||
@@ -34,20 +85,26 @@ public protocol StatementColumnConvertible {
|
||||
atUncheckedIndex index: CInt)
|
||||
-> Self?
|
||||
|
||||
/// Creates a value from a raw SQLite statement pointer, if possible.
|
||||
/// Creates an instance from a raw SQLite statement pointer, if possible.
|
||||
///
|
||||
/// Do not check for `NULL` in your implementation of this method. Null
|
||||
/// database values are handled
|
||||
/// in ``fromStatement(_:atUncheckedIndex:)-2i8y6``.
|
||||
///
|
||||
/// For example, here is the how Int64 adopts StatementColumnConvertible:
|
||||
///
|
||||
/// extension Int64: StatementColumnConvertible {
|
||||
/// init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
/// self = sqlite3_column_int64(sqliteStatement, index)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// extension Int64: StatementColumnConvertible {
|
||||
/// public init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
/// self = sqlite3_column_int64(sqliteStatement, index)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/column_blob.html> for more information.
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/column_blob.html>
|
||||
///
|
||||
/// - precondition: This initializer must not be called with NULL database
|
||||
/// values.
|
||||
/// - precondition: This initializer is not called with a NULL
|
||||
/// database value.
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
@@ -131,36 +188,40 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
// MARK: - Cursors
|
||||
|
||||
/// A cursor of database values extracted from a single column.
|
||||
/// A cursor of database values.
|
||||
///
|
||||
/// A `FastDatabaseValueCursor` iterates all rows from a database request. Its
|
||||
/// elements are the database values decoded from the leftmost column.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let names: ColumnCursor<String> = try String.fetchCursor(db, sql: "SELECT name FROM player")
|
||||
/// while let name = names.next() { // String
|
||||
/// print(name)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let names: FastDatabaseValueCursor<String> = try String.fetchCursor(db, sql: """
|
||||
/// SELECT name FROM player
|
||||
/// """)
|
||||
/// while let name = names.next() { // String
|
||||
/// print(name)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
public final class FastDatabaseValueCursor<Value>: DatabaseCursor
|
||||
where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
{
|
||||
public typealias Element = Value
|
||||
/// :nodoc:
|
||||
public let _statement: Statement
|
||||
/// :nodoc:
|
||||
public var _isDone = false
|
||||
@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 {
|
||||
@@ -169,7 +230,6 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
try? _statement.reset()
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
@inlinable
|
||||
public func _element(sqliteStatement: SQLiteStatement) throws -> Value {
|
||||
try Value.fastDecode(
|
||||
@@ -190,23 +250,35 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
/// Returns a cursor over values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try String.fetchCursor(statement) // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
/// let sql = "SELECT score FROM player WHERE lastName = ?"
|
||||
/// let statement = try db.makeStatement(sql: sql)
|
||||
/// let scores = try Int.fetchCursor(statement, arguments: [lastName])
|
||||
/// while let score = try scores.next() {
|
||||
/// print(score)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column if the `adapter` argument
|
||||
/// is nil.
|
||||
///
|
||||
/// The returned cursor is valid only during the remaining execution of the
|
||||
/// database access. Do not store or return the cursor for later use.
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispatch queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - returns: A ``FastDatabaseValueCursor`` over fetched values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchCursor(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
@@ -218,15 +290,26 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
/// Returns an array of values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try String.fetchAll(statement) // [String]
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
/// let sql = "SELECT score FROM player WHERE lastName = ?"
|
||||
/// let statement = try db.makeStatement(sql: sql)
|
||||
/// let scores = try Int.fetchAll(statement, arguments: [lastName])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column if the `adapter` argument
|
||||
/// is nil.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
@@ -238,15 +321,29 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
/// Returns a single value fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let name = try String.fetchOne(statement) // String?
|
||||
/// The value is decoded from the leftmost column if the `adapter` argument
|
||||
/// is nil.
|
||||
///
|
||||
/// The result is nil if the request returns no row, or one row with a
|
||||
/// `NULL` value.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
/// let sql = "SELECT score FROM player WHERE lastName = ? LIMIT 1"
|
||||
/// let statement = try db.makeStatement(sql: sql)
|
||||
/// let score = try Int.fetchOne(statement, arguments: [lastName])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
@@ -265,15 +362,26 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hashable {
|
||||
/// Returns a set of values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try String.fetchSet(statement) // Set<String>
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
/// let sql = "SELECT score FROM player WHERE lastName = ?"
|
||||
/// let statement = try db.makeStatement(sql: sql)
|
||||
/// let scores = try Int.fetchSet(statement, arguments: [lastName])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column if the `adapter` argument
|
||||
/// is nil.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
@@ -290,23 +398,35 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
/// Returns a cursor over values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try String.fetchCursor(db, sql: "SELECT name FROM ...") // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
/// let sql = "SELECT score FROM player WHERE lastName = ?"
|
||||
/// let scores = try Int.fetchCursor(db, sql: sql, arguments: [lastName])
|
||||
/// while let score = try scores.next() {
|
||||
/// print(score)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column if the `adapter` argument
|
||||
/// is nil.
|
||||
///
|
||||
/// The returned cursor is valid only during the remaining execution of the
|
||||
/// database access. Do not store or return the cursor for later use.
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispatch queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - sql: An SQL string.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - returns: A ``FastDatabaseValueCursor`` over fetched values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchCursor(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
@@ -319,15 +439,26 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
/// Returns an array of values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try String.fetchAll(db, sql: "SELECT name FROM ...") // [String]
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
/// let sql = "SELECT score FROM player WHERE lastName = ?"
|
||||
/// let scores = try Int.fetchAll(db, sql: sql, arguments: [lastName])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column if the `adapter` argument
|
||||
/// is nil.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - sql: An SQL string.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
@@ -340,15 +471,29 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
/// Returns a single value fetched from an SQL query.
|
||||
///
|
||||
/// let name = try String.fetchOne(db, sql: "SELECT name FROM ...") // String?
|
||||
/// The value is decoded from the leftmost column if the `adapter` argument
|
||||
/// is nil.
|
||||
///
|
||||
/// The result is nil if the request returns no row, or one row with a
|
||||
/// `NULL` value.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
/// let sql = "SELECT score FROM player WHERE lastName = ?"
|
||||
/// let score = try Int.fetchOne(db, sql: sql, arguments: [lastName])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - sql: An SQL string.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
@@ -363,15 +508,26 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hashable {
|
||||
/// Returns a set of values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try String.fetchSet(db, sql: "SELECT name FROM ...") // Set<String>
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
/// let sql = "SELECT score FROM player WHERE lastName = ?"
|
||||
/// let scores = try Int.fetchSet(db, sql: sql, arguments: [lastName])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column if the `adapter` argument
|
||||
/// is nil.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - sql: An SQL string.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
@@ -389,23 +545,43 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
/// Returns a cursor over values fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try String.fetchCursor(db, request) // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
/// SELECT score FROM player WHERE lastName = \(lastName)
|
||||
/// """
|
||||
///
|
||||
/// let scores = try Int.fetchCursor(db, request)
|
||||
/// while let score = try scores.next() {
|
||||
/// print(score)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column.
|
||||
///
|
||||
/// The returned cursor is valid only during the remaining execution of the
|
||||
/// database access. Do not store or return the cursor for later use.
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispatch queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R)
|
||||
/// - returns: A ``FastDatabaseValueCursor`` over fetched values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ request: some FetchRequest)
|
||||
throws -> FastDatabaseValueCursor<Self>
|
||||
{
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
@@ -414,30 +590,71 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
/// Returns an array of values fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try String.fetchAll(db, request) // [String]
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
/// SELECT score FROM player WHERE lastName = \(lastName)
|
||||
/// """
|
||||
///
|
||||
/// let scores = try Int.fetchAll(db, request)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [Self] {
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchAll(request.statement, adapter: request.adapter)
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.filter(key: 1).select(Column("name"))
|
||||
/// let name = try String.fetchOne(db, request) // String?
|
||||
/// The value is decoded from the leftmost column.
|
||||
///
|
||||
/// The result is nil if the request returns no row, or one row with a
|
||||
/// `NULL` value.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
/// SELECT score FROM player WHERE lastName = \(lastName) LIMIT 1
|
||||
/// """
|
||||
///
|
||||
/// let scores = try Int.fetchOne(db, request)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne<R: FetchRequest>(_ db: Database, _ request: R) throws -> Self? {
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: true)
|
||||
return try fetchOne(request.statement, adapter: request.adapter)
|
||||
}
|
||||
@@ -446,15 +663,34 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hashable {
|
||||
/// Returns a set of values fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try String.fetchSet(db, request) // Set<String>
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
/// SELECT score FROM player WHERE lastName = \(lastName)
|
||||
/// """
|
||||
///
|
||||
/// let scores = try Int.fetchAll(db, request)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchSet<R: FetchRequest>(_ db: Database, _ request: R) throws -> Set<Self> {
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchSet(request.statement, adapter: request.adapter)
|
||||
}
|
||||
@@ -464,63 +700,140 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
|
||||
// MARK: Fetching Values
|
||||
|
||||
/// A cursor over fetched values.
|
||||
/// Returns a cursor over fetched values.
|
||||
///
|
||||
/// let request: some FetchRequest<String> = ...
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String
|
||||
/// while let string = try strings.next() { // String
|
||||
/// ...
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
/// SELECT score FROM player WHERE lastName = \(lastName)
|
||||
/// """
|
||||
///
|
||||
/// let scores = try request.fetchCursor(db)
|
||||
/// while let score = try scores.next() {
|
||||
/// print(score)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column.
|
||||
///
|
||||
/// The returned cursor is valid only during the remaining execution of the
|
||||
/// database access. Do not store or return the cursor for later use.
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispatch queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - returns: A ``FastDatabaseValueCursor`` over fetched values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> FastDatabaseValueCursor<RowDecoder> {
|
||||
try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched values.
|
||||
/// Returns an array of fetched values.
|
||||
///
|
||||
/// let request: some FetchRequest<String> = ...
|
||||
/// let strings = try request.fetchAll(db) // [String]
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
/// SELECT score FROM player WHERE lastName = \(lastName)
|
||||
/// """
|
||||
///
|
||||
/// let scores = try request.fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched value.
|
||||
/// Returns a single fetched value.
|
||||
///
|
||||
/// The result is nil if the request returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
/// The value is decoded from the leftmost column.
|
||||
///
|
||||
/// let request: some FetchRequest<String> = ...
|
||||
/// let string = try request.fetchOne(db) // String?
|
||||
/// The result is nil if the request returns no row, or one row with a
|
||||
/// `NULL` value.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
/// SELECT score FROM player WHERE lastName = \(lastName) LIMIT 1
|
||||
/// """
|
||||
///
|
||||
/// let score = try request.fetchOne(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible & Hashable {
|
||||
/// A set of fetched values.
|
||||
/// Returns a set of fetched values.
|
||||
///
|
||||
/// let request: some FetchRequest<String> = ...
|
||||
/// let strings = try request.fetchSet(db) // Set<String>
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
/// SELECT score FROM player WHERE lastName = \(lastName)
|
||||
/// """
|
||||
///
|
||||
/// let scores = try request.fetchSet(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Values are decoded from the leftmost column.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
|
||||
try RowDecoder.fetchSet(db, self)
|
||||
}
|
||||
|
||||
@@ -3,13 +3,11 @@ import CoreGraphics
|
||||
|
||||
/// CGFloat adopts DatabaseValueConvertible
|
||||
extension CGFloat: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// Returns a REAL database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
Double(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a CGFloat initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> CGFloat? {
|
||||
guard let double = Double.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
|
||||
@@ -11,13 +11,19 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// Returns a BLOB database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
DatabaseValue(storage: .blob(self))
|
||||
}
|
||||
|
||||
/// Returns a Data initialized from *dbValue*, if it contains
|
||||
/// a Blob.
|
||||
/// Returns a `Data` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a data blob, returns it.
|
||||
///
|
||||
/// If the database value contains a string, returns this string converted
|
||||
/// to UTF8 data.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Data? {
|
||||
switch dbValue.storage {
|
||||
case .blob(let data):
|
||||
@@ -36,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
|
||||
@@ -60,50 +83,4 @@ extension Data {
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, index))
|
||||
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
|
||||
}
|
||||
|
||||
static func fastDecodeNoCopy(
|
||||
fromRow row: Row,
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Data
|
||||
{
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return try fastDecodeNoCopy(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: CInt(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
// Support for fast decoding from adapted rows
|
||||
return try row.fastDecodeDataNoCopy(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
static func fastDecodeNoCopyIfPresent(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: CInt,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
-> Data?
|
||||
{
|
||||
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else {
|
||||
return nil
|
||||
}
|
||||
guard let bytes = sqlite3_column_blob(sqliteStatement, index) else {
|
||||
return Data()
|
||||
}
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, index))
|
||||
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
|
||||
}
|
||||
|
||||
static func fastDecodeNoCopyIfPresent(
|
||||
fromRow row: Row,
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Data?
|
||||
{
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return fastDecodeNoCopyIfPresent(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: CInt(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
// Support for fast decoding from adapted rows
|
||||
return try row.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: index)
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import Foundation
|
||||
|
||||
/// DatabaseDateComponents reads and stores DateComponents in the database.
|
||||
public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnConvertible, Codable {
|
||||
/// A database value that holds date components.
|
||||
public struct DatabaseDateComponents {
|
||||
|
||||
/// The available formats for reading and storing date components.
|
||||
/// The SQLite formats for date components.
|
||||
public enum Format: String {
|
||||
|
||||
/// The format "yyyy-MM-dd".
|
||||
@@ -43,8 +43,6 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - NSDateComponents conversion
|
||||
|
||||
/// The date components
|
||||
public let dateComponents: DateComponents
|
||||
|
||||
@@ -61,9 +59,9 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC
|
||||
self.format = format
|
||||
self.dateComponents = dateComponents
|
||||
}
|
||||
|
||||
// MARK: - StatementColumnConvertible adoption
|
||||
|
||||
}
|
||||
|
||||
extension DatabaseDateComponents: StatementColumnConvertible {
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -86,10 +84,10 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC
|
||||
}
|
||||
self.init(components.dateComponents, format: components.format)
|
||||
}
|
||||
|
||||
// MARK: - DatabaseValueConvertible adoption
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
}
|
||||
|
||||
extension DatabaseDateComponents: DatabaseValueConvertible {
|
||||
/// Returns a TEXT database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
let dateString: String?
|
||||
switch format {
|
||||
@@ -128,39 +126,32 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC
|
||||
return [dateString, timeString].compactMap { $0 }.joined(separator: " ").databaseValue
|
||||
}
|
||||
|
||||
/// Returns a DatabaseDateComponents if *dbValue* contains a
|
||||
/// valid date.
|
||||
/// Creates a `DatabaseDateComponents` from the specified database value.
|
||||
///
|
||||
/// The supported formats are:
|
||||
///
|
||||
/// - `YYYY-MM-DD`
|
||||
/// - `YYYY-MM-DD HH:MM`
|
||||
/// - `YYYY-MM-DD HH:MM:SS`
|
||||
/// - `YYYY-MM-DD HH:MM:SS.SSS`
|
||||
/// - `YYYY-MM-DDTHH:MM`
|
||||
/// - `YYYY-MM-DDTHH:MM:SS`
|
||||
/// - `YYYY-MM-DDTHH:MM:SS.SSS`
|
||||
/// - `HH:MM`
|
||||
/// - `HH:MM:SS`
|
||||
/// - `HH:MM:SS.SSS`
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_datefunc.html>
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> DatabaseDateComponents? {
|
||||
// https://www.sqlite.org/lang_datefunc.html
|
||||
//
|
||||
// Supported formats are:
|
||||
//
|
||||
// - YYYY-MM-DD
|
||||
// - YYYY-MM-DD HH:MM
|
||||
// - YYYY-MM-DD HH:MM:SS
|
||||
// - YYYY-MM-DD HH:MM:SS.SSS
|
||||
// - YYYY-MM-DDTHH:MM
|
||||
// - YYYY-MM-DDTHH:MM:SS
|
||||
// - YYYY-MM-DDTHH:MM:SS.SSS
|
||||
// - HH:MM
|
||||
// - HH:MM:SS
|
||||
// - HH:MM:SS.SSS
|
||||
|
||||
// We need a String
|
||||
guard let string = String.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return SQLiteDateParser().components(from: string)
|
||||
}
|
||||
|
||||
// MARK: - Codable adoption
|
||||
|
||||
|
||||
/// Creates a new instance by decoding from the given decoder.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - decoder: The decoder to read data from.
|
||||
}
|
||||
|
||||
extension DatabaseDateComponents: Decodable {
|
||||
public init(from decoder: Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
let stringValue = try container.decode(String.self)
|
||||
@@ -170,11 +161,9 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC
|
||||
}
|
||||
self = decodedValue
|
||||
}
|
||||
|
||||
/// Encodes this value into the given encoder.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - encoder: The encoder to write data to.
|
||||
}
|
||||
|
||||
extension DatabaseDateComponents: Encodable {
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(String.fromDatabaseValue(databaseValue)!)
|
||||
|
||||
@@ -15,12 +15,10 @@ import Foundation
|
||||
/// extension Foo : DatabaseValueConvertible { /* empty */ }
|
||||
extension DatabaseValueConvertible where Self: ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
(self as! ReferenceType).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a value initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
ReferenceType.fromDatabaseValue(dbValue).flatMap { cast($0) }
|
||||
}
|
||||
|
||||
@@ -4,22 +4,24 @@ import Foundation
|
||||
/// NSDate is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
extension NSDate: DatabaseValueConvertible {
|
||||
/// Returns a database value that contains the date encoded as
|
||||
/// Returns a TEXT database value that contains the date encoded as
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
public var databaseValue: DatabaseValue {
|
||||
(self as Date).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a date initialized from dbValue, if possible.
|
||||
/// Creates an `NSDate` with the specified database value.
|
||||
///
|
||||
/// If database value contains a number, that number is interpreted as a
|
||||
/// If the database value contains a number, that number is interpreted as a
|
||||
/// timeinterval since 00:00:00 UTC on 1 January 1970.
|
||||
///
|
||||
/// If database value contains a string, that string is interpreted as a
|
||||
/// If the database value contains a string, that string is interpreted as a
|
||||
/// [SQLite date](https://sqlite.org/lang_datefunc.html) in the UTC time
|
||||
/// zone. Nil is returned if the date string does not contain at least the
|
||||
/// year, month and day components. Other components (minutes, etc.)
|
||||
/// are set to zero if missing.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
guard let date = Date.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
@@ -32,22 +34,24 @@ extension NSDate: DatabaseValueConvertible {
|
||||
/// Date is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
extension Date: DatabaseValueConvertible {
|
||||
/// Returns a database value that contains the date encoded as
|
||||
/// Returns a TEXT database value that contains the date encoded as
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
public var databaseValue: DatabaseValue {
|
||||
storageDateFormatter.string(from: self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a date initialized from dbValue, if possible.
|
||||
/// Creates an `Date` with the specified database value.
|
||||
///
|
||||
/// If database value contains a number, that number is interpreted as a
|
||||
/// If the database value contains a number, that number is interpreted as a
|
||||
/// timeinterval since 00:00:00 UTC on 1 January 1970.
|
||||
///
|
||||
/// If database value contains a string, that string is interpreted as a
|
||||
/// If the database value contains a string, that string is interpreted as a
|
||||
/// [SQLite date](https://sqlite.org/lang_datefunc.html) in the UTC time
|
||||
/// zone. Nil is returned if the date string does not contain at least the
|
||||
/// year, month and day components. Other components (minutes, etc.)
|
||||
/// are set to zero if missing.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Date? {
|
||||
if let databaseDateComponents = DatabaseDateComponents.fromDatabaseValue(dbValue) {
|
||||
return Date(databaseDateComponents: databaseDateComponents)
|
||||
|
||||
@@ -3,12 +3,22 @@ import Foundation
|
||||
|
||||
/// Decimal adopts DatabaseValueConvertible
|
||||
extension Decimal: DatabaseValueConvertible {
|
||||
/// Returns a TEXT decimal value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
NSDecimalNumber(decimal: self)
|
||||
.description(withLocale: Locale(identifier: "en_US_POSIX"))
|
||||
.databaseValue
|
||||
}
|
||||
|
||||
/// Creates an `Decimal` with the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer or a double, returns a
|
||||
/// `Decimal` initialized from this number.
|
||||
///
|
||||
/// If the database value contains a string, parses the string with the
|
||||
/// `en_US_POSIX` locale.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64):
|
||||
|
||||
@@ -4,13 +4,19 @@ import Foundation
|
||||
/// NSData is convertible to and from DatabaseValue.
|
||||
extension NSData: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// Returns a BLOB database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
(self as Data).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an NSData initialized from *dbValue*, if it contains
|
||||
/// a Blob.
|
||||
/// Returns a `NSData` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a data blob, returns it.
|
||||
///
|
||||
/// If the database value contains a string, returns this string converted
|
||||
/// to UTF8 data.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
guard let data = Data.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
|
||||
@@ -3,7 +3,7 @@ import Foundation
|
||||
/// NSNull adopts DatabaseValueConvertible
|
||||
extension NSNull: DatabaseValueConvertible {
|
||||
|
||||
/// Returns DatabaseValue.null.
|
||||
/// Returns the NULL database value.
|
||||
public var databaseValue: DatabaseValue { .null }
|
||||
|
||||
/// Returns nil.
|
||||
|
||||
@@ -12,7 +12,13 @@ private let integerRoundingBehavior = NSDecimalNumberHandler(
|
||||
/// NSNumber adopts DatabaseValueConvertible
|
||||
extension NSNumber: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// A database value.
|
||||
///
|
||||
/// If the number is an integer `NSDecimalNumber`, returns an INTEGER
|
||||
/// database value.
|
||||
///
|
||||
/// Otherwise, returns an INTEGER or REAL database value, according to the
|
||||
/// value stored in the `NSNumber`.
|
||||
public var databaseValue: DatabaseValue {
|
||||
// Don't lose precision: store integers that fits in Int64 as Int64
|
||||
if let decimal = self as? NSDecimalNumber,
|
||||
@@ -64,7 +70,15 @@ extension NSNumber: DatabaseValueConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an NSNumber initialized from *dbValue*, if possible.
|
||||
/// Returns a `NSNumber` from the specified database value.
|
||||
///
|
||||
/// If the database value is an integer or a double, returns an `NSNumber`
|
||||
/// initialized from this number.
|
||||
///
|
||||
/// If the database value is a string, returns an `NSDecimalNumber` parsed
|
||||
/// with the `en_US_POSIX` locale.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64):
|
||||
|
||||
@@ -4,12 +4,19 @@ import Foundation
|
||||
/// NSString adopts DatabaseValueConvertible
|
||||
extension NSString: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// Returns a TEXT database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
(self as String).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an NSString initialized from *dbValue*, if possible.
|
||||
/// Returns a `NSString` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a string, returns it.
|
||||
///
|
||||
/// If the database value contains a data blob, parses this data as an
|
||||
/// UTF8 string.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
guard let string = String.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
|
||||
@@ -4,13 +4,11 @@ import Foundation
|
||||
/// NSURL stores its absoluteString in the database.
|
||||
extension NSURL: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// (the URL's absoluteString).
|
||||
/// Returns a TEXT database value containing the absolute URL.
|
||||
public var databaseValue: DatabaseValue {
|
||||
absoluteString?.databaseValue ?? .null
|
||||
}
|
||||
|
||||
/// Returns an NSURL initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
guard let string = String.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
|
||||
@@ -3,6 +3,7 @@ import Foundation
|
||||
#if !os(Linux)
|
||||
/// NSUUID adopts DatabaseValueConvertible
|
||||
extension NSUUID: DatabaseValueConvertible {
|
||||
/// Returns a BLOB database value containing the uuid bytes.
|
||||
public var databaseValue: DatabaseValue {
|
||||
var uuidBytes = ContiguousArray(repeating: UInt8(0), count: 16)
|
||||
return uuidBytes.withUnsafeMutableBufferPointer { buffer in
|
||||
@@ -11,6 +12,14 @@ extension NSUUID: DatabaseValueConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a `NSUUID` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a string, parses this string as an uuid.
|
||||
///
|
||||
/// If the database value contains a data blob that contains 16 bytes,
|
||||
/// returns a uuid from those bytes.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
switch dbValue.storage {
|
||||
case .blob(let data) where data.count == 16:
|
||||
@@ -28,12 +37,21 @@ extension NSUUID: DatabaseValueConvertible {
|
||||
|
||||
/// UUID adopts DatabaseValueConvertible
|
||||
extension UUID: DatabaseValueConvertible {
|
||||
/// Returns a BLOB database value containing the uuid bytes.
|
||||
public var databaseValue: DatabaseValue {
|
||||
withUnsafeBytes(of: uuid) {
|
||||
Data(bytes: $0.baseAddress!, count: $0.count).databaseValue
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a `UUID` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a string, parses this string as an uuid.
|
||||
///
|
||||
/// If the database value contains a data blob that contains 16 bytes,
|
||||
/// returns a uuid from those bytes.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UUID? {
|
||||
switch dbValue.storage {
|
||||
case .blob(let data) where data.count == 16:
|
||||
|
||||
@@ -12,12 +12,17 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
self = sqlite3_column_int64(sqliteStatement, index) != 0
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// Returns an INTEGER database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
(self ? 1 : 0).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a Bool initialized from *dbValue*, if possible.
|
||||
/// Returns a `Bool` from the specified database value.
|
||||
///
|
||||
/// If the database value contains an integer or a double, returns whether
|
||||
/// this number is zero.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Bool? {
|
||||
// IMPLEMENTATION NOTE
|
||||
//
|
||||
@@ -106,12 +111,20 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// Returns an INTEGER database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an Int initialized from *dbValue*, if possible.
|
||||
/// Returns a `Int` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
/// rounding toward zero, returns the conversion.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { Int(exactly: $0) }
|
||||
}
|
||||
@@ -137,12 +150,20 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// Returns an INTEGER database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an Int8 initialized from *dbValue*, if possible.
|
||||
/// Returns a `Int8` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
/// rounding toward zero, returns the conversion.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int8? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { Int8(exactly: $0) }
|
||||
}
|
||||
@@ -168,12 +189,20 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// Returns an INTEGER database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an Int16 initialized from *dbValue*, if possible.
|
||||
/// Returns a `Int16` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
/// rounding toward zero, returns the conversion.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int16? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { Int16(exactly: $0) }
|
||||
}
|
||||
@@ -199,12 +228,20 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// Returns an INTEGER database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an Int32 initialized from *dbValue*, if possible.
|
||||
/// Returns a `Int32` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
/// rounding toward zero, returns the conversion.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int32? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { Int32(exactly: $0) }
|
||||
}
|
||||
@@ -226,12 +263,19 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
self = sqlite3_column_int64(sqliteStatement, index)
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// Returns an INTEGER database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
DatabaseValue(storage: .int64(self))
|
||||
}
|
||||
|
||||
/// Returns an Int64 initialized from *dbValue*, if possible.
|
||||
/// Returns a `Int64` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer, returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
/// rounding toward zero, returns the conversion.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int64? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64):
|
||||
@@ -266,12 +310,20 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// Returns an INTEGER database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an Int initialized from *dbValue*, if possible.
|
||||
/// Returns a `UInt` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
/// rounding toward zero, returns the conversion.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { UInt(exactly: $0) }
|
||||
}
|
||||
@@ -297,12 +349,20 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// Returns an INTEGER database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an UInt8 initialized from *dbValue*, if possible.
|
||||
/// Returns a `UInt8` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
/// rounding toward zero, returns the conversion.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt8? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { UInt8(exactly: $0) }
|
||||
}
|
||||
@@ -328,12 +388,20 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// Returns an INTEGER database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an UInt16 initialized from *dbValue*, if possible.
|
||||
/// Returns a `UInt16` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
/// rounding toward zero, returns the conversion.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt16? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { UInt16(exactly: $0) }
|
||||
}
|
||||
@@ -359,12 +427,20 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// Returns an INTEGER database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an UInt32 initialized from *dbValue*, if possible.
|
||||
/// Returns a `UInt32` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
/// rounding toward zero, returns the conversion.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt32? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { UInt32(exactly: $0) }
|
||||
}
|
||||
@@ -390,12 +466,20 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
self = v
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// Returns an INTEGER database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an UInt64 initialized from *dbValue*, if possible.
|
||||
/// Returns a `UInt64` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer representable in this type,
|
||||
/// returns this integer.
|
||||
///
|
||||
/// If the database value contains a double representable in this type after
|
||||
/// rounding toward zero, returns the conversion.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt64? {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { UInt64(exactly: $0) }
|
||||
}
|
||||
@@ -417,12 +501,18 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
self = sqlite3_column_double(sqliteStatement, index)
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// Returns a REAL database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
DatabaseValue(storage: .double(self))
|
||||
}
|
||||
|
||||
/// Returns a Double initialized from *dbValue*, if possible.
|
||||
/// Returns a `Double` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer, returns the conversion.
|
||||
///
|
||||
/// If the database value contains a double, returns this double.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Double? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64):
|
||||
@@ -451,12 +541,18 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
self = Float(sqlite3_column_double(sqliteStatement, index))
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// Returns a REAL database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
Double(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a Float initialized from *dbValue*, if possible.
|
||||
/// Returns a `Float` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer, returns the conversion.
|
||||
///
|
||||
/// If the database value contains a double, returns the conversion.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Float? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64):
|
||||
@@ -485,12 +581,19 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
self = String(cString: sqlite3_column_text(sqliteStatement, index)!)
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// Returns a TEXT database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
DatabaseValue(storage: .string(self))
|
||||
}
|
||||
|
||||
/// Returns a String initialized from *dbValue*, if possible.
|
||||
/// Returns a `String` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a string, returns it.
|
||||
///
|
||||
/// If the database value contains a data blob, parses this data as an
|
||||
/// UTF8 string.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> String? {
|
||||
switch dbValue.storage {
|
||||
case .blob(let data):
|
||||
@@ -507,24 +610,41 @@ 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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - SQL Functions
|
||||
|
||||
extension DatabaseFunction {
|
||||
/// An SQL function that returns the Swift built-in capitalized
|
||||
/// String property.
|
||||
/// An SQL function that calls the Foundation
|
||||
/// `String.capitalized` property.
|
||||
///
|
||||
/// The function returns NULL for non-strings values.
|
||||
/// `NULL` is returned for non-strings values.
|
||||
///
|
||||
/// This function is automatically added by GRDB to your database
|
||||
/// connections. It is the function used by the query interface's
|
||||
/// capitalized:
|
||||
/// ``SQLSpecificExpressible/capitalized``:
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.capitalized)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```swift
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.capitalized)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let capitalize =
|
||||
DatabaseFunction("swiftCapitalizedString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
@@ -533,18 +653,20 @@ extension DatabaseFunction {
|
||||
return string.capitalized
|
||||
}
|
||||
|
||||
/// An SQL function that returns the Swift built-in lowercased
|
||||
/// String property.
|
||||
/// An SQL function that calls the Swift
|
||||
/// `String.lowercased()` method.
|
||||
///
|
||||
/// The function returns NULL for non-strings values.
|
||||
/// `NULL` is returned for non-strings values.
|
||||
///
|
||||
/// This function is automatically added by GRDB to your database
|
||||
/// connections. It is the function used by the query interface's
|
||||
/// lowercased:
|
||||
/// ``SQLSpecificExpressible/lowercased``:
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.lowercased())
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```swift
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.lowercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let lowercase =
|
||||
DatabaseFunction("swiftLowercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
@@ -553,18 +675,20 @@ extension DatabaseFunction {
|
||||
return string.lowercased()
|
||||
}
|
||||
|
||||
/// An SQL function that returns the Swift built-in uppercased
|
||||
/// String property.
|
||||
/// An SQL function that calls the Swift
|
||||
/// `String.uppercased()` method.
|
||||
///
|
||||
/// The function returns NULL for non-strings values.
|
||||
/// `NULL` is returned for non-strings values.
|
||||
///
|
||||
/// This function is automatically added by GRDB to your database
|
||||
/// connections. It is the function used by the query interface's
|
||||
/// uppercased:
|
||||
/// ``SQLSpecificExpressible/uppercased``:
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.uppercased())
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```swift
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.uppercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let uppercase =
|
||||
DatabaseFunction("swiftUppercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
@@ -572,21 +696,21 @@ extension DatabaseFunction {
|
||||
}
|
||||
return string.uppercased()
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseFunction {
|
||||
/// An SQL function that returns the Swift built-in
|
||||
/// localizedCapitalized String property.
|
||||
/// An SQL function that calls the Foundation
|
||||
/// `String.localizedCapitalized` property.
|
||||
///
|
||||
/// The function returns NULL for non-strings values.
|
||||
/// `NULL` is returned for non-strings values.
|
||||
///
|
||||
/// This function is automatically added by GRDB to your database
|
||||
/// connections. It is the function used by the query interface's
|
||||
/// localizedCapitalized:
|
||||
/// ``SQLSpecificExpressible/localizedCapitalized``:
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedCapitalized)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```swift
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedCapitalized)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let localizedCapitalize =
|
||||
DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
@@ -595,18 +719,21 @@ extension DatabaseFunction {
|
||||
return string.localizedCapitalized
|
||||
}
|
||||
|
||||
/// An SQL function that returns the Swift built-in
|
||||
/// localizedLowercased String property.
|
||||
|
||||
/// An SQL function that calls the Foundation
|
||||
/// `String.localizedLowercase` property.
|
||||
///
|
||||
/// The function returns NULL for non-strings values.
|
||||
/// `NULL` is returned for non-strings values.
|
||||
///
|
||||
/// This function is automatically added by GRDB to your database
|
||||
/// connections. It is the function used by the query interface's
|
||||
/// localizedLowercased:
|
||||
/// ``SQLSpecificExpressible/localizedLowercased``:
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedLowercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```swift
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedLowercase)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let localizedLowercase =
|
||||
DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
@@ -615,18 +742,20 @@ extension DatabaseFunction {
|
||||
return string.localizedLowercase
|
||||
}
|
||||
|
||||
/// An SQL function that returns the Swift built-in
|
||||
/// localizedUppercased String property.
|
||||
/// An SQL function that calls the Foundation
|
||||
/// `String.localizedUppercase` property.
|
||||
///
|
||||
/// The function returns NULL for non-strings values.
|
||||
/// `NULL` is returned for non-strings values.
|
||||
///
|
||||
/// This function is automatically added by GRDB to your database
|
||||
/// connections. It is the function used by the query interface's
|
||||
/// localizedUppercased:
|
||||
/// ``SQLSpecificExpressible/localizedUppercased``:
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedUppercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```swift
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedUppercase)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let localizedUppercase =
|
||||
DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
@@ -651,96 +780,146 @@ extension DatabaseCollation {
|
||||
// collation names with sqlite3_collation_needed().
|
||||
// See https://www.sqlite.org/capi3ref.html#sqlite3_collation_needed
|
||||
|
||||
/// A collation, or SQL string comparison function, that compares strings
|
||||
/// according to the the Swift built-in == and <= operators.
|
||||
/// A collation that compares strings according to the built-in `==` and
|
||||
/// `<=` operators of the Swift String.
|
||||
///
|
||||
/// This collation is automatically added by GRDB to your database
|
||||
/// connections.
|
||||
///
|
||||
/// You can use it when creating database tables:
|
||||
/// You can use the collation when creating database tables:
|
||||
///
|
||||
/// let collationName = DatabaseCollation.caseInsensitiveCompare.name
|
||||
/// dbQueue.execute(sql: """
|
||||
/// CREATE TABLE players (
|
||||
/// name TEXT COLLATE \(collationName)
|
||||
/// )
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// try db.create(table: "player") { t in
|
||||
/// t.column("name", .text).collate(.unicodeCompare)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Embed the collation name in your raw SQL queries:
|
||||
///
|
||||
/// ```swift
|
||||
/// let collationName = DatabaseCollation.unicodeCompare.name
|
||||
/// dbQueue.execute(sql: """
|
||||
/// CREATE TABLE player (
|
||||
/// name TEXT COLLATE \(collationName)
|
||||
/// )
|
||||
/// """)
|
||||
/// ```
|
||||
public static let unicodeCompare =
|
||||
DatabaseCollation("swiftCompare") { (lhs, rhs) in
|
||||
(lhs < rhs) ? .orderedAscending : ((lhs == rhs) ? .orderedSame : .orderedDescending)
|
||||
}
|
||||
|
||||
/// A collation, or SQL string comparison function, that compares strings
|
||||
/// according to the the Swift built-in caseInsensitiveCompare(_:) method.
|
||||
/// A collation that compares strings according to the Foundation
|
||||
/// `String.caseInsensitiveCompare(_:)` method.
|
||||
///
|
||||
/// This collation is automatically added by GRDB to your database
|
||||
/// connections.
|
||||
///
|
||||
/// You can use it when creating database tables:
|
||||
/// You can use the collation when creating database tables:
|
||||
///
|
||||
/// let collationName = DatabaseCollation.caseInsensitiveCompare.name
|
||||
/// dbQueue.execute(sql: """
|
||||
/// CREATE TABLE players (
|
||||
/// name TEXT COLLATE \(collationName)
|
||||
/// )
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// try db.create(table: "player") { t in
|
||||
/// t.column("name", .text).collate(.caseInsensitiveCompare)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Embed the collation name in your raw SQL queries:
|
||||
///
|
||||
/// ```swift
|
||||
/// let collationName = DatabaseCollation.caseInsensitiveCompare.name
|
||||
/// dbQueue.execute(sql: """
|
||||
/// CREATE TABLE player (
|
||||
/// name TEXT COLLATE \(collationName)
|
||||
/// )
|
||||
/// """)
|
||||
/// ```
|
||||
public static let caseInsensitiveCompare =
|
||||
DatabaseCollation("swiftCaseInsensitiveCompare") { (lhs, rhs) in
|
||||
lhs.caseInsensitiveCompare(rhs)
|
||||
}
|
||||
|
||||
/// A collation, or SQL string comparison function, that compares strings
|
||||
/// according to the the Swift built-in localizedCaseInsensitiveCompare(_:) method.
|
||||
/// A collation that compares strings according to the Foundation
|
||||
/// `String.localizedCaseInsensitiveCompare(_:)` method.
|
||||
///
|
||||
/// This collation is automatically added by GRDB to your database
|
||||
/// connections.
|
||||
///
|
||||
/// You can use it when creating database tables:
|
||||
/// You can use the collation when creating database tables:
|
||||
///
|
||||
/// let collationName = DatabaseCollation.localizedCaseInsensitiveCompare.name
|
||||
/// dbQueue.execute(sql: """
|
||||
/// CREATE TABLE players (
|
||||
/// name TEXT COLLATE \(collationName)
|
||||
/// )
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// try db.create(table: "player") { t in
|
||||
/// t.column("name", .text).collate(.localizedCaseInsensitiveCompare)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Embed the collation name in your raw SQL queries:
|
||||
///
|
||||
/// ```swift
|
||||
/// let collationName = DatabaseCollation.localizedCaseInsensitiveCompare.name
|
||||
/// dbQueue.execute(sql: """
|
||||
/// CREATE TABLE player (
|
||||
/// name TEXT COLLATE \(collationName)
|
||||
/// )
|
||||
/// """)
|
||||
/// ```
|
||||
public static let localizedCaseInsensitiveCompare =
|
||||
DatabaseCollation("swiftLocalizedCaseInsensitiveCompare") { (lhs, rhs) in
|
||||
lhs.localizedCaseInsensitiveCompare(rhs)
|
||||
}
|
||||
|
||||
/// A collation, or SQL string comparison function, that compares strings
|
||||
/// according to the the Swift built-in localizedCompare(_:) method.
|
||||
/// A collation that compares strings according to the Foundation
|
||||
/// `String.localizedCompare(_:)` method.
|
||||
///
|
||||
/// This collation is automatically added by GRDB to your database
|
||||
/// connections.
|
||||
///
|
||||
/// You can use it when creating database tables:
|
||||
/// You can use the collation when creating database tables:
|
||||
///
|
||||
/// let collationName = DatabaseCollation.localizedCompare.name
|
||||
/// dbQueue.execute(sql: """
|
||||
/// CREATE TABLE players (
|
||||
/// name TEXT COLLATE \(collationName)
|
||||
/// )
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// try db.create(table: "player") { t in
|
||||
/// t.column("name", .text).collate(.localizedCompare)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Embed the collation name in your raw SQL queries:
|
||||
///
|
||||
/// ```swift
|
||||
/// let collationName = DatabaseCollation.localizedCompare.name
|
||||
/// dbQueue.execute(sql: """
|
||||
/// CREATE TABLE player (
|
||||
/// name TEXT COLLATE \(collationName)
|
||||
/// )
|
||||
/// """)
|
||||
/// ```
|
||||
public static let localizedCompare =
|
||||
DatabaseCollation("swiftLocalizedCompare") { (lhs, rhs) in
|
||||
lhs.localizedCompare(rhs)
|
||||
}
|
||||
|
||||
/// A collation, or SQL string comparison function, that compares strings
|
||||
/// according to the the Swift built-in localizedStandardCompare(_:) method.
|
||||
/// A collation that compares strings according to the Foundation
|
||||
/// `String.localizedStandardCompare(_:)` method.
|
||||
///
|
||||
/// This collation is automatically added by GRDB to your database
|
||||
/// connections.
|
||||
///
|
||||
/// You can use it when creating database tables:
|
||||
/// You can use the collation when creating database tables:
|
||||
///
|
||||
/// let collationName = DatabaseCollation.localizedStandardCompare.name
|
||||
/// dbQueue.execute(sql: """
|
||||
/// CREATE TABLE players (
|
||||
/// name TEXT COLLATE \(collationName)
|
||||
/// )
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// try db.create(table: "player") { t in
|
||||
/// t.column("name", .text).collate(.localizedStandardCompare)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Embed the collation name in your raw SQL queries:
|
||||
///
|
||||
/// ```swift
|
||||
/// let collationName = DatabaseCollation.localizedStandardCompare.name
|
||||
/// dbQueue.execute(sql: """
|
||||
/// CREATE TABLE player (
|
||||
/// name TEXT COLLATE \(collationName)
|
||||
/// )
|
||||
/// """)
|
||||
/// ```
|
||||
public static let localizedStandardCompare =
|
||||
DatabaseCollation("swiftLocalizedStandardCompare") { (lhs, rhs) in
|
||||
lhs.localizedStandardCompare(rhs)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+152
-106
@@ -2,8 +2,8 @@ extension Database {
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// Add a transaction observer, so that it gets notified of
|
||||
/// database changes.
|
||||
/// Adds a transaction observer, so that it gets notified of
|
||||
/// database changes and transactions.
|
||||
///
|
||||
/// This method has no effect on read-only database connections.
|
||||
///
|
||||
@@ -21,12 +21,12 @@ extension Database {
|
||||
// Drop cached statements that delete, because the addition of an
|
||||
// observer may change the need for truncate optimization prevention.
|
||||
publicStatementCache.removeAll { $0.isDeleteStatement }
|
||||
internalStatementCache.removeAll{ $0.isDeleteStatement }
|
||||
internalStatementCache.removeAll { $0.isDeleteStatement }
|
||||
|
||||
observationBroker.add(transactionObserver: transactionObserver, extent: extent)
|
||||
}
|
||||
|
||||
/// Remove a transaction observer.
|
||||
/// Removes a transaction observer.
|
||||
public func remove(transactionObserver: some TransactionObserver) {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
guard let observationBroker else { return }
|
||||
@@ -40,21 +40,48 @@ extension Database {
|
||||
}
|
||||
|
||||
/// Registers closures to be executed after the next or current
|
||||
/// transaction completion.
|
||||
/// transaction completes.
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// This method helps synchronizing the database with other resources,
|
||||
/// such as files, or system services.
|
||||
///
|
||||
/// In the example below, a `CLLocationManager` starts monitoring a
|
||||
/// `CLRegion` if and only if it has successfully been stored in
|
||||
/// the database:
|
||||
///
|
||||
/// ```swift
|
||||
/// /// Inserts a region in the database, and start monitoring upon
|
||||
/// /// successful insertion.
|
||||
/// func startMonitoring(_ db: Database, region: CLRegion) throws {
|
||||
/// // Make sure database is inside a transaction
|
||||
/// try db.inSavepoint {
|
||||
///
|
||||
/// // Save the region in the database
|
||||
/// try insert(...)
|
||||
///
|
||||
/// // Start monitoring if and only if the insertion is
|
||||
/// // eventually committed to disk
|
||||
/// db.afterNextTransaction { _ in
|
||||
/// print("success")
|
||||
/// // locationManager prefers the main queue:
|
||||
/// DispatchQueue.main.async {
|
||||
/// locationManager.startMonitoring(for: region)
|
||||
/// }
|
||||
/// }
|
||||
/// ...
|
||||
/// } // prints "commit"
|
||||
///
|
||||
/// Closure are executed in a protected dispatch queue, serialized will all
|
||||
/// database updates.
|
||||
/// return .commit
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - precondition: Database is not read-only.
|
||||
/// - parameter onCommit: A closure execute on transaction commit.
|
||||
/// - parameter onRollback: A closure execute on transaction rollback.
|
||||
/// The method above won't trigger the location manager if the transaction
|
||||
/// is eventually rollbacked (explicitly, or because of an error).
|
||||
///
|
||||
/// The `onCommit` and `onRollback` closures are executed in the writer
|
||||
/// dispatch queue, serialized will all database updates.
|
||||
///
|
||||
/// - precondition: Database connection is not read-only.
|
||||
/// - parameter onCommit: A closure executed on transaction commit.
|
||||
/// - parameter onRollback: A closure executed on transaction rollback.
|
||||
public func afterNextTransaction(
|
||||
onCommit: @escaping (Database) -> Void,
|
||||
onRollback: @escaping (Database) -> Void = { _ in })
|
||||
@@ -89,15 +116,13 @@ extension Database {
|
||||
extent: .nextTransaction)
|
||||
}
|
||||
|
||||
/// The extent of a transaction observation.
|
||||
///
|
||||
/// See ``Database/add(transactionObserver:extent:)``.
|
||||
/// The extent of the observation performed by a ``TransactionObserver``.
|
||||
public enum TransactionObservationExtent {
|
||||
/// Observation lasts until observer is deallocated
|
||||
/// Observation lasts until observer is deallocated.
|
||||
case observerLifetime
|
||||
/// Observation lasts until the next transaction
|
||||
/// Observation lasts until the next transaction.
|
||||
case nextTransaction
|
||||
/// Observation lasts until the database is closed
|
||||
/// Observation lasts until the database is closed.
|
||||
case databaseLifetime
|
||||
}
|
||||
}
|
||||
@@ -714,121 +739,132 @@ class DatabaseObservationBroker {
|
||||
|
||||
// MARK: - TransactionObserver
|
||||
|
||||
/// A transaction observer is notified of all changes and transactions committed
|
||||
/// or rollbacked on a database.
|
||||
///
|
||||
/// Adopting types must be a class.
|
||||
public protocol TransactionObserver: AnyObject {
|
||||
|
||||
/// Filters database changes that should be notified the the
|
||||
/// databaseDidChange(with:) method.
|
||||
/// Returns whether specific kinds of database changes should be notified
|
||||
/// to the observer.
|
||||
///
|
||||
/// When this method returns false, database events of this kind are not
|
||||
/// notified to the ``databaseDidChange(with:)`` method.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // An observer that is only interested in the "player" table
|
||||
/// class PlayerObserver: TransactionObserver {
|
||||
/// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
/// return eventKind.tableName == "player"
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// 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 on the observed tables.
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
|
||||
|
||||
/// Notifies a database change (insert, update, or delete).
|
||||
/// Called when the database is changed by an insert, update, or
|
||||
/// delete event.
|
||||
///
|
||||
/// The change is pending until the current transaction ends. See
|
||||
/// databaseWillCommit, databaseDidCommit and databaseDidRollback.
|
||||
///
|
||||
/// This method is called in a protected dispatch queue, serialized will all
|
||||
/// database updates.
|
||||
///
|
||||
/// The event is only valid for the duration of this method call. If you
|
||||
/// need to keep it longer, store a copy: `event.copy()`
|
||||
/// ``databaseWillCommit()-7mksu``, ``databaseDidCommit(_:)`` and
|
||||
/// ``databaseDidRollback(_:)``.
|
||||
///
|
||||
/// The observer has an opportunity to stop receiving further change events
|
||||
/// from the current transaction by calling the
|
||||
/// stopObservingDatabaseChangesUntilNextTransaction() method.
|
||||
/// ``stopObservingDatabaseChangesUntilNextTransaction()`` method.
|
||||
///
|
||||
/// - warning: this method must not change the database.
|
||||
/// - note: The event is only valid for the duration of this method call.
|
||||
/// If you need to keep it longer, store a copy: `event.copy()`.
|
||||
///
|
||||
/// - precondition: This method must not access the database.
|
||||
func databaseDidChange(with event: DatabaseEvent)
|
||||
|
||||
/// When a transaction is about to be committed, the transaction observer
|
||||
/// has an opportunity to rollback pending changes by throwing an error.
|
||||
/// Called when a transaction is about to be committed.
|
||||
///
|
||||
/// This method is called on the database queue.
|
||||
/// The transaction observer has an opportunity to rollback pending changes
|
||||
/// by throwing an error from this method.
|
||||
///
|
||||
/// - warning: this method must not change the database.
|
||||
///
|
||||
/// - throws: An eventual error that rollbacks pending changes.
|
||||
/// - precondition: This method must not access the database.
|
||||
/// - throws: The eventual error that rollbacks pending changes.
|
||||
func databaseWillCommit() throws
|
||||
|
||||
/// Database changes have been committed.
|
||||
///
|
||||
/// This method is called on the database queue. It can change the database.
|
||||
/// Called when a transaction has been committed on disk.
|
||||
func databaseDidCommit(_ db: Database)
|
||||
|
||||
/// Database changes have been rollbacked.
|
||||
///
|
||||
/// This method is called on the database queue. It can change the database.
|
||||
/// Called when a transaction has been rollbacked.
|
||||
func databaseDidRollback(_ db: Database)
|
||||
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
/// Called when the database is changed by an insert, update, or
|
||||
/// delete event.
|
||||
///
|
||||
/// Notifies before a database change (insert, update, or delete)
|
||||
/// with change information (initial / final values for the row's
|
||||
/// columns). (Called *before* databaseDidChangeWithEvent.)
|
||||
/// columns). (Called *before* ``databaseDidChange(with:)``.)
|
||||
///
|
||||
/// The change is pending until the end of the current transaction,
|
||||
/// and you always get a second chance to get basic event information in
|
||||
/// the databaseDidChangeWithEvent callback.
|
||||
/// the ``databaseDidChange(with:)`` callback.
|
||||
///
|
||||
/// This callback is mostly useful for calculating detailed change
|
||||
/// information for a row, and provides the initial / final values.
|
||||
///
|
||||
/// This method is called in a protected dispatch queue, serialized will all
|
||||
/// database updates.
|
||||
///
|
||||
/// The event is only valid for the duration of this method call. If you
|
||||
/// need to keep it longer, store a copy: `event.copy()`
|
||||
///
|
||||
/// - warning: this method must not change the database.
|
||||
/// - warning: this method must not access the database.
|
||||
///
|
||||
/// **Availability Info**
|
||||
///
|
||||
/// 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>
|
||||
///
|
||||
/// The databaseDidChangeWithEvent callback is always available,
|
||||
/// and may provide most/all of what you need.
|
||||
func databaseWillChange(with event: DatabasePreUpdateEvent)
|
||||
#endif
|
||||
}
|
||||
|
||||
extension TransactionObserver {
|
||||
/// Default implementation does nothing
|
||||
public func databaseWillCommit() throws {
|
||||
}
|
||||
/// The default implementation does nothing.
|
||||
public func databaseWillCommit() throws { }
|
||||
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
/// Default implementation does nothing
|
||||
public func databaseWillChange(with event: DatabasePreUpdateEvent) {
|
||||
}
|
||||
/// The default implementation does nothing.
|
||||
public func databaseWillChange(with event: DatabasePreUpdateEvent) { }
|
||||
#endif
|
||||
|
||||
/// After this method has been called, the `databaseDidChange(with:)`
|
||||
/// Prevents the observer from receiving further change notifications until
|
||||
/// the next transaction.
|
||||
///
|
||||
/// After this method has been called, the ``databaseDidChange(with:)``
|
||||
/// method won't be called until the next transaction.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// class PlayerObserver: TransactionObserver {
|
||||
/// var playerTableWasModified = false
|
||||
/// ```swift
|
||||
/// // An observer that is only interested in the "player" table
|
||||
/// class PlayerObserver: TransactionObserver {
|
||||
/// var playerTableWasModified = false
|
||||
///
|
||||
/// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
/// return eventKind.tableName == "player"
|
||||
/// }
|
||||
///
|
||||
/// func databaseDidChange(with event: DatabaseEvent) {
|
||||
/// playerTableWasModified = true
|
||||
///
|
||||
/// // It is pointless to keep on tracking further changes:
|
||||
/// stopObservingDatabaseChangesUntilNextTransaction()
|
||||
/// }
|
||||
/// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
/// return eventKind.tableName == "player"
|
||||
/// }
|
||||
///
|
||||
/// - precondition: This method must be called from `databaseDidChange(with:)`.
|
||||
/// func databaseDidChange(with event: DatabaseEvent) {
|
||||
/// playerTableWasModified = true
|
||||
///
|
||||
/// // It is pointless to keep on tracking further changes:
|
||||
/// stopObservingDatabaseChangesUntilNextTransaction()
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - precondition: This method must be called from
|
||||
/// ``databaseDidChange(with:)``.
|
||||
public func stopObservingDatabaseChangesUntilNextTransaction() {
|
||||
guard let broker = SchedulingWatchdog.current?.databaseObservationBroker else {
|
||||
fatalError("""
|
||||
@@ -944,17 +980,19 @@ struct StatementObservation {
|
||||
|
||||
// MARK: - Database events
|
||||
|
||||
/// A kind of database event. See the `TransactionObserver` protocol for
|
||||
/// more information.
|
||||
/// A kind of database event.
|
||||
///
|
||||
/// See the ``TransactionObserver/observes(eventsOfKind:)`` method in the
|
||||
/// ``TransactionObserver`` protocol for more information.
|
||||
@frozen
|
||||
public enum DatabaseEventKind {
|
||||
/// The insertion of a row in a database table
|
||||
/// The insertion of a row in a database table.
|
||||
case insert(tableName: String)
|
||||
|
||||
/// The deletion of a row in a database table
|
||||
/// The deletion of a row in a database table.
|
||||
case delete(tableName: String)
|
||||
|
||||
/// The update of a set of columns in a database table
|
||||
/// The update of a set of columns in a database table.
|
||||
case update(tableName: String, columnNames: Set<String>)
|
||||
|
||||
var modifiedRegion: DatabaseRegion {
|
||||
@@ -979,7 +1017,7 @@ public enum DatabaseEventKind {
|
||||
}
|
||||
|
||||
extension DatabaseEventKind {
|
||||
/// The impacted database table
|
||||
/// The name of the impacted database table.
|
||||
public var tableName: String {
|
||||
switch self {
|
||||
case let .insert(tableName: tableName): return tableName
|
||||
@@ -994,43 +1032,51 @@ protocol DatabaseEventProtocol {
|
||||
func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool
|
||||
}
|
||||
|
||||
/// A database event, notified to TransactionObserver.
|
||||
/// A database event.
|
||||
///
|
||||
/// See the ``TransactionObserver/databaseDidChange(with:)`` method in the
|
||||
/// ``TransactionObserver`` protocol for more information.
|
||||
public struct DatabaseEvent {
|
||||
|
||||
/// An event kind
|
||||
/// An event kind.
|
||||
public enum Kind: CInt {
|
||||
/// SQLITE_INSERT
|
||||
case insert = 18
|
||||
/// An insertion event
|
||||
case insert = 18 // SQLITE_INSERT
|
||||
|
||||
/// SQLITE_DELETE
|
||||
case delete = 9
|
||||
/// A deletion event
|
||||
case delete = 9 // SQLITE_DELETE
|
||||
|
||||
/// SQLITE_UPDATE
|
||||
case update = 23
|
||||
/// An update event
|
||||
case update = 23 // SQLITE_UPDATE
|
||||
}
|
||||
|
||||
private let impl: any DatabaseEventImpl
|
||||
|
||||
/// The event kind
|
||||
/// The event kind (insert, delete, or update).
|
||||
public let kind: Kind
|
||||
|
||||
/// The database name
|
||||
/// The name of the changed database.
|
||||
public var databaseName: String { impl.databaseName }
|
||||
|
||||
/// The table name
|
||||
/// The name of the changed database table.
|
||||
public var tableName: String { impl.tableName }
|
||||
|
||||
/// The rowID of the changed row.
|
||||
public let rowID: Int64
|
||||
|
||||
/// Returns an event that can be stored:
|
||||
/// Returns a copy of the event.
|
||||
///
|
||||
/// class MyObserver: TransactionObserver {
|
||||
/// var events: [DatabaseEvent]
|
||||
/// func databaseDidChange(with event: DatabaseEvent) {
|
||||
/// events.append(event.copy())
|
||||
/// }
|
||||
/// An event is only valid for the duration of the
|
||||
/// ``TransactionObserver/databaseDidChange(with:)`` method. You must copy
|
||||
/// the event when you want to store it for later:
|
||||
///
|
||||
/// ```swift
|
||||
/// class MyObserver: TransactionObserver {
|
||||
/// var events: [DatabaseEvent]
|
||||
/// func databaseDidChange(with event: DatabaseEvent) {
|
||||
/// events.append(event.copy())
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
public func copy() -> DatabaseEvent {
|
||||
impl.copy(self)
|
||||
}
|
||||
@@ -1131,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
|
||||
@@ -1158,7 +1204,7 @@ public struct DatabasePreUpdateEvent {
|
||||
/// Returns the initial `DatabaseValue` at given index.
|
||||
///
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
/// righmost column.
|
||||
/// rightmost column.
|
||||
///
|
||||
/// The result is nil if the event is an .Insert event.
|
||||
public func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? {
|
||||
@@ -1180,7 +1226,7 @@ public struct DatabasePreUpdateEvent {
|
||||
/// Returns the final `DatabaseValue` at given index.
|
||||
///
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
/// righmost column.
|
||||
/// rightmost column.
|
||||
///
|
||||
/// The result is nil if the event is a .Delete event.
|
||||
public func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? {
|
||||
@@ -1348,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
|
||||
|
||||
+42
-28
@@ -19,40 +19,44 @@
|
||||
/// Yes, this is an awfully complex logic.
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/snapshot.html>.
|
||||
final class WALSnapshot {
|
||||
// Xcode 14 RC ships with a macOS SDK that misses snapshot support.
|
||||
// TODO: when Xcode ships with a macOS SDK that exposes snapshots, replace
|
||||
// the `os(macOS) || targetEnvironment(macCatalyst)` check with a compiler
|
||||
// version check.
|
||||
//
|
||||
// We can't enable snapshots for SQLCipher, since we don't know if they
|
||||
// are enabled.
|
||||
#if os(macOS) || targetEnvironment(macCatalyst) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT)
|
||||
init?(_ db: Database) {
|
||||
return nil
|
||||
}
|
||||
final class WALSnapshot: Sendable {
|
||||
// Xcode 14 (Swift 5.7) ships with a macOS SDK that misses snapshot support.
|
||||
// Xcode 14.1 (Swift 5.7.1) ships with a macOS SDK that has snapshot support.
|
||||
// This is the meaning of (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))
|
||||
// swiftlint:disable:next line_length
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
static let available = true
|
||||
|
||||
func compare(_ other: WALSnapshot) -> CInt {
|
||||
preconditionFailure("snapshots are not available")
|
||||
}
|
||||
#else
|
||||
private let snapshot: UnsafeMutablePointer<sqlite3_snapshot>?
|
||||
let sqliteSnapshot: UnsafeMutablePointer<sqlite3_snapshot>
|
||||
|
||||
/// Returns nil if `SQLITE_ENABLE_SNAPSHOT` is not enabled, or if an
|
||||
/// error occurs.
|
||||
init?(_ db: Database) {
|
||||
var snapshot: UnsafeMutablePointer<sqlite3_snapshot>?
|
||||
let code = withUnsafeMutablePointer(to: &snapshot) {
|
||||
init(_ db: Database) throws {
|
||||
var sqliteSnapshot: UnsafeMutablePointer<sqlite3_snapshot>?
|
||||
let code = withUnsafeMutablePointer(to: &sqliteSnapshot) {
|
||||
return sqlite3_snapshot_get(db.sqliteConnection, "main", $0)
|
||||
}
|
||||
guard code == SQLITE_OK, let snapshot else {
|
||||
return nil
|
||||
guard code == SQLITE_OK else {
|
||||
if sqlite3_get_autocommit(db.sqliteConnection) != 0 {
|
||||
throw DatabaseError(resultCode: code, message: """
|
||||
Can't create snapshot because database is in autocommit mode.
|
||||
""")
|
||||
}
|
||||
if let journalMode = try? String.fetchOne(db, sql: "PRAGMA journal_mode"),
|
||||
journalMode != "wal"
|
||||
{
|
||||
throw DatabaseError(resultCode: code, message: """
|
||||
Can't create snapshot because database is not in WAL mode.
|
||||
""")
|
||||
}
|
||||
throw DatabaseError(resultCode: code)
|
||||
}
|
||||
self.snapshot = snapshot
|
||||
guard let sqliteSnapshot else {
|
||||
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
|
||||
}
|
||||
self.sqliteSnapshot = sqliteSnapshot
|
||||
}
|
||||
|
||||
deinit {
|
||||
sqlite3_snapshot_free(snapshot)
|
||||
sqlite3_snapshot_free(sqliteSnapshot)
|
||||
}
|
||||
|
||||
/// Compares two WAL snapshots.
|
||||
@@ -61,7 +65,17 @@ final class WALSnapshot {
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/snapshot_cmp.html>.
|
||||
func compare(_ other: WALSnapshot) -> CInt {
|
||||
return sqlite3_snapshot_cmp(snapshot, other.snapshot)
|
||||
sqlite3_snapshot_cmp(sqliteSnapshot, other.sqliteSnapshot)
|
||||
}
|
||||
#endif // os(macOS) || targetEnvironment(macCatalyst) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT)
|
||||
#else
|
||||
static let available = false
|
||||
|
||||
init(_ db: Database) throws {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "snapshots are not available")
|
||||
}
|
||||
|
||||
func compare(_ other: WALSnapshot) -> CInt {
|
||||
preconditionFailure("snapshots are not available")
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -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
|
||||
@@ -0,0 +1,352 @@
|
||||
# Concurrency
|
||||
|
||||
GRDB helps your app deal with SQLite concurrency.
|
||||
|
||||
## Overview
|
||||
|
||||
If your app moves slow database jobs off the main thread, so that the user interface remains responsive, then this guide is for you. In the case of apps that share a database with other processes, such as an iOS app and its extensions, don't miss the dedicated <doc:DatabaseSharing> guide after this one.
|
||||
|
||||
**In all cases, and first and foremost, follow the <doc:Concurrency#Concurrency-Rules> right from the start.**
|
||||
|
||||
The other chapters cover, with more details, the fundamentals of SQLite concurrency, and how GRDB makes it manageable from your Swift code.
|
||||
|
||||
## Concurrency Rules
|
||||
|
||||
**The two concurrency rules are strongly recommended practices.** They are all about SQLite, a robust and reliable database that takes great care of your data: don't miss an opportunity to put it on your side!
|
||||
|
||||
### Rule 1: Connect to any database file only once
|
||||
|
||||
Open one single ``DatabaseQueue`` or ``DatabasePool`` per database file, for the whole duration of your use of the database. Not for the duration of _each_ database access, but really for the duration of _all_ database accesses to this file.
|
||||
|
||||
- *Why does this rule exist?* - Since SQLite does not support parallel writes, each `DatabaseQueue` and `DatabasePool` makes sure application threads perform writes one by one, without overlap.
|
||||
|
||||
- *Practical advice* - An app that uses a single database will connect only once. A document-based app will connect each time a document is opened, and disconnect when the document is closed. See the [demo apps] in order to see how to setup a UIKit or SwiftUI application for a single database.
|
||||
|
||||
- *What if you do not follow this rule?*
|
||||
|
||||
- You will not be able to use the <doc:DatabaseObservation> features.
|
||||
- You will see SQLite errors ([`SQLITE_BUSY`]).
|
||||
|
||||
### Rule 2: Mind your transactions
|
||||
|
||||
Database operations that are grouped in a transaction are guaranteed to be either fully saved on disk, or not at all. Read-only transactions guarantee a stable and immutable view of the database, and do not see changes performed by eventual concurrent writes.
|
||||
|
||||
In other words, transactions are the one and single tool that helps you enforce and rely on the invariants of your database (such as "all authors must have at least one book").
|
||||
|
||||
**You are responsible**, in your Swift code, for delimiting transactions. You do so by grouping database accesses inside a pair of `{ db in ... }` brackets:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// Inside a transaction
|
||||
}
|
||||
|
||||
try dbQueue.read { db
|
||||
// Inside a transaction
|
||||
}
|
||||
```
|
||||
|
||||
Alternatively, you can open an explicit transaction or savepoint: see <doc:Transactions>.
|
||||
|
||||
- *Why does this rule exist?* - Because GRDB and SQLite can not guess where to insert the transaction boundaries that protect the invariants of your database. This is your task. Transactions also avoid concurrency problems, as described in the <doc:Concurrency#Safe-and-Unsafe-Database-Accesses> section below.
|
||||
|
||||
- *Practical advice* - Take the time to identify the invariants of your database. Some of them can be enforced in the database schema itself, such as "all books must have a non-empty title", or "all books must have an author" (see <doc:DatabaseSchema>). Some invariants can only be enforced by transactions, such as "all account credits must have a matching debit", or "all authors must have at least one book".
|
||||
|
||||
- *What if you do not follow this rule?* - You will see broken database invariants, at runtime, or when your apps wakes up after a crash. These bugs corrupt user data, and are very difficult to fix.
|
||||
|
||||
|
||||
## Synchronous and Asynchronous Database Accesses
|
||||
|
||||
**You can access the database from any thread, in a synchronous or asynchronous way.**
|
||||
|
||||
➡️ **A sync access blocks the current thread** until the database operations are completed:
|
||||
|
||||
```swift
|
||||
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)
|
||||
}
|
||||
```
|
||||
|
||||
See ``DatabaseReader/read(_:)-3806d`` and ``DatabaseWriter/write(_:)-76inz``.
|
||||
|
||||
It is a programmer error to perform a sync access from any other database access (this restriction can be lifted: see <doc:Concurrency#Safe-and-Unsafe-Database-Accesses>):
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// Fatal Error: Database methods are not reentrant.
|
||||
try dbQueue.write { db in ... }
|
||||
}
|
||||
```
|
||||
|
||||
🔀 **An async access does not block the current thread.** Instead, it notifies you when the database operations are completed. There are four ways to access the database asynchronously:
|
||||
|
||||
- **Swift concurrency** (async/await)
|
||||
|
||||
[**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
|
||||
```swift
|
||||
let playerCount = try await dbQueue.read { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
|
||||
let newPlayerCount = try await dbQueue.write { db -> Int in
|
||||
try Player(name: "Arthur").insert(db)
|
||||
return try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
See ``DatabaseReader/read(_:)-4w6gy`` and ``DatabaseWriter/write(_:)-88g7e``.
|
||||
|
||||
Note the identical method names: `read`, `write`. The async version is only available in async Swift functions.
|
||||
|
||||
- **Combine publishers**
|
||||
|
||||
For example:
|
||||
|
||||
```swift
|
||||
let playerCountPublisher = dbQueue.readPublisher { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
|
||||
let newPlayerCountPublisher = dbQueue.writePublisher { db -> Int in
|
||||
try Player(name: "Arthur").insert(db)
|
||||
return try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
See ``DatabaseReader/readPublisher(receiveOn:value:)``, and ``DatabaseWriter/writePublisher(receiveOn:updates:)``.
|
||||
|
||||
Those publishers do not access the database until they are subscribed. They complete on the main dispatch queue by default.
|
||||
|
||||
- **RxSwift observables**
|
||||
|
||||
See the companion library [RxGRDB].
|
||||
|
||||
- **Completion blocks**
|
||||
|
||||
See ``DatabaseReader/asyncRead(_:)`` and ``DatabaseWriter/asyncWrite(_:completion:)``.
|
||||
|
||||
During one async access, all individual database operations grouped inside (fetch, insert, etc.) are synchronous:
|
||||
|
||||
```swift
|
||||
// One asynchronous access...
|
||||
try await dbQueue.write { db in
|
||||
// ... always performs synchronous database operations:
|
||||
try Player(...).insert(db)
|
||||
try Player(...).insert(db)
|
||||
let players = try Player.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
This is true for all async techniques.
|
||||
|
||||
This prevents the database operations from various concurrent accesses from being interleaved. For example, one access must not be able to issue a `COMMIT` statement in the middle of an unfinished concurrent write!
|
||||
|
||||
## Safe and Unsafe Database Accesses
|
||||
|
||||
**You will generally use the safe database access methods `read` and `write`.** In this context, "safe" means that a database access is concurrency-friendly, because GRDB provides the following guarantees:
|
||||
|
||||
### Serialized Writes
|
||||
|
||||
**All writes performed by one ``DatabaseQueue`` or ``DatabasePool`` instance are serialized.**
|
||||
|
||||
This guarantee prevents [`SQLITE_BUSY`] errors during concurrent writes.
|
||||
|
||||
### Write Transactions
|
||||
|
||||
**All writes are wrapped in a transaction.**
|
||||
|
||||
Concurrent reads can not see partial database updates (even reads performed by other processes).
|
||||
|
||||
### Isolated Reads
|
||||
|
||||
**All reads are wrapped in a transaction.**
|
||||
|
||||
An isolated read sees a stable and immutable state of the database, and does not see changes performed by eventual concurrent writes (even writes performed by other processes). See [Isolation In SQLite](https://www.sqlite.org/isolation.html) for more information.
|
||||
|
||||
### Forbidden Writes
|
||||
|
||||
**Inside a read access, all attempts to write raise an error.**
|
||||
|
||||
This enforces the immutability of the database during a read.
|
||||
|
||||
### Non-Reentrancy
|
||||
|
||||
**Database accesses methods are not reentrant.**
|
||||
|
||||
This reduces the opportunities for deadlocks, and fosters the clear transaction boundaries of <doc:Concurrency#Rule-2:-Mind-your-transactions>.
|
||||
|
||||
### Unsafe Database Accesses
|
||||
|
||||
Some applications need to relax this safety net, in order to achieve specific SQLite operations. In this case, replace `read` and `write` with one of the methods below:
|
||||
|
||||
- **Write outside of any transaction** (Lifted guarantee: <doc:Concurrency#Write-Transactions>)
|
||||
|
||||
See all ``DatabaseWriter`` methods with `WithoutTransaction` in their names.
|
||||
|
||||
- **Reentrant write, outside of any transaction** (Lifted guarantees: <doc:Concurrency#Write-Transactions>, <doc:Concurrency#Non-Reentrancy>)
|
||||
|
||||
See ``DatabaseWriter/unsafeReentrantWrite(_:)``.
|
||||
|
||||
- **Read outside of any transaction** (Lifted guarantees: <doc:Concurrency#Isolated-Reads>, <doc:Concurrency#Forbidden-Writes>)
|
||||
|
||||
See all ``DatabaseReader`` methods with `unsafe` in their names.
|
||||
|
||||
- **Reentrant read, outside of any transaction** (Lifted guarantees: <doc:Concurrency#Isolated-Reads>, <doc:Concurrency#Forbidden-Writes>, <doc:Concurrency#Non-Reentrancy>)
|
||||
|
||||
See ``DatabaseReader/unsafeReentrantRead(_:)``.
|
||||
|
||||
> Important: By using one of the methods above, you become responsible of the thread-safety of your application. Please understand the consequences of lifting each concurrency guarantee.
|
||||
|
||||
Some concurrency guarantees can be restored at your convenience:
|
||||
|
||||
- The <doc:Concurrency#Write-Transactions> and <doc:Concurrency#Isolated-Reads> guarantees can be restored at any point, with an explicit transaction or savepoint. For example:
|
||||
|
||||
```swift
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
try db.inTransaction { ... }
|
||||
}
|
||||
```
|
||||
|
||||
- The <doc:Concurrency#Forbidden-Writes> guarantee can only be lifted with ``DatabaseQueue``. It can be restored with [`PRAGMA query_only`](https://www.sqlite.org/pragma.html#pragma_query_only).
|
||||
|
||||
## Differences between Database Queues and Pools
|
||||
|
||||
Despite the common guarantees and rules shared by database queues and pools, those two database accessors don't have the same behavior.
|
||||
|
||||
``DatabaseQueue`` opens a single database connection, and serializes all database accesses, reads, and writes. There is never more than one thread that uses the database. In the image below, we see how three threads can see the database as time passes:
|
||||
|
||||

|
||||
|
||||
``DatabasePool`` manages a pool of several database connections, and allows concurrent reads and writes thanks to the [WAL mode](https://www.sqlite.org/wal.html). A database pool serializes all writes (the <doc:Concurrency#Serialized-Writes> guarantee). Reads are isolated so that they don't see changes performed by other threads (the <doc:Concurrency#Isolated-Reads> guarantee). This gives a very different picture:
|
||||
|
||||

|
||||
|
||||
See how, with database pools, two reads can see different database states at the same time. This may look scary! Please see the next chapter below for a relief.
|
||||
|
||||
## Concurrent Thinking
|
||||
|
||||
Despite the <doc:Concurrency#Differences-between-Database-Queues-and-Pools>, you can write robust code that works equally well with both `DatabaseQueue` and `DatabasePool`.
|
||||
|
||||
This allows your app to switch between queues and pools, at your convenience:
|
||||
|
||||
- The [demo applications] share the same database code for the on-disk pool that feeds the app, and the in-memory queue that feeds tests and SwiftUI previews. This makes sure tests and previews run fast, without any temporary file, with the same behavior as the app.
|
||||
|
||||
- Applications that perform slow write transactions (when saving a lot of data from a remote server, for example) may want to replace their queue with a pool so that the reads that feed their user interface can run in parallel.
|
||||
|
||||
All you need is a little "concurrent thinking", based on those two basic facts:
|
||||
|
||||
- You are sure, when you perform a write access, that you deal with the latest database state on disk. This is enforced by SQLite, which simply can't perform parallel writes, and by the <doc:Concurrency#Serialized-Writes> guarantee. Writes performed by other processes can trigger an [`SQLITE_BUSY`] ``DatabaseError`` that you can handle.
|
||||
|
||||
- Whenever you extract some data from a database access, immediately consider it as _stale_. It is stale, whether you use a `DatabaseQueue` or `DatabasePool`. It is stale because nothing prevents other application threads or processes from overwriting the value you have just fetched:
|
||||
|
||||
```swift
|
||||
// or dbQueue.write, for that matter
|
||||
let cookieCount = dbPool.read { db in
|
||||
try Cookie.fetchCount(db)
|
||||
}
|
||||
|
||||
// At this point, the number of cookies on disk
|
||||
// may have already changed.
|
||||
print("We have \(cookieCount) cookies left")
|
||||
```
|
||||
|
||||
Does this mean you can't rely on anything? Of course not:
|
||||
|
||||
- If you intend to display some database value on screen, use ``ValueObservation``: it always eventually notifies the latest state of the database. Your application won't display stale values for a long time: after the database has been changed on disk, the fresh value if fetched, and soon notified on the main thread where the screen can be updated.
|
||||
|
||||
- As said above, the moment of truth is the next write access!
|
||||
|
||||
## Advanced DatabasePool
|
||||
|
||||
``DatabasePool`` is very concurrent, since all reads can run in parallel, and can even run during write operations. But writes are still serialized: at any given point in time, there is no more than a single thread that is writing into the database.
|
||||
|
||||
When your application modifies the database, and then reads some value that depends on those modifications, you may want to avoid blocking concurrent writes longer than necessary - especially when the read is slow:
|
||||
|
||||
```swift
|
||||
let newPlayerCount = try dbPool.write { db in
|
||||
// Increment the number of players
|
||||
try Player(...).insert(db)
|
||||
|
||||
// Read the number of players. Concurrent writes are blocked :-(
|
||||
return try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
➡️ The synchronous solution is the ``DatabaseWriter/concurrentRead(_:)`` method. It must be called from within a write access, outside of any transaction. It returns a ``DatabaseFuture`` which you consume any time later, with the ``DatabaseFuture/wait()`` method:
|
||||
|
||||
```swift
|
||||
let future: DatabaseFuture<Int> = try dbPool.writeWithoutTransaction { db in
|
||||
// Increment the number of players
|
||||
try db.inTransaction {
|
||||
try Player(...).insert(db)
|
||||
return .commit
|
||||
}
|
||||
|
||||
// <- Not in a transaction here
|
||||
return dbPool.concurrentRead { db
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
// Handle the new player count - guaranteed greater than zero
|
||||
let newPlayerCount = try future.wait()
|
||||
} catch {
|
||||
// Handle error
|
||||
}
|
||||
```
|
||||
|
||||
🔀 The asynchronous version of `concurrentRead` is ``DatabasePool/asyncConcurrentRead(_:)``:
|
||||
|
||||
```swift
|
||||
try dbPool.writeWithoutTransaction { db in
|
||||
// Increment the number of players
|
||||
try db.inTransaction {
|
||||
try Player(...).insert(db)
|
||||
return .commit
|
||||
}
|
||||
|
||||
// <- Not in a transaction here
|
||||
dbPool.asyncConcurrentRead { dbResult in
|
||||
do {
|
||||
// Handle the new player count - guaranteed greater than zero
|
||||
let db = try dbResult.get()
|
||||
let newPlayerCount = try Player.fetchCount(db)
|
||||
} catch {
|
||||
// Handle error
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Both ``DatabaseWriter/concurrentRead(_:)`` and ``DatabasePool/asyncConcurrentRead(_:)`` block until they can guarantee their closure argument an isolated access to the database, in the exact state left by the last transaction. It then asynchronously executes this closure.
|
||||
|
||||
In the illustration below, the striped band shows the delay needed for the reading thread to acquire isolation. Until then, no other thread can write:
|
||||
|
||||
|
||||

|
||||
|
||||
Types that conform to ``TransactionObserver`` can also use those methods in their ``TransactionObserver/databaseDidCommit(_:)`` method, in order to process database changes without blocking other threads that want to write into the database.
|
||||
|
||||
## Topics
|
||||
|
||||
### Database Connections with Concurrency Guarantees
|
||||
|
||||
- ``DatabaseWriter``
|
||||
- ``DatabaseReader``
|
||||
- ``DatabaseSnapshotReader``
|
||||
|
||||
### Advanced Concurrency
|
||||
|
||||
- <doc:DatabaseSharing>
|
||||
|
||||
|
||||
[demo apps]: https://github.com/groue/GRDB.swift/tree/master/Documentation/DemoApps
|
||||
[`SQLITE_BUSY`]: https://www.sqlite.org/rescode.html#busy
|
||||
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
|
||||
[demo applications]: https://github.com/groue/GRDB.swift/tree/master/Documentation/DemoApps
|
||||
@@ -0,0 +1,111 @@
|
||||
# Database Connections
|
||||
|
||||
Open database connections to SQLite databases.
|
||||
|
||||
## Overview
|
||||
|
||||
GRDB provides two classes for accessing SQLite databases: ``DatabaseQueue`` and ``DatabasePool``:
|
||||
|
||||
```swift
|
||||
import GRDB
|
||||
|
||||
// Pick one:
|
||||
let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
|
||||
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).
|
||||
- `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
|
||||
|
||||
- ``Configuration``
|
||||
|
||||
### Connections for read and write accesses
|
||||
|
||||
- ``DatabaseQueue``
|
||||
- ``DatabasePool``
|
||||
|
||||
### Read-only connections on an unchanging database content
|
||||
|
||||
- ``DatabaseSnapshot``
|
||||
- ``DatabaseSnapshotPool``
|
||||
|
||||
### Using database connections
|
||||
|
||||
- ``Database``
|
||||
- ``DatabaseError``
|
||||
@@ -0,0 +1,36 @@
|
||||
# Database Observation
|
||||
|
||||
Observe database changes and transactions.
|
||||
|
||||
## Overview
|
||||
|
||||
**SQLite notifies its host application of changes performed to the database, as well of transaction commits and rollbacks.**
|
||||
|
||||
GRDB puts this SQLite feature to some good use, and lets you observe the database in various ways:
|
||||
|
||||
- ``ValueObservation``: Get notified when database values change.
|
||||
- ``DatabaseRegionObservation``: Get notified when a transaction impacts a database region.
|
||||
- ``Database/afterNextTransaction(onCommit:onRollback:)``: Handle transactions commits or rollbacks, one by one.
|
||||
- ``TransactionObserver``: The low-level protocol that supports all database observation features.
|
||||
|
||||
## Topics
|
||||
|
||||
### Observing Database Values
|
||||
|
||||
- ``ValueObservation``
|
||||
- ``SharedValueObservation``
|
||||
- ``AsyncValueObservation``
|
||||
|
||||
### Observing Database Transactions
|
||||
|
||||
- ``DatabaseRegionObservation``
|
||||
|
||||
### Low-Level Transaction Observers
|
||||
|
||||
- ``TransactionObserver``
|
||||
- ``Database/TransactionObservationExtent``
|
||||
|
||||
### Database Regions
|
||||
|
||||
- ``DatabaseRegion``
|
||||
- ``DatabaseRegionConvertible``
|
||||
@@ -0,0 +1,414 @@
|
||||
# The Database Schema
|
||||
|
||||
## Overview
|
||||
|
||||
**GRDB supports all database schemas, and has no requirement.** Any existing SQLite database can be opened, and you are free to structure your new databases as you wish.
|
||||
|
||||
You perform modifications to the database schema with methods such as ``Database/create(table:options:body:)``, listed at the end of this page. For example:
|
||||
|
||||
```swift
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
When you plan to evolve the schema as new versions of your application ship, wrap all schema changes in <doc:Migrations>.
|
||||
|
||||
Prefer Swift methods over raw SQL queries. They allow the compiler to check if a schema change is available on the target operating system. Only use a raw SQL query when no Swift method exist (when creating views or triggers, for example).
|
||||
|
||||
When a schema change is not directly supported by SQLite, or not available on the target operating system, database tables have to be recreated. See <doc:Migrations> for the detailed procedure.
|
||||
|
||||
## Database Schema Recommendations
|
||||
|
||||
Even though all schema are supported, some features of the library and of the Swift language are easier to use when the schema follows a few conventions described below.
|
||||
|
||||
When those conventions are not applied, or not applicable, you will have to perform extra configurations.
|
||||
|
||||
### Table names should be English, singular, and camelCased
|
||||
|
||||
Make them look like singular Swift identifiers: `player`, `team`, `postalAddress`:
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
// table columns and constraints
|
||||
}
|
||||
|
||||
// REQUIRES EXTRA CONFIGURATION
|
||||
try db.create(table: "players") { t in
|
||||
// table columns and constraints
|
||||
}
|
||||
```
|
||||
|
||||
☝️ **If table names follow a different naming convention**, record types (see <doc:QueryInterface>) will need explicit table names:
|
||||
|
||||
```swift
|
||||
extension Player: TableRecord {
|
||||
// Required because table name is not 'player'
|
||||
static let databaseTableName = "players"
|
||||
}
|
||||
|
||||
extension PostalAddress: TableRecord {
|
||||
// Required because table name is not 'postalAddress'
|
||||
static let databaseTableName = "postal_address"
|
||||
}
|
||||
|
||||
extension Award: TableRecord {
|
||||
// Required because table name is not 'award'
|
||||
static let databaseTableName = "Auszeichnung"
|
||||
}
|
||||
```
|
||||
|
||||
[Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) will need explicit keys as well:
|
||||
|
||||
```swift
|
||||
extension Player: TableRecord {
|
||||
// Explicit association key because the table name is not 'postalAddress'
|
||||
static let postalAddress = belongsTo(PostalAddress.self, key: "postalAddress")
|
||||
|
||||
// Explicit association key because the table name is not 'award'
|
||||
static let awards = hasMany(Award.self, key: "awards")
|
||||
}
|
||||
```
|
||||
|
||||
As in the above example, make sure to-one associations use singular keys, and to-many associations use plural keys.
|
||||
|
||||
### Column names should be camelCased
|
||||
|
||||
Again, make them look like Swift identifiers: `fullName`, `score`, `creationDate`:
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("fullName", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
t.column("creationDate", .datetime).notNull()
|
||||
}
|
||||
|
||||
// REQUIRES EXTRA CONFIGURATION
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("full_name", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
t.column("creation_date", .datetime).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
☝️ **If the column names follow a different naming convention**, `Codable` record types will need an explicit `CodingKeys` enum:
|
||||
|
||||
```swift
|
||||
struct Player: Decodable, FetchableRecord {
|
||||
var id: Int64
|
||||
var fullName: String
|
||||
var score: Int
|
||||
var creationDate: Date
|
||||
|
||||
// Required CodingKeys customization because
|
||||
// columns are not named like Swift properties
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id, fullName = "full_name", score, creationDate = "creation_date"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Tables should have explicit primary keys
|
||||
|
||||
A primary key uniquely identifies a row in a table. It is defined on one or several columns:
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
// Auto-incremented primary key
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
|
||||
try db.create(table: "team") { t in
|
||||
// Single-column primary key
|
||||
t.primaryKey("id", .text)
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
|
||||
try db.create(table: "membership") { t in
|
||||
// Composite primary key
|
||||
t.primaryKey {
|
||||
t.column("playerId", .integer).references("player")
|
||||
t.column("teamId", .text).references("team")
|
||||
}
|
||||
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**, 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
|
||||
try db.create(table: "player") { t in
|
||||
t.column("name", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
|
||||
// The record type for the 'player' table'
|
||||
struct Player: Codable {
|
||||
// Uniquely identifies a player.
|
||||
var rowid: Int64?
|
||||
var name: String
|
||||
var score: Int
|
||||
}
|
||||
|
||||
extension Player: Identifiable {
|
||||
// Required because the primary key column is not 'id'
|
||||
var id: Int64? { rowid }
|
||||
}
|
||||
|
||||
extension Player: FetchableRecord, MutablePersistableRecord {
|
||||
// Required because the primary key
|
||||
// is the hidden rowid column.
|
||||
static let databaseSelection: [any SQLSelectable] = [
|
||||
AllColumns(),
|
||||
Column.rowID]
|
||||
|
||||
// Update id upon successful insertion
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
rowid = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.read { db in
|
||||
// SELECT *, rowid FROM player WHERE rowid = 1
|
||||
if let player = try Player.fetchOne(db, id: 1) {
|
||||
// DELETE FROM player WHERE rowid = 1
|
||||
let deleted = try player.delete(db)
|
||||
print(deleted) // true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Single-column primary keys should be named 'id'
|
||||
|
||||
This helps record types play well with the standard `Identifiable` protocol.
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
t.primaryKey("id", .text)
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
|
||||
// REQUIRES EXTRA CONFIGURATION
|
||||
try db.create(table: "player") { t in
|
||||
t.primaryKey("uuid", .text)
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
```
|
||||
☝️ **If the primary key follows a different naming convention**, `Identifiable` record types will need a custom `CodingKeys` enum, or an extra property:
|
||||
|
||||
```swift
|
||||
// Custom coding keys
|
||||
struct Player: Codable, Identifiable {
|
||||
var id: String
|
||||
var name: String
|
||||
|
||||
// Required CodingKeys customization because
|
||||
// columns are not named like Swift properties
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "uuid", name
|
||||
}
|
||||
}
|
||||
|
||||
// Extra property
|
||||
struct Player: Identifiable {
|
||||
var uuid: String
|
||||
var name: String
|
||||
|
||||
// Required because the primary key column is not 'id'
|
||||
var id: String { uuid }
|
||||
}
|
||||
```
|
||||
|
||||
### Unique keys should be supported by unique indexes
|
||||
|
||||
Unique indexes makes sure SQLite prevents the insertion of conflicting rows:
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
// Players must have distinct names
|
||||
t.column("name", .text).unique()
|
||||
t.column("teamId", .integer).notNull().references("team")
|
||||
t.column("position", .integer).notNull()
|
||||
}
|
||||
|
||||
// One single player at any given position in a team
|
||||
try db.create(
|
||||
index: "playerTeamPosition",
|
||||
on: "player", columns: ["teamId", "position"],
|
||||
options: .unique)
|
||||
```
|
||||
|
||||
> Tip: SQLite does not support deferred unique indexes, and this creates undesired churn when you need to temporarily break them. This may happen, for example, when you want to reorder player positions in our above example.
|
||||
>
|
||||
> There exist several workarounds; one of them involves dropping and recreating the unique index after the temporary violations have been fixed. If you plan to use this technique, take care that only actual indexes can be dropped. Unique constraints created inside the table body can not:
|
||||
>
|
||||
> ```swift
|
||||
> // Unique constraint on player(name) can not be dropped.
|
||||
> try db.create(table: "player") { t in
|
||||
> t.column("name", .text).unique()
|
||||
> }
|
||||
>
|
||||
> // Unique index on team(name) can be dropped.
|
||||
> try db.create(table: "team") { t in
|
||||
> t.column("name", .text)
|
||||
> }
|
||||
> try db.create(
|
||||
> index: "teamName",
|
||||
> on: "team", columns: ["name"],
|
||||
> options: .unique)
|
||||
> ```
|
||||
>
|
||||
> If you want to turn an undroppable constraint into a droppable index, you'll need to recreate the database table. See <doc:Migrations> for the detailed procedure.
|
||||
|
||||
☝️ **If a table misses unique indexes**, some record methods such as ``FetchableRecord/fetchOne(_:key:)-92b9m`` and ``TableRecord/deleteOne(_:key:)-5pdh5`` will raise a fatal error:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// Fatal error: table player has no unique index on columns ...
|
||||
let player = try Player.fetchOne(db, key: ["teamId": 42, "position": 1])
|
||||
try Player.deleteOne(db, key: ["name": "Arthur"])
|
||||
|
||||
// Use instead:
|
||||
let player = try Player
|
||||
.filter(Column("teamId") == 42 && Column("position") == 1)
|
||||
.fetchOne(db)
|
||||
|
||||
try Player
|
||||
.filter(Column("name") == "Arthur")
|
||||
.deleteAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
### Relations between tables should be supported by foreign keys
|
||||
|
||||
[Foreign Keys](https://www.sqlite.org/foreignkeys.html) have SQLite enforce valid relationships between tables:
|
||||
|
||||
```swift
|
||||
try db.create(table: "team") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("color", .text).notNull()
|
||||
}
|
||||
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
// A player must refer to an existing team
|
||||
t.column("teamId", .integer).notNull().references("team")
|
||||
}
|
||||
|
||||
// REQUIRES EXTRA CONFIGURATION
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
// No foreign key
|
||||
t.column("teamId", .integer).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
GRDB [Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) are automatically configured from foreign keys declared in the database schema:
|
||||
|
||||
```swift
|
||||
extension Player: TableRecord {
|
||||
static let team = belongsTo(Team.self)
|
||||
}
|
||||
|
||||
extension Team: TableRecord {
|
||||
static let players = hasMany(Player.self)
|
||||
}
|
||||
```
|
||||
|
||||
See [Associations and the Database Schema](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md#associations-and-the-database-schema) for more precise recommendations.
|
||||
|
||||
☝️ **If a foreign key is not declared in the schema**, you will need to explicitly configure related associations:
|
||||
|
||||
```swift
|
||||
extension Player: TableRecord {
|
||||
// Required configuration because the database does
|
||||
// not declare any foreign key from players to their team.
|
||||
static let teamForeignKey = ForeignKey(["teamId"])
|
||||
static let team = belongsTo(Team.self,
|
||||
using: teamForeignKey)
|
||||
}
|
||||
|
||||
extension Team: TableRecord {
|
||||
// Required configuration because the database does
|
||||
// not declare any foreign key from players to their team.
|
||||
static let players = hasMany(Player.self,
|
||||
using: Player.teamForeignKey)
|
||||
}
|
||||
```
|
||||
|
||||
## Topics
|
||||
|
||||
### Database Tables
|
||||
|
||||
- ``Database/alter(table:body:)``
|
||||
- ``Database/create(table:options:body:)``
|
||||
- ``Database/create(virtualTable:ifNotExists:using:)``
|
||||
- ``Database/create(virtualTable:ifNotExists:using:_:)``
|
||||
- ``Database/drop(table:)``
|
||||
- ``Database/dropFTS4SynchronizationTriggers(forTable:)``
|
||||
- ``Database/rename(table:to:)``
|
||||
- ``Database/ColumnType``
|
||||
- ``Database/ConflictResolution``
|
||||
- ``Database/ForeignKeyAction``
|
||||
- ``TableAlteration``
|
||||
- ``TableDefinition``
|
||||
- ``TableOptions``
|
||||
- ``VirtualTableModule``
|
||||
|
||||
### Database Indexes
|
||||
|
||||
- ``Database/create(index:on:columns:options:condition:)``
|
||||
- ``Database/drop(index:)``
|
||||
- ``IndexOptions``
|
||||
|
||||
### Querying the Database Schema
|
||||
|
||||
- ``Database/columns(in:)``
|
||||
- ``Database/foreignKeys(on:)``
|
||||
- ``Database/indexes(on:)``
|
||||
- ``Database/isGRDBInternalTable(_:)``
|
||||
- ``Database/isSQLiteInternalTable(_:)``
|
||||
- ``Database/primaryKey(_:)``
|
||||
- ``Database/schemaVersion()``
|
||||
- ``Database/table(_:hasUniqueKey:)``
|
||||
- ``Database/tableExists(_:)``
|
||||
- ``Database/triggerExists(_:)``
|
||||
- ``Database/viewExists(_:)``
|
||||
- ``ColumnInfo``
|
||||
- ``ForeignKeyInfo``
|
||||
- ``IndexInfo``
|
||||
- ``PrimaryKeyInfo``
|
||||
|
||||
### Integrity Checks
|
||||
|
||||
- ``Database/checkForeignKeys()``
|
||||
- ``Database/checkForeignKeys(in:)``
|
||||
- ``Database/foreignKeyViolations()``
|
||||
- ``Database/foreignKeyViolations(in:)``
|
||||
- ``ForeignKeyViolation``
|
||||
|
||||
### Sunsetted Methods
|
||||
|
||||
Those are legacy interfaces that are preserved for backwards compatibility. Their use is not recommended.
|
||||
|
||||
- ``Database/create(index:on:columns:unique:ifNotExists:condition:)``
|
||||
- ``Database/create(table:temporary:ifNotExists:withoutRowID:body:)``
|
||||
@@ -0,0 +1,251 @@
|
||||
# Sharing a Database
|
||||
|
||||
How to share an SQLite database between multiple processes • Recommendations for App Group containers, App Extensions, App Sandbox, and file coordination.
|
||||
|
||||
## Overview
|
||||
|
||||
**This guide describes a recommended setup that applies as soon as several processes want to access the same SQLite database.** It complements the <doc:Concurrency> guide, that you should read first.
|
||||
|
||||
On iOS for example, you can share database files between multiple processes by storing them in an [App Group Container](https://developer.apple.com/documentation/foundation/nsfilemanager/1412643-containerurlforsecurityapplicati). On macOS, several processes may want to open the same database, according to their particular sandboxing contexts.
|
||||
|
||||
Accessing a shared database from several SQLite connections, from several processes, creates challenges at various levels:
|
||||
|
||||
1. **Database setup** may be attempted by multiple processes, concurrently, with possible conflicts.
|
||||
2. **SQLite** may throw [`SQLITE_BUSY`] errors, "database is locked".
|
||||
3. **iOS** may kill your application with a [`0xDEAD10CC`] exception.
|
||||
4. **GRDB** <doc:DatabaseObservation> does not detect changes performed by external processes.
|
||||
|
||||
We'll address all of those challenges below.
|
||||
|
||||
> Important: Preventing errors that may happen due to database sharing is difficult. It is extremely difficult on iOS. And it is almost impossible to test.
|
||||
>
|
||||
> Always consider sharing plain files, or any other inter-process communication technique, before sharing an SQLite database.
|
||||
|
||||
## Use a Database Pool
|
||||
|
||||
In order to access a shared database, use a ``DatabasePool``. It opens the database in the [WAL mode], which helps sharing a database.
|
||||
|
||||
Since several processes may open the database at the same time, protect the creation of the database pool with an [NSFileCoordinator].
|
||||
|
||||
- In a process that can create and write in the database, use this sample code:
|
||||
|
||||
```swift
|
||||
/// Returns an initialized database pool at the shared location databaseURL
|
||||
func openSharedDatabase(at databaseURL: URL) throws -> DatabasePool {
|
||||
let coordinator = NSFileCoordinator(filePresenter: nil)
|
||||
var coordinatorError: NSError?
|
||||
var dbPool: DatabasePool?
|
||||
var dbError: Error?
|
||||
coordinator.coordinate(writingItemAt: databaseURL, options: .forMerging, error: &coordinatorError) { url in
|
||||
do {
|
||||
dbPool = try openDatabase(at: url)
|
||||
} catch {
|
||||
dbError = error
|
||||
}
|
||||
}
|
||||
if let error = dbError ?? coordinatorError {
|
||||
throw error
|
||||
}
|
||||
return dbPool!
|
||||
}
|
||||
|
||||
private func openDatabase(at databaseURL: URL) throws -> DatabasePool {
|
||||
var configuration = Configuration()
|
||||
configuration.prepareDatabase { db in
|
||||
// Activate the persistent WAL mode so that
|
||||
// read-only processes can access the database.
|
||||
//
|
||||
// See https://www.sqlite.org/walformat.html#operations_that_require_locks_and_which_locks_those_operations_use
|
||||
// and https://www.sqlite.org/c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntlpersistwal
|
||||
if db.configuration.readonly == false {
|
||||
var flag: CInt = 1
|
||||
let code = withUnsafeMutablePointer(to: &flag) { flagP in
|
||||
sqlite3_file_control(db.sqliteConnection, nil, SQLITE_FCNTL_PERSIST_WAL, flagP)
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: ResultCode(rawValue: code))
|
||||
}
|
||||
}
|
||||
}
|
||||
let dbPool = try DatabasePool(path: databaseURL.path, configuration: configuration)
|
||||
|
||||
// Perform here other database setups, such as defining
|
||||
// the database schema with a DatabaseMigrator, and
|
||||
// checking if the application can open the file:
|
||||
try migrator.migrate(dbPool)
|
||||
if try dbPool.read(migrator.hasBeenSuperseded) {
|
||||
// Database is too recent
|
||||
throw /* some error */
|
||||
}
|
||||
|
||||
return dbPool
|
||||
}
|
||||
```
|
||||
|
||||
- In a process that only reads in the database, use this sample code:
|
||||
|
||||
```swift
|
||||
/// Returns an initialized database pool at the shared location databaseURL,
|
||||
/// or nil if the database is not created yet, or does not have the required
|
||||
/// schema version.
|
||||
func openSharedReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
|
||||
let coordinator = NSFileCoordinator(filePresenter: nil)
|
||||
var coordinatorError: NSError?
|
||||
var dbPool: DatabasePool?
|
||||
var dbError: Error?
|
||||
coordinator.coordinate(readingItemAt: databaseURL, options: .withoutChanges, error: &coordinatorError) { url in
|
||||
do {
|
||||
dbPool = try openReadOnlyDatabase(at: url)
|
||||
} catch {
|
||||
dbError = error
|
||||
}
|
||||
}
|
||||
if let error = dbError ?? coordinatorError {
|
||||
throw error
|
||||
}
|
||||
return dbPool
|
||||
}
|
||||
|
||||
private func openReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
|
||||
do {
|
||||
var configuration = Configuration()
|
||||
configuration.readonly = true
|
||||
let dbPool = try DatabasePool(path: databaseURL.path, configuration: configuration)
|
||||
|
||||
// Check here if the database schema is the expected one,
|
||||
// for example with a DatabaseMigrator:
|
||||
return try dbPool.read { db in
|
||||
if try migrator.hasBeenSuperseded(db) {
|
||||
// Database is too recent
|
||||
return nil
|
||||
} else if try migrator.hasCompletedMigrations(db) == false {
|
||||
// Database is too old
|
||||
return nil
|
||||
}
|
||||
return dbPool
|
||||
}
|
||||
} catch {
|
||||
if FileManager.default.fileExists(atPath: databaseURL.path) {
|
||||
throw error
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
#### The Specific Case of Read-Only Connections
|
||||
|
||||
Read-only connections will fail unless two extra files ending in `-shm` and `-wal` are present next to the database file ([source](https://www.sqlite.org/walformat.html#operations_that_require_locks_and_which_locks_those_operations_use)). Those files are regular companions of databases in the [WAL mode]. But they are deleted, under regular operations, when database connections are closed. Precisely speaking, they *may* be deleted: it depends on the SQLite and the operating system versions ([source](https://github.com/groue/GRDB.swift/issues/739#issuecomment-604363998)). And when they are deleted, read-only connections fail.
|
||||
|
||||
The solution is to enable the "persistent WAL mode", as shown in the sample code above, by setting the [SQLITE_FCNTL_PERSIST_WAL](https://www.sqlite.org/c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntlpersistwal) flag. This mode makes sure the `-shm` and `-wal` files are never deleted, and guarantees a database access to read-only connections.
|
||||
|
||||
|
||||
## How to limit the SQLITE_BUSY error
|
||||
|
||||
> SQLite Documentation: The [`SQLITE_BUSY`] result code indicates that the database file could not be written (or in some cases read) because of concurrent activity by some other database connection, usually a database connection in a separate process.
|
||||
|
||||
If several processes want to write in the database, configure the database pool of each process that wants to write:
|
||||
|
||||
```swift
|
||||
var configuration = Configuration()
|
||||
configuration.busyMode = .timeout(/* a TimeInterval */)
|
||||
let dbPool = try DatabasePool(path: ..., configuration: configuration)
|
||||
```
|
||||
|
||||
With such a setup, you may still get `SQLITE_BUSY` errors from all write operations. They will occur if the database remains locked by another process for longer than the specified timeout. You can catch those errors:
|
||||
|
||||
```swift
|
||||
do {
|
||||
try dbPool.write { db in ... }
|
||||
} catch DatabaseError.SQLITE_BUSY {
|
||||
// Another process won't let you write. Deal with it.
|
||||
}
|
||||
```
|
||||
|
||||
## How to limit the 0xDEAD10CC exception
|
||||
|
||||
> Apple documentation: [`0xDEAD10CC`] (pronounced “dead lock”): the operating system terminated the app because it held on to a file lock or SQLite database lock during suspension.
|
||||
|
||||
#### If you use SQLCipher
|
||||
|
||||
Use SQLCipher 4+, and configure the database from ``Configuration/prepareDatabase(_:)``:
|
||||
|
||||
```swift
|
||||
var configuration = Configuration()
|
||||
configuration.prepareDatabase { (db: Database) in
|
||||
try db.usePassphrase("secret")
|
||||
try db.execute(sql: "PRAGMA cipher_plaintext_header_size = 32")
|
||||
}
|
||||
let dbPool = try DatabasePool(path: ..., configuration: configuration)
|
||||
```
|
||||
|
||||
Applications become responsible for managing the salt themselves: see [instructions](https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_plaintext_header_size). See also <https://github.com/sqlcipher/sqlcipher/issues/255> for more context and information.
|
||||
|
||||
#### In all cases
|
||||
|
||||
The technique described below is based on [this discussion](https://developer.apple.com/forums/thread/126438) on the Apple Developer Forums. It is [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features).
|
||||
|
||||
In each process that writes in the database, set the ``Configuration/observesSuspensionNotifications`` configuration flag:
|
||||
|
||||
```swift
|
||||
var configuration = Configuration()
|
||||
configuration.observesSuspensionNotifications = true
|
||||
let dbPool = try DatabasePool(path: ..., configuration: configuration)
|
||||
```
|
||||
|
||||
Post ``Database/suspendNotification`` when the application is about to be [suspended](https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle). You can for example post this notification from `UIApplicationDelegate.applicationDidEnterBackground(_:)`, or in the expiration handler of a [background task](https://forums.developer.apple.com/thread/85066):
|
||||
|
||||
```swift
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
func applicationDidEnterBackground(_ application: UIApplication) {
|
||||
NotificationCenter.default.post(name: Database.suspendNotification, object: self)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Once suspended, a database won't acquire any new lock that could cause the `0xDEAD10CC` exception.
|
||||
|
||||
In exchange, you will get `SQLITE_INTERRUPT` (code 9) or `SQLITE_ABORT` (code 4) errors, with messages "Database is suspended", "Transaction was aborted", or "interrupted". You can catch those errors:
|
||||
|
||||
```swift
|
||||
do {
|
||||
try dbPool.write { db in ... }
|
||||
} catch DatabaseError.SQLITE_INTERRUPT, DatabaseError.SQLITE_ABORT {
|
||||
// Oops, the database is suspended.
|
||||
// Maybe try again after database is resumed?
|
||||
}
|
||||
```
|
||||
|
||||
Post ``Database/resumeNotification`` in order to resume suspended databases. You can safely post this notification when the app comes back to foreground.
|
||||
|
||||
In applications that use the background modes supported by iOS, post `resumeNotification` method from each and every background mode callback that may use the database, and don't forget to post `suspendNotification` again before the app turns suspended.
|
||||
|
||||
## How to perform cross-process database observation
|
||||
|
||||
<doc:DatabaseObservation> features are not able to detect database changes performed by other processes.
|
||||
|
||||
Whenever you need to notify other processes that the database has been changed, you will have to use a cross-process notification mechanism such as [NSFileCoordinator] or [CFNotificationCenterGetDarwinNotifyCenter].
|
||||
|
||||
You can trigger those notifications automatically with ``DatabaseRegionObservation``:
|
||||
|
||||
```swift
|
||||
// Notify all changes made to the database
|
||||
let observation = DatabaseRegionObservation(tracking: .fullDatabase)
|
||||
let observer = try observation.start(in: dbPool) { db in
|
||||
// Notify other processes
|
||||
}
|
||||
|
||||
// Notify changes made to the "player" and "team" tables only
|
||||
let observation = DatabaseRegionObservation(tracking: Player.all(), Team.all())
|
||||
let observer = try observation.start(in: dbPool) { db in
|
||||
// Notify other processes
|
||||
}
|
||||
```
|
||||
|
||||
[NSFileCoordinator]: https://developer.apple.com/documentation/foundation/nsfilecoordinator
|
||||
[CFNotificationCenterGetDarwinNotifyCenter]: https://developer.apple.com/documentation/corefoundation/1542572-cfnotificationcentergetdarwinnot
|
||||
[WAL mode]: https://www.sqlite.org/wal.html
|
||||
[`SQLITE_BUSY`]: https://www.sqlite.org/rescode.html#busy
|
||||
[`0xDEAD10CC`]: https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report
|
||||
@@ -0,0 +1,47 @@
|
||||
# ``GRDB``
|
||||
|
||||
A toolkit for SQLite databases, with a focus on application development
|
||||
|
||||
## Overview
|
||||
|
||||
Use GRDB to save your application’s permanent data into SQLite databases.
|
||||
|
||||
The library provides raw access to SQL and advanced SQLite features, because one sometimes enjoys a sharp tool.
|
||||
|
||||
It has robust concurrency primitives, so that multi-threaded applications can efficiently use their databases.
|
||||
|
||||
It grants your application models with persistence and fetching methods, so that you don't have to deal with SQL and raw database rows when you don't want to.
|
||||
|
||||
Compared to [SQLite.swift](https://github.com/stephencelis/SQLite.swift) or [FMDB](https://github.com/ccgus/fmdb), GRDB can spare you a lot of glue code. Compared to [Core Data](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/) or [Realm](http://realm.io), it can simplify your multi-threaded applications.
|
||||
|
||||
## Topics
|
||||
|
||||
### Fundamentals
|
||||
|
||||
- <doc:DatabaseConnections>
|
||||
- <doc:SQLSupport>
|
||||
- <doc:Concurrency>
|
||||
- <doc:Transactions>
|
||||
|
||||
### Migrations and The Database Schema
|
||||
|
||||
- <doc:DatabaseSchema>
|
||||
- <doc:Migrations>
|
||||
- <doc:SingleRowTables>
|
||||
|
||||
### Records and the Query Interface
|
||||
|
||||
- <doc:QueryInterface>
|
||||
- <doc:RecordTimestamps>
|
||||
|
||||
### Responding to Database Changes
|
||||
|
||||
- <doc:DatabaseObservation>
|
||||
|
||||
### Full-Text Search
|
||||
|
||||
- <doc:FullTextSearch>
|
||||
|
||||
### Combine Publishers
|
||||
|
||||
- ``DatabasePublishers``
|
||||
Loaded 100 of 340 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user