mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-06 05:28:44 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ef07897ba4 | ||
|
|
dd7e7f39e8 | ||
|
|
8801adb21c | ||
|
|
f721af86cd | ||
|
|
23f4254ae3 | ||
|
|
2df6a17c1c | ||
|
|
5aeee0e429 | ||
|
|
3a61a8a0e0 | ||
|
|
e0766449f1 | ||
|
|
c1e752132c | ||
|
|
6ab90a03c4 | ||
|
|
23fa42a3e4 | ||
|
|
07eaeee123 | ||
|
|
0bfb4de02d | ||
|
|
d72b7109ad | ||
|
|
e1a63a4c05 | ||
|
|
caab403282 | ||
|
|
bbe94a9607 | ||
|
|
84bee1977e | ||
|
|
0aa561e61c | ||
|
|
b1b51c01f8 | ||
|
|
cc5196757d | ||
|
|
0e9766373d | ||
|
|
aacaa433c9 | ||
|
|
44ec3535c2 | ||
|
|
38c0d68db7 | ||
|
|
f3cc4add9f | ||
|
|
432670e13a | ||
|
|
3ba13b0af6 | ||
|
|
1a6228e2c5 | ||
|
|
e02f2c8aba | ||
|
|
c0e9c8746d | ||
|
|
d1cba5e5c8 | ||
|
|
bf824bf68c | ||
|
|
5e5b44aa7f | ||
|
|
806919b5be | ||
|
|
a289aecc3c | ||
|
|
3f7adec072 | ||
|
|
c9f3a1e17f | ||
|
|
cf2a79e12f | ||
|
|
a0212eb129 | ||
|
|
d5470b7278 | ||
|
|
cd6960f5e9 | ||
|
|
f72859b5b2 | ||
|
|
b947065d25 | ||
|
|
11f95806c4 | ||
|
|
2ac5c77353 | ||
|
|
2a849d380c | ||
|
|
fd31632203 | ||
|
|
4a98a53dad | ||
|
|
952ee0a137 | ||
|
|
ee92db9d6f | ||
|
|
de4266499c | ||
|
|
4b7a9bbe7b | ||
|
|
184d5aa4af | ||
|
|
6c48e492d1 | ||
|
|
26fedd2702 | ||
|
|
06216fd875 | ||
|
|
42050e5e28 | ||
|
|
9ed309b470 | ||
|
|
00d1a80b31 | ||
|
|
aaf3efe6df | ||
|
|
d8f2989542 | ||
|
|
28543109ea | ||
|
|
63c2bd0876 | ||
|
|
59bd10b1b5 | ||
|
|
758f561fbf | ||
|
|
40b0e98eb5 | ||
|
|
2ec0a4c69d | ||
|
|
ca43f1e803 | ||
|
|
0a7e7d1e5c | ||
|
|
1260980150 | ||
|
|
f0cfde682e | ||
|
|
096a3b2f0f | ||
|
|
f313a43ef9 | ||
|
|
fead2ea634 | ||
|
|
5b254eec16 | ||
|
|
3632edb238 | ||
|
|
752415b5fb | ||
|
|
f17a786165 | ||
|
|
b89ce00361 | ||
|
|
c5eba4741d | ||
|
|
fb18a3938f | ||
|
|
5082207bb0 | ||
|
|
06b5367053 | ||
|
|
819ee588c9 | ||
|
|
1b3f1ed393 | ||
|
|
f0fe7e86ca | ||
|
|
dd5ce280b5 | ||
|
|
744aa825a3 | ||
|
|
24f3de9dfa | ||
|
|
4472d3a60e | ||
|
|
dc03adb4e2 | ||
|
|
dea9bedacb | ||
|
|
83d243853b | ||
|
|
209192d3a5 | ||
|
|
15c06e0374 | ||
|
|
0324f592dc | ||
|
|
051787b17f | ||
|
|
feebc07101 | ||
|
|
80c15c6ef6 | ||
|
|
9014b3ebd0 | ||
|
|
bec58a32d4 | ||
|
|
b66374670c | ||
|
|
f3992a034d | ||
|
|
8b120fa9b6 | ||
|
|
8b58ec4cee | ||
|
|
9b7b603a69 | ||
|
|
a3a26bf88f | ||
|
|
770484b78d | ||
|
|
fafa74c246 | ||
|
|
62450b5817 | ||
|
|
e9b8df68ee | ||
|
|
9fa831b6bb | ||
|
|
43e1871005 | ||
|
|
8a6e784428 | ||
|
|
727ca68b98 | ||
|
|
fb3e08aba8 | ||
|
|
1c614e8de6 | ||
|
|
3f0a8e6730 | ||
|
|
6916a8feca | ||
|
|
e08dfdb0bf | ||
|
|
6236b8a068 | ||
|
|
55dea6f9d2 | ||
|
|
cdb08988f4 | ||
|
|
881bbd3f0d | ||
|
|
6ab3fea8fb | ||
|
|
287ceb8b07 | ||
|
|
4eefb9afbe | ||
|
|
4ea04ec978 | ||
|
|
c30b49117b | ||
|
|
ec975819b7 | ||
|
|
b974dfa9a7 | ||
|
|
e19f21be99 | ||
|
|
9b0e41ad58 | ||
|
|
d40474d2b7 | ||
|
|
685074932e | ||
|
|
f1a23bacc0 | ||
|
|
fbef103f01 | ||
|
|
fc9f0bcad1 | ||
|
|
1929e96d11 | ||
|
|
9d4eb8a6dd | ||
|
|
3914a9ec21 | ||
|
|
29bacc138c | ||
|
|
ba866359b2 | ||
|
|
ffced55d3c | ||
|
|
74caa96dcb | ||
|
|
f6bea21e80 | ||
|
|
27f6125099 | ||
|
|
70ea2027e4 | ||
|
|
e28658c574 | ||
|
|
c184b76849 | ||
|
|
d23d74f65f | ||
|
|
984a5b4c4c | ||
|
|
8e84beee36 | ||
|
|
95ce4a3f8a | ||
|
|
98ca653c6a | ||
|
|
e5a8e130d7 | ||
|
|
72e8dd2816 | ||
|
|
b5338650db | ||
|
|
75f72472ff | ||
|
|
09f7d4d952 | ||
|
|
c1c3cf6605 | ||
|
|
fc7f24ef6e | ||
|
|
3d0b34590f | ||
|
|
2d6c2873e0 | ||
|
|
4e65425c00 | ||
|
|
b82f92f726 | ||
|
|
b8c0e9d2c2 | ||
|
|
b2df255306 | ||
|
|
c60b8cfc53 | ||
|
|
9dc6fbd7f9 | ||
|
|
9a4e1f7806 | ||
|
|
5dde1409ad | ||
|
|
936fd3ed5f | ||
|
|
ed4471c5b9 | ||
|
|
dd025a14e4 | ||
|
|
29808e51ff | ||
|
|
426044154c | ||
|
|
d69db0b9a1 | ||
|
|
914bd14cd1 | ||
|
|
b5395a097c | ||
|
|
99c596f778 | ||
|
|
fd22fac5c0 | ||
|
|
6e3a15ebed | ||
|
|
bb8b39f7fd | ||
|
|
fc5138ae91 | ||
|
|
d3985c7ebf | ||
|
|
9f0ba49c93 | ||
|
|
09922c34ff | ||
|
|
3826003d93 | ||
|
|
9baa72cfd7 | ||
|
|
aacc69f485 | ||
|
|
301fb34702 | ||
|
|
6444285ee2 | ||
|
|
bd42dc69f0 |
No files matched your search
@@ -1,5 +0,0 @@
|
||||
source 'https://rubygems.org'
|
||||
|
||||
gem 'xcpretty'
|
||||
gem 'xcpretty-travis-formatter'
|
||||
gem 'cocoapods', '~> 1.7'
|
||||
@@ -0,0 +1,6 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
+165
-12
@@ -1,19 +1,172 @@
|
||||
name: CI
|
||||
name: "GRDB CI"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master, development ]
|
||||
branches:
|
||||
- master
|
||||
- development
|
||||
- GRDB5
|
||||
paths:
|
||||
- 'GRDB/**'
|
||||
- 'Tests/**'
|
||||
- '.github/workflows/**'
|
||||
- 'Package.swift'
|
||||
pull_request:
|
||||
branches: [ master, development ]
|
||||
paths:
|
||||
- 'GRDB/**'
|
||||
- 'Tests/**'
|
||||
- '.github/workflows/**'
|
||||
- 'Package.swift'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.ref_name }}
|
||||
cancel-in-progress: true
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
runs-on: macos-latest
|
||||
|
||||
macOS:
|
||||
name: macOS
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_13.2.1.app"
|
||||
runsOn: macOS-11
|
||||
name: "macOS 11, Xcode 13.2.1, Swift 5.5.2"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_13.1.app"
|
||||
runsOn: macOS-11
|
||||
name: "macOS 11, Xcode 13.1, Swift 5.5.1"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_13.0.app"
|
||||
runsOn: macOS-11
|
||||
name: "macOS 11, Xcode 13.0, Swift 5.5.0"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.5.1.app"
|
||||
runsOn: macOS-11
|
||||
name: "macOS 11, Xcode 12.5.1, Swift 5.4"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.4.app"
|
||||
runsOn: macOS-10.15
|
||||
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Build
|
||||
run: swift build -v
|
||||
- name: Run tests
|
||||
run: swift test -v
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_GRDBOSX_maxSwift
|
||||
iOS:
|
||||
name: iOS
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.4.app"
|
||||
runsOn: macOS-10.15
|
||||
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
SPM:
|
||||
name: SPM
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_SPM test_install_SPM
|
||||
SQLCipher3:
|
||||
name: SQLCipher3
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_SQLCipher3Encrypted
|
||||
SQLCipher4:
|
||||
name: SQLCipher4
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.4.app"
|
||||
runsOn: macOS-10.15
|
||||
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_SQLCipher4Encrypted
|
||||
CustomSQLite:
|
||||
name: CustomSQLite
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.4.app"
|
||||
runsOn: macOS-10.15
|
||||
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_GRDBCustomSQLiteOSX
|
||||
XCFramework:
|
||||
name: XCFramework
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_archive_GRDBOSX_xcframework
|
||||
|
||||
+115
-24
@@ -7,6 +7,14 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 5.x Releases
|
||||
|
||||
- `5.26.x` Releases - [5.26.0](#5260) | [5.26.1](#5261)
|
||||
- `5.25.x` Releases - [5.25.0](#5250)
|
||||
- `5.24.x` Releases - [5.24.0](#5240) | [5.24.1](#5241)
|
||||
- `5.23.x` Releases - [5.23.0](#5230)
|
||||
- `5.22.x` Releases - [5.22.0](#5220) | [5.22.1](#5221) | [5.22.2](#5222)
|
||||
- `5.21.x` Releases - [5.21.0](#5210)
|
||||
- `5.20.x` Releases - [5.20.0](#5200)
|
||||
- `5.19.x` Releases - [5.19.0](#5190)
|
||||
- `5.18.x` Releases - [5.18.0](#5180)
|
||||
- `5.17.x` Releases - [5.17.0](#5170)
|
||||
- `5.16.x` Releases - [5.16.0](#5160)
|
||||
@@ -85,6 +93,89 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 5.26.1
|
||||
|
||||
Released September 8, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.26.0...v5.26.1)
|
||||
|
||||
- **Fixed**: [#1276](https://github.com/groue/GRDB.swift/pull/1276) Fix build error with Xcode 14.0 RC (14A309)
|
||||
|
||||
## 5.26.0
|
||||
|
||||
Released July 9, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.25.0...v5.26.0)
|
||||
|
||||
- **New**: [#1248](https://github.com/groue/GRDB.swift/pull/1248) by [@groue](https://github.com/groue): Avoid double notification of the initial value for ValueObservation on DatabasePool
|
||||
- **New**: [#1253](https://github.com/groue/GRDB.swift/pull/1253) by [@george-signal](https://github.com/george-signal): Make memory management optional
|
||||
- **Fixed**: DatabasePool no longer prevents database reads when UIKit posts `UIApplication.didReceiveMemoryWarningNotification` (see [#1253](https://github.com/groue/GRDB.swift/pull/1253) for more information).
|
||||
|
||||
## 5.25.0
|
||||
|
||||
Released June 11, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.24.1...v5.25.0)
|
||||
|
||||
- **New**: [#1226](https://github.com/groue/GRDB.swift/pull/1226) by [@naveensrinivasan](https://github.com/naveensrinivasan): Included githubactions in the dependabot config
|
||||
- **New**: [#1228](https://github.com/groue/GRDB.swift/pull/1228) by [@naveensrinivasan](https://github.com/naveensrinivasan): Set permissions for GitHub actions
|
||||
- **New**: [#1235](https://github.com/groue/GRDB.swift/pull/1235) by [@groue](https://github.com/groue): Raise default Quality of Service to `.userInitiated`.
|
||||
- **Fixed**: [#1233](https://github.com/groue/GRDB.swift/pull/1233) by [@GetToSet](https://github.com/GetToSet): Fix warnings of redundant conformance constraint on Xcode 14.
|
||||
|
||||
## 5.24.1
|
||||
|
||||
Released May 26, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.24.0...v5.24.1)
|
||||
|
||||
- **Fixed**: [#1217](https://github.com/groue/GRDB.swift/pull/1217) by [@GetToSet](https://github.com/GetToSet): Fix doc issue on TableRequest.filter(keys:).
|
||||
- **Fixed**: [#1225](https://github.com/groue/GRDB.swift/pull/1225) by [@groue](https://github.com/groue): Prevent heavy DatabasePool concurrent reads from creating too many threads
|
||||
|
||||
## 5.24.0
|
||||
|
||||
Released May 1, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.23.0...v5.24.0)
|
||||
|
||||
- **Fixed**: [#1203](https://github.com/groue/GRDB.swift/pull/1203) by [@EvanHahn](https://github.com/EvanHahn): Fix changelog links
|
||||
- **Fixed**: [#1212](https://github.com/groue/GRDB.swift/pull/1212) by [@MartinP7r](https://github.com/MartinP7r): Fix apple docs links
|
||||
- **Fixed**: [#1213](https://github.com/groue/GRDB.swift/pull/1213) by [@groue](https://github.com/groue): Fix crash when the number of active ValueObservations is high
|
||||
- **Breaking Change**: Transactions performed during a read-only database access are no longer notified to transaction observers. This is, strictly speaking, a breaking change. However it should have no impact since read-only transactions have very little interest.
|
||||
|
||||
## 5.23.0
|
||||
|
||||
Released April 16, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.22.2...v5.23.0)
|
||||
|
||||
- **Breaking Change**: [#1200](https://github.com/groue/GRDB.swift/pull/1200) by [@groue](https://github.com/groue): Require Swift 5.6 Compiler for experimental Concurrency Support
|
||||
|
||||
## 5.22.2
|
||||
|
||||
Released April 2, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.22.1...v5.22.2)
|
||||
|
||||
- **Fixed** a 5.22.0 regression: [#1196](https://github.com/groue/GRDB.swift/pull/1196) by [@layoutSubviews](https://github.com/layoutSubviews): Fix a crash when an observation is quickly cancelled
|
||||
|
||||
## 5.22.1
|
||||
|
||||
Released March 26, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.22.0...v5.22.1)
|
||||
|
||||
- **Fixed** a 5.22.0 regression: [#1194](https://github.com/groue/GRDB.swift/issues/1194) ValueObservation could deadlock when the database is configured with a serial target DispatchQueue.
|
||||
|
||||
## 5.22.0
|
||||
|
||||
Released March 22, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.21.0...v5.22.0)
|
||||
|
||||
- **New**: [#1186](https://github.com/groue/GRDB.swift/pull/1186) by [@benrb](https://github.com/benrb): DatabaseError provide error message as localizedFailureReason
|
||||
- **Breaking Change**: [#1183](https://github.com/groue/GRDB.swift/pull/1183) by [@groue](https://github.com/groue): Starting a ValueObservation keeps a strong reference on the database connection.
|
||||
|
||||
## 5.21.0
|
||||
|
||||
Released February 6, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.20.0...v5.21.0)
|
||||
|
||||
- **New**: [#1165](https://github.com/groue/GRDB.swift/pull/1165) by [@guidedways](https://github.com/guidedways): Support dynamic linking via Swift Package Manager
|
||||
- **Breaking Change**: [#1164](https://github.com/groue/GRDB.swift/pull/1164) by [@groue](https://github.com/groue): Drop experimental async apis from DatabaseMigrator
|
||||
|
||||
|
||||
## 5.20.0
|
||||
|
||||
Released February 1, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.19.0...v5.20.0)
|
||||
|
||||
- **Fixed**: Fixed a bug of `including(all:)` for composite foreign keys and limited requests.
|
||||
- **Fixed**: [#1162](https://github.com/groue/GRDB.swift/pull/1162) by [@groue](https://github.com/groue): Fix truncate optimization handling.
|
||||
- **New**: [#1160](https://github.com/groue/GRDB.swift/pull/1160) by [@groue](https://github.com/groue): Hide statement arguments by default.
|
||||
- **New**: [#1161](https://github.com/groue/GRDB.swift/pull/1161) by [@groue](https://github.com/groue): Target DispatchQueue for non-read-only database connections.
|
||||
- **Documentation Update**: The [Database Configuration](README.md#database-configuration) chapter explains how to opt in for public statement arguments in DEBUG builds.
|
||||
|
||||
|
||||
## 5.19.0
|
||||
|
||||
Released January 19, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.18.0...v5.19.0)
|
||||
@@ -607,7 +698,7 @@ Released May 2, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v
|
||||
|
||||
GRDB 5 is a release focused on **Swift 5.2**, and **removing technical debt**.
|
||||
|
||||
There are breaking changes, though as few as possible. They open the door for future library improvements. And they have GRDB, [GRDBCombine](http://github.com/groue/GRDBCombine), and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) offer a common behavior.
|
||||
There are breaking changes, though as few as possible. They open the door for future library improvements. And they have GRDB, [GRDBCombine](https://github.com/groue/GRDBCombine), and [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB) offer a common behavior.
|
||||
|
||||
New features include support for SQL subqueries, and a simplified handling of database errors. The most demanding users will also find it easier to switch between the system SQLite, SQLCipher, and custom SQLite builds.
|
||||
|
||||
@@ -2325,7 +2416,7 @@ It comes with new features, but also a few breaking changes, and a set of update
|
||||
- `DatabaseMigrator.appliedMigrations(in:)` returns the set of applied migrations identifiers in a database ([#321](https://github.com/groue/GRDB.swift/pull/321)).
|
||||
- `Database.isSQLiteInternalTable(_:)` returns whether a table name is an internal SQLite table ([#321](https://github.com/groue/GRDB.swift/pull/321)).
|
||||
- `Database.isGRDBInternalTable(_:)` returns whether a table name is an internal GRDB table ([#321](https://github.com/groue/GRDB.swift/pull/321)).
|
||||
- Upgrade custom SQLite builds to [v3.23.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Upgrade custom SQLite builds to [v3.23.0](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Improve Row descriptions ([#331](https://github.com/groue/GRDB.swift/pull/331)).
|
||||
- Request derivation protocols ([#329](https://github.com/groue/GRDB.swift/pull/329)).
|
||||
- Preliminary Linux support for the main framework ([#354](https://github.com/groue/GRDB.swift/pull/354)).
|
||||
@@ -2510,7 +2601,7 @@ Released January 29, 2018 • [diff](https://github.com/groue/GRDB.swift/comp
|
||||
|
||||
**New**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.22.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Upgrade custom SQLite builds to [v3.22.0](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- The FTS5 full-text search engine has been enhanced with [initial token queries](https://sqlite.org/fts5.html#carrotq), and FTS5Pattern has gained a new initializer: `FTS5Pattern(matchingPrefixPhrase:)`
|
||||
- The `Cursor` protocol is extended with more methods inspired by the standard Sequence protocol: `drop(while:)`, `dropFirst()`, `dropFirst(_:)`, `dropLast()`, `dropLast(_:)`, `joined(separator:)`, `prefix(_:)`, `max()`, `max(by:)`, `min()`, `min(by:)`, `prefix(while:)`, `reduce(into:_:)`, `suffix(_:)`,
|
||||
|
||||
@@ -2564,7 +2655,7 @@ Released January 18, 2018 • [diff](https://github.com/groue/GRDB.swift/comp
|
||||
- `TransactionObserver.stopObservingDatabaseChangesUntilNextTransaction()` allows transaction observers to stop observing the database for the remaining extent of a transaction.
|
||||
- GRDB no longer prevents the [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt) when no transaction observers are interested in deleted rows.
|
||||
- FetchedRecordsController now avoids checking for changes in untracked rowIds.
|
||||
- `DatabaseRegion` is a new public type that helps transaction observers recognize impactful database changes. This type is not documented in the main documentation. For more information, see [DatabaseRegion reference](http://groue.github.io/GRDB.swift/docs/2.6/Structs/DatabaseRegion.html), and look at [FetchedRecordsController implementation](https://github.com/groue/GRDB.swift/blob/master/GRDB/Record/FetchedRecordsController.swift).
|
||||
- `DatabaseRegion` is a new public type that helps transaction observers recognize impactful database changes. This type is not documented in the main documentation. For more information, see [DatabaseRegion reference](https://groue.github.io/GRDB.swift/docs/2.6/Structs/DatabaseRegion.html), and look at [FetchedRecordsController implementation](https://github.com/groue/GRDB.swift/blob/master/GRDB/Record/FetchedRecordsController.swift).
|
||||
- `TransactionObserver` protocol provides default implementations for rarely used callbacks.
|
||||
|
||||
- `Row` adopts RandomAccessCollection
|
||||
@@ -2651,7 +2742,7 @@ Released January 11, 2018 • [diff](https://github.com/groue/GRDB.swift/comp
|
||||
let player = try request.fetchOne(db) // Player?
|
||||
```
|
||||
|
||||
This feature has been introduced in order to ease the use of [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB):
|
||||
This feature has been introduced in order to ease the use of [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB):
|
||||
|
||||
```swift
|
||||
// New
|
||||
@@ -2720,7 +2811,7 @@ Released December 3, 2017 • [diff](https://github.com/groue/GRDB.swift/comp
|
||||
}
|
||||
```
|
||||
|
||||
- [#281](https://github.com/groue/GRDB.swift/pull/280): The `Database.dropFTS4SynchronizationTriggers` & `Database.dropFTS5SynchronizationTriggers` method help cleaning up synchronized full-text table ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#deleting-synchronized-full-text-tables))
|
||||
- [#281](https://github.com/groue/GRDB.swift/pull/281): The `Database.dropFTS4SynchronizationTriggers` & `Database.dropFTS5SynchronizationTriggers` method help cleaning up synchronized full-text table ([documentation](https://github.com/groue/GRDB.swift/blob/master/README.md#deleting-synchronized-full-text-tables))
|
||||
|
||||
**Breaking Change**
|
||||
|
||||
@@ -2751,7 +2842,7 @@ Released November 5, 2017 • [diff](https://github.com/groue/GRDB.swift/comp
|
||||
|
||||
**New**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.21.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Upgrade custom SQLite builds to [v3.21.0](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
|
||||
|
||||
## 2.2.0
|
||||
@@ -2784,7 +2875,7 @@ Released October 24, 2017 • [diff](https://github.com/groue/GRDB.swift/comp
|
||||
### New
|
||||
|
||||
- GRDBCipher can now build from command line ([groue/sqlcipher/pull/1](https://github.com/groue/sqlcipher/pull/1) by [Darren Clark](https://github.com/darrenclark))
|
||||
- Upgrade custom SQLite builds to [v3.20.1](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Upgrade custom SQLite builds to [v3.20.1](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- The new method `Request.asSQLRequest` allows to inspect the sql and arguments of any request:
|
||||
|
||||
```swift
|
||||
@@ -2928,7 +3019,7 @@ Released September 16, 2017 • [diff](https://github.com/groue/GRDB.swift/co
|
||||
|
||||
### New
|
||||
|
||||
New features have been added in order to plug a few holes and support the [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) and [GRDBObjc](http://github.com/groue/GRDBObjc) companion projects:
|
||||
New features have been added in order to plug a few holes and support the [RxGRDB](https://github.com/RxSwiftCommunity/RxGRDB) and [GRDBObjc](https://github.com/groue/GRDBObjc) companion projects:
|
||||
|
||||
- Persistable records can export themselves as dictionaries:
|
||||
|
||||
@@ -3191,7 +3282,7 @@ Released August 18, 2017 • [diff](https://github.com/groue/GRDB.swift/compa
|
||||
|
||||
**New**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.20.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Upgrade custom SQLite builds to [v3.20.0](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Complete support for all signed and unsigned integer types: from Int8 toUInt64, all integers can be stored and loaded from the database.
|
||||
|
||||
**API diff**
|
||||
@@ -3222,7 +3313,7 @@ Released July 19, 2017 • [diff](https://github.com/groue/GRDB.swift/compare
|
||||
|
||||
**Fixed**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.19.3](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Upgrade custom SQLite builds to [v3.19.3](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- The [Query Interface](https://github.com/groue/GRDB.swift/#the-query-interface) now generates `IS NULL` SQL snippets for comparisons with `DatabaseValue.null`:
|
||||
|
||||
```swift
|
||||
@@ -3536,7 +3627,7 @@ Released May 28, 2017
|
||||
|
||||
**New**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.19.2](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Upgrade custom SQLite builds to [v3.19.2](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Upgrade SQLCipher to v3.4.1 ([announcement](https://discuss.zetetic.net/t/sqlcipher-3-4-1-release/1962), [changelog](https://github.com/sqlcipher/sqlcipher/blob/master/CHANGELOG.md))
|
||||
- A [large test suite](https://travis-ci.org/groue/GRDB.swift) that runs on Travis-CI, thanks to [@swiftlyfalling](https://github.com/swiftlyfalling) in [PR #213](https://github.com/groue/GRDB.swift/pull/213)
|
||||
|
||||
@@ -3626,7 +3717,7 @@ Released April 6, 2017
|
||||
|
||||
**New**
|
||||
|
||||
- `DatabaseWriter.availableDatabaseConnection` allows reentrant uses of GRDB, and improves support for [reactive](http://reactivex.io) programming.
|
||||
- `DatabaseWriter.availableDatabaseConnection` allows reentrant uses of GRDB, and improves support for [reactive](https://reactivex.io) programming.
|
||||
|
||||
|
||||
**Breaking Changes**
|
||||
@@ -3641,8 +3732,8 @@ Released April 3, 2017
|
||||
**New**
|
||||
|
||||
- Support for Xcode 8.3 and Swift 3.1 (Xcode 8.1 and Swift 3 are still supported).
|
||||
- Upgrade custom SQLite builds to [v3.18.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Support for [reactive](http://reactivex.io) extensions:
|
||||
- Upgrade custom SQLite builds to [v3.18.0](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Support for [reactive](https://reactivex.io) extensions:
|
||||
- `SelectStatement.SelectionInfo` is an opaque value that knows which database tables and columns are read by a [select statement](https://github.com/groue/GRDB.swift#prepared-statements).
|
||||
- `DatabaseEventKind.impacts(_ selectionInfo:SelectStatement.SelectionInfo)` tells whether a database change has any impact on the results of a select statement. See [Database Changes Observation](https://github.com/groue/GRDB.swift#database-changes-observation)
|
||||
- `TableMapping.primaryKeyRowComparator(_ db: Database)` returns a function that compares two database rows and return true if and only if they have the same non-null primary key.
|
||||
@@ -3736,7 +3827,7 @@ Released January 10, 2017
|
||||
|
||||
- `Row` adopts the Hashable protocol
|
||||
- [FetchedRecordsController](https://github.com/groue/GRDB.swift#fetchedrecordscontroller) now outputs request changes on all platforms, for both table and collection views. Merged [#160](https://github.com/groue/GRDB.swift/pull/160) by [@kdubb](https://github.com/kdubb).
|
||||
- Upgrade custom SQLite builds to [v3.16.2](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Upgrade custom SQLite builds to [v3.16.2](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
|
||||
**Breaking Changes**
|
||||
|
||||
@@ -3902,7 +3993,7 @@ Released December 4, 2016
|
||||
|
||||
**New**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.15.2](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Upgrade custom SQLite builds to [v3.15.2](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
|
||||
|
||||
## 0.92.1
|
||||
@@ -4139,7 +4230,7 @@ Released November 5, 2016
|
||||
|
||||
**New**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.15.1](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Upgrade custom SQLite builds to [v3.15.1](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
|
||||
**Fixed**
|
||||
|
||||
@@ -4227,7 +4318,7 @@ Released October 16, 2016
|
||||
}
|
||||
```
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.15.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Upgrade custom SQLite builds to [v3.15.0](https://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
|
||||
|
||||
**Breaking Change**
|
||||
@@ -4280,7 +4371,7 @@ Released October 8, 2016
|
||||
try Book.deleteOne(db, key: 1)
|
||||
```
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.14.2](http://www.sqlite.org/changes.html).
|
||||
- Upgrade custom SQLite builds to [v3.14.2](https://www.sqlite.org/changes.html).
|
||||
|
||||
**Breaking Changes**
|
||||
|
||||
@@ -4329,7 +4420,7 @@ Released September 16, 2016
|
||||
|
||||
**New**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.14.1](http://www.sqlite.org/changes.html).
|
||||
- Upgrade custom SQLite builds to [v3.14.1](https://www.sqlite.org/changes.html).
|
||||
|
||||
**Fixed**
|
||||
|
||||
@@ -5416,7 +5507,7 @@ Released April 5, 2016
|
||||
|
||||
**New**
|
||||
|
||||
- The new framework GRDBCipher embeds [SQLCipher](http://sqlcipher.net) and can encrypt databases ([documentation](https://github.com/groue/GRDB.swift#encryption))
|
||||
- The new framework GRDBCipher embeds [SQLCipher](https://www.zetetic.net/sqlcipher/) and can encrypt databases ([documentation](https://github.com/groue/GRDB.swift#encryption))
|
||||
- `DatabaseQueue.path` and `DatabasePool.path` give the path to the database.
|
||||
|
||||
**Fixed**
|
||||
@@ -6366,11 +6457,11 @@ Released August 18, 2015
|
||||
|
||||
- `RowModel.exists(db)` returns whether a row model has a matching row in the database.
|
||||
- `Statement.arguments` property gains a public setter.
|
||||
- `Database.executeMultiStatement(sql)` can execute several SQL statements separated by a semi-colon ([#6](http://github.com/groue/GRDB.swift/pull/6) by [peter-ss](https://github.com/peter-ss))
|
||||
- `Database.executeMultiStatement(sql)` can execute several SQL statements separated by a semi-colon ([#6](https://github.com/groue/GRDB.swift/pull/6) by [peter-ss](https://github.com/peter-ss))
|
||||
|
||||
**Breaking changes**
|
||||
|
||||
- `UpdateStatement.Changes` has been renamed `DatabaseChanges` ([#6](http://github.com/groue/GRDB.swift/pull/6) by [peter-ss](https://github.com/peter-ss)).
|
||||
- `UpdateStatement.Changes` has been renamed `DatabaseChanges` ([#6](https://github.com/groue/GRDB.swift/pull/6) by [peter-ss](https://github.com/peter-ss)).
|
||||
|
||||
|
||||
## 0.7.0
|
||||
|
||||
@@ -1510,7 +1510,7 @@ let sortedAuthor = Book.author.order(Column("name"))
|
||||
let request = Book.including(required: sortedAuthor)
|
||||
```
|
||||
|
||||
When you sort both the base record on the associated record, the request is sorted on the base record first, and on the associated record next:
|
||||
When you sort both the base record and the associated record, the request is sorted on the base record first, and on the associated record next:
|
||||
|
||||
```swift
|
||||
// SELECT book.*, person.*
|
||||
|
||||
@@ -227,7 +227,7 @@ This publisher has the same behavior as ValueObservation:
|
||||
- It notifies an initial value before the eventual changes.
|
||||
- It may coalesce subsequent changes into a single notification.
|
||||
- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](../README.md#valueobservationremoveduplicates) GRDB operator also.
|
||||
- It stops emitting any value after the database connection is closed. But it never completes.
|
||||
- It only completes when it is cancelled.
|
||||
- By default, it notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously.
|
||||
|
||||
This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservation scheduler](../README.md#valueobservation-scheduling).
|
||||
|
||||
@@ -137,7 +137,7 @@ try dbQueue.write { db in
|
||||
<details>
|
||||
<summary><b>Swift concurrency</b> (async/await)</summary>
|
||||
|
||||
[**:fire: EXPERIMENTAL**](../README.md#what-are-experimental-features) GRDB support for Swift concurrency requires Xcode 13.2+.
|
||||
[**:fire: EXPERIMENTAL**](../README.md#what-are-experimental-features) GRDB support for Swift concurrency requires Xcode 13.3.1+.
|
||||
|
||||
```swift
|
||||
let playerCount = try await dbQueue.read { db in
|
||||
@@ -469,7 +469,7 @@ In the illustration below, the striped band shows the delay needed for the readi
|
||||
let snapshot = try dbPool.makeSnapshot()
|
||||
```
|
||||
|
||||
You can create as many snapshots as you need, regardless of the [maximum number of readers](../README.md#databasepool-configuration) in the pool. A snapshot database connection is closed when the snapshot is deinitialized.
|
||||
You can create as many snapshots as you need, regardless of the [maximum number of readers](../README.md#database-configuration) in the pool. A snapshot database connection is closed when the snapshot is deinitialized.
|
||||
|
||||
**A snapshot can be used from any thread.** It has the same [synchronous and asynchronous reading methods](#synchronous-and-asynchronous-database-accesses) as database queues and pools:
|
||||
|
||||
|
||||
@@ -304,7 +304,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.19/Structs/StatementArguments.html):
|
||||
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -587,7 +587,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.19/Structs/StatementArguments.html):
|
||||
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -737,11 +737,11 @@ The SQLite built-in tokenizers for [FTS3, FTS4](#fts3-and-fts4-tokenizers) and [
|
||||
|
||||
Generally speaking, matches may fail when content and query don't use the same [unicode normalization](http://unicode.org/reports/tr15/). SQLite actually exhibits inconsistent behavior in this regard.
|
||||
|
||||
For example, for "aimé" to match "aimé", they better have the same normalization: the NFC "aim\u{00E9}" form may not match its NFD "aime\u{0301}" equivalent. Most strings that you get from Swift, UIKit and Cocoa use NFC, so be careful with NFD inputs (such as strings from the HFS+ file system, or strings that you can't trust like network inputs). Use [String.precomposedStringWithCanonicalMapping](https://developer.apple.com/reference/swift/string/1407210-precomposedstringwithcanonicalma) to turn a string into NFC.
|
||||
For example, for "aimé" to match "aimé", they better have the same normalization: the NFC "aim\u{00E9}" form may not match its NFD "aime\u{0301}" equivalent. Most strings that you get from Swift, UIKit and Cocoa use NFC, so be careful with NFD inputs (such as strings from the HFS+ file system, or strings that you can't trust like network inputs). Use [String.precomposedStringWithCanonicalMapping](https://developer.apple.com/documentation/foundation/nsstring/1412645-precomposedstringwithcanonicalma) to turn a string into NFC.
|
||||
|
||||
Besides, if you want "fi" to match the ligature "fi" (U+FB01), then you need to normalize your indexed contents and inputs to NFKC or NFKD. Use [String.precomposedStringWithCompatibilityMapping](https://developer.apple.com/reference/swift/string/1407834-precomposedstringwithcompatibili) to turn a string into NFKC.
|
||||
Besides, if you want "fi" to match the ligature "fi" (U+FB01), then you need to normalize your indexed contents and inputs to NFKC or NFKD. Use [String.precomposedStringWithCompatibilityMapping](https://developer.apple.com/documentation/foundation/nsstring/1412625-precomposedstringwithcompatibili) to turn a string into NFKC.
|
||||
|
||||
Unicode normalization is not the end of the story, because it won't help "Encyclopaedia" match "Encyclopædia", "Mueller", "Müller", "Grossmann", "Großmann", or "Diyarbakır", "DIYARBAKIR". The [String.applyingTransform](https://developer.apple.com/reference/swift/string/1643133-applyingtransform) method can help.
|
||||
Unicode normalization is not the end of the story, because it won't help "Encyclopaedia" match "Encyclopædia", "Mueller", "Müller", "Grossmann", "Großmann", or "Diyarbakır", "DIYARBAKIR". The [String.applyingTransform](https://developer.apple.com/documentation/foundation/nsstring/1407787-applyingtransform) method can help.
|
||||
|
||||
GRDB lets you write [custom FTS5 tokenizers](FTS5Tokenizers.md) that can transparently deal with all these issues. For FTS3 and FTS4, you'll need to pre-process your strings before injecting them in the full-text engine.
|
||||
|
||||
|
||||
@@ -77,7 +77,7 @@ try dbQueue.read { db in
|
||||
}
|
||||
```
|
||||
|
||||
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.19/Structs/DatabaseMigrator.html) for more migrator methods.
|
||||
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.26/Structs/DatabaseMigrator.html) for more migrator methods.
|
||||
|
||||
|
||||
## The `eraseDatabaseOnSchemaChange` Option
|
||||
@@ -268,13 +268,7 @@ while let violation = try violations.next() {
|
||||
|
||||
## Asynchronous Migrations
|
||||
|
||||
`DatabaseMigrator` provides three ways to migrate a database in an asynchronous way.
|
||||
|
||||
The async `migrate()` method:
|
||||
|
||||
```swift
|
||||
try await migrator.migrate(dbQueue)
|
||||
```
|
||||
`DatabaseMigrator` provides the following ways to migrate a database in an asynchronous way.
|
||||
|
||||
The `asyncMigrate(_:completion:)` method:
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '5.19.0'
|
||||
s.version = '5.26.1'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -287,9 +287,9 @@
|
||||
564448831EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
|
||||
564448871EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
|
||||
564A50C81BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */; };
|
||||
564CE43121AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
|
||||
564CE43221AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
|
||||
564CE43321AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
|
||||
564CE43121AA901800652B19 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */; };
|
||||
564CE43221AA901800652B19 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */; };
|
||||
564CE43321AA901800652B19 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */; };
|
||||
564CE4E921B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; };
|
||||
564CE4EA21B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; };
|
||||
564CE59D21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* RemoveDuplicates.swift */; };
|
||||
@@ -539,6 +539,10 @@
|
||||
56781B0C243F86E600650A83 /* Refinable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56781B0A243F86E600650A83 /* Refinable.swift */; };
|
||||
56781B0D243F86E600650A83 /* Refinable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56781B0A243F86E600650A83 /* Refinable.swift */; };
|
||||
56781B0E243F86E600650A83 /* Refinable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56781B0A243F86E600650A83 /* Refinable.swift */; };
|
||||
5679533327E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */; };
|
||||
5679533427E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */; };
|
||||
5679533527E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */; };
|
||||
5679533627E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */; };
|
||||
567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; };
|
||||
567DAF1C1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
|
||||
567DAF1F1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
|
||||
@@ -729,6 +733,10 @@
|
||||
56B14E831D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; };
|
||||
56B6EF56208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */; };
|
||||
56B6EF57208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */; };
|
||||
56B7EE832863781300C0525F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7EE822863781300C0525F /* WALSnapshot.swift */; };
|
||||
56B7EE842863781300C0525F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7EE822863781300C0525F /* WALSnapshot.swift */; };
|
||||
56B7EE852863781300C0525F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7EE822863781300C0525F /* WALSnapshot.swift */; };
|
||||
56B7EE862863781300C0525F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7EE822863781300C0525F /* WALSnapshot.swift */; };
|
||||
56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; };
|
||||
56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; };
|
||||
56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; };
|
||||
@@ -920,6 +928,9 @@
|
||||
56F5ABDA1D814330001F60CB /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; };
|
||||
56F5ABDC1D814330001F60CB /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; };
|
||||
56F5ABDD1D814330001F60CB /* UUID.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C22F1D1914540096E9D4 /* UUID.swift */; };
|
||||
56F61DD5283D344E00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DD4283D344E00AF9884 /* getThreadsCount.c */; };
|
||||
56F61DD6283D344E00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DD4283D344E00AF9884 /* getThreadsCount.c */; };
|
||||
56F61DD7283D344E00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DD4283D344E00AF9884 /* getThreadsCount.c */; };
|
||||
56FBFED92210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
|
||||
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
|
||||
56FBFEDB2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
|
||||
@@ -949,7 +960,7 @@
|
||||
AAA4DC85230F1E0600C74B15 /* Column.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5401EAA359A00BFAF62 /* Column.swift */; };
|
||||
AAA4DC87230F1E0600C74B15 /* Date.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F14F1C672E4000235C62 /* Date.swift */; };
|
||||
AAA4DC89230F1E0600C74B15 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
|
||||
AAA4DC8A230F1E0600C74B15 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
|
||||
AAA4DC8A230F1E0600C74B15 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */; };
|
||||
AAA4DC8B230F1E0600C74B15 /* Fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AACAA722ACED7100A40F2A /* Fetch.swift */; };
|
||||
AAA4DC8C230F1E0600C74B15 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */; };
|
||||
AAA4DC8D230F1E0600C74B15 /* FTS3+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterface.swift */; };
|
||||
@@ -1385,7 +1396,7 @@
|
||||
5643676D272EDF2400C718C7 /* Scripts */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Scripts; sourceTree = "<group>"; };
|
||||
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
|
||||
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
|
||||
564CE43021AA901800652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = "<group>"; };
|
||||
564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueConcurrentObserver.swift; sourceTree = "<group>"; };
|
||||
564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = "<group>"; };
|
||||
564CE59621B7A8B500652B19 /* RemoveDuplicates.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RemoveDuplicates.swift; sourceTree = "<group>"; };
|
||||
564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = "<group>"; };
|
||||
@@ -1480,6 +1491,7 @@
|
||||
5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchableRecordDecodableTests.swift; sourceTree = "<group>"; };
|
||||
5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = "<group>"; };
|
||||
56781B0A243F86E600650A83 /* Refinable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Refinable.swift; sourceTree = "<group>"; };
|
||||
5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueWriteOnlyObserver.swift; sourceTree = "<group>"; };
|
||||
567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = "<group>"; };
|
||||
567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = "<group>"; };
|
||||
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1587,6 +1599,7 @@
|
||||
56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = "<group>"; };
|
||||
56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = "<group>"; };
|
||||
56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = "<group>"; };
|
||||
56B7EE822863781300C0525F /* WALSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshot.swift; sourceTree = "<group>"; };
|
||||
56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = "<group>"; };
|
||||
56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = "<group>"; };
|
||||
56B86E72220FF4E000524C16 /* SQLLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLLiteralTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1641,6 +1654,9 @@
|
||||
56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLExpressionIsConstantTests.swift; sourceTree = "<group>"; };
|
||||
56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLIdentifyingColumnsTests.swift; sourceTree = "<group>"; };
|
||||
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = "<group>"; };
|
||||
56F61DD0283D344D00AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "GRDBTests-Bridging-Header.h"; path = "GRDBTests/GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
|
||||
56F61DD3283D344E00AF9884 /* getThreadsCount.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = getThreadsCount.h; sourceTree = "<group>"; };
|
||||
56F61DD4283D344E00AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
|
||||
56FBFED82210731A00945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = "<group>"; };
|
||||
56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = "<group>"; };
|
||||
56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseTraceTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1791,6 +1807,8 @@
|
||||
569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */,
|
||||
56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */,
|
||||
563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */,
|
||||
56F61DD3283D344E00AF9884 /* getThreadsCount.h */,
|
||||
56F61DD4283D344E00AF9884 /* getThreadsCount.c */,
|
||||
);
|
||||
name = DatabasePool;
|
||||
sourceTree = "<group>";
|
||||
@@ -1815,9 +1833,10 @@
|
||||
children = (
|
||||
563082E32430B6BE00C14A05 /* DatabaseCancellable.swift */,
|
||||
560233C32724234F00529DF3 /* SharedValueObservation.swift */,
|
||||
564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */,
|
||||
563B06AA217EF0CC00B38F35 /* ValueObservation.swift */,
|
||||
56848972242DE36F002F9702 /* ValueObservationScheduler.swift */,
|
||||
564CE43021AA901800652B19 /* ValueObserver.swift */,
|
||||
5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */,
|
||||
56AACAA022ACEC9700A40F2A /* ValueReducer */,
|
||||
);
|
||||
path = ValueObservation;
|
||||
@@ -2361,8 +2380,9 @@
|
||||
56A238781B9C75030082EB20 /* Statement.swift */,
|
||||
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
|
||||
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
|
||||
5605F1471C672E4000235C62 /* Support */,
|
||||
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
|
||||
56B7EE822863781300C0525F /* WALSnapshot.swift */,
|
||||
5605F1471C672E4000235C62 /* Support */,
|
||||
);
|
||||
path = Core;
|
||||
sourceTree = "<group>";
|
||||
@@ -2496,6 +2516,7 @@
|
||||
DC37740319C8CBB3004FCF85 /* Supporting Files */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56F61DD0283D344D00AF9884 /* GRDBTests-Bridging-Header.h */,
|
||||
DC37740419C8CBB3004FCF85 /* Info.plist */,
|
||||
);
|
||||
name = "Supporting Files";
|
||||
@@ -2583,9 +2604,9 @@
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 565490B31D5A4798005622CB /* Build configuration list for PBXNativeTarget "GRDBWatchOS" */;
|
||||
buildPhases = (
|
||||
5654909D1D5A4798005622CB /* Headers */,
|
||||
5654909B1D5A4798005622CB /* Sources */,
|
||||
5654909C1D5A4798005622CB /* Frameworks */,
|
||||
5654909D1D5A4798005622CB /* Headers */,
|
||||
5654909E1D5A4798005622CB /* Resources */,
|
||||
);
|
||||
buildRules = (
|
||||
@@ -2619,9 +2640,9 @@
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 56E5D7DB1B4D3FEE00430942 /* Build configuration list for PBXNativeTarget "GRDBiOS" */;
|
||||
buildPhases = (
|
||||
56E5D7C71B4D3FED00430942 /* Headers */,
|
||||
56E5D7C51B4D3FED00430942 /* Sources */,
|
||||
56E5D7C61B4D3FED00430942 /* Frameworks */,
|
||||
56E5D7C71B4D3FED00430942 /* Headers */,
|
||||
56E5D7C81B4D3FED00430942 /* Resources */,
|
||||
56EB54FA22C9115E00850069 /* Swiftlint */,
|
||||
);
|
||||
@@ -2674,9 +2695,9 @@
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = AAA4DCFB230F1E0600C74B15 /* Build configuration list for PBXNativeTarget "GRDBtvOS" */;
|
||||
buildPhases = (
|
||||
AAA4DCF5230F1E0600C74B15 /* Headers */,
|
||||
AAA4DC76230F1E0600C74B15 /* Sources */,
|
||||
AAA4DCF4230F1E0600C74B15 /* Frameworks */,
|
||||
AAA4DCF5230F1E0600C74B15 /* Headers */,
|
||||
AAA4DCF9230F1E0600C74B15 /* Resources */,
|
||||
AAA4DCFA230F1E0600C74B15 /* Swiftlint */,
|
||||
);
|
||||
@@ -2711,9 +2732,9 @@
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = DC37740919C8CBB3004FCF85 /* Build configuration list for PBXNativeTarget "GRDBOSX" */;
|
||||
buildPhases = (
|
||||
DC3773F019C8CBB3004FCF85 /* Headers */,
|
||||
DC3773EE19C8CBB3004FCF85 /* Sources */,
|
||||
DC3773EF19C8CBB3004FCF85 /* Frameworks */,
|
||||
DC3773F019C8CBB3004FCF85 /* Headers */,
|
||||
DC3773F119C8CBB3004FCF85 /* Resources */,
|
||||
56EB54F322C8ED5100850069 /* Swiftlint */,
|
||||
);
|
||||
@@ -2746,17 +2767,18 @@
|
||||
};
|
||||
56E5D7D21B4D3FEE00430942 = {
|
||||
CreatedOnToolsVersion = 7.0;
|
||||
LastSwiftMigration = 1130;
|
||||
LastSwiftMigration = 1340;
|
||||
ProvisioningStyle = Manual;
|
||||
};
|
||||
56E5D7F81B4D422D00430942 = {
|
||||
CreatedOnToolsVersion = 7.0;
|
||||
LastSwiftMigration = 1020;
|
||||
LastSwiftMigration = 1340;
|
||||
};
|
||||
AAA4DC75230F1E0600C74B15 = {
|
||||
ProvisioningStyle = Manual;
|
||||
};
|
||||
AAA4DD07230F262000C74B15 = {
|
||||
LastSwiftMigration = 1340;
|
||||
ProvisioningStyle = Manual;
|
||||
};
|
||||
DC3773F219C8CBB3004FCF85 = {
|
||||
@@ -2858,6 +2880,7 @@
|
||||
/* Begin PBXShellScriptBuildPhase section */
|
||||
56EB54F322C8ED5100850069 /* Swiftlint */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
alwaysOutOfDate = 1;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
@@ -2876,6 +2899,7 @@
|
||||
};
|
||||
56EB54FA22C9115E00850069 /* Swiftlint */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
alwaysOutOfDate = 1;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
@@ -2894,6 +2918,7 @@
|
||||
};
|
||||
AAA4DCFA230F1E0600C74B15 /* Swiftlint */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
alwaysOutOfDate = 1;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
@@ -2943,11 +2968,12 @@
|
||||
564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */,
|
||||
5659F4961EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
|
||||
56894FD12606589C00268F4D /* Decimal.swift in Sources */,
|
||||
5679533527E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */,
|
||||
56172950223533F40006E219 /* EncodableRecord.swift in Sources */,
|
||||
56AE64142229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */,
|
||||
5613ED3721A95A5C00DC7A68 /* Map.swift in Sources */,
|
||||
5659F48E1EA8D94E004A4992 /* Utils.swift in Sources */,
|
||||
564CE43321AA901800652B19 /* ValueObserver.swift in Sources */,
|
||||
564CE43321AA901800652B19 /* ValueConcurrentObserver.swift in Sources */,
|
||||
563B8FC724A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
566B9C2225C6CC24004542CF /* RowDecodingError.swift in Sources */,
|
||||
565490B91D5AE236005622CB /* DatabasePool.swift in Sources */,
|
||||
@@ -2956,6 +2982,7 @@
|
||||
565490D81D5AE252005622CB /* DatabaseMigrator.swift in Sources */,
|
||||
5656A8AF2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */,
|
||||
565490C21D5AE236005622CB /* Row.swift in Sources */,
|
||||
56B7EE852863781300C0525F /* WALSnapshot.swift in Sources */,
|
||||
565490C71D5AE236005622CB /* StatementColumnConvertible.swift in Sources */,
|
||||
565490D91D5AE252005622CB /* Migration.swift in Sources */,
|
||||
56CEB5001EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
|
||||
@@ -3094,7 +3121,7 @@
|
||||
56CEB5481EAA359A00BFAF62 /* Column.swift in Sources */,
|
||||
5605F1641C672E4000235C62 /* Date.swift in Sources */,
|
||||
566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
564CE43221AA901800652B19 /* ValueObserver.swift in Sources */,
|
||||
564CE43221AA901800652B19 /* ValueConcurrentObserver.swift in Sources */,
|
||||
568ECA8B25D7013000B71526 /* SQLSelection.swift in Sources */,
|
||||
56AACAA922ACED7100A40F2A /* Fetch.swift in Sources */,
|
||||
5605F1721C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
|
||||
@@ -3125,6 +3152,7 @@
|
||||
5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
|
||||
56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
|
||||
56DDDDF5242F87C60025E381 /* ValueObservationScheduler.swift in Sources */,
|
||||
56B7EE842863781300C0525F /* WALSnapshot.swift in Sources */,
|
||||
560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */,
|
||||
56A2FA3B24424F4700E97D23 /* Export.swift in Sources */,
|
||||
569BBA4F229170F900478429 /* Inflections+English.swift in Sources */,
|
||||
@@ -3179,6 +3207,7 @@
|
||||
C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */,
|
||||
5605F1681C672E4000235C62 /* NSNumber.swift in Sources */,
|
||||
564CE5AD21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
|
||||
5679533427E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */,
|
||||
56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
|
||||
563B8F93249E6171007A48C9 /* Trace.swift in Sources */,
|
||||
5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */,
|
||||
@@ -3424,6 +3453,7 @@
|
||||
56A2383A1B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift in Sources */,
|
||||
56A5E40A1BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift in Sources */,
|
||||
56677C1A241D217F0050755D /* ValueObservationRecorderTests.swift in Sources */,
|
||||
56F61DD6283D344E00AF9884 /* getThreadsCount.c in Sources */,
|
||||
5653EAF520944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */,
|
||||
563B06BE2185CCD300B38F35 /* ValueObservationTests.swift in Sources */,
|
||||
56FF455A1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */,
|
||||
@@ -3659,6 +3689,7 @@
|
||||
56DF001D228DDBA300D611F3 /* AssociationPrefetchingCodableRecordTests.swift in Sources */,
|
||||
5653EAD820944B4F00F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */,
|
||||
562205F11E420E47005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */,
|
||||
56F61DD5283D344E00AF9884 /* getThreadsCount.c in Sources */,
|
||||
56677C19241D217F0050755D /* ValueObservationRecorderTests.swift in Sources */,
|
||||
5653EAF420944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */,
|
||||
563B06BD2185CCD300B38F35 /* ValueObservationTests.swift in Sources */,
|
||||
@@ -3699,7 +3730,7 @@
|
||||
AAA4DC85230F1E0600C74B15 /* Column.swift in Sources */,
|
||||
AAA4DC87230F1E0600C74B15 /* Date.swift in Sources */,
|
||||
AAA4DC89230F1E0600C74B15 /* TransactionObserver.swift in Sources */,
|
||||
AAA4DC8A230F1E0600C74B15 /* ValueObserver.swift in Sources */,
|
||||
AAA4DC8A230F1E0600C74B15 /* ValueConcurrentObserver.swift in Sources */,
|
||||
568ECA8D25D7013000B71526 /* SQLSelection.swift in Sources */,
|
||||
AAA4DC8B230F1E0600C74B15 /* Fetch.swift in Sources */,
|
||||
AAA4DC8C230F1E0600C74B15 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
|
||||
@@ -3730,6 +3761,7 @@
|
||||
AAA4DCA5230F1E0600C74B15 /* FTS3TokenizerDescriptor.swift in Sources */,
|
||||
AAA4DCA6230F1E0600C74B15 /* FetchableRecord+TableRecord.swift in Sources */,
|
||||
56DDDDF7242F87C70025E381 /* ValueObservationScheduler.swift in Sources */,
|
||||
56B7EE862863781300C0525F /* WALSnapshot.swift in Sources */,
|
||||
AAA4DCA7230F1E0600C74B15 /* TableRecord.swift in Sources */,
|
||||
56A2FA3D24424F4800E97D23 /* Export.swift in Sources */,
|
||||
AAA4DCA8230F1E0600C74B15 /* Inflections+English.swift in Sources */,
|
||||
@@ -3784,6 +3816,7 @@
|
||||
AAA4DCD8230F1E0600C74B15 /* SQLiteDateParser.swift in Sources */,
|
||||
AAA4DCD9230F1E0600C74B15 /* NSNumber.swift in Sources */,
|
||||
AAA4DCDB230F1E0600C74B15 /* DatabaseRegionObservation.swift in Sources */,
|
||||
5679533627E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */,
|
||||
AAA4DCDC230F1E0600C74B15 /* FTS4.swift in Sources */,
|
||||
563B8F95249E6171007A48C9 /* Trace.swift in Sources */,
|
||||
AAA4DCDD230F1E0600C74B15 /* StandardLibrary.swift in Sources */,
|
||||
@@ -4029,6 +4062,7 @@
|
||||
AAA4DDC0230F262000C74B15 /* DatabaseQueueInMemoryTests.swift in Sources */,
|
||||
AAA4DDC1230F262000C74B15 /* RecordWithColumnNameManglingTests.swift in Sources */,
|
||||
56677C1B241D217F0050755D /* ValueObservationRecorderTests.swift in Sources */,
|
||||
56F61DD7283D344E00AF9884 /* getThreadsCount.c in Sources */,
|
||||
AAA4DDC2230F262000C74B15 /* AssociationParallelSQLTests.swift in Sources */,
|
||||
AAA4DDC3230F262000C74B15 /* ValueObservationTests.swift in Sources */,
|
||||
AAA4DDC4230F262000C74B15 /* RecordUniqueIndexTests.swift in Sources */,
|
||||
@@ -4100,6 +4134,7 @@
|
||||
569BBA4E229170F800478429 /* Inflections+English.swift in Sources */,
|
||||
5656A81E2295B12F001FF3FF /* SQLAssociation.swift in Sources */,
|
||||
5617294E223533F40006E219 /* EncodableRecord.swift in Sources */,
|
||||
56B7EE832863781300C0525F /* WALSnapshot.swift in Sources */,
|
||||
5698AD181DAAD17A0056AF8C /* FTS5Tokenizer.swift in Sources */,
|
||||
56A2FA3624424D2A00E97D23 /* Export.swift in Sources */,
|
||||
56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
|
||||
@@ -4146,7 +4181,7 @@
|
||||
56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
|
||||
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */,
|
||||
563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */,
|
||||
564CE43121AA901800652B19 /* ValueObserver.swift in Sources */,
|
||||
564CE43121AA901800652B19 /* ValueConcurrentObserver.swift in Sources */,
|
||||
5605F1651C672E4000235C62 /* NSNull.swift in Sources */,
|
||||
56CEB5191EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */,
|
||||
568ECB1825D9161600B71526 /* SQLSubquery.swift in Sources */,
|
||||
@@ -4154,6 +4189,7 @@
|
||||
5653EB0620944C7C00F46237 /* SQLForeignKeyRequest.swift in Sources */,
|
||||
56E9FACB221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */,
|
||||
563B8F92249E6171007A48C9 /* Trace.swift in Sources */,
|
||||
5679533327E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */,
|
||||
5698AC781DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */,
|
||||
56A2387D1B9C75030082EB20 /* Database.swift in Sources */,
|
||||
566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
|
||||
@@ -4372,6 +4408,7 @@
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */;
|
||||
buildSettings = {
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
CODE_SIGN_STYLE = Manual;
|
||||
@@ -4390,6 +4427,9 @@
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
"PROVISIONING_PROFILE_SPECIFIER[sdk=macosx*]" = "";
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Tests/GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -4397,6 +4437,7 @@
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */;
|
||||
buildSettings = {
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
CODE_SIGN_STYLE = Manual;
|
||||
@@ -4417,7 +4458,9 @@
|
||||
"PROVISIONING_PROFILE_SPECIFIER[sdk=macosx*]" = "";
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Tests/GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
@@ -4425,6 +4468,7 @@
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */;
|
||||
buildSettings = {
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
@@ -4439,6 +4483,9 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = macosx;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Tests/GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -4446,6 +4493,7 @@
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */;
|
||||
buildSettings = {
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
@@ -4462,7 +4510,9 @@
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = macosx;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Tests/GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
@@ -4534,6 +4584,7 @@
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */;
|
||||
buildSettings = {
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
CODE_SIGN_IDENTITY = "iPhone Developer";
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
@@ -4552,6 +4603,9 @@
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
SDKROOT = appletvos;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Tests/GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -4559,6 +4613,7 @@
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */;
|
||||
buildSettings = {
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
CODE_SIGN_IDENTITY = "iPhone Developer";
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
@@ -4579,7 +4634,9 @@
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
SDKROOT = appletvos;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Tests/GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import Foundation
|
||||
import Dispatch
|
||||
import Foundation
|
||||
|
||||
/// Configuration for a DatabaseQueue or DatabasePool.
|
||||
public struct Configuration {
|
||||
@@ -102,6 +102,52 @@ public struct Configuration {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public var observesSuspensionNotifications = false
|
||||
|
||||
/// If false (the default), statement arguments are not visible in the
|
||||
/// description of database errors and trace events, preventing sensitive
|
||||
/// information from leaking in unexpected places.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // Error: sensitive information is not printed when an error occurs:
|
||||
/// do {
|
||||
/// let email = "..." // sensitive information
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// print(error)
|
||||
/// }
|
||||
///
|
||||
/// // Trace: sensitive information is not printed when a statement is traced:
|
||||
/// db.trace { event in
|
||||
/// print(event)
|
||||
/// }
|
||||
/// let email = "..." // sensitive information
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
///
|
||||
/// For debugging purpose, you can set this flag to true, and get more
|
||||
/// precise database reports. It is your responsibility to prevent sensitive
|
||||
/// information from leaking in unexpected locations, so you should not set
|
||||
/// this flag in release builds (think about GDPR and other
|
||||
/// privacy-related rules):
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// #if DEBUG
|
||||
/// // Protect sensitive information by enabling verbose debugging in DEBUG builds only
|
||||
/// config.publicStatementArguments = true
|
||||
/// #endif
|
||||
///
|
||||
/// // The descriptions of trace events and errors now contain the
|
||||
/// // sensitive information:
|
||||
/// db.trace { event in
|
||||
/// print(event)
|
||||
/// }
|
||||
/// do {
|
||||
/// let email = "..."
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// print(error)
|
||||
/// }
|
||||
public var publicStatementArguments = false
|
||||
|
||||
// MARK: - Managing SQLite Connections
|
||||
|
||||
private var setups: [(Database) throws -> Void] = []
|
||||
@@ -199,22 +245,45 @@ public struct Configuration {
|
||||
///
|
||||
/// The quality of service is ignored if you supply a target queue.
|
||||
///
|
||||
/// Default: .default
|
||||
public var qos: DispatchQoS = .default
|
||||
/// Default: .userInitiated
|
||||
public var qos: DispatchQoS = .userInitiated
|
||||
|
||||
/// The target queue for all database accesses.
|
||||
/// The quality of service of read accesses
|
||||
var readQoS: DispatchQoS {
|
||||
targetQueue?.qos ?? self.qos
|
||||
}
|
||||
|
||||
/// A target queue for database accesses.
|
||||
///
|
||||
/// When you use a database pool, make sure the queue is concurrent. If
|
||||
/// it is serial, no concurrent database access can happen, and you may
|
||||
/// experience deadlocks.
|
||||
/// Database connections which are not read-only will prefer
|
||||
/// `writeTargetQueue` instead, if it is not nil.
|
||||
///
|
||||
/// When you use a database pool, make sure this queue is concurrent. This
|
||||
/// is because in a serial dispatch queue, no concurrent database access can
|
||||
/// happen, and you may experience deadlocks.
|
||||
///
|
||||
/// If the queue is nil, all database accesses happen in unspecified
|
||||
/// dispatch queues whose quality of service and label are determined by the
|
||||
/// `qos` and `label` Configuration properties.
|
||||
/// dispatch queues whose quality of service is determined by the
|
||||
/// `qos` property.
|
||||
///
|
||||
/// Default: nil
|
||||
public var targetQueue: DispatchQueue? = nil
|
||||
|
||||
/// The target queue for database connections which are not read-only.
|
||||
///
|
||||
/// If this queue is nil, writer connections are controlled by `targetQueue`.
|
||||
///
|
||||
/// Default: nil
|
||||
public var writeTargetQueue: DispatchQueue? = nil
|
||||
|
||||
#if os(iOS)
|
||||
/// Sets whether GRDB will release memory when entering the background or
|
||||
/// upon receiving a memory warning in iOS.
|
||||
///
|
||||
/// Default: true
|
||||
public var automaticMemoryManagement = true
|
||||
#endif
|
||||
|
||||
// MARK: - Factory Configuration
|
||||
|
||||
/// Creates a factory configuration
|
||||
@@ -241,7 +310,19 @@ public struct Configuration {
|
||||
(self.label ?? defaultLabel) + (purpose.map { "." + $0 } ?? "")
|
||||
}
|
||||
|
||||
func makeDispatchQueue(label: String) -> DispatchQueue {
|
||||
/// Creates a DispatchQueue which has the quality of service and target
|
||||
/// queue of write accesses.
|
||||
func makeWriterDispatchQueue(label: String) -> DispatchQueue {
|
||||
if let targetQueue = writeTargetQueue ?? targetQueue {
|
||||
return DispatchQueue(label: label, target: targetQueue)
|
||||
} else {
|
||||
return DispatchQueue(label: label, qos: qos)
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a DispatchQueue which has the quality of service and target
|
||||
/// queue of read accesses.
|
||||
func makeReaderDispatchQueue(label: String) -> DispatchQueue {
|
||||
if let targetQueue = targetQueue {
|
||||
return DispatchQueue(label: label, target: targetQueue)
|
||||
} else {
|
||||
|
||||
+24
-2
@@ -21,8 +21,9 @@ extension RangeReplaceableCollection {
|
||||
/// - parameter cursor: The cursor whose elements feed the collection.
|
||||
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
|
||||
self.init()
|
||||
// Use `forEach` in order to deal with <https://github.com/groue/GRDB.swift/issues/1124>.
|
||||
// See `Statement.forEachStep(_:)` for more information.
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
// database cursors.
|
||||
try cursor.forEach { append($0) }
|
||||
}
|
||||
|
||||
@@ -38,6 +39,9 @@ extension RangeReplaceableCollection {
|
||||
public init<C: Cursor>(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element {
|
||||
self.init()
|
||||
reserveCapacity(minimumCapacity)
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
// database cursors.
|
||||
try cursor.forEach { append($0) }
|
||||
}
|
||||
}
|
||||
@@ -58,6 +62,9 @@ extension Dictionary {
|
||||
throws where Value == [C.Element]
|
||||
{
|
||||
self.init()
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
// database cursors.
|
||||
try cursor.forEach { value in
|
||||
try self[keyForValue(value), default: []].append(value)
|
||||
}
|
||||
@@ -84,6 +91,9 @@ extension Dictionary {
|
||||
throws where Value == [C.Element]
|
||||
{
|
||||
self.init(minimumCapacity: minimumCapacity)
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
// database cursors.
|
||||
try cursor.forEach { value in
|
||||
try self[keyForValue(value), default: []].append(value)
|
||||
}
|
||||
@@ -106,6 +116,9 @@ extension Dictionary {
|
||||
throws where C.Element == (Key, Value)
|
||||
{
|
||||
self.init()
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
// database cursors.
|
||||
try keysAndValues.forEach { key, value in
|
||||
if updateValue(value, forKey: key) != nil {
|
||||
fatalError("Duplicate values for key: '\(String(describing: key))'")
|
||||
@@ -135,6 +148,9 @@ extension Dictionary {
|
||||
throws where C.Element == (Key, Value)
|
||||
{
|
||||
self.init(minimumCapacity: minimumCapacity)
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
// database cursors.
|
||||
try keysAndValues.forEach { key, value in
|
||||
if updateValue(value, forKey: key) != nil {
|
||||
fatalError("Duplicate values for key: '\(String(describing: key))'")
|
||||
@@ -153,6 +169,9 @@ extension Set {
|
||||
/// - parameter cursor: A cursor of values to gather into a set.
|
||||
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
|
||||
self.init()
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
// database cursors.
|
||||
try cursor.forEach { insert($0) }
|
||||
}
|
||||
|
||||
@@ -168,6 +187,9 @@ extension Set {
|
||||
/// storage buffer.
|
||||
public init<C: Cursor>(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element {
|
||||
self.init(minimumCapacity: minimumCapacity)
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
// database cursors.
|
||||
try cursor.forEach { insert($0) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1046,9 +1046,9 @@ struct SchemaInfo: Equatable {
|
||||
|
||||
/// - parameter masterTable: "sqlite_master" or "sqlite_temp_master"
|
||||
init(_ db: Database, masterTableName: String) throws { // swiftlint:disable:this inclusive_language
|
||||
objects = try Set(SchemaObject.fetchCursor(db, sql: """
|
||||
objects = try SchemaObject.fetchSet(db, sql: """
|
||||
SELECT type, name, tbl_name, sql FROM \(masterTableName)
|
||||
"""))
|
||||
""")
|
||||
}
|
||||
|
||||
/// All names for a given type
|
||||
|
||||
@@ -542,21 +542,21 @@ public class SQLStatementCursor: Cursor {
|
||||
}
|
||||
|
||||
extension Database {
|
||||
/// Returns the authorizer that should be used during statement execution
|
||||
/// (this allows preventing the truncate optimization when there exists a
|
||||
/// transaction observer for row deletion).
|
||||
/// Makes sure statement can be executed, and prepares database observation.
|
||||
@usableFromInline
|
||||
func statementWillExecute(_ statement: Statement) throws -> StatementAuthorizer? {
|
||||
func statementWillExecute(_ statement: Statement) throws {
|
||||
// Two things must prevent the statement from executing: aborted
|
||||
// transactions, and database suspension.
|
||||
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
|
||||
try checkForSuspensionViolation(from: statement)
|
||||
|
||||
if _isRecordingSelectedRegion {
|
||||
_selectedRegion.formUnion(statement.databaseRegion)
|
||||
// Database observation: record what the statement is looking at.
|
||||
if isRecordingSelectedRegion {
|
||||
selectedRegion.formUnion(statement.databaseRegion)
|
||||
}
|
||||
|
||||
return observationBroker.statementWillExecute(statement)
|
||||
// Database observation: prepare transaction observers.
|
||||
observationBroker.statementWillExecute(statement)
|
||||
}
|
||||
|
||||
/// May throw a cancelled commit error, if a transaction observer cancels
|
||||
@@ -589,7 +589,8 @@ extension Database {
|
||||
resultCode: resultCode,
|
||||
message: lastErrorMessage,
|
||||
sql: statement.sql,
|
||||
arguments: statement.arguments)
|
||||
arguments: statement.arguments,
|
||||
publicStatementArguments: configuration.publicStatementArguments)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -639,4 +640,8 @@ struct StatementCache {
|
||||
mutating func remove(_ statement: Statement) {
|
||||
statements.removeFirst { $0.value === statement }
|
||||
}
|
||||
|
||||
mutating func removeAll(where shouldBeRemoved: (Statement) -> Bool) {
|
||||
statements = statements.filter { (_, statement) in !shouldBeRemoved(statement) }
|
||||
}
|
||||
}
|
||||
+136
-97
@@ -150,10 +150,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
lazy var internalStatementCache = StatementCache(database: self)
|
||||
lazy var publicStatementCache = StatementCache(database: self)
|
||||
|
||||
/// Statement authorizer. Use withAuthorizer(_:_:).
|
||||
fileprivate var _authorizer: StatementAuthorizer?
|
||||
|
||||
// Transaction observers management
|
||||
// Database observation
|
||||
lazy var authorizer = StatementAuthorizer(self)
|
||||
lazy var observationBroker = DatabaseObservationBroker(self)
|
||||
|
||||
/// The list of compile options used when building SQLite
|
||||
@@ -163,8 +161,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// If true, select statement execution is recorded.
|
||||
/// Use recordingSelectedRegion(_:), see `statementWillExecute(_:)`
|
||||
var _isRecordingSelectedRegion = false
|
||||
var _selectedRegion = DatabaseRegion()
|
||||
var isRecordingSelectedRegion = false
|
||||
var selectedRegion = DatabaseRegion()
|
||||
|
||||
/// Support for checkForAbortedTransaction()
|
||||
var isInsideTransactionBlock = false
|
||||
@@ -235,7 +233,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
setupDefaultFunctions()
|
||||
setupDefaultCollations()
|
||||
setupAuthorizer()
|
||||
observationBroker.installCommitAndRollbackHooks()
|
||||
if !configuration.readonly {
|
||||
observationBroker.installCommitAndRollbackHooks()
|
||||
}
|
||||
try activateExtendedCodes()
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
@@ -318,17 +318,16 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
//
|
||||
// - DatabaseCursorTests.testIssue583()
|
||||
// - http://sqlite.1065341.n5.nabble.com/Issue-report-sqlite3-set-authorizer-triggers-error-4-516-SQLITE-ABORT-ROLLBACK-during-statement-itern-td107972.html
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
let authorizerP = Unmanaged.passUnretained(authorizer).toOpaque()
|
||||
sqlite3_set_authorizer(
|
||||
sqliteConnection,
|
||||
{ (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer.unsafelyUnwrapped).takeUnretainedValue()
|
||||
guard let authorizer = db._authorizer else {
|
||||
return SQLITE_OK
|
||||
}
|
||||
return authorizer.authorize(actionCode, cString1, cString2, cString3, cString4)
|
||||
{ (authorizerP, actionCode, cString1, cString2, cString3, cString4) -> Int32 in
|
||||
Unmanaged<StatementAuthorizer>
|
||||
.fromOpaque(authorizerP.unsafelyUnwrapped)
|
||||
.takeUnretainedValue()
|
||||
.authorize(actionCode, cString1, cString2, cString3, cString4)
|
||||
},
|
||||
dbPointer)
|
||||
authorizerP)
|
||||
}
|
||||
|
||||
|
||||
@@ -549,47 +548,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
finally: endReadOnly)
|
||||
}
|
||||
|
||||
// MARK: - Snapshots
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT
|
||||
/// Returns a snapshot that must be freed with `sqlite3_snapshot_free`.
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/snapshot.html>
|
||||
func takeVersionSnapshot() throws -> UnsafeMutablePointer<sqlite3_snapshot> {
|
||||
var snapshot: UnsafeMutablePointer<sqlite3_snapshot>?
|
||||
let code = withUnsafeMutablePointer(to: &snapshot) {
|
||||
sqlite3_snapshot_get(sqliteConnection, "main", $0)
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: lastErrorMessage)
|
||||
}
|
||||
if let snapshot = snapshot {
|
||||
return snapshot
|
||||
} else {
|
||||
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
|
||||
}
|
||||
}
|
||||
|
||||
func wasChanged(since initialSnapshot: UnsafeMutablePointer<sqlite3_snapshot>) throws -> Bool {
|
||||
let secondSnapshot = try takeVersionSnapshot()
|
||||
defer {
|
||||
sqlite3_snapshot_free(secondSnapshot)
|
||||
}
|
||||
let cmp = sqlite3_snapshot_cmp(initialSnapshot, secondSnapshot)
|
||||
assert(cmp <= 0, "Unexpected snapshot ordering")
|
||||
return cmp < 0
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Authorizer
|
||||
|
||||
@usableFromInline
|
||||
func withAuthorizer<T>(_ authorizer: StatementAuthorizer?, _ block: () throws -> T) rethrows -> T {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
let old = self._authorizer
|
||||
self._authorizer = authorizer
|
||||
defer { self._authorizer = old }
|
||||
return try block()
|
||||
/// Returns whether database connection is read-only.
|
||||
var isReadOnly: Bool {
|
||||
_readOnlyDepth > 0 || configuration.readonly
|
||||
}
|
||||
|
||||
// MARK: - Recording of the selected region
|
||||
@@ -599,17 +560,17 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
return try block()
|
||||
}
|
||||
|
||||
let oldFlag = self._isRecordingSelectedRegion
|
||||
let oldRegion = self._selectedRegion
|
||||
_isRecordingSelectedRegion = true
|
||||
_selectedRegion = DatabaseRegion()
|
||||
let oldFlag = self.isRecordingSelectedRegion
|
||||
let oldRegion = self.selectedRegion
|
||||
isRecordingSelectedRegion = true
|
||||
selectedRegion = DatabaseRegion()
|
||||
defer {
|
||||
region.formUnion(_selectedRegion)
|
||||
_isRecordingSelectedRegion = oldFlag
|
||||
if _isRecordingSelectedRegion {
|
||||
_selectedRegion = oldRegion.union(_selectedRegion)
|
||||
region.formUnion(selectedRegion)
|
||||
isRecordingSelectedRegion = oldFlag
|
||||
if isRecordingSelectedRegion {
|
||||
selectedRegion = oldRegion.union(selectedRegion)
|
||||
} else {
|
||||
_selectedRegion = oldRegion
|
||||
selectedRegion = oldRegion
|
||||
}
|
||||
}
|
||||
return try block()
|
||||
@@ -713,7 +674,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
impl: .trace_v2(
|
||||
sqliteStatement: OpaquePointer(sqliteStatement),
|
||||
unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)),
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql))
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql,
|
||||
publicStatementArguments: configuration.publicStatementArguments))
|
||||
trace(TraceEvent.statement(statement))
|
||||
}
|
||||
case SQLITE_TRACE_PROFILE:
|
||||
@@ -722,7 +684,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
impl: .trace_v2(
|
||||
sqliteStatement: OpaquePointer(sqliteStatement),
|
||||
unexpandedSQL: nil,
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql))
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql,
|
||||
publicStatementArguments: configuration.publicStatementArguments))
|
||||
let duration = TimeInterval(durationP.pointee) / 1.0e9
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
|
||||
@@ -897,7 +860,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
resultCode: .SQLITE_ABORT,
|
||||
message: "Database is suspended",
|
||||
sql: statement.sql,
|
||||
arguments: statement.arguments)
|
||||
arguments: statement.arguments,
|
||||
publicStatementArguments: configuration.publicStatementArguments)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -930,7 +894,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
resultCode: .SQLITE_ABORT,
|
||||
message: "Transaction was aborted",
|
||||
sql: sql(),
|
||||
arguments: arguments())
|
||||
arguments: arguments(),
|
||||
publicStatementArguments: configuration.publicStatementArguments)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -949,10 +914,16 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// This method is not reentrant: you can't nest transactions.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .deferred. See <https://www.sqlite.org/lang_transaction.html>
|
||||
/// for more information.
|
||||
/// - kind: The transaction type (default nil).
|
||||
///
|
||||
/// If nil, and the database connection is read-only, the transaction
|
||||
/// kind is `.deferred`.
|
||||
///
|
||||
/// If nil, and the database connection is not read-only, the
|
||||
/// transaction kind is `configuration.defaultTransactionKind`.
|
||||
///
|
||||
/// See <https://www.sqlite.org/lang_transaction.html> for
|
||||
/// more information.
|
||||
/// - block: A block that executes SQL statements and return either
|
||||
/// .commit or .rollback.
|
||||
/// - throws: The error thrown by the block.
|
||||
@@ -1011,15 +982,24 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// Runs the block with an isolation level equal or greater than
|
||||
/// snapshot isolation.
|
||||
///
|
||||
/// - parameter readOnly: If true, writes are forbidden.
|
||||
func isolated<T>(readOnly: Bool = false, _ block: () throws -> T) throws -> T {
|
||||
var result: T?
|
||||
try inSavepoint {
|
||||
if readOnly {
|
||||
result = try self.readOnly(block)
|
||||
} else {
|
||||
result = try block()
|
||||
if readOnly {
|
||||
// Enter read-only mode before starting a transaction, so that the
|
||||
// transaction commit does not trigger database observation.
|
||||
try self.readOnly {
|
||||
try inSavepoint {
|
||||
result = try block()
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
} else {
|
||||
try inSavepoint {
|
||||
result = try block()
|
||||
return .commit
|
||||
}
|
||||
return .commit
|
||||
}
|
||||
return result!
|
||||
}
|
||||
@@ -1063,7 +1043,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
//
|
||||
// For those two reasons, we open a transaction instead of a
|
||||
// top-level savepoint.
|
||||
try inTransaction(configuration.defaultTransactionKind, block)
|
||||
try inTransaction { try block() }
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1131,13 +1111,20 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// Begins a database transaction.
|
||||
///
|
||||
/// - parameter kind: The transaction type (default nil). If nil, the
|
||||
/// transaction type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .deferred. See <https://www.sqlite.org/lang_transaction.html>
|
||||
/// for more information.
|
||||
/// - throws: The error thrown by the block.
|
||||
/// - parameter kind: The transaction type (default nil).
|
||||
///
|
||||
/// If nil, and the database connection is read-only, the transaction kind
|
||||
/// is `.deferred`.
|
||||
///
|
||||
/// If nil, and the database connection is not read-only, the transaction
|
||||
/// kind is `configuration.defaultTransactionKind`.
|
||||
///
|
||||
/// See <https://www.sqlite.org/lang_transaction.html> for
|
||||
/// more information.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func beginTransaction(_ kind: TransactionKind? = nil) throws {
|
||||
let kind = kind ?? configuration.defaultTransactionKind
|
||||
// SQLite throws an error for non-deferred transactions when read-only.
|
||||
let kind = kind ?? (isReadOnly ? .deferred : configuration.defaultTransactionKind)
|
||||
try execute(sql: "BEGIN \(kind.rawValue) TRANSACTION")
|
||||
assert(sqlite3_get_autocommit(sqliteConnection) == 0)
|
||||
}
|
||||
@@ -1197,7 +1184,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// MARK: - Memory Management
|
||||
|
||||
func releaseMemory() {
|
||||
public func releaseMemory() {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
sqlite3_db_release_memory(sqliteConnection)
|
||||
schemaCache.clear()
|
||||
internalStatementCache.clear()
|
||||
@@ -1642,22 +1630,23 @@ extension Database {
|
||||
public enum TraceEvent: CustomStringConvertible {
|
||||
|
||||
/// Information about a statement reported by `Database.trace(options:_:)`
|
||||
public struct Statement {
|
||||
public struct Statement: CustomStringConvertible {
|
||||
enum Impl {
|
||||
case trace_v1(String)
|
||||
case trace_v2(
|
||||
sqliteStatement: SQLiteStatement,
|
||||
unexpandedSQL: UnsafePointer<CChar>?,
|
||||
sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
|
||||
sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?,
|
||||
publicStatementArguments: Bool) // See Configuration.publicStatementArguments
|
||||
}
|
||||
let impl: Impl
|
||||
var impl: Impl
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
|
||||
/// The executed SQL, where bound parameters are not expanded.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// UPDATE player SET score = ? WHERE id = ?
|
||||
/// SELECT * FROM player WHERE email = ?
|
||||
public var sql: String { _sql }
|
||||
#elseif os(Linux)
|
||||
#else
|
||||
@@ -1665,7 +1654,7 @@ extension Database {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// UPDATE player SET score = ? WHERE id = ?
|
||||
/// SELECT * FROM player WHERE email = ?
|
||||
@available(OSX 10.12, tvOS 10.0, watchOS 3.0, *)
|
||||
public var sql: String { _sql }
|
||||
#endif
|
||||
@@ -1673,10 +1662,10 @@ extension Database {
|
||||
var _sql: String {
|
||||
switch impl {
|
||||
case .trace_v1:
|
||||
// Likely a GRDB bug
|
||||
fatalError("Not get statement SQL")
|
||||
// Likely a GRDB bug: this api is not supposed to be available
|
||||
fatalError("Unavailable statement SQL")
|
||||
|
||||
case let .trace_v2(sqliteStatement, unexpandedSQL, _):
|
||||
case let .trace_v2(sqliteStatement, unexpandedSQL, _, _):
|
||||
if let unexpandedSQL = unexpandedSQL {
|
||||
return String(cString: unexpandedSQL)
|
||||
.trimmingCharacters(in: .sqlStatementSeparators)
|
||||
@@ -1691,13 +1680,17 @@ extension Database {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// UPDATE player SET score = 1000 WHERE id = 1
|
||||
/// SELECT * FROM player WHERE email = 'arthur@example.com'
|
||||
///
|
||||
/// - warning: It is your responsibility to prevent sensitive
|
||||
/// information from leaking in unexpected locations, so use this
|
||||
/// property with care.
|
||||
public var expandedSQL: String {
|
||||
switch impl {
|
||||
case let .trace_v1(expandedSQL):
|
||||
return expandedSQL
|
||||
|
||||
case let .trace_v2(sqliteStatement, _, sqlite3_expanded_sql):
|
||||
case let .trace_v2(sqliteStatement, _, sqlite3_expanded_sql, _):
|
||||
guard let cString = sqlite3_expanded_sql(sqliteStatement) else {
|
||||
return ""
|
||||
}
|
||||
@@ -1706,6 +1699,20 @@ extension Database {
|
||||
.trimmingCharacters(in: .sqlStatementSeparators)
|
||||
}
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
switch impl {
|
||||
case let .trace_v1(expandedSQL):
|
||||
return expandedSQL
|
||||
|
||||
case let .trace_v2(_, _, _, publicStatementArguments):
|
||||
if publicStatementArguments {
|
||||
return expandedSQL
|
||||
} else {
|
||||
return _sql
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An event reported by `TracingOptions.statement`.
|
||||
@@ -1714,7 +1721,39 @@ extension Database {
|
||||
/// An event reported by `TracingOptions.profile`.
|
||||
case profile(statement: Statement, duration: TimeInterval)
|
||||
|
||||
/// The trace event description.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// SELECT * FROM player WHERE email = ?
|
||||
/// 0.1s SELECT * FROM player WHERE email = ?
|
||||
///
|
||||
/// The format of the event description may change between GRDB releases,
|
||||
/// without notice: don't have your application rely on any specific format.
|
||||
public var description: String {
|
||||
switch self {
|
||||
case let .statement(statement):
|
||||
return statement.description
|
||||
case let .profile(statement: statement, duration: duration):
|
||||
let durationString = String(format: "%.3f", duration)
|
||||
return "\(durationString)s \(statement)"
|
||||
}
|
||||
}
|
||||
|
||||
/// The trace event description, where bound parameters are expanded.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// SELECT * FROM player WHERE email = 'arthur@example.com'
|
||||
/// 0.1s SELECT * FROM player WHERE email = 'arthur@example.com'
|
||||
///
|
||||
/// The format of the event description may change between GRDB releases,
|
||||
/// without notice: don't have your application rely on any specific format.
|
||||
///
|
||||
/// - warning: It is your responsibility to prevent sensitive
|
||||
/// information from leaking in unexpected locations, so use this
|
||||
/// property with care.
|
||||
public var expandedDescription: String {
|
||||
switch self {
|
||||
case let .statement(statement):
|
||||
return statement.expandedSQL
|
||||
|
||||
@@ -241,17 +241,31 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
/// The query arguments that yielded the error (if relevant).
|
||||
public let arguments: StatementArguments?
|
||||
|
||||
/// Creates a Database Error
|
||||
/// See Configuration.publicStatementArguments
|
||||
var publicStatementArguments: Bool
|
||||
|
||||
/// Creates a DatabaseError.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - resultCode: A ResultCode (defaults to .SQLITE_ERROR).
|
||||
/// - message: An eventual error message. If nil, the error message is
|
||||
/// derived from the result code.
|
||||
/// - sql: An eventual SQL string.
|
||||
/// - arguments: Eventual Statement arguments.
|
||||
/// - publicStatementArguments: If false (the default), statement
|
||||
/// arguments are not visible in the error's `description` property.
|
||||
public init(
|
||||
resultCode: ResultCode = .SQLITE_ERROR,
|
||||
message: String? = nil,
|
||||
sql: String? = nil,
|
||||
arguments: StatementArguments? = nil)
|
||||
arguments: StatementArguments? = nil,
|
||||
publicStatementArguments: Bool = false)
|
||||
{
|
||||
self.extendedResultCode = resultCode
|
||||
self.message = message ?? resultCode.errorString
|
||||
self.sql = sql
|
||||
self.arguments = arguments
|
||||
self.publicStatementArguments = publicStatementArguments
|
||||
}
|
||||
|
||||
/// Creates a Database Error with a raw CInt result code.
|
||||
@@ -259,8 +273,31 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
/// This initializer is not public because library user is not supposed to
|
||||
/// be exposed to raw result codes.
|
||||
@usableFromInline
|
||||
init(resultCode: CInt, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
|
||||
self.init(resultCode: ResultCode(rawValue: resultCode), message: message, sql: sql, arguments: arguments)
|
||||
init(resultCode: CInt, message: String? = nil, sql: String? = nil) {
|
||||
self.init(
|
||||
resultCode: ResultCode(rawValue: resultCode),
|
||||
message: message,
|
||||
sql: sql)
|
||||
}
|
||||
|
||||
/// Creates a Database Error with a raw CInt result code.
|
||||
///
|
||||
/// This initializer is not public because library user is not supposed to
|
||||
/// be exposed to raw result codes.
|
||||
@usableFromInline
|
||||
init(
|
||||
resultCode: CInt,
|
||||
message: String? = nil,
|
||||
sql: String? = nil,
|
||||
arguments: StatementArguments?,
|
||||
publicStatementArguments: Bool)
|
||||
{
|
||||
self.init(
|
||||
resultCode: ResultCode(rawValue: resultCode),
|
||||
message: message,
|
||||
sql: sql,
|
||||
arguments: arguments,
|
||||
publicStatementArguments: publicStatementArguments)
|
||||
}
|
||||
|
||||
static func noSuchTable(_ tableName: String) -> Self {
|
||||
@@ -404,8 +441,44 @@ extension DatabaseError {
|
||||
|
||||
// CustomStringConvertible
|
||||
extension DatabaseError {
|
||||
/// :nodoc:
|
||||
/// The error description.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// SQLite error 19: NOT NULL constraint failed: player.score
|
||||
/// - while executing `UPDATE player SET score = ? WHERE email = ?
|
||||
///
|
||||
/// The format of the error description may change between GRDB releases,
|
||||
/// without notice: don't have your application rely on any specific format.
|
||||
public var description: String {
|
||||
var description = "SQLite error \(resultCode.rawValue)"
|
||||
if let message = message {
|
||||
description += ": \(message)"
|
||||
}
|
||||
if let sql = sql {
|
||||
description += " - while executing `\(sql)`"
|
||||
}
|
||||
if publicStatementArguments, let arguments = arguments, !arguments.isEmpty {
|
||||
description += " with arguments \(arguments)"
|
||||
}
|
||||
return description
|
||||
}
|
||||
|
||||
/// The error description, where bound parameters, if present, are visible.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// SQLite error 19: NOT NULL constraint failed: player.score
|
||||
/// - while executing `UPDATE player SET score = ? WHERE email = ?
|
||||
/// with arguments [nil, "arthur@example.com"]
|
||||
///
|
||||
/// The format of the error description may change between GRDB releases,
|
||||
/// without notice: don't have your application rely on any specific format.
|
||||
///
|
||||
/// - warning: It is your responsibility to prevent sensitive
|
||||
/// information from leaking in unexpected locations, so use this
|
||||
/// property with care.
|
||||
public var expandedDescription: String {
|
||||
var description = "SQLite error \(resultCode.rawValue)"
|
||||
if let message = message {
|
||||
description += ": \(message)"
|
||||
@@ -433,5 +506,11 @@ extension DatabaseError {
|
||||
|
||||
/// NSError bridging: the user-info dictionary.
|
||||
/// :nodoc:
|
||||
public var errorUserInfo: [String: Any] { [NSLocalizedDescriptionKey: description] }
|
||||
public var errorUserInfo: [String: Any] {
|
||||
var userInfo = [NSLocalizedDescriptionKey: description]
|
||||
if let message = message {
|
||||
userInfo[NSLocalizedFailureReasonErrorKey] = message
|
||||
}
|
||||
return userInfo
|
||||
}
|
||||
}
|
||||
+126
-317
@@ -1,5 +1,5 @@
|
||||
import Foundation
|
||||
import Dispatch
|
||||
import Foundation
|
||||
#if os(iOS)
|
||||
import UIKit
|
||||
#endif
|
||||
@@ -57,14 +57,17 @@ public final class DatabasePool: DatabaseWriter {
|
||||
readerConfiguration.allowsUnsafeTransactions = false
|
||||
|
||||
var readerCount = 0
|
||||
readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: {
|
||||
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
|
||||
return try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: readerConfiguration,
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "reader.\(readerCount)")
|
||||
})
|
||||
readerPool = Pool(
|
||||
maximumCount: configuration.maximumReaderCount,
|
||||
qos: configuration.readQoS,
|
||||
makeElement: {
|
||||
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
|
||||
return try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: readerConfiguration,
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "reader.\(readerCount)")
|
||||
})
|
||||
|
||||
// Activate WAL Mode unless readonly
|
||||
if !configuration.readonly {
|
||||
@@ -100,7 +103,9 @@ public final class DatabasePool: DatabaseWriter {
|
||||
// Be a nice iOS citizen, and don't consume too much memory
|
||||
// See https://github.com/groue/GRDB.swift/#memory-management
|
||||
#if os(iOS)
|
||||
setupMemoryManagement()
|
||||
if configuration.automaticMemoryManagement {
|
||||
setupMemoryManagement()
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -151,16 +156,9 @@ public final class DatabasePool: DatabaseWriter {
|
||||
|
||||
return configuration
|
||||
}
|
||||
|
||||
/// Blocks the current thread until all database connections have
|
||||
/// executed the *body* block.
|
||||
fileprivate func forEachConnection(_ body: (Database) -> Void) {
|
||||
writer.sync(body)
|
||||
readerPool?.forEach { $0.sync(body) }
|
||||
}
|
||||
}
|
||||
|
||||
#if swift(>=5.5) && canImport(_Concurrency)
|
||||
#if swift(>=5.6) && canImport(_Concurrency)
|
||||
// @unchecked because of databaseSnapshotCount and readerPool
|
||||
extension DatabasePool: @unchecked Sendable { }
|
||||
#endif
|
||||
@@ -169,19 +167,49 @@ extension DatabasePool {
|
||||
|
||||
// MARK: - Memory management
|
||||
|
||||
/// Free as much memory as possible.
|
||||
/// Frees as much memory as possible, by disposing non-essential memory from
|
||||
/// the writer connection, and closing all reader connections.
|
||||
///
|
||||
/// This method blocks the current thread until all database accesses
|
||||
/// are completed.
|
||||
/// This method is synchronous, and blocks the current thread until all
|
||||
/// database accesses are completed.
|
||||
///
|
||||
/// - warning: This method can prevent concurrent reads from executing,
|
||||
/// until it returns. Prefer ``releaseMemoryEventually()`` if you intend
|
||||
/// to keep on using the database while releasing memory.
|
||||
public func releaseMemory() {
|
||||
// Release writer memory
|
||||
writer.sync { $0.releaseMemory() }
|
||||
// Release readers memory by closing all connections
|
||||
|
||||
// Release readers memory by closing all connections.
|
||||
//
|
||||
// We must use a barrier in order to guarantee that memory has been
|
||||
// freed (reader connections closed) when the method exits, as
|
||||
// documented.
|
||||
//
|
||||
// Without the barrier, connections would only close _eventually_ (after
|
||||
// their eventual concurrent jobs have completed).
|
||||
readerPool?.barrier {
|
||||
readerPool?.removeAll()
|
||||
}
|
||||
}
|
||||
|
||||
/// Eventually frees as much memory as possible, by disposing non-essential
|
||||
/// memory from the writer connection, and closing all reader connections.
|
||||
///
|
||||
/// Unlike ``releaseMemory()``, this method does not prevent concurrent
|
||||
/// database accesses when it is executing. But it does not notify when
|
||||
/// non-essential memory has been freed.
|
||||
public func releaseMemoryEventually() {
|
||||
// Release readers memory by eventually closing all reader connections
|
||||
// (they will close after their current jobs have completed).
|
||||
readerPool?.removeAll()
|
||||
|
||||
// Release writer memory eventually.
|
||||
writer.async { db in
|
||||
db.releaseMemory()
|
||||
}
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
/// Listens to UIApplicationDidEnterBackgroundNotification and
|
||||
/// UIApplicationDidReceiveMemoryWarningNotification in order to release
|
||||
@@ -213,12 +241,20 @@ extension DatabasePool {
|
||||
|
||||
let task: UIBackgroundTaskIdentifier = application.beginBackgroundTask(expirationHandler: nil)
|
||||
if task == .invalid {
|
||||
// Perform releaseMemory() synchronously.
|
||||
// Release memory synchronously
|
||||
releaseMemory()
|
||||
} else {
|
||||
// Perform releaseMemory() asynchronously.
|
||||
DispatchQueue.global().async {
|
||||
self.releaseMemory()
|
||||
// Release memory eventually.
|
||||
//
|
||||
// We don't know when reader connections will be closed (because
|
||||
// they may be currently in use), so we don't quite know when
|
||||
// reader memory will be freed (which would be the ideal timing for
|
||||
// ending our background task).
|
||||
//
|
||||
// So let's just end the background task after the writer connection
|
||||
// has freed its memory. That's better than nothing.
|
||||
releaseMemoryEventually()
|
||||
writer.async { _ in
|
||||
application.endBackgroundTask(task)
|
||||
}
|
||||
}
|
||||
@@ -226,9 +262,7 @@ extension DatabasePool {
|
||||
|
||||
@objc
|
||||
private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
|
||||
DispatchQueue.global().async {
|
||||
self.releaseMemory()
|
||||
}
|
||||
releaseMemoryEventually()
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -330,88 +364,33 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
// First async jump in order to grab a reader connection.
|
||||
// Honor configuration dispatching (qos/targetQueue).
|
||||
let label = configuration.identifier(
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "asyncRead")
|
||||
configuration
|
||||
.makeDispatchQueue(label: label)
|
||||
.async {
|
||||
do {
|
||||
guard let readerPool = self.readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
guard let readerPool = self.readerPool else {
|
||||
value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")))
|
||||
return
|
||||
}
|
||||
|
||||
readerPool.asyncGet { result in
|
||||
do {
|
||||
let (reader, releaseReader) = try result.get()
|
||||
// Second async jump because that's how `Pool.async` has to be used.
|
||||
reader.async { db in
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader()
|
||||
}
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
|
||||
// Second async jump because sync could deadlock if
|
||||
// configuration has a serial targetQueue.
|
||||
reader.async { db in
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader()
|
||||
}
|
||||
do {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
value(.success(db))
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
do {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
value(.success(db))
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncRead(_ value: @escaping (Result<Database, Error>?) -> Void) {
|
||||
// First async jump in order to grab a reader connection.
|
||||
// Honor configuration dispatching (qos/targetQueue).
|
||||
let label = configuration.identifier(
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "asyncRead")
|
||||
configuration
|
||||
.makeDispatchQueue(label: label)
|
||||
.async { [weak self] in
|
||||
guard let self = self else {
|
||||
value(nil)
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
guard let readerPool = self.readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
|
||||
// Second async jump because sync could deadlock if
|
||||
// configuration has a serial targetQueue.
|
||||
reader.weakAsync { db in
|
||||
guard let db = db else {
|
||||
value(nil)
|
||||
return
|
||||
}
|
||||
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader()
|
||||
}
|
||||
do {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
value(.success(db))
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
@@ -429,38 +408,31 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
// First async jump in order to grab a reader connection.
|
||||
// Honor configuration dispatching (qos/targetQueue).
|
||||
let label = configuration.identifier(
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "asyncUnsafeRead")
|
||||
configuration
|
||||
.makeDispatchQueue(label: label)
|
||||
.async {
|
||||
do {
|
||||
guard let readerPool = self.readerPool else {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")
|
||||
guard let readerPool = self.readerPool else {
|
||||
value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")))
|
||||
return
|
||||
}
|
||||
|
||||
readerPool.asyncGet { result in
|
||||
do {
|
||||
let (reader, releaseReader) = try result.get()
|
||||
// Second async jump because that's how `Pool.async` has to be used.
|
||||
reader.async { db in
|
||||
defer {
|
||||
releaseReader()
|
||||
}
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
|
||||
// Second async jump because sync could deadlock if
|
||||
// configuration has a serial targetQueue.
|
||||
reader.async { db in
|
||||
defer {
|
||||
releaseReader()
|
||||
}
|
||||
do {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
value(.success(db))
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
do {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
value(.success(db))
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
@@ -748,11 +720,6 @@ extension DatabasePool: DatabaseReader {
|
||||
writer.async(updates)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncWriteWithoutTransaction(_ updates: @escaping (Database?) -> Void) {
|
||||
writer.weakAsync(updates)
|
||||
}
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// :nodoc:
|
||||
@@ -763,25 +730,26 @@ extension DatabasePool: DatabaseReader {
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
// The easy case: the database does not change
|
||||
return _addReadOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
}
|
||||
|
||||
if observation.requiresWriteAccess {
|
||||
let observer = _addWriteOnly(
|
||||
|
||||
} else if observation.requiresWriteAccess {
|
||||
// Observe from the writer database connection.
|
||||
return _addWriteOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
|
||||
} else {
|
||||
// DatabasePool can perform concurrent observation
|
||||
return _addConcurrent(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
return AnyDatabaseCancellable(cancel: observer.cancel)
|
||||
}
|
||||
|
||||
let observer = _addConcurrent(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
return AnyDatabaseCancellable(cancel: observer.cancel)
|
||||
}
|
||||
|
||||
/// A concurrent observation fetches the initial value without waiting for
|
||||
@@ -790,178 +758,19 @@ extension DatabasePool: DatabaseReader {
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> ValueObserver<Reducer> // For testability
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
|
||||
assert(!observation.requiresWriteAccess, "Use _addWriteOnly(observation:) instead")
|
||||
|
||||
let reduceQueueLabel = configuration.identifier(
|
||||
defaultLabel: "GRDB",
|
||||
purpose: "ValueObservation")
|
||||
let observer = ValueObserver(
|
||||
observation: observation,
|
||||
writer: self,
|
||||
let observer = ValueConcurrentObserver(
|
||||
dbPool: self,
|
||||
scheduler: scheduler,
|
||||
reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel),
|
||||
trackingMode: observation.trackingMode,
|
||||
reducer: observation.makeReducer(),
|
||||
events: observation.events,
|
||||
onChange: onChange)
|
||||
|
||||
// Starting a concurrent observation means that we'll fetch the initial
|
||||
// value right away, without waiting for an access to the writer queue,
|
||||
// and the opportunity to install a transaction observer.
|
||||
//
|
||||
// This is how DatabasePool can start an observation and promptly notify
|
||||
// an initial value, even when there is a long-running write transaction
|
||||
// in the background.
|
||||
//
|
||||
// We thus have to deal with the fact that between this initial fetch,
|
||||
// and the beginning of transaction tracking, any number of untracked
|
||||
// writes may occur.
|
||||
//
|
||||
// We must notify changes that happen during this untracked window. But
|
||||
// how do we spot them, since we're not tracking database changes yet?
|
||||
//
|
||||
// A safe solution is to always perform a second fetch. We may fetch the
|
||||
// same initial value, if no change did happen. But we don't miss
|
||||
// possible changes.
|
||||
//
|
||||
// We can avoid this second fetch when SQLite is compiled with the
|
||||
// SQLITE_ENABLE_SNAPSHOT option:
|
||||
//
|
||||
// 1. Perform the initial fetch in a DatabaseSnapshot. Its long running
|
||||
// transaction acquires a lock that will prevent checkpointing until we
|
||||
// get a writer access, so that we can reliably compare database
|
||||
// versions with `sqlite3_snapshot`:
|
||||
// https://www.sqlite.org/c3ref/snapshot.html.
|
||||
//
|
||||
// 2. Get a writer access, and compare the versions of the initial
|
||||
// snapshot, and the current state of the database: if versions are
|
||||
// identical, we can avoid the second fetch. If they are not, we perform
|
||||
// the second fetch, even if the actual changes are unrelated to the
|
||||
// tracked database region (we have no way to know).
|
||||
//
|
||||
// 3. Install the transaction observer.
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
let initialSnapshot = try makeSnapshot()
|
||||
let initialValue = try initialSnapshot.read(observer.fetchInitialValue)
|
||||
onChange(initialValue)
|
||||
add(observer: observer, from: initialSnapshot)
|
||||
} catch {
|
||||
observer.complete()
|
||||
observation.events.didFail?(error)
|
||||
}
|
||||
} else {
|
||||
let label = configuration.identifier(
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "ValueObservation")
|
||||
configuration
|
||||
.makeDispatchQueue(label: label)
|
||||
.async { [weak self] in
|
||||
guard let self = self else { return }
|
||||
if observer.isCompleted { return }
|
||||
|
||||
do {
|
||||
let initialSnapshot = try self.makeSnapshot()
|
||||
let initialValue = try initialSnapshot.read(observer.fetchInitialValue)
|
||||
observer.notifyChange(initialValue)
|
||||
self.add(observer: observer, from: initialSnapshot)
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
#else
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
let initialValue = try read(observer.fetchInitialValue)
|
||||
onChange(initialValue)
|
||||
addObserver(observer: observer)
|
||||
} catch {
|
||||
observer.complete()
|
||||
observation.events.didFail?(error)
|
||||
}
|
||||
} else {
|
||||
_weakAsyncRead { [weak self] dbResult in
|
||||
guard let self = self, let dbResult = dbResult else { return }
|
||||
if observer.isCompleted { return }
|
||||
|
||||
do {
|
||||
let initialValue = try observer.fetchInitialValue(dbResult.get())
|
||||
observer.notifyChange(initialValue)
|
||||
self.addObserver(observer: observer)
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
return observer
|
||||
return observer.start()
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT
|
||||
// Support for _addConcurrent(observation:)
|
||||
private func add<Reducer: ValueReducer>(
|
||||
observer: ValueObserver<Reducer>,
|
||||
from initialSnapshot: DatabaseSnapshot)
|
||||
{
|
||||
_weakAsyncWriteWithoutTransaction { db in
|
||||
guard let db = db else { return }
|
||||
if observer.isCompleted { return }
|
||||
|
||||
do {
|
||||
// Transaction is needed for version snapshotting
|
||||
try db.inTransaction(.deferred) {
|
||||
// Keep DatabaseSnaphot alive until we have compared
|
||||
// database versions. It prevents database checkpointing,
|
||||
// and keeps versions (`sqlite3_snapshot`) valid
|
||||
// and comparable.
|
||||
let fetchNeeded: Bool = try withExtendedLifetime(initialSnapshot) {
|
||||
guard let initialVersion = initialSnapshot.version else {
|
||||
return true
|
||||
}
|
||||
return try db.wasChanged(since: initialVersion)
|
||||
}
|
||||
|
||||
if fetchNeeded {
|
||||
observer.events.databaseDidChange?()
|
||||
if let value = try observer.fetchValue(db) {
|
||||
observer.notifyChange(value)
|
||||
}
|
||||
}
|
||||
return .commit
|
||||
}
|
||||
|
||||
// Now we can start observation
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
#else
|
||||
// Support for _addConcurrent(observation:)
|
||||
private func addObserver<Reducer: ValueReducer>(observer: ValueObserver<Reducer>) {
|
||||
_weakAsyncWriteWithoutTransaction { db in
|
||||
guard let db = db else { return }
|
||||
if observer.isCompleted { return }
|
||||
|
||||
do {
|
||||
observer.events.databaseDidChange?()
|
||||
if let value = try observer.fetchValue(db) {
|
||||
observer.notifyChange(value)
|
||||
}
|
||||
|
||||
// Now we can start observation
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
@@ -43,7 +43,9 @@ public final class DatabaseQueue: DatabaseWriter {
|
||||
// Be a nice iOS citizen, and don't consume too much memory
|
||||
// See https://github.com/groue/GRDB.swift/#memory-management
|
||||
#if os(iOS)
|
||||
setupMemoryManagement()
|
||||
if configuration.automaticMemoryManagement {
|
||||
setupMemoryManagement()
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -117,12 +119,12 @@ extension DatabaseQueue {
|
||||
|
||||
let task: UIBackgroundTaskIdentifier = application.beginBackgroundTask(expirationHandler: nil)
|
||||
if task == .invalid {
|
||||
// Perform releaseMemory() synchronously.
|
||||
// Release memory synchronously
|
||||
releaseMemory()
|
||||
} else {
|
||||
// Perform releaseMemory() asynchronously.
|
||||
DispatchQueue.global().async {
|
||||
self.releaseMemory()
|
||||
// Release memory asynchronously
|
||||
writer.async { db in
|
||||
db.releaseMemory()
|
||||
application.endBackgroundTask(task)
|
||||
}
|
||||
}
|
||||
@@ -130,8 +132,8 @@ extension DatabaseQueue {
|
||||
|
||||
@objc
|
||||
private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
|
||||
DispatchQueue.global().async {
|
||||
self.releaseMemory()
|
||||
writer.async { db in
|
||||
db.releaseMemory()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -212,32 +214,6 @@ extension DatabaseQueue {
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncRead(_ value: @escaping (Result<Database, Error>?) -> Void) {
|
||||
writer.weakAsync { db in
|
||||
guard let db = db else {
|
||||
value(nil)
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
// The transaction guarantees snapshot isolation against eventual
|
||||
// external connection.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.beginReadOnly()
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
return
|
||||
}
|
||||
|
||||
value(.success(db))
|
||||
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.endReadOnly()
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) rethrows -> T {
|
||||
try writer.sync(value)
|
||||
}
|
||||
@@ -366,11 +342,6 @@ extension DatabaseQueue {
|
||||
writer.async(updates)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncWriteWithoutTransaction(_ updates: @escaping (Database?) -> Void) {
|
||||
writer.weakAsync(updates)
|
||||
}
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// :nodoc:
|
||||
@@ -381,16 +352,17 @@ extension DatabaseQueue {
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
// The easy case: the database does not change
|
||||
return _addReadOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
} else {
|
||||
// Observe from the writer database connection.
|
||||
return _addWriteOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
}
|
||||
|
||||
let observer = _addWriteOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
return AnyDatabaseCancellable(cancel: observer.cancel)
|
||||
}
|
||||
}
|
||||
@@ -178,11 +178,6 @@ public protocol DatabaseReader: AnyObject, GRDBSendable {
|
||||
/// that would prevent establishing the read access to the database.
|
||||
func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void)
|
||||
|
||||
/// Same as asyncRead, but without retaining self
|
||||
///
|
||||
/// :nodoc:
|
||||
func _weakAsyncRead(_ value: @escaping (Result<Database, Error>?) -> Void)
|
||||
|
||||
/// Synchronously executes a function that accepts a database
|
||||
/// connection, and returns its result.
|
||||
///
|
||||
@@ -376,7 +371,7 @@ extension DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=5.5.2) && canImport(_Concurrency)
|
||||
#if compiler(>=5.6) && canImport(_Concurrency)
|
||||
extension DatabaseReader {
|
||||
// MARK: - Asynchronous Database Access
|
||||
|
||||
@@ -566,6 +561,8 @@ extension DatabaseReader {
|
||||
{
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
// Perform a reentrant read, in case the observation would be
|
||||
// started from a database access.
|
||||
let value = try unsafeReentrantRead { db in
|
||||
try db.isolated(readOnly: true) {
|
||||
try observation.fetchValue(db)
|
||||
@@ -575,13 +572,11 @@ extension DatabaseReader {
|
||||
} catch {
|
||||
observation.events.didFail?(error)
|
||||
}
|
||||
return AnyDatabaseCancellable(cancel: { })
|
||||
return AnyDatabaseCancellable(cancel: { /* nothing to cancel */ })
|
||||
} else {
|
||||
var isCancelled = false
|
||||
_weakAsyncRead { dbResult in
|
||||
guard !isCancelled,
|
||||
let dbResult = dbResult
|
||||
else { return }
|
||||
asyncRead { dbResult in
|
||||
guard !isCancelled else { return }
|
||||
|
||||
let result = dbResult.flatMap { db in
|
||||
Result { try observation.fetchValue(db) }
|
||||
@@ -638,11 +633,6 @@ public final class AnyDatabaseReader: DatabaseReader {
|
||||
base.asyncRead(value)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncRead(_ value: @escaping (Result<Database, Error>?) -> Void) {
|
||||
base._weakAsyncRead(value)
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try base.unsafeRead(value)
|
||||
|
||||
@@ -269,7 +269,7 @@ extension DatabaseRegion {
|
||||
}
|
||||
return tableRegions
|
||||
.sorted(by: { (l, r) in l.key.rawValue < r.key.rawValue })
|
||||
.map({ (table, tableRegion) in
|
||||
.map { (table, tableRegion) in
|
||||
var desc = table.rawValue
|
||||
if let columns = tableRegion.columns {
|
||||
desc += "(" + columns.map(\.rawValue).sorted().joined(separator: ",") + ")"
|
||||
@@ -280,7 +280,7 @@ extension DatabaseRegion {
|
||||
desc += "[" + rowIds.sorted().map { "\($0)" }.joined(separator: ",") + "]"
|
||||
}
|
||||
return desc
|
||||
})
|
||||
}
|
||||
.joined(separator: ",")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ extension DatabaseRegionObservation {
|
||||
/// on subscription.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func publisher(in writer: DatabaseWriter) -> DatabasePublishers.DatabaseRegion {
|
||||
return DatabasePublishers.DatabaseRegion(self, in: writer)
|
||||
DatabasePublishers.DatabaseRegion(self, in: writer)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -14,14 +14,6 @@ public final class DatabaseSnapshot: DatabaseReader {
|
||||
serializedDatabase.configuration
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT
|
||||
typealias Version = UnsafeMutablePointer<sqlite3_snapshot>
|
||||
// Support for ValueObservation in DatabasePool
|
||||
let version: Version?
|
||||
#else
|
||||
typealias Version = Void
|
||||
#endif
|
||||
|
||||
init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws {
|
||||
var configuration = DatabasePool.readerConfiguration(configuration)
|
||||
configuration.allowsUnsafeTransactions = true // Snaphost keeps a long-lived transaction
|
||||
@@ -31,8 +23,8 @@ public final class DatabaseSnapshot: DatabaseReader {
|
||||
configuration: configuration,
|
||||
defaultLabel: defaultLabel,
|
||||
purpose: purpose)
|
||||
|
||||
let version: Version? = try serializedDatabase.sync { db in
|
||||
|
||||
try serializedDatabase.sync { db in
|
||||
// Assert WAL mode
|
||||
let journalMode = try String.fetchOne(db, sql: "PRAGMA journal_mode")
|
||||
guard journalMode == "wal" else {
|
||||
@@ -44,29 +36,12 @@ public final class DatabaseSnapshot: DatabaseReader {
|
||||
|
||||
// Acquire snapshot isolation
|
||||
try db.internalCachedStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next()
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT
|
||||
// We must expect an error: https://www.sqlite.org/c3ref/snapshot_get.html
|
||||
// > At least one transaction must be written to it first.
|
||||
return try? db.takeVersionSnapshot()
|
||||
#else
|
||||
return nil
|
||||
#endif
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT
|
||||
self.version = version
|
||||
#endif
|
||||
}
|
||||
|
||||
deinit {
|
||||
// Leave snapshot isolation
|
||||
serializedDatabase.reentrantSync { db in
|
||||
#if SQLITE_ENABLE_SNAPSHOT
|
||||
if let version = version {
|
||||
sqlite3_snapshot_free(version)
|
||||
}
|
||||
#endif
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
@@ -95,11 +70,6 @@ extension DatabaseSnapshot {
|
||||
serializedDatabase.async { value(.success($0)) }
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncRead(_ value: @escaping (Result<Database, Error>?) -> Void) {
|
||||
serializedDatabase.weakAsync { value($0.map { .success($0) }) }
|
||||
}
|
||||
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) rethrows -> T {
|
||||
try serializedDatabase.sync(value)
|
||||
}
|
||||
|
||||
@@ -159,7 +159,7 @@ extension DatabaseValue: StatementBinding {
|
||||
|
||||
extension DatabaseValue: GRDBSendable { }
|
||||
|
||||
#if swift(>=5.5) && canImport(_Concurrency)
|
||||
#if swift(>=5.6) && canImport(_Concurrency)
|
||||
// @unchecked due to Foundation.Data not conforming to Sendable
|
||||
// TODO: Remove @unchecked when Foundation has been upgraded
|
||||
extension DatabaseValue.Storage: @unchecked Sendable { }
|
||||
|
||||
@@ -134,12 +134,6 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// in a transaction.
|
||||
func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
|
||||
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, without retaining self.
|
||||
///
|
||||
/// :nodoc:
|
||||
func _weakAsyncWriteWithoutTransaction(_ updates: @escaping (Database?) -> Void)
|
||||
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, and returns the result.
|
||||
///
|
||||
@@ -299,9 +293,7 @@ extension DatabaseWriter {
|
||||
}
|
||||
|
||||
public func remove(transactionObserver: TransactionObserver) {
|
||||
_weakAsyncWriteWithoutTransaction {
|
||||
$0?.remove(transactionObserver: transactionObserver)
|
||||
}
|
||||
writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) }
|
||||
}
|
||||
|
||||
// MARK: - Erasing the content of the database
|
||||
@@ -366,56 +358,29 @@ extension DatabaseWriter {
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// A write-only observation only uses the serialized writer
|
||||
/// Starts an observation that fetches fresh database values synchronously,
|
||||
/// from the writer database connection, right after the database
|
||||
/// was modified.
|
||||
func _addWriteOnly<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> ValueObserver<Reducer> // For testability
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
|
||||
|
||||
let reduceQueueLabel = configuration.identifier(
|
||||
defaultLabel: "GRDB",
|
||||
purpose: "ValueObservation")
|
||||
let observer = ValueObserver(
|
||||
observation: observation,
|
||||
let observer = ValueWriteOnlyObserver(
|
||||
writer: self,
|
||||
scheduler: scheduler,
|
||||
reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel),
|
||||
readOnly: !observation.requiresWriteAccess,
|
||||
trackingMode: observation.trackingMode,
|
||||
reducer: observation.makeReducer(),
|
||||
events: observation.events,
|
||||
onChange: onChange)
|
||||
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
let initialValue: Reducer.Value = try unsafeReentrantWrite { db in
|
||||
let initialValue = try observer.fetchInitialValue(db)
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
return initialValue
|
||||
}
|
||||
onChange(initialValue)
|
||||
} catch {
|
||||
observer.complete()
|
||||
observation.events.didFail?(error)
|
||||
}
|
||||
} else {
|
||||
_weakAsyncWriteWithoutTransaction { db in
|
||||
guard let db = db else { return }
|
||||
if observer.isCompleted { return }
|
||||
do {
|
||||
let initialValue = try observer.fetchInitialValue(db)
|
||||
observer.notifyChange(initialValue)
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return observer
|
||||
return observer.start()
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=5.5.2) && canImport(_Concurrency)
|
||||
#if compiler(>=5.6) && canImport(_Concurrency)
|
||||
extension DatabaseWriter {
|
||||
// MARK: - Asynchronous Database Access
|
||||
|
||||
@@ -576,11 +541,11 @@ extension DatabaseWriter {
|
||||
-> DatabasePublishers.Write<Output>
|
||||
where S: Scheduler
|
||||
{
|
||||
OnDemandFuture({ fulfill in
|
||||
OnDemandFuture { fulfill in
|
||||
self.asyncWrite(updates, completion: { _, result in
|
||||
fulfill(result)
|
||||
})
|
||||
})
|
||||
}
|
||||
// We don't want users to process emitted values on a
|
||||
// database dispatch queue.
|
||||
.receiveValues(on: scheduler)
|
||||
@@ -629,7 +594,7 @@ extension DatabaseWriter {
|
||||
-> DatabasePublishers.Write<Output>
|
||||
where S: Scheduler
|
||||
{
|
||||
OnDemandFuture({ fulfill in
|
||||
OnDemandFuture { fulfill in
|
||||
self.asyncWriteWithoutTransaction { db in
|
||||
var updatesValue: T?
|
||||
do {
|
||||
@@ -645,7 +610,7 @@ extension DatabaseWriter {
|
||||
fulfill(dbResult.flatMap { db in Result { try value(db, updatesValue!) } })
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
// We don't want users to process emitted values on a
|
||||
// database dispatch queue.
|
||||
.receiveValues(on: scheduler)
|
||||
@@ -760,11 +725,6 @@ public final class AnyDatabaseWriter: DatabaseWriter {
|
||||
base.asyncRead(value)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncRead(_ value: @escaping (Result<Database, Error>?) -> Void) {
|
||||
base._weakAsyncRead(value)
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try base.unsafeRead(value)
|
||||
@@ -819,11 +779,6 @@ public final class AnyDatabaseWriter: DatabaseWriter {
|
||||
base.asyncWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _weakAsyncWriteWithoutTransaction(_ updates: @escaping (Database?) -> Void) {
|
||||
base._weakAsyncWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try base.unsafeReentrantWrite(updates)
|
||||
}
|
||||
|
||||
+14
-14
@@ -287,7 +287,7 @@ extension Row {
|
||||
/// The result is nil if the row does not contain the column.
|
||||
public subscript(_ columnName: String) -> DatabaseValueConvertible? {
|
||||
// IMPLEMENTATION NOTE
|
||||
// This method has a single know use case: checking if the value is nil,
|
||||
// This method has a single known use case: checking if the value is nil,
|
||||
// as in:
|
||||
//
|
||||
// if row["foo"] != nil { ... }
|
||||
@@ -1285,7 +1285,7 @@ extension Row {
|
||||
throws -> [Row]
|
||||
{
|
||||
// The cursor reuses a single mutable row. Return immutable copies.
|
||||
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter).map { $0.copy() })
|
||||
try Array(fetchCursor(statement, arguments: arguments, adapter: adapter).map { $0.copy() })
|
||||
}
|
||||
|
||||
/// Returns a set of rows fetched from a prepared statement.
|
||||
@@ -1306,7 +1306,7 @@ extension Row {
|
||||
throws -> Set<Row>
|
||||
{
|
||||
// The cursor reuses a single mutable row. Return immutable copies.
|
||||
return try Set(fetchCursor(statement, arguments: arguments, adapter: adapter).map { $0.copy() })
|
||||
try Set(fetchCursor(statement, arguments: arguments, adapter: adapter).map { $0.copy() })
|
||||
}
|
||||
|
||||
/// Returns a single row fetched from a prepared statement.
|
||||
@@ -2089,27 +2089,27 @@ protocol RowImpl {
|
||||
extension RowImpl {
|
||||
func copiedRow(_ row: Row) -> Row {
|
||||
// unless customized, assume unsafe and unadapted row
|
||||
return Row(impl: ArrayRowImpl(columns: Array(row)))
|
||||
Row(impl: ArrayRowImpl(columns: Array(row)))
|
||||
}
|
||||
|
||||
func unscopedRow(_ row: Row) -> Row {
|
||||
// unless customized, assume unadapted row (see AdaptedRowImpl for customization)
|
||||
return row
|
||||
row
|
||||
}
|
||||
|
||||
func unadaptedRow(_ row: Row) -> Row {
|
||||
// unless customized, assume unadapted row (see AdaptedRowImpl for customization)
|
||||
return row
|
||||
row
|
||||
}
|
||||
|
||||
func scopes(prefetchedRows: Row.PrefetchedRowsView) -> Row.ScopesView {
|
||||
// unless customized, assume unuscoped row (see AdaptedRowImpl for customization)
|
||||
return Row.ScopesView()
|
||||
Row.ScopesView()
|
||||
}
|
||||
|
||||
func hasNull(atUncheckedIndex index: Int) -> Bool {
|
||||
// unless customized, use slow check (see StatementRowImpl and AdaptedRowImpl for customization)
|
||||
return databaseValue(atUncheckedIndex: index).isNull
|
||||
databaseValue(atUncheckedIndex: index).isNull
|
||||
}
|
||||
|
||||
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
@@ -2118,7 +2118,7 @@ extension RowImpl {
|
||||
throws -> Value
|
||||
{
|
||||
// unless customized, use slow decoding (see StatementRowImpl and AdaptedRowImpl for customization)
|
||||
return try Value.decode(
|
||||
try Value.decode(
|
||||
fromDatabaseValue: databaseValue(atUncheckedIndex: index),
|
||||
context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index)))
|
||||
}
|
||||
@@ -2129,21 +2129,21 @@ extension RowImpl {
|
||||
throws -> Value?
|
||||
{
|
||||
// unless customized, use slow decoding (see StatementRowImpl and AdaptedRowImpl for customization)
|
||||
return try Value.decodeIfPresent(
|
||||
try Value.decodeIfPresent(
|
||||
fromDatabaseValue: databaseValue(atUncheckedIndex: index),
|
||||
context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index)))
|
||||
}
|
||||
|
||||
func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data {
|
||||
// unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization)
|
||||
return try Data.decode(
|
||||
try Data.decode(
|
||||
fromDatabaseValue: databaseValue(atUncheckedIndex: index),
|
||||
context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index)))
|
||||
}
|
||||
|
||||
func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? {
|
||||
// unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization)
|
||||
return try Data.decodeIfPresent(
|
||||
try Data.decodeIfPresent(
|
||||
fromDatabaseValue: databaseValue(atUncheckedIndex: index),
|
||||
context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index)))
|
||||
}
|
||||
@@ -2182,7 +2182,7 @@ struct ArrayRowImpl: RowImpl {
|
||||
}
|
||||
}
|
||||
|
||||
#if swift(>=5.5) && canImport(_Concurrency)
|
||||
#if swift(>=5.6) && canImport(_Concurrency)
|
||||
// @unchecked because columns property is not inferred as Sendable
|
||||
// TODO: remove this @unchecked when compiler can handle tuples.
|
||||
extension ArrayRowImpl: @unchecked Sendable { }
|
||||
@@ -2254,7 +2254,7 @@ private struct StatementRowImpl: RowImpl {
|
||||
|
||||
func hasNull(atUncheckedIndex index: Int) -> Bool {
|
||||
// Avoid extracting values, because this modifies the SQLite statement.
|
||||
return sqlite3_column_type(sqliteStatement, Int32(index)) == SQLITE_NULL
|
||||
sqlite3_column_type(sqliteStatement, Int32(index)) == SQLITE_NULL
|
||||
}
|
||||
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
|
||||
|
||||
@@ -185,9 +185,11 @@ public protocol _RowAdapter {
|
||||
/// GRDB ships with four concrete types that adopt the RowAdapter protocol:
|
||||
///
|
||||
/// - `ColumnMapping`: renames row columns
|
||||
/// - `SuffixRowAdapter`: hides the first columns of a row
|
||||
/// - `RangeRowAdapter`: only exposes a range of columns
|
||||
/// - `EmptyRowAdapter`: hides all columns
|
||||
/// - `RangeRowAdapter`: exposes a range of columns
|
||||
/// - `RenameColumnAdapter`: transforms column names with a function
|
||||
/// - `ScopeAdapter`: defines row scopes
|
||||
/// - `SuffixRowAdapter`: hides the first columns of a row
|
||||
///
|
||||
/// To use a row adapter, provide it to any method that fetches:
|
||||
///
|
||||
|
||||
@@ -49,7 +49,13 @@ final class SchedulingWatchdog {
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
{
|
||||
GRDBPrecondition(current?.allows(db) ?? false, message(), file: file, line: line)
|
||||
GRDBPrecondition(allows(db), message(), file: file, line: line)
|
||||
}
|
||||
|
||||
/// Returns true iff the database argument can be used in the current
|
||||
/// dispatch queue.
|
||||
static func allows(_ db: Database) -> Bool {
|
||||
current?.allows(db) ?? false
|
||||
}
|
||||
|
||||
static var current: SchedulingWatchdog? {
|
||||
|
||||
@@ -47,7 +47,11 @@ final class SerializedDatabase {
|
||||
path: path,
|
||||
description: identifier,
|
||||
configuration: config)
|
||||
self.queue = configuration.makeDispatchQueue(label: identifier)
|
||||
if config.readonly {
|
||||
self.queue = configuration.makeReaderDispatchQueue(label: identifier)
|
||||
} else {
|
||||
self.queue = configuration.makeWriterDispatchQueue(label: identifier)
|
||||
}
|
||||
SchedulingWatchdog.allowDatabase(db, onQueue: queue)
|
||||
try queue.sync {
|
||||
do {
|
||||
@@ -193,19 +197,6 @@ final class SerializedDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Asynchronously executes a block in the serialized dispatch queue,
|
||||
/// without retaining self.
|
||||
func weakAsync(_ block: @escaping (Database?) -> Void) {
|
||||
queue.async { [weak self] in
|
||||
if let self = self {
|
||||
block(self.db)
|
||||
self.preconditionNoUnsafeTransactionLeft(self.db)
|
||||
} else {
|
||||
block(nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if any only if the current dispatch queue is valid.
|
||||
var onValidQueue: Bool {
|
||||
SchedulingWatchdog.current?.allows(db) ?? false
|
||||
@@ -258,7 +249,7 @@ final class SerializedDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
#if swift(>=5.5) && canImport(_Concurrency)
|
||||
#if swift(>=5.6) && canImport(_Concurrency)
|
||||
// @unchecked because the wrapped `Database` itself is not Sendable.
|
||||
// It happens the job of SerializedDatabase is precisely to provide thread-safe
|
||||
// access to `Database`.
|
||||
|
||||
+58
-76
@@ -87,24 +87,26 @@ public final class Statement {
|
||||
{
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
|
||||
let authorizer = StatementCompilationAuthorizer()
|
||||
// Reset authorizer before preparing the statement
|
||||
let authorizer = database.authorizer
|
||||
authorizer.reset()
|
||||
|
||||
var sqliteStatement: SQLiteStatement? = nil
|
||||
let code: Int32 = database.withAuthorizer(authorizer) {
|
||||
// sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
return sqlite3_prepare_v3(
|
||||
let code: Int32
|
||||
// sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
code = sqlite3_prepare_v3(
|
||||
database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags),
|
||||
&sqliteStatement, statementEnd)
|
||||
#else
|
||||
if #available(iOS 12.0, OSX 10.14, tvOS 12.0, watchOS 5.0, *) {
|
||||
code = sqlite3_prepare_v3(
|
||||
database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags),
|
||||
&sqliteStatement, statementEnd)
|
||||
#else
|
||||
if #available(iOS 12.0, OSX 10.14, tvOS 12.0, watchOS 5.0, *) {
|
||||
return sqlite3_prepare_v3(
|
||||
database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags),
|
||||
&sqliteStatement, statementEnd)
|
||||
} else {
|
||||
return sqlite3_prepare_v2(database.sqliteConnection, statementStart, -1, &sqliteStatement, statementEnd)
|
||||
}
|
||||
#endif
|
||||
} else {
|
||||
code = sqlite3_prepare_v2(database.sqliteConnection, statementStart, -1, &sqliteStatement, statementEnd)
|
||||
}
|
||||
#endif
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(
|
||||
@@ -296,33 +298,52 @@ public final class Statement {
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func execute(arguments: StatementArguments? = nil) throws {
|
||||
try reset(withArguments: arguments)
|
||||
try database.withAuthorizer(database.statementWillExecute(self)) {
|
||||
// Iterate all rows, since they may execute side effects.
|
||||
while true {
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
try database.statementDidExecute(self)
|
||||
return
|
||||
case SQLITE_ROW:
|
||||
break
|
||||
case let code:
|
||||
try database.statementDidFail(self, withResultCode: code)
|
||||
}
|
||||
try database.statementWillExecute(self)
|
||||
|
||||
// Iterate all rows, since they may execute side effects.
|
||||
while true {
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
try database.statementDidExecute(self)
|
||||
return
|
||||
case SQLITE_ROW:
|
||||
break
|
||||
case let code:
|
||||
try database.statementDidFail(self, withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls the given closure after each successful call to `sqlite3_step()`.
|
||||
///
|
||||
/// This method is slighly faster than calling `step(_:)` repeatedly, due
|
||||
/// to the single `sqlite3_stmt_busy` check.
|
||||
@usableFromInline
|
||||
func forEachStep(_ body: (SQLiteStatement) throws -> Void) throws {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
|
||||
if sqlite3_stmt_busy(sqliteStatement) == 0 {
|
||||
try database.statementWillExecute(self)
|
||||
}
|
||||
|
||||
while true {
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
try database.statementDidExecute(self)
|
||||
return
|
||||
case SQLITE_ROW:
|
||||
try body(sqliteStatement)
|
||||
case let code:
|
||||
try database.statementDidFail(self, withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls the given closure after one successful call to `sqlite3_step()`.
|
||||
///
|
||||
/// This method is unable to deal with statements that need a specific
|
||||
/// authorizer. See `forEachStep(_:)`.
|
||||
@usableFromInline
|
||||
func step<Element>(_ body: (SQLiteStatement) throws -> Element) throws -> Element? {
|
||||
// This check takes 0 time when profiled. It is, practically speaking, free.
|
||||
func step<T>(_ body: (SQLiteStatement) throws -> T) throws -> T? {
|
||||
if sqlite3_stmt_busy(sqliteStatement) == 0 {
|
||||
guard try database.statementWillExecute(self) == nil else {
|
||||
fatalError("Can't execute step by step a statement that requires a customized authorizer.")
|
||||
}
|
||||
try database.statementWillExecute(self)
|
||||
}
|
||||
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
@@ -335,44 +356,6 @@ public final class Statement {
|
||||
try database.statementDidFail(self, withResultCode: code)
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls the given closure after each successful call to `sqlite3_step()`.
|
||||
///
|
||||
/// Unlike multiple calls to `step(_:)`, this method is able to deal with
|
||||
/// statements that need a specific authorizer.
|
||||
///
|
||||
/// That's how we deal with TransactionObservers that observe deletion:
|
||||
/// the authorizer prevents the truncate optimization
|
||||
/// <https://www.sqlite.org/lang_delete.html#the_truncate_optimization>.
|
||||
///
|
||||
/// That's also how we deal with <https://github.com/groue/GRDB.swift/issues/1124>,
|
||||
/// in four steps:
|
||||
///
|
||||
/// 1. `T.fetchAll(...)` calls `Array(T.fetchCursor(...))`
|
||||
/// 2. `Array(T.fetchCursor(...))` calls `Cursor.forEach(...)`
|
||||
/// 3. `DatabaseCursor.forEach(...)` calls `Statement.forEachStep(...)`
|
||||
/// 4. `Statement.forEachStep(...)` deals with the eventual authorizer.
|
||||
@usableFromInline
|
||||
func forEachStep(_ body: (SQLiteStatement) throws -> Void) throws {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
guard sqlite3_stmt_busy(sqliteStatement) == 0 else {
|
||||
// We can't deal with possible authorizer
|
||||
fatalError("Statement is busy")
|
||||
}
|
||||
try database.withAuthorizer(database.statementWillExecute(self)) {
|
||||
while true {
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
try database.statementDidExecute(self)
|
||||
return
|
||||
case SQLITE_ROW:
|
||||
try body(sqliteStatement)
|
||||
case let code:
|
||||
try database.statementDidFail(self, withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "Statement")
|
||||
@@ -383,7 +366,7 @@ public typealias UpdateStatement = Statement
|
||||
|
||||
extension Statement: CustomStringConvertible {
|
||||
public var description: String {
|
||||
"SQL: \(sql), Arguments: \(arguments)"
|
||||
SchedulingWatchdog.allows(database) ? sql : "Statement"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -443,9 +426,8 @@ extension DatabaseCursor {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Specific implementation of `forEach` in order to deal with
|
||||
// <https://github.com/groue/GRDB.swift/issues/1124>.
|
||||
// See `Statement.forEachStep(_:)` for more information.
|
||||
/// Specific implementation of `forEach`, for a slight performance
|
||||
/// improvement due to the single `sqlite3_stmt_busy` check.
|
||||
@inlinable
|
||||
public func forEach(_ body: (Element) throws -> Void) throws {
|
||||
if _isDone { return }
|
||||
|
||||
@@ -2,29 +2,19 @@
|
||||
import Glibc
|
||||
#endif
|
||||
|
||||
/// A protocol around sqlite3_set_authorizer
|
||||
@usableFromInline
|
||||
protocol StatementAuthorizer: AnyObject {
|
||||
func authorize(
|
||||
_ actionCode: Int32,
|
||||
_ cString1: UnsafePointer<Int8>?,
|
||||
_ cString2: UnsafePointer<Int8>?,
|
||||
_ cString3: UnsafePointer<Int8>?,
|
||||
_ cString4: UnsafePointer<Int8>?)
|
||||
-> Int32
|
||||
}
|
||||
|
||||
/// A class that gathers information about one statement during its compilation.
|
||||
final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
final class StatementAuthorizer {
|
||||
private unowned var database: Database
|
||||
|
||||
/// What this statements reads
|
||||
var selectedRegion = DatabaseRegion()
|
||||
|
||||
/// What this statements writes
|
||||
var databaseEventKinds: [DatabaseEventKind] = []
|
||||
|
||||
/// True if a statement alter the schema in a way that required schema cache
|
||||
/// invalidation. For example, adding a column to a table invalidates the
|
||||
/// schema cache, but not creating a table.
|
||||
/// True if a statement alters the schema in a way that requires
|
||||
/// invalidation of the schema cache. For example, adding a column to a
|
||||
/// table invalidates the schema cache.
|
||||
var invalidatesDatabaseSchemaCache = false
|
||||
|
||||
/// Not nil if a statement is a BEGIN/COMMIT/ROLLBACK/RELEASE transaction or
|
||||
@@ -33,6 +23,19 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
|
||||
private var isDropStatement = false
|
||||
|
||||
init(_ database: Database) {
|
||||
self.database = database
|
||||
}
|
||||
|
||||
/// Reset before compiling a new statement
|
||||
func reset() {
|
||||
selectedRegion = DatabaseRegion()
|
||||
databaseEventKinds = []
|
||||
invalidatesDatabaseSchemaCache = false
|
||||
transactionEffect = nil
|
||||
isDropStatement = false
|
||||
}
|
||||
|
||||
func authorize(
|
||||
_ actionCode: Int32,
|
||||
_ cString1: UnsafePointer<Int8>?,
|
||||
@@ -43,7 +46,7 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
{
|
||||
// Uncomment when debugging
|
||||
// print("""
|
||||
// StatementCompilationAuthorizer: \
|
||||
// StatementAuthorizer: \
|
||||
// \(AuthorizerActionCode(rawValue: actionCode)) \
|
||||
// \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) }.joined(separator: ", "))
|
||||
// """)
|
||||
@@ -94,10 +97,16 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
guard strcmp(cString1, "sqlite_master") != 0 else { return SQLITE_OK }
|
||||
guard strcmp(cString1, "sqlite_temp_master") != 0 else { return SQLITE_OK }
|
||||
|
||||
let tableName = String(cString: cString1)
|
||||
databaseEventKinds.append(.delete(tableName: tableName))
|
||||
|
||||
// Now we prevent the truncate optimization so that transaction
|
||||
// observers are notified of individual row deletions.
|
||||
databaseEventKinds.append(.delete(tableName: String(cString: cString1)))
|
||||
return SQLITE_IGNORE
|
||||
if database.observationBroker.observesDeletions(on: tableName) {
|
||||
return SQLITE_IGNORE
|
||||
} else {
|
||||
return SQLITE_OK
|
||||
}
|
||||
|
||||
case SQLITE_UPDATE:
|
||||
guard let tableName = cString1.map(String.init) else { return SQLITE_OK }
|
||||
@@ -176,30 +185,6 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
}
|
||||
}
|
||||
|
||||
/// This authorizer prevents the [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
|
||||
/// which makes transaction observers unable to observe individual deletions
|
||||
/// when user runs `DELETE FROM t` statements.
|
||||
//
|
||||
/// Warning: to perform well, this authorizer must be used during statement
|
||||
/// execution, not during statement compilation.
|
||||
final class TruncateOptimizationBlocker: StatementAuthorizer {
|
||||
func authorize(
|
||||
_ actionCode: Int32,
|
||||
_ cString1: UnsafePointer<Int8>?,
|
||||
_ cString2: UnsafePointer<Int8>?,
|
||||
_ cString3: UnsafePointer<Int8>?,
|
||||
_ cString4: UnsafePointer<Int8>?)
|
||||
-> Int32
|
||||
{
|
||||
// print("""
|
||||
// TruncateOptimizationBlocker: \
|
||||
// \(AuthorizerActionCode(rawValue: actionCode)) \
|
||||
// \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) })
|
||||
// """)
|
||||
return (actionCode == SQLITE_DELETE) ? SQLITE_IGNORE : SQLITE_OK
|
||||
}
|
||||
}
|
||||
|
||||
private struct AuthorizerActionCode: RawRepresentable, CustomStringConvertible {
|
||||
let rawValue: Int32
|
||||
|
||||
|
||||
@@ -708,7 +708,7 @@ extension DatabaseCollation {
|
||||
/// """)
|
||||
public static let localizedCaseInsensitiveCompare =
|
||||
DatabaseCollation("swiftLocalizedCaseInsensitiveCompare") { (lhs, rhs) in
|
||||
return lhs.localizedCaseInsensitiveCompare(rhs)
|
||||
lhs.localizedCaseInsensitiveCompare(rhs)
|
||||
}
|
||||
|
||||
/// A collation, or SQL string comparison function, that compares strings
|
||||
|
||||
@@ -14,12 +14,24 @@ extension Database {
|
||||
extent: TransactionObservationExtent = .observerLifetime)
|
||||
{
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
|
||||
// Drop cached statements that delete, because the addition of an
|
||||
// observer may change the need for truncate optimization prevention.
|
||||
publicStatementCache.removeAll { $0.databaseEventKinds.contains(where: \.isDelete) }
|
||||
internalStatementCache.removeAll{ $0.databaseEventKinds.contains(where: \.isDelete) }
|
||||
|
||||
observationBroker.add(transactionObserver: transactionObserver, extent: extent)
|
||||
}
|
||||
|
||||
/// Remove a transaction observer.
|
||||
public func remove(transactionObserver: TransactionObserver) {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
|
||||
// Drop cached statements that delete, because the removal of an
|
||||
// observer may change the need for truncate optimization prevention.
|
||||
publicStatementCache.removeAll { $0.databaseEventKinds.contains(where: \.isDelete) }
|
||||
internalStatementCache.removeAll { $0.databaseEventKinds.contains(where: \.isDelete) }
|
||||
|
||||
observationBroker.remove(transactionObserver: transactionObserver)
|
||||
}
|
||||
|
||||
@@ -198,17 +210,17 @@ class DatabaseObservationBroker {
|
||||
|
||||
// MARK: - Statement execution
|
||||
|
||||
/// Setups observation of changes that are about to be performed by the
|
||||
/// statement, and returns the authorizer that should be used during
|
||||
/// statement execution (this allows preventing the truncate optimization
|
||||
/// when there exists a transaction observer for row deletion).
|
||||
func statementWillExecute(_ statement: Statement) -> StatementAuthorizer? {
|
||||
// If any observer observes row deletions, we'll have to disable
|
||||
// [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
|
||||
// so that observers are notified.
|
||||
var observesRowDeletion = false
|
||||
|
||||
if transactionObservations.isEmpty == false {
|
||||
/// Returns true if there exists some transaction observers interested in
|
||||
/// deletions in the given table.
|
||||
func observesDeletions(on table: String) -> Bool {
|
||||
transactionObservations.contains { observation in
|
||||
observation.observes(eventsOfKind: .delete(tableName: table))
|
||||
}
|
||||
}
|
||||
|
||||
/// Prepares observation of changes that are about to be performed by the statement.
|
||||
func statementWillExecute(_ statement: Statement) {
|
||||
if !database.isReadOnly && !transactionObservations.isEmpty {
|
||||
// As statement executes, it may trigger database changes that will
|
||||
// be notified to transaction observers. As a consequence, observers
|
||||
// may disable themselves with stopObservingDatabaseChangesUntilNextTransaction()
|
||||
@@ -245,10 +257,6 @@ class DatabaseObservationBroker {
|
||||
return nil
|
||||
}
|
||||
|
||||
if case .delete = eventKind {
|
||||
observesRowDeletion = true
|
||||
}
|
||||
|
||||
// observation will be notified of all individual events
|
||||
return (observation, DatabaseEventPredicate.true)
|
||||
}
|
||||
@@ -268,13 +276,6 @@ class DatabaseObservationBroker {
|
||||
return nil
|
||||
}
|
||||
|
||||
for eventKind in observedKinds {
|
||||
if case .delete = eventKind {
|
||||
observesRowDeletion = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// observation will only be notified of individual events that
|
||||
// match one of the observed kinds.
|
||||
return (
|
||||
@@ -287,12 +288,6 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
|
||||
transactionState = .none
|
||||
|
||||
if observesRowDeletion {
|
||||
return TruncateOptimizationBlocker()
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// May throw a cancelled commit error, if a transaction observer cancels
|
||||
@@ -314,7 +309,7 @@ class DatabaseObservationBroker {
|
||||
// SQLITE_CONSTRAINT error)
|
||||
databaseDidRollback(notifyTransactionObservers: false)
|
||||
case .cancelledCommit(let error):
|
||||
databaseDidRollback(notifyTransactionObservers: true)
|
||||
databaseDidRollback(notifyTransactionObservers: !database.isReadOnly)
|
||||
throw error
|
||||
default:
|
||||
break
|
||||
@@ -386,7 +381,7 @@ class DatabaseObservationBroker {
|
||||
case .commit:
|
||||
databaseDidCommit()
|
||||
case .rollback:
|
||||
databaseDidRollback(notifyTransactionObservers: true)
|
||||
databaseDidRollback(notifyTransactionObservers: !database.isReadOnly)
|
||||
default:
|
||||
break
|
||||
}
|
||||
@@ -395,6 +390,8 @@ class DatabaseObservationBroker {
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
// Called from sqlite3_preupdate_hook
|
||||
private func databaseWillChange(with event: DatabasePreUpdateEvent) {
|
||||
assert(!database.isReadOnly, "Read-only transactions are not notified")
|
||||
|
||||
if savepointStack.isEmpty {
|
||||
// Notify now
|
||||
for (observation, predicate) in statementObservations where predicate.evaluate(event) {
|
||||
@@ -409,6 +406,8 @@ class DatabaseObservationBroker {
|
||||
|
||||
// Called from sqlite3_update_hook
|
||||
private func databaseDidChange(with event: DatabaseEvent) {
|
||||
assert(!database.isReadOnly, "Read-only transactions are not notified")
|
||||
|
||||
// We're about to call the databaseDidChange(with:) method of
|
||||
// transaction observers. In this method, observers may disable
|
||||
// themselves with stopObservingDatabaseChangesUntilNextTransaction()
|
||||
@@ -434,8 +433,10 @@ class DatabaseObservationBroker {
|
||||
// Called from sqlite3_commit_hook and databaseDidCommitEmptyDeferredTransaction()
|
||||
private func databaseWillCommit() throws {
|
||||
notifyBufferedEvents()
|
||||
for observation in transactionObservations {
|
||||
try observation.databaseWillCommit()
|
||||
if !database.isReadOnly {
|
||||
for observation in transactionObservations {
|
||||
try observation.databaseWillCommit()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -443,9 +444,12 @@ class DatabaseObservationBroker {
|
||||
private func databaseDidCommit() {
|
||||
savepointStack.clear()
|
||||
|
||||
for observation in transactionObservations {
|
||||
observation.databaseDidCommit(database)
|
||||
if !database.isReadOnly {
|
||||
for observation in transactionObservations {
|
||||
observation.databaseDidCommit(database)
|
||||
}
|
||||
}
|
||||
|
||||
databaseDidEndTransaction()
|
||||
}
|
||||
|
||||
@@ -489,7 +493,7 @@ class DatabaseObservationBroker {
|
||||
try databaseWillCommit()
|
||||
databaseDidCommit()
|
||||
} catch {
|
||||
databaseDidRollback(notifyTransactionObservers: true)
|
||||
databaseDidRollback(notifyTransactionObservers: !database.isReadOnly)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -499,6 +503,7 @@ class DatabaseObservationBroker {
|
||||
savepointStack.clear()
|
||||
|
||||
if notifyTransactionObservers {
|
||||
assert(!database.isReadOnly, "Read-only transactions are not notified")
|
||||
for observation in transactionObservations {
|
||||
observation.databaseDidRollback(database)
|
||||
}
|
||||
@@ -570,6 +575,7 @@ class DatabaseObservationBroker {
|
||||
savepointStack.clear()
|
||||
|
||||
for (event, statementObservations) in eventsBuffer {
|
||||
assert(statementObservations.isEmpty || !database.isReadOnly, "Read-only transactions are not notified")
|
||||
for (observation, predicate) in statementObservations where predicate.evaluate(event) {
|
||||
event.send(to: observation)
|
||||
}
|
||||
@@ -902,6 +908,15 @@ public enum DatabaseEventKind {
|
||||
return DatabaseRegion(table: tableName, columns: updatedColumnNames)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true iff this is a delete event.
|
||||
var isDelete: Bool {
|
||||
if case .delete = self {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseEventKind {
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
/// An instance of WALSnapshot records the state of a WAL mode database for some
|
||||
/// specific point in history.
|
||||
///
|
||||
/// We use `WALSnapshot` to help `ValueObservation` check for changes
|
||||
/// that would happen between the initial fetch, and the start of the
|
||||
/// actual observation. This class has no other purpose, and is not intended to
|
||||
/// become public.
|
||||
///
|
||||
/// It does not work with SQLCipher, because SQLCipher does not support
|
||||
/// `SQLITE_ENABLE_SNAPSHOT` correctly: we have linker errors.
|
||||
/// See <https://github.com/ericsink/SQLitePCL.raw/issues/452>.
|
||||
///
|
||||
/// With custom SQLite builds, it only works if `SQLITE_ENABLE_SNAPSHOT`
|
||||
/// is defined.
|
||||
///
|
||||
/// With system SQLite, it can only work when the SDK exposes the C apis and
|
||||
/// their availability, which means XCode 14 (identified with Swift 5.7).
|
||||
///
|
||||
/// Yes, this is an awfully complex logic.
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/snapshot.html>.
|
||||
final class WALSnapshot {
|
||||
#if os(macOS) || targetEnvironment(macCatalyst) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) || compiler(<5.7)
|
||||
init?(_ db: Database) {
|
||||
return nil
|
||||
}
|
||||
|
||||
func compare(_ other: WALSnapshot) -> CInt {
|
||||
preconditionFailure("snapshots are not available")
|
||||
}
|
||||
#else
|
||||
private let snapshot: 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: CInt = withUnsafeMutablePointer(to: &snapshot) {
|
||||
#if GRDBCUSTOMSQLITE
|
||||
return sqlite3_snapshot_get(db.sqliteConnection, "main", $0)
|
||||
#else
|
||||
// iOS 10.0 is always true because our minimum requirement is iOS 11.
|
||||
if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) {
|
||||
return sqlite3_snapshot_get(db.sqliteConnection, "main", $0)
|
||||
} else {
|
||||
return SQLITE_ERROR
|
||||
}
|
||||
#endif
|
||||
}
|
||||
guard code == SQLITE_OK, let s = snapshot else {
|
||||
return nil
|
||||
}
|
||||
self.snapshot = s
|
||||
}
|
||||
|
||||
deinit {
|
||||
#if GRDBCUSTOMSQLITE
|
||||
sqlite3_snapshot_free(snapshot)
|
||||
#else
|
||||
// iOS 10.0 is always true because our minimum requirement is iOS 11.
|
||||
if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) {
|
||||
sqlite3_snapshot_free(snapshot)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Compares two WAL snapshots.
|
||||
///
|
||||
/// `a.compare(b) < 0` iff a is older than b.
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/snapshot_cmp.html>.
|
||||
func compare(_ other: WALSnapshot) -> CInt {
|
||||
#if GRDBCUSTOMSQLITE
|
||||
return sqlite3_snapshot_cmp(snapshot, other.snapshot)
|
||||
#else
|
||||
// iOS 10.0 is always true because our minimum requirement is iOS 11.
|
||||
if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) {
|
||||
return sqlite3_snapshot_cmp(snapshot, other.snapshot)
|
||||
} else {
|
||||
preconditionFailure("snapshots are not available")
|
||||
}
|
||||
#endif
|
||||
}
|
||||
#endif // os(macOS) || targetEnvironment(macCatalyst) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) || compiler(<5.7)
|
||||
}
|
||||
+11
-60
@@ -314,19 +314,14 @@ extension ValueObservation {
|
||||
{ preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
|
||||
public func combine<
|
||||
R1: _ValueReducer,
|
||||
Combined>(
|
||||
public func combine<R1, Combined>(
|
||||
_ other: ValueObservation<R1>,
|
||||
_ transform: @escaping (Reducer.Value, R1.Value) -> Combined)
|
||||
-> ValueObservation<ValueReducers.Unavailable<Combined>>
|
||||
{ preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
|
||||
public func combine<
|
||||
R1: _ValueReducer,
|
||||
R2: _ValueReducer,
|
||||
Combined>(
|
||||
public func combine<R1, R2, Combined>(
|
||||
_ observation1: ValueObservation<R1>,
|
||||
_ observation2: ValueObservation<R2>,
|
||||
_ transform: @escaping (Reducer.Value, R1.Value, R2.Value) -> Combined)
|
||||
@@ -334,11 +329,7 @@ extension ValueObservation {
|
||||
{ preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
|
||||
public func combine<
|
||||
R1: _ValueReducer,
|
||||
R2: _ValueReducer,
|
||||
R3: _ValueReducer,
|
||||
Combined>(
|
||||
public func combine<R1, R2, R3, Combined>(
|
||||
_ observation1: ValueObservation<R1>,
|
||||
_ observation2: ValueObservation<R2>,
|
||||
_ observation3: ValueObservation<R3>,
|
||||
@@ -347,12 +338,7 @@ extension ValueObservation {
|
||||
{ preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
|
||||
public func combine<
|
||||
R1: _ValueReducer,
|
||||
R2: _ValueReducer,
|
||||
R3: _ValueReducer,
|
||||
R4: _ValueReducer,
|
||||
Combined>(
|
||||
public func combine<R1, R2, R3, R4, Combined>(
|
||||
_ observation1: ValueObservation<R1>,
|
||||
_ observation2: ValueObservation<R2>,
|
||||
_ observation3: ValueObservation<R3>,
|
||||
@@ -374,19 +360,14 @@ extension ValueObservation {
|
||||
|
||||
extension ValueObservation where Reducer == ValueReducers.Auto {
|
||||
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
|
||||
public static func combine<
|
||||
R1: _ValueReducer,
|
||||
R2: _ValueReducer>(
|
||||
public static func combine<R1, R2>(
|
||||
_ o1: ValueObservation<R1>,
|
||||
_ o2: ValueObservation<R2>)
|
||||
-> ValueObservation<ValueReducers.Unavailable<(R1.Value, R2.Value)>>
|
||||
{ preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
|
||||
public static func combine<
|
||||
R1: _ValueReducer,
|
||||
R2: _ValueReducer,
|
||||
R3: _ValueReducer>(
|
||||
public static func combine<R1, R2, R3>(
|
||||
_ o1: ValueObservation<R1>,
|
||||
_ o2: ValueObservation<R2>,
|
||||
_ o3: ValueObservation<R3>)
|
||||
@@ -394,11 +375,7 @@ extension ValueObservation where Reducer == ValueReducers.Auto {
|
||||
{ preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
|
||||
public static func combine<
|
||||
R1: _ValueReducer,
|
||||
R2: _ValueReducer,
|
||||
R3: _ValueReducer,
|
||||
R4: _ValueReducer>(
|
||||
public static func combine<R1, R2, R3, R4>(
|
||||
_ o1: ValueObservation<R1>,
|
||||
_ o2: ValueObservation<R2>,
|
||||
_ o3: ValueObservation<R3>,
|
||||
@@ -407,12 +384,7 @@ extension ValueObservation where Reducer == ValueReducers.Auto {
|
||||
{ preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
|
||||
public static func combine<
|
||||
R1: _ValueReducer,
|
||||
R2: _ValueReducer,
|
||||
R3: _ValueReducer,
|
||||
R4: _ValueReducer,
|
||||
R5: _ValueReducer>(
|
||||
public static func combine<R1, R2, R3, R4, R5>(
|
||||
_ o1: ValueObservation<R1>,
|
||||
_ o2: ValueObservation<R2>,
|
||||
_ o3: ValueObservation<R3>,
|
||||
@@ -422,13 +394,7 @@ extension ValueObservation where Reducer == ValueReducers.Auto {
|
||||
{ preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
|
||||
public static func combine<
|
||||
R1: _ValueReducer,
|
||||
R2: _ValueReducer,
|
||||
R3: _ValueReducer,
|
||||
R4: _ValueReducer,
|
||||
R5: _ValueReducer,
|
||||
R6: _ValueReducer>(
|
||||
public static func combine<R1, R2, R3, R4, R5, R6>(
|
||||
_ o1: ValueObservation<R1>,
|
||||
_ o2: ValueObservation<R2>,
|
||||
_ o3: ValueObservation<R3>,
|
||||
@@ -439,14 +405,7 @@ extension ValueObservation where Reducer == ValueReducers.Auto {
|
||||
{ preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
|
||||
public static func combine<
|
||||
R1: _ValueReducer,
|
||||
R2: _ValueReducer,
|
||||
R3: _ValueReducer,
|
||||
R4: _ValueReducer,
|
||||
R5: _ValueReducer,
|
||||
R6: _ValueReducer,
|
||||
R7: _ValueReducer>(
|
||||
public static func combine<R1, R2, R3, R4, R5, R6, R7>(
|
||||
_ o1: ValueObservation<R1>,
|
||||
_ o2: ValueObservation<R2>,
|
||||
_ o3: ValueObservation<R3>,
|
||||
@@ -458,15 +417,7 @@ extension ValueObservation where Reducer == ValueReducers.Auto {
|
||||
{ preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
|
||||
public static func combine<
|
||||
R1: _ValueReducer,
|
||||
R2: _ValueReducer,
|
||||
R3: _ValueReducer,
|
||||
R4: _ValueReducer,
|
||||
R5: _ValueReducer,
|
||||
R6: _ValueReducer,
|
||||
R7: _ValueReducer,
|
||||
R8: _ValueReducer>(
|
||||
public static func combine<R1, R2, R3, R4, R5, R6, R7, R8>(
|
||||
_ o1: ValueObservation<R1>,
|
||||
_ o2: ValueObservation<R2>,
|
||||
_ o3: ValueObservation<R3>,
|
||||
|
||||
@@ -3,6 +3,7 @@ import Combine
|
||||
#endif
|
||||
import Foundation
|
||||
|
||||
// TODO: provide concurrent apis for migrations that run @Sendable closures.
|
||||
/// A DatabaseMigrator registers and applies database migrations.
|
||||
///
|
||||
/// Migrations are named blocks of SQL statements that are guaranteed to be
|
||||
@@ -196,7 +197,6 @@ public struct DatabaseMigrator {
|
||||
/// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool)
|
||||
/// where migrations should apply.
|
||||
/// - throws: An eventual error thrown by the registered migration blocks.
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func migrate(_ writer: DatabaseWriter) throws {
|
||||
guard let lastMigration = _migrations.last else {
|
||||
return
|
||||
@@ -204,25 +204,6 @@ public struct DatabaseMigrator {
|
||||
try migrate(writer, upTo: lastMigration.identifier)
|
||||
}
|
||||
|
||||
#if compiler(>=5.5.2) && canImport(_Concurrency)
|
||||
/// Iterate migrations in the same order as they were registered. If a
|
||||
/// migration has not yet been applied, its block is executed in
|
||||
/// a transaction.
|
||||
///
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool)
|
||||
/// where migrations should apply.
|
||||
/// - throws: An eventual error thrown by the registered migration blocks.
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func migrate(_ writer: DatabaseWriter) async throws {
|
||||
guard let lastMigration = _migrations.last else {
|
||||
return
|
||||
}
|
||||
try await migrate(writer, upTo: lastMigration.identifier)
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Iterate migrations in the same order as they were registered, up to the
|
||||
/// provided target. If a migration has not yet been applied, its block is
|
||||
/// executed in a transaction.
|
||||
@@ -231,32 +212,12 @@ public struct DatabaseMigrator {
|
||||
/// where migrations should apply.
|
||||
/// - parameter targetIdentifier: The identifier of a registered migration.
|
||||
/// - throws: An eventual error thrown by the registered migration blocks.
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws {
|
||||
try writer.barrierWriteWithoutTransaction { db in
|
||||
try migrate(db, upTo: targetIdentifier)
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=5.5.2) && canImport(_Concurrency)
|
||||
/// Iterate migrations in the same order as they were registered, up to the
|
||||
/// provided target. If a migration has not yet been applied, its block is
|
||||
/// executed in a transaction.
|
||||
///
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool)
|
||||
/// where migrations should apply.
|
||||
/// - parameter targetIdentifier: The identifier of a registered migration.
|
||||
/// - throws: An eventual error thrown by the registered migration blocks.
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) async throws {
|
||||
try await writer.barrierWriteWithoutTransaction { [self] db in
|
||||
try migrate(db, upTo: targetIdentifier)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Iterate migrations in the same order as they were registered. If a
|
||||
/// migration has not yet been applied, its block is executed in
|
||||
/// a transaction.
|
||||
@@ -310,7 +271,7 @@ public struct DatabaseMigrator {
|
||||
/// - throws: An eventual database error.
|
||||
public func appliedIdentifiers(_ db: Database) throws -> Set<String> {
|
||||
do {
|
||||
return try Set(String.fetchCursor(db, sql: "SELECT identifier FROM grdb_migrations"))
|
||||
return try String.fetchSet(db, sql: "SELECT identifier FROM grdb_migrations")
|
||||
} catch {
|
||||
// Rethrow if we can't prove grdb_migrations does not exist yet
|
||||
if (try? !db.tableExists("grdb_migrations")) ?? false {
|
||||
@@ -432,6 +393,7 @@ public struct DatabaseMigrator {
|
||||
// just as the migrated database
|
||||
var tmpConfig = db.configuration
|
||||
tmpConfig.targetQueue = nil // Avoid deadlocks
|
||||
tmpConfig.writeTargetQueue = nil // Avoid deadlocks
|
||||
tmpConfig.label = "GRDB.DatabaseMigrator.temporary"
|
||||
|
||||
// Create the temporary database on disk, just in
|
||||
|
||||
@@ -686,7 +686,7 @@ private func prefetch(
|
||||
// In the CTE, ordering and including(all:) children are
|
||||
// useless, and we only need to select pivot columns:
|
||||
let originRelation = originRelation
|
||||
.unordered()
|
||||
.unorderedUnlessLimited() // only preserve ordering in the CTE if limited
|
||||
.removingChildrenForPrefetchedAssociations()
|
||||
.selectOnly(leftColumns.map { SQLExpression.column($0).sqlSelection })
|
||||
let originCTE = CommonTableExpression(
|
||||
|
||||
@@ -325,7 +325,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
|
||||
|
||||
/// Creates a request filtered by unique key.
|
||||
///
|
||||
/// // SELECT * FROM player WHERE ... email = 'arthur@example.com' OR ...
|
||||
/// // SELECT * FROM player WHERE ... email = 'arthur@example.com' AND ...
|
||||
/// let request = try Player...filter(keys: [["email": "arthur@example.com"], ...])
|
||||
///
|
||||
/// When executed, this request raises a fatal error if there is no unique
|
||||
|
||||
@@ -120,7 +120,7 @@ public struct _SQLAssociation {
|
||||
// via: Pivot.belongsTo(Destination.self))
|
||||
// Origin(id: 1).request(for: association)
|
||||
let reversedSteps = zip(steps, steps.dropFirst())
|
||||
.map({ (step, nextStep) -> SQLAssociationStep in
|
||||
.map { (step, nextStep) -> SQLAssociationStep in
|
||||
// Intermediate steps are not selected, and including(all:)
|
||||
// children are useless:
|
||||
let relation = step.relation
|
||||
@@ -137,7 +137,7 @@ public struct _SQLAssociation {
|
||||
condition: nextStep.condition.reversed(to: step.relation.source.tableName),
|
||||
relation: relation,
|
||||
cardinality: .toOne)
|
||||
})
|
||||
}
|
||||
.reversed()
|
||||
let reversedAssociation = _SQLAssociation(steps: Array(reversedSteps))
|
||||
return destination.relation.appendingChild(for: reversedAssociation, kind: .oneRequired)
|
||||
|
||||
@@ -325,7 +325,7 @@ public struct SQLExpression {
|
||||
/// let operator = BinaryOperator("LIKE", negated: "NOT LIKE")
|
||||
/// operator.negated!.sql // NOT LIKE
|
||||
var negated: EscapableBinaryOperator {
|
||||
return EscapableBinaryOperator(negatedSQL, negated: sql)
|
||||
EscapableBinaryOperator(negatedSQL, negated: sql)
|
||||
}
|
||||
|
||||
/// The `LIKE` escapable binary operator
|
||||
|
||||
@@ -274,6 +274,15 @@ extension SQLRelation: Refinable {
|
||||
}
|
||||
}
|
||||
|
||||
// Remove ordering iff relation has no LIMIT clause
|
||||
func unorderedUnlessLimited() -> Self {
|
||||
if limit != nil {
|
||||
return self
|
||||
} else {
|
||||
return unordered()
|
||||
}
|
||||
}
|
||||
|
||||
func group(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self {
|
||||
with {
|
||||
$0.groupPromise = DatabasePromise(expressions)
|
||||
|
||||
@@ -554,9 +554,9 @@ public enum DatabaseColumnEncodingStrategy {
|
||||
searchRange = lowerCaseRange.upperBound..<searchRange.upperBound
|
||||
}
|
||||
words.append(wordStart..<searchRange.upperBound)
|
||||
let result = words.map({ (range) in
|
||||
return stringKey[range].lowercased()
|
||||
}).joined(separator: "_")
|
||||
let result = words
|
||||
.map { (range) in stringKey[range].lowercased() }
|
||||
.joined(separator: "_")
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -117,8 +117,6 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
}
|
||||
|
||||
func decodeNil(forKey key: Key) throws -> Bool {
|
||||
// Nil is only possible for columns and scopes (optional
|
||||
// associations), not for prefetched rows.
|
||||
let row = decoder.row
|
||||
if let column = try? decodeColumn(forKey: key), row[column] != nil {
|
||||
return false
|
||||
@@ -126,6 +124,9 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
if row.scopesTree[key.stringValue] != nil {
|
||||
return false
|
||||
}
|
||||
if row.prefetchedRows[key.stringValue] != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -218,9 +219,15 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
}
|
||||
}
|
||||
|
||||
// Scope? (beware left joins: check if scoped row contains non-null values)
|
||||
if let scopedRow = row.scopesTree[key.stringValue], scopedRow.containsNonNullValue {
|
||||
return try decode(type, fromRow: scopedRow, codingPath: codingPath + [key])
|
||||
// Scope?
|
||||
if let scopedRow = row.scopesTree[key.stringValue] {
|
||||
// Beware left joins: check if scoped row contains non-null
|
||||
// values before decoding
|
||||
if scopedRow.containsNonNullValue {
|
||||
return try decode(type, fromRow: scopedRow, codingPath: codingPath + [key])
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Prefetched Rows?
|
||||
@@ -229,7 +236,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
return try T(from: decoder)
|
||||
}
|
||||
|
||||
// Key is not a column, and not a scope.
|
||||
// Unknown key
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -264,7 +271,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
return try T(from: decoder)
|
||||
}
|
||||
|
||||
// Key is not a column, and not a scope.
|
||||
// Unknown key
|
||||
//
|
||||
// Should be throw an error? Well... The use case is the following:
|
||||
//
|
||||
@@ -291,7 +298,8 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
//
|
||||
// Our current strategy is to assume that a missing key (such as
|
||||
// "book", which is not the name of a column, and not the name of a
|
||||
// scope) has to be decoded right from the base row.
|
||||
// scope) has to be decoded right from the base row. But this can
|
||||
// happen only once.
|
||||
if let decodedRootKey = decodedRootKey {
|
||||
let keys = [decodedRootKey.stringValue, key.stringValue].sorted()
|
||||
throw DecodingError.keyNotFound(key, DecodingError.Context(
|
||||
|
||||
@@ -196,8 +196,6 @@ extension FetchableRecord {
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Self]
|
||||
{
|
||||
// Use Array initializer in order to deal with <https://github.com/groue/GRDB.swift/issues/1124>.
|
||||
// See `Statement.forEachStep(_:)` for more information.
|
||||
try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
@@ -691,5 +689,4 @@ public enum DatabaseColumnDecodingStrategy {
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
}
|
||||
+34
-2
@@ -51,13 +51,26 @@ final class Pool<T> {
|
||||
private let itemsSemaphore: DispatchSemaphore // limits the number of elements
|
||||
private let itemsGroup: DispatchGroup // knows when no element is used
|
||||
private let barrierQueue: DispatchQueue
|
||||
private let semaphoreWaitingQueue: DispatchQueue // Inspired by https://khanlou.com/2016/04/the-GCD-handbook/
|
||||
|
||||
init(maximumCount: Int, makeElement: @escaping () throws -> T) {
|
||||
/// Creates a Pool.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - maximumCount: The maximum number of elements.
|
||||
/// - qos: The quality of service of asynchronous accesses.
|
||||
/// - makeElement: A function that creates an element. It is called
|
||||
/// on demand.
|
||||
init(
|
||||
maximumCount: Int,
|
||||
qos: DispatchQoS = .unspecified,
|
||||
makeElement: @escaping () throws -> T)
|
||||
{
|
||||
GRDBPrecondition(maximumCount > 0, "Pool size must be at least 1")
|
||||
self.makeElement = makeElement
|
||||
self.itemsSemaphore = DispatchSemaphore(value: maximumCount)
|
||||
self.itemsGroup = DispatchGroup()
|
||||
self.barrierQueue = DispatchQueue(label: "GRDB.Pool.barrier", attributes: [.concurrent])
|
||||
self.barrierQueue = DispatchQueue(label: "GRDB.Pool.barrier", qos: qos, attributes: [.concurrent])
|
||||
self.semaphoreWaitingQueue = DispatchQueue(label: "GRDB.Pool.wait", qos: qos)
|
||||
}
|
||||
|
||||
/// Returns a tuple (element, release)
|
||||
@@ -87,6 +100,25 @@ final class Pool<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Eventually produces a tuple (element, release), where element is
|
||||
/// intended to be used asynchronously.
|
||||
///
|
||||
/// Client must call release(), only once, after the element has been used.
|
||||
///
|
||||
/// - important: The `execute` argument is executed in a serial dispatch
|
||||
/// queue, so make sure you use the element asynchronously.
|
||||
func asyncGet(_ execute: @escaping (Result<(element: T, release: () -> Void), Error>) -> Void) {
|
||||
// Inspired by https://khanlou.com/2016/04/the-GCD-handbook/
|
||||
// > We wait on the semaphore in the serial queue, which means that
|
||||
// > we’ll have at most one blocked thread when we reach maximum
|
||||
// > executing blocks on the concurrent queue. Any other tasks the user
|
||||
// > enqueues will sit inertly on the serial queue waiting to be
|
||||
// > executed, and won’t cause new threads to be started.
|
||||
semaphoreWaitingQueue.async {
|
||||
execute(Result { try self.get() })
|
||||
}
|
||||
}
|
||||
|
||||
/// Performs a synchronous block with an element. The element turns
|
||||
/// available after the block has executed.
|
||||
func get<U>(block: (T) throws -> U) throws -> U {
|
||||
|
||||
@@ -218,7 +218,7 @@ extension Publisher {
|
||||
/// The difference with the stock `receive(on:options:)` Combine method is
|
||||
/// that only values and completion are re-scheduled. Subscriptions are not.
|
||||
func receiveValues<S: Scheduler>(on scheduler: S, options: S.SchedulerOptions? = nil) -> ReceiveValuesOn<Self, S> {
|
||||
return ReceiveValuesOn(upstream: self, context: scheduler, options: options)
|
||||
ReceiveValuesOn(upstream: self, context: scheduler, options: options)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -32,7 +32,7 @@ public protocol _OptionalProtocol {
|
||||
/// :nodoc:
|
||||
extension Optional: _OptionalProtocol { }
|
||||
|
||||
#if swift(>=5.5) && canImport(_Concurrency)
|
||||
#if swift(>=5.6) && canImport(_Concurrency)
|
||||
public typealias GRDBSendable = Swift.Sendable
|
||||
#else
|
||||
public typealias GRDBSendable = Any
|
||||
@@ -172,7 +172,7 @@ func concat<T>(_ rhs: ((T) -> Void)?, _ lhs: ((T) -> Void)?) -> ((T) -> Void)? {
|
||||
}
|
||||
}
|
||||
|
||||
extension NSRecursiveLock {
|
||||
extension NSLocking {
|
||||
func synchronized<T>(
|
||||
_ message: @autoclosure () -> String = #function,
|
||||
_ block: () throws -> T)
|
||||
|
||||
@@ -17,10 +17,14 @@ public class AnyDatabaseCancellable: DatabaseCancellable {
|
||||
_cancel = cancel
|
||||
}
|
||||
|
||||
/// Initializes a cancellable object that forwards cancellation to the
|
||||
/// Creates a cancellable object that forwards cancellation to the
|
||||
/// provided cancellable.
|
||||
public convenience init(_ cancellable: DatabaseCancellable) {
|
||||
self.init(cancel: cancellable.cancel)
|
||||
var cancellable: DatabaseCancellable? = cancellable
|
||||
self.init {
|
||||
cancellable?.cancel()
|
||||
cancellable = nil // Release memory
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
|
||||
@@ -299,7 +299,7 @@ public final class SharedValueObservation<Element> {
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=5.5.2) && canImport(_Concurrency)
|
||||
#if compiler(>=5.6) && canImport(_Concurrency)
|
||||
extension SharedValueObservation {
|
||||
// MARK: - Asynchronous Observation
|
||||
/// The database observation, as an asynchronous sequence of
|
||||
|
||||
@@ -0,0 +1,636 @@
|
||||
import Foundation
|
||||
|
||||
/// `ValueConcurrentObserver` observes the database for `ValueObservation`, in
|
||||
/// a `DatabasePool`.
|
||||
///
|
||||
/// It performs the following database observation cycle:
|
||||
///
|
||||
/// 1. Start observation or detect a database change
|
||||
/// 2. Fetch
|
||||
/// 3. Reduce
|
||||
/// 4. Notify
|
||||
///
|
||||
/// **Fetch** is performed concurrently (hence the name of this observer).
|
||||
///
|
||||
/// **Reduce** is the operation that turns the fetched database values into the
|
||||
/// observed values. Those are not the same. Consider, for example, the `map()`
|
||||
/// and `removeDuplicates()` operators: they perform their job during the
|
||||
/// reducing stage.
|
||||
///
|
||||
/// **Notify** is calling user callbacks, in case of database change or error.
|
||||
final class ValueConcurrentObserver<Reducer: ValueReducer> {
|
||||
// MARK: - Configuration
|
||||
//
|
||||
// Configuration is not mutable.
|
||||
|
||||
/// How to schedule observed values and errors.
|
||||
private let scheduler: ValueObservationScheduler
|
||||
|
||||
/// Configures the tracked database region.
|
||||
private let trackingMode: ValueObservationTrackingMode
|
||||
|
||||
// MARK: - Mutable State
|
||||
//
|
||||
// The observer has four distinct mutable states that evolve independently,
|
||||
// and are made thread-safe with various mechanisms:
|
||||
//
|
||||
// - A `DatabaseAccess`: ability to access the database. It is constant but
|
||||
// turns nil after the observation fails or is cancelled, in order to
|
||||
// release memory and resources when the observation completes. It is
|
||||
// guarded by `lock`, because observation can fail or be cancelled from
|
||||
// multiple threads.
|
||||
//
|
||||
// - A `NotificationCallbacks`: ability to notify observation events. It is
|
||||
// constant but turns nil when failure or cancellation is notified, in
|
||||
// order to release memory and resources when the observation completes.
|
||||
// It is guarded by `lock`, because observation can fail or be cancelled
|
||||
// from multiple threads.
|
||||
//
|
||||
// - An `ObservationState`: relationship with the `TransactionObserver`
|
||||
// protocol. It is only accessed from the serialized writer
|
||||
// dispatch queue.
|
||||
//
|
||||
// - A `Reducer`: the observation reducer, only accessed from the
|
||||
// serialized dispatch queue `reduceQueue`.
|
||||
//
|
||||
// The `reduceQueue` guarantees that fresh value notifications have the same
|
||||
// order as transactions. It is different from the serialized writer
|
||||
// dispatch queue because we do not want to lock the database as
|
||||
// computations (`map`, `removeDuplicates()`, etc.) are performed.
|
||||
//
|
||||
// Despite being protected by the same lock, `DatabaseAccess` and
|
||||
// `NotificationCallbacks` are not merged together. This is because the
|
||||
// observer does not lose `DatabaseAccess` at the same time it
|
||||
// looses `NotificationCallbacks`:
|
||||
//
|
||||
// - In case of cancellation, `NotificationCallbacks` is lost first, and
|
||||
// `DatabaseAccess` is lost asynchronously, after the observer could
|
||||
// resign as a transaction observer. See `cancel()`.
|
||||
//
|
||||
// - In case of error, `DatabaseAccess` may be lost synchronously, and
|
||||
// `NotificationCallbacks` is lost asynchronously, after the error could
|
||||
// be notified. See error catching clauses.
|
||||
|
||||
/// Ability to access the database
|
||||
private struct DatabaseAccess {
|
||||
/// The observed DatabasePool.
|
||||
let dbPool: DatabasePool
|
||||
|
||||
/// The function that fetches database values.
|
||||
let fetch: (Database) throws -> Reducer.Fetched
|
||||
}
|
||||
|
||||
/// Ability to notify observation events
|
||||
private struct NotificationCallbacks {
|
||||
let events: ValueObservationEvents
|
||||
let onChange: (Reducer.Value) -> Void
|
||||
}
|
||||
|
||||
/// Relationship with the `TransactionObserver` protocol
|
||||
private struct ObservationState {
|
||||
var region: DatabaseRegion?
|
||||
var isModified = false
|
||||
|
||||
static var notObserving: Self { .init(region: nil, isModified: false) }
|
||||
}
|
||||
|
||||
/// Protects `databaseAccess` and `notificationCallbacks`.
|
||||
///
|
||||
/// Check out this compiler bug:
|
||||
/// - <https://github.com/groue/GRDB.swift/issues/1026>
|
||||
/// - <https://github.com/groue/GRDB.swift/pull/1025>
|
||||
private let lock = NSLock()
|
||||
|
||||
/// The dispatch queue where database values are reduced into observed
|
||||
/// values before being notified. Protects `reducer`.
|
||||
private let reduceQueue: DispatchQueue
|
||||
|
||||
/// Access to the database, protected by `lock`.
|
||||
private var databaseAccess: DatabaseAccess?
|
||||
|
||||
/// Ability to notify observation events, protected by `lock`.
|
||||
private var notificationCallbacks: NotificationCallbacks?
|
||||
|
||||
/// Support for `TransactionObserver`, protected by the serialized writer
|
||||
/// dispatch queue.
|
||||
private var observationState = ObservationState.notObserving
|
||||
|
||||
/// Protected by `reduceQueue`.
|
||||
private var reducer: Reducer
|
||||
|
||||
init(
|
||||
dbPool: DatabasePool,
|
||||
scheduler: ValueObservationScheduler,
|
||||
trackingMode: ValueObservationTrackingMode,
|
||||
reducer: Reducer,
|
||||
events: ValueObservationEvents,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
{
|
||||
// Configuration
|
||||
self.scheduler = scheduler
|
||||
self.trackingMode = trackingMode
|
||||
|
||||
// State
|
||||
self.databaseAccess = DatabaseAccess(
|
||||
dbPool: dbPool,
|
||||
// ValueReducer semantics guarantees that reducer._fetch
|
||||
// is independent from the reducer state
|
||||
fetch: reducer._fetch)
|
||||
self.notificationCallbacks = NotificationCallbacks(events: events, onChange: onChange)
|
||||
self.reducer = reducer
|
||||
self.reduceQueue = DispatchQueue(
|
||||
label: dbPool.configuration.identifier(
|
||||
defaultLabel: "GRDB",
|
||||
purpose: "ValueObservation"),
|
||||
qos: dbPool.configuration.readQoS)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Starting the Observation
|
||||
//
|
||||
// When we start an observation from a `DatabasePool`, we do not wait for an
|
||||
// access to the writer connection before fetching the initial value. That is
|
||||
// because the user of a `DatabasePool` expects to be notified with the initial
|
||||
// value as fast as possible, even if a long write transaction is running in the
|
||||
// background.
|
||||
//
|
||||
// We will thus perform the initial fetch from a reader connection, and only
|
||||
// then access the writer connection, and start database observation.
|
||||
//
|
||||
// Between this initial fetch, and the beginning of database observation, any
|
||||
// number of unobserved writes may occur. We must notify the changes that happen
|
||||
// during this unobserved window. But how do we spot them, since we were not
|
||||
// observing the database yet?
|
||||
//
|
||||
// The solution depends on the presence of the `SQLITE_ENABLE_SNAPSHOT`
|
||||
// SQLite compilation flag.
|
||||
//
|
||||
// Without `SQLITE_ENABLE_SNAPSHOT`, we have NO WAY to detect if the database
|
||||
// was changed or not between the initial fetch and the beginning of database
|
||||
// observation. We will thus always perform a secondary fetch from the initial
|
||||
// access to the writer connection. Even if no change was performed. We may end
|
||||
// up notifying the same value twice. Such stuttering is a documented glitch,
|
||||
// and the user can perform deduplication with the
|
||||
// `removeDuplicates()` operator.
|
||||
//
|
||||
// With `SQLITE_ENABLE_SNAPSHOT`, we can detect if the database was not changed
|
||||
// at all between the initial fetch and the beginning of database observation.
|
||||
// If the database was changed, we perform a secondary fetch from the initial
|
||||
// access to the writer connection. It is possible that the change was not
|
||||
// related to the observed value. Actually we have NO WAY to know. So we may end
|
||||
// up notifying the same value twice. Such stuttering is a documented glitch,
|
||||
// and the user can perform deduplication with the
|
||||
// `removeDuplicates()` operator.
|
||||
//
|
||||
// This is how we can both:
|
||||
// 1. Start the observation without waiting for a write access (the expected
|
||||
// benefit of `DatabasePool`).
|
||||
// 2. Make sure we do not miss a change (a documented guarantee)
|
||||
//
|
||||
// Support for `SQLITE_ENABLE_SNAPSHOT` is implemented by our
|
||||
// `WALSnapshot` class.
|
||||
extension ValueConcurrentObserver {
|
||||
// Starts the observation
|
||||
func start() -> DatabaseCancellable {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let (notificationCallbacksOpt, databaseAccessOpt) = lock.synchronized {
|
||||
(self.notificationCallbacks, self.databaseAccess)
|
||||
}
|
||||
guard let notificationCallbacks = notificationCallbacksOpt, let databaseAccess = databaseAccessOpt else {
|
||||
// Likely a GRDB bug: during a synchronous start, user is not
|
||||
// able to cancel observation.
|
||||
fatalError("can't start a cancelled or failed observation")
|
||||
}
|
||||
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
// Start the observation in an synchronous way
|
||||
let initialValue = try syncStart(from: databaseAccess)
|
||||
|
||||
// Notify the initial value from the dispatch queue the
|
||||
// observation was started from
|
||||
notificationCallbacks.onChange(initialValue)
|
||||
} catch {
|
||||
// Notify error from the dispatch queue the observation
|
||||
// was started from.
|
||||
notificationCallbacks.events.didFail?(error)
|
||||
|
||||
// Early return!
|
||||
return AnyDatabaseCancellable { /* nothing to cancel */ }
|
||||
}
|
||||
} else {
|
||||
// Start the observation in an asynchronous way
|
||||
asyncStart(from: databaseAccess)
|
||||
}
|
||||
|
||||
// Make sure the returned cancellable cancels the observation
|
||||
// when deallocated. We can't relying on the deallocation of
|
||||
// self to trigger early cancellation, because self may be retained by
|
||||
// some closure waiting to run in some DispatchQueue.
|
||||
return AnyDatabaseCancellable(self)
|
||||
}
|
||||
|
||||
private func startObservation(_ writerDB: Database, observedRegion: DatabaseRegion) {
|
||||
observationState.region = observedRegion
|
||||
assert(observationState.isModified == false)
|
||||
writerDB.add(transactionObserver: self, extent: .observerLifetime)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Starting the Observation (with SQLITE_ENABLE_SNAPSHOT)
|
||||
|
||||
extension ValueConcurrentObserver {
|
||||
/// Synchronously starts the observation, and returns the initial value.
|
||||
///
|
||||
/// Unlike `asyncStart()`, this method does not notify the initial value or error.
|
||||
private func syncStart(from databaseAccess: DatabaseAccess) throws -> Reducer.Value {
|
||||
// Start from a read access. The whole point of using a DatabasePool
|
||||
// for observing the database is to be able to fetch the initial value
|
||||
// without having to wait for an eventual long-running write
|
||||
// transaction to complete.
|
||||
//
|
||||
// Fetch value & tracked region in a synchronous way.
|
||||
//
|
||||
// TODO: we currently perform the initial read from a snapshot, because
|
||||
// it is a handy way to keep a read transaction open until we grab a
|
||||
// write access, and compare the database versions. The problem is that
|
||||
// we do not control the number of created shapshots: we should instead
|
||||
// use a reader from the pool.
|
||||
let initialSnapshot = try databaseAccess.dbPool.makeSnapshot()
|
||||
let (fetchedValue, initialRegion, initialWALSnapshot) = try initialSnapshot.read {
|
||||
db -> (Reducer.Fetched, DatabaseRegion, WALSnapshot?) in
|
||||
// swiftlint:disable:previous closure_parameter_position
|
||||
|
||||
switch trackingMode {
|
||||
case let .constantRegion(regions):
|
||||
let fetchedValue = try databaseAccess.fetch(db)
|
||||
let region = try DatabaseRegion.union(regions)(db)
|
||||
let initialRegion = try region.observableRegion(db)
|
||||
return (fetchedValue, initialRegion, WALSnapshot(db))
|
||||
|
||||
case .constantRegionRecordedFromSelection,
|
||||
.nonConstantRegionRecordedFromSelection:
|
||||
var region = DatabaseRegion()
|
||||
let fetchedValue = try db.recordingSelection(®ion) {
|
||||
try databaseAccess.fetch(db)
|
||||
}
|
||||
let initialRegion = try region.observableRegion(db)
|
||||
return (fetchedValue, initialRegion, WALSnapshot(db))
|
||||
}
|
||||
}
|
||||
|
||||
// Reduce
|
||||
let initialValue: Reducer.Value = reduceQueue.sync {
|
||||
guard let initialValue = reducer._value(fetchedValue) else {
|
||||
fatalError("Broken contract: reducer has no initial value")
|
||||
}
|
||||
return initialValue
|
||||
}
|
||||
|
||||
// Start observation
|
||||
asyncStartObservation(
|
||||
from: databaseAccess,
|
||||
initialSnapshot: initialSnapshot,
|
||||
initialWALSnapshot: initialWALSnapshot,
|
||||
initialRegion: initialRegion)
|
||||
|
||||
return initialValue
|
||||
}
|
||||
|
||||
/// Asynchronously starts the observation
|
||||
///
|
||||
/// Unlike `syncStart()`, this method does notify the initial value or error.
|
||||
private func asyncStart(from databaseAccess: DatabaseAccess) {
|
||||
// Start from a read access. The whole point of using a DatabasePool
|
||||
// for observing the database is to be able to fetch the initial value
|
||||
// without having to wait for an eventual long-running write
|
||||
// transaction to complete.
|
||||
//
|
||||
// TODO: we currently perform the initial read from a snapshot, because
|
||||
// it is a handy way to keep a read transaction open until we grab a
|
||||
// write access, and compare the database versions. The problem is that
|
||||
// we do not control the number of created shapshots: we should instead
|
||||
// use a reader from the pool.
|
||||
do {
|
||||
let initialSnapshot = try databaseAccess.dbPool.makeSnapshot()
|
||||
initialSnapshot.asyncRead { dbResult in
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
do {
|
||||
// Fetch
|
||||
let fetchedValue: Reducer.Fetched
|
||||
let initialRegion: DatabaseRegion
|
||||
let db = try dbResult.get()
|
||||
switch self.trackingMode {
|
||||
case let .constantRegion(regions):
|
||||
fetchedValue = try databaseAccess.fetch(db)
|
||||
let region = try DatabaseRegion.union(regions)(db)
|
||||
initialRegion = try region.observableRegion(db)
|
||||
|
||||
case .constantRegionRecordedFromSelection,
|
||||
.nonConstantRegionRecordedFromSelection:
|
||||
var region = DatabaseRegion()
|
||||
fetchedValue = try db.recordingSelection(®ion) {
|
||||
try databaseAccess.fetch(db)
|
||||
}
|
||||
initialRegion = try region.observableRegion(db)
|
||||
}
|
||||
|
||||
// Reduce
|
||||
//
|
||||
// Reducing is performed asynchronously, so that we do not lock
|
||||
// a database dispatch queue longer than necessary.
|
||||
self.reduceQueue.async {
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
guard let initialValue = self.reducer._value(fetchedValue) else {
|
||||
fatalError("Broken contract: reducer has no initial value")
|
||||
}
|
||||
|
||||
// Notify
|
||||
self.scheduler.schedule {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let onChangeOpt = self.lock.synchronized { self.notificationCallbacks?.onChange }
|
||||
guard let onChange = onChangeOpt else { return /* Cancelled */ }
|
||||
onChange(initialValue)
|
||||
}
|
||||
}
|
||||
|
||||
// Start observation
|
||||
self.asyncStartObservation(
|
||||
from: databaseAccess,
|
||||
initialSnapshot: initialSnapshot,
|
||||
initialWALSnapshot: WALSnapshot(db),
|
||||
initialRegion: initialRegion)
|
||||
} catch {
|
||||
self.notifyError(error)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
self.notifyError(error)
|
||||
}
|
||||
}
|
||||
|
||||
private func asyncStartObservation(
|
||||
from databaseAccess: DatabaseAccess,
|
||||
initialSnapshot: DatabaseSnapshot,
|
||||
initialWALSnapshot: WALSnapshot?,
|
||||
initialRegion: DatabaseRegion)
|
||||
{
|
||||
databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let eventsOpt = self.lock.synchronized { self.notificationCallbacks?.events }
|
||||
guard let events = eventsOpt else { return /* Cancelled */ }
|
||||
|
||||
do {
|
||||
var observedRegion = initialRegion
|
||||
|
||||
// Transaction is needed for comparing version snapshots
|
||||
try writerDB.isolated(readOnly: true) {
|
||||
// Keep DatabaseSnaphot alive until we have compared
|
||||
// database versions. It prevents database checkpointing,
|
||||
// and keeps WAL snapshots (`sqlite3_snapshot`) valid
|
||||
// and comparable.
|
||||
let isModified: Bool = withExtendedLifetime(initialSnapshot) {
|
||||
guard let initialWALSnapshot = initialWALSnapshot,
|
||||
let currentWALSnapshot = WALSnapshot(writerDB)
|
||||
else {
|
||||
return true
|
||||
}
|
||||
let ordering = initialWALSnapshot.compare(currentWALSnapshot)
|
||||
assert(ordering <= 0, "Unexpected snapshot ordering")
|
||||
return ordering < 0
|
||||
}
|
||||
|
||||
if isModified {
|
||||
events.databaseDidChange?()
|
||||
|
||||
// Fetch
|
||||
let fetchedValue: Reducer.Fetched
|
||||
|
||||
switch self.trackingMode {
|
||||
case .constantRegion:
|
||||
fetchedValue = try databaseAccess.fetch(writerDB)
|
||||
events.willTrackRegion?(initialRegion)
|
||||
self.startObservation(writerDB, observedRegion: initialRegion)
|
||||
|
||||
case .constantRegionRecordedFromSelection,
|
||||
.nonConstantRegionRecordedFromSelection:
|
||||
var region = DatabaseRegion()
|
||||
fetchedValue = try writerDB.recordingSelection(®ion) {
|
||||
try databaseAccess.fetch(writerDB)
|
||||
}
|
||||
observedRegion = try region.observableRegion(writerDB)
|
||||
events.willTrackRegion?(observedRegion)
|
||||
self.startObservation(writerDB, observedRegion: observedRegion)
|
||||
}
|
||||
|
||||
// Reduce
|
||||
//
|
||||
// Reducing is performed asynchronously, so that we do not lock
|
||||
// the writer dispatch queue longer than necessary.
|
||||
//
|
||||
// Important: reduceQueue.async guarantees the same ordering
|
||||
// between transactions and notifications!
|
||||
self.reduceQueue.async {
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
let value = self.reducer._value(fetchedValue)
|
||||
|
||||
// Notify
|
||||
if let value = value {
|
||||
self.scheduler.schedule {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let onChangeOpt = self.lock.synchronized { self.notificationCallbacks?.onChange }
|
||||
guard let onChange = onChangeOpt else { return /* Cancelled */ }
|
||||
onChange(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
events.willTrackRegion?(initialRegion)
|
||||
self.startObservation(writerDB, observedRegion: initialRegion)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
self.notifyError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Observing Database Transactions
|
||||
|
||||
extension ValueConcurrentObserver: TransactionObserver {
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
if let region = observationState.region {
|
||||
return region.isModified(byEventsOfKind: eventKind)
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
if let region = observationState.region, region.isModified(by: event) {
|
||||
// Database was modified!
|
||||
observationState.isModified = true
|
||||
// We can stop observing the current transaction
|
||||
stopObservingDatabaseChangesUntilNextTransaction()
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidCommit(_ writerDB: Database) {
|
||||
// Ignore transaction unless database was modified
|
||||
guard observationState.isModified else { return }
|
||||
|
||||
// Reset the isModified flag until next transaction
|
||||
observationState.isModified = false
|
||||
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
// Ignore transaction unless we are still notifying database events, and
|
||||
// we can still access the database.
|
||||
let (eventsOpt, databaseAccessOpt) = lock.synchronized {
|
||||
(notificationCallbacks?.events, self.databaseAccess)
|
||||
}
|
||||
guard let events = eventsOpt, let databaseAccess = databaseAccessOpt else { return /* Cancelled */ }
|
||||
|
||||
events.databaseDidChange?()
|
||||
|
||||
// Fetch
|
||||
let future: DatabaseFuture<Reducer.Fetched>
|
||||
|
||||
switch trackingMode {
|
||||
case .constantRegion, .constantRegionRecordedFromSelection:
|
||||
future = databaseAccess.dbPool.concurrentRead { db in
|
||||
try databaseAccess.fetch(db)
|
||||
}
|
||||
case .nonConstantRegionRecordedFromSelection:
|
||||
// When the tracked region is not constant, we can't perform
|
||||
// concurrent fetches of observed values.
|
||||
//
|
||||
// This is because after a concurrent fetch has acquired snapshot
|
||||
// isolation, and before it completes, a change can be performed
|
||||
// in the *next* tracked region. When this happens, the
|
||||
// concurrent fetch has loaded an obsolete value, and we need to
|
||||
// perform a new fetch, with the latest values. But the
|
||||
// observation was not triggered by the change because we didn't
|
||||
// know that this change was about to be tracked! This means
|
||||
// that we'd miss a change, and fail notifying the latest value.
|
||||
//
|
||||
// Conclusion: fetch from the writer connection, and update the
|
||||
// tracked region.
|
||||
do {
|
||||
var region = DatabaseRegion()
|
||||
let fetchedValue = try writerDB.recordingSelection(®ion) {
|
||||
try writerDB.isolated(readOnly: true) {
|
||||
try databaseAccess.fetch(writerDB)
|
||||
}
|
||||
}
|
||||
|
||||
let observedRegion = try region.observableRegion(writerDB)
|
||||
|
||||
// Don't spam the user with region tracking events: wait for an actual change
|
||||
if let willTrackRegion = events.willTrackRegion, observedRegion != observationState.region {
|
||||
willTrackRegion(observedRegion)
|
||||
}
|
||||
|
||||
observationState.region = observedRegion
|
||||
future = DatabaseFuture(.success(fetchedValue))
|
||||
} catch {
|
||||
stopDatabaseObservation(writerDB)
|
||||
notifyError(error)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Reduce
|
||||
//
|
||||
// Reducing is performed asynchronously, so that we do not lock
|
||||
// the writer dispatch queue longer than necessary.
|
||||
//
|
||||
// Important: reduceQueue.async guarantees the same ordering between
|
||||
// transactions and notifications!
|
||||
reduceQueue.async {
|
||||
do {
|
||||
// Wait until fetch has completed
|
||||
// TODO: find a way to guarantee correct ordering without waiting for a semaphore and blocking a thread.
|
||||
let fetchedValue = try future.wait()
|
||||
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
let value = self.reducer._value(fetchedValue)
|
||||
|
||||
// Notify value
|
||||
if let value = value {
|
||||
self.scheduler.schedule {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let onChangeOpt = self.lock.synchronized { self.notificationCallbacks?.onChange }
|
||||
guard let onChange = onChangeOpt else { return /* Cancelled */ }
|
||||
onChange(value)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
let dbPool = self.lock.synchronized { self.databaseAccess?.dbPool }
|
||||
dbPool?.asyncWriteWithoutTransaction { writerDB in
|
||||
self.stopDatabaseObservation(writerDB)
|
||||
}
|
||||
self.notifyError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidRollback(_ db: Database) {
|
||||
// Reset the isModified flag until next transaction
|
||||
observationState.isModified = false
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Ending the Observation
|
||||
|
||||
extension ValueConcurrentObserver: DatabaseCancellable {
|
||||
func cancel() {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
// Notify cancellation
|
||||
let (eventsOpt, dbPoolOpt): (ValueObservationEvents?, DatabasePool?) = lock.synchronized {
|
||||
let events = notificationCallbacks?.events
|
||||
notificationCallbacks = nil
|
||||
return (events, databaseAccess?.dbPool)
|
||||
}
|
||||
|
||||
guard let events = eventsOpt else { return /* Cancelled or failed */ }
|
||||
events.didCancel?()
|
||||
|
||||
// Stop observing the database
|
||||
// Do it asynchronously, so that we do not block the current thread:
|
||||
// cancellation may be triggered while a long write access is executing.
|
||||
guard let dbPool = dbPoolOpt else { return /* Failed */ }
|
||||
dbPool.asyncWriteWithoutTransaction { db in
|
||||
self.stopDatabaseObservation(db)
|
||||
}
|
||||
}
|
||||
|
||||
func notifyError(_ error: Error) {
|
||||
scheduler.schedule {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let eventsOpt: ValueObservationEvents? = self.lock.synchronized {
|
||||
let events = self.notificationCallbacks?.events
|
||||
self.notificationCallbacks = nil
|
||||
return events
|
||||
}
|
||||
guard let events = eventsOpt else { return /* Cancelled */ }
|
||||
events.didFail?(error)
|
||||
}
|
||||
}
|
||||
|
||||
private func stopDatabaseObservation(_ writerDB: Database) {
|
||||
writerDB.remove(transactionObserver: self)
|
||||
observationState = .notObserving
|
||||
lock.synchronized {
|
||||
databaseAccess = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,7 @@ public struct ValueObservation<Reducer: ValueReducer> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Configures the tracked region
|
||||
enum ValueObservationTrackingMode {
|
||||
/// The tracked region is constant and explicit.
|
||||
///
|
||||
@@ -187,7 +188,7 @@ extension ValueObservation: Refinable {
|
||||
-> ValueObservation<ValueReducers.Trace<Reducer>>
|
||||
{
|
||||
self
|
||||
.mapReducer({ reducer in
|
||||
.mapReducer { reducer in
|
||||
ValueReducers.Trace(
|
||||
base: reducer,
|
||||
// Adding the willFetch handler to the reducer is handy: we
|
||||
@@ -196,7 +197,7 @@ extension ValueObservation: Refinable {
|
||||
// Adding the didReceiveValue handler to the reducer is necessary:
|
||||
// the type of the value may change with the `map` operator.
|
||||
didReceiveValue: didReceiveValue ?? { _ in })
|
||||
})
|
||||
}
|
||||
.with {
|
||||
$0.events.willStart = concat($0.events.willStart, willStart)
|
||||
$0.events.willTrackRegion = concat($0.events.willTrackRegion, willTrackRegion)
|
||||
@@ -244,14 +245,14 @@ extension ValueObservation: Refinable {
|
||||
/// Returns the value.
|
||||
func fetchValue(_ db: Database) throws -> Reducer.Value {
|
||||
var reducer = makeReducer()
|
||||
guard let value = try reducer.fetchAndReduce(db) else {
|
||||
fatalError("Contract broken: reducer has no initial value")
|
||||
guard let value = try reducer._value(reducer._fetch(db)) else {
|
||||
fatalError("Broken contract: reducer has no initial value")
|
||||
}
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=5.5.2) && canImport(_Concurrency)
|
||||
#if compiler(>=5.6) && canImport(_Concurrency)
|
||||
extension ValueObservation {
|
||||
// MARK: - Asynchronous Observation
|
||||
/// The database observation, as an asynchronous sequence of
|
||||
@@ -401,11 +402,8 @@ extension ValueObservation {
|
||||
scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main))
|
||||
-> DatabasePublishers.Value<Reducer.Value>
|
||||
{
|
||||
DatabasePublishers.Value { [weak reader] (onError, onChange) in
|
||||
guard let reader = reader else {
|
||||
return AnyDatabaseCancellable(cancel: { })
|
||||
}
|
||||
return self.start(
|
||||
DatabasePublishers.Value { (onError, onChange) in
|
||||
self.start(
|
||||
in: reader,
|
||||
scheduling: scheduler,
|
||||
onError: onError,
|
||||
@@ -471,8 +469,8 @@ extension DatabasePublishers {
|
||||
downstream: Downstream)
|
||||
{
|
||||
state = .waitingForDemand(WaitingForDemand(
|
||||
downstream: downstream,
|
||||
start: start))
|
||||
downstream: downstream,
|
||||
start: start))
|
||||
}
|
||||
|
||||
func request(_ demand: Subscribers.Demand) {
|
||||
@@ -483,8 +481,8 @@ extension DatabasePublishers {
|
||||
return
|
||||
}
|
||||
state = .observing(Observing(
|
||||
downstream: info.downstream,
|
||||
remainingDemand: demand))
|
||||
downstream: info.downstream,
|
||||
remainingDemand: demand))
|
||||
let cancellable = info.start(
|
||||
{ [weak self] error in self?.receiveCompletion(.failure(error)) },
|
||||
{ [weak self] value in self?.receive(value) })
|
||||
|
||||
@@ -14,6 +14,9 @@ public class ValueObservationScheduler {
|
||||
impl.schedule(action)
|
||||
}
|
||||
|
||||
/// Returns whether the initial value should be immediately notified.
|
||||
///
|
||||
/// If true, then this method was called on the main thread.
|
||||
func immediateInitialValue() -> Bool {
|
||||
impl.immediateInitialValue()
|
||||
}
|
||||
@@ -71,6 +74,10 @@ public class ValueObservationScheduler {
|
||||
|
||||
private protocol ValueObservationSchedulerImpl {
|
||||
func schedule(_ action: @escaping () -> Void)
|
||||
|
||||
/// Returns whether the initial value should be immediately notified.
|
||||
///
|
||||
/// If true, then this method was called on the main thread.
|
||||
func immediateInitialValue() -> Bool
|
||||
}
|
||||
|
||||
|
||||
@@ -1,284 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
/// Support for ValueObservation.
|
||||
/// See DatabaseWriter.add(observation:onError:onChange:)
|
||||
final class ValueObserver<Reducer: ValueReducer> {
|
||||
var isCompleted: Bool { synchronized { _isCompleted } }
|
||||
let events: ValueObservationEvents
|
||||
let trackingMode: ValueObservationTrackingMode
|
||||
private var observedRegion: DatabaseRegion? {
|
||||
didSet {
|
||||
if let willTrackRegion = events.willTrackRegion,
|
||||
let region = observedRegion,
|
||||
region != oldValue
|
||||
{
|
||||
willTrackRegion(region)
|
||||
}
|
||||
}
|
||||
}
|
||||
private var _isCompleted = false
|
||||
private var reducer: Reducer
|
||||
private let requiresWriteAccess: Bool
|
||||
private weak var writer: DatabaseWriter?
|
||||
private let scheduler: ValueObservationScheduler
|
||||
private let reduceQueue: DispatchQueue
|
||||
private var isChanged = false
|
||||
private let onChange: (Reducer.Value) -> Void
|
||||
|
||||
// This lock protects `_isCompleted`.
|
||||
// It also protects `reducer` because of what is likely a compiler bug:
|
||||
// - <https://github.com/groue/GRDB.swift/issues/1026>
|
||||
// - <https://github.com/groue/GRDB.swift/pull/1025>
|
||||
private var lock = NSRecursiveLock() // protects _isCompleted and reducer
|
||||
|
||||
init(
|
||||
events: ValueObservationEvents,
|
||||
reducer: Reducer,
|
||||
requiresWriteAccess: Bool,
|
||||
trackingMode: ValueObservationTrackingMode,
|
||||
writer: DatabaseWriter,
|
||||
scheduler: ValueObservationScheduler,
|
||||
reduceQueue: DispatchQueue,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
{
|
||||
self.events = events
|
||||
self.reducer = reducer
|
||||
self.requiresWriteAccess = requiresWriteAccess
|
||||
self.trackingMode = trackingMode
|
||||
self.writer = writer
|
||||
self.scheduler = scheduler
|
||||
self.reduceQueue = reduceQueue
|
||||
self.onChange = onChange
|
||||
}
|
||||
|
||||
convenience init(
|
||||
observation: ValueObservation<Reducer>,
|
||||
writer: DatabaseWriter,
|
||||
scheduler: ValueObservationScheduler,
|
||||
reduceQueue: DispatchQueue,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
{
|
||||
self.init(
|
||||
events: observation.events,
|
||||
reducer: observation.makeReducer(),
|
||||
requiresWriteAccess: observation.requiresWriteAccess,
|
||||
trackingMode: observation.trackingMode,
|
||||
writer: writer,
|
||||
scheduler: scheduler,
|
||||
reduceQueue: reduceQueue,
|
||||
onChange: onChange)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - TransactionObserver
|
||||
|
||||
extension ValueObserver: TransactionObserver {
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
assert(
|
||||
observedRegion != nil,
|
||||
"fetchInitialValue() was not called before ValueObserver was added as a transaction observer")
|
||||
return observedRegion!.isModified(byEventsOfKind: eventKind)
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
assert(
|
||||
observedRegion != nil,
|
||||
"fetchInitialValue() was not called before ValueObserver was added as a transaction observer")
|
||||
if observedRegion!.isModified(by: event) {
|
||||
isChanged = true
|
||||
stopObservingDatabaseChangesUntilNextTransaction()
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidCommit(_ writerDB: Database) {
|
||||
guard isChanged else { return }
|
||||
isChanged = false
|
||||
if isCompleted { return }
|
||||
|
||||
events.databaseDidChange?()
|
||||
|
||||
guard let future = fetchFuture(writerDB) else {
|
||||
// Database connection closed: give up
|
||||
return
|
||||
}
|
||||
|
||||
reduce(future: future)
|
||||
}
|
||||
|
||||
func databaseDidRollback(_ db: Database) {
|
||||
isChanged = false
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Internal
|
||||
|
||||
extension ValueObserver {
|
||||
/// Fetch the initial observed value, and moves the reducer forward.
|
||||
///
|
||||
/// This method must be called once, before the observer is added
|
||||
/// to the database writer.
|
||||
func fetchInitialValue(_ db: Database) throws -> Reducer.Value {
|
||||
guard let value = try fetchValue(db) else {
|
||||
fatalError("Contract broken: reducer has no initial value")
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
/// Fetch an observed value, and moves the reducer forward.
|
||||
func fetchValue(_ db: Database) throws -> Reducer.Value? {
|
||||
try db.isolated(readOnly: !requiresWriteAccess) {
|
||||
try updatingObserverRegionIfNeeded(db) {
|
||||
try synchronized {
|
||||
try reducer.fetchAndReduce(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func complete() {
|
||||
synchronized {
|
||||
_isCompleted = true
|
||||
writer?.remove(transactionObserver: self)
|
||||
}
|
||||
}
|
||||
|
||||
func cancel() {
|
||||
synchronized {
|
||||
if _isCompleted { return }
|
||||
complete()
|
||||
events.didCancel?()
|
||||
}
|
||||
}
|
||||
|
||||
func notifyChange(_ value: Reducer.Value) {
|
||||
if isCompleted { return }
|
||||
scheduler.schedule {
|
||||
if self.isCompleted { return }
|
||||
self.onChange(value)
|
||||
}
|
||||
}
|
||||
|
||||
func notifyErrorAndComplete(_ error: Error) {
|
||||
if isCompleted { return }
|
||||
scheduler.schedule {
|
||||
let shouldNotify: Bool = self.synchronized {
|
||||
if self._isCompleted {
|
||||
return false
|
||||
} else {
|
||||
self.complete()
|
||||
return true
|
||||
}
|
||||
}
|
||||
if shouldNotify {
|
||||
self.events.didFail?(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
extension ValueObserver {
|
||||
/// Returns nil if the database was closed
|
||||
private func fetchFuture(_ writerDB: Database) -> DatabaseFuture<Reducer.Fetched>? {
|
||||
if requiresWriteAccess {
|
||||
// We obviously need to fetch from the writer connection
|
||||
return fetchFutureSync(writerDB)
|
||||
}
|
||||
|
||||
switch trackingMode {
|
||||
case .nonConstantRegionRecordedFromSelection:
|
||||
// When the tracked region is not constant, we must fetch from the
|
||||
// writer connection so that we do not miss future changes that
|
||||
// would modify the tracked region.
|
||||
return fetchFutureSync(writerDB)
|
||||
|
||||
case .constantRegion, .constantRegionRecordedFromSelection:
|
||||
// When the tracked region is constant, we can fetch concurrently.
|
||||
return fetchFutureConcurrent(writerDB)
|
||||
}
|
||||
}
|
||||
|
||||
private func fetchFutureSync(_ writerDB: Database) -> DatabaseFuture<Reducer.Fetched> {
|
||||
DatabaseFuture(Result {
|
||||
try writerDB.isolated(readOnly: !requiresWriteAccess) {
|
||||
try fetchUpdatingObserverRegionIfNeeded(writerDB)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns nil if the database was closed
|
||||
private func fetchFutureConcurrent(_ writerDB: Database) -> DatabaseFuture<Reducer.Fetched>? {
|
||||
guard let writer = writer else {
|
||||
// Database connection closed: give up
|
||||
return nil
|
||||
}
|
||||
return writer.concurrentRead { readerDB in
|
||||
try self.fetchUpdatingObserverRegionIfNeeded(readerDB)
|
||||
}
|
||||
}
|
||||
|
||||
private func fetchUpdatingObserverRegionIfNeeded(_ db: Database) throws -> Reducer.Fetched {
|
||||
try updatingObserverRegionIfNeeded(db) {
|
||||
let reducer = synchronized { self.reducer }
|
||||
return try reducer._fetch(db)
|
||||
}
|
||||
}
|
||||
|
||||
private func reduce(future: DatabaseFuture<Reducer.Fetched>) {
|
||||
// Wait for the future fetched value in reduceQueue. This guarantees:
|
||||
// - that notifications have the same ordering as transactions.
|
||||
// - that expensive reduce operations are computed without blocking
|
||||
// any database dispatch queue.
|
||||
reduceQueue.async {
|
||||
if self.isCompleted { return }
|
||||
do {
|
||||
let fetchedValue = try future.wait()
|
||||
if let value = self.synchronized({ self.reducer._value(fetchedValue) }) {
|
||||
self.notifyChange(value)
|
||||
}
|
||||
} catch {
|
||||
self.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func synchronized<T>(_ execute: () throws -> T) rethrows -> T {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return try execute()
|
||||
}
|
||||
|
||||
private func updatingObserverRegionIfNeeded<T>(
|
||||
_ db: Database,
|
||||
fetch: () throws -> T)
|
||||
throws -> T
|
||||
{
|
||||
switch trackingMode {
|
||||
case let .constantRegion(regions):
|
||||
if observedRegion == nil {
|
||||
observedRegion = try DatabaseRegion.union(regions)(db)
|
||||
}
|
||||
return try fetch()
|
||||
case .constantRegionRecordedFromSelection:
|
||||
if observedRegion == nil {
|
||||
return try recordingSelectedRegion(db, fetch: fetch)
|
||||
} else {
|
||||
return try fetch()
|
||||
}
|
||||
case .nonConstantRegionRecordedFromSelection:
|
||||
return try recordingSelectedRegion(db, fetch: fetch)
|
||||
}
|
||||
}
|
||||
|
||||
private func recordingSelectedRegion<T>(
|
||||
_ db: Database,
|
||||
fetch: () throws -> T)
|
||||
throws -> T
|
||||
{
|
||||
var region = DatabaseRegion()
|
||||
let result = try db.recordingSelection(®ion, fetch)
|
||||
observedRegion = try region.observableRegion(db)
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -32,12 +32,6 @@ public protocol _ValueReducer {
|
||||
/// The `ValueReducer` protocol supports `ValueObservation`.
|
||||
public protocol ValueReducer: _ValueReducer { }
|
||||
|
||||
extension ValueReducer {
|
||||
mutating func fetchAndReduce(_ db: Database) throws -> Value? {
|
||||
try _value(_fetch(db))
|
||||
}
|
||||
}
|
||||
|
||||
/// A namespace for types related to the `ValueReducer` protocol.
|
||||
public enum ValueReducers {
|
||||
// ValueReducers.Auto allows us to define ValueObservation factory methods.
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
import Foundation
|
||||
|
||||
/// `ValueWriteOnlyObserver` observes the database for `ValueObservation`.
|
||||
///
|
||||
/// It performs the following database observation cycle:
|
||||
///
|
||||
/// 1. Start observation or detect a database change
|
||||
/// 2. Fetch
|
||||
/// 3. Reduce
|
||||
/// 4. Notify
|
||||
///
|
||||
/// **Fetch** is always performed from the writer database connection (hence
|
||||
/// the name of this observer).
|
||||
///
|
||||
/// **Reduce** is the operation that turns the fetched database values into the
|
||||
/// observed values. Those are not the same. Consider, for example, the `map()`
|
||||
/// and `removeDuplicates()` operators: they perform their job during the
|
||||
/// reducing stage.
|
||||
///
|
||||
/// **Notify** is calling user callbacks, in case of database change or error.
|
||||
final class ValueWriteOnlyObserver<Writer: DatabaseWriter, Reducer: ValueReducer> {
|
||||
// MARK: - Configuration
|
||||
//
|
||||
// Configuration is not mutable.
|
||||
|
||||
/// How to schedule observed values and errors.
|
||||
private let scheduler: ValueObservationScheduler
|
||||
|
||||
/// If true, database values are fetched from a read-only access.
|
||||
private let readOnly: Bool
|
||||
|
||||
/// Configures the tracked database region.
|
||||
private let trackingMode: ValueObservationTrackingMode
|
||||
|
||||
// MARK: - Mutable State
|
||||
//
|
||||
// The observer has four distinct mutable states that evolve independently,
|
||||
// and are made thread-safe with various mechanisms:
|
||||
//
|
||||
// - A `DatabaseAccess`: ability to access the database. It is constant but
|
||||
// turns nil after the observation fails or is cancelled, in order to
|
||||
// release memory and resources when the observation completes. It is
|
||||
// guarded by `lock`, because observation can fail or be cancelled from
|
||||
// multiple threads.
|
||||
//
|
||||
// - A `NotificationCallbacks`: ability to notify observation events. It is
|
||||
// constant but turns nil when failure or cancellation is notified, in
|
||||
// order to release memory and resources when the observation completes.
|
||||
// It is guarded by `lock`, because observation can fail or be cancelled
|
||||
// from multiple threads.
|
||||
//
|
||||
// - An `ObservationState`: relationship with the `TransactionObserver`
|
||||
// protocol. It is only accessed from the serialized writer
|
||||
// dispatch queue.
|
||||
//
|
||||
// - A `Reducer`: the observation reducer, only accessed from the
|
||||
// serialized dispatch queue `reduceQueue`.
|
||||
//
|
||||
// The `reduceQueue` guarantees that fresh value notifications have the same
|
||||
// order as transactions. It is different from the serialized writer
|
||||
// dispatch queue because we do not want to lock the database as
|
||||
// computations (`map`, `removeDuplicates()`, etc.) are performed.
|
||||
//
|
||||
// Despite being protected by the same lock, `DatabaseAccess` and
|
||||
// `NotificationCallbacks` are not merged together. This is because the
|
||||
// observer does not lose `DatabaseAccess` at the same time it
|
||||
// looses `NotificationCallbacks`:
|
||||
//
|
||||
// - In case of cancellation, `NotificationCallbacks` is lost first, and
|
||||
// `DatabaseAccess` is lost asynchronously, after the observer could
|
||||
// resign as a transaction observer. See `cancel()`.
|
||||
//
|
||||
// - In case of error, `DatabaseAccess` is lost first, and
|
||||
// `NotificationCallbacks` is lost asynchronously, after the error could
|
||||
// be notified. See error catching clauses.
|
||||
|
||||
/// Ability to access the database
|
||||
private struct DatabaseAccess {
|
||||
/// The observed DatabaseWriter.
|
||||
let writer: Writer
|
||||
|
||||
/// The function that fetches database values.
|
||||
let fetch: (Database) throws -> Reducer.Fetched
|
||||
}
|
||||
|
||||
/// Ability to notify observation events
|
||||
private struct NotificationCallbacks {
|
||||
let events: ValueObservationEvents
|
||||
let onChange: (Reducer.Value) -> Void
|
||||
}
|
||||
|
||||
/// Relationship with the `TransactionObserver` protocol
|
||||
private struct ObservationState {
|
||||
var region: DatabaseRegion?
|
||||
var isModified = false
|
||||
|
||||
static var notObserving: Self { .init(region: nil, isModified: false) }
|
||||
}
|
||||
|
||||
/// Protects `databaseAccess` and `notificationCallbacks`.
|
||||
private let lock = NSLock()
|
||||
|
||||
/// The dispatch queue where database values are reduced into observed
|
||||
/// values before being notified. Protects `reducer`.
|
||||
private let reduceQueue: DispatchQueue
|
||||
|
||||
/// Access to the database, protected by `lock`.
|
||||
private var databaseAccess: DatabaseAccess?
|
||||
|
||||
/// Ability to notify observation events, protected by `lock`.
|
||||
private var notificationCallbacks: NotificationCallbacks?
|
||||
|
||||
/// Support for `TransactionObserver`, protected by the serialized writer
|
||||
/// dispatch queue.
|
||||
private var observationState = ObservationState.notObserving
|
||||
|
||||
/// Protected by `reduceQueue`.
|
||||
private var reducer: Reducer
|
||||
|
||||
init(
|
||||
writer: Writer,
|
||||
scheduler: ValueObservationScheduler,
|
||||
readOnly: Bool,
|
||||
trackingMode: ValueObservationTrackingMode,
|
||||
reducer: Reducer,
|
||||
events: ValueObservationEvents,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
{
|
||||
// Configuration
|
||||
self.scheduler = scheduler
|
||||
self.readOnly = readOnly
|
||||
self.trackingMode = trackingMode
|
||||
|
||||
// State
|
||||
self.databaseAccess = DatabaseAccess(
|
||||
writer: writer,
|
||||
// ValueReducer semantics guarantees that reducer._fetch
|
||||
// is independent from the reducer state
|
||||
fetch: reducer._fetch)
|
||||
self.notificationCallbacks = NotificationCallbacks(events: events, onChange: onChange)
|
||||
self.reducer = reducer
|
||||
self.reduceQueue = DispatchQueue(
|
||||
label: writer.configuration.identifier(
|
||||
defaultLabel: "GRDB",
|
||||
purpose: "ValueObservation"),
|
||||
qos: writer.configuration.readQoS)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Starting the Observation
|
||||
|
||||
extension ValueWriteOnlyObserver {
|
||||
// Starts the observation
|
||||
func start() -> DatabaseCancellable {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let (notificationCallbacksOpt, databaseAccessOpt) = lock.synchronized {
|
||||
(self.notificationCallbacks, self.databaseAccess)
|
||||
}
|
||||
guard let notificationCallbacks = notificationCallbacksOpt, let writer = databaseAccessOpt?.writer else {
|
||||
// Likely a GRDB bug: during a synchronous start, user is not
|
||||
// able to cancel observation.
|
||||
fatalError("can't start a cancelled or failed observation")
|
||||
}
|
||||
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
// Start the observation in an synchronous way
|
||||
let initialValue = try syncStart(from: writer)
|
||||
|
||||
// Notify the initial value from the dispatch queue the
|
||||
// observation was started from
|
||||
notificationCallbacks.onChange(initialValue)
|
||||
} catch {
|
||||
// Notify error from the dispatch queue the observation
|
||||
// was started from.
|
||||
notificationCallbacks.events.didFail?(error)
|
||||
|
||||
// Early return!
|
||||
return AnyDatabaseCancellable { /* nothing to cancel */ }
|
||||
}
|
||||
} else {
|
||||
// Start the observation in an asynchronous way
|
||||
asyncStart(from: writer)
|
||||
}
|
||||
|
||||
// Make sure the returned cancellable cancels the observation
|
||||
// when deallocated. We can't relying on the deallocation of
|
||||
// self to trigger early cancellation, because self may be retained by
|
||||
// some closure waiting to run in some DispatchQueue.
|
||||
return AnyDatabaseCancellable(self)
|
||||
}
|
||||
|
||||
/// Synchronously starts the observation, and returns the initial value.
|
||||
///
|
||||
/// Unlike `asyncStart()`, this method does not notify the initial value or error.
|
||||
private func syncStart(from writer: Writer) throws -> Reducer.Value {
|
||||
// Start from a write access, so that self can register as a
|
||||
// transaction observer.
|
||||
//
|
||||
// Start in a synchronous reentrant way, in case this method is called
|
||||
// from a database access.
|
||||
try writer.unsafeReentrantWrite { db in
|
||||
// Fetch & Start observing the database
|
||||
guard let fetchedValue = try fetchAndStartObservation(db) else {
|
||||
// Likely a GRDB bug: during a synchronous start, user is not
|
||||
// able to cancel observation.
|
||||
fatalError("can't start a cancelled or failed observation")
|
||||
}
|
||||
|
||||
// Reduce
|
||||
return reduceQueue.sync {
|
||||
guard let initialValue = reducer._value(fetchedValue) else {
|
||||
fatalError("Broken contract: reducer has no initial value")
|
||||
}
|
||||
|
||||
return initialValue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Asynchronously starts the observation
|
||||
///
|
||||
/// Unlike `syncStart()`, this method does notify the initial value or error.
|
||||
private func asyncStart(from writer: Writer) {
|
||||
// Start from a write access, so that self can register as a
|
||||
// transaction observer.
|
||||
writer.asyncWriteWithoutTransaction { db in
|
||||
do {
|
||||
// Fetch & Start observing the database
|
||||
guard let fetchedValue = try self.fetchAndStartObservation(db) else {
|
||||
return /* Cancelled */
|
||||
}
|
||||
|
||||
// Reduce
|
||||
//
|
||||
// Reducing is performed asynchronously, so that we do not lock
|
||||
// the writer dispatch queue longer than necessary.
|
||||
//
|
||||
// Important: reduceQueue.async guarantees the same ordering
|
||||
// between transactions and notifications!
|
||||
self.reduceQueue.async {
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
guard let initialValue = self.reducer._value(fetchedValue) else {
|
||||
fatalError("Broken contract: reducer has no initial value")
|
||||
}
|
||||
|
||||
// Notify
|
||||
self.scheduler.schedule {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let onChangeOpt = self.lock.synchronized { self.notificationCallbacks?.onChange }
|
||||
guard let onChange = onChangeOpt else { return /* Cancelled */ }
|
||||
onChange(initialValue)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
self.stopDatabaseObservation(db)
|
||||
self.notifyError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetches the initial value, and start observing the database.
|
||||
///
|
||||
/// Returns nil if the observation was cancelled before database observation
|
||||
/// could start.
|
||||
///
|
||||
/// By grouping the initial fetch and the beginning of observation in a
|
||||
/// single database access, we are sure that no concurrent write can happen
|
||||
/// during the initial fetch, and that we won't miss any future change.
|
||||
private func fetchAndStartObservation(_ db: Database) throws -> Reducer.Fetched? {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let (eventsOpt, fetchOpt) = lock.synchronized {
|
||||
(notificationCallbacks?.events, databaseAccess?.fetch)
|
||||
}
|
||||
guard let events = eventsOpt, let fetch = fetchOpt else {
|
||||
return nil /* Cancelled */
|
||||
}
|
||||
|
||||
switch trackingMode {
|
||||
case let .constantRegion(regions):
|
||||
let fetchedValue = try db.isolated(readOnly: readOnly) {
|
||||
try fetch(db)
|
||||
}
|
||||
let region = try DatabaseRegion.union(regions)(db)
|
||||
let observedRegion = try region.observableRegion(db)
|
||||
events.willTrackRegion?(observedRegion)
|
||||
startObservation(db, observedRegion: observedRegion)
|
||||
return fetchedValue
|
||||
|
||||
case .constantRegionRecordedFromSelection,
|
||||
.nonConstantRegionRecordedFromSelection:
|
||||
var region = DatabaseRegion()
|
||||
let fetchedValue = try db.recordingSelection(®ion) {
|
||||
try db.isolated(readOnly: readOnly) {
|
||||
try fetch(db)
|
||||
}
|
||||
}
|
||||
let observedRegion = try region.observableRegion(db)
|
||||
events.willTrackRegion?(observedRegion)
|
||||
startObservation(db, observedRegion: observedRegion)
|
||||
return fetchedValue
|
||||
}
|
||||
}
|
||||
|
||||
private func startObservation(_ db: Database, observedRegion: DatabaseRegion) {
|
||||
observationState.region = observedRegion
|
||||
assert(observationState.isModified == false)
|
||||
db.add(transactionObserver: self, extent: .observerLifetime)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Observing Database Transactions
|
||||
|
||||
extension ValueWriteOnlyObserver: TransactionObserver {
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
if let region = observationState.region {
|
||||
return region.isModified(byEventsOfKind: eventKind)
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
if let region = observationState.region, region.isModified(by: event) {
|
||||
// Database was modified!
|
||||
observationState.isModified = true
|
||||
// We can stop observing the current transaction
|
||||
stopObservingDatabaseChangesUntilNextTransaction()
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidCommit(_ db: Database) {
|
||||
// Ignore transaction unless database was modified
|
||||
guard observationState.isModified else { return }
|
||||
|
||||
// Reset the isModified flag until next transaction
|
||||
observationState.isModified = false
|
||||
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
// Ignore transaction unless we are still notifying database events, and
|
||||
// we can still fetch fresh values.
|
||||
let (eventsOpt, fetchOpt) = lock.synchronized {
|
||||
(notificationCallbacks?.events, databaseAccess?.fetch)
|
||||
}
|
||||
guard let events = eventsOpt, let fetch = fetchOpt else { return /* Cancelled */ }
|
||||
|
||||
// Notify
|
||||
events.databaseDidChange?()
|
||||
|
||||
do {
|
||||
// Fetch
|
||||
let fetchedValue: Reducer.Fetched
|
||||
|
||||
switch trackingMode {
|
||||
case .constantRegion, .constantRegionRecordedFromSelection:
|
||||
// Tracked region is already known. Fetch only.
|
||||
fetchedValue = try db.isolated(readOnly: readOnly) {
|
||||
try fetch(db)
|
||||
}
|
||||
case .nonConstantRegionRecordedFromSelection:
|
||||
// Fetch and update the tracked region.
|
||||
var region = DatabaseRegion()
|
||||
fetchedValue = try db.recordingSelection(®ion) {
|
||||
try db.isolated(readOnly: readOnly) {
|
||||
try fetch(db)
|
||||
}
|
||||
}
|
||||
|
||||
let observedRegion = try region.observableRegion(db)
|
||||
|
||||
// Don't spam the user with region tracking events: wait for an actual change
|
||||
if let willTrackRegion = events.willTrackRegion, observedRegion != observationState.region {
|
||||
willTrackRegion(observedRegion)
|
||||
}
|
||||
|
||||
observationState.region = observedRegion
|
||||
}
|
||||
|
||||
// Reduce
|
||||
//
|
||||
// Reducing is performed asynchronously, so that we do not lock
|
||||
// the writer dispatch queue longer than necessary.
|
||||
//
|
||||
// Important: reduceQueue.async guarantees the same ordering between
|
||||
// transactions and notifications!
|
||||
reduceQueue.async {
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
let value = self.reducer._value(fetchedValue)
|
||||
|
||||
// Notify value
|
||||
if let value = value {
|
||||
self.scheduler.schedule {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let onChangeOpt = self.lock.synchronized { self.notificationCallbacks?.onChange }
|
||||
guard let onChange = onChangeOpt else { return /* Cancelled */ }
|
||||
onChange(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
stopDatabaseObservation(db)
|
||||
notifyError(error)
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidRollback(_ db: Database) {
|
||||
// Reset the isModified flag until next transaction
|
||||
observationState.isModified = false
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Ending the Observation
|
||||
|
||||
extension ValueWriteOnlyObserver: DatabaseCancellable {
|
||||
func cancel() {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
// Notify cancellation
|
||||
let (eventsOpt, writerOpt): (ValueObservationEvents?, Writer?) = lock.synchronized {
|
||||
let events = notificationCallbacks?.events
|
||||
notificationCallbacks = nil
|
||||
return (events, databaseAccess?.writer)
|
||||
}
|
||||
|
||||
guard let events = eventsOpt else { return /* Cancelled or failed */ }
|
||||
events.didCancel?()
|
||||
|
||||
// Stop observing the database
|
||||
// Do it asynchronously, so that we do not block the current thread:
|
||||
// cancellation may be triggered while a long write access is executing.
|
||||
guard let writer = writerOpt else { return /* Failed */ }
|
||||
writer.asyncWriteWithoutTransaction { db in
|
||||
self.stopDatabaseObservation(db)
|
||||
}
|
||||
}
|
||||
|
||||
func notifyError(_ error: Error) {
|
||||
scheduler.schedule {
|
||||
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
|
||||
let eventsOpt: ValueObservationEvents? = self.lock.synchronized {
|
||||
let events = self.notificationCallbacks?.events
|
||||
self.notificationCallbacks = nil
|
||||
return events
|
||||
}
|
||||
guard let events = eventsOpt else { return /* Cancelled */ }
|
||||
events.didFail?(error)
|
||||
}
|
||||
}
|
||||
|
||||
private func stopDatabaseObservation(_ db: Database) {
|
||||
db.remove(transactionObserver: self)
|
||||
observationState = .notObserving
|
||||
lock.synchronized {
|
||||
databaseAccess = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -168,8 +168,8 @@
|
||||
5644DE8020F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */; };
|
||||
564B3D72239BDBD6007BF308 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */; };
|
||||
564B3D73239BDBD6007BF308 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */; };
|
||||
564CE43C21AA955B00652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueObserver.swift */; };
|
||||
564CE43D21AA955B00652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueObserver.swift */; };
|
||||
564CE43C21AA955B00652B19 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueConcurrentObserver.swift */; };
|
||||
564CE43D21AA955B00652B19 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueConcurrentObserver.swift */; };
|
||||
564CE4E321B2E05400652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */; };
|
||||
564CE4E421B2E05400652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */; };
|
||||
564CE5B721B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */; };
|
||||
@@ -214,6 +214,8 @@
|
||||
5653EB8120961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6420961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift */; };
|
||||
5653EB8220961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */; };
|
||||
5653EB8320961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */; };
|
||||
56564F3928637C9900A19E9F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56564F3828637C9900A19E9F /* WALSnapshot.swift */; };
|
||||
56564F3A28637C9900A19E9F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56564F3828637C9900A19E9F /* WALSnapshot.swift */; };
|
||||
5656A7F622946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A7F422946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; };
|
||||
5656A7F722946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A7F422946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; };
|
||||
5656A8512295BD56001FF3FF /* SQLInterpolation+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8262295BD56001FF3FF /* SQLInterpolation+QueryInterface.swift */; };
|
||||
@@ -360,6 +362,8 @@
|
||||
5676FBAB22F5CEB9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */; };
|
||||
56781B08243F7B5300650A83 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = 56781B06243F7B4B00650A83 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; };
|
||||
56781B09243F7B5300650A83 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = 56781B06243F7B4B00650A83 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; };
|
||||
5679533927E0A305004D18BD /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5679533727E0A305004D18BD /* ValueWriteOnlyObserver.swift */; };
|
||||
5679533A27E0A305004D18BD /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5679533727E0A305004D18BD /* ValueWriteOnlyObserver.swift */; };
|
||||
567A80561D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; };
|
||||
567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; };
|
||||
567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; };
|
||||
@@ -533,6 +537,8 @@
|
||||
56F34FC724B0A0C9007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC524B0A0C8007513FC /* SQLIdentifyingColumnsTests.swift */; };
|
||||
56F3E74C1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
|
||||
56F3E7501E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
|
||||
56F61DEA283D469F00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DE8283D469F00AF9884 /* getThreadsCount.c */; };
|
||||
56F61DEB283D469F00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DE8283D469F00AF9884 /* getThreadsCount.c */; };
|
||||
56FBFED62210731100945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED52210731000945324 /* SQLRequest.swift */; };
|
||||
56FBFED72210731100945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED52210731000945324 /* SQLRequest.swift */; };
|
||||
56FEB8FE248403270081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */; };
|
||||
@@ -886,7 +892,7 @@
|
||||
5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = "<group>"; };
|
||||
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
|
||||
564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = "<group>"; };
|
||||
564CE43B21AA955B00652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = "<group>"; };
|
||||
564CE43B21AA955B00652B19 /* ValueConcurrentObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueConcurrentObserver.swift; sourceTree = "<group>"; };
|
||||
564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = "<group>"; };
|
||||
564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = "<group>"; };
|
||||
564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = "<group>"; };
|
||||
@@ -909,6 +915,7 @@
|
||||
5653EB6320961FB200F46237 /* AssociationChainSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainSQLTests.swift; sourceTree = "<group>"; };
|
||||
5653EB6420961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToDecodableRecordTests.swift; sourceTree = "<group>"; };
|
||||
5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = "<group>"; };
|
||||
56564F3828637C9900A19E9F /* WALSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshot.swift; sourceTree = "<group>"; };
|
||||
5656A7F422946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationQueryInterfaceRequestTests.swift; sourceTree = "<group>"; };
|
||||
5656A8262295BD56001FF3FF /* SQLInterpolation+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLInterpolation+QueryInterface.swift"; sourceTree = "<group>"; };
|
||||
5656A8282295BD56001FF3FF /* FTS5+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FTS5+QueryInterface.swift"; sourceTree = "<group>"; };
|
||||
@@ -991,6 +998,7 @@
|
||||
5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchableRecordDecodableTests.swift; sourceTree = "<group>"; };
|
||||
5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = "<group>"; };
|
||||
56781B06243F7B4B00650A83 /* GRDB-Bridging.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "GRDB-Bridging.h"; path = "SQLiteCustom/GRDB-Bridging.h"; sourceTree = "<group>"; };
|
||||
5679533727E0A305004D18BD /* ValueWriteOnlyObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueWriteOnlyObserver.swift; sourceTree = "<group>"; };
|
||||
567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = "<group>"; };
|
||||
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = "<group>"; };
|
||||
567E4207242AB3CB00CAAD2C /* FailureTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FailureTestCase.swift; sourceTree = "<group>"; };
|
||||
@@ -1130,6 +1138,8 @@
|
||||
56F34FBD24B094D1007513FC /* SQLExpressionIsConstantTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLExpressionIsConstantTests.swift; sourceTree = "<group>"; };
|
||||
56F34FC524B0A0C8007513FC /* SQLIdentifyingColumnsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLIdentifyingColumnsTests.swift; sourceTree = "<group>"; };
|
||||
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = "<group>"; };
|
||||
56F61DE8283D469F00AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
|
||||
56F61DE9283D469F00AF9884 /* getThreadsCount.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = getThreadsCount.h; sourceTree = "<group>"; };
|
||||
56FBFED52210731000945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = "<group>"; };
|
||||
56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = "<group>"; };
|
||||
56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTraceTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1259,6 +1269,8 @@
|
||||
569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */,
|
||||
56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */,
|
||||
563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */,
|
||||
56F61DE8283D469F00AF9884 /* getThreadsCount.c */,
|
||||
56F61DE9283D469F00AF9884 /* getThreadsCount.h */,
|
||||
);
|
||||
name = DatabasePool;
|
||||
sourceTree = "<group>";
|
||||
@@ -1282,9 +1294,10 @@
|
||||
children = (
|
||||
563082E82430B6CD00C14A05 /* DatabaseCancellable.swift */,
|
||||
560233D027243A9100529DF3 /* SharedValueObservation.swift */,
|
||||
564CE43B21AA955B00652B19 /* ValueConcurrentObserver.swift */,
|
||||
5613ED5921A95E6100DC7A68 /* ValueObservation.swift */,
|
||||
563A4B6F242E7CE50075D8CF /* ValueObservationScheduler.swift */,
|
||||
564CE43B21AA955B00652B19 /* ValueObserver.swift */,
|
||||
5679533727E0A305004D18BD /* ValueWriteOnlyObserver.swift */,
|
||||
56C0538822ACEECD0029D27D /* ValueReducer */,
|
||||
);
|
||||
path = ValueObservation;
|
||||
@@ -1820,8 +1833,9 @@
|
||||
56A238781B9C75030082EB20 /* Statement.swift */,
|
||||
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
|
||||
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
|
||||
5605F1471C672E4000235C62 /* Support */,
|
||||
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
|
||||
56564F3828637C9900A19E9F /* WALSnapshot.swift */,
|
||||
5605F1471C672E4000235C62 /* Support */,
|
||||
);
|
||||
path = Core;
|
||||
sourceTree = "<group>";
|
||||
@@ -1951,8 +1965,8 @@
|
||||
DC37742D19C8CC90004FCF85 /* GRDB */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56A2386F1B9C75030082EB20 /* Core */,
|
||||
56A2FA3724424F4200E97D23 /* Export.swift */,
|
||||
56A2386F1B9C75030082EB20 /* Core */,
|
||||
5614089D221596A100DAD589 /* Fixit */,
|
||||
5698AC291D9E5A480056AF8C /* FTS */,
|
||||
56A238911B9C750B0082EB20 /* Migration */,
|
||||
@@ -2045,9 +2059,9 @@
|
||||
buildConfigurationList = F3BA80031CFB25E4003DC1BA /* Build configuration list for PBXNativeTarget "GRDBiOS" */;
|
||||
buildPhases = (
|
||||
EED476F01CFD0B290026A4EC /* Copy .example configuration files (if no USER customizations exist) */,
|
||||
F3BA7FFB1CFB25E4003DC1BA /* Headers */,
|
||||
F3BA7FF91CFB25E4003DC1BA /* Sources */,
|
||||
F3BA7FFA1CFB25E4003DC1BA /* Frameworks */,
|
||||
F3BA7FFB1CFB25E4003DC1BA /* Headers */,
|
||||
F3BA7FFC1CFB25E4003DC1BA /* Resources */,
|
||||
56EB54FD22C9119B00850069 /* Swiftlint */,
|
||||
);
|
||||
@@ -2084,9 +2098,9 @@
|
||||
buildConfigurationList = F3BA805F1CFB2BB2003DC1BA /* Build configuration list for PBXNativeTarget "GRDBOSX" */;
|
||||
buildPhases = (
|
||||
EED476F51CFD1A610026A4EC /* Copy .example configuration files (if no USER customizations exist) */,
|
||||
F3BA80571CFB2BB2003DC1BA /* Headers */,
|
||||
F3BA80551CFB2BB2003DC1BA /* Sources */,
|
||||
F3BA80561CFB2BB2003DC1BA /* Frameworks */,
|
||||
F3BA80571CFB2BB2003DC1BA /* Headers */,
|
||||
F3BA80581CFB2BB2003DC1BA /* Resources */,
|
||||
56EB54FB22C9118600850069 /* Swiftlint */,
|
||||
);
|
||||
@@ -2134,7 +2148,7 @@
|
||||
};
|
||||
F3BA80401CFB2AD7003DC1BA = {
|
||||
CreatedOnToolsVersion = 7.3.1;
|
||||
LastSwiftMigration = 1020;
|
||||
LastSwiftMigration = 1340;
|
||||
};
|
||||
F3BA80591CFB2BB2003DC1BA = {
|
||||
CreatedOnToolsVersion = 7.3.1;
|
||||
@@ -2142,7 +2156,7 @@
|
||||
};
|
||||
F3BA809A1CFB2F6F003DC1BA = {
|
||||
CreatedOnToolsVersion = 7.3.1;
|
||||
LastSwiftMigration = 1020;
|
||||
LastSwiftMigration = 1340;
|
||||
};
|
||||
};
|
||||
};
|
||||
@@ -2221,6 +2235,7 @@
|
||||
/* Begin PBXShellScriptBuildPhase section */
|
||||
56EB54FB22C9118600850069 /* Swiftlint */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
alwaysOutOfDate = 1;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
@@ -2239,6 +2254,7 @@
|
||||
};
|
||||
56EB54FD22C9119B00850069 /* Swiftlint */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
alwaysOutOfDate = 1;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
@@ -2298,6 +2314,7 @@
|
||||
files = (
|
||||
5656A8722295BD56001FF3FF /* HasOneThroughAssociation.swift in Sources */,
|
||||
56713FE42691F487006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
5679533A27E0A305004D18BD /* ValueWriteOnlyObserver.swift in Sources */,
|
||||
5636E9C11D22574100B9B05F /* FetchRequest.swift in Sources */,
|
||||
F3BA801B1CFB2886003DC1BA /* CGFloat.swift in Sources */,
|
||||
563B8FBE24A1D388007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
@@ -2347,6 +2364,7 @@
|
||||
56A6EB2526076F6A00C27594 /* SQL.swift in Sources */,
|
||||
5656A8762295BD56001FF3FF /* RequestProtocols.swift in Sources */,
|
||||
568ECB3625D91CEF00B71526 /* SQLSubquery.swift in Sources */,
|
||||
56564F3A28637C9900A19E9F /* WALSnapshot.swift in Sources */,
|
||||
561729552235340E0006E219 /* EncodableRecord.swift in Sources */,
|
||||
5656A87E2295BD56001FF3FF /* SQLAssociation.swift in Sources */,
|
||||
F3BA80131CFB2876003DC1BA /* DatabaseValue.swift in Sources */,
|
||||
@@ -2401,7 +2419,7 @@
|
||||
561408A1221596A100DAD589 /* GRDB-5.0.swift in Sources */,
|
||||
F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */,
|
||||
56FBFED72210731100945324 /* SQLRequest.swift in Sources */,
|
||||
564CE43D21AA955B00652B19 /* ValueObserver.swift in Sources */,
|
||||
564CE43D21AA955B00652B19 /* ValueConcurrentObserver.swift in Sources */,
|
||||
5674A6FD1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
|
||||
F3BA80141CFB2876003DC1BA /* DatabaseValueConvertible.swift in Sources */,
|
||||
5656A8702295BD56001FF3FF /* Association.swift in Sources */,
|
||||
@@ -2553,6 +2571,7 @@
|
||||
56419C8724A51D6F004967E1 /* ValueObservationPublisherTests.swift in Sources */,
|
||||
560432A7228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */,
|
||||
5690C33E1D23E7D200E59934 /* FoundationDateTests.swift in Sources */,
|
||||
56F61DEB283D469F00AF9884 /* getThreadsCount.c in Sources */,
|
||||
567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */,
|
||||
5674A7291F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */,
|
||||
56057C5A2291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */,
|
||||
@@ -2667,6 +2686,7 @@
|
||||
files = (
|
||||
5656A8712295BD56001FF3FF /* HasOneThroughAssociation.swift in Sources */,
|
||||
56713FE32691F487006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
5679533927E0A305004D18BD /* ValueWriteOnlyObserver.swift in Sources */,
|
||||
5636E9BE1D22574100B9B05F /* FetchRequest.swift in Sources */,
|
||||
F3BA80771CFB2E5C003DC1BA /* CGFloat.swift in Sources */,
|
||||
563B8FBD24A1D388007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
@@ -2716,6 +2736,7 @@
|
||||
56A6EB2426076F6A00C27594 /* SQL.swift in Sources */,
|
||||
5656A8752295BD56001FF3FF /* RequestProtocols.swift in Sources */,
|
||||
568ECB3525D91CEF00B71526 /* SQLSubquery.swift in Sources */,
|
||||
56564F3928637C9900A19E9F /* WALSnapshot.swift in Sources */,
|
||||
561729562235340E0006E219 /* EncodableRecord.swift in Sources */,
|
||||
5656A87D2295BD56001FF3FF /* SQLAssociation.swift in Sources */,
|
||||
F3BA806F1CFB2E55003DC1BA /* DatabaseValue.swift in Sources */,
|
||||
@@ -2770,7 +2791,7 @@
|
||||
561408A0221596A100DAD589 /* GRDB-5.0.swift in Sources */,
|
||||
F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */,
|
||||
56FBFED62210731100945324 /* SQLRequest.swift in Sources */,
|
||||
564CE43C21AA955B00652B19 /* ValueObserver.swift in Sources */,
|
||||
564CE43C21AA955B00652B19 /* ValueConcurrentObserver.swift in Sources */,
|
||||
5674A6FC1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
|
||||
F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */,
|
||||
5656A86F2295BD56001FF3FF /* Association.swift in Sources */,
|
||||
@@ -2922,6 +2943,7 @@
|
||||
56419C8224A51D6E004967E1 /* ValueObservationPublisherTests.swift in Sources */,
|
||||
560432A6228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */,
|
||||
5698AC061D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */,
|
||||
56F61DEA283D469F00AF9884 /* getThreadsCount.c in Sources */,
|
||||
F3BA80FA1CFB3021003DC1BA /* SelectStatementTests.swift in Sources */,
|
||||
5674A7271F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */,
|
||||
56057C592291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */,
|
||||
@@ -3231,6 +3253,7 @@
|
||||
baseConfigurationReference = F3BA813B1CFB3770003DC1BA /* GRDBCustomSQLite-Testing.xcconfig */;
|
||||
buildSettings = {
|
||||
CLANG_ANALYZER_NONNULL = YES;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
@@ -3244,6 +3267,9 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCustomSQLite.GRDBCustomSQLiteiOSTests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Tests/GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -3252,6 +3278,7 @@
|
||||
baseConfigurationReference = F3BA813B1CFB3770003DC1BA /* GRDBCustomSQLite-Testing.xcconfig */;
|
||||
buildSettings = {
|
||||
CLANG_ANALYZER_NONNULL = YES;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
COPY_PHASE_STRIP = NO;
|
||||
@@ -3267,7 +3294,9 @@
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Tests/GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
@@ -3333,6 +3362,7 @@
|
||||
baseConfigurationReference = F3BA813B1CFB3770003DC1BA /* GRDBCustomSQLite-Testing.xcconfig */;
|
||||
buildSettings = {
|
||||
CLANG_ANALYZER_NONNULL = YES;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
CODE_SIGN_IDENTITY = "-";
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
@@ -3347,6 +3377,9 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCustomSQLiteOSXTests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = macosx;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Tests/GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -3355,6 +3388,7 @@
|
||||
baseConfigurationReference = F3BA813B1CFB3770003DC1BA /* GRDBCustomSQLite-Testing.xcconfig */;
|
||||
buildSettings = {
|
||||
CLANG_ANALYZER_NONNULL = YES;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
CODE_SIGN_IDENTITY = "-";
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
@@ -3371,7 +3405,9 @@
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = macosx;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Tests/GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
# make distclean - Restore repository to a pristine state
|
||||
|
||||
default: test
|
||||
smokeTest: test_framework_GRDBiOS_maxTarget test_framework_GRDBiOS_minTarget test_framework_SQLCipher4 test_framework_GRDBCustomSQLiteiOS_maxTarget test_SPM
|
||||
smokeTest: test_framework_GRDBiOS_maxTarget test_framework_GRDBiOS_minTarget test_framework_SQLCipher4Encrypted test_framework_GRDBCustomSQLiteiOS_maxTarget test_SPM
|
||||
|
||||
# Requirements
|
||||
# ============
|
||||
@@ -50,14 +50,41 @@ TEST_ACTIONS = clean build build-for-testing test-without-building
|
||||
|
||||
# When adding support for an Xcode version, look for available devices with
|
||||
# `xcrun xctrace list devices` (or the deprecated `instruments -s devices`).
|
||||
ifeq ($(XCODEVERSION),13.2)
|
||||
ifeq ($(XCODEVERSION),14.0)
|
||||
MAX_SWIFT_VERSION = 5.7
|
||||
MIN_SWIFT_VERSION = 5.3
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 13,OS=16.0"
|
||||
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=12.4"
|
||||
MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=16.0"
|
||||
#MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" TODO: restore
|
||||
OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK'
|
||||
GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1'
|
||||
else ifeq ($(XCODEVERSION),13.4)
|
||||
MAX_SWIFT_VERSION = 5.6
|
||||
MIN_SWIFT_VERSION = 5.3
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 13,OS=15.5"
|
||||
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=13.7"
|
||||
MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=15.4"
|
||||
#MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" TODO: restore
|
||||
OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK'
|
||||
GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1'
|
||||
else ifeq ($(XCODEVERSION),13.3)
|
||||
MAX_SWIFT_VERSION = 5.6
|
||||
MIN_SWIFT_VERSION = 5.3
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 13,OS=15.4"
|
||||
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=13.7"
|
||||
MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=15.4"
|
||||
#MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" TODO: restore
|
||||
OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK'
|
||||
GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1'
|
||||
else ifeq ($(XCODEVERSION),13.2)
|
||||
MAX_SWIFT_VERSION = 5.5
|
||||
MIN_SWIFT_VERSION = 5.3
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 13,OS=15.2"
|
||||
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=13.7"
|
||||
MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=15.2"
|
||||
#MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" TODO: restore
|
||||
OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks'
|
||||
OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK'
|
||||
GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1'
|
||||
else ifeq ($(XCODEVERSION),13.1)
|
||||
MAX_SWIFT_VERSION = 5.5
|
||||
@@ -162,7 +189,7 @@ test_framework: test_framework_darwin
|
||||
test_framework_darwin: test_framework_GRDB test_framework_GRDBCustom test_framework_SQLCipher test_SPM
|
||||
test_framework_GRDB: test_framework_GRDBOSX test_framework_GRDBWatchOS test_framework_GRDBiOS test_framework_GRDBtvOS
|
||||
test_framework_GRDBCustom: test_framework_GRDBCustomSQLiteOSX test_framework_GRDBCustomSQLiteiOS
|
||||
test_framework_SQLCipher: test_framework_SQLCipher3 test_framework_SQLCipher4
|
||||
test_framework_SQLCipher: test_framework_SQLCipher3 test_framework_SQLCipher3Encrypted test_framework_SQLCipher4 test_framework_SQLCipher4Encrypted
|
||||
test_archive: test_archive_GRDBOSX_xcframework
|
||||
test_install: test_install_manual test_install_SPM test_install_customSQLite test_install_GRDB_CocoaPods test_CocoaPodsLint
|
||||
test_CocoaPodsLint: test_CocoaPodsLint_GRDB
|
||||
@@ -330,6 +357,21 @@ else
|
||||
@exit 1
|
||||
endif
|
||||
|
||||
test_framework_SQLCipher3Encrypted:
|
||||
ifdef POD
|
||||
cd Tests/CocoaPods/SQLCipher3 && \
|
||||
$(POD) install && \
|
||||
$(XCODEBUILD) \
|
||||
-workspace GRDBTests.xcworkspace \
|
||||
-scheme GRDBEncryptedTests \
|
||||
SWIFT_VERSION=$(MAX_SWIFT_VERSION) \
|
||||
build-for-testing test-without-building \
|
||||
$(XCPRETTY)
|
||||
else
|
||||
@echo CocoaPods must be installed for test_framework_SQLCipher3Encrypted
|
||||
@exit 1
|
||||
endif
|
||||
|
||||
test_framework_SQLCipher4:
|
||||
ifdef POD
|
||||
cd Tests/CocoaPods/SQLCipher4 && \
|
||||
@@ -345,6 +387,21 @@ else
|
||||
@exit 1
|
||||
endif
|
||||
|
||||
test_framework_SQLCipher4Encrypted:
|
||||
ifdef POD
|
||||
cd Tests/CocoaPods/SQLCipher4 && \
|
||||
$(POD) install && \
|
||||
$(XCODEBUILD) \
|
||||
-workspace GRDBTests.xcworkspace \
|
||||
-scheme GRDBEncryptedTests \
|
||||
SWIFT_VERSION=$(MAX_SWIFT_VERSION) \
|
||||
build-for-testing test-without-building \
|
||||
$(XCPRETTY)
|
||||
else
|
||||
@echo CocoaPods must be installed for test_framework_SQLCipher4Encrypted
|
||||
@exit 1
|
||||
endif
|
||||
|
||||
test_SPM:
|
||||
# Add sanitizers when available: https://twitter.com/simjp/status/929140877540278272
|
||||
$(SWIFT) package clean
|
||||
@@ -379,7 +436,7 @@ test_install_manual:
|
||||
clean build \
|
||||
$(XCPRETTY)
|
||||
|
||||
test_install_SPM: test_install_SPM_Package test_install_SPM_Project test_install_SPM_macos_release test_install_SPM_ios_release
|
||||
test_install_SPM: test_install_SPM_Package test_install_SPM_Project test_install_SPM_Dynamic_Project test_install_SPM_macos_release test_install_SPM_ios_release
|
||||
|
||||
test_install_SPM_Package:
|
||||
cd Tests/SPM/PlainPackage && \
|
||||
@@ -393,6 +450,15 @@ test_install_SPM_Project:
|
||||
-configuration Release \
|
||||
clean build \
|
||||
$(XCPRETTY)
|
||||
|
||||
test_install_SPM_Dynamic_Project:
|
||||
$(XCODEBUILD) \
|
||||
-project Tests/SPM/ios-dynamic/ios-dynamic.xcodeproj \
|
||||
-scheme ios-dynamic \
|
||||
-destination $(MAX_IOS_DESTINATION) \
|
||||
-configuration Release \
|
||||
clean build \
|
||||
$(XCPRETTY)
|
||||
|
||||
test_install_SPM_macos_release:
|
||||
$(XCODEBUILD) \
|
||||
@@ -520,10 +586,10 @@ ifdef JAZZY
|
||||
--author 'Gwendal Roué' \
|
||||
--author_url https://github.com/groue \
|
||||
--github_url https://github.com/groue/GRDB.swift \
|
||||
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.19.0 \
|
||||
--module-version 5.19.0 \
|
||||
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.26.1 \
|
||||
--module-version 5.26.1 \
|
||||
--module GRDB \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/5.19/ \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/5.26/ \
|
||||
--output Documentation/Reference \
|
||||
--xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS
|
||||
else
|
||||
|
||||
@@ -13,6 +13,7 @@ let package = Package(
|
||||
],
|
||||
products: [
|
||||
.library(name: "GRDB", targets: ["GRDB"]),
|
||||
.library(name: "GRDB-dynamic", type: .dynamic, targets: ["GRDB"]),
|
||||
],
|
||||
dependencies: [
|
||||
],
|
||||
@@ -34,6 +35,7 @@ let package = Package(
|
||||
"Crash",
|
||||
"Performance",
|
||||
"SPM",
|
||||
"GRDBTests/getThreadsCount.c",
|
||||
])
|
||||
],
|
||||
swiftLanguageVersions: [.v5]
|
||||
|
||||
@@ -11,13 +11,13 @@
|
||||
|
||||
---
|
||||
|
||||
**Latest release**: January 19, 2022 • [version 5.19.0](https://github.com/groue/GRDB.swift/tree/v5.19.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
|
||||
**Latest release**: September 8, 2022 • [version 5.26.1](https://github.com/groue/GRDB.swift/tree/v5.26.1) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
|
||||
|
||||
**Requirements**: iOS 11.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ • SQLite 3.8.5+ • Swift 5.3+ / Xcode 12+
|
||||
|
||||
| Swift version | GRDB version |
|
||||
| -------------- | ----------------------------------------------------------- |
|
||||
| **Swift 5.3+** | **v5.19.0** |
|
||||
| **Swift 5.3+** | **v5.26.1** |
|
||||
| Swift 5.2 | [v5.12.0](https://github.com/groue/GRDB.swift/tree/v5.12.0) |
|
||||
| Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
|
||||
| Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
|
||||
@@ -63,7 +63,7 @@ See [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md) if you are looking for your
|
||||
|
||||
## Features
|
||||
|
||||
GRDB ships with:
|
||||
Programming tools for both database beginners and SQLite experts:
|
||||
|
||||
- [Access to raw SQL and SQLite](#sqlite-api)
|
||||
- [Records](#records): Fetching and persistence methods for your custom structs and class hierarchies.
|
||||
@@ -72,18 +72,21 @@ GRDB ships with:
|
||||
- [WAL Mode Support](#database-pools): Extra performance for multi-threaded applications.
|
||||
- [Migrations]: Transform your database as your application evolves.
|
||||
- [Database Observation]: Observe database changes and transactions.
|
||||
- [Swift Concurrency]: `try await` your database (Xcode 13.2+).
|
||||
- [Combine Support]: Access and observe the database with Combine publishers.
|
||||
- [RxSwift Support](http://github.com/RxSwiftCommunity/RxGRDB): Access and observe the database with RxSwift observables.
|
||||
- [Full-Text Search]
|
||||
- [Encryption](#encryption)
|
||||
- [Support for Custom SQLite Builds](Documentation/CustomSQLiteBuilds.md)
|
||||
|
||||
In-depth integration with our programming environment:
|
||||
|
||||
- [Swift Concurrency]: `try await` your database (Xcode 13.3.1+).
|
||||
- [SwiftUI](http://github.com/groue/GRDBQuery): Access and observe the database from your SwiftUI views.
|
||||
- [Combine](Documentation/Combine.md): Access and observe the database with Combine publishers.
|
||||
- [RxSwift](http://github.com/RxSwiftCommunity/RxGRDB): Access and observe the database with RxSwift observables.
|
||||
|
||||
## Usage
|
||||
|
||||
<details open>
|
||||
<summary>Start using the database in four easy steps</summary>
|
||||
<summary>Start using the database in four steps</summary>
|
||||
|
||||
```swift
|
||||
import GRDB
|
||||
@@ -318,7 +321,7 @@ Documentation
|
||||
|
||||
#### Reference
|
||||
|
||||
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.19/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
|
||||
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.26/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
|
||||
|
||||
#### Getting Started
|
||||
|
||||
@@ -397,6 +400,8 @@ GRDB can be installed as a framework, or a static library.
|
||||
|
||||
The [Swift Package Manager](https://swift.org/package-manager/) automates the distribution of Swift code. To use GRDB with SPM, add a dependency to `https://github.com/groue/GRDB.swift.git`
|
||||
|
||||
GRDB offers two libraries, `GRDB` and `GRDB-dynamic`. Pick only one. When in doubt, prefer `GRDB`. The `GRDB-dynamic` library can reveal useful if you are going to link it with multiple targets within your app and only wish to link to a shared, dynamic framework once. See [How to link a Swift Package as dynamic](https://forums.swift.org/t/how-to-link-a-swift-package-as-dynamic/32062) for more information.
|
||||
|
||||
> :point_up: **Note**: Linux is not currently supported.
|
||||
>
|
||||
> :warning: **Warning**: Due to an Xcode bug, you will get "No such module 'CSQLite'" errors when you want to embed the GRDB package in other targets than the main application (watch extensions, for example). UI and Unit testing targets are OK, though. See [#642](https://github.com/groue/GRDB.swift/issues/642#issuecomment-575994093) for more information.
|
||||
@@ -486,6 +491,8 @@ let newPlaceCount = try dbQueue.write { db -> Int in
|
||||
}
|
||||
```
|
||||
|
||||
See the [Concurrency] guide for asynchronous database accesses.
|
||||
|
||||
**A database queue serializes accesses to the database**, which means that there is never more than one thread that uses the database.
|
||||
|
||||
- When you don't need to modify the database, prefer the `read` method. It prevents any modification to the database.
|
||||
@@ -496,23 +503,9 @@ let newPlaceCount = try dbQueue.write { db -> Int in
|
||||
|
||||
**A database queue needs your application to follow rules in order to deliver its safety guarantees.** Please refer to the [Concurrency] guide.
|
||||
|
||||
> :bulb: **Tip**: see the [Demo Applications] for sample code that sets up a database queue on iOS.
|
||||
See [Database Configuration] for DatabaseQueue options.
|
||||
|
||||
|
||||
### DatabaseQueue Configuration
|
||||
|
||||
```swift
|
||||
var config = Configuration()
|
||||
config.readonly = true
|
||||
config.foreignKeysEnabled = true // Default is already true
|
||||
config.label = "MyDatabase" // Useful when your app opens multiple databases
|
||||
|
||||
let dbQueue = try DatabaseQueue(
|
||||
path: "/path/to/database.sqlite",
|
||||
configuration: config)
|
||||
```
|
||||
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.19/Structs/Configuration.html) for more details.
|
||||
> :bulb: **Tip**: see the [Demo Applications] for sample code.
|
||||
|
||||
|
||||
## Database Pools
|
||||
@@ -557,11 +550,13 @@ let newPlaceCount = try dbPool.write { db -> Int in
|
||||
}
|
||||
```
|
||||
|
||||
See the [Concurrency] guide for asynchronous database accesses.
|
||||
|
||||
**Database pools allow several threads to access the database at the same time:**
|
||||
|
||||
- When you don't need to modify the database, prefer the `read` method, because several threads can perform reads in parallel.
|
||||
|
||||
Reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be [configured](#databasepool-configuration).
|
||||
Reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be [configured](#database-configuration).
|
||||
|
||||
- Reads are guaranteed an immutable view of the last committed state of the database, regardless of concurrent writes. This kind of isolation is called [snapshot isolation](https://sqlite.org/isolation.html).
|
||||
|
||||
@@ -575,27 +570,54 @@ let newPlaceCount = try dbPool.write { db -> Int in
|
||||
|
||||
**A database pool needs your application to follow rules in order to deliver its safety guarantees.** See the [Concurrency] guide for more details about database pools, how they differ from database queues, and advanced use cases.
|
||||
|
||||
> :bulb: **Tip**: see the [Demo Applications] for sample code that sets up a database queue on iOS, and just replace DatabaseQueue with DatabasePool.
|
||||
See [Database Configuration] for DatabasePool options.
|
||||
|
||||
> :bulb: **Tip**: see the [Demo Applications] for sample code.
|
||||
|
||||
|
||||
### DatabasePool Configuration
|
||||
## Database Configuration
|
||||
|
||||
```swift
|
||||
var config = Configuration()
|
||||
config.readonly = true
|
||||
config.foreignKeysEnabled = true // Default is already true
|
||||
config.label = "MyDatabase" // Useful when your app opens multiple databases
|
||||
config.maximumReaderCount = 10 // The default is 5
|
||||
config.maximumReaderCount = 10 // (DatabasePool only) The default is 5
|
||||
|
||||
let dbPool = try DatabasePool(
|
||||
let dbQueue = try DatabaseQueue( // or DatabasePool
|
||||
path: "/path/to/database.sqlite",
|
||||
configuration: config)
|
||||
```
|
||||
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.19/Structs/Configuration.html) for more details.
|
||||
In debug builds, you can increase the verbosity of [error descriptions](#databaseerror) and [trace events](#how-do-i-print-a-request-as-sql) if you opt in for public statement arguments:
|
||||
|
||||
```swift
|
||||
#if DEBUG
|
||||
// Protect sensitive information by enabling verbose debugging in DEBUG builds only
|
||||
config.publicStatementArguments = true
|
||||
#endif
|
||||
|
||||
Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information.
|
||||
let dbQueue = try DatabaseQueue(path: ..., configuration: config)
|
||||
|
||||
do {
|
||||
try dbQueue.write { db in
|
||||
user.name = ...
|
||||
user.location = ...
|
||||
user.address = ...
|
||||
user.phoneNumber = ...
|
||||
try user.save(db)
|
||||
}
|
||||
} catch {
|
||||
// Prints sensitive information in debug builds only
|
||||
print(error)
|
||||
}
|
||||
```
|
||||
|
||||
> :warning: **Warning**: It is your responsibility to prevent sensitive information from leaking in unexpected locations, so you should not set the `publicStatementArguments` flag in release builds (think about GDPR and other privacy-related rules).
|
||||
>
|
||||
> :warning: **Warning**: The SQLite version that ships with old operating systems (prior to OSX 10.12, tvOS 10.0, and watchOS 3.0) outputs statement arguments in the [trace events](#how-do-i-print-a-request-as-sql), regardless of the `publicStatementArguments` flag.
|
||||
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.26/Structs/Configuration.html) for more details and configuration options.
|
||||
|
||||
|
||||
SQLite API
|
||||
@@ -652,7 +674,7 @@ try dbQueue.write { db in
|
||||
}
|
||||
```
|
||||
|
||||
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.19/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
|
||||
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
|
||||
|
||||
You can also embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details.
|
||||
|
||||
@@ -910,7 +932,7 @@ try dbQueue.read { db in
|
||||
let dictionary = try Dictionary(uniqueKeysWithValues: cursor)
|
||||
```
|
||||
|
||||
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.19/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
|
||||
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.26/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
|
||||
|
||||
```swift
|
||||
// Prints all Github links
|
||||
@@ -989,7 +1011,7 @@ let rows = try Row.fetchAll(db,
|
||||
arguments: ["name": "Arthur"])
|
||||
```
|
||||
|
||||
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.19/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
|
||||
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
|
||||
|
||||
Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care:
|
||||
|
||||
@@ -1274,7 +1296,7 @@ GRDB ships with built-in support for the following value types:
|
||||
|
||||
- Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol.
|
||||
|
||||
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.19/Structs/StatementArguments.html):
|
||||
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let url: URL = ...
|
||||
@@ -1373,6 +1395,8 @@ Here is how GRDB supports the various [date formats](https://www.sqlite.org/lang
|
||||
|
||||
³ GRDB 2+ interprets numerical values as timestamps that fuel `Date(timeIntervalSince1970:)`. Previous GRDB versions used to interpret numbers as [julian days](https://en.wikipedia.org/wiki/Julian_day). Julian days are still supported, with the `Date(julianDay:)` initializer.
|
||||
|
||||
> :warning: **Warning**: the range of valid years in the SQLite date formats is 0000-9999. You will need to pick another date format when your application needs to process years outside of this range. See the following chapters.
|
||||
|
||||
|
||||
#### Date
|
||||
|
||||
@@ -1395,19 +1419,39 @@ Dates are stored using the format "YYYY-MM-DD HH:MM:SS.SSS" in the UTC time zone
|
||||
> - Comparable with the SQLite keyword CURRENT_TIMESTAMP (`WHERE date > CURRENT_TIMESTAMP` works)
|
||||
> - Able to feed [SQLite date & time functions](https://www.sqlite.org/lang_datefunc.html)
|
||||
> - Precise enough
|
||||
>
|
||||
> :warning: **Warning**: the range of valid years in the SQLite date format is 0000-9999. You will experience problems with years outside of this range, such as decoding errors, or invalid date computations with [SQLite date & time functions](https://www.sqlite.org/lang_datefunc.html).
|
||||
|
||||
When the default format does not fit your needs, customize date conversions. For example:
|
||||
Some applications may prefer another date format:
|
||||
|
||||
- Some may prefer ISO-8601, with a `T` separator.
|
||||
- Some may prefer ISO-8601, with a time zone.
|
||||
- Some may need to store years beyond the 0000-9999 range.
|
||||
- Some may need sub-millisecond precision.
|
||||
- Some may need exact `Date` roundtrip.
|
||||
- Etc.
|
||||
|
||||
**You should think twice before choosing a different date format:**
|
||||
|
||||
- ISO-8601 is about *exchange and communication*, when SQLite is about *storage and data manipulation*. Sharing the same representation in your database and in JSON files only provides a superficial convenience, and should be the least of your priorities. Don't store dates as ISO-8601 without understanding what you lose. For example, ISO-8601 time zones forbid database-level date comparison.
|
||||
- Sub-millisecond precision and exact `Date` roundtrip are not as obvious needs as it seems at first sight. Dates generally don't precisely roundtrip as soon as they leave your application anyway, because the other systems your app communicates with use their own date representation (the Android version of your app, the server your application is talking to, etc.) On top of that, `Date` comparison is at least as hard and nasty as [floating point comparison](https://www.google.com/search?q=floating+point+comparison+is+hard).
|
||||
|
||||
The customization of date format is explicit. For example:
|
||||
|
||||
```swift
|
||||
let date = Date()
|
||||
let timeInterval = date.timeIntervalSinceReferenceDate
|
||||
try db.execute(
|
||||
sql: "INSERT INTO player (creationDate, ...) VALUES (?, ...)",
|
||||
arguments: [Date().timeIntervalSinceReferenceDate, ...])
|
||||
arguments: [timeInterval, ...])
|
||||
|
||||
let row = try Row.fetchOne(db, ...)!
|
||||
let creationDate = Date(timeIntervalSinceReferenceDate: row["creationDate"])
|
||||
if let row = try Row.fetchOne(db, ...) {
|
||||
let timeInterval: TimeInterval = row["creationDate"]
|
||||
let creationDate = Date(timeIntervalSinceReferenceDate: timeInterval)
|
||||
}
|
||||
```
|
||||
|
||||
See [Codable Records] for more date customization options.
|
||||
See also [Codable Records] for more date customization options, and [DatabaseValueConvertible](#custom-value-types) if you want to define a Date-wrapping type with customized database representation.
|
||||
|
||||
|
||||
#### DateComponents
|
||||
@@ -1416,6 +1460,8 @@ DateComponents is indirectly supported, through the **DatabaseDateComponents** h
|
||||
|
||||
DatabaseDateComponents reads date components from all [date formats supported by SQLite](https://www.sqlite.org/lang_datefunc.html), and stores them in the format of your choice, from HH:MM to YYYY-MM-DD HH:MM:SS.SSS.
|
||||
|
||||
> :warning: **Warning**: the range of valid years is 0000-9999. You will experience problems with years outside of this range, such as decoding errors, or invalid date computations with [SQLite date & time functions](https://www.sqlite.org/lang_datefunc.html). See [Date](#date) for more information.
|
||||
|
||||
DatabaseDateComponents can be stored and fetched from the database just like other [values](#values):
|
||||
|
||||
```swift
|
||||
@@ -1721,7 +1767,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction
|
||||
}
|
||||
```
|
||||
|
||||
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.19/Structs/Configuration.html) configuration flag:
|
||||
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.26/Structs/Configuration.html) configuration flag:
|
||||
|
||||
```swift
|
||||
// fatal error: A transaction has been left opened at the end of a database access
|
||||
@@ -1833,7 +1879,7 @@ try dbQueue.write { db in
|
||||
}
|
||||
```
|
||||
|
||||
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.19/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
|
||||
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
|
||||
|
||||
```swift
|
||||
insertStatement.arguments = ["name": "Arthur", "score": 1000]
|
||||
@@ -1916,7 +1962,7 @@ See also `Database.execute(sql:)` in the [Executing Updates](#executing-updates)
|
||||
|
||||
> :point_up: **Note**: it is a programmer error to reuse a prepared statement that has failed: GRDB may crash if you do so.
|
||||
|
||||
For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.19/Classes/Statement.html).
|
||||
For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.26/Classes/Statement.html).
|
||||
|
||||
|
||||
### Prepared Statements Cache
|
||||
@@ -2659,7 +2705,7 @@ try Place.fetchSet(db, sql: "SELECT ...", arguments:...) // Set<Place>
|
||||
try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place?
|
||||
```
|
||||
|
||||
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.19/Structs/StatementArguments.html) for more information about the query arguments.
|
||||
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html) for more information about the query arguments.
|
||||
|
||||
> :point_up: **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`.
|
||||
|
||||
@@ -3099,7 +3145,7 @@ protocol EncodableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.19/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.19/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies.
|
||||
See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.26/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.26/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies.
|
||||
|
||||
|
||||
### Date and UUID Coding Strategies
|
||||
@@ -3121,7 +3167,7 @@ protocol EncodableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.19/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.19/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.19/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
|
||||
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.26/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.26/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.26/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
|
||||
|
||||
There is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs and uuid strings, both uppercase and lowercase).
|
||||
|
||||
@@ -4440,18 +4486,6 @@ You can now build requests with the following methods: `all`, `none`, `select`,
|
||||
Player.annotated(with: (scoreColumn + bonusColumn).forKey("total"))
|
||||
```
|
||||
|
||||
Such annotations can help using [Associations]:
|
||||
|
||||
```swift
|
||||
// SELECT player.*, team.name
|
||||
// FROM player
|
||||
// JOIN team ON team.id = player.teamId
|
||||
let teamAlias = TableAlias()
|
||||
let request = Player
|
||||
.annotated(with: teamAlias[nameColumn])
|
||||
.joining(required: Player.team.aliased(teamAlias))
|
||||
```
|
||||
|
||||
- `annotated(with: aggregate)` extends the selection with [association aggregates](Documentation/AssociationsBasics.md#association-aggregates).
|
||||
|
||||
```swift
|
||||
@@ -4462,6 +4496,15 @@ You can now build requests with the following methods: `all`, `none`, `select`,
|
||||
Team.annotated(with: Team.players.count)
|
||||
```
|
||||
|
||||
- `annotated(withRequired: association)` and `annotated(withOptional: association)` extends the selection with [Associations].
|
||||
|
||||
```swift
|
||||
// SELECT player.*, team.color
|
||||
// FROM player
|
||||
// JOIN team ON team.id = player.teamId
|
||||
Player.annotated(withRequired: Player.team.select(colorColumn))
|
||||
```
|
||||
|
||||
- `distinct()` performs uniquing.
|
||||
|
||||
```swift
|
||||
@@ -4649,7 +4692,7 @@ Player // SELECT * FROM player
|
||||
```
|
||||
|
||||
|
||||
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.19/Structs/StatementArguments.html):
|
||||
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate)
|
||||
@@ -5555,7 +5598,7 @@ try Player.customRequest().fetchAll(db) // [Player]
|
||||
|
||||
- The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method.
|
||||
|
||||
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.19/Structs/AnyFetchRequest.html): a type-erased request.
|
||||
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.26/Structs/AnyFetchRequest.html): a type-erased request.
|
||||
|
||||
|
||||
## Joined Queries Support
|
||||
@@ -6099,10 +6142,10 @@ See the companion library [RxGRDB] for more information.
|
||||
- By default, ValueObservation notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously. This can be [configured](#valueobservation-scheduling).
|
||||
- ValueObservation may coalesce subsequent changes into a single notification.
|
||||
- ValueObservation may notify consecutive identical values. You can filter out the undesired duplicates with the [removeDuplicates](#valueobservationremoveduplicates) method.
|
||||
- Starting an observation retains the database connection, until it is stopped. As long as the observation is active, the database connection won't be deallocated.
|
||||
- The database observation stops when any of those conditions is met:
|
||||
- The cancellable returned by the `start` method is cancelled or deinitialized.
|
||||
- An error occurs.
|
||||
- The database connection is closed.
|
||||
|
||||
Take care that there are use cases that ValueObservation is unfit for. For example, your application may need to process absolutely all changes, and avoid any coalescing. It may also need to process changes before any further modifications are performed in the database file. In those cases, you need to track *individual transactions*, not values. See [DatabaseRegionObservation]. If you need to process uncommitted changes, see [TransactionObserver](#transactionobserver-protocol).
|
||||
|
||||
@@ -6372,19 +6415,15 @@ let sharedObservation = ValueObservation
|
||||
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
```
|
||||
|
||||
> :point_up: **Note**: `ValueObservation` and `SharedValueObservation` are nearly identical, but there are a few differences you should be aware of:
|
||||
>
|
||||
> - `SharedValueObservation` has no [operator](#valueobservation-operators) such as `map`. As a replacement, you may use Combine apis:
|
||||
>
|
||||
> ```swift
|
||||
> let sharedObservation = ValueObservation.tracking { ... }.shared(in: dbQueue)
|
||||
> let cancellable = try sharedObservation
|
||||
> .publisher() // Turn shared observation into a Combine Publisher
|
||||
> .map { ... } // The map operator from Combine
|
||||
> .sink(...)
|
||||
> ```
|
||||
>
|
||||
> - Unlike `ValueObservation`, `SharedValueObservation` retains the database connection. As long as there exists a `SharedValueObservation` instance, or an active suscription to a shared observation, the database connection won't be deinitialized.
|
||||
> :point_up: **Note**: `ValueObservation` and `SharedValueObservation` are nearly identical, but there is a difference you should be aware of. `SharedValueObservation` has no [operator](#valueobservation-operators) such as `map`. As a replacement, you may, for example, use Combine apis:
|
||||
>
|
||||
> ```swift
|
||||
> let sharedObservation = ValueObservation.tracking { ... }.shared(in: dbQueue)
|
||||
> let cancellable = try sharedObservation
|
||||
> .publisher() // Turn shared observation into a Combine Publisher
|
||||
> .map { ... } // The map operator from Combine
|
||||
> .sink(...)
|
||||
> ```
|
||||
|
||||
|
||||
### Specifying the Region Tracked by ValueObservation
|
||||
@@ -6651,6 +6690,8 @@ By default, database holds weak references to its transaction observers: they ar
|
||||
**A transaction observer is notified of all database changes**: inserts, updates and deletes. This includes indirect changes triggered by ON DELETE and ON UPDATE actions associated to [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions), and [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
|
||||
|
||||
> :point_up: **Note**: Some changes are not notified: changes to internal system tables (such as `sqlite_master`), changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables, and the deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite).
|
||||
>
|
||||
> :point_up: **Note**: Transactions performed during read-only database accesses are not notified.
|
||||
|
||||
Notified changes are not actually written to disk until the [transaction](#transactions-and-savepoints) commits, and the `databaseDidCommit` callback is called. On the other side, `databaseDidRollback` confirms their invalidation:
|
||||
|
||||
@@ -6762,7 +6803,7 @@ class PlayerScoreObserver: TransactionObserver {
|
||||
}
|
||||
```
|
||||
|
||||
When the `observes(eventsOfKind:)` method returns false for all event kinds, the observer is still notified of commits and rollbacks:
|
||||
When the `observes(eventsOfKind:)` method returns false for all event kinds, the observer is still notified of commits and rollbacks (except during read-only database accesses):
|
||||
|
||||
```swift
|
||||
class PureTransactionObserver: TransactionObserver {
|
||||
@@ -6859,7 +6900,7 @@ DatabaseRegion helps [ValueObservation] and [DatabaseRegionObservation] track ch
|
||||
|
||||
For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table.
|
||||
|
||||
For more details, see the [reference](https://groue.github.io/GRDB.swift/docs/5.19/Structs/DatabaseRegion.html).
|
||||
For more details, see the [reference](https://groue.github.io/GRDB.swift/docs/5.26/Structs/DatabaseRegion.html).
|
||||
|
||||
|
||||
#### The DatabaseRegionConvertible Protocol
|
||||
@@ -7380,13 +7421,15 @@ do {
|
||||
// [1, "Bobby"]
|
||||
error.arguments
|
||||
|
||||
// Full error description:
|
||||
// "SQLite error 19 with statement `INSERT INTO pet (masterId, name)
|
||||
// VALUES (?, ?)` arguments [1, "Bobby"]: FOREIGN KEY constraint failed""
|
||||
// Full error description
|
||||
// > SQLite error 19: FOREIGN KEY constraint failed -
|
||||
// > while executing `INSERT INTO pet (masterId, name) VALUES (?, ?)`
|
||||
error.description
|
||||
}
|
||||
```
|
||||
|
||||
If you want to see statement arguments in the error description, [make statement arguments public](#database-configuration).
|
||||
|
||||
**SQLite uses [results codes](https://www.sqlite.org/rescode.html) to distinguish between various errors**.
|
||||
|
||||
You can catch a DatabaseError and match on result codes:
|
||||
@@ -7675,12 +7718,36 @@ dbPool.releaseMemory()
|
||||
|
||||
This method blocks the current thread until all current database accesses are completed, and the memory collected.
|
||||
|
||||
> :warning: **Warning**: If `DatabasePool.releaseMemory()` is called while a long read is performed concurrently, then no other read access will be possible until this long read has completed, and the memory has been released. If this does not suit your application needs, look for the asynchronous options below:
|
||||
|
||||
You can release memory in an asynchronous way as well:
|
||||
|
||||
```swift
|
||||
// On a DatabaseQueue
|
||||
dbQueue.asyncWriteWithoutTransaction { db in
|
||||
db.releaseMemory()
|
||||
}
|
||||
|
||||
// On a DatabasePool
|
||||
dbPool.releaseMemoryEventually()
|
||||
```
|
||||
|
||||
`DatabasePool.releaseMemoryEventually()` does not block the current thread, and does not prevent concurrent database accesses. In exchange for this convenience, you don't know when memory has been freed.
|
||||
|
||||
|
||||
### Memory Management on iOS
|
||||
|
||||
**The iOS operating system likes applications that do not consume much memory.**
|
||||
|
||||
[Database queues](#database-queues) and [pools](#database-pools) automatically call the `releaseMemory` method when the application receives a memory warning, and when the application enters background.
|
||||
[Database queues](#database-queues) and [pools](#database-pools) automatically free non-essential memory when the application receives a memory warning, and when the application enters background.
|
||||
|
||||
You can opt out of this automatic memory management:
|
||||
|
||||
```swift
|
||||
var config = Configuration()
|
||||
config.automaticMemoryManagement = false
|
||||
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) // or DatabasePool
|
||||
```
|
||||
|
||||
|
||||
## Data Protection
|
||||
@@ -7832,9 +7899,10 @@ You can compile the request into a prepared statement:
|
||||
|
||||
```swift
|
||||
try dbQueue.read { db in
|
||||
let request = Player.filter(Column("name") == "O'Brien")
|
||||
let request = Player.filter(Column("email") == "arthur@example.com")
|
||||
let statement = try request.makePreparedRequest(db).statement
|
||||
print(statement) // SQL: SELECT * FROM player WHERE name = ?, Arguments: ["O'Brien"]
|
||||
print(statement) // SELECT * FROM player WHERE email = ?
|
||||
print(statement.arguments) // ["arthur@example.com"]
|
||||
}
|
||||
```
|
||||
|
||||
@@ -7849,21 +7917,12 @@ config.prepareDatabase { db in
|
||||
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
|
||||
|
||||
try dbQueue.read { db in
|
||||
let players = try Player.filter(Column("name") == "O'Brien").fetchAll(db)
|
||||
// Prints SELECT * FROM player WHERE name = 'O''Brien'
|
||||
// Prints "SELECT * FROM player WHERE email = ?"
|
||||
let players = try Player.filter(Column("email") == "arthur@example.com").fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
If you want to hide values such as `'O''Brien'` from the logged statements, adapt the tracing function as below:
|
||||
|
||||
```swift
|
||||
db.trace { event in
|
||||
if case let .statement(statement) = event {
|
||||
// Prints SELECT * FROM player WHERE name = ?
|
||||
print(statement.sql)
|
||||
}
|
||||
}
|
||||
```
|
||||
If you want to see statement arguments such as `'arthur@example.com'` in the logged statements, [make statement arguments public](#database-configuration).
|
||||
|
||||
> :point_up: **Note**: the generated SQL may change between GRDB releases, without notice: don't have your application rely on any specific SQL output.
|
||||
|
||||
@@ -7895,11 +7954,13 @@ config.prepareDatabase { db in
|
||||
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
|
||||
|
||||
try dbQueue.read { db in
|
||||
let players = try Player.filter(Column("name") == "O'Brien").fetchAll(db)
|
||||
// Prints "0.003s SELECT * FROM player WHERE name = 'O''Brien'"
|
||||
let players = try Player.filter(Column("email") == "arthur@example.com").fetchAll(db)
|
||||
// Prints "0.003s SELECT * FROM player WHERE email = ?"
|
||||
}
|
||||
```
|
||||
|
||||
If you want to see statement arguments such as `'arthur@example.com'` in the logged statements, [make statement arguments public](#database-configuration).
|
||||
|
||||
### What Are Experimental Features?
|
||||
|
||||
Since GRDB 1.0, all backwards compatibility guarantees of [semantic versioning](http://semver.org) apply: no breaking change will happen until the next major version of the library.
|
||||
@@ -8203,7 +8264,7 @@ When this is the case, there are two possible explanations:
|
||||
try db.execute(sql: "UPDATE player SET name = ?", arguments: [name])
|
||||
```
|
||||
|
||||
For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.19/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp).
|
||||
For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.26/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp).
|
||||
|
||||
|
||||
|
||||
@@ -8264,7 +8325,7 @@ Sample Code
|
||||
**Thanks**
|
||||
|
||||
- [Pierlis](http://pierlis.com), where we write great software.
|
||||
- [@alextrob](https://github.com/alextrob), [@alexwlchan](https://github.com/alexwlchan), [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@charlesmchen-signal](https://github.com/charlesmchen-signal), [@Chiliec](https://github.com/Chiliec), [@chrisballinger](https://github.com/chrisballinger), [@darrenclark](https://github.com/darrenclark), [@davidkraus](https://github.com/davidkraus), [@eburns-vmware](https://github.com/eburns-vmware), [@felixscheinost](https://github.com/felixscheinost), [@fpillet](http://github.com/fpillet), [@gcox](https://github.com/gcox), [@GetToSet](https://github.com/GetToSet), [@gjeck](https://github.com/gjeck), [@gusrota](https://github.com/gusrota), [@haikusw](https://github.com/haikusw), [@hartbit](https://github.com/hartbit), [@holsety](https://github.com/holsety), [@jroselightricks](https://github.com/jroselightricks), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@KyleLeneau](https://github.com/KyleLeneau), [@layoutSubviews](https://github.com/layoutSubviews), [@mallman](https://github.com/mallman), [@MartinP7r](https://github.com/MartinP7r), [@Marus](https://github.com/Marus), [@mattgallagher](https://github.com/mattgallagher), [@MaxDesiatov](https://github.com/MaxDesiatov), [@michaelkirk-signal](https://github.com/michaelkirk-signal), [@mtancock](https://github.com/mtancock), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@pp5x](https://github.com/pp5x), [@professordeng](https://github.com/professordeng), [@robcas3](https://github.com/robcas3), [@runhum](https://github.com/runhum), [@sberrevoets](https://github.com/sberrevoets), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@steipete](https://github.com/steipete), [@swiftlyfalling](https://github.com/swiftlyfalling), [@Timac](https://github.com/Timac), [@tternes](https://github.com/tternes), [@valexa](https://github.com/valexa), [@wuyuehyang](https://github.com/wuyuehyang), [@ZevEisenberg](https://github.com/ZevEisenberg), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB.
|
||||
- [@alextrob](https://github.com/alextrob), [@alexwlchan](https://github.com/alexwlchan), [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@charlesmchen-signal](https://github.com/charlesmchen-signal), [@Chiliec](https://github.com/Chiliec), [@chrisballinger](https://github.com/chrisballinger), [@darrenclark](https://github.com/darrenclark), [@davidkraus](https://github.com/davidkraus), [@eburns-vmware](https://github.com/eburns-vmware), [@felixscheinost](https://github.com/felixscheinost), [@fpillet](http://github.com/fpillet), [@gcox](https://github.com/gcox), [@GetToSet](https://github.com/GetToSet), [@gjeck](https://github.com/gjeck), [@guidedways](https://github.com/guidedways), [@gusrota](https://github.com/gusrota), [@haikusw](https://github.com/haikusw), [@hartbit](https://github.com/hartbit), [@holsety](https://github.com/holsety), [@jroselightricks](https://github.com/jroselightricks), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@KyleLeneau](https://github.com/KyleLeneau), [@layoutSubviews](https://github.com/layoutSubviews), [@mallman](https://github.com/mallman), [@MartinP7r](https://github.com/MartinP7r), [@Marus](https://github.com/Marus), [@mattgallagher](https://github.com/mattgallagher), [@MaxDesiatov](https://github.com/MaxDesiatov), [@michaelkirk-signal](https://github.com/michaelkirk-signal), [@mtancock](https://github.com/mtancock), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@pp5x](https://github.com/pp5x), [@professordeng](https://github.com/professordeng), [@robcas3](https://github.com/robcas3), [@runhum](https://github.com/runhum), [@sberrevoets](https://github.com/sberrevoets), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@steipete](https://github.com/steipete), [@swiftlyfalling](https://github.com/swiftlyfalling), [@Timac](https://github.com/Timac), [@tternes](https://github.com/tternes), [@valexa](https://github.com/valexa), [@wuyuehyang](https://github.com/wuyuehyang), [@ZevEisenberg](https://github.com/ZevEisenberg), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB.
|
||||
- [@aymerick](https://github.com/aymerick) and [@kali](https://github.com/kali) because SQL.
|
||||
- [ccgus/fmdb](https://github.com/ccgus/fmdb) for its excellency.
|
||||
|
||||
@@ -8344,7 +8405,7 @@ This chapter has [moved](Documentation/Concurrency.md#database-snapshots).
|
||||
|
||||
#### DatabaseWriter and DatabaseReader Protocols
|
||||
|
||||
This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.19/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.19/Protocols/DatabaseWriter.html).
|
||||
This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.26/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.26/Protocols/DatabaseWriter.html).
|
||||
|
||||
#### Asynchronous APIs
|
||||
|
||||
@@ -8397,7 +8458,8 @@ This chapter was renamed to [Embedding SQL in Query Interface Requests].
|
||||
[Sharing a Database]: Documentation/SharingADatabase.md
|
||||
[FAQ]: #faq
|
||||
[Database Observation]: #database-changes-observation
|
||||
[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.19/Structs/SQLRequest.html
|
||||
[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.26/Structs/SQLRequest.html
|
||||
[SQL literal]: Documentation/SQLInterpolation.md#sql-literal
|
||||
[Identifiable]: https://developer.apple.com/documentation/swift/identifiable
|
||||
[Query Interface Organization]: Documentation/QueryInterfaceOrganization.md
|
||||
[Database Configuration]: #database-configuration
|
||||
@@ -56,6 +56,7 @@ opt_in_rules:
|
||||
- reduce_into
|
||||
- redundant_type_annotation
|
||||
- sorted_first_last
|
||||
- sorted_imports
|
||||
- toggle_bool
|
||||
- unused_declaration
|
||||
- unused_import
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>5.19.0</string>
|
||||
<string>5.26.1</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
- [ ] Enhance the introduction to SQLRequest, based on the feedback in https://github.com/groue/GRDB.swift/issues/617
|
||||
- [ ] Association: document how to use aggregates with inner join (testAnnotatedWithHasManyDefaultMaxJoiningRequired)
|
||||
- [ ] Should we document that `PRAGMA locking_mode = EXCLUSIVE` improves performances? https://sqlite.org/forum/forumpost/866bf3407a
|
||||
|
||||
|
||||
## Features
|
||||
@@ -22,11 +23,17 @@
|
||||
- [ ] Property wrapper that decodes dictionaries (but how to tell the key column?)
|
||||
- [X] See if SQLITE_FCNTL_DATA_VERSION could help working around the lack of snapshots in order to avoid double initial fetch of ValueObservation. Result: no, it does not look it returns values that are comparable between two distinct SQLite connections (from the initial reader, and from the writer thhat starts the observation)
|
||||
- [ ] Grab all FTS tokens in a string
|
||||
- [ ] GRDB 6: Swift 5.7
|
||||
- [ ] GRDB 6: any / some
|
||||
- [ ] GRDB 6: primary associated types (cursor, requests, ...)
|
||||
- [ ] GRDB 6: remove existential/generic duplicated methods
|
||||
- [ ] GRDB 6: remove useless AnyXXX Type erasers
|
||||
- [ ] GRDB 6: decoding errors
|
||||
- [ ] GRDB 6: conflict resolution in persistence methods
|
||||
- [ ] GRDB 6: UPSERT
|
||||
- [ ] GRDB 6: support for RETURNING
|
||||
- [ ] GRDB 6: allow mutating `update` (for timestamps)
|
||||
- [ ] GRDB 6: choose persistence table
|
||||
- [ ] Long run edition. Use case: user edits the database (CRUD) but the application wants to commit and the end of the editing session.
|
||||
* Create an edition SQLite connection with an open transaction (a new kind of DatabaseWriter with a save() method)
|
||||
* All other writes will fail with SQLITE_BUSY. Unless they are schedules in a target dispatch queue which is paused during the edition.
|
||||
|
||||
@@ -447,6 +447,8 @@
|
||||
565A27CD27871FFF00659A62 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565A27CB27871FFF00659A62 /* BackupTestCase.swift */; };
|
||||
5691D97527257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; };
|
||||
5691D97627257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; };
|
||||
56F61DF0283D484700AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DEE283D484700AF9884 /* getThreadsCount.c */; };
|
||||
56F61DF1283D484700AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DEE283D484700AF9884 /* getThreadsCount.c */; };
|
||||
5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; };
|
||||
98AB0B01EB11B33719AE412E /* Pods_GRDBTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FE2436BF42B9FCD6552E7076 /* Pods_GRDBTests.framework */; };
|
||||
F2B3C4250D67969FF3948955 /* Pods_GRDBTestsEncrypted.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */; };
|
||||
@@ -678,6 +680,9 @@
|
||||
564A2156226B8E18001F64F1 /* GRDBTestsEncrypted.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTestsEncrypted.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
565A27CB27871FFF00659A62 /* BackupTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BackupTestCase.swift; sourceTree = "<group>"; };
|
||||
5691D97427257CE40021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = "<group>"; };
|
||||
56F61DEC283D484700AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
|
||||
56F61DEE283D484700AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
|
||||
56F61DEF283D484700AF9884 /* getThreadsCount.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = getThreadsCount.h; sourceTree = "<group>"; };
|
||||
6A4788C0F815F6C5E4EBDE12 /* Pods-GRDBTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.debug.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.debug.xcconfig"; sourceTree = "<group>"; };
|
||||
7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_GRDBTestsEncrypted.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
83BFB5733A86DAA3D0BEE684 /* Pods-GRDBTestsEncrypted.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTestsEncrypted.debug.xcconfig"; path = "Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted.debug.xcconfig"; sourceTree = "<group>"; };
|
||||
@@ -768,6 +773,9 @@
|
||||
564A1F1F226B876D001F64F1 /* GRDBTests */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56F61DEE283D484700AF9884 /* getThreadsCount.c */,
|
||||
56F61DEF283D484700AF9884 /* getThreadsCount.h */,
|
||||
56F61DEC283D484700AF9884 /* GRDBTests-Bridging-Header.h */,
|
||||
564A1F6F226B89D6001F64F1 /* Betty.jpeg */,
|
||||
56419CDA24A54058004967E1 /* InflectionsTests.json */,
|
||||
56419CE724A54058004967E1 /* AnyCursorTests.swift */,
|
||||
@@ -900,11 +908,9 @@
|
||||
56419D0024A5405A004967E1 /* JoinSupportTests.swift */,
|
||||
56419CDC24A54058004967E1 /* MapCursorTests.swift */,
|
||||
56419D0224A5405A004967E1 /* MutablePersistableRecordChangesTests.swift */,
|
||||
56419D3A24A5405F004967E1 /* TableRecordDeleteTests.swift */,
|
||||
56419D2F24A5405E004967E1 /* MutablePersistableRecordEncodableTests.swift */,
|
||||
56419D4424A5405F004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */,
|
||||
56419D3B24A5405F004967E1 /* MutablePersistableRecordTests.swift */,
|
||||
56419CD224A54057004967E1 /* TableRecordUpdateTests.swift */,
|
||||
56419CFD24A5405A004967E1 /* NumericOverflowTests.swift */,
|
||||
56419D4F24A54060004967E1 /* OrderedDictionaryTests.swift */,
|
||||
56419D4524A5405F004967E1 /* PersistableRecordTests.swift */,
|
||||
@@ -952,7 +958,9 @@
|
||||
56419D6124A54062004967E1 /* StatementColumnConvertibleFetchTests.swift */,
|
||||
56419D5724A54061004967E1 /* TableDefinitionTests.swift */,
|
||||
56419D4A24A54060004967E1 /* TableRecord+QueryInterfaceRequestTests.swift */,
|
||||
56419D3A24A5405F004967E1 /* TableRecordDeleteTests.swift */,
|
||||
56419CA224A54054004967E1 /* TableRecordTests.swift */,
|
||||
56419CD224A54057004967E1 /* TableRecordUpdateTests.swift */,
|
||||
56419CB624A54055004967E1 /* TransactionObserverSavepointsTests.swift */,
|
||||
56419D0924A5405B004967E1 /* TransactionObserverTests.swift */,
|
||||
56419D2224A5405D004967E1 /* TruncateOptimizationTests.swift */,
|
||||
@@ -1051,10 +1059,10 @@
|
||||
TargetAttributes = {
|
||||
564A1F1C226B876D001F64F1 = {
|
||||
CreatedOnToolsVersion = 10.2.1;
|
||||
LastSwiftMigration = 1150;
|
||||
LastSwiftMigration = 1340;
|
||||
};
|
||||
564A2095226B8E18001F64F1 = {
|
||||
LastSwiftMigration = 1150;
|
||||
LastSwiftMigration = 1340;
|
||||
};
|
||||
};
|
||||
};
|
||||
@@ -1243,6 +1251,7 @@
|
||||
56419EAB24A54063004967E1 /* DatabaseValueTests.swift in Sources */,
|
||||
56419D7724A54062004967E1 /* DatabaseCursorTests.swift in Sources */,
|
||||
56419E1524A54062004967E1 /* AssociationChainRowScopesTests.swift in Sources */,
|
||||
56F61DF0283D484700AF9884 /* getThreadsCount.c in Sources */,
|
||||
56419EC724A54063004967E1 /* RecordPrimaryKeyMultipleTests.swift in Sources */,
|
||||
56419DF724A54062004967E1 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
|
||||
56419EB724A54063004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */,
|
||||
@@ -1468,6 +1477,7 @@
|
||||
56419EAC24A54063004967E1 /* DatabaseValueTests.swift in Sources */,
|
||||
56419D7824A54062004967E1 /* DatabaseCursorTests.swift in Sources */,
|
||||
56419E1624A54062004967E1 /* AssociationChainRowScopesTests.swift in Sources */,
|
||||
56F61DF1283D484700AF9884 /* getThreadsCount.c in Sources */,
|
||||
56419EC824A54063004967E1 /* RecordPrimaryKeyMultipleTests.swift in Sources */,
|
||||
56419DF824A54062004967E1 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
|
||||
56419EB824A54063004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */,
|
||||
@@ -1766,6 +1776,7 @@
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = macosx;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "../../GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
@@ -1829,6 +1840,7 @@
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = macosx;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "../../GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
@@ -1900,6 +1912,7 @@
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = macosx;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "../../GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
@@ -1964,6 +1977,7 @@
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = macosx;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "../../GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1340"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "564A2095226B8E18001F64F1"
|
||||
BuildableName = "GRDBTestsEncrypted.xctest"
|
||||
BlueprintName = "GRDBTestsEncrypted"
|
||||
ReferencedContainer = "container:GRDBTests.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "564A2095226B8E18001F64F1"
|
||||
BuildableName = "GRDBTestsEncrypted.xctest"
|
||||
BlueprintName = "GRDBTestsEncrypted"
|
||||
ReferencedContainer = "container:GRDBTests.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
-24
@@ -20,20 +20,6 @@
|
||||
ReferencedContainer = "container:GRDBTests.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "564A2095226B8E18001F64F1"
|
||||
BuildableName = "GRDBTestsEncrypted.xctest"
|
||||
BlueprintName = "GRDBTestsEncrypted"
|
||||
ReferencedContainer = "container:GRDBTests.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
@@ -61,16 +47,6 @@
|
||||
ReferencedContainer = "container:GRDBTests.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "564A2095226B8E18001F64F1"
|
||||
BuildableName = "GRDBTestsEncrypted.xctest"
|
||||
BlueprintName = "GRDBTestsEncrypted"
|
||||
ReferencedContainer = "container:GRDBTests.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
|
||||
@@ -449,6 +449,8 @@
|
||||
565A27CA27871FE500659A62 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565A27C827871FE500659A62 /* BackupTestCase.swift */; };
|
||||
5691D97227257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; };
|
||||
5691D97327257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; };
|
||||
56F61DF6283D4AB100AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */; };
|
||||
56F61DF7283D4AB100AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */; };
|
||||
5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; };
|
||||
E158370AAEED49ECD53CE24A /* Pods_GRDBTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 67377FE4CDAD675809F93AD4 /* Pods_GRDBTests.framework */; };
|
||||
F2B3C4250D67969FF3948955 /* Pods_GRDBTestsEncrypted.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */; };
|
||||
@@ -681,6 +683,9 @@
|
||||
564A2158226C8F24001F64F1 /* db.SQLCipher3 */ = {isa = PBXFileReference; lastKnownFileType = file; path = db.SQLCipher3; sourceTree = SOURCE_ROOT; };
|
||||
565A27C827871FE500659A62 /* BackupTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BackupTestCase.swift; sourceTree = "<group>"; };
|
||||
5691D97127257C930021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = "<group>"; };
|
||||
56F61DF2283D4AB100AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
|
||||
56F61DF4283D4AB100AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
|
||||
56F61DF5283D4AB100AF9884 /* getThreadsCount.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = getThreadsCount.h; sourceTree = "<group>"; };
|
||||
67377FE4CDAD675809F93AD4 /* Pods_GRDBTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_GRDBTests.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
6A4788C0F815F6C5E4EBDE12 /* Pods-GRDBTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.debug.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.debug.xcconfig"; sourceTree = "<group>"; };
|
||||
7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_GRDBTestsEncrypted.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
@@ -771,6 +776,9 @@
|
||||
564A1F1F226B876D001F64F1 /* GRDBTests */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56F61DF4283D4AB100AF9884 /* getThreadsCount.c */,
|
||||
56F61DF5283D4AB100AF9884 /* getThreadsCount.h */,
|
||||
56F61DF2283D4AB100AF9884 /* GRDBTests-Bridging-Header.h */,
|
||||
564A1F6F226B89D6001F64F1 /* Betty.jpeg */,
|
||||
56419F4E24A54098004967E1 /* InflectionsTests.json */,
|
||||
564A2158226C8F24001F64F1 /* db.SQLCipher3 */,
|
||||
@@ -904,11 +912,9 @@
|
||||
56419F6D24A5409A004967E1 /* JoinSupportTests.swift */,
|
||||
56419F7B24A5409B004967E1 /* MapCursorTests.swift */,
|
||||
56419F4524A54097004967E1 /* MutablePersistableRecordChangesTests.swift */,
|
||||
56419EFF24A54093004967E1 /* TableRecordDeleteTests.swift */,
|
||||
56419F0224A54093004967E1 /* MutablePersistableRecordEncodableTests.swift */,
|
||||
56419F3124A54096004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */,
|
||||
56419F0124A54093004967E1 /* MutablePersistableRecordTests.swift */,
|
||||
56419F0624A54093004967E1 /* TableRecordUpdateTests.swift */,
|
||||
56419F0824A54093004967E1 /* NumericOverflowTests.swift */,
|
||||
56419F0324A54093004967E1 /* OrderedDictionaryTests.swift */,
|
||||
56419F1A24A54094004967E1 /* PersistableRecordTests.swift */,
|
||||
@@ -956,7 +962,9 @@
|
||||
56419FA624A5409E004967E1 /* StatementColumnConvertibleFetchTests.swift */,
|
||||
56419F5F24A54099004967E1 /* TableDefinitionTests.swift */,
|
||||
56419F9C24A5409D004967E1 /* TableRecord+QueryInterfaceRequestTests.swift */,
|
||||
56419EFF24A54093004967E1 /* TableRecordDeleteTests.swift */,
|
||||
56419F9024A5409C004967E1 /* TableRecordTests.swift */,
|
||||
56419F0624A54093004967E1 /* TableRecordUpdateTests.swift */,
|
||||
56419F8B24A5409C004967E1 /* TransactionObserverSavepointsTests.swift */,
|
||||
56419F7A24A5409B004967E1 /* TransactionObserverTests.swift */,
|
||||
56419FB624A5409F004967E1 /* TruncateOptimizationTests.swift */,
|
||||
@@ -1055,10 +1063,10 @@
|
||||
TargetAttributes = {
|
||||
564A1F1C226B876D001F64F1 = {
|
||||
CreatedOnToolsVersion = 10.2.1;
|
||||
LastSwiftMigration = 1150;
|
||||
LastSwiftMigration = 1340;
|
||||
};
|
||||
564A2095226B8E18001F64F1 = {
|
||||
LastSwiftMigration = 1150;
|
||||
LastSwiftMigration = 1340;
|
||||
};
|
||||
};
|
||||
};
|
||||
@@ -1249,6 +1257,7 @@
|
||||
5641A01824A540A1004967E1 /* FoundationDateComponentsTests.swift in Sources */,
|
||||
5641A01E24A540A1004967E1 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
|
||||
56419FCE24A540A1004967E1 /* AssociationBelongsToSQLDerivationTests.swift in Sources */,
|
||||
56F61DF6283D4AB100AF9884 /* getThreadsCount.c in Sources */,
|
||||
5641A0A024A540A1004967E1 /* SQLRequestTests.swift in Sources */,
|
||||
5641A02224A540A1004967E1 /* ValueObservationFetchTests.swift in Sources */,
|
||||
5641A12624A540A1004967E1 /* DatabasePoolSchemaCacheTests.swift in Sources */,
|
||||
@@ -1474,6 +1483,7 @@
|
||||
5641A01924A540A1004967E1 /* FoundationDateComponentsTests.swift in Sources */,
|
||||
5641A01F24A540A1004967E1 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
|
||||
56419FCF24A540A1004967E1 /* AssociationBelongsToSQLDerivationTests.swift in Sources */,
|
||||
56F61DF7283D4AB100AF9884 /* getThreadsCount.c in Sources */,
|
||||
5641A0A124A540A1004967E1 /* SQLRequestTests.swift in Sources */,
|
||||
5641A02324A540A1004967E1 /* ValueObservationFetchTests.swift in Sources */,
|
||||
5641A12724A540A1004967E1 /* DatabasePoolSchemaCacheTests.swift in Sources */,
|
||||
@@ -1775,6 +1785,7 @@
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
SDKROOT = macosx;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "../../GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
@@ -1841,6 +1852,7 @@
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
SDKROOT = macosx;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "../../GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
@@ -1915,6 +1927,7 @@
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
SDKROOT = macosx;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "../../GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
@@ -1982,6 +1995,7 @@
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
SDKROOT = macosx;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "../../GRDBTests/GRDBTests-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1340"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "564A2095226B8E18001F64F1"
|
||||
BuildableName = "GRDBTestsEncrypted.xctest"
|
||||
BlueprintName = "GRDBTestsEncrypted"
|
||||
ReferencedContainer = "container:GRDBTests.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "564A2095226B8E18001F64F1"
|
||||
BuildableName = "GRDBTestsEncrypted.xctest"
|
||||
BlueprintName = "GRDBTestsEncrypted"
|
||||
ReferencedContainer = "container:GRDBTests.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
-24
@@ -20,20 +20,6 @@
|
||||
ReferencedContainer = "container:GRDBTests.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "564A2095226B8E18001F64F1"
|
||||
BuildableName = "GRDBTestsEncrypted.xctest"
|
||||
BlueprintName = "GRDBTestsEncrypted"
|
||||
ReferencedContainer = "container:GRDBTests.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
@@ -61,16 +47,6 @@
|
||||
ReferencedContainer = "container:GRDBTests.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "564A2095226B8E18001F64F1"
|
||||
BuildableName = "GRDBTestsEncrypted.xctest"
|
||||
BlueprintName = "GRDBTestsEncrypted"
|
||||
ReferencedContainer = "container:GRDBTests.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
|
||||
@@ -36,7 +36,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
|
||||
try Player.fetchCount(db)
|
||||
})
|
||||
let recorder = publisher.record()
|
||||
let value = try wait(for: recorder.single, timeout: 1)
|
||||
let value = try wait(for: recorder.single, timeout: 5)
|
||||
XCTAssertEqual(value, 0)
|
||||
}
|
||||
|
||||
@@ -135,7 +135,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
|
||||
try Row.fetchAll(db, sql: "THIS IS NOT SQL")
|
||||
})
|
||||
let recorder = publisher.record()
|
||||
let recording = try wait(for: recorder.recording, timeout: 1)
|
||||
let recording = try wait(for: recorder.recording, timeout: 5)
|
||||
XCTAssertTrue(recording.output.isEmpty)
|
||||
assertFailure(recording.completion) { (error: DatabaseError) in
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
@@ -177,7 +177,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
|
||||
})
|
||||
|
||||
semaphore.signal()
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
waitForExpectations(timeout: 5, handler: nil)
|
||||
cancellable.cancel()
|
||||
}
|
||||
|
||||
@@ -215,7 +215,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
|
||||
dispatchPrecondition(condition: .onQueue(.main))
|
||||
})
|
||||
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
waitForExpectations(timeout: 5, handler: nil)
|
||||
cancellable.cancel()
|
||||
}
|
||||
|
||||
@@ -254,7 +254,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
|
||||
dispatchPrecondition(condition: .onQueue(queue))
|
||||
})
|
||||
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
waitForExpectations(timeout: 5, handler: nil)
|
||||
cancellable.cancel()
|
||||
}
|
||||
|
||||
@@ -277,7 +277,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
|
||||
try Player.createTable(db)
|
||||
})
|
||||
let recorder = publisher.record()
|
||||
let recording = try wait(for: recorder.recording, timeout: 1)
|
||||
let recording = try wait(for: recorder.recording, timeout: 5)
|
||||
XCTAssertTrue(recording.output.isEmpty)
|
||||
assertFailure(recording.completion) { (error: DatabaseError) in
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_READONLY)
|
||||
|
||||
@@ -37,7 +37,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase {
|
||||
try Player(id: 1, name: "Arthur", score: 1000).insert(db)
|
||||
})
|
||||
let recorder = publisher.record()
|
||||
try wait(for: recorder.single, timeout: 1)
|
||||
try wait(for: recorder.single, timeout: 5)
|
||||
try XCTAssertEqual(writer.read(Player.fetchCount), 1)
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase {
|
||||
return try Player.fetchCount(db)
|
||||
})
|
||||
let recorder = publisher.record()
|
||||
let count = try wait(for: recorder.single, timeout: 1)
|
||||
let count = try wait(for: recorder.single, timeout: 5)
|
||||
XCTAssertEqual(count, 1)
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase {
|
||||
try db.execute(sql: "THIS IS NOT SQL")
|
||||
})
|
||||
let recorder = publisher.record()
|
||||
let recording = try wait(for: recorder.recording, timeout: 1)
|
||||
let recording = try wait(for: recorder.recording, timeout: 5)
|
||||
XCTAssertTrue(recording.output.isEmpty)
|
||||
assertFailure(recording.completion) { (error: DatabaseError) in
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
@@ -117,7 +117,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase {
|
||||
try db.execute(sql: "THIS IS NOT SQL")
|
||||
})
|
||||
let recorder = publisher.record()
|
||||
let recording = try wait(for: recorder.recording, timeout: 1)
|
||||
let recording = try wait(for: recorder.recording, timeout: 5)
|
||||
XCTAssertTrue(recording.output.isEmpty)
|
||||
assertFailure(recording.completion) { (error: DatabaseError) in
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
@@ -160,7 +160,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase {
|
||||
})
|
||||
|
||||
semaphore.signal()
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
waitForExpectations(timeout: 5, handler: nil)
|
||||
cancellable.cancel()
|
||||
}
|
||||
|
||||
@@ -199,7 +199,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase {
|
||||
expectation.fulfill()
|
||||
})
|
||||
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
waitForExpectations(timeout: 5, handler: nil)
|
||||
cancellable.cancel()
|
||||
}
|
||||
|
||||
@@ -239,7 +239,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase {
|
||||
expectation.fulfill()
|
||||
})
|
||||
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
waitForExpectations(timeout: 5, handler: nil)
|
||||
cancellable.cancel()
|
||||
}
|
||||
|
||||
@@ -269,7 +269,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase {
|
||||
updates: { db in try Player(id: 1, name: "Arthur", score: 1000).insert(db) },
|
||||
thenRead: { db, _ in try Player.fetchCount(db) })
|
||||
let recorder = publisher.record()
|
||||
let count = try wait(for: recorder.single, timeout: 1)
|
||||
let count = try wait(for: recorder.single, timeout: 5)
|
||||
XCTAssertEqual(count, 1)
|
||||
}
|
||||
|
||||
@@ -292,7 +292,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase {
|
||||
updates: { _ in },
|
||||
thenRead: { db, _ in try Player.createTable(db) })
|
||||
let recorder = publisher.record()
|
||||
let recording = try wait(for: recorder.recording, timeout: 1)
|
||||
let recording = try wait(for: recorder.recording, timeout: 5)
|
||||
XCTAssertTrue(recording.output.isEmpty)
|
||||
assertFailure(recording.completion) { (error: DatabaseError) in
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_READONLY)
|
||||
@@ -317,7 +317,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase {
|
||||
updates: { db in try db.execute(sql: "THIS IS NOT SQL") },
|
||||
thenRead: { _, _ in XCTFail("Should not read") })
|
||||
let recorder = publisher.record()
|
||||
let recording = try wait(for: recorder.recording, timeout: 1)
|
||||
let recording = try wait(for: recorder.recording, timeout: 5)
|
||||
XCTAssertTrue(recording.output.isEmpty)
|
||||
assertFailure(recording.completion) { (error: DatabaseError) in
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
@@ -349,7 +349,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase {
|
||||
},
|
||||
thenRead: { _, _ in XCTFail("Should not read") })
|
||||
let recorder = publisher.record()
|
||||
let recording = try wait(for: recorder.recording, timeout: 1)
|
||||
let recording = try wait(for: recorder.recording, timeout: 5)
|
||||
XCTAssertTrue(recording.output.isEmpty)
|
||||
assertFailure(recording.completion) { (error: DatabaseError) in
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
@@ -379,7 +379,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase {
|
||||
updates: { _ in },
|
||||
thenRead: { db, _ in try Row.fetchAll(db, sql: "THIS IS NOT SQL") })
|
||||
let recorder = publisher.record()
|
||||
let recording = try wait(for: recorder.recording, timeout: 1)
|
||||
let recording = try wait(for: recorder.recording, timeout: 5)
|
||||
XCTAssertTrue(recording.output.isEmpty)
|
||||
assertFailure(recording.completion) { (error: DatabaseError) in
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
@@ -411,17 +411,17 @@ class DatabaseWriterWritePublisherTests : XCTestCase {
|
||||
// print(iteration)
|
||||
let scoreSubject = PassthroughSubject<Int, Error>()
|
||||
let publisher = scoreSubject
|
||||
.map({ score in
|
||||
.map { score in
|
||||
writer.writePublisher { db -> Int in
|
||||
try Player(id: 1, name: "Arthur", score: score).insert(db)
|
||||
return try Player.fetchCount(db)
|
||||
}
|
||||
})
|
||||
}
|
||||
.switchToLatest()
|
||||
.prefix(1)
|
||||
let recorder = publisher.record()
|
||||
scoreSubject.send(0)
|
||||
let count = try wait(for: recorder.single, timeout: 1)
|
||||
let count = try wait(for: recorder.single, timeout: 5)
|
||||
XCTAssertEqual(count, 1)
|
||||
}
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ final class Test<Context> {
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=5.5.2) && canImport(_Concurrency)
|
||||
#if compiler(>=5.6) && canImport(_Concurrency)
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
final class AsyncTest<Context> {
|
||||
// Raise the repeatCount in order to help spotting flaky tests.
|
||||
|
||||
@@ -423,5 +423,53 @@ class ValueObservationPublisherTests : XCTestCase {
|
||||
.runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) }
|
||||
.runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) }
|
||||
}
|
||||
|
||||
// MARK: - Regression Tests
|
||||
|
||||
/// Regression test for https://github.com/groue/GRDB.swift/issues/1194
|
||||
func testIssue1194() throws {
|
||||
guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else {
|
||||
throw XCTSkip("Combine is not available")
|
||||
}
|
||||
|
||||
struct Record: Codable, FetchableRecord, PersistableRecord {
|
||||
var id: Int64
|
||||
}
|
||||
|
||||
var configuration = Configuration()
|
||||
configuration.targetQueue = DispatchQueue(label: "crash.test", qos: .userInitiated)
|
||||
|
||||
let database = DatabaseQueue(configuration: configuration)
|
||||
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.registerMigration("v1") { (db) in
|
||||
try db.create(table: Record.databaseTableName) { (t) in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
}
|
||||
}
|
||||
|
||||
try migrator.migrate(database)
|
||||
|
||||
let observation = ValueObservation.tracking { (db) in
|
||||
try Record.fetchCount(db)
|
||||
}
|
||||
|
||||
let exp = expectation(description: "")
|
||||
let cancellable = observation.publisher(in: database, scheduling: .immediate)
|
||||
.map { _ in
|
||||
database.readPublisher { (db) in
|
||||
try Record.fetchCount(db)
|
||||
}
|
||||
}
|
||||
.switchToLatest()
|
||||
.sink(receiveCompletion: { _ in },
|
||||
receiveValue: { (value) in
|
||||
exp.fulfill()
|
||||
})
|
||||
|
||||
withExtendedLifetime(cancellable) {
|
||||
waitForExpectations(timeout: 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -79,6 +79,91 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testMissingIncludingAllHasMany() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
let request = A.orderByPrimaryKey()
|
||||
|
||||
do {
|
||||
struct Record: FetchableRecord, Decodable, Equatable {
|
||||
var a: A
|
||||
var bs: [B]? // Support for missing association
|
||||
}
|
||||
|
||||
// Record.fetchAll
|
||||
do {
|
||||
let records = try Record.fetchAll(db, request)
|
||||
XCTAssertEqual(records, [
|
||||
Record(
|
||||
a: A(row: ["cola1": 1, "cola2": "a1"]),
|
||||
bs: nil),
|
||||
Record(
|
||||
a: A(row: ["cola1": 2, "cola2": "a2"]),
|
||||
bs: nil),
|
||||
Record(
|
||||
a: A(row: ["cola1": 3, "cola2": "a3"]),
|
||||
bs: nil),
|
||||
])
|
||||
}
|
||||
|
||||
// Record.fetchOne
|
||||
do {
|
||||
let record = try Record.fetchOne(db, request)!
|
||||
XCTAssertEqual(record, Record(
|
||||
a: A(row: ["cola1": 1, "cola2": "a1"]),
|
||||
bs: nil))
|
||||
}
|
||||
}
|
||||
|
||||
// Test container.decodeNil
|
||||
do {
|
||||
struct Record: FetchableRecord, Decodable, Equatable {
|
||||
var a: A
|
||||
var bs: [B]? // Support for missing association
|
||||
|
||||
init(a: A, bs: [B]?) {
|
||||
self.a = a
|
||||
self.bs = bs
|
||||
}
|
||||
|
||||
enum CodingKeys: CodingKey { case a, bs }
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
a = try container.decode(A.self, forKey: .a)
|
||||
if try container.decodeNil(forKey: .bs) {
|
||||
bs = nil
|
||||
} else {
|
||||
bs = []
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Record.fetchAll
|
||||
do {
|
||||
let records = try Record.fetchAll(db, request)
|
||||
XCTAssertEqual(records, [
|
||||
Record(
|
||||
a: A(row: ["cola1": 1, "cola2": "a1"]),
|
||||
bs: nil),
|
||||
Record(
|
||||
a: A(row: ["cola1": 2, "cola2": "a2"]),
|
||||
bs: nil),
|
||||
Record(
|
||||
a: A(row: ["cola1": 3, "cola2": "a3"]),
|
||||
bs: nil),
|
||||
])
|
||||
}
|
||||
|
||||
// Record.fetchOne
|
||||
do {
|
||||
let record = try Record.fetchOne(db, request)!
|
||||
XCTAssertEqual(record, Record(
|
||||
a: A(row: ["cola1": 1, "cola2": "a1"]),
|
||||
bs: nil))
|
||||
}
|
||||
} }
|
||||
}
|
||||
|
||||
func testIncludingAllHasMany() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
@@ -209,6 +294,62 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
|
||||
]))
|
||||
}
|
||||
}
|
||||
|
||||
// Test container.decodeNil
|
||||
do {
|
||||
struct Record: FetchableRecord, Decodable, Equatable {
|
||||
var a: A
|
||||
var bs: [B]
|
||||
|
||||
init(a: A, bs: [B]) {
|
||||
self.a = a
|
||||
self.bs = bs
|
||||
}
|
||||
|
||||
enum CodingKeys: CodingKey { case a, bs }
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
a = try container.decode(A.self, forKey: .a)
|
||||
if try container.decodeNil(forKey: .bs) {
|
||||
fatalError("Test failed")
|
||||
} else {
|
||||
bs = try container.decode([B].self, forKey: .bs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Record.fetchAll
|
||||
do {
|
||||
let records = try Record.fetchAll(db, request)
|
||||
XCTAssertEqual(records, [
|
||||
Record(
|
||||
a: A(row: ["cola1": 1, "cola2": "a1"]),
|
||||
bs: [
|
||||
B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]),
|
||||
B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]),
|
||||
]),
|
||||
Record(
|
||||
a: A(row: ["cola1": 2, "cola2": "a2"]),
|
||||
bs: [
|
||||
B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]),
|
||||
]),
|
||||
Record(
|
||||
a: A(row: ["cola1": 3, "cola2": "a3"]),
|
||||
bs: []),
|
||||
])
|
||||
}
|
||||
|
||||
// Record.fetchOne
|
||||
do {
|
||||
let record = try Record.fetchOne(db, request)!
|
||||
XCTAssertEqual(record, Record(
|
||||
a: A(row: ["cola1": 1, "cola2": "a1"]),
|
||||
bs: [
|
||||
B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]),
|
||||
B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]),
|
||||
]))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Request with filters
|
||||
|
||||
@@ -278,6 +278,29 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
|
||||
WHERE ("name" = 'foo') AND (("pA", "pB") IN "grdb_base")
|
||||
"""])
|
||||
}
|
||||
|
||||
// Limited ordered request (preserve both ordering and limit in the CTE)
|
||||
do {
|
||||
let request = Parent
|
||||
.including(all: Parent.hasMany(Child.self))
|
||||
.orderByPrimaryKey()
|
||||
.limit(1)
|
||||
|
||||
sqlQueries.removeAll()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "parent" ORDER BY "parentA", "parentB" LIMIT 1
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent" ORDER BY "parentA", "parentB" LIMIT 1) \
|
||||
SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB" \
|
||||
FROM "child" \
|
||||
WHERE ("pA", "pB") IN "grdb_base"
|
||||
"""])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,52 @@ class DatabaseCursorTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: this test should be duplicated for all cursor types
|
||||
func testNextFollowedByForEach() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
let cursor = try Int.fetchCursor(db, sql: "SELECT 1")
|
||||
XCTAssertEqual(try cursor.next()!, 1)
|
||||
try cursor.forEach { _ in
|
||||
XCTFail("Cursor iteration should have ended")
|
||||
}
|
||||
XCTAssert(try cursor.next() == nil) // end
|
||||
}
|
||||
do {
|
||||
let cursor = try Int.fetchCursor(db, sql: "SELECT 1 UNION SELECT 2")
|
||||
XCTAssertEqual(try cursor.next()!, 1)
|
||||
try cursor.forEach { i in
|
||||
XCTAssertEqual(i, 2)
|
||||
}
|
||||
XCTAssert(try cursor.next() == nil) // end
|
||||
}
|
||||
do {
|
||||
let cursor = try Int.fetchCursor(db, sql: "SELECT 1 UNION SELECT 2 UNION SELECT 3")
|
||||
XCTAssertEqual(try cursor.next()!, 1)
|
||||
try XCTAssertEqual(Array(cursor), [2, 3])
|
||||
XCTAssert(try cursor.next() == nil) // end
|
||||
}
|
||||
do {
|
||||
struct Break: Error { }
|
||||
let cursor = try Int.fetchCursor(db, sql: "SELECT 1 UNION SELECT 2 UNION SELECT 3")
|
||||
try? cursor.forEach { i in
|
||||
XCTAssertEqual(i, 1)
|
||||
throw Break()
|
||||
}
|
||||
try? cursor.forEach { i in
|
||||
XCTAssertEqual(i, 2)
|
||||
throw Break()
|
||||
}
|
||||
try? cursor.forEach { i in
|
||||
XCTAssertEqual(i, 3)
|
||||
throw Break()
|
||||
}
|
||||
XCTAssert(try cursor.next() == nil) // end
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: this test should be duplicated for all cursor types
|
||||
func testStepError() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
@@ -27,8 +27,8 @@ class DatabaseErrorTests: GRDBTestCase {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
|
||||
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
|
||||
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
|
||||
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
|
||||
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)`")
|
||||
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
XCTAssertEqual(sqlQueries.count, 2)
|
||||
XCTAssertEqual(sqlQueries[0], "INSERT INTO pets (masterId, name) VALUES (1, 'Bobby')")
|
||||
XCTAssertEqual(sqlQueries[1], "ROLLBACK TRANSACTION")
|
||||
@@ -60,11 +60,71 @@ class DatabaseErrorTests: GRDBTestCase {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
|
||||
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
|
||||
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
|
||||
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)`")
|
||||
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabaseErrorThrownByUpdateStatementContainSQLAndArguments() throws {
|
||||
func testDatabaseErrorThrownByUpdateStatementContainSQLAndNoPrivateArguments() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY)")
|
||||
try db.execute(sql: "CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT)")
|
||||
}
|
||||
|
||||
// db.execute(sql, arguments)
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [1, "Bobby"])
|
||||
XCTFail()
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
|
||||
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
|
||||
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
|
||||
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)`")
|
||||
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
}
|
||||
}
|
||||
|
||||
// statement.execute(arguments)
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
let statement = try db.makeStatement(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)")
|
||||
try statement.execute(arguments: [1, "Bobby"])
|
||||
XCTFail()
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
|
||||
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
|
||||
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
|
||||
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)`")
|
||||
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
}
|
||||
}
|
||||
|
||||
// statement.execute()
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
let statement = try db.makeStatement(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)")
|
||||
statement.arguments = [1, "Bobby"]
|
||||
try statement.execute()
|
||||
XCTFail()
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY)
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
|
||||
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
|
||||
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
|
||||
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)`")
|
||||
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabaseErrorThrownByUpdateStatementContainSQLAndPublicArguments() throws {
|
||||
// Opt in for public statement arguments
|
||||
dbConfiguration.publicStatementArguments = true
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY)")
|
||||
@@ -82,6 +142,7 @@ class DatabaseErrorTests: GRDBTestCase {
|
||||
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
|
||||
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
|
||||
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,6 +158,7 @@ class DatabaseErrorTests: GRDBTestCase {
|
||||
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
|
||||
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
|
||||
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,6 +175,7 @@ class DatabaseErrorTests: GRDBTestCase {
|
||||
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
|
||||
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)")
|
||||
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (?, ?)` with arguments [1, \"bobby\"]")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -133,6 +196,7 @@ class DatabaseErrorTests: GRDBTestCase {
|
||||
XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version
|
||||
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (1, 'Bobby')")
|
||||
XCTAssertEqual(error.description.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (1, 'bobby')`")
|
||||
XCTAssertEqual(error.expandedDescription.lowercased(), "sqlite error 19: foreign key constraint failed - while executing `insert into pets (masterid, name) values (1, 'bobby')`")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -162,8 +226,8 @@ class DatabaseErrorTests: GRDBTestCase {
|
||||
XCTAssertEqual(DatabaseError.errorDomain, "GRDB.DatabaseError")
|
||||
XCTAssertEqual(error.domain, DatabaseError.errorDomain)
|
||||
XCTAssertEqual(error.code, 787)
|
||||
XCTAssertNotNil(error.localizedFailureReason)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -26,7 +26,7 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
try! db.execute(sql: "CREATE TABLE t(a)")
|
||||
expectation.fulfill()
|
||||
})
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
waitForExpectations(timeout: 5, handler: nil)
|
||||
}
|
||||
|
||||
try Test(test)
|
||||
@@ -98,54 +98,6 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
.runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
|
||||
}
|
||||
|
||||
#if compiler(>=5.5.2) && canImport(_Concurrency)
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
func testAsyncAwait_NonEmptyMigratorSync() async throws {
|
||||
func test(writer: DatabaseWriter) async throws {
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.registerMigration("createPersons") { db in
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE persons (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT)
|
||||
""")
|
||||
}
|
||||
migrator.registerMigration("createPets") { db in
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE pets (
|
||||
id INTEGER PRIMARY KEY,
|
||||
masterID INTEGER NOT NULL
|
||||
REFERENCES persons(id)
|
||||
ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
name TEXT)
|
||||
""")
|
||||
}
|
||||
|
||||
var migrator2 = migrator
|
||||
migrator2.registerMigration("destroyPersons") { db in
|
||||
try db.execute(sql: "DROP TABLE pets")
|
||||
}
|
||||
|
||||
try await migrator.migrate(writer)
|
||||
try await writer.read { db in
|
||||
XCTAssertTrue(try db.tableExists("persons"))
|
||||
XCTAssertTrue(try db.tableExists("pets"))
|
||||
}
|
||||
|
||||
try await migrator2.migrate(writer)
|
||||
try await writer.read { db in
|
||||
XCTAssertTrue(try db.tableExists("persons"))
|
||||
XCTAssertFalse(try db.tableExists("pets"))
|
||||
}
|
||||
}
|
||||
|
||||
try await AsyncTest(test)
|
||||
.run { DatabaseQueue() }
|
||||
.runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
|
||||
.runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
|
||||
}
|
||||
#endif
|
||||
|
||||
func testNonEmptyMigratorAsync() throws {
|
||||
func test(writer: DatabaseWriter) throws {
|
||||
var migrator = DatabaseMigrator()
|
||||
@@ -189,7 +141,7 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
expectation.fulfill()
|
||||
})
|
||||
})
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
waitForExpectations(timeout: 5, handler: nil)
|
||||
}
|
||||
|
||||
try Test(test)
|
||||
@@ -272,7 +224,7 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
})
|
||||
|
||||
semaphore.signal()
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
waitForExpectations(timeout: 5, handler: nil)
|
||||
cancellable.cancel()
|
||||
}
|
||||
|
||||
@@ -300,7 +252,7 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
})
|
||||
|
||||
semaphore.signal()
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
waitForExpectations(timeout: 5, handler: nil)
|
||||
cancellable.cancel()
|
||||
}
|
||||
|
||||
@@ -330,7 +282,7 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
expectation.fulfill()
|
||||
})
|
||||
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
waitForExpectations(timeout: 5, handler: nil)
|
||||
cancellable.cancel()
|
||||
}
|
||||
|
||||
@@ -361,7 +313,7 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
expectation.fulfill()
|
||||
})
|
||||
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
waitForExpectations(timeout: 5, handler: nil)
|
||||
cancellable.cancel()
|
||||
}
|
||||
|
||||
@@ -422,61 +374,6 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
.runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
|
||||
.runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
|
||||
}
|
||||
|
||||
#if compiler(>=5.5.2) && canImport(_Concurrency)
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
func testAsyncAwait_MigrateUpTo() async throws {
|
||||
func test(writer: DatabaseWriter) async throws {
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.registerMigration("a") { db in
|
||||
try db.execute(sql: "CREATE TABLE a (id INTEGER PRIMARY KEY)")
|
||||
}
|
||||
migrator.registerMigration("b") { db in
|
||||
try db.execute(sql: "CREATE TABLE b (id INTEGER PRIMARY KEY)")
|
||||
}
|
||||
migrator.registerMigration("c") { db in
|
||||
try db.execute(sql: "CREATE TABLE c (id INTEGER PRIMARY KEY)")
|
||||
}
|
||||
|
||||
// one step
|
||||
try await migrator.migrate(writer, upTo: "a")
|
||||
try await writer.read { db in
|
||||
XCTAssertTrue(try db.tableExists("a"))
|
||||
XCTAssertFalse(try db.tableExists("b"))
|
||||
}
|
||||
|
||||
// zero step
|
||||
try await migrator.migrate(writer, upTo: "a")
|
||||
try await writer.read { db in
|
||||
XCTAssertTrue(try db.tableExists("a"))
|
||||
XCTAssertFalse(try db.tableExists("b"))
|
||||
}
|
||||
|
||||
// two steps
|
||||
try await migrator.migrate(writer, upTo: "c")
|
||||
try await writer.read { db in
|
||||
XCTAssertTrue(try db.tableExists("a"))
|
||||
XCTAssertTrue(try db.tableExists("b"))
|
||||
XCTAssertTrue(try db.tableExists("c"))
|
||||
}
|
||||
|
||||
// zero step
|
||||
try await migrator.migrate(writer, upTo: "c")
|
||||
try await migrator.migrate(writer)
|
||||
|
||||
// fatal error: undefined migration: "missing"
|
||||
// try migrator.migrate(writer, upTo: "missing")
|
||||
|
||||
// fatal error: database is already migrated beyond migration "b"
|
||||
// try migrator.migrate(writer, upTo: "b")
|
||||
}
|
||||
|
||||
try await AsyncTest(test)
|
||||
.run { DatabaseQueue() }
|
||||
.runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
|
||||
.runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
|
||||
}
|
||||
#endif
|
||||
|
||||
func testMigrationFailureTriggersRollback() throws {
|
||||
var migrator = DatabaseMigrator()
|
||||
@@ -530,7 +427,7 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
|
||||
expectation.fulfill()
|
||||
})
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
waitForExpectations(timeout: 5, handler: nil)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -772,7 +669,7 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
}
|
||||
|
||||
// Regression test for https://github.com/groue/GRDB.swift/issues/741
|
||||
func testEraseDatabaseOnSchemaChangeDoesNotDeadLock() throws {
|
||||
func testEraseDatabaseOnSchemaChangeDoesNotDeadLockOnTargetQueue() throws {
|
||||
dbConfiguration.targetQueue = DispatchQueue(label: "target")
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
@@ -785,6 +682,20 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
try migrator.migrate(dbQueue)
|
||||
}
|
||||
|
||||
// Regression test for https://github.com/groue/GRDB.swift/issues/741
|
||||
func testEraseDatabaseOnSchemaChangeDoesNotDeadLockOnWriteTargetQueue() throws {
|
||||
dbConfiguration.writeTargetQueue = DispatchQueue(label: "writerTarget")
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
migrator.registerMigration("1", migrate: { _ in })
|
||||
try migrator.migrate(dbQueue)
|
||||
|
||||
migrator.registerMigration("2", migrate: { _ in })
|
||||
try migrator.migrate(dbQueue)
|
||||
}
|
||||
|
||||
func testEraseDatabaseOnSchemaChange() throws {
|
||||
// 1st version of the migrator
|
||||
var migrator1 = DatabaseMigrator()
|
||||
|
||||
@@ -994,6 +994,60 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
waitForExpectations(timeout: 2, handler: nil)
|
||||
}
|
||||
|
||||
func testWriteTargetQueue() throws {
|
||||
guard #available(OSX 10.12, tvOS 10.0, *) else {
|
||||
throw XCTSkip("dispatchPrecondition(condition:) is not available")
|
||||
}
|
||||
|
||||
func test(targetQueue: DispatchQueue, writeTargetQueue: DispatchQueue) throws {
|
||||
dbConfiguration.targetQueue = targetQueue
|
||||
dbConfiguration.writeTargetQueue = writeTargetQueue
|
||||
let dbPool = try makeDatabasePool()
|
||||
try dbPool.write { _ in
|
||||
dispatchPrecondition(condition: .onQueue(writeTargetQueue))
|
||||
}
|
||||
try dbPool.read { _ in
|
||||
dispatchPrecondition(condition: .onQueue(targetQueue))
|
||||
}
|
||||
}
|
||||
|
||||
// background queue
|
||||
try test(targetQueue: .global(qos: .background), writeTargetQueue: DispatchQueue(label: "writer"))
|
||||
|
||||
// main queue
|
||||
let expectation = self.expectation(description: "main")
|
||||
DispatchQueue.global(qos: .default).async {
|
||||
try! test(targetQueue: .main, writeTargetQueue: .main)
|
||||
expectation.fulfill()
|
||||
}
|
||||
waitForExpectations(timeout: 2, handler: nil)
|
||||
}
|
||||
|
||||
func testWriteTargetQueueReadOnly() throws {
|
||||
guard #available(OSX 10.12, tvOS 10.0, *) else {
|
||||
throw XCTSkip("dispatchPrecondition(condition:) is not available")
|
||||
}
|
||||
|
||||
// Create a database before we perform read-only accesses
|
||||
_ = try makeDatabasePool(filename: "test")
|
||||
|
||||
func test(targetQueue: DispatchQueue, writeTargetQueue: DispatchQueue) throws {
|
||||
dbConfiguration.readonly = true
|
||||
dbConfiguration.targetQueue = targetQueue
|
||||
dbConfiguration.writeTargetQueue = writeTargetQueue // unused
|
||||
let dbPool = try makeDatabasePool(filename: "test")
|
||||
try dbPool.write { _ in
|
||||
// Not on writeTargetQueue because read-only
|
||||
dispatchPrecondition(condition: .onQueue(targetQueue))
|
||||
}
|
||||
try dbPool.read { _ in
|
||||
dispatchPrecondition(condition: .onQueue(targetQueue))
|
||||
}
|
||||
}
|
||||
|
||||
try test(targetQueue: .global(qos: .background), writeTargetQueue: DispatchQueue(label: "writer"))
|
||||
}
|
||||
|
||||
func testQoS() throws {
|
||||
guard #available(OSX 10.12, tvOS 10.0, *) else {
|
||||
throw XCTSkip("dispatchPrecondition(condition:) is not available")
|
||||
|
||||
@@ -41,6 +41,85 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
|
||||
XCTAssertEqual(openConnectionCount, 0)
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
func testDatabasePoolReleasesMemoryOnPressureEvent() throws {
|
||||
// Create a database pool, and expect a reader connection to be closed
|
||||
let expectation = self.expectation(description: "Reader connection closed")
|
||||
|
||||
var configuration = Configuration()
|
||||
configuration.SQLiteConnectionWillClose = { conn in
|
||||
if sqlite3_db_readonly(conn, nil) != 0 {
|
||||
expectation.fulfill()
|
||||
}
|
||||
}
|
||||
let dbPool = try makeDatabasePool(configuration: configuration)
|
||||
|
||||
// Precondition: there is one reader.
|
||||
try dbPool.read { _ in }
|
||||
|
||||
// Simulate memory warning.
|
||||
NotificationCenter.default.post(
|
||||
name: NSNotification.Name(rawValue: "UIApplicationDidReceiveMemoryWarningNotification"),
|
||||
object: nil)
|
||||
|
||||
// Postcondition: reader connection was closed
|
||||
withExtendedLifetime(dbPool) { _ in
|
||||
waitForExpectations(timeout: 0.5)
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabasePoolDoesNotReleaseMemoryOnPressureEventIfDisabled() throws {
|
||||
// Create a database pool, and do not expect any reader connection to be closed
|
||||
let expectation = self.expectation(description: "Reader connection closed")
|
||||
expectation.isInverted = true
|
||||
|
||||
var configuration = Configuration()
|
||||
configuration.automaticMemoryManagement = false
|
||||
configuration.SQLiteConnectionWillClose = { conn in
|
||||
if sqlite3_db_readonly(conn, nil) != 0 {
|
||||
expectation.fulfill()
|
||||
}
|
||||
}
|
||||
let dbPool = try makeDatabasePool(configuration: configuration)
|
||||
|
||||
// Precondition: there is one reader.
|
||||
try dbPool.read { _ in }
|
||||
|
||||
// Simulate memory warning.
|
||||
NotificationCenter.default.post(
|
||||
name: NSNotification.Name(rawValue: "UIApplicationDidReceiveMemoryWarningNotification"),
|
||||
object: nil)
|
||||
|
||||
// Postcondition: no reader connection was closed
|
||||
withExtendedLifetime(dbPool) { _ in
|
||||
waitForExpectations(timeout: 0.5)
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for <https://github.com/groue/GRDB.swift/pull/1253#issuecomment-1177166630>
|
||||
func testDatabasePoolDoesNotPreventConcurrentReadsOnPressureEvent() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
|
||||
// Start a read that blocks
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
dbPool.asyncRead { _ in
|
||||
semaphore.wait()
|
||||
}
|
||||
|
||||
// Simulate memory warning.
|
||||
NotificationCenter.default.post(
|
||||
name: NSNotification.Name(rawValue: "UIApplicationDidReceiveMemoryWarningNotification"),
|
||||
object: nil)
|
||||
|
||||
// Make sure we can read
|
||||
try dbPool.read { _ in }
|
||||
|
||||
// Cleanup
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
// TODO: fix flaky test
|
||||
// func testDatabasePoolReleaseMemoryClosesReaderConnections() throws {
|
||||
// let countQueue = DispatchQueue(label: "GRDB")
|
||||
|
||||
@@ -76,6 +76,90 @@ class DatabasePoolTests: GRDBTestCase {
|
||||
try migrator.migrate(dbQueue)
|
||||
}
|
||||
|
||||
func testNumberOfThreads_asyncUnsafeRead() throws {
|
||||
#if SWIFT_PACKAGE
|
||||
// Can't access getThreadsCount() C function
|
||||
throw XCTSkip("Thread count is not available")
|
||||
#else
|
||||
if getThreadsCount() < 0 {
|
||||
throw XCTSkip("Thread count is not available")
|
||||
}
|
||||
|
||||
let pool = try makeDatabasePool()
|
||||
|
||||
// Keep this number big, so that we have a good chance to detect
|
||||
// thread explosion.
|
||||
let numberOfConcurrentReads = 10000
|
||||
|
||||
// Wait for all concurrent reads to end
|
||||
let group = DispatchGroup()
|
||||
|
||||
// The maximum number of threads we could witness
|
||||
var maxThreadCount: CInt = 0
|
||||
let lock = NSLock()
|
||||
|
||||
for _ in (0..<numberOfConcurrentReads) {
|
||||
group.enter()
|
||||
pool.asyncUnsafeRead { result in
|
||||
if case let .failure(error) = result {
|
||||
XCTFail("Unexpected error \(error)")
|
||||
}
|
||||
|
||||
let threadsCount = getThreadsCount()
|
||||
lock.lock()
|
||||
maxThreadCount = max(maxThreadCount, threadsCount)
|
||||
lock.unlock()
|
||||
|
||||
group.leave()
|
||||
}
|
||||
}
|
||||
group.wait()
|
||||
XCTAssert(maxThreadCount < 50)
|
||||
#endif
|
||||
}
|
||||
|
||||
func testNumberOfThreads_asyncRead() throws {
|
||||
#if SWIFT_PACKAGE
|
||||
// Can't access getThreadsCount() C function
|
||||
throw XCTSkip("Thread count is not available")
|
||||
#else
|
||||
if getThreadsCount() < 0 {
|
||||
throw XCTSkip("Thread count is not available")
|
||||
}
|
||||
|
||||
let pool = try makeDatabasePool()
|
||||
|
||||
// Keep this number big, so that we have a good chance to detect
|
||||
// thread explosion.
|
||||
let numberOfConcurrentReads = 10000
|
||||
|
||||
// Wait for all concurrent reads to end
|
||||
let group = DispatchGroup()
|
||||
|
||||
// The maximum number of threads we could witness
|
||||
var maxThreadCount: CInt = 0
|
||||
let lock = NSLock()
|
||||
|
||||
for _ in (0..<numberOfConcurrentReads) {
|
||||
group.enter()
|
||||
pool.asyncRead { result in
|
||||
if case let .failure(error) = result {
|
||||
XCTFail("Unexpected error \(error)")
|
||||
}
|
||||
|
||||
let threadsCount = getThreadsCount()
|
||||
lock.lock()
|
||||
maxThreadCount = max(maxThreadCount, threadsCount)
|
||||
lock.unlock()
|
||||
|
||||
group.leave()
|
||||
}
|
||||
}
|
||||
group.wait()
|
||||
XCTAssert(maxThreadCount < 50)
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - Closing
|
||||
|
||||
func testClose() throws {
|
||||
|
||||
@@ -152,6 +152,59 @@ class DatabaseQueueTests: GRDBTestCase {
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
}
|
||||
|
||||
func testWriteTargetQueue() throws {
|
||||
guard #available(OSX 10.12, tvOS 10.0, *) else {
|
||||
throw XCTSkip("dispatchPrecondition(condition:) is not available")
|
||||
}
|
||||
|
||||
func test(targetQueue: DispatchQueue, writeTargetQueue: DispatchQueue) throws {
|
||||
dbConfiguration.targetQueue = targetQueue // unused
|
||||
dbConfiguration.writeTargetQueue = writeTargetQueue
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { _ in
|
||||
dispatchPrecondition(condition: .onQueue(writeTargetQueue))
|
||||
}
|
||||
try dbQueue.read { _ in
|
||||
dispatchPrecondition(condition: .onQueue(writeTargetQueue))
|
||||
}
|
||||
}
|
||||
|
||||
// background queue
|
||||
try test(targetQueue: .global(qos: .background), writeTargetQueue: DispatchQueue(label: "writer"))
|
||||
|
||||
// main queue
|
||||
let expectation = self.expectation(description: "main")
|
||||
DispatchQueue.global(qos: .default).async {
|
||||
try! test(targetQueue: .main, writeTargetQueue: .main)
|
||||
expectation.fulfill()
|
||||
}
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
}
|
||||
|
||||
func testWriteTargetQueueReadOnly() throws {
|
||||
guard #available(OSX 10.12, tvOS 10.0, *) else {
|
||||
throw XCTSkip("dispatchPrecondition(condition:) is not available")
|
||||
}
|
||||
|
||||
// Create a database before we perform read-only accesses
|
||||
_ = try makeDatabaseQueue(filename: "test")
|
||||
|
||||
func test(targetQueue: DispatchQueue, writeTargetQueue: DispatchQueue) throws {
|
||||
dbConfiguration.readonly = true
|
||||
dbConfiguration.targetQueue = targetQueue
|
||||
dbConfiguration.writeTargetQueue = writeTargetQueue // unused
|
||||
let dbQueue = try makeDatabaseQueue(filename: "test")
|
||||
try dbQueue.write { _ in
|
||||
dispatchPrecondition(condition: .onQueue(targetQueue))
|
||||
}
|
||||
try dbQueue.read { _ in
|
||||
dispatchPrecondition(condition: .onQueue(targetQueue))
|
||||
}
|
||||
}
|
||||
|
||||
try test(targetQueue: .global(qos: .background), writeTargetQueue: DispatchQueue(label: "writer"))
|
||||
}
|
||||
|
||||
func testQoS() throws {
|
||||
guard #available(OSX 10.12, tvOS 10.0, *) else {
|
||||
throw XCTSkip("dispatchPrecondition(condition:) is not available")
|
||||
|
||||
@@ -30,7 +30,7 @@ class DatabaseReaderTests : GRDBTestCase {
|
||||
try test(setup(makeDatabasePool()).makeSnapshot())
|
||||
}
|
||||
|
||||
#if compiler(>=5.5.2) && canImport(_Concurrency)
|
||||
#if compiler(>=5.6) && canImport(_Concurrency)
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
func testAsyncAwait_ReadCanRead() async throws {
|
||||
func setup<T: DatabaseWriter>(_ dbWriter: T) throws -> T {
|
||||
@@ -68,7 +68,7 @@ class DatabaseReaderTests : GRDBTestCase {
|
||||
try test(makeDatabasePool().makeSnapshot())
|
||||
}
|
||||
|
||||
#if compiler(>=5.5.2) && canImport(_Concurrency)
|
||||
#if compiler(>=5.6) && canImport(_Concurrency)
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
func testAsyncAwait_ReadPreventsDatabaseModification() async throws {
|
||||
func test(_ dbReader: DatabaseReader) async throws {
|
||||
@@ -107,7 +107,7 @@ class DatabaseReaderTests : GRDBTestCase {
|
||||
try test(setup(makeDatabasePool()).makeSnapshot())
|
||||
}
|
||||
|
||||
#if compiler(>=5.5.2) && canImport(_Concurrency)
|
||||
#if compiler(>=5.6) && canImport(_Concurrency)
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
func testAsyncAwait_UnsafeReadCanRead() async throws {
|
||||
func setup<T: DatabaseWriter>(_ dbWriter: T) throws -> T {
|
||||
|
||||
@@ -566,6 +566,36 @@ class DatabaseTests : GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testReadOnlyTransaction() throws {
|
||||
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
|
||||
guard sqlite3_libversion_number() >= 3008000 else {
|
||||
return
|
||||
}
|
||||
|
||||
dbConfiguration.defaultTransactionKind = .immediate
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
sqlQueries.removeAll()
|
||||
try db.inSavepoint { .commit }
|
||||
try db.inTransaction { .commit }
|
||||
try db.inTransaction(.immediate) { .commit }
|
||||
XCTAssertEqual(Set(sqlQueries), ["BEGIN IMMEDIATE TRANSACTION", "COMMIT TRANSACTION"])
|
||||
}
|
||||
|
||||
try db.readOnly {
|
||||
sqlQueries.removeAll()
|
||||
try db.inSavepoint { .commit }
|
||||
try db.inTransaction { .commit }
|
||||
XCTAssertEqual(Set(sqlQueries), ["BEGIN DEFERRED TRANSACTION", "COMMIT TRANSACTION"])
|
||||
do {
|
||||
try db.inTransaction(.immediate) { .commit }
|
||||
XCTFail("Expected error")
|
||||
} catch DatabaseError.SQLITE_READONLY { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testCheckpoint() throws {
|
||||
do {
|
||||
// Not a WAL database
|
||||
|
||||
@@ -31,8 +31,10 @@ class DatabaseTraceTests : GRDBTestCase {
|
||||
try dbQueue.inDatabase { db in
|
||||
var lastSQL: String?
|
||||
var lastDescription: String?
|
||||
var lastExpandedDescription: String?
|
||||
db.trace(options: .statement) { event in
|
||||
lastDescription = event.description
|
||||
lastExpandedDescription = event.expandedDescription
|
||||
switch event {
|
||||
case let .statement(statement):
|
||||
lastSQL = statement.sql
|
||||
@@ -43,10 +45,12 @@ class DatabaseTraceTests : GRDBTestCase {
|
||||
try db.execute(sql: "CREATE table t(a);")
|
||||
XCTAssertEqual(lastSQL, "CREATE table t(a)")
|
||||
XCTAssertEqual(lastDescription, "CREATE table t(a)")
|
||||
XCTAssertEqual(lastExpandedDescription, "CREATE table t(a)")
|
||||
|
||||
try db.execute(sql: "INSERT INTO t (a) VALUES (?)", arguments: [1])
|
||||
XCTAssertEqual(lastSQL, "INSERT INTO t (a) VALUES (?)")
|
||||
XCTAssertEqual(lastDescription, "INSERT INTO t (a) VALUES (1)")
|
||||
XCTAssertEqual(lastDescription, "INSERT INTO t (a) VALUES (?)")
|
||||
XCTAssertEqual(lastExpandedDescription, "INSERT INTO t (a) VALUES (1)")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,8 +65,10 @@ class DatabaseTraceTests : GRDBTestCase {
|
||||
var lastExpandedSQL: String?
|
||||
var lastDuration: TimeInterval?
|
||||
var lastDescription: String?
|
||||
var lastExpandedDescription: String?
|
||||
db.trace(options: .profile) { event in
|
||||
lastDescription = event.description
|
||||
lastExpandedDescription = event.expandedDescription
|
||||
switch event {
|
||||
case let .profile(statement: statement, duration: duration):
|
||||
lastSQL = statement.sql
|
||||
@@ -77,12 +83,14 @@ class DatabaseTraceTests : GRDBTestCase {
|
||||
XCTAssertEqual(lastExpandedSQL, "CREATE table t(a)")
|
||||
XCTAssertTrue(lastDuration! >= 0)
|
||||
XCTAssert(lastDescription!.hasSuffix("s CREATE table t(a)"))
|
||||
XCTAssert(lastExpandedDescription!.hasSuffix("s CREATE table t(a)"))
|
||||
|
||||
try db.execute(sql: "INSERT INTO t (a) VALUES (?)", arguments: [1])
|
||||
XCTAssertEqual(lastSQL, "INSERT INTO t (a) VALUES (?)")
|
||||
XCTAssertEqual(lastExpandedSQL, "INSERT INTO t (a) VALUES (1)")
|
||||
XCTAssertTrue(lastDuration! >= 0)
|
||||
XCTAssert(lastDescription!.hasSuffix("s INSERT INTO t (a) VALUES (1)"))
|
||||
XCTAssert(lastDescription!.hasSuffix("s INSERT INTO t (a) VALUES (?)"))
|
||||
XCTAssert(lastExpandedDescription!.hasSuffix("s INSERT INTO t (a) VALUES (1)"))
|
||||
|
||||
db.add(function: DatabaseFunction("wait", argumentCount: 1, pure: true, function: { dbValues in
|
||||
if let delay = TimeInterval.fromDatabaseValue(dbValues[0]) {
|
||||
@@ -96,7 +104,8 @@ class DatabaseTraceTests : GRDBTestCase {
|
||||
XCTAssertEqual(lastExpandedSQL, "SELECT wait(0.5)")
|
||||
XCTAssertGreaterThan(lastDuration!, 0.4)
|
||||
XCTAssertLessThan(lastDuration!, 2) // Travis can be so slow
|
||||
XCTAssert(lastDescription!.hasSuffix("s SELECT wait(0.5)"))
|
||||
XCTAssert(lastDescription!.hasSuffix("s SELECT wait(?)"))
|
||||
XCTAssert(lastExpandedDescription!.hasSuffix("s SELECT wait(0.5)"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,6 +134,27 @@ class DatabaseTraceTests : GRDBTestCase {
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue(configuration: configuration)
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: """
|
||||
CREATE table t(a);
|
||||
INSERT INTO t (a) VALUES (?)
|
||||
""", arguments: [1])
|
||||
XCTAssertEqual(events.suffix(2), [
|
||||
"SQL: CREATE table t(a)",
|
||||
"SQL: INSERT INTO t (a) VALUES (?)"])
|
||||
}
|
||||
}
|
||||
|
||||
func testTraceFromConfigurationWithPublicStatementArguments() throws {
|
||||
var events: [String] = []
|
||||
var configuration = Configuration()
|
||||
configuration.publicStatementArguments = true
|
||||
configuration.prepareDatabase { db in
|
||||
db.trace { event in
|
||||
events.append("SQL: \(event)")
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue(configuration: configuration)
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: """
|
||||
CREATE table t(a);
|
||||
|
||||
@@ -266,7 +266,7 @@ class DatabaseWriterTests : GRDBTestCase {
|
||||
try DatabaseQueue().backup(to: dbQueue)
|
||||
}
|
||||
|
||||
#if compiler(>=5.5.2) && canImport(_Concurrency)
|
||||
#if compiler(>=5.6) && canImport(_Concurrency)
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
func testAsyncAwait_write() async throws {
|
||||
func setup<T: DatabaseWriter>(_ dbWriter: T) throws -> T {
|
||||
@@ -288,7 +288,7 @@ class DatabaseWriterTests : GRDBTestCase {
|
||||
}
|
||||
#endif
|
||||
|
||||
#if compiler(>=5.5.2) && canImport(_Concurrency)
|
||||
#if compiler(>=5.6) && canImport(_Concurrency)
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
func testAsyncAwait_writeWithoutTransaction() async throws {
|
||||
func setup<T: DatabaseWriter>(_ dbWriter: T) throws -> T {
|
||||
@@ -313,7 +313,7 @@ class DatabaseWriterTests : GRDBTestCase {
|
||||
}
|
||||
#endif
|
||||
|
||||
#if compiler(>=5.5.2) && canImport(_Concurrency)
|
||||
#if compiler(>=5.6) && canImport(_Concurrency)
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
func testAsyncAwait_barrierWriteWithoutTransaction() async throws {
|
||||
func setup<T: DatabaseWriter>(_ dbWriter: T) throws -> T {
|
||||
@@ -338,7 +338,7 @@ class DatabaseWriterTests : GRDBTestCase {
|
||||
}
|
||||
#endif
|
||||
|
||||
#if compiler(>=5.5.2) && canImport(_Concurrency)
|
||||
#if compiler(>=5.6) && canImport(_Concurrency)
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
func testAsyncAwait_erase() async throws {
|
||||
func setup<T: DatabaseWriter>(_ dbWriter: T) throws -> T {
|
||||
@@ -358,7 +358,7 @@ class DatabaseWriterTests : GRDBTestCase {
|
||||
}
|
||||
#endif
|
||||
|
||||
#if compiler(>=5.5.2) && canImport(_Concurrency)
|
||||
#if compiler(>=5.6) && canImport(_Concurrency)
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
func testAsyncAwait_vacuum() async throws {
|
||||
func setup<T: DatabaseWriter>(_ dbWriter: T) throws -> T {
|
||||
@@ -376,7 +376,7 @@ class DatabaseWriterTests : GRDBTestCase {
|
||||
}
|
||||
#endif
|
||||
|
||||
#if compiler(>=5.5.2) && canImport(_Concurrency)
|
||||
#if compiler(>=5.6) && canImport(_Concurrency)
|
||||
@available(macOS 10.16, iOS 14, tvOS 14, watchOS 7, *) // async + vacuum into
|
||||
func testAsyncAwait_vacuumInto() async throws {
|
||||
// Prevent SQLCipher failures
|
||||
|
||||
@@ -534,9 +534,9 @@ class EncryptionTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite", configuration: config)
|
||||
try dbQueue.inDatabase({ db in
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertEqual(try Int.fetchOne(db, sql: "PRAGMA cipher_page_size")!, 8192)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
@@ -547,16 +547,15 @@ class EncryptionTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
let dbPool = try makeDatabasePool(filename: "testpool.sqlite", configuration: config)
|
||||
try dbPool.write({ db in
|
||||
try dbPool.write { db in
|
||||
XCTAssertEqual(try Int.fetchOne(db, sql: "PRAGMA cipher_page_size")!, 4096)
|
||||
try db.execute(sql: "CREATE TABLE data(value INTEGER)")
|
||||
try db.execute(sql: "INSERT INTO data(value) VALUES(1)")
|
||||
})
|
||||
try dbPool.read({ db in
|
||||
}
|
||||
try dbPool.read { db in
|
||||
XCTAssertEqual(try Int.fetchOne(db, sql: "PRAGMA cipher_page_size")!, 4096)
|
||||
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT value FROM data"), 1)
|
||||
})
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -684,7 +683,7 @@ class EncryptionTests: GRDBTestCase {
|
||||
guard let cipherMajorVersion = try DatabaseQueue()
|
||||
.read({ try String.fetchOne($0, sql: "PRAGMA cipher_version") })
|
||||
.flatMap({ $0.split(separator: ".").first })
|
||||
.flatMap({ Int($0 )})
|
||||
.flatMap({ Int($0) })
|
||||
else { XCTFail("Unknown SQLCipher version"); return }
|
||||
|
||||
if cipherMajorVersion >= 4 {
|
||||
|
||||
@@ -105,7 +105,7 @@ class GRDBTestCase: XCTestCase {
|
||||
|
||||
dbConfiguration.prepareDatabase { db in
|
||||
db.trace { event in
|
||||
self.sqlQueries.append(event.description)
|
||||
self.sqlQueries.append(event.expandedDescription)
|
||||
}
|
||||
|
||||
#if GRDBCIPHER_USE_ENCRYPTION
|
||||
@@ -258,3 +258,8 @@ public struct AnyValueReducer<Fetched, Value>: ValueReducer {
|
||||
__value(fetched)
|
||||
}
|
||||
}
|
||||
|
||||
#if swift(>=5.6) && canImport(_Concurrency)
|
||||
// Assume this is correct :-/
|
||||
extension XCTestExpectation: @unchecked Sendable { }
|
||||
#endif
|
||||
@@ -0,0 +1,5 @@
|
||||
//
|
||||
// Use this file to import your target's public headers that you would like to expose to Swift.
|
||||
//
|
||||
|
||||
#include "getThreadsCount.h"
|
||||
@@ -20,32 +20,36 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
extent: .observationLifetime)
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
do {
|
||||
var value: Int?
|
||||
let cancellable = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value = $0 })
|
||||
// We want to control when the shared observation is deallocated
|
||||
withExtendedLifetime(sharedObservation) { sharedObservation in
|
||||
do {
|
||||
var value: Int?
|
||||
let cancellable = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value = $0 })
|
||||
|
||||
XCTAssertEqual(value, 0)
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"])
|
||||
|
||||
cancellable.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
}
|
||||
|
||||
XCTAssertEqual(value, 0)
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"])
|
||||
|
||||
cancellable.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
do {
|
||||
var value: Int?
|
||||
let cancellable = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value = $0 })
|
||||
|
||||
XCTAssertEqual(value, 0)
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
cancellable.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
var value: Int?
|
||||
let cancellable = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value = $0 })
|
||||
|
||||
XCTAssertEqual(value, 0)
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
cancellable.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
}
|
||||
|
||||
// Deallocate the shared observation
|
||||
sharedObservation = nil
|
||||
XCTAssertEqual(log.flush(), ["cancel"])
|
||||
}
|
||||
@@ -68,28 +72,32 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
extent: .observationLifetime)
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
do {
|
||||
var value1: Int?
|
||||
var value2: Int?
|
||||
let cancellable1 = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value in
|
||||
value1 = value
|
||||
_ = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value in
|
||||
value2 = value
|
||||
})
|
||||
})
|
||||
|
||||
XCTAssertEqual(value1, 0)
|
||||
XCTAssertEqual(value2, 0)
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"])
|
||||
|
||||
cancellable1.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
// We want to control when the shared observation is deallocated
|
||||
withExtendedLifetime(sharedObservation) { sharedObservation in
|
||||
do {
|
||||
var value1: Int?
|
||||
var value2: Int?
|
||||
let cancellable1 = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value in
|
||||
value1 = value
|
||||
_ = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value in
|
||||
value2 = value
|
||||
})
|
||||
})
|
||||
|
||||
XCTAssertEqual(value1, 0)
|
||||
XCTAssertEqual(value2, 0)
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"])
|
||||
|
||||
cancellable1.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
}
|
||||
}
|
||||
|
||||
// Deallocate the shared observation
|
||||
sharedObservation = nil
|
||||
XCTAssertEqual(log.flush(), ["cancel"])
|
||||
}
|
||||
@@ -120,7 +128,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 1)
|
||||
}
|
||||
|
||||
|
||||
do {
|
||||
let recorder = publisher.record()
|
||||
try XCTAssertEqual(recorder.next().get(), 1)
|
||||
@@ -148,32 +156,36 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
extent: .whileObserved)
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
do {
|
||||
var value: Int?
|
||||
let cancellable = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value = $0 })
|
||||
// We want to control when the shared observation is deallocated
|
||||
withExtendedLifetime(sharedObservation) { sharedObservation in
|
||||
do {
|
||||
var value: Int?
|
||||
let cancellable = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value = $0 })
|
||||
|
||||
XCTAssertEqual(value, 0)
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"])
|
||||
|
||||
cancellable.cancel()
|
||||
XCTAssertEqual(log.flush(), ["cancel"])
|
||||
}
|
||||
|
||||
XCTAssertEqual(value, 0)
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"])
|
||||
|
||||
cancellable.cancel()
|
||||
XCTAssertEqual(log.flush(), ["cancel"])
|
||||
do {
|
||||
var value: Int?
|
||||
let cancellable = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value = $0 })
|
||||
|
||||
XCTAssertEqual(value, 0)
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"])
|
||||
|
||||
cancellable.cancel()
|
||||
XCTAssertEqual(log.flush(), ["cancel"])
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
var value: Int?
|
||||
let cancellable = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value = $0 })
|
||||
|
||||
XCTAssertEqual(value, 0)
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"])
|
||||
|
||||
cancellable.cancel()
|
||||
XCTAssertEqual(log.flush(), ["cancel"])
|
||||
}
|
||||
|
||||
// Deallocate the shared observation
|
||||
sharedObservation = nil
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
}
|
||||
@@ -196,7 +208,8 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
extent: .whileObserved)
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
do {
|
||||
// We want to control when the shared observation is deallocated
|
||||
withExtendedLifetime(sharedObservation) { sharedObservation in
|
||||
var value1: Int?
|
||||
var value2: Int?
|
||||
let cancellable1 = sharedObservation!.start(
|
||||
@@ -212,16 +225,17 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
|
||||
XCTAssertEqual(value1, 0)
|
||||
XCTAssertEqual(value2, 0)
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"])
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"])
|
||||
|
||||
cancellable1.cancel()
|
||||
XCTAssertEqual(log.flush(), ["cancel"])
|
||||
}
|
||||
|
||||
// Deallocate the shared observation
|
||||
sharedObservation = nil
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
}
|
||||
|
||||
|
||||
func test_async_observationLifetime() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
@@ -240,79 +254,82 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
extent: .observationLifetime)
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
// --- Start observation 1
|
||||
var values1: [Int] = []
|
||||
let exp1 = expectation(description: "")
|
||||
exp1.expectedFulfillmentCount = 2
|
||||
exp1.assertForOverFulfill = false
|
||||
let cancellable1 = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: {
|
||||
values1.append($0)
|
||||
exp1.fulfill()
|
||||
})
|
||||
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
wait(for: [exp1], timeout: 1)
|
||||
XCTAssertEqual(values1, [0, 1])
|
||||
XCTAssertEqual(log.flush(), [
|
||||
"start", "fetch", "value: 0", "tracked region: player(*)",
|
||||
"database did change", "fetch", "value: 1"])
|
||||
|
||||
// --- Start observation 2
|
||||
var values2: [Int] = []
|
||||
let exp2 = expectation(description: "")
|
||||
exp2.expectedFulfillmentCount = 2
|
||||
exp2.assertForOverFulfill = false
|
||||
let cancellable2 = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: {
|
||||
values2.append($0)
|
||||
exp2.fulfill()
|
||||
})
|
||||
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
wait(for: [exp2], timeout: 1)
|
||||
XCTAssertEqual(values1, [0, 1, 2])
|
||||
XCTAssertEqual(values2, [1, 2])
|
||||
XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 2"])
|
||||
|
||||
// --- Stop observation 1
|
||||
cancellable1.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
// --- Start observation 3
|
||||
var values3: [Int] = []
|
||||
let exp3 = expectation(description: "")
|
||||
exp3.expectedFulfillmentCount = 2
|
||||
exp3.assertForOverFulfill = false
|
||||
let cancellable3 = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: {
|
||||
values3.append($0)
|
||||
exp3.fulfill()
|
||||
})
|
||||
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
wait(for: [exp3], timeout: 1)
|
||||
XCTAssertEqual(values1, [0, 1, 2])
|
||||
XCTAssertEqual(values2, [1, 2, 3])
|
||||
XCTAssertEqual(values3, [2, 3])
|
||||
XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 3"])
|
||||
|
||||
// --- Stop observation 2
|
||||
cancellable2.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
// --- Stop observation 3
|
||||
cancellable3.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
// We want to control when the shared observation is deallocated
|
||||
try withExtendedLifetime(sharedObservation) { sharedObservation in
|
||||
// --- Start observation 1
|
||||
var values1: [Int] = []
|
||||
let exp1 = expectation(description: "")
|
||||
exp1.expectedFulfillmentCount = 2
|
||||
exp1.assertForOverFulfill = false
|
||||
let cancellable1 = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: {
|
||||
values1.append($0)
|
||||
exp1.fulfill()
|
||||
})
|
||||
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
wait(for: [exp1], timeout: 1)
|
||||
XCTAssertEqual(values1, [0, 1])
|
||||
XCTAssertEqual(log.flush(), [
|
||||
"start", "fetch", "tracked region: player(*)", "value: 0",
|
||||
"database did change", "fetch", "value: 1"])
|
||||
|
||||
// --- Start observation 2
|
||||
var values2: [Int] = []
|
||||
let exp2 = expectation(description: "")
|
||||
exp2.expectedFulfillmentCount = 2
|
||||
exp2.assertForOverFulfill = false
|
||||
let cancellable2 = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: {
|
||||
values2.append($0)
|
||||
exp2.fulfill()
|
||||
})
|
||||
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
wait(for: [exp2], timeout: 1)
|
||||
XCTAssertEqual(values1, [0, 1, 2])
|
||||
XCTAssertEqual(values2, [1, 2])
|
||||
XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 2"])
|
||||
|
||||
// --- Stop observation 1
|
||||
cancellable1.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
// --- Start observation 3
|
||||
var values3: [Int] = []
|
||||
let exp3 = expectation(description: "")
|
||||
exp3.expectedFulfillmentCount = 2
|
||||
exp3.assertForOverFulfill = false
|
||||
let cancellable3 = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: {
|
||||
values3.append($0)
|
||||
exp3.fulfill()
|
||||
})
|
||||
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
wait(for: [exp3], timeout: 1)
|
||||
XCTAssertEqual(values1, [0, 1, 2])
|
||||
XCTAssertEqual(values2, [1, 2, 3])
|
||||
XCTAssertEqual(values3, [2, 3])
|
||||
XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 3"])
|
||||
|
||||
// --- Stop observation 2
|
||||
cancellable2.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
// --- Stop observation 3
|
||||
cancellable3.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
}
|
||||
|
||||
// --- Release shared observation
|
||||
sharedObservation = nil
|
||||
XCTAssertEqual(log.flush(), ["cancel"])
|
||||
}
|
||||
|
||||
|
||||
func test_async_observationLifetime_early_release() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
@@ -342,7 +359,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
|
||||
switch value {
|
||||
case 0:
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"])
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"])
|
||||
case 1:
|
||||
XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 1"])
|
||||
case 2:
|
||||
@@ -387,7 +404,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 1)
|
||||
}
|
||||
|
||||
|
||||
do {
|
||||
let recorder = publisher.record()
|
||||
try XCTAssert(recorder.availableElements.get().isEmpty)
|
||||
@@ -416,73 +433,76 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
extent: .whileObserved)
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
// --- Start observation 1
|
||||
var values1: [Int] = []
|
||||
let exp1 = expectation(description: "")
|
||||
exp1.expectedFulfillmentCount = 2
|
||||
exp1.assertForOverFulfill = false
|
||||
let cancellable1 = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: {
|
||||
values1.append($0)
|
||||
exp1.fulfill()
|
||||
})
|
||||
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
wait(for: [exp1], timeout: 1)
|
||||
XCTAssertEqual(values1, [0, 1])
|
||||
XCTAssertEqual(log.flush(), [
|
||||
"start", "fetch", "value: 0", "tracked region: player(*)",
|
||||
"database did change", "fetch", "value: 1"])
|
||||
|
||||
// --- Start observation 2
|
||||
var values2: [Int] = []
|
||||
let exp2 = expectation(description: "")
|
||||
exp2.expectedFulfillmentCount = 2
|
||||
exp2.assertForOverFulfill = false
|
||||
let cancellable2 = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: {
|
||||
values2.append($0)
|
||||
exp2.fulfill()
|
||||
})
|
||||
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
wait(for: [exp2], timeout: 1)
|
||||
XCTAssertEqual(values1, [0, 1, 2])
|
||||
XCTAssertEqual(values2, [1, 2])
|
||||
XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 2"])
|
||||
|
||||
// --- Stop observation 1
|
||||
cancellable1.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
// --- Start observation 3
|
||||
var values3: [Int] = []
|
||||
let exp3 = expectation(description: "")
|
||||
exp3.expectedFulfillmentCount = 2
|
||||
exp3.assertForOverFulfill = false
|
||||
let cancellable3 = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: {
|
||||
values3.append($0)
|
||||
exp3.fulfill()
|
||||
})
|
||||
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
wait(for: [exp3], timeout: 1)
|
||||
XCTAssertEqual(values1, [0, 1, 2])
|
||||
XCTAssertEqual(values2, [1, 2, 3])
|
||||
XCTAssertEqual(values3, [2, 3])
|
||||
XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 3"])
|
||||
|
||||
// --- Stop observation 2
|
||||
cancellable2.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
// --- Stop observation 3
|
||||
cancellable3.cancel()
|
||||
XCTAssertEqual(log.flush(), ["cancel"])
|
||||
// We want to control when the shared observation is deallocated
|
||||
try withExtendedLifetime(sharedObservation) { sharedObservation in
|
||||
// --- Start observation 1
|
||||
var values1: [Int] = []
|
||||
let exp1 = expectation(description: "")
|
||||
exp1.expectedFulfillmentCount = 2
|
||||
exp1.assertForOverFulfill = false
|
||||
let cancellable1 = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: {
|
||||
values1.append($0)
|
||||
exp1.fulfill()
|
||||
})
|
||||
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
wait(for: [exp1], timeout: 1)
|
||||
XCTAssertEqual(values1, [0, 1])
|
||||
XCTAssertEqual(log.flush(), [
|
||||
"start", "fetch", "tracked region: player(*)", "value: 0",
|
||||
"database did change", "fetch", "value: 1"])
|
||||
|
||||
// --- Start observation 2
|
||||
var values2: [Int] = []
|
||||
let exp2 = expectation(description: "")
|
||||
exp2.expectedFulfillmentCount = 2
|
||||
exp2.assertForOverFulfill = false
|
||||
let cancellable2 = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: {
|
||||
values2.append($0)
|
||||
exp2.fulfill()
|
||||
})
|
||||
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
wait(for: [exp2], timeout: 1)
|
||||
XCTAssertEqual(values1, [0, 1, 2])
|
||||
XCTAssertEqual(values2, [1, 2])
|
||||
XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 2"])
|
||||
|
||||
// --- Stop observation 1
|
||||
cancellable1.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
// --- Start observation 3
|
||||
var values3: [Int] = []
|
||||
let exp3 = expectation(description: "")
|
||||
exp3.expectedFulfillmentCount = 2
|
||||
exp3.assertForOverFulfill = false
|
||||
let cancellable3 = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: {
|
||||
values3.append($0)
|
||||
exp3.fulfill()
|
||||
})
|
||||
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
wait(for: [exp3], timeout: 1)
|
||||
XCTAssertEqual(values1, [0, 1, 2])
|
||||
XCTAssertEqual(values2, [1, 2, 3])
|
||||
XCTAssertEqual(values3, [2, 3])
|
||||
XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 3"])
|
||||
|
||||
// --- Stop observation 2
|
||||
cancellable2.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
// --- Stop observation 3
|
||||
cancellable3.cancel()
|
||||
XCTAssertEqual(log.flush(), ["cancel"])
|
||||
}
|
||||
|
||||
// --- Release shared observation
|
||||
sharedObservation = nil
|
||||
@@ -526,7 +546,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
if case .finished = try wait(for: recorder1.completion, timeout: 1) { XCTFail("Expected error") }
|
||||
if case .finished = try wait(for: recorder2.completion, timeout: 1) { XCTFail("Expected error") }
|
||||
XCTAssertEqual(log.flush(), [
|
||||
"start", "fetch", "value: 0", "tracked region: player(*)",
|
||||
"start", "fetch", "tracked region: player(*)", "value: 0",
|
||||
"database did change", "fetch", "failure: TestError()"])
|
||||
}
|
||||
|
||||
@@ -582,7 +602,7 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
if case .finished = try wait(for: recorder1.completion, timeout: 1) { XCTFail("Expected error") }
|
||||
if case .finished = try wait(for: recorder2.completion, timeout: 1) { XCTFail("Expected error") }
|
||||
XCTAssertEqual(log.flush(), [
|
||||
"start", "fetch", "value: 0", "tracked region: player(*)",
|
||||
"start", "fetch", "tracked region: player(*)", "value: 0",
|
||||
"database did change", "fetch", "failure: TestError()"])
|
||||
}
|
||||
|
||||
@@ -596,12 +616,12 @@ class SharedValueObservationTests: GRDBTestCase {
|
||||
fetchError = nil
|
||||
let recorder = publisher.record()
|
||||
try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 1)
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "value: 1", "tracked region: player(*)"])
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 1"])
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if compiler(>=5.5.2) && canImport(_Concurrency)
|
||||
|
||||
#if compiler(>=5.6) && canImport(_Concurrency)
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
func testAsyncAwait() async throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
@testable import GRDB
|
||||
|
||||
private class Observer : TransactionObserver {
|
||||
var lastCommittedEvents: [DatabaseEvent] = []
|
||||
@@ -1784,4 +1784,89 @@ class TransactionObserverTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Read-Only Connection
|
||||
|
||||
func testReadOnlyConnection() throws {
|
||||
let dbQueue = try makeDatabaseQueue(filename: "database.sqlite")
|
||||
try setupArtistDatabase(in: dbQueue)
|
||||
|
||||
dbConfiguration.readonly = true
|
||||
let readOnlyQueue = try makeDatabaseQueue(filename: "database.sqlite")
|
||||
|
||||
let observer = Observer()
|
||||
readOnlyQueue.add(transactionObserver: observer, extent: .databaseLifetime)
|
||||
|
||||
try readOnlyQueue.inDatabase { db in
|
||||
do {
|
||||
try db.execute(sql: """
|
||||
BEGIN;
|
||||
COMMIT;
|
||||
""")
|
||||
XCTAssertEqual(observer.didChangeCount, 0)
|
||||
XCTAssertEqual(observer.willCommitCount, 0)
|
||||
XCTAssertEqual(observer.didCommitCount, 0)
|
||||
XCTAssertEqual(observer.didRollbackCount, 0)
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
XCTAssertEqual(observer.willChangeCount, 0)
|
||||
#endif
|
||||
}
|
||||
|
||||
do {
|
||||
try db.execute(sql: """
|
||||
BEGIN;
|
||||
SELECT * FROM artists;
|
||||
COMMIT;
|
||||
""")
|
||||
XCTAssertEqual(observer.didChangeCount, 0)
|
||||
XCTAssertEqual(observer.willCommitCount, 0)
|
||||
XCTAssertEqual(observer.didCommitCount, 0)
|
||||
XCTAssertEqual(observer.didRollbackCount, 0)
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
XCTAssertEqual(observer.willChangeCount, 0)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testReadOnlyBlock() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try setupArtistDatabase(in: dbQueue)
|
||||
|
||||
let observer = Observer()
|
||||
dbQueue.add(transactionObserver: observer, extent: .databaseLifetime)
|
||||
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.readOnly {
|
||||
do {
|
||||
try db.execute(sql: """
|
||||
BEGIN;
|
||||
COMMIT;
|
||||
""")
|
||||
XCTAssertEqual(observer.didChangeCount, 0)
|
||||
XCTAssertEqual(observer.willCommitCount, 0)
|
||||
XCTAssertEqual(observer.didCommitCount, 0)
|
||||
XCTAssertEqual(observer.didRollbackCount, 0)
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
XCTAssertEqual(observer.willChangeCount, 0)
|
||||
#endif
|
||||
}
|
||||
|
||||
do {
|
||||
try db.execute(sql: """
|
||||
BEGIN;
|
||||
SELECT * FROM artists;
|
||||
COMMIT;
|
||||
""")
|
||||
XCTAssertEqual(observer.didChangeCount, 0)
|
||||
XCTAssertEqual(observer.willCommitCount, 0)
|
||||
XCTAssertEqual(observer.didCommitCount, 0)
|
||||
XCTAssertEqual(observer.didRollbackCount, 0)
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
XCTAssertEqual(observer.willChangeCount, 0)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -85,6 +85,53 @@ class TruncateOptimizationTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testExecuteDeleteCaseSensitivity() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
class DeletionObserver : TransactionObserver {
|
||||
var deletionCount = 0
|
||||
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
if case .delete(tableName: "pLaYeR") = eventKind {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
if case .delete = event.kind {
|
||||
deletionCount += 1
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidCommit(_ db: Database) { }
|
||||
func databaseDidRollback(_ db: Database) { }
|
||||
}
|
||||
|
||||
let observer = DeletionObserver()
|
||||
dbQueue.add(transactionObserver: observer, extent: .databaseLifetime)
|
||||
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
observer.deletionCount = 0
|
||||
try db.execute(sql: "CREATE TABLE pLaYeR(a)")
|
||||
try db.execute(sql: "INSERT INTO pLaYeR VALUES (NULL)")
|
||||
try db.execute(sql: "INSERT INTO pLaYeR VALUES (NULL)")
|
||||
try db.execute(sql: "DELETE FROM pLaYeR")
|
||||
XCTAssertEqual(observer.deletionCount, 2)
|
||||
|
||||
observer.deletionCount = 0
|
||||
try db.execute(sql: "INSERT INTO pLaYeR VALUES (NULL)")
|
||||
try db.execute(sql: "DELETE FROM PLAYER")
|
||||
XCTAssertEqual(observer.deletionCount, 1)
|
||||
|
||||
observer.deletionCount = 0
|
||||
try db.execute(sql: "INSERT INTO pLaYeR VALUES (NULL)")
|
||||
try db.execute(sql: "DELETE FROM player")
|
||||
XCTAssertEqual(observer.deletionCount, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func testExecuteDeleteWithPreparedStatement() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
@@ -111,6 +158,37 @@ class TruncateOptimizationTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testExecuteDeleteWithCachedPreparedStatement() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
var deletionEvents: [[String: Int]] = []
|
||||
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
try db.execute(sql: "CREATE TABLE t(a)")
|
||||
try db.cachedStatement(sql: "DELETE FROM t").execute()
|
||||
|
||||
// Start observing after statement has been cached: it does not
|
||||
// prevent the truncate optimization.
|
||||
let observer = DeletionObserver { deletionEvents.append($0) }
|
||||
db.add(transactionObserver: observer, extent: .databaseLifetime)
|
||||
|
||||
try db.execute(sql: "INSERT INTO t VALUES (NULL)")
|
||||
try db.execute(sql: "INSERT INTO t VALUES (NULL)")
|
||||
deletionEvents = []
|
||||
// This must be a recompiled statement, so that the truncate
|
||||
// optimization is prevented.
|
||||
try db.cachedStatement(sql: "DELETE FROM t").execute()
|
||||
XCTAssertEqual(deletionEvents.count, 1)
|
||||
XCTAssertEqual(deletionEvents[0], ["t": 2])
|
||||
|
||||
try db.execute(sql: "INSERT INTO t VALUES (NULL)")
|
||||
deletionEvents = []
|
||||
try db.cachedStatement(sql: "DELETE FROM t").execute()
|
||||
XCTAssertEqual(deletionEvents.count, 1)
|
||||
XCTAssertEqual(deletionEvents[0], ["t": 1])
|
||||
}
|
||||
}
|
||||
|
||||
func testDropTable() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
|
||||
@@ -186,8 +186,8 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
XCTAssertEqual(logger.strings.prefix(7), [
|
||||
"start",
|
||||
"fetch",
|
||||
"value: nil",
|
||||
"tracked region: \(expectedRegion)",
|
||||
"value: nil",
|
||||
"database did change",
|
||||
"fetch",
|
||||
"value: Optional(1)"])
|
||||
@@ -228,8 +228,8 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
XCTAssertEqual(logger.strings.prefix(7), [
|
||||
"start",
|
||||
"fetch",
|
||||
"value: nil",
|
||||
"tracked region: \(expectedRegion)",
|
||||
"value: nil",
|
||||
"database did change",
|
||||
"fetch",
|
||||
"value: Optional(1)"])
|
||||
@@ -325,8 +325,8 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
XCTAssertEqual(logger.strings, [
|
||||
"start",
|
||||
"fetch",
|
||||
"value: nil",
|
||||
"tracked region: \(expectedRegion)",
|
||||
"value: nil",
|
||||
"database did change",
|
||||
"fetch",
|
||||
"failure: SQLite error 1: no such table: player - while executing `SELECT MAX(id) FROM player`"])
|
||||
@@ -368,8 +368,8 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
XCTAssertEqual(logger.strings, [
|
||||
"start",
|
||||
"fetch",
|
||||
"value: nil",
|
||||
"tracked region: \(expectedRegion)",
|
||||
"value: nil",
|
||||
"database did change",
|
||||
"fetch",
|
||||
"failure: SQLite error 1: no such table: player - while executing `SELECT MAX(id) FROM player`"])
|
||||
@@ -394,7 +394,7 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
// transaction observer, some write did happen.
|
||||
var needsChange = true
|
||||
let observation = ValueObservation
|
||||
.trackingConstantRegion({ db -> Int? in
|
||||
.trackingConstantRegion { db -> Int? in
|
||||
if needsChange {
|
||||
needsChange = false
|
||||
try dbPool.write { db in
|
||||
@@ -405,7 +405,7 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
return try Int.fetchOne(db, sql: "SELECT MAX(id) FROM player")
|
||||
})
|
||||
}
|
||||
.print(to: logger)
|
||||
|
||||
let expectedRegion = try region(sql: "SELECT MAX(id) FROM player", in: dbPool)
|
||||
@@ -422,9 +422,9 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
"start",
|
||||
"fetch",
|
||||
"value: nil",
|
||||
"tracked region: \(expectedRegion)",
|
||||
"database did change",
|
||||
"fetch",
|
||||
"tracked region: \(expectedRegion)",
|
||||
"value: nil"])
|
||||
}
|
||||
}
|
||||
@@ -441,7 +441,7 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
// transaction observer, some write did happen.
|
||||
var needsChange = true
|
||||
let observation = ValueObservation
|
||||
.trackingConstantRegion({ db -> Int? in
|
||||
.trackingConstantRegion { db -> Int? in
|
||||
if needsChange {
|
||||
needsChange = false
|
||||
try dbPool.write { db in
|
||||
@@ -452,7 +452,7 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
return try Int.fetchOne(db, sql: "SELECT MAX(id) FROM player")
|
||||
})
|
||||
}
|
||||
.print(to: logger)
|
||||
|
||||
let expectedRegion = try region(sql: "SELECT MAX(id) FROM player", in: dbPool)
|
||||
@@ -469,9 +469,9 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
"start",
|
||||
"fetch",
|
||||
"value: nil",
|
||||
"tracked region: \(expectedRegion)",
|
||||
"database did change",
|
||||
"fetch",
|
||||
"tracked region: \(expectedRegion)",
|
||||
"value: nil"])
|
||||
}
|
||||
}
|
||||
@@ -491,10 +491,10 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
|
||||
let logger = TestStream()
|
||||
let observation = ValueObservation
|
||||
.tracking({ db -> Int? in
|
||||
.tracking { db -> Int? in
|
||||
let table = try String.fetchOne(db, sql: "SELECT t FROM choice")!
|
||||
return try Int.fetchOne(db, sql: "SELECT MAX(id) FROM \(table)")
|
||||
})
|
||||
}
|
||||
.print(to: logger)
|
||||
|
||||
let expectedRegionA = try region(sql: "SELECT MAX(id) FROM a", in: dbQueue)
|
||||
@@ -520,8 +520,8 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
XCTAssertEqual(logger.strings.prefix(11), [
|
||||
"start",
|
||||
"fetch",
|
||||
"value: nil",
|
||||
"tracked region: \(expectedRegionA),choice(t)",
|
||||
"value: nil",
|
||||
"database did change",
|
||||
"fetch",
|
||||
"tracked region: \(expectedRegionB),choice(t)",
|
||||
@@ -555,13 +555,15 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
onChange: { _ in expectation.fulfill() })
|
||||
withExtendedLifetime(cancellable) {
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
XCTAssertEqual(logger1.strings.prefix(3), [
|
||||
XCTAssertEqual(logger1.strings.prefix(4), [
|
||||
"start",
|
||||
"fetch",
|
||||
"tracked region: player(*)",
|
||||
"value: nil"])
|
||||
XCTAssertEqual(logger2.strings.prefix(3), [
|
||||
XCTAssertEqual(logger2.strings.prefix(4), [
|
||||
"log: start",
|
||||
"log: fetch",
|
||||
"log: tracked region: player(*)",
|
||||
"log: value: nil"])
|
||||
}
|
||||
}
|
||||
@@ -589,13 +591,15 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
onChange: { _ in expectation.fulfill() })
|
||||
withExtendedLifetime(cancellable) {
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
XCTAssertEqual(logger1.strings.prefix(3), [
|
||||
XCTAssertEqual(logger1.strings.prefix(4), [
|
||||
"start",
|
||||
"fetch",
|
||||
"tracked region: player(*)",
|
||||
"value: nil"])
|
||||
XCTAssertEqual(logger2.strings.prefix(3), [
|
||||
XCTAssertEqual(logger2.strings.prefix(4), [
|
||||
"start",
|
||||
"fetch",
|
||||
"tracked region: player(*)",
|
||||
"value: foo"])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,7 +80,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase {
|
||||
|
||||
let recorder = observation.record(in: dbQueue)
|
||||
try dbQueue.writeWithoutTransaction(performDatabaseModifications)
|
||||
let results = try wait(for: recorder.next(6), timeout: 1)
|
||||
let results = try wait(for: recorder.next(6), timeout: 5)
|
||||
|
||||
XCTAssertNil(results[0])
|
||||
|
||||
@@ -117,7 +117,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase {
|
||||
|
||||
let recorder = observation.record(in: dbQueue)
|
||||
try dbQueue.writeWithoutTransaction(performDatabaseModifications)
|
||||
let results = try wait(for: recorder.next(6), timeout: 1)
|
||||
let results = try wait(for: recorder.next(6), timeout: 5)
|
||||
|
||||
XCTAssertEqual(results[0].count, 0)
|
||||
|
||||
|
||||
@@ -228,13 +228,13 @@ extension ValueObservation {
|
||||
let cancellable = start(
|
||||
in: reader,
|
||||
scheduling: scheduler,
|
||||
onError: {
|
||||
onError: { [weak recorder] in
|
||||
onError?($0)
|
||||
recorder.onError($0)
|
||||
recorder?.onError($0)
|
||||
},
|
||||
onChange: {
|
||||
onChange: { [weak recorder] in
|
||||
onChange?($0)
|
||||
recorder.onChange($0)
|
||||
recorder?.onChange($0)
|
||||
})
|
||||
recorder.receive(cancellable)
|
||||
return recorder
|
||||
@@ -422,13 +422,6 @@ extension GRDBTestCase {
|
||||
throws
|
||||
where Reducer.Value: Equatable
|
||||
{
|
||||
#if SQLITE_HAS_CODEC || GRDBCUSTOMSQLITE
|
||||
// debug SQLite builds can be *very* slow
|
||||
let timeout: TimeInterval = 4
|
||||
#else
|
||||
let timeout: TimeInterval = 1
|
||||
#endif
|
||||
|
||||
func test(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
@@ -455,7 +448,7 @@ extension GRDBTestCase {
|
||||
try writer.writeWithoutTransaction(recordedUpdates)
|
||||
|
||||
let expectation = recorder.next(expectedValues.count)
|
||||
let values = try wait(for: expectation, timeout: timeout)
|
||||
let values = try wait(for: expectation, timeout: 5)
|
||||
XCTAssertEqual(
|
||||
values, expectedValues,
|
||||
"\(#function), \(writer), \(scheduler)", file: file, line: line)
|
||||
@@ -485,7 +478,7 @@ extension GRDBTestCase {
|
||||
}
|
||||
|
||||
let expectation = recorder.next(expectedValues.count)
|
||||
let values = try wait(for: expectation, timeout: timeout)
|
||||
let values = try wait(for: expectation, timeout: 5)
|
||||
XCTAssertEqual(
|
||||
values, expectedValues,
|
||||
"\(#function), \(writer), \(scheduler)", file: file, line: line)
|
||||
@@ -516,14 +509,14 @@ extension GRDBTestCase {
|
||||
if waitForLast {
|
||||
// Optimization!
|
||||
let expectation = recorder.prefix(until: { $0 == lastExpectedValue } )
|
||||
recordedValues = try wait(for: expectation, timeout: timeout)
|
||||
recordedValues = try wait(for: expectation, timeout: 5)
|
||||
} else {
|
||||
// Slow!
|
||||
assertionFailure("Please rewrite your test, because it is too slow: make sure the last expected value is unique.")
|
||||
let expectation = recorder
|
||||
.prefix(expectedValues.count + 2 /* pool may perform double initial fetch */)
|
||||
.inverted
|
||||
recordedValues = try wait(for: expectation, timeout: timeout)
|
||||
recordedValues = try wait(for: expectation, timeout: 5)
|
||||
}
|
||||
|
||||
if scheduler.immediateInitialValue() {
|
||||
@@ -565,14 +558,14 @@ extension GRDBTestCase {
|
||||
if waitForLast {
|
||||
// Optimization!
|
||||
let expectation = recorder.prefix(until: { $0 == lastExpectedValue } )
|
||||
recordedValues = try wait(for: expectation, timeout: timeout)
|
||||
recordedValues = try wait(for: expectation, timeout: 5)
|
||||
} else {
|
||||
// Slow!
|
||||
assertionFailure("Please rewrite your test, because it is too slow: make sure the last expected value is unique.")
|
||||
let expectation = recorder
|
||||
.prefix(expectedValues.count + 2 /* pool may perform double initial fetch */)
|
||||
.inverted
|
||||
recordedValues = try wait(for: expectation, timeout: timeout)
|
||||
recordedValues = try wait(for: expectation, timeout: 5)
|
||||
}
|
||||
|
||||
XCTAssertEqual(recordedValues.first, expectedValues.first)
|
||||
@@ -639,13 +632,6 @@ extension GRDBTestCase {
|
||||
line: UInt)
|
||||
throws
|
||||
{
|
||||
#if SQLITE_HAS_CODEC || GRDBCUSTOMSQLITE
|
||||
// debug SQLite builds can be *very* slow
|
||||
let timeout: TimeInterval = 2
|
||||
#else
|
||||
let timeout: TimeInterval = 1
|
||||
#endif
|
||||
|
||||
func test(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
@@ -659,7 +645,7 @@ extension GRDBTestCase {
|
||||
scheduling: scheduler,
|
||||
onError: { _ in testErrorDispatching() })
|
||||
|
||||
let (_, error) = try wait(for: recorder.failure(), timeout: timeout)
|
||||
let (_, error) = try wait(for: recorder.failure(), timeout: 5)
|
||||
if let error = error as? Failure {
|
||||
try testFailure(error, writer)
|
||||
} else {
|
||||
|
||||
@@ -137,10 +137,10 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
|
||||
|
||||
var regions: [DatabaseRegion] = []
|
||||
let observation = ValueObservation
|
||||
.tracking({ db -> Int in
|
||||
.tracking { db -> Int in
|
||||
let table = try String.fetchOne(db, sql: "SELECT name FROM source")!
|
||||
return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")!
|
||||
})
|
||||
}
|
||||
.handleEvents(willTrackRegion: { regions.append($0) })
|
||||
|
||||
let observer = observation.start(
|
||||
@@ -188,10 +188,10 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
|
||||
|
||||
var regions: [DatabaseRegion] = []
|
||||
let observation = ValueObservation
|
||||
.tracking({ db -> Int in
|
||||
.tracking { db -> Int in
|
||||
let table = try String.fetchOne(db, sql: "SELECT name FROM source")!
|
||||
return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")!
|
||||
})
|
||||
}
|
||||
.handleEvents(willTrackRegion: { regions.append($0) })
|
||||
|
||||
let observer = observation.start(
|
||||
|
||||
@@ -210,8 +210,8 @@ class ValueObservationTests: GRDBTestCase {
|
||||
wait(for: [expectation], timeout: 4)
|
||||
XCTAssertEqual(logger.strings, [
|
||||
"start",
|
||||
"tracked region: t(*)",
|
||||
"fetch",
|
||||
"tracked region: t(*)",
|
||||
"value: 0",
|
||||
"database did change",
|
||||
"fetch",
|
||||
@@ -254,8 +254,8 @@ class ValueObservationTests: GRDBTestCase {
|
||||
wait(for: [expectation], timeout: 4)
|
||||
XCTAssertEqual(logger.strings, [
|
||||
"start",
|
||||
"tracked region: other(*)",
|
||||
"fetch",
|
||||
"tracked region: other(*)",
|
||||
"value: 0",
|
||||
"database did change",
|
||||
"fetch",
|
||||
@@ -298,8 +298,8 @@ class ValueObservationTests: GRDBTestCase {
|
||||
wait(for: [expectation], timeout: 4)
|
||||
XCTAssertEqual(logger.strings, [
|
||||
"start",
|
||||
"tracked region: other(*),t(*)",
|
||||
"fetch",
|
||||
"tracked region: other(*),t(*)",
|
||||
"value: 0",
|
||||
"database did change",
|
||||
"fetch",
|
||||
@@ -418,39 +418,38 @@ class ValueObservationTests: GRDBTestCase {
|
||||
return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")!
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT
|
||||
let expectation = self.expectation(description: "")
|
||||
expectation.expectedFulfillmentCount = 2
|
||||
var observedCounts: [Int] = []
|
||||
let cancellable = observation.start(
|
||||
in: dbPool,
|
||||
scheduling: .async(onQueue: .main),
|
||||
onError: { error in XCTFail("Unexpected error: \(error)") },
|
||||
onChange: { count in
|
||||
observedCounts.append(count)
|
||||
expectation.fulfill()
|
||||
})
|
||||
withExtendedLifetime(cancellable) {
|
||||
waitForExpectations(timeout: 2, handler: nil)
|
||||
XCTAssertEqual(observedCounts, [0, 1])
|
||||
}
|
||||
let expectedCounts: [Int]
|
||||
#if os(macOS) || targetEnvironment(macCatalyst) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) || compiler(<5.7)
|
||||
// Optimization not available
|
||||
expectedCounts = [0, 0, 1]
|
||||
#elseif GRDBCUSTOMSQLITE
|
||||
// Optimization available
|
||||
expectedCounts = [0, 1]
|
||||
#else
|
||||
let expectation = self.expectation(description: "")
|
||||
expectation.expectedFulfillmentCount = 3
|
||||
var observedCounts: [Int] = []
|
||||
let cancellable = observation.start(
|
||||
in: dbPool,
|
||||
scheduling: .async(onQueue: .main),
|
||||
onError: { error in XCTFail("Unexpected error: \(error)") },
|
||||
onChange: { count in
|
||||
observedCounts.append(count)
|
||||
expectation.fulfill()
|
||||
})
|
||||
withExtendedLifetime(cancellable) {
|
||||
waitForExpectations(timeout: 2, handler: nil)
|
||||
XCTAssertEqual(observedCounts, [0, 0, 1])
|
||||
if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) {
|
||||
// Optimization available
|
||||
expectedCounts = [0, 1]
|
||||
} else {
|
||||
// Optimization not available
|
||||
expectedCounts = [0, 0, 1]
|
||||
}
|
||||
#endif
|
||||
|
||||
let expectation = self.expectation(description: "")
|
||||
expectation.expectedFulfillmentCount = expectedCounts.count
|
||||
var observedCounts: [Int] = []
|
||||
let cancellable = observation.start(
|
||||
in: dbPool,
|
||||
scheduling: .async(onQueue: .main),
|
||||
onError: { error in XCTFail("Unexpected error: \(error)") },
|
||||
onChange: { count in
|
||||
observedCounts.append(count)
|
||||
expectation.fulfill()
|
||||
})
|
||||
withExtendedLifetime(cancellable) {
|
||||
waitForExpectations(timeout: 2, handler: nil)
|
||||
XCTAssertEqual(observedCounts, expectedCounts)
|
||||
}
|
||||
}
|
||||
|
||||
func testAllowedSnapshotOptimizationWithImmediateScheduler() throws {
|
||||
@@ -477,39 +476,38 @@ class ValueObservationTests: GRDBTestCase {
|
||||
return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")!
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT
|
||||
let expectation = self.expectation(description: "")
|
||||
expectation.expectedFulfillmentCount = 2
|
||||
var observedCounts: [Int] = []
|
||||
let cancellable = observation.start(
|
||||
in: dbPool,
|
||||
scheduling: .immediate,
|
||||
onError: { error in XCTFail("Unexpected error: \(error)") },
|
||||
onChange: { count in
|
||||
observedCounts.append(count)
|
||||
expectation.fulfill()
|
||||
})
|
||||
withExtendedLifetime(cancellable) {
|
||||
waitForExpectations(timeout: 2, handler: nil)
|
||||
XCTAssertEqual(observedCounts, [0, 1])
|
||||
}
|
||||
let expectedCounts: [Int]
|
||||
#if os(macOS) || targetEnvironment(macCatalyst) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) || compiler(<5.7)
|
||||
// Optimization not available
|
||||
expectedCounts = [0, 0, 1]
|
||||
#elseif GRDBCUSTOMSQLITE
|
||||
// Optimization available
|
||||
expectedCounts = [0, 1]
|
||||
#else
|
||||
let expectation = self.expectation(description: "")
|
||||
expectation.expectedFulfillmentCount = 3
|
||||
var observedCounts: [Int] = []
|
||||
let cancellable = observation.start(
|
||||
in: dbPool,
|
||||
scheduling: .immediate,
|
||||
onError: { error in XCTFail("Unexpected error: \(error)") },
|
||||
onChange: { count in
|
||||
observedCounts.append(count)
|
||||
expectation.fulfill()
|
||||
})
|
||||
withExtendedLifetime(cancellable) {
|
||||
waitForExpectations(timeout: 2, handler: nil)
|
||||
XCTAssertEqual(observedCounts, [0, 0, 1])
|
||||
if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) {
|
||||
// Optimization available
|
||||
expectedCounts = [0, 1]
|
||||
} else {
|
||||
// Optimization not available
|
||||
expectedCounts = [0, 0, 1]
|
||||
}
|
||||
#endif
|
||||
|
||||
let expectation = self.expectation(description: "")
|
||||
expectation.expectedFulfillmentCount = expectedCounts.count
|
||||
var observedCounts: [Int] = []
|
||||
let cancellable = observation.start(
|
||||
in: dbPool,
|
||||
scheduling: .immediate,
|
||||
onError: { error in XCTFail("Unexpected error: \(error)") },
|
||||
onChange: { count in
|
||||
observedCounts.append(count)
|
||||
expectation.fulfill()
|
||||
})
|
||||
withExtendedLifetime(cancellable) {
|
||||
waitForExpectations(timeout: 2, handler: nil)
|
||||
XCTAssertEqual(observedCounts, expectedCounts)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Cancellation
|
||||
@@ -649,7 +647,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
try test(makeDatabasePool())
|
||||
}
|
||||
|
||||
func tesCancellableInvalidation2() throws {
|
||||
func testCancellableInvalidation2() throws {
|
||||
// Test that observation stops when cancellable is deallocated
|
||||
func test(_ dbWriter: DatabaseWriter) throws {
|
||||
try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
|
||||
@@ -694,7 +692,56 @@ class ValueObservationTests: GRDBTestCase {
|
||||
try test(makeDatabasePool())
|
||||
}
|
||||
|
||||
#if compiler(>=5.5.2) && canImport(_Concurrency)
|
||||
func testIssue1209() throws {
|
||||
func test<Writer: DatabaseWriter>(_ dbWriter: Writer) throws {
|
||||
try dbWriter.write {
|
||||
try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
|
||||
}
|
||||
|
||||
// We'll start N observations
|
||||
let N = 100
|
||||
|
||||
// We'll wait for initial value notification before modifying the database
|
||||
let initialValueExpectation = expectation(description: "")
|
||||
initialValueExpectation.expectedFulfillmentCount = N
|
||||
|
||||
// The test will pass if we get change notifications
|
||||
let changeExpectation = expectation(description: "")
|
||||
changeExpectation.expectedFulfillmentCount = N
|
||||
|
||||
// Observe N times
|
||||
let cancellables = (0..<N).map { _ in
|
||||
ValueObservation
|
||||
.tracking(Table("t").fetchCount)
|
||||
.removeDuplicates()
|
||||
.start(
|
||||
in: dbWriter,
|
||||
onError: { XCTFail("Unexpected error: \($0)") },
|
||||
onChange: { value in
|
||||
if value == 0 {
|
||||
initialValueExpectation.fulfill()
|
||||
} else {
|
||||
changeExpectation.fulfill()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
wait(for: [initialValueExpectation], timeout: 5)
|
||||
dbWriter.asyncWriteWithoutTransaction {
|
||||
try! $0.execute(sql: "INSERT INTO t DEFAULT VALUES")
|
||||
}
|
||||
wait(for: [changeExpectation], timeout: 5)
|
||||
|
||||
// Cleanup
|
||||
for cancellable in cancellables { cancellable.cancel() }
|
||||
try dbWriter.close()
|
||||
}
|
||||
|
||||
try test(makeDatabaseQueue())
|
||||
try test(makeDatabasePool())
|
||||
}
|
||||
|
||||
#if compiler(>=5.6) && canImport(_Concurrency)
|
||||
// MARK: - Async Await
|
||||
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
@@ -704,12 +751,11 @@ class ValueObservationTests: GRDBTestCase {
|
||||
try await writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
|
||||
|
||||
let cancellationExpectation = expectation(description: "cancelled")
|
||||
let observation = ValueObservation
|
||||
.trackingConstantRegion(Table("t").fetchCount)
|
||||
.handleEvents(didCancel: { cancellationExpectation.fulfill() })
|
||||
|
||||
let task = Task { () -> [Int] in
|
||||
var counts: [Int] = []
|
||||
let observation = ValueObservation
|
||||
.trackingConstantRegion(Table("t").fetchCount)
|
||||
.handleEvents(didCancel: { cancellationExpectation.fulfill() })
|
||||
|
||||
for try await count in try observation.values(in: writer).prefix(while: { $0 < 3 }) {
|
||||
counts.append(count)
|
||||
@@ -740,12 +786,11 @@ class ValueObservationTests: GRDBTestCase {
|
||||
try await writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
|
||||
|
||||
let cancellationExpectation = expectation(description: "cancelled")
|
||||
let observation = ValueObservation
|
||||
.trackingConstantRegion(Table("t").fetchCount)
|
||||
.handleEvents(didCancel: { cancellationExpectation.fulfill() })
|
||||
|
||||
let task = Task { @MainActor () -> [Int] in
|
||||
var counts: [Int] = []
|
||||
let observation = ValueObservation
|
||||
.trackingConstantRegion(Table("t").fetchCount)
|
||||
.handleEvents(didCancel: { cancellationExpectation.fulfill() })
|
||||
|
||||
for try await count in try observation.values(in: writer, scheduling: .immediate).prefix(while: { $0 < 3 }) {
|
||||
counts.append(count)
|
||||
@@ -776,12 +821,11 @@ class ValueObservationTests: GRDBTestCase {
|
||||
try await writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
|
||||
|
||||
let cancellationExpectation = expectation(description: "cancelled")
|
||||
let observation = ValueObservation
|
||||
.trackingConstantRegion(Table("t").fetchCount)
|
||||
.handleEvents(didCancel: { cancellationExpectation.fulfill() })
|
||||
|
||||
let task = Task { () -> [Int] in
|
||||
var counts: [Int] = []
|
||||
let observation = ValueObservation
|
||||
.trackingConstantRegion(Table("t").fetchCount)
|
||||
.handleEvents(didCancel: { cancellationExpectation.fulfill() })
|
||||
|
||||
for try await count in observation.values(in: writer) {
|
||||
counts.append(count)
|
||||
@@ -816,12 +860,12 @@ class ValueObservationTests: GRDBTestCase {
|
||||
try await writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
|
||||
|
||||
let cancellationExpectation = expectation(description: "cancelled")
|
||||
let observation = ValueObservation
|
||||
.trackingConstantRegion(Table("t").fetchCount)
|
||||
.handleEvents(didCancel: { cancellationExpectation.fulfill() })
|
||||
|
||||
let task = Task { @MainActor () -> [Int] in
|
||||
var counts: [Int] = []
|
||||
let observation = ValueObservation
|
||||
.trackingConstantRegion(Table("t").fetchCount)
|
||||
.handleEvents(didCancel: { cancellationExpectation.fulfill() })
|
||||
|
||||
for try await count in observation.values(in: writer, scheduling: .immediate) {
|
||||
counts.append(count)
|
||||
@@ -851,22 +895,22 @@ class ValueObservationTests: GRDBTestCase {
|
||||
// We need something to change
|
||||
try await writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
|
||||
|
||||
let observation = ValueObservation.trackingConstantRegion(Table("t").fetchCount)
|
||||
|
||||
let cancellationExpectation = expectation(description: "cancelled")
|
||||
let cancelledObservation = observation.handleEvents(didCancel: {
|
||||
cancellationExpectation.fulfill()
|
||||
})
|
||||
|
||||
// Launch a task that we'll cancel
|
||||
let cancelledTask = Task<String, Error> {
|
||||
// Loops until cancelled
|
||||
let observation = ValueObservation.trackingConstantRegion(Table("t").fetchCount)
|
||||
let cancelledObservation = observation.handleEvents(didCancel: {
|
||||
cancellationExpectation.fulfill()
|
||||
})
|
||||
for try await _ in cancelledObservation.values(in: writer) { }
|
||||
return "cancelled loop"
|
||||
}
|
||||
|
||||
// Lanch the task that cancels
|
||||
Task {
|
||||
let observation = ValueObservation.trackingConstantRegion(Table("t").fetchCount)
|
||||
for try await count in observation.values(in: writer) {
|
||||
if count == 3 {
|
||||
cancelledTask.cancel()
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
#include <unistd.h>
|
||||
#include <mach/mach.h>
|
||||
#include "getThreadsCount.h"
|
||||
|
||||
// https://stackoverflow.com/a/21571172/525656
|
||||
int getThreadsCount(void) {
|
||||
thread_array_t threadList;
|
||||
mach_msg_type_number_t threadCount;
|
||||
task_t task;
|
||||
|
||||
kern_return_t kernReturn = task_for_pid(mach_task_self(), getpid(), &task);
|
||||
if (kernReturn != KERN_SUCCESS) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
kernReturn = task_threads(task, &threadList, &threadCount);
|
||||
if (kernReturn != KERN_SUCCESS) {
|
||||
return -1;
|
||||
}
|
||||
vm_deallocate (mach_task_self(), (vm_address_t)threadList, threadCount * sizeof(thread_act_t));
|
||||
|
||||
return threadCount;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
#ifndef getThreadsCount_h
|
||||
#define getThreadsCount_h
|
||||
|
||||
/// Returns the number of mach threads, or -1 in case of error.
|
||||
int getThreadsCount(void);
|
||||
|
||||
#endif /* getThreadsCount_h */
|
||||
@@ -11,8 +11,6 @@
|
||||
560C98241C0E23BB00BF8471 /* PerformanceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CA22211BB41565009A04C5 /* PerformanceTests.swift */; };
|
||||
561C25912439C92D001227F2 /* SQLite in Frameworks */ = {isa = PBXBuildFile; productRef = 561C25902439C92D001227F2 /* SQLite */; };
|
||||
561C25942439C942001227F2 /* FMDB in Frameworks */ = {isa = PBXBuildFile; productRef = 561C25932439C942001227F2 /* FMDB */; };
|
||||
561C25972439CBC0001227F2 /* Realm in Frameworks */ = {isa = PBXBuildFile; productRef = 561C25962439CBC0001227F2 /* Realm */; };
|
||||
561C25992439CBC0001227F2 /* RealmSwift in Frameworks */ = {isa = PBXBuildFile; productRef = 561C25982439CBC0001227F2 /* RealmSwift */; };
|
||||
56439B341F4CA1DC0066043F /* InsertRecordClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB86121BA9886D001F9168 /* InsertRecordClassTests.swift */; };
|
||||
56439B361F4CA1DC0066043F /* FetchRecordClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B2B1C41311900861EB8 /* FetchRecordClassTests.swift */; };
|
||||
56439B381F4CA1DC0066043F /* FetchNamedValuesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B271C41302500861EB8 /* FetchNamedValuesTests.swift */; };
|
||||
@@ -31,6 +29,8 @@
|
||||
5690AFD92120589A001530EA /* InsertRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFD72120589A001530EA /* InsertRecordEncodableTests.swift */; };
|
||||
5690AFDB212058CB001530EA /* FetchRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFDA212058CB001530EA /* FetchRecordDecodableTests.swift */; };
|
||||
5690AFDC212058CB001530EA /* FetchRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFDA212058CB001530EA /* FetchRecordDecodableTests.swift */; };
|
||||
56A3FEA827A85F4800B0292E /* Realm in Frameworks */ = {isa = PBXBuildFile; productRef = 56A3FEA727A85F4800B0292E /* Realm */; };
|
||||
56A3FEAA27A85F4800B0292E /* RealmSwift in Frameworks */ = {isa = PBXBuildFile; productRef = 56A3FEA927A85F4800B0292E /* RealmSwift */; };
|
||||
56B6D0E52618BF78003CC455 /* FetchRecordOptimizedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D0E42618BF78003CC455 /* FetchRecordOptimizedTests.swift */; };
|
||||
56B6D0E62618BF78003CC455 /* FetchRecordOptimizedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D0E42618BF78003CC455 /* FetchRecordOptimizedTests.swift */; };
|
||||
56B6D0EA2618C00C003CC455 /* InsertRecordOptimizedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D0E92618C00C003CC455 /* InsertRecordOptimizedTests.swift */; };
|
||||
@@ -169,12 +169,12 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
561C25992439CBC0001227F2 /* RealmSwift in Frameworks */,
|
||||
56A3FEAA27A85F4800B0292E /* RealmSwift in Frameworks */,
|
||||
561C25912439C92D001227F2 /* SQLite in Frameworks */,
|
||||
561C25942439C942001227F2 /* FMDB in Frameworks */,
|
||||
5679870523A37A790076902D /* GRDB.framework in Frameworks */,
|
||||
56439B431F4CA1DC0066043F /* CoreData.framework in Frameworks */,
|
||||
561C25972439CBC0001227F2 /* Realm in Frameworks */,
|
||||
56A3FEA827A85F4800B0292E /* Realm in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -300,8 +300,8 @@
|
||||
packageProductDependencies = (
|
||||
561C25902439C92D001227F2 /* SQLite */,
|
||||
561C25932439C942001227F2 /* FMDB */,
|
||||
561C25962439CBC0001227F2 /* Realm */,
|
||||
561C25982439CBC0001227F2 /* RealmSwift */,
|
||||
56A3FEA727A85F4800B0292E /* Realm */,
|
||||
56A3FEA927A85F4800B0292E /* RealmSwift */,
|
||||
);
|
||||
productName = GRDBOSXTests;
|
||||
productReference = 56439B501F4CA1DC0066043F /* GRDBOSXPerformanceComparisonTests.xctest */;
|
||||
@@ -329,7 +329,7 @@
|
||||
packageReferences = (
|
||||
561C258F2439C92D001227F2 /* XCRemoteSwiftPackageReference "SQLite.swift" */,
|
||||
561C25922439C942001227F2 /* XCRemoteSwiftPackageReference "fmdb" */,
|
||||
561C25952439CBC0001227F2 /* XCRemoteSwiftPackageReference "realm-cocoa" */,
|
||||
56A3FEA627A85F4800B0292E /* XCRemoteSwiftPackageReference "realm-swift" */,
|
||||
);
|
||||
productRefGroup = DC3773F419C8CBB3004FCF85 /* Products */;
|
||||
projectDirPath = "";
|
||||
@@ -733,12 +733,12 @@
|
||||
minimumVersion = 2.7.0;
|
||||
};
|
||||
};
|
||||
561C25952439CBC0001227F2 /* XCRemoteSwiftPackageReference "realm-cocoa" */ = {
|
||||
56A3FEA627A85F4800B0292E /* XCRemoteSwiftPackageReference "realm-swift" */ = {
|
||||
isa = XCRemoteSwiftPackageReference;
|
||||
repositoryURL = "https://github.com/realm/realm-cocoa.git";
|
||||
repositoryURL = "https://github.com/realm/realm-swift.git";
|
||||
requirement = {
|
||||
kind = upToNextMajorVersion;
|
||||
minimumVersion = 10.5.0;
|
||||
minimumVersion = 10.22.0;
|
||||
};
|
||||
};
|
||||
/* End XCRemoteSwiftPackageReference section */
|
||||
@@ -754,14 +754,14 @@
|
||||
package = 561C25922439C942001227F2 /* XCRemoteSwiftPackageReference "fmdb" */;
|
||||
productName = FMDB;
|
||||
};
|
||||
561C25962439CBC0001227F2 /* Realm */ = {
|
||||
56A3FEA727A85F4800B0292E /* Realm */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = 561C25952439CBC0001227F2 /* XCRemoteSwiftPackageReference "realm-cocoa" */;
|
||||
package = 56A3FEA627A85F4800B0292E /* XCRemoteSwiftPackageReference "realm-swift" */;
|
||||
productName = Realm;
|
||||
};
|
||||
561C25982439CBC0001227F2 /* RealmSwift */ = {
|
||||
56A3FEA927A85F4800B0292E /* RealmSwift */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
package = 561C25952439CBC0001227F2 /* XCRemoteSwiftPackageReference "realm-cocoa" */;
|
||||
package = 56A3FEA627A85F4800B0292E /* XCRemoteSwiftPackageReference "realm-swift" */;
|
||||
productName = RealmSwift;
|
||||
};
|
||||
/* End XCSwiftPackageProductDependency section */
|
||||
|
||||
+38
-40
@@ -1,43 +1,41 @@
|
||||
{
|
||||
"object": {
|
||||
"pins": [
|
||||
{
|
||||
"package": "FMDB",
|
||||
"repositoryURL": "https://github.com/ccgus/fmdb.git",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "61e51fde7f7aab6554f30ab061cc588b28a97d04",
|
||||
"version": "2.7.7"
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "Realm",
|
||||
"repositoryURL": "https://github.com/realm/realm-cocoa.git",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "f483fa0a52f6d49897d133a827510a35e21183c1",
|
||||
"version": "10.20.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "RealmDatabase",
|
||||
"repositoryURL": "https://github.com/realm/realm-core",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "c3c11a841642ac93c27bd1edd61f989fc0bfb809",
|
||||
"version": "11.6.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"package": "SQLite.swift",
|
||||
"repositoryURL": "https://github.com/stephencelis/SQLite.swift.git",
|
||||
"state": {
|
||||
"branch": null,
|
||||
"revision": "60a65015f6402b7c34b9a924f755ca0a73afeeaa",
|
||||
"version": "0.13.1"
|
||||
}
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "fmdb",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/ccgus/fmdb.git",
|
||||
"state" : {
|
||||
"revision" : "61e51fde7f7aab6554f30ab061cc588b28a97d04",
|
||||
"version" : "2.7.7"
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": 1
|
||||
},
|
||||
{
|
||||
"identity" : "realm-core",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/realm/realm-core",
|
||||
"state" : {
|
||||
"revision" : "d97eed3ae7dff2f2e2ffbda83fa8f3b8c445c6ba",
|
||||
"version" : "11.17.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "realm-swift",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/realm/realm-swift.git",
|
||||
"state" : {
|
||||
"revision" : "7f123e48ec12926bb5080e449df360127ee0352d",
|
||||
"version" : "10.26.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "sqlite.swift",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/stephencelis/SQLite.swift.git",
|
||||
"state" : {
|
||||
"revision" : "4d543d811ee644fa4cc4bfa0be996b4dd6ba0f54",
|
||||
"version" : "0.13.3"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 2
|
||||
}
|
||||
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user